hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e13b28bdf0f8577d34f1bcb219e9d83e84a8499 | 990 | java | Java | src/main/java/niu/study/thread/JUC/BlockingQueue/BlockQueue_ThrowException.java | chillman21/NIUstudy | 8d0803534e4716441b4f980716aadde6452c78d9 | [
"MIT"
] | null | null | null | src/main/java/niu/study/thread/JUC/BlockingQueue/BlockQueue_ThrowException.java | chillman21/NIUstudy | 8d0803534e4716441b4f980716aadde6452c78d9 | [
"MIT"
] | null | null | null | src/main/java/niu/study/thread/JUC/BlockingQueue/BlockQueue_ThrowException.java | chillman21/NIUstudy | 8d0803534e4716441b4f980716aadde6452c78d9 | [
"MIT"
] | null | null | null | 31.935484 | 71 | 0.644444 | 8,336 | package niu.study.thread.JUC.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
public class BlockQueue_ThrowException {
public static void main(String[] args) {
test1();
}
/**
* 抛出异常
*/
public static void test1(){
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.element());//查看队首元素是谁
System.out.println("-----------------");
//抛出异常! java.lang.IllegalStateException: Queue full
//System.out.println(blockingQueue.add("d"));//阻塞
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
//抛出异常!java.util.NoSuchElementException
//System.out.println(blockingQueue.remove());
}
}
|
3e13b2eb5036d368a7a805151f567774a3405ee7 | 311 | java | Java | src/main/java/com/dsm/immigration/utils/form/UserIdWrapper.java | DSM-DIS/API-Gateway-Immigration | d142c55532973a7bd450993a0e8b7061cd0c1039 | [
"MIT"
] | null | null | null | src/main/java/com/dsm/immigration/utils/form/UserIdWrapper.java | DSM-DIS/API-Gateway-Immigration | d142c55532973a7bd450993a0e8b7061cd0c1039 | [
"MIT"
] | null | null | null | src/main/java/com/dsm/immigration/utils/form/UserIdWrapper.java | DSM-DIS/API-Gateway-Immigration | d142c55532973a7bd450993a0e8b7061cd0c1039 | [
"MIT"
] | null | null | null | 15.55 | 39 | 0.585209 | 8,337 | package com.dsm.immigration.utils.form;
public class UserIdWrapper {
private String id;
public UserIdWrapper() {}
public UserIdWrapper(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
|
3e13b323f958eee4e9de9d16c5b0ad1b17799863 | 1,321 | java | Java | Application/app/src/main/java/ImageProcessing/ImageSaver.java | krzysztofkolek/android--ocr-equation | 2a4657c3764bd916f148932460da4462b4412727 | [
"Apache-2.0"
] | null | null | null | Application/app/src/main/java/ImageProcessing/ImageSaver.java | krzysztofkolek/android--ocr-equation | 2a4657c3764bd916f148932460da4462b4412727 | [
"Apache-2.0"
] | null | null | null | Application/app/src/main/java/ImageProcessing/ImageSaver.java | krzysztofkolek/android--ocr-equation | 2a4657c3764bd916f148932460da4462b4412727 | [
"Apache-2.0"
] | null | null | null | 23.175439 | 67 | 0.626798 | 8,338 | package ImageProcessing;
import android.graphics.Bitmap;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageSaver extends ApplicationImageContent {
private byte[] _bitmap = null;
public ImageSaver() {
super();
}
public void setData(Bitmap bitmap) {
this._bitmap = transformImageToByteArray(bitmap);
}
public void setData(byte[] bitmap) {
this._bitmap = bitmap;
}
private byte[] transformImageToByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
public void saveImage() throws Exception {
if (_bitmap == null) {
throw new Exception("No data!");
}
try {
FileOutputStream outStream = null;
outStream = new FileOutputStream(getFileWithPath());
outStream.write(_bitmap);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
|
3e13b3ac92a92116b92b1e43e3836382e7b527cd | 1,310 | java | Java | Backend/logininit/src/main/java/com/jbr/springmvc/model/User.java | geekypanda25/309-project | f3e149a38ae1fa71615ab1321ba4b1398bc9aa8e | [
"MIT"
] | null | null | null | Backend/logininit/src/main/java/com/jbr/springmvc/model/User.java | geekypanda25/309-project | f3e149a38ae1fa71615ab1321ba4b1398bc9aa8e | [
"MIT"
] | 5 | 2020-03-04T22:03:44.000Z | 2021-12-09T21:37:07.000Z | Backend/logininit/src/main/java/com/jbr/springmvc/model/User.java | geekypanda25/309-project | f3e149a38ae1fa71615ab1321ba4b1398bc9aa8e | [
"MIT"
] | null | null | null | 18.194444 | 50 | 0.671756 | 8,339 | package com.jbr.springmvc.model;
public class User {
private String username;
private String password;
private String firstname;
private String lastname;
private String email;
private String address;
private int phone;
public String getUsername() {
return username;
}
public void setUsername(String username) {
System.out.println("username: " + username);
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
System.out.println("firstname: " + firstname);
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
System.out.println("lastname: " + lastname);
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
}
|
3e13b3ca961538ac091d4b180c09744f4af6d017 | 1,576 | java | Java | flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyInvokable.java | Shih-Wei-Hsu/flink | 3fed93d62d8f79627d4ded2dd1fae6fae91b36e8 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | 41 | 2018-11-14T04:05:42.000Z | 2022-02-09T10:39:23.000Z | flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyInvokable.java | Shih-Wei-Hsu/flink | 3fed93d62d8f79627d4ded2dd1fae6fae91b36e8 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | 15 | 2021-06-13T18:06:12.000Z | 2022-02-09T22:40:04.000Z | flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/DummyInvokable.java | houmaozheng/flink | ef692d0967daf8f532d9011122e1d3104a07fb39 | [
"Apache-2.0"
] | 16 | 2019-01-04T09:19:03.000Z | 2022-01-10T14:34:31.000Z | 27.172414 | 75 | 0.754442 | 8,340 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.operators.testutils;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
/**
* An invokable that does nothing.
*/
public class DummyInvokable extends AbstractInvokable {
public DummyInvokable() {
super(new DummyEnvironment("test", 1, 0));
}
@Override
public void invoke() {}
@Override
public int getCurrentNumberOfSubtasks() {
return 1;
}
@Override
public int getIndexInSubtaskGroup() {
return 0;
}
@Override
public final Configuration getJobConfiguration() {
return new Configuration();
}
@Override
public ExecutionConfig getExecutionConfig() {
return new ExecutionConfig();
}
}
|
3e13b3dc8eb89480594351195ee3ad4a39652aca | 3,637 | java | Java | src/server/src/main/java/org/apache/accumulo/server/master/tserverOps/FlushTablets.java | jatrost/accumulo | 6be40f2f3711aaa7d0b68b5b6852b79304af3cff | [
"Apache-2.0"
] | 3 | 2021-11-11T05:18:23.000Z | 2021-11-11T05:18:43.000Z | src/server/src/main/java/org/apache/accumulo/server/master/tserverOps/FlushTablets.java | jatrost/accumulo | 6be40f2f3711aaa7d0b68b5b6852b79304af3cff | [
"Apache-2.0"
] | null | null | null | src/server/src/main/java/org/apache/accumulo/server/master/tserverOps/FlushTablets.java | jatrost/accumulo | 6be40f2f3711aaa7d0b68b5b6852b79304af3cff | [
"Apache-2.0"
] | 1 | 2021-11-09T05:32:32.000Z | 2021-11-09T05:32:32.000Z | 39.967033 | 150 | 0.696178 | 8,341 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.server.master.tserverOps;
import java.util.Collection;
import org.apache.accumulo.server.fate.Repo;
import org.apache.accumulo.server.master.EventCoordinator.Listener;
import org.apache.accumulo.server.master.LiveTServerSet.TServerConnection;
import org.apache.accumulo.server.master.Master;
import org.apache.accumulo.server.master.state.DistributedStoreException;
import org.apache.accumulo.server.master.state.MetaDataStateStore;
import org.apache.accumulo.server.master.state.TabletLocationState;
import org.apache.accumulo.server.master.state.TabletStateStore;
import org.apache.accumulo.server.master.state.ZooTabletStateStore;
import org.apache.accumulo.server.master.tableOps.MasterRepo;
import org.apache.log4j.Logger;
public class FlushTablets extends MasterRepo {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FlushTablets.class);
String logger;
public FlushTablets(String logger) {
this.logger = logger;
}
@Override
public long isReady(long tid, Master environment) throws Exception {
return 0;
}
@Override
public Repo<Master> call(long tid, Master m) throws Exception {
// TODO move this code to isReady() and drop while loop?
// Make sure nobody is still using logs hosted on that node
Listener listener = m.getEventCoordinator().getListener();
while (m.stillMaster()) {
boolean flushed = false;
ZooTabletStateStore zooTabletStateStore = null;
try {
zooTabletStateStore = new ZooTabletStateStore();
} catch (DistributedStoreException e) {
log.warn("Unable to open ZooTabletStateStore, will retry", e);
}
MetaDataStateStore theRest = new MetaDataStateStore();
for (TabletStateStore store : new TabletStateStore[] {zooTabletStateStore, theRest}) {
if (store != null) {
for (TabletLocationState tabletState : store) {
for (Collection<String> logSet : tabletState.walogs) {
for (String logEntry : logSet) {
if (logger.equals(logEntry.split("/")[0])) {
TServerConnection tserver = m.getConnection(tabletState.current);
if (tserver != null) {
log.info("Requesting " + tabletState.current + " flush tablet " + tabletState.extent + " because it has a log entry " + logEntry);
tserver.flushTablet(m.getMasterLock(), tabletState.extent);
}
flushed = true;
}
}
}
}
}
}
if (zooTabletStateStore != null && !flushed)
break;
listener.waitForEvents(1000);
}
return new StopLogger(logger);
}
@Override
public void undo(long tid, Master m) throws Exception {}
}
|
3e13b552eca4d80c986b3ad09ad7eee14a6659bb | 293 | java | Java | Spring_Data_Course/Exam/src/main/java/com/example/football/repository/StatRepository.java | lmarinov/MySQL_StudyMaterialsAndExercise | 999c5b215660f43f195bd79555acdfd48322f026 | [
"MIT"
] | null | null | null | Spring_Data_Course/Exam/src/main/java/com/example/football/repository/StatRepository.java | lmarinov/MySQL_StudyMaterialsAndExercise | 999c5b215660f43f195bd79555acdfd48322f026 | [
"MIT"
] | null | null | null | Spring_Data_Course/Exam/src/main/java/com/example/football/repository/StatRepository.java | lmarinov/MySQL_StudyMaterialsAndExercise | 999c5b215660f43f195bd79555acdfd48322f026 | [
"MIT"
] | null | null | null | 26.636364 | 67 | 0.832765 | 8,342 | package com.example.football.repository;
import com.example.football.models.entity.Stat;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
//ToDo:
@Repository
public interface StatRepository extends JpaRepository<Stat, Long> {
}
|
3e13b565c8a10cd0110de3aa274ccacfc9958f7c | 2,183 | java | Java | PalmCarTreasure/app/src/main/java/com/cango/palmcartreasure/trailer/task/TrailerTaskAdapter.java | androidlli/work | ba26bacd68d520eb118196a43769a3c3c454591a | [
"Apache-2.0"
] | null | null | null | PalmCarTreasure/app/src/main/java/com/cango/palmcartreasure/trailer/task/TrailerTaskAdapter.java | androidlli/work | ba26bacd68d520eb118196a43769a3c3c454591a | [
"Apache-2.0"
] | null | null | null | PalmCarTreasure/app/src/main/java/com/cango/palmcartreasure/trailer/task/TrailerTaskAdapter.java | androidlli/work | ba26bacd68d520eb118196a43769a3c3c454591a | [
"Apache-2.0"
] | null | null | null | 36.383333 | 132 | 0.704077 | 8,343 | package com.cango.palmcartreasure.trailer.task;
import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cango.palmcartreasure.R;
import com.cango.palmcartreasure.baseAdapter.BaseAdapter;
import com.cango.palmcartreasure.baseAdapter.BaseHolder;
import com.cango.palmcartreasure.model.TypeTaskData;
import java.util.List;
/**
* Created by cango on 2017/4/10.
*/
public class TrailerTaskAdapter extends BaseAdapter<TypeTaskData.DataBean.TaskListBean> {
String mType;
public TrailerTaskAdapter(Context context, List<TypeTaskData.DataBean.TaskListBean> datas, boolean isOpenLoadMore,String type) {
super(context, datas, isOpenLoadMore);
mType=type;
}
@Override
protected int getItemLayoutId() {
//如果是管理员的话就返回 管理员item界面,如果不是就返回普通的
return R.layout.trailer_task_item_normal;
}
@Override
protected void convert(BaseHolder holder, TypeTaskData.DataBean.TaskListBean data) {
TextView tvApplyCD = holder.getView(R.id.tv_task_item_id);
TextView tvDistance = holder.getView(R.id.tv_distance);
TextView tvShortName = holder.getView(R.id.tv_task_item_type);
TextView tvCustomerName = holder.getView(R.id.tv_task_item_name);
TextView tvCarPlateNO = holder.getView(R.id.tv_task_item_plate);
LinearLayout llOver = holder.getView(R.id.ll_over);
tvApplyCD.setText(data.getApplyCD());
tvDistance.setText(data.getDistance());
tvShortName.setText(data.getShortName());
tvCustomerName.setText(data.getCustomerName());
tvCarPlateNO.setText(data.getCarPlateNO());
if (TrailerTasksFragment.SEARCH.equals(mType)){
llOver.setVisibility(View.INVISIBLE);
}else {
if ("F".equals(data.getIsStart())&&"F".equals(data.getIsCheckPoint())&&"F".equals(data.getIsDone())){
llOver.setVisibility(View.INVISIBLE);
}else {
llOver.setVisibility(View.VISIBLE);
}
}
TextView tvAddress = holder.getView(R.id.tv_address);
tvAddress.setText(data.getAddress());
}
}
|
3e13b6890fb76f189cb9cd00a5c48e0592c655f7 | 6,076 | java | Java | MeasureApplications/MobileNetworkMeasurement/app/src/main/java/de/tudarmstadt/tk/dbsystel/mobilenetworkmeasurement/sensors/MobileParameters.java | Telecooperation/big-sense | 813c5a6e983778602dfa83d63ff14807542e328f | [
"MIT"
] | null | null | null | MeasureApplications/MobileNetworkMeasurement/app/src/main/java/de/tudarmstadt/tk/dbsystel/mobilenetworkmeasurement/sensors/MobileParameters.java | Telecooperation/big-sense | 813c5a6e983778602dfa83d63ff14807542e328f | [
"MIT"
] | null | null | null | MeasureApplications/MobileNetworkMeasurement/app/src/main/java/de/tudarmstadt/tk/dbsystel/mobilenetworkmeasurement/sensors/MobileParameters.java | Telecooperation/big-sense | 813c5a6e983778602dfa83d63ff14807542e328f | [
"MIT"
] | null | null | null | 36.166667 | 160 | 0.633147 | 8,344 | package de.tudarmstadt.tk.dbsystel.mobilenetworkmeasurement.sensors;
import android.content.Context;
import android.telephony.CellIdentityLte;
import android.telephony.CellInfo;
import android.telephony.CellInfoLte;
import android.telephony.CellSignalStrengthLte;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import de.tudarmstadt.tk.dbsystel.mobilenetworkmeasurement.StartService;
/**
* Created by Martin on 24.11.2015.
*/
public class MobileParameters {
private Context context;
private TelephonyManager telephonyManager;
private SignalStrength listenedSignalStrength;
private int cellID;
private int pci;
private String operator;
private String networkType;
private int level;
private int dbm;
private int asu;
private String lastOperator;
public MobileParameters(Context context) {
this.context = context;
telephonyManager = (TelephonyManager) this.context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneStateListener() {
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
listenedSignalStrength = signalStrength;
}
}, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
/**
* Collects all important parameters for gsm and lte data
* @return true, if all parameters (except pci) are set
*/
public boolean getLastValuesForMeasurement() {
cellID = -1;
pci = -1;
lastOperator = operator;
operator = "";
this.networkType = "";
level = -1;
dbm = -1;
asu = -1;
operator = telephonyManager.getNetworkOperatorName();
//Get network type
int networkType = telephonyManager.getNetworkType();
this.networkType = getNetworkTypeAsString(networkType);
//This only works with lte on some models (like Nexus devices, not on Samsung phones)
if (telephonyManager.getAllCellInfo() != null) {
for (CellInfo info : telephonyManager.getAllCellInfo()) {
if (info instanceof CellInfoLte && info.isRegistered()) {
CellIdentityLte lteCellIdentity = ((CellInfoLte) info).getCellIdentity();
CellSignalStrengthLte lteSignalStrength = ((CellInfoLte) info).getCellSignalStrength();
level = lteSignalStrength.getLevel();
dbm = lteSignalStrength.getDbm();
asu = lteSignalStrength.getAsuLevel();
cellID = lteCellIdentity.getCi();
pci = lteCellIdentity.getPci();
}
}
}
//no info was given in the above request, then try another one
//these infos are valid (normal) only for gsm, but on Samsung phones these values are also correct for lte
if (cellID == -1 || dbm == -1 || asu == -1 || level == -1) {
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
if (cellLocation != null) {
cellID = cellLocation.getCid();
}
if (listenedSignalStrength != null) {
asu = listenedSignalStrength.getGsmSignalStrength();
level = listenedSignalStrength.getLevel();
if (listenedSignalStrength.getGsmSignalStrength() != 99)
dbm = listenedSignalStrength.getGsmSignalStrength() * 2 - 113;
else
dbm = listenedSignalStrength.getGsmSignalStrength();
}
}
Log.i(StartService.LOG_TAG, "Operator: " + operator + ", NetworkType: " + this.networkType + ", CellID: " + cellID + ", DBM: " + dbm + ", ASU: " + asu);
if (dbm != -1 && asu != -1) {
if(cellID == 0) cellID = -1;
if(operator.equals("")) operator = lastOperator;
else lastOperator = operator;
return true;
} else return false;
}
/**
* Gets the name of network type as a string (e.g. GPRS or LTE)
* @param networkType type as int (defined in TelephonyManager)
* @return NetworkType as String
*/
private String getNetworkTypeAsString(int networkType) {
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT";
case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA";
case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE";
case TelephonyManager.NETWORK_TYPE_EHRPD: return "eHRPD";
case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO rev. 0";
case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO rev. A";
case TelephonyManager.NETWORK_TYPE_EVDO_B: return "EVDO rev. B";
case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS";
case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA";
case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA";
case TelephonyManager.NETWORK_TYPE_HSPAP: return "HSPA+";
case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA";
case TelephonyManager.NETWORK_TYPE_IDEN: return "iDen";
case TelephonyManager.NETWORK_TYPE_LTE: return "LTE";
case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS";
case TelephonyManager.NETWORK_TYPE_UNKNOWN: return "Unknown";
}
return "";
}
public int getAsu() {
return asu;
}
public int getDbm() {
return dbm;
}
public int getLevel() {
return level;
}
public String getNetworkType() {
return networkType;
}
public String getOperator() {
return operator;
}
public int getPci() {
return pci;
}
public int getCellID() {
return cellID;
}
}
|
3e13b6cae0ab82566bbab4c3ca70f8f6ecc0dc0e | 8,302 | java | Java | src/test/java/freemarker/template/utility/NumberUtilTest.java | rototor/freemarker | eb1343fc43bed24f5eb2ffcd9971bc2aeb0caf6a | [
"Apache-2.0"
] | 536 | 2018-03-30T08:35:24.000Z | 2022-03-31T08:53:43.000Z | src/test/java/freemarker/template/utility/NumberUtilTest.java | Seanpm2001-FreeMarker-lang/freemarker | 5821339c3188e8083af1fc72e17b34d09af09fcb | [
"Apache-2.0"
] | 20 | 2015-10-12T06:45:37.000Z | 2018-01-25T09:51:04.000Z | src/test/java/freemarker/template/utility/NumberUtilTest.java | Seanpm2001-FreeMarker-lang/freemarker | 5821339c3188e8083af1fc72e17b34d09af09fcb | [
"Apache-2.0"
] | 167 | 2018-04-02T19:32:53.000Z | 2022-03-16T09:27:02.000Z | 38.435185 | 119 | 0.59034 | 8,345 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package freemarker.template.utility;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.Test;
import junit.framework.TestCase;
public class NumberUtilTest extends TestCase {
@Test
public void testGetSignum() {
assertEquals(1, NumberUtil.getSignum(Double.valueOf(Double.POSITIVE_INFINITY)));
assertEquals(1, NumberUtil.getSignum(Double.valueOf(3)));
assertEquals(0, NumberUtil.getSignum(Double.valueOf(0)));
assertEquals(-1, NumberUtil.getSignum(Double.valueOf(-3)));
assertEquals(-1, NumberUtil.getSignum(Double.valueOf(Double.NEGATIVE_INFINITY)));
try {
NumberUtil.getSignum(Double.valueOf(Double.NaN));
fail();
} catch (ArithmeticException e) {
// expected
}
assertEquals(1, NumberUtil.getSignum(Float.valueOf(Float.POSITIVE_INFINITY)));
assertEquals(1, NumberUtil.getSignum(Float.valueOf(3)));
assertEquals(0, NumberUtil.getSignum(Float.valueOf(0)));
assertEquals(-1, NumberUtil.getSignum(Float.valueOf(-3)));
assertEquals(-1, NumberUtil.getSignum(Float.valueOf(Float.NEGATIVE_INFINITY)));
try {
NumberUtil.getSignum(Float.valueOf(Float.NaN));
fail();
} catch (ArithmeticException e) {
// expected
}
assertEquals(1, NumberUtil.getSignum(Long.valueOf(3)));
assertEquals(0, NumberUtil.getSignum(Long.valueOf(0)));
assertEquals(-1, NumberUtil.getSignum(Long.valueOf(-3)));
assertEquals(1, NumberUtil.getSignum(Integer.valueOf(3)));
assertEquals(0, NumberUtil.getSignum(Integer.valueOf(0)));
assertEquals(-1, NumberUtil.getSignum(Integer.valueOf(-3)));
assertEquals(1, NumberUtil.getSignum(Short.valueOf((short) 3)));
assertEquals(0, NumberUtil.getSignum(Short.valueOf((short) 0)));
assertEquals(-1, NumberUtil.getSignum(Short.valueOf((short) -3)));
assertEquals(1, NumberUtil.getSignum(Byte.valueOf((byte) 3)));
assertEquals(0, NumberUtil.getSignum(Byte.valueOf((byte) 0)));
assertEquals(-1, NumberUtil.getSignum(Byte.valueOf((byte) -3)));
assertEquals(1, NumberUtil.getSignum(BigDecimal.valueOf(3)));
assertEquals(0, NumberUtil.getSignum(BigDecimal.valueOf(0)));
assertEquals(-1, NumberUtil.getSignum(BigDecimal.valueOf(-3)));
assertEquals(1, NumberUtil.getSignum(BigInteger.valueOf(3)));
assertEquals(0, NumberUtil.getSignum(BigInteger.valueOf(0)));
assertEquals(-1, NumberUtil.getSignum(BigInteger.valueOf(-3)));
}
@Test
public void testIsBigDecimalInteger() {
BigDecimal n1 = new BigDecimal("1.125");
if (n1.precision() != 4 || n1.scale() != 3) {
throw new RuntimeException("Wrong: " + n1);
}
BigDecimal n2 = new BigDecimal("1.125").subtract(new BigDecimal("0.005"));
if (n2.precision() != 4 || n2.scale() != 3) {
throw new RuntimeException("Wrong: " + n2);
}
BigDecimal n3 = new BigDecimal("123");
BigDecimal n4 = new BigDecimal("6000");
BigDecimal n5 = new BigDecimal("1.12345").subtract(new BigDecimal("0.12345"));
if (n5.precision() != 6 || n5.scale() != 5) {
throw new RuntimeException("Wrong: " + n5);
}
BigDecimal n6 = new BigDecimal("0");
BigDecimal n7 = new BigDecimal("0.001").subtract(new BigDecimal("0.001"));
BigDecimal n8 = new BigDecimal("60000.5").subtract(new BigDecimal("0.5"));
BigDecimal n9 = new BigDecimal("6").movePointRight(3).setScale(-3);
BigDecimal[] ns = new BigDecimal[] {
n1, n2, n3, n4, n5, n6, n7, n8, n9,
n1.negate(), n2.negate(), n3.negate(), n4.negate(), n5.negate(), n6.negate(), n7.negate(), n8.negate(),
n9.negate(),
};
for (BigDecimal n : ns) {
assertEquals(n.doubleValue() == n.longValue(), NumberUtil.isIntegerBigDecimal(n));
}
}
@Test
public void testToIntExcact() {
for (int n : new int[] { Integer.MIN_VALUE, Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE, Integer.MAX_VALUE }) {
if (n != Integer.MIN_VALUE && n != Integer.MAX_VALUE) {
assertEquals(n, NumberUtil.toIntExact(Byte.valueOf((byte) n)));
assertEquals(n, NumberUtil.toIntExact(Short.valueOf((short) n)));
assertEquals(n, NumberUtil.toIntExact(Float.valueOf(n)));
}
assertEquals(n, NumberUtil.toIntExact(Integer.valueOf(n)));
assertEquals(n, NumberUtil.toIntExact(Long.valueOf(n)));
assertEquals(n, NumberUtil.toIntExact(Double.valueOf(n)));
assertEquals(n, NumberUtil.toIntExact(BigDecimal.valueOf(n)));
assertEquals(n, NumberUtil.toIntExact(BigDecimal.valueOf(n * 10L).divide(BigDecimal.TEN)));
assertEquals(n, NumberUtil.toIntExact(BigInteger.valueOf(n)));
}
try {
NumberUtil.toIntExact(Long.valueOf(Integer.MIN_VALUE - 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Long.valueOf(Integer.MAX_VALUE + 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Float.valueOf(1.00001f));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Float.valueOf(Integer.MIN_VALUE - 129L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Float.valueOf(Integer.MAX_VALUE));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Double.valueOf(1.00001));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Double.valueOf(Integer.MIN_VALUE - 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(Double.valueOf(Integer.MAX_VALUE + 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(new BigDecimal("100.000001"));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(BigDecimal.valueOf(Integer.MIN_VALUE - 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(BigDecimal.valueOf(Integer.MAX_VALUE + 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(BigInteger.valueOf(Integer.MIN_VALUE - 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
try {
NumberUtil.toIntExact(BigInteger.valueOf(Integer.MAX_VALUE + 1L));
fail();
} catch (ArithmeticException e) {
// Expected
}
}
}
|
3e13b7a8886c8c261dccf09dcd75ecf6b39493b1 | 1,222 | java | Java | blade-service/blade-anbiao/src/main/java/org/springblade/anbiao/yingjijiuyuan/service/IYingjiduiwuChengyuanService.java | huangyaping9455/SafetyStandards_HN | 7400711a75ad32919fa6b532f2597efcbeb503f6 | [
"Apache-2.0"
] | null | null | null | blade-service/blade-anbiao/src/main/java/org/springblade/anbiao/yingjijiuyuan/service/IYingjiduiwuChengyuanService.java | huangyaping9455/SafetyStandards_HN | 7400711a75ad32919fa6b532f2597efcbeb503f6 | [
"Apache-2.0"
] | null | null | null | blade-service/blade-anbiao/src/main/java/org/springblade/anbiao/yingjijiuyuan/service/IYingjiduiwuChengyuanService.java | huangyaping9455/SafetyStandards_HN | 7400711a75ad32919fa6b532f2597efcbeb503f6 | [
"Apache-2.0"
] | 1 | 2021-07-05T09:14:57.000Z | 2021-07-05T09:14:57.000Z | 26.021277 | 86 | 0.726901 | 8,346 | /**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (ychag@example.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springblade.anbiao.yingjijiuyuan.service;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springblade.anbiao.yingjijiuyuan.entity.YingjiduiwuChengyuan;
import java.util.List;
/**
* 应急救援-应急队伍-队伍成员 服务类
*
* @author hyp
* @since 2019-04-29
*/
public interface IYingjiduiwuChengyuanService extends IService<YingjiduiwuChengyuan> {
/**
* 根据预案id查询应急队伍成员
*
* @param id
* @return
*/
List<YingjiduiwuChengyuan> selectByDuiwuId(String id);
/**
* 自定义 假删除
*
* @param id
* @author :hyp
*/
boolean deleleChengyuan(String id);
}
|
3e13b94dd55d28a95c4e50c59c9bb6e0a116405a | 5,946 | java | Java | Web/iTalker/src/main/java/net/ggxiaozhi/web/italker/push/service/UserService.java | guzhigang001/iTalker | b403de85c4b5b1d5e5212e5982efc888390429c1 | [
"Apache-2.0"
] | 26 | 2018-02-28T11:08:53.000Z | 2020-12-20T22:55:31.000Z | Web/iTalker/src/main/java/net/ggxiaozhi/web/italker/push/service/UserService.java | guzhigang001/iTalker | b403de85c4b5b1d5e5212e5982efc888390429c1 | [
"Apache-2.0"
] | null | null | null | Web/iTalker/src/main/java/net/ggxiaozhi/web/italker/push/service/UserService.java | guzhigang001/iTalker | b403de85c4b5b1d5e5212e5982efc888390429c1 | [
"Apache-2.0"
] | 7 | 2018-03-21T09:06:50.000Z | 2021-10-31T10:16:36.000Z | 32.67033 | 125 | 0.631517 | 8,347 | package net.ggxiaozhi.web.italker.push.service;
import com.google.common.base.Strings;
import net.ggxiaozhi.web.italker.push.bean.api.base.PushModel;
import net.ggxiaozhi.web.italker.push.bean.api.base.ResponseModel;
import net.ggxiaozhi.web.italker.push.bean.api.user.UpdateInfoModle;
import net.ggxiaozhi.web.italker.push.bean.card.UserCard;
import net.ggxiaozhi.web.italker.push.bean.db.User;
import net.ggxiaozhi.web.italker.push.bean.db.UserFollow;
import net.ggxiaozhi.web.italker.push.bean.factory.PushFactory;
import net.ggxiaozhi.web.italker.push.bean.factory.UserFactory;
import net.ggxiaozhi.web.italker.push.utils.PushDispatcher;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* 工程名 : iTalker
* 包名 : net.ggxiaozhi.web.italker.push.service
* 作者名 : 志先生_
* 日期 : 2017/11
* 功能 :操作用户的相关接口
*/
//127.0.0.1/api/user/...
@Path("/user")
public class UserService extends BaseService {
//用户信息修改接口
//返回自己的个人信息
@PUT
//@Path("update")//127.0.0.1/api/user/update 不需要写 就是当前目录
//指定请求与响应体为json
@Consumes(MediaType.APPLICATION_JSON)//指定传入的格式
@Produces(MediaType.APPLICATION_JSON)//指定返回的格式
public ResponseModel<UserCard> update(
//不需要token 拦截器已经帮我们做了处理
// @HeaderParam("token") String token,
UpdateInfoModle modle) {
//表示当前登录缺少必要参数
if (/*Strings.isNullOrEmpty(token) ||*/ !UpdateInfoModle.check(modle)) {
//参数异常
return ResponseModel.buildParameterError();
}
//拿到自己的个人信息
User self = getSelf();
//更新用户信息
self = modle.updateToUser(self);
//更新用户信息到数据库
self = UserFactory.update(self);
//构建自己的用户信息
UserCard card = new UserCard(self, true);
//将修改后的用户信息返回
return ResponseModel.buildOk(card);
}
//拉去联系人列表
@GET
@Path("/contact")//127.0.0.1/api/user/update
//指定请求与响应体为json
@Consumes(MediaType.APPLICATION_JSON)//指定传入的格式
@Produces(MediaType.APPLICATION_JSON)//指定返回的格式
public ResponseModel<List<UserCard>> contact() {
User self = getSelf();
//拿到我的联系人
List<User> users = UserFactory.contacts(self);
//转换UserCard
List<UserCard> userCards = users.stream()
//map操作 相当于转置操作 User->UserCard
.map(user -> new UserCard(user, true))
.collect(Collectors.toList());
//返回
return ResponseModel.buildOk(userCards);
}
//关注某人
// 简化:关注人的操作 其实是双方同时关注 不需要对方同意
@PUT//修改类型的请求用PUT
@Path("/follow/{followId}")//127.0.0.1/api/user/update
//指定请求与响应体为json
@Consumes(MediaType.APPLICATION_JSON)//指定传入的格式
@Produces(MediaType.APPLICATION_JSON)//指定返回的格式
public ResponseModel<UserCard> follow(@PathParam("followId") String followId) {
User self = getSelf();
//不能关注自己
if (self.getId().equalsIgnoreCase(followId) || Strings.isNullOrEmpty(followId)) {
//返回参数异常
return ResponseModel.buildParameterError();
}
//找到我要关注的人
User userFollow = UserFactory.findById(followId);
if (userFollow == null) {
//未找到人
return ResponseModel.buildNotFoundUserError(null);
}
//备注默认没有 后面可以扩展
User follow = UserFactory.follow(self, userFollow, null);
if (follow == null) {
//关注失败 返回服务器异常
return ResponseModel.buildServiceError();
}
//通知我关注的人 我关注了他的消息
//给他发送一个我的信息过去
PushFactory.pushFollow(userFollow,new UserCard(self));
//返回关注人的信息
return ResponseModel.buildOk(new UserCard(userFollow, true));
}
//拉取某人的信息
@GET
@Path("{id}")//127.0.0.1/api/user/{id}
//指定请求与响应体为json
@Consumes(MediaType.APPLICATION_JSON)//指定传入的格式
@Produces(MediaType.APPLICATION_JSON)//指定返回的格式
public ResponseModel<UserCard> getUser(@PathParam("id") String id) {
//校验参数
if (Strings.isNullOrEmpty(id)) {
return ResponseModel.buildParameterError();
}
User self = getSelf();
if (self.getId().equalsIgnoreCase(id)) {
//如果查询的用户是我自己 那么直接返回我自己 不用数据库查询操作
return ResponseModel.buildOk(new UserCard(self, true));
}
User user = UserFactory.findById(id);
if (user == null) {
//没有找到匹配的用户
return ResponseModel.buildNotFoundUserError(null);
}
//判断两个人是否已经关注了对方
boolean isFollow = UserFactory.getUserFollow(self, user) != null;
return ResponseModel.buildOk(new UserCard(user, isFollow));
}
//用户搜索
//为了简化分页:只返回20条数据
@GET//搜索人不涉及数据更改 只是查询 所以用GET
//127.0.0.1/api/user/search/{name}
@Path("/search/{name:(.*)?}")//名字为任意字符 可以为空
//指定请求与响应体为json
@Consumes(MediaType.APPLICATION_JSON)//指定传入的格式
@Produces(MediaType.APPLICATION_JSON)//指定返回的格式
public ResponseModel<List<UserCard>> search(@DefaultValue("") @PathParam("name") String name) {
User self = getSelf();
//先查询数据 searchUsers查询到的模糊匹配的用户集合
List<User> searchUsers = UserFactory.search(name);
//把查询到人封装成UserCard
//判断这些人是否存在我已经关注的
//如果有 则返回的关注状态中应该已经设置好了状态
//拿到当前用户的联系人
final List<User> contacts = UserFactory.contacts(self);
List<UserCard> userCards = searchUsers.stream()
.map(user -> {
//判断这个user是否在我的联系人中
boolean isFollow = user.getId().equalsIgnoreCase(self.getId())//搜索中的人中是否有自己 因为自己对自己肯定是已经关注了
//进行联系人的任意匹配 匹配其中的Id字段
|| contacts.stream().anyMatch(contactUser -> contactUser.getId().equalsIgnoreCase(user.getId()));
return new UserCard(user, isFollow);
}).collect(Collectors.toList());
//返回
return ResponseModel.buildOk(userCards);
}
}
|
3e13b956226fe1b8b45ede63f96d5e949958f2ec | 1,571 | java | Java | aliyun-java-sdk-rds/src/main/java/com/aliyuncs/rds/transform/v20140815/DescribeDatabaseLockDiagnosisResponseUnmarshaller.java | 17610178081/aliyun-openapi-java-sdk | df66894d4b14e1669cf006419578c5516266f1ab | [
"Apache-2.0"
] | 1 | 2020-04-28T03:09:56.000Z | 2020-04-28T03:09:56.000Z | aliyun-java-sdk-rds/src/main/java/com/aliyuncs/rds/transform/v20140815/DescribeDatabaseLockDiagnosisResponseUnmarshaller.java | 17610178081/aliyun-openapi-java-sdk | df66894d4b14e1669cf006419578c5516266f1ab | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-rds/src/main/java/com/aliyuncs/rds/transform/v20140815/DescribeDatabaseLockDiagnosisResponseUnmarshaller.java | 17610178081/aliyun-openapi-java-sdk | df66894d4b14e1669cf006419578c5516266f1ab | [
"Apache-2.0"
] | null | null | null | 41.342105 | 171 | 0.800127 | 8,348 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.rds.transform.v20140815;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.rds.model.v20140815.DescribeDatabaseLockDiagnosisResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeDatabaseLockDiagnosisResponseUnmarshaller {
public static DescribeDatabaseLockDiagnosisResponse unmarshall(DescribeDatabaseLockDiagnosisResponse describeDatabaseLockDiagnosisResponse, UnmarshallerContext context) {
describeDatabaseLockDiagnosisResponse.setRequestId(context.stringValue("DescribeDatabaseLockDiagnosisResponse.RequestId"));
List<String> deadLockList = new ArrayList<String>();
for (int i = 0; i < context.lengthValue("DescribeDatabaseLockDiagnosisResponse.DeadLockList.Length"); i++) {
deadLockList.add(context.stringValue("DescribeDatabaseLockDiagnosisResponse.DeadLockList["+ i +"]"));
}
describeDatabaseLockDiagnosisResponse.setDeadLockList(deadLockList);
return describeDatabaseLockDiagnosisResponse;
}
} |
3e13b9c41e94897fc3259be8bfcfd2a4495e2036 | 316 | java | Java | src/main/java/com/typelead/gradle/utils/NoSpec.java | jneira/gradle-eta | a3f264caf3cc10c0b9c7dd1c8d2903186541048b | [
"BSD-3-Clause"
] | 31 | 2017-10-04T00:27:56.000Z | 2020-02-17T22:49:17.000Z | src/main/java/com/typelead/gradle/utils/NoSpec.java | jneira/gradle-eta | a3f264caf3cc10c0b9c7dd1c8d2903186541048b | [
"BSD-3-Clause"
] | 42 | 2017-10-06T23:39:52.000Z | 2022-03-26T10:05:55.000Z | src/main/java/com/typelead/gradle/utils/NoSpec.java | jneira/gradle-eta | a3f264caf3cc10c0b9c7dd1c8d2903186541048b | [
"BSD-3-Clause"
] | 7 | 2018-03-26T06:34:04.000Z | 2021-11-06T22:32:10.000Z | 17.555556 | 56 | 0.64557 | 8,349 | package com.typelead.gradle.utils;
public class NoSpec extends ExecutableSpec {
private static final NoSpec INSTANCE = new NoSpec();
public static NoSpec getInstance() {
return INSTANCE;
}
private NoSpec() {}
@Override
public String toString() {
return "NoSpec";
}
}
|
3e13ba1060f1a17eb902b2500de89bdffdd80178 | 8,098 | java | Java | com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_UnholyArmament.java | welterde/ewok | 6fce1fd0b8b1164eba79c17252708d3215bd90e9 | [
"Apache-2.0"
] | 1 | 2019-02-25T09:33:03.000Z | 2019-02-25T09:33:03.000Z | com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_UnholyArmament.java | welterde/ewok | 6fce1fd0b8b1164eba79c17252708d3215bd90e9 | [
"Apache-2.0"
] | null | null | null | com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_UnholyArmament.java | welterde/ewok | 6fce1fd0b8b1164eba79c17252708d3215bd90e9 | [
"Apache-2.0"
] | 2 | 2017-08-15T12:28:07.000Z | 2021-08-07T05:24:00.000Z | 37.146789 | 193 | 0.686219 | 8,350 | package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
@SuppressWarnings("unchecked")
public class Prayer_UnholyArmament extends Prayer
{
public String ID() { return "Prayer_UnholyArmament"; }
public String name(){ return "Unholy Armament";}
protected int canAffectCode(){return 0;}
protected int canTargetCode(){return 0;}
public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_HOLYPROTECTION;}
public int abstractQuality(){ return Ability.QUALITY_OK_SELF;}
public long flags(){return Ability.FLAG_UNHOLY;}
protected int overrideMana(){return Integer.MAX_VALUE;}
public static final long[] checkOrder={
Wearable.WORN_WIELD,
Wearable.WORN_TORSO,
Wearable.WORN_LEGS,
Wearable.WORN_WAIST,
Wearable.WORN_HEAD,
Wearable.WORN_ARMS,
Wearable.WORN_FEET,
Wearable.WORN_HANDS,
Wearable.WORN_LEFT_WRIST,
Wearable.WORN_RIGHT_WRIST,
Wearable.WORN_ABOUT_BODY,
};
public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
{
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
if(mob.isInCombat())
{
mob.tell("Not during combat!");
return false;
}
long pos=-1;
int i=0;
Item I=null;
while(i<checkOrder.length)
{
if(mob.freeWearPositions(checkOrder[i],(short)0,(short)0)<=0)
{
i++;
continue;
}
pos=checkOrder[i];
if(pos<0)
{
if(mob.getWorshipCharID().length()>0)
mob.tell(mob.getWorshipCharID()+" can see that you are already completely armed.");
else
mob.tell("The gods can see that you are already armed.");
return false;
}
if(pos==Wearable.WORN_WIELD)
{
I=CMClass.getWeapon("GenWeapon");
I.setName("an unholy blade");
I.setDisplayText("an wicked looking blade sits here.");
((Weapon)I).setWeaponClassification(Weapon.CLASS_SWORD);
((Weapon)I).setWeaponType(Weapon.TYPE_SLASHING);
I.setDescription("Whatever made this sharp twisted thing couldn`t have been good..");
I.baseEnvStats().setLevel(mob.envStats().level());
I.baseEnvStats().setWeight(20);
I.setMaterial(RawMaterial.RESOURCE_MITHRIL);
I.recoverEnvStats();
Hashtable H=CMLib.itemBuilder().timsItemAdjustments(I,mob.envStats().level()+(2*super.getXLEVELLevel(mob)),I.material(),1,((Weapon)I).weaponClassification(),0,I.rawProperLocationBitmap());
I.baseEnvStats().setDamage(CMath.s_int((String)H.get("DAMAGE")));
I.baseEnvStats().setAttackAdjustment(CMath.s_int((String)H.get("ATTACK")));
I.setBaseValue(0);
}
else
{
I=CMClass.getArmor("GenArmor");
I.setRawProperLocationBitmap(pos);
I.baseEnvStats().setLevel(mob.envStats().level());
if(pos==Wearable.WORN_ABOUT_BODY)
I.setMaterial(RawMaterial.RESOURCE_COTTON);
else
I.setMaterial(RawMaterial.RESOURCE_MITHRIL);
I.recoverEnvStats();
Hashtable H=CMLib.itemBuilder().timsItemAdjustments(I,mob.envStats().level()+(2*super.getXLEVELLevel(mob)),I.material(),1,0,0,I.rawProperLocationBitmap());
I.baseEnvStats().setArmor(CMath.s_int((String)H.get("ARMOR")));
I.baseEnvStats().setWeight(CMath.s_int((String)H.get("WEIGHT")));
I.setBaseValue(0);
if(pos==Wearable.WORN_TORSO)
{
I.setName("an unholy breast plate");
I.setDisplayText("a wicked looking breast plate sits here.");
I.setDescription("Whatever made this black spiked armor couldn`t have been good.");
}
if(pos==Wearable.WORN_HEAD)
{
I.setName("an unholy helm");
I.setDisplayText("a wicked looking helmet sits here.");
I.setDescription("Whatever made this spiked helmet couldn`t have been good.");
}
if(pos==Wearable.WORN_ABOUT_BODY)
{
I.setName("an unholy cape");
I.setDisplayText("a torn black cape sits here.");
I.setDescription("Whatever made this cape couldn`t have been good.");
}
if(pos==Wearable.WORN_ARMS)
{
I.setName("some unholy arm cannons");
I.setDisplayText("a pair of wicked looking arm cannons sit here.");
I.setDescription("Whatever made this couldn`t have been good.");
}
if((pos==Wearable.WORN_LEFT_WRIST)
||(pos==Wearable.WORN_RIGHT_WRIST))
{
I.setName("an unholy vambrace");
I.setDisplayText("a wicked looking spiked vambrace sit here.");
I.setDescription("Whatever made this twisted black metal couldn`t have been good.");
}
if(pos==Wearable.WORN_HANDS)
{
I.setName("a pair of unholy gauntlets");
I.setDisplayText("some wicked looking gauntlets sit here.");
I.setDescription("Whatever made this twisted black metal couldn`t have been good.");
}
if(pos==Wearable.WORN_WAIST)
{
I.setName("an unholy girdle");
I.setDisplayText("a wicked looking girdle sits here.");
I.setDescription("Whatever made this twisted black metal couldn`t have been good.");
}
if(pos==Wearable.WORN_LEGS)
{
I.setName("a pair of unholy leg cannons");
I.setDisplayText("a wicked looking pair of leg cannons sits here.");
I.setDescription("Whatever made this twisted and spiked black metal couldn`t have been good.");
}
if(pos==Wearable.WORN_FEET)
{
I.setName("a pair of unholy boots");
I.setDisplayText("a wicked looking pair of boots sits here.");
I.setDescription("Whatever made this pair of twisted and spiked black metal boots couldn`t have been good.");
}
}
Ability A=CMClass.getAbility("Prop_HaveZapper");
if(A!=null)
{
A.setMiscText("-GOOD -NEUTRAL -NAMES \"+"+mob.Name()+"\"");
I.addNonUninvokableEffect(A);
}
I.recoverEnvStats();
if((mob.fetchInventory(null,"$"+I.name()+"$")!=null)
||(mob.location().fetchItem(null,"$"+I.name()+"$")!=null))
{
i++;
I=null;
continue;
}
break;
}
boolean success=proficiencyCheck(mob,0,auto);
if((success)&&(I!=null))
{
// it worked, so build a copy of this ability,
// and add it to the affects list of the
// affected MOB. Then tell everyone else
// what happened.
CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":"^S<S-NAME> "+prayWord(mob)+" to be provided armament!^?");
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().addItemRefuse(I,CMProps.getIntVar(CMProps.SYSTEMI_EXPIRE_MONSTER_EQ));
mob.location().showHappens(CMMsg.MSG_OK_VISUAL,I.name()+" materializes out of the ground.");
}
}
else
return beneficialWordsFizzle(mob, null,"<S-NAME> "+prayWord(mob)+" for armament, but flub(s) it.");
// return whether it worked
return success;
}
}
|
3e13ba393dc06f77475f4f9852a663f8bad90918 | 672 | java | Java | src/main/java/com/qiangdong/reader/request/topic/AddOrUpdateTopicRequest.java | zshnb/qiangdongserver | 0c16fec01b369d5491b8239860f291732db38f2e | [
"Apache-2.0"
] | 8 | 2021-05-21T06:33:01.000Z | 2021-07-29T08:47:09.000Z | src/main/java/com/qiangdong/reader/request/topic/AddOrUpdateTopicRequest.java | zshnb/qiangdongserver | 0c16fec01b369d5491b8239860f291732db38f2e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/qiangdong/reader/request/topic/AddOrUpdateTopicRequest.java | zshnb/qiangdongserver | 0c16fec01b369d5491b8239860f291732db38f2e | [
"Apache-2.0"
] | 5 | 2021-05-24T09:20:04.000Z | 2021-09-18T08:09:29.000Z | 18.666667 | 58 | 0.706845 | 8,351 | package com.qiangdong.reader.request.topic;
import com.qiangdong.reader.request.BaseRequest;
import javax.validation.constraints.Size;
public class AddOrUpdateTopicRequest extends BaseRequest {
private Long topicId = 0L;
@Size(min = 1, max = 15, message = "话题在1-15字之间")
private String name = "";
private String cover = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public Long getTopicId() {
return topicId;
}
public void setTopicId(Long topicId) {
this.topicId = topicId;
}
}
|
3e13babc5d3d6db6df6e4fca06009bfee5c2a4e4 | 1,460 | java | Java | motiverFi/src/com/delect/motiver/client/view/nutrition/NutritionPageView.java | motiver/motiver_fi | 2bed6e765484e7909e44ccbaa2e07ae9ce981331 | [
"OML"
] | 1 | 2021-03-11T13:38:42.000Z | 2021-03-11T13:38:42.000Z | motiverFi/src/com/delect/motiver/client/view/nutrition/NutritionPageView.java | motiver/motiver_fi | 2bed6e765484e7909e44ccbaa2e07ae9ce981331 | [
"OML"
] | null | null | null | motiverFi/src/com/delect/motiver/client/view/nutrition/NutritionPageView.java | motiver/motiver_fi | 2bed6e765484e7909e44ccbaa2e07ae9ce981331 | [
"OML"
] | null | null | null | 34.785714 | 96 | 0.669405 | 8,352 | /*******************************************************************************
* Copyright 2011 Antti Havanko
*
* This file is part of Motiver.fi.
* Motiver.fi is licensed under one open source license and one commercial license.
*
* Commercial license: This is the appropriate option if you want to use Motiver.fi in
* commercial purposes. Contact nnheo@example.com for licensing options.
*
* Open source license: This is the appropriate option if you are creating an open source
* application with a license compatible with the GNU GPL license v3. Although the GPLv3 has
* many terms, the most important is that you must provide the source code of your application
* to your users so they can be free to modify your application for their own needs.
******************************************************************************/
package com.delect.motiver.client.view.nutrition;
import com.google.gwt.user.client.ui.Widget;
import com.delect.motiver.client.presenter.nutrition.NutritionPagePresenter;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
public class NutritionPageView extends NutritionPagePresenter.NutritionPageDisplay {
private LayoutContainer panelCalendar = new LayoutContainer();
@Override
public Widget asWidget() {
this.add(panelCalendar);
return this;
}
@Override
public LayoutContainer getCalendarContainer() {
return panelCalendar;
}
}
|
3e13bcfa52d62fa8e4a70c7e2456093dd36446da | 1,296 | java | Java | src/main/java/cn/itechyou/cms/service/impl/SystemServiceImpl.java | xinhudong/dreamer_cms | 3652d7a03ab879b63bdd2b0d301f0617e751bc13 | [
"Apache-2.0"
] | 31 | 2019-11-04T06:43:56.000Z | 2022-03-26T03:29:11.000Z | src/main/java/cn/itechyou/cms/service/impl/SystemServiceImpl.java | xinhudong/dreamer_cms | 3652d7a03ab879b63bdd2b0d301f0617e751bc13 | [
"Apache-2.0"
] | 2 | 2020-06-22T01:28:11.000Z | 2020-06-22T01:28:12.000Z | src/main/java/cn/itechyou/cms/service/impl/SystemServiceImpl.java | xinhudong/dreamer_cms | 3652d7a03ab879b63bdd2b0d301f0617e751bc13 | [
"Apache-2.0"
] | 15 | 2019-10-16T08:20:26.000Z | 2021-09-03T09:48:37.000Z | 21.6 | 85 | 0.777006 | 8,353 | package cn.itechyou.cms.service.impl;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import cn.itechyou.cms.dao.SystemMapper;
import cn.itechyou.cms.entity.System;
import cn.itechyou.cms.service.SystemService;
import cn.itechyou.cms.utils.FileConfiguration;
import cn.itechyou.cms.utils.LoggerUtils;
/**
* 系统设置业务处理类
*
* @author LIGW
*/
@Service
public class SystemServiceImpl implements SystemService {
/**
* 日志输出
*/
private static final Logger logger = LoggerUtils.getLogger(SystemServiceImpl.class);
@Autowired
private SystemMapper systemMapper;
@Autowired
private FileConfiguration fileConfiguration;
/**
* 系统设置列表
*/
@Override
public System getSystem() {
System System = systemMapper.getCurrentSystem();
return System;
}
/**
* 更新系统设置
*/
@Override
public int update(System system) {
int num = systemMapper.updateByPrimaryKey(system);
return num;
}
}
|
3e13be03e9dd04e360d40c8f878f3350450eb6ec | 278 | java | Java | CapitalBusConnectRepository/src/main/java/eu/sanjin/kurelic/cbc/repo/entity/Country_.java | SanjinKurelic/CapitalBusConnect | 6a6c868d5bbdc380551b76ab69ed37ec7536db75 | [
"Apache-2.0"
] | 1 | 2021-08-06T19:38:37.000Z | 2021-08-06T19:38:37.000Z | CapitalBusConnectRepository/src/main/java/eu/sanjin/kurelic/cbc/repo/entity/Country_.java | SanjinKurelic/CapitalBusConnect | 6a6c868d5bbdc380551b76ab69ed37ec7536db75 | [
"Apache-2.0"
] | null | null | null | CapitalBusConnectRepository/src/main/java/eu/sanjin/kurelic/cbc/repo/entity/Country_.java | SanjinKurelic/CapitalBusConnect | 6a6c868d5bbdc380551b76ab69ed37ec7536db75 | [
"Apache-2.0"
] | null | null | null | 23.166667 | 66 | 0.820144 | 8,354 | package eu.sanjin.kurelic.cbc.repo.entity;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@StaticMetamodel(Country.class)
public class Country_ {
public static volatile SingularAttribute<Country, Integer> id;
}
|
3e13be5aded714efdd17ae76c564eb028dfaa727 | 196 | java | Java | transaction/src/main/java/transaction/ModelRepository.java | 1459177541/study-test | 3dce400562ee47a22da0ffb6cbb80b3bb6c22b83 | [
"Apache-2.0"
] | null | null | null | transaction/src/main/java/transaction/ModelRepository.java | 1459177541/study-test | 3dce400562ee47a22da0ffb6cbb80b3bb6c22b83 | [
"Apache-2.0"
] | 4 | 2021-12-10T01:31:33.000Z | 2021-12-18T18:38:05.000Z | transaction/src/main/java/transaction/ModelRepository.java | Yang-xingchen/study-test | 3f7a143c727fd0caf201e1582a98a02ba46dffc7 | [
"Apache-2.0"
] | null | null | null | 19.6 | 69 | 0.806122 | 8,355 | package transaction;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ModelRepository extends JpaRepository<Model, Long> {
long countByValue(String value);
}
|
3e13bf3d8044cc0b47c287f38cc4cf9e1497cdf4 | 688 | java | Java | src/main/java/io/github/jroy/cowbot/managers/proxy/discord/Roles.java | schlatt-co/CowBot | f98df6cec191d9d783721cf65f77ea7d20779924 | [
"Apache-2.0"
] | 8 | 2019-06-12T04:30:16.000Z | 2021-04-23T21:48:12.000Z | src/main/java/io/github/jroy/cowbot/managers/proxy/discord/Roles.java | JRoy/CowBot | f98df6cec191d9d783721cf65f77ea7d20779924 | [
"Apache-2.0"
] | 7 | 2019-08-15T00:18:58.000Z | 2020-04-30T04:12:03.000Z | src/main/java/io/github/jroy/cowbot/managers/proxy/discord/Roles.java | schlatt-co/CowBot | f98df6cec191d9d783721cf65f77ea7d20779924 | [
"Apache-2.0"
] | 5 | 2019-08-05T22:13:27.000Z | 2020-06-15T19:20:17.000Z | 21.5 | 53 | 0.732558 | 8,356 | package io.github.jroy.cowbot.managers.proxy.discord;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Role;
public enum Roles {
MINECRAFT("667473176887820328"),
MC_EVENTS("678039483261911062"),
CIVILIZATION("620410029698449412"),
TF2("667473453502300200"),
CSGO("642104537431408670"),
STELLARIS("667472343416963103"),
RAINBOW("611356436345389066"),
TARKOV("673316710631079940"),
DESTINY_2("673392168747925514");
private final String roleId;
Roles(String roleId) {
this.roleId = roleId;
}
public String getRoleId() {
return roleId;
}
public Role getRole(Guild guild) {
return guild.getRoleById(roleId);
}
}
|
3e13bffe6d7219d5a50de217ea405f173fa267af | 2,210 | java | Java | src/java/org/codehaus/groovy/grails/resolve/GrailsPluginsDirectoryResolver.java | slaunay/grails-core | d97520274c244fe0705d82acf1138659ebad57f5 | [
"Apache-2.0"
] | 2 | 2017-12-24T06:58:32.000Z | 2017-12-24T06:58:35.000Z | src/java/org/codehaus/groovy/grails/resolve/GrailsPluginsDirectoryResolver.java | danklynn/grails-core | 55a1e8ebe6384dfb9e0e4dcf50420ccb3177418b | [
"Apache-2.0"
] | null | null | null | src/java/org/codehaus/groovy/grails/resolve/GrailsPluginsDirectoryResolver.java | danklynn/grails-core | 55a1e8ebe6384dfb9e0e4dcf50420ccb3177418b | [
"Apache-2.0"
] | null | null | null | 34.53125 | 97 | 0.675566 | 8,357 | /* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.resolve;
import grails.util.BuildSettings;
import java.io.File;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.plugins.resolver.FileSystemResolver;
/**
* A resolver that resolves JAR files from plugin lib directories.
*
* @author Graeme Rocher
* @since 1.2
*/
public class GrailsPluginsDirectoryResolver extends FileSystemResolver {
private static final String GRAILS_PLUGINS = "grailsPlugins";
private static final String LIB_DIR_PATTERN = "/lib/[artifact]-[revision].[ext]";
public GrailsPluginsDirectoryResolver(BuildSettings buildSettings, IvySettings ivySettings) {
if (buildSettings != null) {
final File pluginsDir = buildSettings.getProjectPluginsDir();
final File basedir = buildSettings.getBaseDir();
if (basedir != null) {
addArtifactPattern(basedir.getAbsolutePath() + LIB_DIR_PATTERN);
}
addPatternsForPluginsDirectory(pluginsDir);
addPatternsForPluginsDirectory(buildSettings.getGlobalPluginsDir());
}
setName(GRAILS_PLUGINS);
setSettings(ivySettings);
}
private void addPatternsForPluginsDirectory(File pluginsDir) {
if (pluginsDir == null) {
return;
}
final File[] files = pluginsDir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
addArtifactPattern(f.getAbsolutePath()+ LIB_DIR_PATTERN);
}
}
}
}
}
|
3e13c078cc585819f700fde4ac7ce693c8f72cd9 | 23,327 | java | Java | app/src/main/java/ml/melun/mangaview/activity/SettingsActivity.java | ghk01214/MangaViewAndroid | b5d20d29616a0cece94d8fd4c298006d2b509d62 | [
"MIT"
] | 32 | 2019-01-16T15:30:35.000Z | 2021-12-18T03:47:36.000Z | app/src/main/java/ml/melun/mangaview/activity/SettingsActivity.java | ghk01214/MangaViewAndroid | b5d20d29616a0cece94d8fd4c298006d2b509d62 | [
"MIT"
] | 16 | 2019-01-17T02:16:17.000Z | 2022-02-20T05:49:06.000Z | app/src/main/java/ml/melun/mangaview/activity/SettingsActivity.java | ghk01214/MangaViewAndroid | b5d20d29616a0cece94d8fd4c298006d2b509d62 | [
"MIT"
] | 10 | 2019-01-17T02:12:21.000Z | 2021-11-06T16:33:18.000Z | 43.198148 | 145 | 0.531916 | 8,358 | package ml.melun.mangaview.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import ml.melun.mangaview.Preference;
import ml.melun.mangaview.R;
import ml.melun.mangaview.UrlUpdater;
import static ml.melun.mangaview.MainApplication.p;
import static ml.melun.mangaview.Utils.readPreferenceFromFile;
import static ml.melun.mangaview.Utils.showPopup;
import static ml.melun.mangaview.Utils.writePreferenceToFile;
import static ml.melun.mangaview.activity.FolderSelectActivity.MODE_FILE_SAVE;
import static ml.melun.mangaview.activity.FolderSelectActivity.MODE_FILE_SELECT;
import static ml.melun.mangaview.activity.FolderSelectActivity.MODE_FOLDER_SELECT;
public class SettingsActivity extends AppCompatActivity {
//다운로드 위치 설정
//데이터 절약 모드 : 외부 이미지 로드 안함
//
Context context;
ConstraintLayout s_setHomeDir, s_resetHistory, s_dark, s_viewer, s_reverse, s_pageRtl, s_dataSave, s_tab, s_stretch;
Spinner s_tab_spinner, s_viewer_spinner;
Switch s_dark_switch, s_reverse_switch, s_pageRtl_switch, s_dataSave_switch, s_stretch_switch;
Boolean dark;
public static final String prefExtension = ".mvpref";
public static final int RESULT_NEED_RESTART = 7;
View.OnClickListener pbtnClear, nbtnClear, pbtnSet, nbtnSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
dark = p.getDarkTheme();
if(dark) setTheme(R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
context = this;
s_setHomeDir = this.findViewById(R.id.setting_dir);
s_setHomeDir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, FolderSelectActivity.class);
startActivityForResult(intent, MODE_FOLDER_SELECT);
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// s_getSd = this.findViewById(R.id.setting_externalSd);
// s_getSd.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// p.setHomeDir("/sdcard");
// }
// });
s_resetHistory = this.findViewById(R.id.setting_reset);
s_resetHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
p.resetBookmark();
p.resetViewerBookmark();
p.resetRecent();
Toast.makeText(context,"초기화 되었습니다.",Toast.LENGTH_LONG).show();
setResult(RESULT_NEED_RESTART);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder;
if(dark) builder = new AlertDialog.Builder(context, R.style.darkDialog);
else builder = new AlertDialog.Builder(context);
builder.setMessage("최근 본 만화, 북마크 및 모든 만화 열람 기록이 사라집니다. 계속 하시겠습니까?\n(좋아요, 저장한 만화 제외)").setPositiveButton("네", dialogClickListener)
.setNegativeButton("아니오", dialogClickListener).show();
}
});
this.findViewById(R.id.setting_key).setOnClickListener(new View.OnClickListener() {
int prevKeyCode;
int nextKeyCode;
InputCallback inputCallback = null;
@Override
public void onClick(View view) {
prevKeyCode = p.getPrevPageKey();
nextKeyCode = p.getNextPageKey();
View v = getLayoutInflater().inflate(R.layout.content_key_set_popup, null);
Button pbtn = v.findViewById(R.id.key_prev);
Button nbtn = v.findViewById(R.id.key_next);
TextView ptext = v.findViewById(R.id.key_prev_text);
TextView ntext = v.findViewById(R.id.key_next_text);
if(prevKeyCode == -1)
ptext.setText("-");
else
ptext.setText(KeyEvent.keyCodeToString(prevKeyCode));
if(nextKeyCode == -1)
ntext.setText("-");
else
ntext.setText(KeyEvent.keyCodeToString(nextKeyCode));
pbtnClear = new View.OnClickListener() {
@Override
public void onClick(View view) {
if(prevKeyCode == -1)
ptext.setText("-");
else
ptext.setText(KeyEvent.keyCodeToString(prevKeyCode));
inputCallback = null;
view.setOnClickListener(pbtnSet);
}
};
nbtnClear = new View.OnClickListener() {
@Override
public void onClick(View view) {
if(nextKeyCode == -1)
ntext.setText("-");
else
ntext.setText(KeyEvent.keyCodeToString(nextKeyCode));
inputCallback = null;
view.setOnClickListener(nbtnSet);
}
};
pbtnSet = new View.OnClickListener() {
@Override
public void onClick(View view) {
if(inputCallback == null) {
view.setOnClickListener(pbtnClear);
ptext.setText("키를 입력해 주세요");
inputCallback = new InputCallback() {
@Override
public void onKeyEvent(KeyEvent event) {
prevKeyCode = event.getKeyCode();
ptext.setText(KeyEvent.keyCodeToString(prevKeyCode));
view.setEnabled(true);
view.setOnClickListener(pbtnSet);
}
};
}
}
};
nbtnSet = new View.OnClickListener() {
@Override
public void onClick(View view) {
if(inputCallback == null) {
view.setOnClickListener(nbtnClear);
ntext.setText("키를 입력해 주세요");
inputCallback = new InputCallback() {
@Override
public void onKeyEvent(KeyEvent event) {
nextKeyCode = event.getKeyCode();
ntext.setText(KeyEvent.keyCodeToString(nextKeyCode));
view.setEnabled(true);
view.setOnClickListener(nbtnSet);
}
};
}
}
};
pbtn.setOnClickListener(pbtnSet);
nbtn.setOnClickListener(nbtnSet);
AlertDialog.Builder builder;
if(dark) builder = new AlertDialog.Builder(context,R.style.darkDialog);
else builder = new AlertDialog.Builder(context);
builder.setTitle("단축키 설정")
.setView(v)
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if(inputCallback != null){
if(keyEvent.getAction() == KeyEvent.ACTION_DOWN){
inputCallback.onKeyEvent(keyEvent);
inputCallback = null;
}
return true;
}
return false;
}
})
.setNeutralButton("초기화", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
p.setPrevPageKey(-1);
p.setNextPageKey(-1);
inputCallback = null;
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
inputCallback = null;
}
})
.setPositiveButton("적용", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
inputCallback = null;
p.setNextPageKey(nextKeyCode);
p.setPrevPageKey(prevKeyCode);
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
inputCallback = null;
}
})
.show();
}
});
s_dark = this.findViewById(R.id.setting_dark);
s_dark_switch = this.findViewById(R.id.setting_dark_switch);
s_dark_switch.setChecked(p.getDarkTheme());
s_dark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s_dark_switch.toggle();
}
});
s_dark_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
p.setDarkTheme(isChecked);
if(isChecked != dark) setResult(RESULT_NEED_RESTART);
else setResult(RESULT_CANCELED);
}
});
s_viewer = this.findViewById(R.id.setting_viewer);
s_viewer_spinner = this.findViewById(R.id.setting_viewer_spinner);
if(dark) s_viewer_spinner.setPopupBackgroundResource(R.color.colorDarkWindowBackground);
s_viewer_spinner.setSelection(p.getViewerType());
s_viewer_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
p.setViewerType(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//
}
});
s_reverse = this.findViewById(R.id.setting_reverse);
s_reverse_switch = this.findViewById(R.id.setting_reverse_switch);
s_reverse_switch.setChecked(p.getReverse());
s_reverse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s_reverse_switch.toggle();
}
});
s_reverse_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
p.setReverse(isChecked);
}
});
s_pageRtl = this.findViewById(R.id.setting_pageRtl);
s_pageRtl_switch = this.findViewById(R.id.setting_pageRtl_switch);
s_pageRtl_switch.setChecked(p.getPageRtl());
s_pageRtl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s_pageRtl_switch.toggle();
}
});
s_pageRtl_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
p.setPageRtl(isChecked);
}
});
s_dataSave = this.findViewById(R.id.setting_dataSave);
s_dataSave_switch = this.findViewById(R.id.setting_dataSave_switch);
s_dataSave_switch.setChecked(p.getDataSave());
s_dataSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s_dataSave_switch.toggle();
}
});
s_dataSave_switch.setOnCheckedChangeListener((buttonView, isChecked) -> p.setDataSave(isChecked));
s_tab = this.findViewById(R.id.setting_startTab);
s_tab_spinner = this.findViewById(R.id.setting_startTab_spinner);
if(dark) s_tab_spinner.setPopupBackgroundResource(R.color.colorDarkWindowBackground);
s_tab_spinner.setSelection(p.getStartTab());
s_tab_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
p.setStartTab(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//
}
});
this.findViewById(R.id.setting_license).setOnClickListener(v -> {
Intent l = new Intent(context,LicenseActivity.class);
startActivity(l);
});
this.findViewById(R.id.setting_url).setOnClickListener(v -> {
urlSettingPopup(context, p);
});
s_stretch = this.findViewById(R.id.setting_stretch);
s_stretch_switch = this.findViewById(R.id.setting_stretch_switch);
s_stretch_switch.setChecked(p.getStretch());
s_stretch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s_stretch_switch.toggle();
}
});
s_stretch_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
p.setStretch(isChecked);
}
});
this.findViewById(R.id.setting_buttonLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(context, LayoutEditActivity.class));
}
});
this.findViewById(R.id.setting_dataExport).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, FolderSelectActivity.class);
intent.putExtra("mode", MODE_FILE_SAVE);
intent.putExtra("title", "파일 저장");
startActivityForResult(intent, MODE_FILE_SAVE);
}
});
this.findViewById(R.id.setting_dataImport).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, FolderSelectActivity.class);
intent.putExtra("mode", MODE_FILE_SELECT);
intent.putExtra("title", "파일 선택");
startActivityForResult(intent, MODE_FILE_SELECT);
}
});
}
public static void urlSettingPopup(Context context, Preference p){
final LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
final LinearLayout switch_layout = new LinearLayout(context);
switch_layout.setOrientation(LinearLayout.HORIZONTAL);
switch_layout.setGravity(Gravity.RIGHT);
switch_layout.setPadding(0,0,10,0);
final TextView definputtext = new TextView(context);
final EditText definput = new EditText(context);
final TextView inputtext = new TextView(context);
final EditText input = new EditText(context);
final TextView toggle_lbl = new TextView(context);
toggle_lbl.setText("URL 자동 설정");
final Switch toggle = new Switch(context);
definputtext.setText("기본 URL (숫자 없는 주소):");
inputtext.setText("URL:");
switch_layout.addView(toggle_lbl);
switch_layout.addView(toggle);
layout.addView(definputtext);
layout.addView(definput);
layout.addView(inputtext);
layout.addView(input);
layout.addView(switch_layout);
toggle.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
definput.setEnabled(true);
input.setEnabled(false);
input.setText("...");
}else{
definput.setEnabled(false);
input.setEnabled(true);
input.setText(p.getUrl());
}
}
});
toggle.setChecked(p.getAutoUrl());
if(toggle.isChecked()){
definput.setEnabled(true);
input.setEnabled(false);
input.setText("...");
}else{
definput.setEnabled(false);
input.setEnabled(true);
input.setText(p.getUrl());
}
input.setText(p.getUrl());
input.setHint(p.getUrl());
definput.setText(p.getDefUrl());
definput.setHint(p.getDefUrl());
AlertDialog.Builder builder;
if(p.getDarkTheme()) builder = new AlertDialog.Builder(context,R.style.darkDialog);
else builder = new AlertDialog.Builder(context);
builder.setTitle("URL 설정")
.setView(layout)
.setPositiveButton("설정", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
if(toggle.isChecked()){
// 자동 설정
if(definput.getText().length()>0)
p.setDefUrl(definput.getText().toString());
else
p.setDefUrl(definput.getHint().toString());
p.setAutoUrl(true);
new UrlUpdater(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else {
// 수동 설정
p.setAutoUrl(false);
if (input.getText().length() > 0)
p.setUrl(input.getText().toString());
else
p.setUrl(input.getHint().toString());
}
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
//do nothing
}
})
.show();
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data != null) {
String path = data.getStringExtra("path");
if (path != null) {
switch (requestCode) {
case MODE_FILE_SELECT:
if(readPreferenceFromFile(p, context, new File(path))) {
setResult(RESULT_NEED_RESTART);
showPopup(context, "데이터 불러오기", "데이터 불러오기를 성공했습니다. 변경사항을 적용하기 위해 앱을 재시작 합니다.", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
});
}else
Toast.makeText(context, "불러오기 실패", Toast.LENGTH_LONG).show();
break;
case MODE_FOLDER_SELECT:
p.setHomeDir(path);
Toast.makeText(context, "설정 완료!", Toast.LENGTH_LONG).show();
break;
case MODE_FILE_SAVE:
if(writePreferenceToFile(context, new File(path)))
Toast.makeText(context, "내보내기 완료!", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "내보내기 실패", Toast.LENGTH_LONG).show();
break;
}
}
}
}
private interface InputCallback{
void onKeyEvent(KeyEvent event);
}
}
|
3e13c08a53c78f4efb3feb2fce94894b1996d0b4 | 228 | java | Java | guice/binder-basic/src/main/java/io/edurt/lc/guice/GuiceBasicServiceImpl.java | EdurtIO/learning-center-code | 2bc497a70c7a2832725baac74d7c787cdbc41751 | [
"Apache-2.0"
] | null | null | null | guice/binder-basic/src/main/java/io/edurt/lc/guice/GuiceBasicServiceImpl.java | EdurtIO/learning-center-code | 2bc497a70c7a2832725baac74d7c787cdbc41751 | [
"Apache-2.0"
] | null | null | null | guice/binder-basic/src/main/java/io/edurt/lc/guice/GuiceBasicServiceImpl.java | EdurtIO/learning-center-code | 2bc497a70c7a2832725baac74d7c787cdbc41751 | [
"Apache-2.0"
] | null | null | null | 19 | 61 | 0.671053 | 8,359 | package io.edurt.lc.guice;
public class GuiceBasicServiceImpl
implements GuiceBasicService
{
@Override
public void print(String input)
{
System.out.println(String.format("print %s", input));
}
}
|
3e13c09731c61f668ee8b1e5359e3411499a898e | 9,300 | java | Java | loaders/src/androidTest/java/mobi/liaison/loaders/database/ContentTableTest.java | EmirWeb/liaison-loaders | 7c4db35488b9c01d5d894bce495e57aa8f4d6026 | [
"Apache-2.0"
] | null | null | null | loaders/src/androidTest/java/mobi/liaison/loaders/database/ContentTableTest.java | EmirWeb/liaison-loaders | 7c4db35488b9c01d5d894bce495e57aa8f4d6026 | [
"Apache-2.0"
] | null | null | null | loaders/src/androidTest/java/mobi/liaison/loaders/database/ContentTableTest.java | EmirWeb/liaison-loaders | 7c4db35488b9c01d5d894bce495e57aa8f4d6026 | [
"Apache-2.0"
] | null | null | null | 36.758893 | 169 | 0.682581 | 8,360 | package mobi.liaison.loaders.database;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.Set;
import mobi.liaison.loaders.Path;
import mobi.liaison.loaders.database.annotations.PrimaryKey;
import mobi.liaison.loaders.database.annotations.TableColumn;
import mobi.liaison.loaders.database.annotations.TableColumns;
import mobi.liaison.loaders.database.annotations.TablePath;
import mobi.liaison.loaders.database.annotations.TablePaths;
import mobi.liaison.loaders.database.annotations.Unique;
import static junit.framework.Assert.fail;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.IsEqual.equalTo;
@RunWith(AndroidJUnit4.class)
public class ContentTableTest {
public final Context mContext = InstrumentationRegistry.getContext();
@Test
public void getCreateWithOneParameter_returnsCorrectSqlTableCreationAndDrop(){
final MockModel mockModel = new MockModel("EMIR", new Path("PATH1", "PATH2"));
final Column modelColumn = new Column("CONTENT_NAME", "COLUMN_NAME", Column.Type.text);
mockModel.setModelColums(modelColumn);
final String sqlCreateQuery = mockModel.getCreate(mContext);
assertThat(sqlCreateQuery, equalTo("CREATE TABLE IF NOT EXISTS EMIR ( COLUMN_NAME TEXT );"));
final String sqlDropQuery = mockModel.getDrop(mContext);
assertThat(sqlDropQuery, equalTo("DROP TABLE IF EXISTS EMIR;"));
}
@Test
public void getCreateWithOneParameterAndUnique_returnsCorrectSqlTableCreationAndDrop(){
final MockModel mockModel = new MockModel("EMIR", new Path("PATH1", "PATH2"));
final Column modelColumn = new Column("CONTENT_NAME", "COLUMN_NAME", Column.Type.text);
mockModel.setModelColums(modelColumn);
mockModel.setUniqueModelColums(modelColumn);
final String sqlCreateQuery = mockModel.getCreate(mContext);
assertThat(sqlCreateQuery, equalTo("CREATE TABLE IF NOT EXISTS EMIR ( COLUMN_NAME TEXT, UNIQUE ( COLUMN_NAME ) ON CONFLICT REPLACE );"));
final String sqlDropQuery = mockModel.getDrop(mContext);
assertThat(sqlDropQuery, equalTo("DROP TABLE IF EXISTS EMIR;"));
}
@Test
public void getCreateWithMultipleParameters_returnsCorrectSqlTableCreationAndDrop(){
final MockModel mockModel = new MockModel("EMIR", new Path("PATH1", "PATH2"));
final Column modelColumn = new Column("CONTENT_NAME", "COLUMN_NAME", Column.Type.text);
final Column modelColumn1 = new Column("CONTENT_NAME1", "COLUMN_NAME1", Column.Type.integer);
mockModel.setModelColums(modelColumn, modelColumn1);
final String sqlCreateQuery = mockModel.getCreate(mContext);
assertThat(sqlCreateQuery, equalTo("CREATE TABLE IF NOT EXISTS EMIR ( COLUMN_NAME TEXT, COLUMN_NAME1 INTEGER );"));
final String sqlDropQuery = mockModel.getDrop(mContext);
assertThat(sqlDropQuery, equalTo("DROP TABLE IF EXISTS EMIR;"));
}
@Test
public void createShouldUseUniquesPrimaryKeyAndColumns(){
final MockAnnotationModel mockAnnotationModel = new MockAnnotationModel();
final String sqlCreateQuery = mockAnnotationModel.getCreate(mContext);
assertThat(sqlCreateQuery, equalTo("CREATE TABLE IF NOT EXISTS MockAnnotationModel " +
"(" +
" MODEL_COLUMN_1 TEXT," +
" MODEL_COLUMN_2 TEXT," +
" MODEL_COLUMN_3 TEXT," +
" UNIQUE ( MODEL_COLUMN_2 ) ON CONFLICT REPLACE," +
" PRIMARY KEY ( MODEL_COLUMN_3 ) " +
");"));
}
@Test
public void createShouldUseForeignKeyAndColumns(){
final MockForeignKeyAnnotationModel mockForeignKeyAnnotationModel = new MockForeignKeyAnnotationModel();
final String sqlCreateQuery = mockForeignKeyAnnotationModel.getCreate(mContext);
assertThat(sqlCreateQuery, equalTo("CREATE TABLE IF NOT EXISTS MockForeignKeyAnnotationModel " +
"(" +
" MODEL_COLUMN_1 TEXT," +
" MODEL_COLUMN_2 TEXT," +
" FOREIGN KEY ( MODEL_COLUMN_1, MODEL_COLUMN_2 ) REFERENCES MockAnnotationModel( MODEL_COLUMN_1, MODEL_COLUMN_2 ) ON DELETE CASCADE ON UPDATE CASCADE " +
");"));
}
@Test
public void createThrowErrorForBadForeignKeyAndColumns(){
final MockBadForeignKeyAnnotationModel mockBadForeignKeyAnnotationModel = new MockBadForeignKeyAnnotationModel();
try {
final String sqlCreateQuery = mockBadForeignKeyAnnotationModel.getCreate(mContext);
fail("Expected Exception");
} catch (final Exception exception){
}
}
@Test
public void annotationsShouldBuildGetColumnsAndGetUniquesAndPathsAndGetId(){
final MockAnnotationModel mockAnnotationModel = new MockAnnotationModel();
final List<Column> columns = mockAnnotationModel.getColumns(mContext);
assertThat(columns, hasSize(3));
final Set<Column> uniqueColumns = mockAnnotationModel.getUniqueColumns(mContext);
assertThat(uniqueColumns, hasSize(1));
final List<Path> paths = mockAnnotationModel.getPaths(mContext);
assertThat(paths, hasSize(1));
}
public static class MockModel extends TableContent {
public String mName;
public List<Path> mPathSegments;
private List<Column> mModelColums;
private Set<Column> mUniqueModelColums;
public MockModel(String name, Path... pathSegments) {
mName = name;
mPathSegments = Lists.newArrayList(pathSegments);
}
public void setModelColums(Column... modelColums){
mModelColums = Lists.newArrayList(modelColums);
}
public void setUniqueModelColums(Column... modelColums){
mUniqueModelColums = Sets.newHashSet(modelColums);
}
@Override
public String getName(Context context) {
return mName;
}
@Override
public List<Path> getPaths(Context context) {
return mPathSegments;
}
@Override
public List<Column> getColumns(Context context) {
return mModelColums;
}
@Override
public Set<Column> getUniqueColumns(Context context) {
return mUniqueModelColums;
}
}
public static class MockAnnotationModel extends TableContent {
public static final String NAME = MockAnnotationModel.class.getSimpleName();
@Override
public String getName(Context context) {
return NAME;
}
@TableColumns
public static class Columns {
@TableColumn
public static final Column MODEL_COLUMN_1 = new Column(NAME, "MODEL_COLUMN_1", Column.Type.text);
@Unique
@TableColumn
public static final Column MODEL_COLUMN_2 = new Column(NAME, "MODEL_COLUMN_2", Column.Type.text);
@PrimaryKey
@TableColumn
public static final Column MODEL_COLUMN_3 = new Column(NAME, "MODEL_COLUMN_3", Column.Type.text);
}
@TablePaths
public static class Paths {
@TablePath
public static final Path PATH = new Path(NAME);
}
}
public static class MockForeignKeyAnnotationModel extends TableContent {
public static final String NAME = MockForeignKeyAnnotationModel.class.getSimpleName();
@Override
public String getName(Context context) {
return NAME;
}
@TableColumns
public static class Columns {
@TableColumn
public static final ForeignKeyColumn MODEL_COLUMN_1 = new ForeignKeyColumn(NAME, MockAnnotationModel.Columns.MODEL_COLUMN_1);
@TableColumn
public static final ForeignKeyColumn MODEL_COLUMN_2 = new ForeignKeyColumn(NAME, MockAnnotationModel.Columns.MODEL_COLUMN_2);
}
@TablePaths
public static class Paths {
@TablePath
public static final Path PATH = new Path(NAME);
}
}
public static class MockBadForeignKeyAnnotationModel extends TableContent {
public static final String NAME = MockForeignKeyAnnotationModel.class.getSimpleName();
@Override
public String getName(Context context) {
return NAME;
}
@TableColumns
public static class Columns {
@TableColumn
public static final ForeignKeyColumn MODEL_COLUMN_1 = new ForeignKeyColumn(NAME, MockAnnotationModel.Columns.MODEL_COLUMN_1);
@TableColumn
public static final ForeignKeyColumn MODEL_COLUMN_2 = new ForeignKeyColumn(NAME, MockForeignKeyAnnotationModel.Columns.MODEL_COLUMN_1);
}
@TablePaths
public static class Paths {
@TablePath
public static final Path PATH = new Path(NAME);
}
}
} |
3e13c1109c8250455a08dcdbda9904c3474bfc12 | 784 | java | Java | server/router/src/test/java/org/infinispan/server/router/utils/CacheManagerTestingUtil.java | mrseal/infinispan | 87b78f4da3c4b488a44f605d068e9993dadbccc5 | [
"Apache-2.0"
] | null | null | null | server/router/src/test/java/org/infinispan/server/router/utils/CacheManagerTestingUtil.java | mrseal/infinispan | 87b78f4da3c4b488a44f605d068e9993dadbccc5 | [
"Apache-2.0"
] | 1 | 2017-09-15T18:57:37.000Z | 2017-09-15T18:57:37.000Z | server/router/src/test/java/org/infinispan/server/router/utils/CacheManagerTestingUtil.java | mrseal/infinispan | 87b78f4da3c4b488a44f605d068e9993dadbccc5 | [
"Apache-2.0"
] | null | null | null | 39.2 | 91 | 0.797194 | 8,361 | package org.infinispan.server.router.utils;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
public class CacheManagerTestingUtil {
public static ConfigurationBuilder createDefaultCacheConfiguration() {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.compatibility().enable();
return configurationBuilder;
}
public static GlobalConfigurationBuilder createDefaultGlobalConfiguration() {
GlobalConfigurationBuilder configurationBuilder = new GlobalConfigurationBuilder();
configurationBuilder.globalJmxStatistics().disable().allowDuplicateDomains(true);
return configurationBuilder;
}
}
|
3e13c1e70a4dbc28a0e25e6b8db0fb5189f407a5 | 262 | java | Java | src/test/java/demo/reuse/TemplateMethodTest.java | alengul/project | b895645bcdbc320c6a1abff5b19ad91366c517b6 | [
"OML"
] | null | null | null | src/test/java/demo/reuse/TemplateMethodTest.java | alengul/project | b895645bcdbc320c6a1abff5b19ad91366c517b6 | [
"OML"
] | null | null | null | src/test/java/demo/reuse/TemplateMethodTest.java | alengul/project | b895645bcdbc320c6a1abff5b19ad91366c517b6 | [
"OML"
] | null | null | null | 18.714286 | 61 | 0.70229 | 8,362 | package demo.reuse;
import org.junit.Test;
import java.sql.Connection;
public class TemplateMethodTest {
@Test
public void shouldUseTemplateAndSubstituteStep() {
final TemplateMethod sut = new StepImplementation2();
sut.log();
}
}
|
3e13c2c2d89ad6e998c18f91b6db9926d6364dcb | 3,691 | java | Java | src/org/mindinformatics/gwt/domeo/plugins/resource/bibliography/src/connector/gwt/GwtBibliographyConnector.java | rkboyce/DomeoClient | f247733cc9a67c34d0d983defcec74124c3b0dc5 | [
"Apache-2.0"
] | null | null | null | src/org/mindinformatics/gwt/domeo/plugins/resource/bibliography/src/connector/gwt/GwtBibliographyConnector.java | rkboyce/DomeoClient | f247733cc9a67c34d0d983defcec74124c3b0dc5 | [
"Apache-2.0"
] | 19 | 2015-03-10T15:36:41.000Z | 2016-01-14T17:46:27.000Z | src/org/mindinformatics/gwt/domeo/plugins/resource/bibliography/src/connector/gwt/GwtBibliographyConnector.java | rkboyce/DomeoClient | f247733cc9a67c34d0d983defcec74124c3b0dc5 | [
"Apache-2.0"
] | null | null | null | 51.375 | 190 | 0.780752 | 8,363 | package org.mindinformatics.gwt.domeo.plugins.resource.bibliography.src.connector.gwt;
import org.mindinformatics.gwt.domeo.client.IDomeo;
import org.mindinformatics.gwt.domeo.model.MAnnotationReference;
import org.mindinformatics.gwt.domeo.plugins.resource.bibliography.src.connector.IBibliographyConnector;
import org.mindinformatics.gwt.domeo.plugins.resource.bibliography.src.connector.IStarringRequestCompleted;
import org.mindinformatics.gwt.domeo.plugins.resource.document.model.MDocumentResource;
import org.mindinformatics.gwt.framework.model.references.MPublicationArticleReference;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.Window;
/**
* @author Paolo Ciccarese <hzdkv@example.com>
*/
public class GwtBibliographyConnector implements IBibliographyConnector {
private IDomeo _domeo;
public GwtBibliographyConnector(IDomeo domeo) {
_domeo = domeo;
}
@Override
public void starResource(MDocumentResource documentResource, IStarringRequestCompleted completionHandler) {
JSONObject r = new JSONObject();
r.put("url", new JSONString(documentResource.getUrl()));
r.put("label", new JSONString(documentResource.getLabel()));
if(_domeo.getAnnotationPersistenceManager().getBibliographicSet().getSelfReference()!=null &&
_domeo.getAnnotationPersistenceManager().getBibliographicSet().getSelfReference()!=null &&
((MAnnotationReference)_domeo.getAnnotationPersistenceManager().getBibliographicSet().getSelfReference()).getReference()!=null &&
((MAnnotationReference)_domeo.getAnnotationPersistenceManager().getBibliographicSet().getSelfReference()).getReference() instanceof MPublicationArticleReference) {
MPublicationArticleReference ref = (MPublicationArticleReference) ((MAnnotationReference)_domeo.getAnnotationPersistenceManager().getBibliographicSet().getSelfReference()).getReference();
Window.alert("Self reference");
JSONObject reference = new JSONObject();
//jo.put("class", new JSONString(MAnnotation.class.getName()));
reference.put("@type", new JSONString(ref.getClass().getName()));
reference.put("@id", new JSONString(ref.getDoi()!=null?ref.getDoi():"<unknown-fix>"));
reference.put("title", new JSONString(ref.getTitle()!=null?ref.getTitle():"<unknown>"));
reference.put("authorNames", new JSONString(ref.getAuthorNames()!=null?ref.getAuthorNames():"<unknown>"));
if(ref.getDoi()!=null) reference.put("doi", new JSONString(ref.getDoi()));
if(ref.getPubMedId()!=null) reference.put("pmid", new JSONString(ref.getPubMedId()));
if(ref.getPubMedCentralId()!=null) reference.put("pmcid", new JSONString(ref.getPubMedCentralId()));
reference.put("publicationInfo", new JSONString(ref.getJournalPublicationInfo()!=null?ref.getJournalPublicationInfo():"<unknown>"));
reference.put("journalName", new JSONString(ref.getJournalName()!=null?ref.getJournalName():"<unknown>"));
reference.put("journalIssn", new JSONString(ref.getJournalIssn()!=null?ref.getJournalIssn():"<unknown>"));
if(ref.getUnrecognized()!=null) reference.put("unrecognized", new JSONString(ref.getUnrecognized()));
r.put("reference", reference);
} else {
Window.alert("No self reference");
}
Window.alert(r.toString());
completionHandler.documentResourceStarred();
}
@Override
public void isResourceStarred(MDocumentResource resource,
IStarringRequestCompleted completionHandler) {
completionHandler.documentResourceStarred(false);
}
@Override
public void unstarResource(MDocumentResource resource, IStarringRequestCompleted completionHandler) {
completionHandler.documentResourceUnstarred();
}
}
|
3e13c3357150c0fbd5c763e2783282507c897382 | 1,193 | java | Java | ontologymanager/generic/servicesapi/src/main/java/org/apache/stanbol/ontologymanager/ontonet/api/collector/UnmodifiableOntologyCollectorException.java | nikosnikolaidis/stanbol | 2fcf471b467fb84e59491f4c54ba0a95924ab04a | [
"Apache-2.0"
] | 55 | 2015-01-24T12:50:00.000Z | 2021-11-10T19:27:16.000Z | ontologymanager/generic/servicesapi/src/main/java/org/apache/stanbol/ontologymanager/ontonet/api/collector/UnmodifiableOntologyCollectorException.java | fogbeam/semantic-objects | 2fcf471b467fb84e59491f4c54ba0a95924ab04a | [
"Apache-2.0"
] | 2 | 2015-11-26T15:30:34.000Z | 2019-11-07T17:50:37.000Z | ontologymanager/generic/servicesapi/src/main/java/org/apache/stanbol/ontologymanager/ontonet/api/collector/UnmodifiableOntologyCollectorException.java | fogbeam/semantic-objects | 2fcf471b467fb84e59491f4c54ba0a95924ab04a | [
"Apache-2.0"
] | 76 | 2015-02-09T09:53:49.000Z | 2022-01-31T12:11:59.000Z | 37.28125 | 100 | 0.761106 | 8,364 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.stanbol.ontologymanager.ontonet.api.collector;
@Deprecated
public class UnmodifiableOntologyCollectorException extends OntologyCollectorModificationException {
/**
*
*/
private static final long serialVersionUID = 18384908686644080L;
public UnmodifiableOntologyCollectorException(OntologyCollector collector) {
super(collector);
}
}
|
3e13c33c228a68cbd347dc8bd54d59c911546e8b | 1,450 | java | Java | eventmesh-spi/src/main/java/org/apache/eventmesh/spi/loader/ExtensionClassLoader.java | horoc/incubator-eventmesh | 02deb6224df1620c5a302947ec41dda6230cc7aa | [
"Apache-2.0"
] | 337 | 2021-04-19T04:05:58.000Z | 2022-03-31T02:43:42.000Z | eventmesh-spi/src/main/java/org/apache/eventmesh/spi/loader/ExtensionClassLoader.java | horoc/incubator-eventmesh | 02deb6224df1620c5a302947ec41dda6230cc7aa | [
"Apache-2.0"
] | 383 | 2021-04-15T06:26:01.000Z | 2022-03-31T12:44:39.000Z | eventmesh-spi/src/main/java/org/apache/eventmesh/spi/loader/ExtensionClassLoader.java | horoc/incubator-eventmesh | 02deb6224df1620c5a302947ec41dda6230cc7aa | [
"Apache-2.0"
] | 122 | 2021-04-15T04:05:16.000Z | 2022-03-24T08:14:11.000Z | 35.365854 | 103 | 0.711034 | 8,365 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eventmesh.spi.loader;
import java.util.Map;
/**
* Load extension class
* <ul>
* <li>{@link MetaInfExtensionClassLoader}</li>
* <li>{@link JarExtensionClassLoader}</li>
* </ul>
*/
public interface ExtensionClassLoader {
/**
* load extension class
*
* @param extensionType extension type class
* @param extensionInstanceName extension instance name
* @param <T> extension type
* @return extension instance name to extension instance class
*/
<T> Map<String, Class<?>> loadExtensionClass(Class<T> extensionType, String extensionInstanceName);
}
|
3e13c357bd461b1b5a3bfb89ebe92abe0b54fc3e | 694 | java | Java | exercicios/src/streams/Mapeamento.java | josivantarcio/PassaTempoCod3r | 8815cac4af485540d57bac7381c8388da2475c41 | [
"MIT"
] | 1 | 2022-02-09T20:12:35.000Z | 2022-02-09T20:12:35.000Z | exercicios/src/streams/Mapeamento.java | josivantarcio/PassaTempoCod3r | 8815cac4af485540d57bac7381c8388da2475c41 | [
"MIT"
] | null | null | null | exercicios/src/streams/Mapeamento.java | josivantarcio/PassaTempoCod3r | 8815cac4af485540d57bac7381c8388da2475c41 | [
"MIT"
] | null | null | null | 31.545455 | 119 | 0.723343 | 8,366 | package streams;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public class Mapeamento {
public final static UnaryOperator<String> maiusculo = m -> m.toUpperCase();
public final static UnaryOperator<String> primeiraLetra = pl -> "" + pl.charAt(0);
public final static UnaryOperator<String> grito = g -> g + "!!! ";
public final static Consumer<Object> print = System.out::println;
public final static Predicate<Aluno> nota = n -> (n.getValue() > 7);
public final static Function<Aluno, String> congratulation = a -> ("Congratulation " + a.getName() + ", you passed!");
}
|
3e13c38cde1b3c29cd4718abdc486b11b68eb947 | 1,771 | java | Java | hummer-simple/hummer-simple-dubbo-client/src/main/java/com/hummer/simple/dubbo/client/DubboConsumer.java | hummer-team/hummer-framework | 0740091b02b95f16f8177a8d0635e757359402af | [
"MIT"
] | 3 | 2020-11-16T12:01:13.000Z | 2021-02-08T15:20:51.000Z | hummer-simple/hummer-simple-dubbo-client/src/main/java/com/hummer/simple/dubbo/client/DubboConsumer.java | hummer-team/hummer-framework | 0740091b02b95f16f8177a8d0635e757359402af | [
"MIT"
] | 10 | 2020-07-25T05:31:54.000Z | 2022-03-15T04:11:59.000Z | hummer-simple/hummer-simple-dubbo-client/src/main/java/com/hummer/simple/dubbo/client/DubboConsumer.java | hummer-team/hummer-framework | 0740091b02b95f16f8177a8d0635e757359402af | [
"MIT"
] | 4 | 2021-09-19T14:00:48.000Z | 2022-01-19T05:24:51.000Z | 36.9375 | 81 | 0.746193 | 8,367 | /*
* Copyright (c) 2019-2021 LiGuo <ychag@example.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.hummer.simple.dubbo.client;
import com.google.common.collect.Maps;
import comm.hummer.simple.common.facade.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class DubboConsumer {
@Autowired
private HelloService helloService;
public String hello() {
Map<String, Object> map = Maps.newConcurrentMap();
map.put("AA", System.currentTimeMillis());
return helloService.save(map);
}
public Integer add(int a,int b) {
return helloService.add(a, b);
}
}
|
3e13c3e7e78accb248e45f902c43dde2c1534eb4 | 22,956 | java | Java | framework/src/main/java/org/apache/felix/framework/util/WeakZipFileFactory.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 73 | 2020-02-28T19:50:03.000Z | 2022-03-31T14:40:18.000Z | framework/src/main/java/org/apache/felix/framework/util/WeakZipFileFactory.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 50 | 2020-03-02T10:53:06.000Z | 2022-03-25T13:23:51.000Z | framework/src/main/java/org/apache/felix/framework/util/WeakZipFileFactory.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 97 | 2020-03-02T10:40:18.000Z | 2022-03-25T01:13:32.000Z | 31.105691 | 96 | 0.439624 | 8,368 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.framework.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* This class implements a factory for creating weak zip files, which behave
* mostly like a ZipFile, but can be weakly closed to limit the number of
* open files.
*/
public class WeakZipFileFactory
{
private static final int WEAKLY_CLOSED = 0;
private static final int OPEN = 1;
private static final int CLOSED = 2;
private static final SecureAction m_secureAction = new SecureAction();
private final List<WeakZipFile> m_zipFiles = new ArrayList<WeakZipFile>();
private final List<WeakZipFile> m_openFiles = new ArrayList<WeakZipFile>();
private final Lock m_globalMutex = new ReentrantLock();
private final int m_limit;
/**
* Constructs a weak zip file factory with the specified file limit. A limit
* of zero signifies no limit.
* @param limit maximum number of open zip files at any given time.
*/
public WeakZipFileFactory(int limit)
{
if (limit < 0)
{
throw new IllegalArgumentException("Limit must be non-negative.");
}
m_limit = limit;
}
/**
* Factory method used to create weak zip files.
* @param file the target zip file.
* @return the created weak zip file.
* @throws IOException if the zip file could not be opened.
*/
public WeakZipFile create(File file) throws IOException
{
WeakZipFile wzf = new WeakZipFile(file);
if (m_limit > 0)
{
m_globalMutex.lock();
try
{
m_zipFiles.add(wzf);
m_openFiles.add(wzf);
if (m_openFiles.size() > m_limit)
{
WeakZipFile candidate = m_openFiles.get(0);
for (WeakZipFile tmp : m_openFiles)
{
if (candidate.m_timestamp > tmp.m_timestamp)
{
candidate = tmp;
}
}
candidate._closeWeakly();
}
}
finally
{
m_globalMutex.unlock();
}
}
return wzf;
}
/**
* Only used for testing.
* @return unclosed weak zip files.
**/
List<WeakZipFile> getZipZiles()
{
m_globalMutex.lock();
try
{
return m_zipFiles;
}
finally
{
m_globalMutex.unlock();
}
}
/**
* Only used for testing.
* @return open weak zip files.
**/
List<WeakZipFile> getOpenZipZiles()
{
m_globalMutex.lock();
try
{
return m_openFiles;
}
finally
{
m_globalMutex.unlock();
}
}
/**
* This class wraps a ZipFile to making it possible to weakly close it;
* this means the underlying zip file will be automatically reopened on demand
* if anyone tries to use it.
*/
public class WeakZipFile
{
private final File m_file;
private final Lock m_localMutex = new ReentrantLock(false);
private volatile ZipFile m_zipFile;
private volatile int m_status = OPEN;
private volatile long m_timestamp;
private volatile SoftReference<LinkedHashMap<String, ZipEntry>> m_entries;
/**
* Constructor is private since instances need to be centrally
* managed.
* @param file the target zip file.
* @throws IOException if the zip file could not be opened.
*/
private WeakZipFile(File file) throws IOException
{
m_file = file;
m_zipFile = m_secureAction.openZipFile(m_file);
m_timestamp = System.currentTimeMillis();
}
/**
* Returns the specified entry from the zip file.
* @param name the name of the entry to return.
* @return the zip entry associated with the specified name or null
* if it does not exist.
*/
public ZipEntry getEntry(String name)
{
ensureZipFileIsOpen();
try
{
LinkedHashMap<String, ZipEntry> entries = getEntries(false);
ZipEntry ze;
if (entries != null)
{
ze = entries.get(name);
if (ze == null)
{
ze = entries.get(name + "/");
}
}
else
{
ze = m_zipFile.getEntry(name);
}
if ((ze != null) && (ze.getSize() == 0) && !ze.isDirectory())
{
//The attempts to fix an apparent bug in the JVM in versions
// 1.4.2 and lower where directory entries in ZIP/JAR files are
// not correctly identified.
ZipEntry dirEntry = m_zipFile.getEntry(name + '/');
if (dirEntry != null)
{
ze = dirEntry;
}
}
return ze;
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
/**
* Returns an enumeration of zip entries from the zip file.
* @return an enumeration of zip entries.
*/
public Enumeration<ZipEntry> entries()
{
ensureZipFileIsOpen();
try
{
LinkedHashMap<String, ZipEntry> entries = getEntries(true);
return Collections.enumeration(entries.values());
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
public Enumeration<String> names()
{
ensureZipFileIsOpen();
try
{
LinkedHashMap<String, ZipEntry> entries = getEntries(true);
return Collections.enumeration(entries.keySet());
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
private LinkedHashMap<String, ZipEntry> getEntries(boolean create)
{
LinkedHashMap<String, ZipEntry> entries = null;
if (m_entries != null)
{
entries = m_entries.get();
}
if (entries == null && create)
{
synchronized (m_zipFile)
{
if (m_entries != null)
{
entries = m_entries.get();
}
if (entries == null)
{
// We need to suck in all of the entries since the zip
// file may get weakly closed during iteration. Technically,
// this may not be 100% correct either since if the zip file
// gets weakly closed and reopened, then the zip entries
// will be from a different zip file. It is not clear if this
// will cause any issues.
Enumeration<? extends ZipEntry> e = m_zipFile.entries();
entries = new LinkedHashMap<String, ZipEntry>();
while (e.hasMoreElements())
{
ZipEntry entry = e.nextElement();
entries.put(entry.getName(), entry);
}
m_entries = new SoftReference<LinkedHashMap<String, ZipEntry>>(entries);
}
}
}
return entries;
}
/**
* Returns an input stream for the specified zip entry.
* @param ze the zip entry whose input stream is to be retrieved.
* @return an input stream to the zip entry.
* @throws IOException if the input stream cannot be opened.
*/
public InputStream getInputStream(ZipEntry ze) throws IOException
{
ensureZipFileIsOpen();
try
{
InputStream is = m_zipFile.getInputStream(ze);
return m_limit == 0 ? is : new WeakZipInputStream(ze.getName(), is);
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
/**
* Weakly closes the zip file, which means that it will be reopened
* if anyone tries to use it again.
*/
void closeWeakly()
{
m_globalMutex.lock();
try
{
_closeWeakly();
}
finally
{
m_globalMutex.unlock();
}
}
/**
* This method is used internally to weakly close a zip file. It should
* only be called when already holding the global lock, otherwise use
* closeWeakly().
*/
private void _closeWeakly()
{
m_localMutex.lock();
try
{
if (m_status == OPEN)
{
try
{
m_status = WEAKLY_CLOSED;
if (m_zipFile != null)
{
m_zipFile.close();
m_zipFile = null;
}
m_openFiles.remove(this);
}
catch (IOException ex)
{
__close();
}
}
}
finally
{
m_localMutex.unlock();
}
}
/**
* This method permanently closes the zip file.
* @throws IOException if any error occurs while trying to close the
* zip file.
*/
public void close() throws IOException
{
if (m_limit > 0)
{
m_globalMutex.lock();
m_localMutex.lock();
}
try
{
ZipFile tmp = m_zipFile;
__close();
if (tmp != null)
{
tmp.close();
}
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
m_globalMutex.unlock();
}
}
}
/**
* This internal method is used to clear the zip file from the data
* structures and reset its state. It should only be called when
* holding the global and local mutexes.
*/
private void __close()
{
m_status = CLOSED;
m_zipFile = null;
m_zipFiles.remove(this);
m_openFiles.remove(this);
}
/**
* This method ensures that the zip file associated with this
* weak zip file instance is actually open and acquires the
* local weak zip file mutex. If the underlying zip file is closed,
* then the local mutex is released and an IllegalStateException is
* thrown. If the zip file is weakly closed, then it is reopened.
* If the zip file is already opened, then no additional action is
* necessary. If this method does not throw an exception, then
* the end result is the zip file member field is non-null and the
* local mutex has been acquired.
*/
private void ensureZipFileIsOpen()
{
if (m_limit == 0)
{
return;
}
// Get mutex for zip file.
m_localMutex.lock();
// If zip file is closed, then just return null.
if (m_status == CLOSED)
{
m_localMutex.unlock();
throw new IllegalStateException("Zip file is closed: " + m_file);
}
// If zip file is weakly closed, we need to reopen it,
// but we have to release the zip mutex to acquire the
// global mutex, then reacquire the zip mutex. This
// ensures that the global mutex is always acquired
// before any local mutex to avoid deadlocks.
IOException cause = null;
if (m_status == WEAKLY_CLOSED)
{
m_localMutex.unlock();
m_globalMutex.lock();
m_localMutex.lock();
// Double check status since it may have changed.
if (m_status == CLOSED)
{
m_localMutex.unlock();
m_globalMutex.unlock();
throw new IllegalStateException("Zip file is closed: " + m_file);
}
else if (m_status == WEAKLY_CLOSED)
{
try
{
__reopenZipFile();
}
catch (IOException ex)
{
cause = ex;
}
}
// Release the global mutex, since it should no longer be necessary.
m_globalMutex.unlock();
}
// It is possible that reopening the zip file failed, so we check
// for that case and throw an exception.
if (m_zipFile == null)
{
m_localMutex.unlock();
IllegalStateException ise =
new IllegalStateException("Zip file is closed: " + m_file);
if (cause != null)
{
ise.initCause(cause);
}
throw ise;
}
}
/**
* Thie internal method is used to reopen a weakly closed zip file.
* It makes a best effort, but may fail and leave the zip file member
* field null. Any failure reopening a zip file results in it being
* permanently closed. This method should only be invoked when holding
* the global and local mutexes.
*/
private void __reopenZipFile() throws IOException
{
if (m_status == WEAKLY_CLOSED)
{
try
{
m_zipFile = m_secureAction.openZipFile(m_file);
m_status = OPEN;
m_timestamp = System.currentTimeMillis();
}
catch (IOException ex)
{
__close();
throw ex;
}
if (m_zipFile != null)
{
m_openFiles.add(this);
if (m_openFiles.size() > m_limit)
{
WeakZipFile candidate = m_openFiles.get(0);
for (WeakZipFile tmp : m_openFiles)
{
if (candidate.m_timestamp > tmp.m_timestamp)
{
candidate = tmp;
}
}
candidate._closeWeakly();
}
}
}
}
/**
* This is an InputStream wrapper that will properly reopen the underlying
* zip file if it is weakly closed and create the underlying input stream.
*/
class WeakZipInputStream extends InputStream
{
private final String m_entryName;
private volatile InputStream m_is;
private volatile int m_currentPos = 0;
private volatile ZipFile m_zipFileSnapshot;
WeakZipInputStream(String entryName, InputStream is)
{
m_entryName = entryName;
m_is = is;
m_zipFileSnapshot = m_zipFile;
}
/**
* This internal method ensures that the zip file is open and that
* the underlying input stream is valid. Upon successful completion,
* the underlying input stream will be valid and the local mutex
* will be held.
* @throws IOException if the was an error handling the input stream.
*/
private void ensureInputStreamIsValid() throws IOException
{
if (m_limit == 0)
{
return;
}
ensureZipFileIsOpen();
// If the underlying zip file changed, then we need
// to get the input stream again.
if (m_zipFileSnapshot != m_zipFile)
{
m_zipFileSnapshot = m_zipFile;
if (m_is != null)
{
try
{
m_is.close();
}
catch (Exception ex)
{
// Not much we can do.
}
}
try
{
m_is = m_zipFile.getInputStream(m_zipFile.getEntry(m_entryName));
m_is.skip(m_currentPos);
}
catch (IOException ex)
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
throw ex;
}
}
}
@Override
public int available() throws IOException
{
ensureInputStreamIsValid();
try
{
return m_is.available();
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
@Override
public void close() throws IOException
{
ensureInputStreamIsValid();
try
{
InputStream is = m_is;
m_is = null;
if (is != null)
{
is.close();
}
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
public int read() throws IOException
{
ensureInputStreamIsValid();
try
{
int len = m_is.read();
if (len > 0)
{
m_currentPos++;
}
return len;
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
@Override
public int read(byte[] bytes) throws IOException
{
ensureInputStreamIsValid();
try
{
int len = m_is.read(bytes);
if (len > 0)
{
m_currentPos += len;
}
return len;
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
@Override
public int read(byte[] bytes, int i, int i1) throws IOException
{
ensureInputStreamIsValid();
try
{
int len = m_is.read(bytes, i, i1);
if (len > 0)
{
m_currentPos += len;
}
return len;
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
@Override
public long skip(long l) throws IOException
{
ensureInputStreamIsValid();
try
{
long len = m_is.skip(l);
if (len > 0)
{
m_currentPos += len;
}
return len;
}
finally
{
if (m_limit > 0)
{
m_localMutex.unlock();
}
}
}
}
}
}
|
3e13c4edd64101befa10ac2b181ba697e51a4ad7 | 4,540 | java | Java | agtms-parent/agtms-core/src/main/java/net/saisimon/agtms/core/util/AuthUtils.java | Saisimon/AGTMS | 5ffecd2398cf1927214794447a8dc529732e0890 | [
"MIT"
] | 2 | 2020-04-07T07:01:53.000Z | 2021-09-26T02:48:28.000Z | agtms-parent/agtms-core/src/main/java/net/saisimon/agtms/core/util/AuthUtils.java | Saisimon/AGTMS | 5ffecd2398cf1927214794447a8dc529732e0890 | [
"MIT"
] | 21 | 2020-06-06T13:32:04.000Z | 2022-02-26T10:00:23.000Z | agtms-parent/agtms-core/src/main/java/net/saisimon/agtms/core/util/AuthUtils.java | Saisimon/AGTMS | 5ffecd2398cf1927214794447a8dc529732e0890 | [
"MIT"
] | null | null | null | 24.808743 | 139 | 0.68304 | 8,369 | package net.saisimon.agtms.core.util;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import cn.hutool.core.util.RandomUtil;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
/**
* 认证相关工具类
*
* @author saisimon
*
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class AuthUtils {
private static final long MAX_TOKEN_TIMEOUT = 30 * 60 * 1000;
public static final String AUTHORIZE_TOKEN = "X-TOKEN";
public static final String AUTHORIZE_UID = "X-UID";
/**
* 创建 Token,去掉“-”的UUID字符串
*
* @return Token
*/
public static String createToken() {
String uuid = UUID.randomUUID().toString();
return uuid.replaceAll("\\-", "");
}
/**
* 获取过期时间(当前时间 + 30分钟)
* 单位:ms
*
* @return
*/
public static long getExpireTime() {
return System.currentTimeMillis() + MAX_TOKEN_TIMEOUT;
}
/**
* 获取当前线程的请求中的用户ID
*
* @return 用户ID
*/
public static Long getUid() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return null;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
if (request == null) {
return null;
}
return getUid(request);
}
/**
* 获取请求中的用户ID
*
* @param request HTTP 请求
* @return 用户ID
*/
public static Long getUid(HttpServletRequest request) {
String uid = request.getHeader(AUTHORIZE_UID);
if (SystemUtils.isBlank(uid)) {
uid = request.getParameter(AUTHORIZE_UID);
}
if (SystemUtils.isBlank(uid)) {
return null;
}
try {
return Long.valueOf(uid);
} catch (NumberFormatException e) {
return null;
}
}
/**
* 获取当前线程的请求中的 Token
*
* @return Token
*/
public static String getToken() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return null;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
if (request == null) {
return null;
}
return getToken(request);
}
/**
* 获取请求中的 Token
*
* @param request HTTP 请求
* @return Token
*/
public static String getToken(HttpServletRequest request) {
String token = request.getHeader(AUTHORIZE_TOKEN);
if (SystemUtils.isBlank(token)) {
token = request.getParameter(AUTHORIZE_TOKEN);
}
return token;
}
/**
* 创建10位随机盐
*
* @return 随机盐
*/
public static String createSalt() {
return RandomUtil.randomString(10);
}
/**
* 加盐的 sha-256 摘要
*
* @param password 待摘要字符串
* @param salt 随机盐
* @return 摘要
*/
public static String hmac(String password, String salt) {
return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, salt).hmacHex(password).toUpperCase();
}
/**
* AES 加密
*
* @param text
* @param key
* @return
*/
public static String aesEncrypt(String text, String key) throws Exception {
if (text == null || key == null) {
return text;
}
Cipher cipher = buildAESCipher(Cipher.ENCRYPT_MODE, key);
return Base64.encodeBase64String(cipher.doFinal(text.getBytes("UTF-8")));
}
/**
* AES 解密
*
* @param ciphertext
* @param key
* @return
*/
public static String aesDecrypt(String ciphertext, String key) throws Exception {
if (ciphertext == null || key == null) {
return ciphertext;
}
Cipher cipher = buildAESCipher(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.decodeBase64(ciphertext)), "UTF-8");
}
private static Cipher buildAESCipher(int mode, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
Cipher result = Cipher.getInstance("AES");
result.init(mode, new SecretKeySpec(DigestUtils.md5(key), "AES"));
return result;
}
}
|
3e13c506c088a83ed955e57d73ba3759a3c4cd62 | 1,290 | java | Java | src/main/java/com/igorkhromov/portsadapters/config/KafkaProducerConfig.java | xrom888/ports-adapters | 7f2df8f25fa5ac1cb395f82f5936f4def0de3393 | [
"MIT"
] | null | null | null | src/main/java/com/igorkhromov/portsadapters/config/KafkaProducerConfig.java | xrom888/ports-adapters | 7f2df8f25fa5ac1cb395f82f5936f4def0de3393 | [
"MIT"
] | null | null | null | src/main/java/com/igorkhromov/portsadapters/config/KafkaProducerConfig.java | xrom888/ports-adapters | 7f2df8f25fa5ac1cb395f82f5936f4def0de3393 | [
"MIT"
] | null | null | null | 36.857143 | 94 | 0.786822 | 8,370 | package com.igorkhromov.portsadapters.config;
import akka.serialization.StringSerializer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import java.util.HashMap;
import java.util.Map;
//@Configuration
public class KafkaProducerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Bean
public ProducerFactory<String, String> producerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}
|
3e13c59ed72a1cd83b6b9b5334f260ee191c2147 | 797 | java | Java | src/main/test/CasosDeUsoSem2/CasoDeUso1Test.java | SeleneMartinez/Algo3_AlgoThieft | 10f79be7cc1c8adf6aa0dba5baf37e206aaed37d | [
"MIT"
] | null | null | null | src/main/test/CasosDeUsoSem2/CasoDeUso1Test.java | SeleneMartinez/Algo3_AlgoThieft | 10f79be7cc1c8adf6aa0dba5baf37e206aaed37d | [
"MIT"
] | 13 | 2021-12-02T02:09:35.000Z | 2021-12-10T18:03:53.000Z | src/main/test/CasosDeUsoSem2/CasoDeUso1Test.java | SeleneMartinez/Algo3_AlgoThief | 10f79be7cc1c8adf6aa0dba5baf37e206aaed37d | [
"MIT"
] | null | null | null | 33.208333 | 73 | 0.676286 | 8,371 | package CasosDeUsoSem2;
import edu.fiuba.algo3.modelo.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CasoDeUso1Test {
@Test
public void detectiveSufreHeridaDeCuchilloYdetectiveDuerme() {
// String respuestaEsperada = "Matón atacó al policia";
// Integer horaEsperada = 10;
// String nombrePolicia = "PoliNovato";
// Policia novato = new Policia(nombrePolicia);
// Cuchillo cuchillo = new Cuchillo();
// Maton maton = new Maton(cuchillo);
// Amenaza respuesta = (Amenaza) maton.atacar(novato);
// novato.dormir();
// assertEquals(respuestaEsperada, respuesta.obtenerRespuesta());
// assertEquals(horaEsperada, novato.obtenerHora());
}
} |
3e13c5b905dd7321a0f3be2659887eb5ec3c52b4 | 1,916 | java | Java | server/src/main/java/org/elasticsearch/action/admin/indices/dangling/find/NodeFindDanglingIndexResponse.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | server/src/main/java/org/elasticsearch/action/admin/indices/dangling/find/NodeFindDanglingIndexResponse.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | server/src/main/java/org/elasticsearch/action/admin/indices/dangling/find/NodeFindDanglingIndexResponse.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | 36.846154 | 101 | 0.752088 | 8,372 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.admin.indices.dangling.find;
import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import java.io.IOException;
import java.util.List;
/**
* Used when querying every node in the cluster for a specific dangling index.
*/
public class NodeFindDanglingIndexResponse extends BaseNodeResponse {
/**
* A node could report several dangling indices. This class will contain them all.
* A single node could even multiple different index versions for the same index
* UUID if the situation is really crazy, though perhaps this is more likely
* when collating responses from different nodes.
*/
private final List<IndexMetadata> danglingIndexInfo;
public List<IndexMetadata> getDanglingIndexInfo() {
return this.danglingIndexInfo;
}
public NodeFindDanglingIndexResponse(DiscoveryNode node, List<IndexMetadata> danglingIndexInfo) {
super(node);
this.danglingIndexInfo = danglingIndexInfo;
}
protected NodeFindDanglingIndexResponse(StreamInput in) throws IOException {
super(in);
this.danglingIndexInfo = in.readList(IndexMetadata::readFrom);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeList(this.danglingIndexInfo);
}
}
|
3e13c6c6d69bee0d1b7ed5ad5306256d8d2619ff | 5,465 | java | Java | src/main/java/be/cytomine/client/models/Property.java | danyfel80/Cytomine-java-client | 518662e880063ecd9981d3358abc5881029fc91d | [
"Apache-2.0"
] | 13 | 2015-04-17T06:33:31.000Z | 2021-04-30T18:30:12.000Z | src/main/java/be/cytomine/client/models/Property.java | danyfel80/Cytomine-java-client | 518662e880063ecd9981d3358abc5881029fc91d | [
"Apache-2.0"
] | 17 | 2017-12-27T15:15:02.000Z | 2022-01-04T16:52:23.000Z | src/main/java/be/cytomine/client/models/Property.java | danyfel80/Cytomine-java-client | 518662e880063ecd9981d3358abc5881029fc91d | [
"Apache-2.0"
] | 14 | 2015-04-22T09:03:42.000Z | 2022-02-14T18:28:42.000Z | 35.718954 | 99 | 0.587923 | 8,373 | package be.cytomine.client.models;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import be.cytomine.client.Cytomine;
import be.cytomine.client.CytomineConnection;
import be.cytomine.client.CytomineException;
import org.json.simple.JSONObject;
import java.util.Map;
public class Property extends Model<Property> {
public Property() {}
public Property(Model model) {
this(model, null, null);
}
public Property(Model model, String key, String value) {
this(model.getClass().getSimpleName().toLowerCase(),model.getId(), key, value);
}
public Property(String domain, Long idDomain){
this(domain, idDomain, null);
}
public Property(String domain, Long idDomain, String key) {
this(domain, idDomain, key, null);
}
public Property(String domain, Long idDomain, String key, String value) {
addFilter(domain,idDomain.toString());
addFilter("key",key);
set("key", key);
set("value", value);
}
@Override
public Property fetch(Long id) throws CytomineException {
return this.fetch(Cytomine.getInstance().getDefaultCytomineConnection(),id);
}
public Property fetch(String id) throws CytomineException {
return this.fetch(Cytomine.getInstance().getDefaultCytomineConnection(),id);
}
@Override
public Property fetch(CytomineConnection connection, Long id) throws CytomineException {
throw new CytomineException(400,"Cannot fetch property with an id, fetch it with its key");
}
public Property fetch(CytomineConnection connection, String id) throws CytomineException {
this.set("key", id);
addFilter("key",id);
JSONObject json = connection.doGet(this.toURL());
this.setAttr(json);
return this;
}
@Override
public String getJSONResourceURL() {
Long id = getId();
String base = "/api/";
//base += "domain/";
//hack to fit url until refactoring of urls
if(getFilter("key")!=null && get("value") != null) filters.remove("key");
base += getFilterPrefix();
base += getDomainName();
if(id!= null) {
base += "/" + id + ".json?";
} else {
base += ".json?";
}
for (Map.Entry<String, String> param : params.entrySet()) {
base = base + param.getKey() + "=" + param.getValue() + "&";
}
base = base.substring(0, base.length() - 1);
return base;
}
/*public String toURL() {
Long id = (Long) get("id");
Long domainIdent = (Long) get("domainIdent");
String domain = (String) get("domain");
String key = (String) get("key");
if (id != null && domainIdent != null && domain != null) {
return getJSONResourceURL(id, domainIdent, domain);
} else if (domainIdent != null && domain != null && key != null) {
return getJSONResourceURL(domainIdent, domain, key);
} else if (domainIdent != null && domain != null) {
return getJSONResourceURL(domainIdent, domain);
} else {
return getJSONResourceURL();
}
}
public String getJSONResourceURL(Long id, Long domainIdent, String domain) {
String domainFix = domain;
if (domain.contains(".")) {
domainFix = "domain/" + domain;
}
if (params.isEmpty()) {
return "/api/" + domainFix + "/" + domainIdent + "/property/" + id + ".json";
} else {
String base = "/api/" + domainFix + "/" + domainIdent + "/property/" + id + ".json?";
for (Map.Entry<String, String> param : params.entrySet()) {
base = base + param.getKey() + "=" + param.getValue() + "&";
}
base = base.substring(0, base.length() - 1);
return base;
}
}
public String getJSONResourceURL(Long domainIdent, String domain) {
String domainFix = domain;
if (domain.contains(".")) {
domainFix = "domain/" + domain;
}
if (params.isEmpty()) {
return "/api/" + domainFix + "/" + domainIdent + "/property.json";
} else {
String base = "/api/" + domainFix + "/" + domainIdent + "/property.json?";
for (Map.Entry<String, String> param : params.entrySet()) {
base = base + param.getKey() + "=" + param.getValue() + "&";
}
base = base.substring(0, base.length() - 1);
return base;
}
}
public String getJSONResourceURL(Long domainIdent, String domain, String key) {
String domainFix = domain;
if (domain.contains(".")) {
domainFix = "domain/" + domain;
}
String base = "/api/" + domainFix + "/" + domainIdent + "/key/"+key+"/property.json";
return base;
}*/
}
|
3e13c73535ee939a7bcbdeff7be2590242b3c0cc | 2,333 | java | Java | src/repositorios/RepositorioFuncionariosArray.java | Ramomjcs/Projeto---IP | 8b1bc5d0cc6e79b3a7a19fe58eb918d02b36f532 | [
"Apache-2.0"
] | 1 | 2020-10-17T14:01:27.000Z | 2020-10-17T14:01:27.000Z | src/repositorios/RepositorioFuncionariosArray.java | Ramomjcs/ProjetoIP | 8b1bc5d0cc6e79b3a7a19fe58eb918d02b36f532 | [
"Apache-2.0"
] | null | null | null | src/repositorios/RepositorioFuncionariosArray.java | Ramomjcs/ProjetoIP | 8b1bc5d0cc6e79b3a7a19fe58eb918d02b36f532 | [
"Apache-2.0"
] | null | null | null | 29.1625 | 96 | 0.701672 | 8,374 | package repositorios;
import basicas.Funcionario;
import excecoes.FuncionarioNaoEncontradoException;
import excecoes.RepositorioFuncionariosCheioException;
import interfaces.RepositorioFuncionarios;
public class RepositorioFuncionariosArray implements RepositorioFuncionarios {
private Funcionario[] funcionarios = new Funcionario[50];
public void inserir(Funcionario funcionario) throws RepositorioFuncionariosCheioException {
boolean cheio = true;
for (int i = 0; i < funcionarios.length && cheio; i++) {
if (funcionarios[i] == null) {
funcionarios[i] = funcionario;
cheio = false;
}
}
if (cheio) {
throw new RepositorioFuncionariosCheioException();
}
}
public Funcionario procurar(String cpf) throws FuncionarioNaoEncontradoException {
boolean achou = false;
Funcionario procurado = null;
for (int i = 0; i < funcionarios.length && !achou; i++) {
if (funcionarios[i] != null && funcionarios[i].getCodigo().equals(cpf)) {
procurado = funcionarios[i];
achou = true;
}
}
if (!achou) {
throw new FuncionarioNaoEncontradoException();
}
return procurado;
}
public void atualizar(Funcionario funcionario) throws FuncionarioNaoEncontradoException {
boolean achou = false;
for (int i = 0; i < funcionarios.length && !achou; i++) {
if (funcionarios[i] != null && funcionarios[i].getCodigo().equals(funcionario.getCodigo())) {
this.funcionarios[i].setNome(funcionario.getNome());
this.funcionarios[i].setSalario(funcionario.getSalario());
this.funcionarios[i].setFuncao(funcionario.getFuncao());
this.funcionarios[i].setSalario(funcionario.getSalario());
achou = true;
}
}
if (!achou) {
throw new FuncionarioNaoEncontradoException();
}
}
public void remover(String cpf) throws FuncionarioNaoEncontradoException {
boolean achou = false;
for (int i = 0; i < funcionarios.length && !achou; i++) {
if (funcionarios[i] != null && funcionarios[i].getCodigo().equals(cpf)) {
funcionarios[i] = null;
achou = true;
}
}
if (!achou) {
throw new FuncionarioNaoEncontradoException();
}
}
@Override
public boolean existe(String cpf) {
for (int i = 0; i < funcionarios.length; i++) {
if (funcionarios[i] != null && funcionarios[i].getCodigo().equals(cpf)) {
return true;
}
}
return false;
}
}
|
3e13c7b1ee4ca31d3d99459dc6851e6ad296041d | 1,394 | java | Java | haifa-springframework/spring-bean-internal/src/main/java/org/wrj/allspring/version4/hook/BaseModelBeanFactoryPostProcessor.java | wangrenjun12/haifa | d8a5fc2c9380f775551c0fd1e2d9a25bd58eff1b | [
"MIT"
] | null | null | null | haifa-springframework/spring-bean-internal/src/main/java/org/wrj/allspring/version4/hook/BaseModelBeanFactoryPostProcessor.java | wangrenjun12/haifa | d8a5fc2c9380f775551c0fd1e2d9a25bd58eff1b | [
"MIT"
] | 15 | 2020-02-28T01:15:05.000Z | 2021-10-10T00:17:59.000Z | haifa-springframework/spring-bean-internal/src/main/java/org/wrj/allspring/version4/hook/BaseModelBeanFactoryPostProcessor.java | wangrenjun12/haifa | d8a5fc2c9380f775551c0fd1e2d9a25bd58eff1b | [
"MIT"
] | 1 | 2018-05-01T14:15:27.000Z | 2018-05-01T14:15:27.000Z | 41 | 112 | 0.766858 | 8,375 | package org.wrj.allspring.version4.hook;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
/**
* Created by wangrenjun on 2017/3/14.
*/
@Service
public class BaseModelBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("BaseModelBeanFactoryPostProcessor.postProcessBeanFactory");
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
for (String def : beanDefinitionNames) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(def);
MutablePropertyValues mpv = beanDefinition.getPropertyValues();
if (beanDefinition.getBeanClassName().endsWith("Model")) {
beanDefinition.getPropertyValues().add("createTime", new Timestamp(System.currentTimeMillis()));
beanDefinition.getPropertyValues().add("updateTime", new Timestamp(System.currentTimeMillis()));
}
}
}
}
|
3e13c99fff9080082ee0207a77604c04fe0be2e4 | 2,636 | java | Java | spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java | richardhu1991/spring-framework | 1deac11143bbcd9ad67fbdfdea0457ab21b1266e | [
"Apache-2.0"
] | 1 | 2016-03-03T09:03:51.000Z | 2016-03-03T09:03:51.000Z | spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java | richardhu1991/spring-framework | 1deac11143bbcd9ad67fbdfdea0457ab21b1266e | [
"Apache-2.0"
] | null | null | null | spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java | richardhu1991/spring-framework | 1deac11143bbcd9ad67fbdfdea0457ab21b1266e | [
"Apache-2.0"
] | 4 | 2018-02-05T23:49:37.000Z | 2021-08-12T20:14:01.000Z | 35.146667 | 103 | 0.763278 | 8,376 | /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.expression.spel.ast;
import java.math.BigDecimal;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.support.BooleanTypedValue;
import org.springframework.util.NumberUtils;
/**
* Implements the less-than operator.
*
* @author Andy Clement
* @author Giovanni Dall'Oglio Risso
* @since 3.0
*/
public class OpLT extends Operator {
public OpLT(int pos, SpelNodeImpl... operands) {
super("<", pos, operands);
}
@Override
public BooleanTypedValue getValueInternal(ExpressionState state)
throws EvaluationException {
Object left = getLeftOperand().getValueInternal(state).getValue();
Object right = getRightOperand().getValueInternal(state).getValue();
if (left instanceof Number && right instanceof Number) {
Number leftNumber = (Number) left;
Number rightNumber = (Number) right;
if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) {
BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class);
BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
return BooleanTypedValue.forValue(leftBigDecimal.compareTo(rightBigDecimal) < 0);
}
if (leftNumber instanceof Double || rightNumber instanceof Double) {
return BooleanTypedValue.forValue(leftNumber.doubleValue() < rightNumber.doubleValue());
}
if (leftNumber instanceof Float || rightNumber instanceof Float) {
return BooleanTypedValue.forValue(leftNumber.floatValue() < rightNumber.floatValue());
}
if (leftNumber instanceof Long || rightNumber instanceof Long) {
return BooleanTypedValue.forValue(leftNumber.longValue() < rightNumber.longValue());
}
return BooleanTypedValue.forValue(leftNumber.intValue() < rightNumber.intValue());
}
return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) < 0);
}
}
|
3e13c9be6b118ebcc7d7b180d64efbce889a0e7e | 2,704 | java | Java | src/main/java/com/github/ramasct1/aop/proxies/CaptureRequestParamsProxy.java | ramasct1/mm-audit | c47875d01c2a131ba93d129f36272d78c65ef866 | [
"MIT"
] | null | null | null | src/main/java/com/github/ramasct1/aop/proxies/CaptureRequestParamsProxy.java | ramasct1/mm-audit | c47875d01c2a131ba93d129f36272d78c65ef866 | [
"MIT"
] | 2 | 2020-05-21T19:11:28.000Z | 2021-03-19T20:23:37.000Z | src/main/java/com/github/ramasct1/aop/proxies/CaptureRequestParamsProxy.java | ramasct1/mm-audit | c47875d01c2a131ba93d129f36272d78c65ef866 | [
"MIT"
] | null | null | null | 35.578947 | 130 | 0.739275 | 8,377 | package com.github.ramasct1.aop.proxies;
import com.github.ramasct1.aop.annotations.CaptureRequestParams;
import com.github.ramasct1.aop.annotations.ParamField;
import com.github.ramasct1.aop.errors.BadRequestException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* A cross cutting concern implementation for {@link CaptureRequestParams}
*/
@Aspect
@Component
public class CaptureRequestParamsProxy {
private final RequestParamsHolder requestParamsHolder;
@Autowired
public CaptureRequestParamsProxy(final RequestParamsHolder requestParamsHolder) {
this.requestParamsHolder = requestParamsHolder;
}
@Pointcut("@annotation(captureRequestParams)")
public void perform(CaptureRequestParams captureRequestParams) {
}
@Before("perform(captureRequestParams)")
public void interceptRequestParams(JoinPoint joinPoint, CaptureRequestParams captureRequestParams) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
ParamField[] paramNames = captureRequestParams.paramsNames();
Arrays.stream(paramNames).forEach(paramName -> {
Optional<String> value = Optional.ofNullable(request.getHeader(paramName.fieldName()));
if (value.isPresent()) {
requestParamsHolder.setParam(paramName.fieldName(), value.get());
} else if (paramName.required()) {
throw new BadRequestException(String.format("%s is missing and marked as required field", paramName.fieldName()));
}
});
}
@Component
@RequestScope
public static class RequestParamsHolder {
private final Map<String, String> requestParams;
public RequestParamsHolder() {
this.requestParams = new HashMap<>();
}
public Optional<String> getParam(String paramName) {
return Optional.ofNullable(requestParams.get(paramName));
}
public void setParam(String name, String value) {
requestParams.put(name, value);
}
}
}
|
3e13c9d95c53a72caede1dd3909194ab59db7a5b | 2,319 | java | Java | open-sphere-base/core/src/main/java/io/opensphere/core/util/swing/pie/DefaultIconModel.java | smagill/opensphere-desktop | ac18dac63d6496a9f9b96debf2e1d06841f92118 | [
"Apache-2.0"
] | 25 | 2018-01-25T23:01:39.000Z | 2022-02-21T22:24:00.000Z | open-sphere-base/core/src/main/java/io/opensphere/core/util/swing/pie/DefaultIconModel.java | smagill/opensphere-desktop | ac18dac63d6496a9f9b96debf2e1d06841f92118 | [
"Apache-2.0"
] | 71 | 2019-11-22T22:39:25.000Z | 2020-03-30T01:06:30.000Z | open-sphere-base/core/src/main/java/io/opensphere/core/util/swing/pie/DefaultIconModel.java | smagill/opensphere-desktop | ac18dac63d6496a9f9b96debf2e1d06841f92118 | [
"Apache-2.0"
] | 11 | 2018-09-04T09:35:01.000Z | 2021-04-21T14:15:33.000Z | 22.514563 | 104 | 0.65373 | 8,378 | package io.opensphere.core.util.swing.pie;
import java.awt.Image;
import java.util.Collection;
import java.util.Objects;
import io.opensphere.core.util.ChangeSupport;
import io.opensphere.core.util.StrongChangeSupport;
import io.opensphere.core.util.collections.New;
/**
* Default IconModel.
*/
public class DefaultIconModel implements IconModel
{
/** The icon info collection. */
private final Collection<IconInfo> myIconInfos = New.list();
/** The mouse-over icon. */
private IconInfo myMouseOverIcon;
/** The Arcs. */
private final Collection<Arc> myArcs = New.list();
/** The change support. */
private final transient ChangeSupport<ChangeListener> myChangeSupport = new StrongChangeSupport<>();
@Override
public void addArc(Arc arc)
{
myArcs.add(arc);
}
@Override
public void addChangeListener(ChangeListener listener)
{
myChangeSupport.addListener(listener);
}
@Override
public void addIcon(Image icon, float angle, Object userObject)
{
myIconInfos.add(new IconInfo(icon, angle, userObject));
}
@Override
public void clearArcs()
{
myArcs.clear();
}
@Override
public void clearIcons()
{
myIconInfos.clear();
}
@Override
public Collection<Arc> getArcs()
{
return myArcs;
}
@Override
public Collection<IconInfo> getIcons()
{
return New.list(myIconInfos);
}
@Override
public IconInfo getMouseOverIcon()
{
return myMouseOverIcon;
}
@Override
public void removeChangeListener(ChangeListener listener)
{
myChangeSupport.removeListener(listener);
}
@Override
public void setMouseOverIcon(IconInfo iconInfo, Object source)
{
if (!Objects.equals(myMouseOverIcon, iconInfo))
{
myMouseOverIcon = iconInfo;
fireStateChanged(ChangeType.MOUSE_OVER, source);
}
}
/**
* Fires a state change.
*
* @param changeType the change type
* @param source the source of the change
*/
protected void fireStateChanged(final ChangeType changeType, final Object source)
{
myChangeSupport.notifyListeners(listener -> listener.stateChanged(changeType, source));
}
}
|
3e13cb06a959f68b689f18a52d2f0f70a9dc82d1 | 1,692 | java | Java | agentsimulator/src/info/financialecology/finance/abm/model/strategy/TradingStrategy.java | gitwitcho/var-agent-model | 1a2239fce5de429bc62c8b4a1011535c75f278f4 | [
"Apache-2.0"
] | 1 | 2019-09-16T14:46:56.000Z | 2019-09-16T14:46:56.000Z | agentsimulator/src/info/financialecology/finance/abm/model/strategy/TradingStrategy.java | gitwitcho/var-agent-model | 1a2239fce5de429bc62c8b4a1011535c75f278f4 | [
"Apache-2.0"
] | null | null | null | agentsimulator/src/info/financialecology/finance/abm/model/strategy/TradingStrategy.java | gitwitcho/var-agent-model | 1a2239fce5de429bc62c8b4a1011535c75f278f4 | [
"Apache-2.0"
] | null | null | null | 23.597222 | 70 | 0.55621 | 8,379 | /**
* Simple financial systemic risk simulator for Java
* http://code.google.com/p/systemic-risk/
*
* Copyright (c) 2011, 2012
* Gilbert Peffer, CIMNE
* nnheo@example.com
* All rights reserved
*
* This software is open-source under the BSD license; see
* http://code.google.com/p/systemic-risk/wiki/SoftwareLicense
*/
package info.financialecology.finance.abm.model.strategy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import info.financialecology.finance.abm.model.util.TradingPortfolio;
/**
* @author Gilbert Peffer
*
*/
public interface TradingStrategy {
public class Order {
private String secId;
private double order;
public Order() {
this.secId = null;
this.order = 0;
}
/**
* @return the secId
*/
public String getSecId() {
return secId;
}
/**
* @param secId the secId to set
*/
public void setSecId(String secId) {
this.secId = secId;
}
/**
* @return the order
*/
public double getOrder() {
return order;
}
/**
* @param order the order to set
*/
public void setOrder(double order) {
this.order = order;
}
}
public void trade(TradingPortfolio portfolio);
public ArrayList<Order> getOrders();
public String getUniqueId();
public HashSet<String> getSecIds();
// public double getOrder(String secId);
// public String getSecId();
}
|
3e13cc077ae39b88241a533e44360b9a0148838c | 182 | java | Java | src/mainComm/rmw2/functions/TileEntityRenderFunction.java | anatawa12/rtm-mc-wrapper | 8bb37bf09257078385d489990f341696d8dfbace | [
"MIT"
] | null | null | null | src/mainComm/rmw2/functions/TileEntityRenderFunction.java | anatawa12/rtm-mc-wrapper | 8bb37bf09257078385d489990f341696d8dfbace | [
"MIT"
] | 1 | 2020-07-01T12:29:02.000Z | 2020-07-01T12:55:31.000Z | src/mainComm/rmw2/functions/TileEntityRenderFunction.java | fixrtm/rtm-mc-wrapper | 8bb37bf09257078385d489990f341696d8dfbace | [
"MIT"
] | null | null | null | 22.75 | 65 | 0.807692 | 8,380 | package rmw2.functions;
import net.minecraft.tileentity.TileEntity;
public interface TileEntityRenderFunction {
void render(TileEntity entity, int pass, float partialTicks);
}
|
3e13cc7163fb7d07f2822ba26ca77d86296f915c | 6,099 | java | Java | soul-admin/src/test/java/org/dromara/soul/admin/controller/PluginHandleControllerTest.java | onlyonezhongjinhui/soul | 8b824dd75e085b43ad3031c0bfd9f0c3423ed4b7 | [
"Apache-2.0"
] | 3 | 2021-02-19T02:03:03.000Z | 2021-02-26T08:42:58.000Z | soul-admin/src/test/java/org/dromara/soul/admin/controller/PluginHandleControllerTest.java | onlyonezhongjinhui/soul | 8b824dd75e085b43ad3031c0bfd9f0c3423ed4b7 | [
"Apache-2.0"
] | 2 | 2020-12-03T09:05:39.000Z | 2021-01-14T02:16:57.000Z | soul-admin/src/test/java/org/dromara/soul/admin/controller/PluginHandleControllerTest.java | onlyonezhongjinhui/soul | 8b824dd75e085b43ad3031c0bfd9f0c3423ed4b7 | [
"Apache-2.0"
] | 1 | 2021-02-21T02:05:26.000Z | 2021-02-21T02:05:26.000Z | 44.195652 | 109 | 0.705853 | 8,381 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.soul.admin.controller;
import org.dromara.soul.admin.dto.PluginHandleDTO;
import org.dromara.soul.admin.page.CommonPager;
import org.dromara.soul.admin.page.PageParameter;
import org.dromara.soul.admin.query.PluginHandleQuery;
import org.dromara.soul.admin.service.PluginHandleService;
import org.dromara.soul.admin.utils.SoulResultMessage;
import org.dromara.soul.admin.vo.PluginHandleVO;
import org.dromara.soul.common.utils.DateUtils;
import org.dromara.soul.common.utils.GsonUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test case for PluginHandleController.
*
* @author charlesgongC
*/
@RunWith(SpringRunner.class)
public final class PluginHandleControllerTest {
private MockMvc mockMvc;
@InjectMocks
private PluginHandleController pluginHandleController;
@Mock
private PluginHandleService pluginHandleService;
private final PluginHandleVO pluginHandleVO = new PluginHandleVO("1", "2", "3", "label",
1, 1, 1, null, DateUtils.localDateTimeToString(LocalDateTime.now()),
DateUtils.localDateTimeToString(LocalDateTime.now()), new ArrayList<>());
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(pluginHandleController).build();
}
@Test
public void testQueryPluginHandles() throws Exception {
given(this.pluginHandleService.listByPage(new PluginHandleQuery("2", null, new PageParameter(1, 1))))
.willReturn(new CommonPager<>());
this.mockMvc.perform(MockMvcRequestBuilders.get("/plugin-handle/", "1", 1, 1))
.andExpect(status().isOk())
.andReturn();
}
@Test
public void testQueryAllPluginHandlesByPluginId() throws Exception {
given(this.pluginHandleService.list("1", 1)).willReturn(Collections.singletonList(pluginHandleVO));
this.mockMvc.perform(MockMvcRequestBuilders.get("/plugin-handle/all/{pluginId}/{type}", "1", 1))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(SoulResultMessage.QUERY_SUCCESS)))
.andExpect(jsonPath("$.data[0].id", is(pluginHandleVO.getId())))
.andReturn();
}
@Test
public void testDetailRule() throws Exception {
given(this.pluginHandleService.findById("1")).willReturn(pluginHandleVO);
this.mockMvc.perform(MockMvcRequestBuilders.get("/plugin-handle/{id}", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(SoulResultMessage.DETAIL_SUCCESS)))
.andExpect(jsonPath("$.data.id", is(pluginHandleVO.getId())))
.andReturn();
}
@Test
public void testCreatePluginHandle() throws Exception {
PluginHandleDTO pluginHandleDTO = new PluginHandleDTO();
pluginHandleDTO.setId("1");
given(this.pluginHandleService.createOrUpdate(pluginHandleDTO)).willReturn(1);
this.mockMvc.perform(MockMvcRequestBuilders.post("/plugin-handle/")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(pluginHandleDTO)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(SoulResultMessage.CREATE_SUCCESS)))
.andReturn();
}
@Test
public void testUpdatePluginHandle() throws Exception {
PluginHandleDTO pluginHandleDTO = new PluginHandleDTO();
pluginHandleDTO.setId("1");
given(this.pluginHandleService.createOrUpdate(pluginHandleDTO)).willReturn(1);
this.mockMvc.perform(MockMvcRequestBuilders.put("/plugin-handle/{id}", "1")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(pluginHandleDTO)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(SoulResultMessage.UPDATE_SUCCESS)))
.andReturn();
}
@Test
public void testDeletePluginHandles() throws Exception {
given(this.pluginHandleService.deletePluginHandles(Collections.singletonList("1"))).willReturn(1);
this.mockMvc.perform(MockMvcRequestBuilders.delete("/plugin-handle/batch", "1")
.contentType(MediaType.APPLICATION_JSON)
.content(GsonUtils.getInstance().toJson(Collections.singletonList("1"))))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is(SoulResultMessage.DELETE_SUCCESS)))
.andReturn();
}
}
|
3e13ccc24d1a6c25beb5b000745c0aab407f1419 | 3,196 | java | Java | im-base-2/src/main/java/com/xuegao/im/domain/doo/GroupRelation.java | WarriorFromLongAgo/xuegao-im-2 | 7f588e5f67326e03f85f907a171d2aaa7125c9fb | [
"Apache-2.0"
] | null | null | null | im-base-2/src/main/java/com/xuegao/im/domain/doo/GroupRelation.java | WarriorFromLongAgo/xuegao-im-2 | 7f588e5f67326e03f85f907a171d2aaa7125c9fb | [
"Apache-2.0"
] | null | null | null | im-base-2/src/main/java/com/xuegao/im/domain/doo/GroupRelation.java | WarriorFromLongAgo/xuegao-im-2 | 7f588e5f67326e03f85f907a171d2aaa7125c9fb | [
"Apache-2.0"
] | null | null | null | 23.328467 | 56 | 0.618586 | 8,382 | package com.xuegao.im.domain.doo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
/**
* <br/> @PackageName:com.xuegao.xuegaoimbase.domain.doo
* <br/> @ClassName:GroupRelation
* <br/> @Description:
* <br/> @author:xuegao
* <br/> @date:2020/11/20 18:27:31
*/
@ApiModel(value = "群与人的关系表")
@TableName("t_group_relation")
public class GroupRelation implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
@ApiModelProperty(value = "主键")
private Long id;
@TableField("user_id")
@ApiModelProperty(value = "用户id")
private Long userId;
@TableField("group_id")
@ApiModelProperty(value = "群id")
private Long groupId;
@TableField("delete_flag")
@ApiModelProperty(value = "是否删除,0未删除,1已删除")
private Integer deleteFlag;
@TableField("create_id")
@ApiModelProperty(value = "创建人id")
private Long createId;
@TableField("create_time")
@ApiModelProperty(value = "创建时间")
private Date createTime;
@TableField("update_id")
@ApiModelProperty(value = "修改人id")
private Long updateId;
@TableField("update_time")
@ApiModelProperty(value = "修改时间")
private Date updateTime;
public GroupRelation() {
}
public Long getId() {
return id;
}
public Long getUserid() {
return userId;
}
public Long getGroupid() {
return groupId;
}
public Integer getDeleteflag() {
return deleteFlag;
}
public Long getCreateid() {
return createId;
}
public Date getCreatetime() {
return createTime;
}
public Long getUpdateid() {
return updateId;
}
public Date getUpdatetime() {
return updateTime;
}
public void setId(Long id) {
this.id = id;
}
public void setUserid(Long userId) {
this.userId = userId;
}
public void setGroupid(Long groupId) {
this.groupId = groupId;
}
public void setDeleteflag(Integer deleteFlag) {
this.deleteFlag = deleteFlag;
}
public void setCreateid(Long createId) {
this.createId = createId;
}
public void setCreatetime(Date createTime) {
this.createTime = createTime;
}
public void setUpdateid(Long updateId) {
this.updateId = updateId;
}
public void setUpdatetime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "GroupRelation { " +
"id=" + id +
", userId=" + userId +
", groupId=" + groupId +
", deleteFlag=" + deleteFlag +
", createId=" + createId +
", createTime=" + createTime +
", updateId=" + updateId +
", updateTime=" + updateTime +
"}";
}
} |
3e13ccff7a16e3717f0ec6496452576ed3b3c2f6 | 2,614 | java | Java | src/labs/vex/lumen/module/ModuleProcessor.java | phantomteam/lumen | 9f588c5d5d5333b9e90e68529d59c91b6ecc7b60 | [
"Apache-2.0"
] | null | null | null | src/labs/vex/lumen/module/ModuleProcessor.java | phantomteam/lumen | 9f588c5d5d5333b9e90e68529d59c91b6ecc7b60 | [
"Apache-2.0"
] | null | null | null | src/labs/vex/lumen/module/ModuleProcessor.java | phantomteam/lumen | 9f588c5d5d5333b9e90e68529d59c91b6ecc7b60 | [
"Apache-2.0"
] | null | null | null | 39.606061 | 255 | 0.695103 | 8,383 | package labs.vex.lumen.module;
import labs.vex.lumen.Lumen;
import labs.vex.lumen.dexter.EngineException;
import labs.vex.lumen.firefly.ILoader;
import labs.vex.lumen.firefly.exceptions.IllegalFootprintException;
import labs.vex.lumen.dexter.Curiosity;
import labs.vex.lumen.firefly.ConfigurationManager;
import labs.vex.lumen.ion.Ion;
import labs.vex.lumen.ion.IonManager;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
/**
* Class used to process a describer
*
* @author vex | Ciobanu Laurentiu
*/
public class ModuleProcessor {
/**
* Mixed method used to process a descriptor using a loader
*
* @param descriptor input descriptor
* @param loader the loader used for configuration
* @throws IOException Standard IO Exception
* @throws ClassNotFoundException Standard Reflection Exception
* @throws IllegalAccessException Standard Reflection Exception
* @throws NoSuchFieldException Standard Reflection Exception
* @throws IllegalFootprintException Standard Reflection Exception
* @throws InvocationTargetException Standard Reflection Exception
* @throws InstantiationException Standard Reflection Exception
* @throws EngineException Standard Engine Exception
* @author vex | Ciobanu Laurentiu
*/
public static void process(Descriptor descriptor, ILoader loader) throws IOException, ClassNotFoundException, IllegalAccessException, NoSuchFieldException, IllegalFootprintException, InvocationTargetException, InstantiationException, EngineException {
for(Module module: descriptor.modules) {
Map<String, String> include = new HashMap<>();
for(String configurationName: module.configuration){
String path = module.name + "/" + configurationName + ".json";
include.put(configurationName, path);
}
ConfigurationManager manager = loader.load(include);
Lumen.firefly().daemon().load(module.pack, manager);
}
for(Class c: Curiosity.explore(descriptor.root)) {
Lumen.firefly().daemon().handle(c);
}
for(Module module: descriptor.modules) {
for(Class c: Curiosity.explore(descriptor.root + "." + module.pack)) {
Object instance = Lumen.anemoi().handle(c);
if(instance != null && Ion.class.isAssignableFrom(instance.getClass())) {
IonManager.register((Ion) instance);
}
}
}
IonManager.build();
}
}
|
3e13ceb46b56c49d320e5f5cadbe82808fbe792e | 20,829 | java | Java | sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java | veniuscloudpower/azure-sdk-for-java | d5ce3351b625745983fb96b989fe43493e88babe | [
"MIT"
] | 2 | 2021-09-15T15:21:37.000Z | 2022-01-08T06:40:15.000Z | sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java | LarryOsterman/azure-sdk-for-java | 0d4171c3052c4d13a51af72164f64fabbfc0fde5 | [
"MIT"
] | 12 | 2019-07-17T16:18:54.000Z | 2019-07-17T21:30:02.000Z | sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java | LarryOsterman/azure-sdk-for-java | 0d4171c3052c4d13a51af72164f64fabbfc0fde5 | [
"MIT"
] | 1 | 2022-03-29T20:22:47.000Z | 2022-03-29T20:22:47.000Z | 43.758403 | 158 | 0.68227 | 8,384 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.keys;
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceModifiedException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpPipeline;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.SyncPoller;
import com.azure.security.keyvault.keys.models.CreateKeyOptions;
import com.azure.security.keyvault.keys.models.DeletedKey;
import com.azure.security.keyvault.keys.models.KeyProperties;
import com.azure.security.keyvault.keys.models.KeyType;
import com.azure.security.keyvault.keys.models.KeyVaultKey;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.azure.security.keyvault.keys.cryptography.TestHelper.DISPLAY_NAME_WITH_ARGUMENTS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class KeyClientTest extends KeyClientTestBase {
protected KeyClient client;
@Override
protected void beforeTest() {
beforeTestSetup();
}
protected void createKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) {
HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion);
KeyAsyncClient asyncClient = spy(new KeyClientBuilder()
.vaultUrl(getEndpoint())
.pipeline(httpPipeline)
.serviceVersion(serviceVersion)
.buildAsyncClient());
if (interceptorManager.isPlaybackMode()) {
when(asyncClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10));
}
client = new KeyClient(asyncClient);
}
/**
* Tests that a key can be created in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyRunner((expected) -> assertKeyEquals(expected, client.createKey(expected)));
}
/**
* Tests that an RSA key is created.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void createRsaKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
createRsaKeyRunner((expected) -> assertKeyEquals(expected, client.createRsaKey(expected)));
}
/**
* Tests that an attempt to create a key with empty string name throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyEmptyName(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
if (isManagedHsmTest) {
assertRestException(() -> client.createKey("", KeyType.RSA_HSM), HttpResponseException.class,
HttpURLConnection.HTTP_SERVER_ERROR);
} else {
assertRestException(() -> client.createKey("", KeyType.RSA), ResourceModifiedException.class,
HttpURLConnection.HTTP_BAD_REQUEST);
}
}
/**
* Tests that we cannot create keys when key type is null.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyNullType(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
setKeyEmptyValueRunner((key) -> {
assertRestException(() -> client.createKey(key.getName(), key.getKeyType()), ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST);
});
}
/**
* Verifies that an exception is thrown when null key object is passed for creation.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void setKeyNull(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRunnableThrowsException(() -> client.createKey(null), NullPointerException.class);
assertRunnableThrowsException(() -> client.createKey(null), NullPointerException.class);
}
/**
* Tests that a key is able to be updated when it exists.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void updateKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
updateKeyRunner((original, updated) -> {
assertKeyEquals(original, client.createKey(original));
KeyVaultKey keyToUpdate = client.getKey(original.getName());
client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()));
assertKeyEquals(updated, client.getKey(original.getName()));
});
}
/**
* Tests that a key is able to be updated when it is disabled.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void updateDisabledKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
updateDisabledKeyRunner((original, updated) -> {
assertKeyEquals(original, client.createKey(original));
KeyVaultKey keyToUpdate = client.getKey(original.getName());
client.updateKeyProperties(keyToUpdate.getProperties().setExpiresOn(updated.getExpiresOn()));
assertKeyEquals(updated, client.getKey(original.getName()));
});
}
/**
* Tests that an existing key can be retrieved.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getKeyRunner((original) -> {
client.createKey(original);
assertKeyEquals(original, client.getKey(original.getName()));
});
}
/**
* Tests that a specific version of the key can be retrieved.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKeySpecificVersion(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getKeySpecificVersionRunner((key, keyWithNewVal) -> {
KeyVaultKey keyVersionOne = client.createKey(key);
KeyVaultKey keyVersionTwo = client.createKey(keyWithNewVal);
assertKeyEquals(key, client.getKey(keyVersionOne.getName(), keyVersionOne.getProperties().getVersion()));
assertKeyEquals(keyWithNewVal, client.getKey(keyVersionTwo.getName(), keyVersionTwo.getProperties().getVersion()));
});
}
/**
* Tests that an attempt to get a non-existing key throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.getKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that an existing key can be deleted.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void deleteKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
deleteKeyRunner((keyToDelete) -> {
sleepInRecordMode(30000);
assertKeyEquals(keyToDelete, client.createKey(keyToDelete));
SyncPoller<DeletedKey, Void> deletedKeyPoller = client.beginDeleteKey(keyToDelete.getName());
PollResponse<DeletedKey> pollResponse = deletedKeyPoller.poll();
DeletedKey deletedKey = pollResponse.getValue();
// Key is being deleted on server.
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(10000);
pollResponse = deletedKeyPoller.poll();
}
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
assertNotNull(deletedKey.getScheduledPurgeDate());
assertEquals(keyToDelete.getName(), deletedKey.getName());
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void deleteKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.beginDeleteKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that an attempt to retrieve a non existing deleted key throws an error on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.getDeletedKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a deleted key can be recovered on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void recoverDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
recoverDeletedKeyRunner((keyToDeleteAndRecover) -> {
assertKeyEquals(keyToDeleteAndRecover, client.createKey(keyToDeleteAndRecover));
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndRecover.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
assertNotNull(pollResponse.getValue());
SyncPoller<KeyVaultKey, Void> recoverPoller = client.beginRecoverDeletedKey(keyToDeleteAndRecover.getName());
PollResponse<KeyVaultKey> recoverPollResponse = recoverPoller.poll();
KeyVaultKey recoveredKey = recoverPollResponse.getValue();
//
recoverPollResponse = recoverPoller.poll();
while (!recoverPollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
recoverPollResponse = recoverPoller.poll();
}
assertEquals(keyToDeleteAndRecover.getName(), recoveredKey.getName());
assertEquals(keyToDeleteAndRecover.getNotBefore(), recoveredKey.getProperties().getNotBefore());
assertEquals(keyToDeleteAndRecover.getExpiresOn(), recoveredKey.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to recover a non existing deleted key throws an error on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void recoverDeletedKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.beginRecoverDeletedKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a key can be backed up in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void backupKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
backupKeyRunner((keyToBackup) -> {
assertKeyEquals(keyToBackup, client.createKey(keyToBackup));
byte[] backupBytes = (client.backupKey(keyToBackup.getName()));
assertNotNull(backupBytes);
assertTrue(backupBytes.length > 0);
});
}
/**
* Tests that an attempt to backup a non existing key throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void backupKeyNotFound(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
assertRestException(() -> client.backupKey("non-existing"), ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Tests that a key can be backed up in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void restoreKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
restoreKeyRunner((keyToBackupAndRestore) -> {
assertKeyEquals(keyToBackupAndRestore, client.createKey(keyToBackupAndRestore));
byte[] backupBytes = (client.backupKey(keyToBackupAndRestore.getName()));
assertNotNull(backupBytes);
assertTrue(backupBytes.length > 0);
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToBackupAndRestore.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
client.purgeDeletedKey(keyToBackupAndRestore.getName());
pollOnKeyPurge(keyToBackupAndRestore.getName());
sleepInRecordMode(60000);
KeyVaultKey restoredKey = client.restoreKeyBackup(backupBytes);
assertEquals(keyToBackupAndRestore.getName(), restoredKey.getName());
assertEquals(keyToBackupAndRestore.getExpiresOn(), restoredKey.getProperties().getExpiresOn());
});
}
/**
* Tests that an attempt to restore a key from malformed backup bytes throws an error.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void restoreKeyFromMalformedBackup(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
byte[] keyBackupBytes = "non-existing".getBytes();
assertRestException(() -> client.restoreKeyBackup(keyBackupBytes), ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST);
}
/**
* Tests that keys can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
listKeysRunner((keys) -> {
HashMap<String, CreateKeyOptions> keysToList = keys;
for (CreateKeyOptions key : keysToList.values()) {
assertKeyEquals(key, client.createKey(key));
sleepInRecordMode(5000);
}
for (KeyProperties actualKey : client.listPropertiesOfKeys()) {
if (keys.containsKey(actualKey.getName())) {
CreateKeyOptions expectedKey = keys.get(actualKey.getName());
assertEquals(expectedKey.getExpiresOn(), actualKey.getExpiresOn());
assertEquals(expectedKey.getNotBefore(), actualKey.getNotBefore());
keys.remove(actualKey.getName());
}
}
assertEquals(0, keys.size());
});
}
/**
* Tests that a deleted key can be retrieved on a soft-delete enabled vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void getDeletedKey(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
getDeletedKeyRunner((keyToDeleteAndGet) -> {
assertKeyEquals(keyToDeleteAndGet, client.createKey(keyToDeleteAndGet));
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(keyToDeleteAndGet.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
sleepInRecordMode(30000);
DeletedKey deletedKey = client.getDeletedKey(keyToDeleteAndGet.getName());
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
assertNotNull(deletedKey.getScheduledPurgeDate());
assertEquals(keyToDeleteAndGet.getName(), deletedKey.getName());
});
}
/**
* Tests that deleted keys can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listDeletedKeys(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
/*if (!interceptorManager.isPlaybackMode()) {
return;
}*/
listDeletedKeysRunner((keys) -> {
HashMap<String, CreateKeyOptions> keysToDelete = keys;
for (CreateKeyOptions key : keysToDelete.values()) {
assertKeyEquals(key, client.createKey(key));
}
for (CreateKeyOptions key : keysToDelete.values()) {
SyncPoller<DeletedKey, Void> poller = client.beginDeleteKey(key.getName());
PollResponse<DeletedKey> pollResponse = poller.poll();
while (!pollResponse.getStatus().isComplete()) {
sleepInRecordMode(1000);
pollResponse = poller.poll();
}
}
sleepInRecordMode(300000);
Iterable<DeletedKey> deletedKeys = client.listDeletedKeys();
assertTrue(deletedKeys.iterator().hasNext());
for (DeletedKey deletedKey : deletedKeys) {
assertNotNull(deletedKey.getDeletedOn());
assertNotNull(deletedKey.getRecoveryId());
}
});
}
/**
* Tests that key versions can be listed in the key vault.
*/
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("getTestParameters")
public void listKeyVersions(HttpClient httpClient, KeyServiceVersion serviceVersion) {
createKeyClient(httpClient, serviceVersion);
listKeyVersionsRunner((keys) -> {
List<CreateKeyOptions> keyVersions = keys;
String keyName = null;
for (CreateKeyOptions key : keyVersions) {
keyName = key.getName();
sleepInRecordMode(4000);
assertKeyEquals(key, client.createKey(key));
}
Iterable<KeyProperties> keyVersionsOutput = client.listPropertiesOfKeyVersions(keyName);
List<KeyProperties> keyVersionsList = new ArrayList<>();
keyVersionsOutput.forEach(keyVersionsList::add);
assertEquals(keyVersions.size(), keyVersionsList.size());
});
}
private DeletedKey pollOnKeyPurge(String keyName) {
int pendingPollCount = 0;
while (pendingPollCount < 10) {
DeletedKey deletedKey = null;
try {
deletedKey = client.getDeletedKey(keyName);
} catch (ResourceNotFoundException e) {
}
if (deletedKey != null) {
sleepInRecordMode(2000);
pendingPollCount += 1;
continue;
} else {
return deletedKey;
}
}
System.err.printf("Deleted Key %s was not purged \n", keyName);
return null;
}
}
|
3e13cf39fba92d332c60ea19929e8737455b071c | 918 | java | Java | spring-mvc-hello/src/main/java/com/jeiker/controller/HelloController.java | jeikerxiao/spring-mvc | 14fbd8d160bbf18275864472d3bf94c65c913fac | [
"MIT"
] | 2 | 2017-06-30T12:16:15.000Z | 2019-03-07T03:28:26.000Z | spring-mvc-hello/src/main/java/com/jeiker/controller/HelloController.java | jeikerxiao/spring-mvc | 14fbd8d160bbf18275864472d3bf94c65c913fac | [
"MIT"
] | null | null | null | spring-mvc-hello/src/main/java/com/jeiker/controller/HelloController.java | jeikerxiao/spring-mvc | 14fbd8d160bbf18275864472d3bf94c65c913fac | [
"MIT"
] | null | null | null | 27.818182 | 72 | 0.699346 | 8,385 | package com.jeiker.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Description: spring-mvc-hello
* User: jeikerxiao
* Date: 2019/3/8 10:04 AM
*/
@Controller
public class HelloController {
private final Log log = LogFactory.getLog(HelloController.class);
@RequestMapping(value = "/", method = RequestMethod.HEAD)
public String head() {
log.info("in head()");
return "hello.jsp";
}
@RequestMapping(value = {"/index", "/"}, method = RequestMethod.GET)
public String index(Model model) {
log.info("in index()");
model.addAttribute("msg", "Hello World");
return "hello.jsp";
}
}
|
3e13d0eaa04187e77bb9eb933fd198e0f6152fe4 | 742 | java | Java | src/tutorial02/Increment.java | ainzone/BIS2151-Tutorial | b40dd407f280a7ce9ff4c19426214be43f7b968e | [
"Apache-2.0"
] | null | null | null | src/tutorial02/Increment.java | ainzone/BIS2151-Tutorial | b40dd407f280a7ce9ff4c19426214be43f7b968e | [
"Apache-2.0"
] | 2 | 2020-04-01T09:21:20.000Z | 2020-04-01T10:24:39.000Z | src/tutorial02/Increment.java | ainzone/BIS2151-Tutorial | b40dd407f280a7ce9ff4c19426214be43f7b968e | [
"Apache-2.0"
] | null | null | null | 23.1875 | 101 | 0.602426 | 8,386 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package tutorial02;
/**
*
* @author Jascha Pfäfflin
*
* pre- and post-incremet example
*/
public class Increment {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int x = 0; // x wird post-incremented
int y = 0; // y wird pre-incremented
// post-increment
System.out.println("X: " + x++);
System.out.println("X: " + x);
// pre-increment
System.out.println("Y: " + ++y);
System.out.println("Y: " + y);
}
}
|
3e13d14aa77987fc752bfb85cb02d8bb4fdde966 | 618 | java | Java | chapter_001/src/main/java/ru/job4j/array/BubbleSort.java | ChakeGetSome/job4j | 33a3930f9b144ae841b90da58d1d2492a139c1b9 | [
"Apache-2.0"
] | null | null | null | chapter_001/src/main/java/ru/job4j/array/BubbleSort.java | ChakeGetSome/job4j | 33a3930f9b144ae841b90da58d1d2492a139c1b9 | [
"Apache-2.0"
] | null | null | null | chapter_001/src/main/java/ru/job4j/array/BubbleSort.java | ChakeGetSome/job4j | 33a3930f9b144ae841b90da58d1d2492a139c1b9 | [
"Apache-2.0"
] | null | null | null | 25.75 | 56 | 0.441748 | 8,387 | package ru.job4j.array;
/**
* @author Vasiliy Koreshkov
* @version $Id$
* @since 0.1
*/
public class BubbleSort {
/**
* @param array массив который нужно отсортировать.
* @return отсортированный массив.
*/
public int[] sort(int[] array) {
for (int j = 0; j < array.length; j++) {
for (int i = 1; i < array.length - j; i++) {
if (array[i] < array[i - 1]) {
int temp = array[i];
array[i] = array [i - 1];
array[i - 1] = temp;
}
}
}
return array;
}
} |
3e13d16b144835b37309ca48270b42a7bce9cf7d | 329 | java | Java | hr-domain/src/com/example/hr/domain/Photo.java | deepcloudlabs/dcl350-2021-mar-26 | eed9ad27df44f6016096c872def6dcc34cb7fe4c | [
"MIT"
] | null | null | null | hr-domain/src/com/example/hr/domain/Photo.java | deepcloudlabs/dcl350-2021-mar-26 | eed9ad27df44f6016096c872def6dcc34cb7fe4c | [
"MIT"
] | null | null | null | hr-domain/src/com/example/hr/domain/Photo.java | deepcloudlabs/dcl350-2021-mar-26 | eed9ad27df44f6016096c872def6dcc34cb7fe4c | [
"MIT"
] | null | null | null | 14.954545 | 43 | 0.68997 | 8,388 | package com.example.hr.domain;
import java.util.Objects;
@ValueObject
public class Photo {
private final byte[] data;
private Photo(byte[] data) {
this.data = data;
}
public byte[] getData() {
return data;
}
public static Photo valueOf(byte[] data) {
Objects.requireNonNull(data);
return new Photo(data);
}
}
|
3e13d173aa3f1cedbb8706c63f3d34a811698dad | 10,686 | java | Java | drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/DMNScenarioRunnerHelper.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 5 | 2016-07-31T17:00:18.000Z | 2022-01-11T04:34:29.000Z | drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/DMNScenarioRunnerHelper.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 4 | 2019-08-15T11:38:50.000Z | 2021-03-02T09:01:40.000Z | drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/DMNScenarioRunnerHelper.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | null | null | null | 52.382353 | 181 | 0.669755 | 8,389 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.scenariosimulation.backend.runner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.drools.scenariosimulation.api.model.ExpressionElement;
import org.drools.scenariosimulation.api.model.ExpressionIdentifier;
import org.drools.scenariosimulation.api.model.FactIdentifier;
import org.drools.scenariosimulation.api.model.FactMapping;
import org.drools.scenariosimulation.api.model.FactMappingValue;
import org.drools.scenariosimulation.api.model.ScenarioSimulationModel;
import org.drools.scenariosimulation.api.model.ScenarioWithIndex;
import org.drools.scenariosimulation.api.model.ScesimModelDescriptor;
import org.drools.scenariosimulation.api.model.Settings;
import org.drools.scenariosimulation.backend.expression.ExpressionEvaluator;
import org.drools.scenariosimulation.backend.expression.ExpressionEvaluatorFactory;
import org.drools.scenariosimulation.backend.fluent.DMNScenarioExecutableBuilder;
import org.drools.scenariosimulation.backend.runner.model.InstanceGiven;
import org.drools.scenariosimulation.backend.runner.model.ResultWrapper;
import org.drools.scenariosimulation.backend.runner.model.ScenarioExpect;
import org.drools.scenariosimulation.backend.runner.model.ScenarioResult;
import org.drools.scenariosimulation.backend.runner.model.ScenarioResultMetadata;
import org.drools.scenariosimulation.backend.runner.model.ScenarioRunnerData;
import org.kie.api.runtime.KieContainer;
import org.kie.dmn.api.core.DMNDecisionResult;
import org.kie.dmn.api.core.DMNModel;
import org.kie.dmn.api.core.DMNResult;
import org.kie.dmn.api.core.ast.DecisionNode;
import static org.drools.scenariosimulation.backend.runner.model.ResultWrapper.createErrorResultWithErrorMessage;
import static org.kie.dmn.api.core.DMNDecisionResult.DecisionEvaluationStatus.SUCCEEDED;
public class DMNScenarioRunnerHelper extends AbstractRunnerHelper {
@Override
protected Map<String, Object> executeScenario(KieContainer kieContainer,
ScenarioRunnerData scenarioRunnerData,
ExpressionEvaluatorFactory expressionEvaluatorFactory,
ScesimModelDescriptor scesimModelDescriptor,
Settings settings) {
if (!ScenarioSimulationModel.Type.DMN.equals(settings.getType())) {
throw new ScenarioException("Impossible to run a not-DMN simulation with DMN runner");
}
DMNScenarioExecutableBuilder executableBuilder = createBuilderWrapper(kieContainer);
executableBuilder.setActiveModel(settings.getDmnFilePath());
loadInputData(scenarioRunnerData.getBackgrounds(), executableBuilder);
loadInputData(scenarioRunnerData.getGivens(), executableBuilder);
return executableBuilder.run().getOutputs();
}
protected void loadInputData(List<InstanceGiven> dataToLoad, DMNScenarioExecutableBuilder executableBuilder) {
for (InstanceGiven input : dataToLoad) {
executableBuilder.setValue(input.getFactIdentifier().getName(), input.getValue());
}
}
@Override
protected ScenarioResultMetadata extractResultMetadata(Map<String, Object> requestContext,
ScenarioWithIndex scenarioWithIndex) {
DMNModel dmnModel = (DMNModel) requestContext.get(DMNScenarioExecutableBuilder.DMN_MODEL);
DMNResult dmnResult = (DMNResult) requestContext.get(DMNScenarioExecutableBuilder.DMN_RESULT);
ScenarioResultMetadata scenarioResultMetadata = new ScenarioResultMetadata(scenarioWithIndex);
for (DecisionNode decision : dmnModel.getDecisions()) {
scenarioResultMetadata.addAvailable(decision.getName());
}
final AtomicInteger counter = new AtomicInteger(0);
for (DMNDecisionResult decisionResult : dmnResult.getDecisionResults()) {
if (SUCCEEDED.equals(decisionResult.getEvaluationStatus())) {
scenarioResultMetadata.addExecuted(decisionResult.getDecisionName());
}
if (decisionResult.getMessages().isEmpty()) {
scenarioResultMetadata.addAuditMessage(counter.addAndGet(1), decisionResult.getDecisionName(), decisionResult.getEvaluationStatus().name());
} else {
decisionResult.getMessages().forEach(dmnMessage -> scenarioResultMetadata.addAuditMessage(counter.addAndGet(1), dmnMessage.getText(), dmnMessage.getLevel().name()));
}
}
return scenarioResultMetadata;
}
@Override
protected void verifyConditions(ScesimModelDescriptor scesimModelDescriptor,
ScenarioRunnerData scenarioRunnerData,
ExpressionEvaluatorFactory expressionEvaluatorFactory,
Map<String, Object> requestContext) {
DMNResult dmnResult = (DMNResult) requestContext.get(DMNScenarioExecutableBuilder.DMN_RESULT);
for (ScenarioExpect output : scenarioRunnerData.getExpects()) {
FactIdentifier factIdentifier = output.getFactIdentifier();
String decisionName = factIdentifier.getName();
DMNDecisionResult decisionResult = dmnResult.getDecisionResultByName(decisionName);
if (decisionResult == null) {
throw new ScenarioException("DMN execution has not generated a decision result with name " + decisionName);
}
for (FactMappingValue expectedResult : output.getExpectedResult()) {
ExpressionIdentifier expressionIdentifier = expectedResult.getExpressionIdentifier();
FactMapping factMapping = scesimModelDescriptor.getFactMapping(factIdentifier, expressionIdentifier)
.orElseThrow(() -> new IllegalStateException("Wrong expression, this should not happen"));
ExpressionEvaluator expressionEvaluator = expressionEvaluatorFactory.getOrCreate(expectedResult);
ScenarioResult scenarioResult = fillResult(expectedResult,
() -> getSingleFactValueResult(factMapping, expectedResult, decisionResult, expressionEvaluator),
expressionEvaluator);
scenarioRunnerData.addResult(scenarioResult);
}
}
}
@SuppressWarnings("unchecked")
protected ResultWrapper getSingleFactValueResult(FactMapping factMapping,
FactMappingValue expectedResult,
DMNDecisionResult decisionResult,
ExpressionEvaluator expressionEvaluator) {
Object resultRaw = decisionResult.getResult();
final DMNDecisionResult.DecisionEvaluationStatus evaluationStatus = decisionResult.getEvaluationStatus();
if (!SUCCEEDED.equals(evaluationStatus)) {
return createErrorResultWithErrorMessage("The decision " +
decisionResult.getDecisionName() +
" has not been successfully evaluated: " +
evaluationStatus);
}
List<ExpressionElement> elementsWithoutClass = factMapping.getExpressionElementsWithoutClass();
// DMN engine doesn't generate the whole object when no entry of the decision table match
if (resultRaw != null) {
for (ExpressionElement expressionElement : elementsWithoutClass) {
if (!(resultRaw instanceof Map)) {
throw new ScenarioException("Wrong resultRaw structure because it is not a complex type as expected");
}
Map<String, Object> result = (Map<String, Object>) resultRaw;
resultRaw = result.get(expressionElement.getStep());
}
}
Class<?> resultClass = resultRaw != null ? resultRaw.getClass() : null;
Object expectedResultRaw = expectedResult.getRawValue();
return getResultWrapper(factMapping.getClassName(),
expectedResult,
expressionEvaluator,
expectedResultRaw,
resultRaw,
resultClass);
}
@SuppressWarnings("unchecked")
@Override
protected Object createObject(Optional<Object> initialInstance, String className, Map<List<String>, Object> params, ClassLoader classLoader) {
// simple types
if (initialInstance.isPresent() && !(initialInstance.get() instanceof Map)) {
return initialInstance.get();
}
Map<String, Object> toReturn = (Map<String, Object>) initialInstance.orElseGet(HashMap::new);
for (Map.Entry<List<String>, Object> listObjectEntry : params.entrySet()) {
// direct mapping already considered
if (listObjectEntry.getKey().isEmpty()) {
continue;
}
List<String> allSteps = listObjectEntry.getKey();
List<String> steps = allSteps.subList(0, allSteps.size() - 1);
String lastStep = allSteps.get(allSteps.size() - 1);
Map<String, Object> targetMap = toReturn;
for (String step : steps) {
targetMap = (Map<String, Object>) targetMap.computeIfAbsent(step, k -> new HashMap<>());
}
targetMap.put(lastStep, listObjectEntry.getValue());
}
return toReturn;
}
protected DMNScenarioExecutableBuilder createBuilderWrapper(KieContainer kieContainer) {
return DMNScenarioExecutableBuilder.createBuilder(kieContainer);
}
}
|
3e13d28a3cdc95eacb6a48102772f7a521656c22 | 1,946 | java | Java | Game/src/Base/MapLoaders/EasyLoader.java | Pashhaa/Maze-runner | e380567e60dd7e4785840799f09704769049cfa1 | [
"MIT"
] | 2 | 2021-04-12T16:49:52.000Z | 2021-04-12T16:52:58.000Z | Game/src/Base/MapLoaders/EasyLoader.java | Pashhaa/Maze-runner | e380567e60dd7e4785840799f09704769049cfa1 | [
"MIT"
] | null | null | null | Game/src/Base/MapLoaders/EasyLoader.java | Pashhaa/Maze-runner | e380567e60dd7e4785840799f09704769049cfa1 | [
"MIT"
] | null | null | null | 32.433333 | 81 | 0.419322 | 8,390 | package Base.MapLoaders;
import Base.Objects.Abstracts.AbstractFigur;
import Base.Objects.Realization.*;
import java.util.Random;
public class EasyLoader implements Loader{
@Override
public AbstractFigur[][] loading(AbstractFigur[][] data, Player player) {
String[] array = {"N","N","N","N","GG","GG","E", "M","N","N","N"};
short goldCount = 17;
short botCount = 2;
AbstractFigur exit = Exit.getExit();
Random random = new Random();
int exitIndexX = random.nextInt(11);
int exitIndexY = random.nextInt(10);
data[exitIndexY][exitIndexX] = exit;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
int elemIndex = random.nextInt(array.length);
if(data[i][j].getClass() == Emptiness.class) {
AbstractFigur arrayValue;
if (array[elemIndex].equals("M") && botCount > 0){
arrayValue = new Bot();
botCount--;
}
else if(array[elemIndex].equals("GG") && goldCount > 0){
arrayValue = new Gold();
goldCount--;
}
else {
arrayValue = data[i][j];
}
arrayValue.setX(j);
arrayValue.setY(i);
data[i][j]=arrayValue;
}
}
}
int playerX = 5;
int playerY = 6;
player = new Player();
player.setX(playerX);
player.setY(playerY);
data[playerY][playerX] = player;
return data;
}
}
|
3e13d2929d4d8cc096ea0bfc67ab690006c8e514 | 627 | java | Java | schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/pending/container/LoanRepaymentFormConverter.java | nagaikenshin/schemaOrg | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | [
"Apache-2.0"
] | 1 | 2020-02-18T01:55:36.000Z | 2020-02-18T01:55:36.000Z | schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/pending/container/LoanRepaymentFormConverter.java | nagaikenshin/schemaOrg | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | [
"Apache-2.0"
] | null | null | null | schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/pending/container/LoanRepaymentFormConverter.java | nagaikenshin/schemaOrg | 4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8 | [
"Apache-2.0"
] | null | null | null | 27.26087 | 95 | 0.827751 | 8,391 | package org.kyojo.schemaorg.m3n4.doma.pending.container;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaorg.m3n4.pending.impl.LOAN_REPAYMENT_FORM;
import org.kyojo.schemaorg.m3n4.pending.Container.LoanRepaymentForm;
@ExternalDomain
public class LoanRepaymentFormConverter implements DomainConverter<LoanRepaymentForm, String> {
@Override
public String fromDomainToValue(LoanRepaymentForm domain) {
return domain.getNativeValue();
}
@Override
public LoanRepaymentForm fromValueToDomain(String value) {
return new LOAN_REPAYMENT_FORM(value);
}
}
|
3e13d2ac6456814cefb56e2b314281b1227aaae1 | 1,554 | java | Java | src/main/java/com/soasta/jenkins/WakeUpIOSDevice.java | JLLeitschuh/cloudtest-plugin | a7ac262f64a7cc43cd41a3c8541f35b58a95772f | [
"MIT"
] | 5 | 2015-01-20T11:17:25.000Z | 2019-04-23T20:40:20.000Z | src/main/java/com/soasta/jenkins/WakeUpIOSDevice.java | JLLeitschuh/cloudtest-plugin | a7ac262f64a7cc43cd41a3c8541f35b58a95772f | [
"MIT"
] | 7 | 2015-01-20T13:00:56.000Z | 2017-04-25T19:02:22.000Z | src/main/java/com/soasta/jenkins/WakeUpIOSDevice.java | JLLeitschuh/cloudtest-plugin | a7ac262f64a7cc43cd41a3c8541f35b58a95772f | [
"MIT"
] | 8 | 2015-02-27T06:02:59.000Z | 2020-02-11T01:35:30.000Z | 29.320755 | 98 | 0.680824 | 8,392 | /*
* Copyright (c) 2013, SOASTA, Inc.
* All Rights Reserved.
*/
package com.soasta.jenkins;
import java.io.IOException;
import java.util.logging.Logger;
import hudson.EnvVars;
import hudson.Extension;
import hudson.util.ArgumentListBuilder;
import org.kohsuke.stapler.DataBoundConstructor;
public class WakeUpIOSDevice extends iOSAppInstallerBase {
@DataBoundConstructor
public WakeUpIOSDevice(String url, String cloudTestServerID, String additionalOptions) {
super(url, cloudTestServerID, additionalOptions);
}
public Object readResolve() throws IOException {
if (getCloudTestServerID() != null)
return this;
// We don't have a server ID.
// This means the builder config is based an older version the plug-in.
// Look up the server by URL instead.
// We'll use the ID going forward.
CloudTestServer s = CloudTestServer.getByURL(getUrl());
LOGGER.info("Matched server URL " + getUrl() + " to ID: " + s.getId() + "; re-creating.");
return new WakeUpIOSDevice(getUrl(), s.getId(), getAdditionalOptions());
}
@Override
protected void addArgs(EnvVars envs, ArgumentListBuilder args) {
args.add("--wakeup");
}
@Extension
public static class DescriptorImpl extends AbstractCloudTestBuilderDescriptor {
@Override
public String getDisplayName() {
return "Wake up iOS Device";
}
}
private static final Logger LOGGER = Logger.getLogger(WakeUpIOSDevice.class.getName());
}
|
3e13d36fa3a5bf80c03bd582a55853abe9526bf3 | 140 | java | Java | util/src/main/java/coco/tx/Transmitter.java | mxns/valpen | 2a24877c69d3da4f93aa55fbdef575fcead9faa4 | [
"MIT"
] | null | null | null | util/src/main/java/coco/tx/Transmitter.java | mxns/valpen | 2a24877c69d3da4f93aa55fbdef575fcead9faa4 | [
"MIT"
] | null | null | null | util/src/main/java/coco/tx/Transmitter.java | mxns/valpen | 2a24877c69d3da4f93aa55fbdef575fcead9faa4 | [
"MIT"
] | null | null | null | 15.555556 | 45 | 0.692857 | 8,393 | package coco.tx;
public interface Transmitter<E> {
public void send(E pMessage);
public void send(E pMessage, boolean pVip);
}
|
3e13d4b1b2ebecba9452d5707b9431dbe0b15518 | 2,176 | java | Java | src/main/java/de/vandermeer/skb/interfaces/translators/HtmlElementTranslator.java | hunter1703/skb-java-interfaces | a2f312b12a7c28bc61971e4986bf9ce142013c64 | [
"Apache-2.0"
] | 1 | 2017-05-02T12:58:16.000Z | 2017-05-02T12:58:16.000Z | src/main/java/de/vandermeer/skb/interfaces/translators/HtmlElementTranslator.java | hunter1703/skb-java-interfaces | a2f312b12a7c28bc61971e4986bf9ce142013c64 | [
"Apache-2.0"
] | 1 | 2021-05-04T11:40:26.000Z | 2021-05-04T11:40:26.000Z | src/main/java/de/vandermeer/skb/interfaces/translators/HtmlElementTranslator.java | hunter1703/skb-java-interfaces | a2f312b12a7c28bc61971e4986bf9ce142013c64 | [
"Apache-2.0"
] | 3 | 2017-12-13T05:36:09.000Z | 2021-04-30T10:03:53.000Z | 36.366667 | 114 | 0.724106 | 8,394 | /* Copyright 2016 Sven van der Meer <upchh@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.vandermeer.skb.interfaces.translators;
/**
* Interface for an HTML Element translator.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
* @version v0.0.2 build 170502 (02-May-17) for Java 1.8
* @since v0.0.1
*/
public interface HtmlElementTranslator {
/**
* Translates HTML elements into a temporary representation that is not picked up by any character translator.
* @param input string to translate
* @return translated string
*/
String text2tmp(String input);
/**
* Translates a temporary representation of HTML elements to a target representation.
* @param input string to translate, with temporary HTML element representations
* @return translated string, with target representations of HTML elements
*/
String tmp2target(String input);
/**
* Translates HTML elements found in the input to a target representation, without any temporary representation.
* @param input string to translate
* @return translated string, with target representation of HTML elements
*/
String translateHtmlElements(String input);
/**
* Translates HTML elements found in the input to a target representation, without any temporary representation.
* @param input object to translate (toString is used)
* @return translated string, with target representation of HTML elements
*/
default String translateHtmlElements(Object input){
if(input!=null){
return this.translateHtmlElements(input.toString());
}
return null;
}
}
|
3e13d5a1452a65f91391e4a885414207e0b716aa | 841 | java | Java | Java Programs/PackageChallenge/src/info/jessequinn/mylibrary/Series.java | jessequinn/Java-Programming-Masterclass-for-Software-Developers | 6ec20170e65f73808c65033100e2bf984feec05e | [
"MIT"
] | null | null | null | Java Programs/PackageChallenge/src/info/jessequinn/mylibrary/Series.java | jessequinn/Java-Programming-Masterclass-for-Software-Developers | 6ec20170e65f73808c65033100e2bf984feec05e | [
"MIT"
] | null | null | null | Java Programs/PackageChallenge/src/info/jessequinn/mylibrary/Series.java | jessequinn/Java-Programming-Masterclass-for-Software-Developers | 6ec20170e65f73808c65033100e2bf984feec05e | [
"MIT"
] | null | null | null | 21.025 | 42 | 0.370987 | 8,395 | package info.jessequinn.mylibrary;
public class Series {
public static long nSum(int n) {
return (n * (n + 1)) / 2;
}
public static long factorial(int n) {
if (n == 0) {
return 1;
} else {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
}
public static long fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
long nMinus1 = 1;
long nMinus2 = 0;
long fib = 0;
for (int i = 1; i < n; i++) {
fib = (nMinus2 + nMinus1);
nMinus2 = nMinus1;
nMinus1 = fib;
}
return fib;
}
}
}
|
3e13d5d6f25e5a079839d8881a375b803563f894 | 864 | java | Java | code/server/sys/src/main/java/com/jianli/sys/dao/lookup/OrgLookup.java | jikanghz/jianli | effedf6842558207eff0f1595a16bc2c5025da6f | [
"MIT"
] | 1 | 2021-03-03T05:50:02.000Z | 2021-03-03T05:50:02.000Z | code/server/sys/src/main/java/com/jianli/sys/dao/lookup/OrgLookup.java | jikanghz/jianli | effedf6842558207eff0f1595a16bc2c5025da6f | [
"MIT"
] | null | null | null | code/server/sys/src/main/java/com/jianli/sys/dao/lookup/OrgLookup.java | jikanghz/jianli | effedf6842558207eff0f1595a16bc2c5025da6f | [
"MIT"
] | 1 | 2020-12-23T10:33:07.000Z | 2020-12-23T10:33:07.000Z | 27 | 91 | 0.715278 | 8,396 | package com.jianli.sys.dao.lookup;
import com.jianli.common.dao.LookupDao;
import com.jianli.common.service.JsonRequest;
import com.jianli.common.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("orgLookup")
public class OrgLookup extends LookupDao {
@Autowired
private SecurityUtil securityUtil;
public OrgLookup()
{
tableName = "sys_org";
codeValueField = "id";
codeNameField = "orgName";
defaultOrder = "orgName";
}
@Override
protected String getCondition(String inputValue, JsonRequest jsonRequest) {
String condition = super.getCondition(inputValue, jsonRequest);
condition += " AND tenantId = " + securityUtil.getTenantId(jsonRequest.getToken());
return condition;
}
}
|
3e13d6ca13578b5bcf6766997a225192ecbc893b | 2,878 | java | Java | Applications/RSSReader/src/za/android/vdm/rssreader/models/RSSfeedXMLParser.java | micklinISgood/JPF-Android | a970286a0d404a7a8f6d4752e443875ada2b00a7 | [
"Apache-2.0"
] | 3 | 2016-12-09T00:22:13.000Z | 2018-07-13T05:36:35.000Z | Applications/RSSReader/src/za/android/vdm/rssreader/models/RSSfeedXMLParser.java | micklinISgood/JPF-Android | a970286a0d404a7a8f6d4752e443875ada2b00a7 | [
"Apache-2.0"
] | 1 | 2020-04-29T03:32:41.000Z | 2021-04-08T15:24:40.000Z | Applications/RSSReader/src/za/android/vdm/rssreader/models/RSSfeedXMLParser.java | micklinISgood/JPF-Android | a970286a0d404a7a8f6d4752e443875ada2b00a7 | [
"Apache-2.0"
] | 4 | 2016-11-26T08:39:13.000Z | 2021-09-25T03:22:08.000Z | 24.598291 | 99 | 0.660181 | 8,397 | package za.android.vdm.rssreader.models;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
// import android.util.Log;
public class RSSfeedXMLParser extends DefaultHandler {
private static final String TAG = RSSfeedXMLParser.class.getSimpleName();
RSSFeed feed;
List<RSSItem> items;
RSSItem tempItem;
final int RSS_TITLE = 1;
final int RSS_LINK = 2;
final int RSS_DESCRIPTION = 3;
final int RSS_PUBDATE = 4;
private StringBuffer builder;
int currentElement = 0;
/**
* Default Constructor for the feed
*/
public RSSfeedXMLParser() {
}
public void startDocument() throws SAXException {
feed = new RSSFeed();
tempItem = null;
items = new ArrayList<RSSItem>();
builder = new StringBuffer();
}
public void endDocument() throws SAXException {
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
builder.append(ch, start, length);
}
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
throws SAXException {
builder = new StringBuffer();
if (localName.equals("item")) {
// create a new item
tempItem = new RSSItem();
return;
}
}
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
RSSBase base = null;
if (tempItem == null)
base = feed;
else
base = tempItem;
if (localName.equalsIgnoreCase("title") && base.getTitle() == null) {
base.setTitle(builder.toString());
} else if (localName.equalsIgnoreCase("link") && base.getLink() == null) {
if (base != null)
base.setLink(builder.toString());
} else if (localName.equalsIgnoreCase("description")) {
base.setDescription(builder.toString());
} else if (localName.equalsIgnoreCase("pubdate")) {
base.setPubdate(convertDateToLong(builder.toString()));
} else if (localName.equalsIgnoreCase("item")) {
items.add(tempItem);
tempItem = null;
} else
return;
}
/**
* Converts the String pubdate of a feed to a long value
*
* @param dateString
* @return
*/
public long convertDateToLong(String dateString) {
// SimpleDateFormat formatter;
// Date date = null;
// try {
// formatter = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");
// date = (Date) formatter.parse(dateString);
// } catch (ParseException e) {
// Log.e(TAG, "Error parsing date");
// }
return 1;//date.getTime();
}
/*
* getFeed - this returns our feed when all of the parsing is complete
*/
public RSSFeed getFeed() {
return feed;
}
public List<RSSItem> getFeedItems() {
return items;
}
} |
3e13d80dc6822b4068116eb763eff4fe4852d469 | 7,767 | java | Java | src/test/java/dk/jyskebank/tools/enunciate/modules/openapi/ObjectTypeRendererTest.java | selimok/enunciate-openapi | 5fa164e41d17ca37dc083b989dff4a09f04ef357 | [
"Apache-2.0"
] | 3 | 2021-08-21T17:44:43.000Z | 2021-11-15T18:06:59.000Z | src/test/java/dk/jyskebank/tools/enunciate/modules/openapi/ObjectTypeRendererTest.java | selimok/enunciate-openapi | 5fa164e41d17ca37dc083b989dff4a09f04ef357 | [
"Apache-2.0"
] | 6 | 2020-12-15T18:04:56.000Z | 2021-07-26T09:28:15.000Z | src/test/java/dk/jyskebank/tools/enunciate/modules/openapi/ObjectTypeRendererTest.java | selimok/enunciate-openapi | 5fa164e41d17ca37dc083b989dff4a09f04ef357 | [
"Apache-2.0"
] | 3 | 2021-03-31T16:30:53.000Z | 2021-04-20T05:03:12.000Z | 39.627551 | 128 | 0.696794 | 8,398 | package dk.jyskebank.tools.enunciate.modules.openapi;
import com.webcohesion.enunciate.api.InterfaceDescriptionFile;
import com.webcohesion.enunciate.api.datatype.BaseType;
import com.webcohesion.enunciate.api.datatype.DataType;
import com.webcohesion.enunciate.api.datatype.DataTypeReference;
import com.webcohesion.enunciate.api.datatype.Namespace;
import com.webcohesion.enunciate.modules.jaxb.api.impl.ComplexDataTypeImpl;
import dk.jyskebank.tools.enunciate.modules.openapi.yaml.IndentationPrinter;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static dk.jyskebank.tools.enunciate.modules.openapi.ObjectTypeRenderer.JSON_REF_FORMAT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ObjectTypeRendererTest {
public static final String CONCRETE_TYPE_LABEL = "ConcreteX";
public static final String CONCRETE_TYPE_XML_NAME = "xml_xmlns_concreteX";
public static final String CONCRETE_TYPE_XML_URI = "http://www.w3.org/2000/xmlns/";
public static final String CONCRETE_TYPE_XML_PREFIX = "xmlns";
@Test
void verifyRenderAbstractType() {
ObjectTypeRenderer objectTypeRenderer = new ObjectTypeRenderer(new OutputLogger(), null
, null, null, false, false);
IndentationPrinter ip = TestHelper.getIndentationPrinter();
DataType abstractType = getAbstractTypeWithTwoSubtypes();
objectTypeRenderer.render(ip, abstractType, true);
final String expected = createExpectedResultForAbstractType();
assertEquals(expected, ip.toString());
}
@Test
void verifyRenderConcreteType() {
ObjectTypeRenderer objectTypeRenderer = new ObjectTypeRenderer(new OutputLogger(), null
, null, null, false, false);
IndentationPrinter ip = TestHelper.getIndentationPrinter();
DataType concreteType = getConcreteType();
objectTypeRenderer.render(ip, concreteType, false);
final String expected = createExpectedResultForConcreteType();
assertEquals(expected, ip.toString());
}
@Test
void verifyRenderConcreteTypeNamespacePrefix(){
ObjectTypeRenderer objectTypeRenderer = new ObjectTypeRenderer(new OutputLogger(), null
, null, Collections.singletonMap(CONCRETE_TYPE_XML_URI,CONCRETE_TYPE_XML_PREFIX), false, false);
IndentationPrinter ip = TestHelper.getIndentationPrinter();
DataType concreteType = getConcreteTypeWithNamespace();
objectTypeRenderer.render(ip, concreteType, false);
final String expected = createExpectedResultForConcreteTypeWithNamespacePrefix();
assertEquals(expected, ip.toString());
}
@Test
void verifyRenderConcreteTypeWithoutNamespacePrefix(){
ObjectTypeRenderer objectTypeRenderer = new ObjectTypeRenderer(new OutputLogger(), null
, null, null, false, false);
IndentationPrinter ip = TestHelper.getIndentationPrinter();
DataType concreteType = getConcreteTypeWithNamespace();
objectTypeRenderer.render(ip, concreteType, false);
final String expected = createExpectedResultForConcreteTypeWithoutNamespacePrefix();
assertEquals(expected, ip.toString());
}
private ComplexDataTypeImpl getConcreteTypeWithNamespace() {
ComplexDataTypeImpl mockedDataType = mock(ComplexDataTypeImpl.class);
when(mockedDataType.isAbstract()).thenReturn(Boolean.FALSE);
when(mockedDataType.getLabel()).thenReturn(CONCRETE_TYPE_LABEL);
when(mockedDataType.getXmlName()).thenReturn(CONCRETE_TYPE_XML_NAME);
when(mockedDataType.getBaseType()).thenReturn(BaseType.string);
Namespace customNamespace = new Namespace() {
@Override
public String getUri() {
return CONCRETE_TYPE_XML_URI;
}
@Override
public InterfaceDescriptionFile getSchemaFile() {
return null;
}
@Override
public List<? extends DataType> getTypes() {
return null;
}
};
when(mockedDataType.getNamespace()).thenReturn(customNamespace);
return mockedDataType;
}
private String createExpectedResultForConcreteTypeWithNamespacePrefix() {
String DOS_NEWLINE = "\r\n";
return String.format("title: \"%s\"%s%s type: string%s%s xml:%s%s name: %s%s%s namespace: %s%s%s prefix: %s",
CONCRETE_TYPE_LABEL, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
CONCRETE_TYPE_XML_NAME, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
CONCRETE_TYPE_XML_URI, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
CONCRETE_TYPE_XML_PREFIX, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION);
}
private String createExpectedResultForConcreteTypeWithoutNamespacePrefix() {
String DOS_NEWLINE = "\r\n";
return String.format("title: \"%s\"%s%s type: string%s%s xml:%s%s name: %s%s%s namespace: %s",
CONCRETE_TYPE_LABEL, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
CONCRETE_TYPE_XML_NAME, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION,
CONCRETE_TYPE_XML_URI, DOS_NEWLINE, TestHelper.INITIAL_INDENTATION);
}
private String createExpectedResultForConcreteType() {
String DOS_NEWLINE = "\r\n";
return String.format("title: \"%s\"%s%s type: string",
CONCRETE_TYPE_LABEL,
DOS_NEWLINE,
TestHelper.INITIAL_INDENTATION);
}
private DataType getConcreteType() {
DataType mockedDataType = mock(DataType.class);
when(mockedDataType.isAbstract()).thenReturn(Boolean.FALSE);
when(mockedDataType.getLabel()).thenReturn(CONCRETE_TYPE_LABEL);
when(mockedDataType.getBaseType()).thenReturn(BaseType.string);
when(mockedDataType.getSubtypes()).thenReturn(Collections.emptyList());
when(mockedDataType.getProperties()).thenReturn(Collections.emptyList());
when(mockedDataType.getValues()).thenReturn(Collections.emptyList());
return mockedDataType;
}
private String createExpectedResultForAbstractType() {
String DOS_NEWLINE = "\r\n";
return String.format("oneOf: %s%s %s%s%s %s",
DOS_NEWLINE,
TestHelper.INITIAL_INDENTATION,
getJsonRefForSubType("A"),
DOS_NEWLINE,
TestHelper.INITIAL_INDENTATION,
getJsonRefForSubType("B"));
}
private String getJsonRefForSubType(String a) {
return String.format(JSON_REF_FORMAT, a);
}
private DataType getAbstractTypeWithTwoSubtypes() {
DataType mockedDataType = mock(DataType.class);
when(mockedDataType.isAbstract()).thenReturn(Boolean.TRUE);
List<DataTypeReference> subTypes = new ArrayList<>();
subTypes.add(createConcreteSubtype("A"));
subTypes.add(createConcreteSubtype("B"));
when(mockedDataType.getSubtypes()).thenReturn(subTypes);
return mockedDataType;
}
private DataTypeReference createConcreteSubtype(String nameOfConcreteType) {
DataTypeReference concreteTypeA = mock(DataTypeReference.class);
when(concreteTypeA.getSlug()).thenReturn(nameOfConcreteType);
return concreteTypeA;
}
}
|
3e13d8c97afa8cbddb63e600678bdd067d6cddf8 | 1,244 | java | Java | nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/LocalFileSource.java | taotesea/EclipseDeeplearning4j | a119da98b5fdf0181fa6f9ae93f1bfff45772495 | [
"Apache-2.0"
] | 13,006 | 2015-02-13T18:35:31.000Z | 2022-03-18T12:11:44.000Z | nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/LocalFileSource.java | taotesea/EclipseDeeplearning4j | a119da98b5fdf0181fa6f9ae93f1bfff45772495 | [
"Apache-2.0"
] | 5,319 | 2015-02-13T08:21:46.000Z | 2019-06-12T14:56:50.000Z | nd4j/nd4j-common/src/main/java/org/nd4j/common/loader/LocalFileSource.java | taotesea/EclipseDeeplearning4j | a119da98b5fdf0181fa6f9ae93f1bfff45772495 | [
"Apache-2.0"
] | 4,719 | 2015-02-13T22:48:55.000Z | 2022-03-22T07:25:36.000Z | 33.621622 | 96 | 0.652733 | 8,399 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.common.loader;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.io.*;
/**
* A simple {@link Source} that returns a (buffered) FileInputStream for the specified file path
*/
@AllArgsConstructor
public class LocalFileSource implements Source {
@Getter
private String path;
@Override
public InputStream getInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(new File(path)));
}
}
|
3e13d940c06a373e9baf95138255a40f2fa35d1d | 724 | java | Java | src/controllers/simulation/hard/HardSimulationGUIController.java | theghia/SalsaAUI | 2ce5017c5e54ac983d5a759ea1f2cbc1a1844435 | [
"MIT"
] | null | null | null | src/controllers/simulation/hard/HardSimulationGUIController.java | theghia/SalsaAUI | 2ce5017c5e54ac983d5a759ea1f2cbc1a1844435 | [
"MIT"
] | null | null | null | src/controllers/simulation/hard/HardSimulationGUIController.java | theghia/SalsaAUI | 2ce5017c5e54ac983d5a759ea1f2cbc1a1844435 | [
"MIT"
] | null | null | null | 36.2 | 105 | 0.758287 | 8,400 | package controllers.simulation.hard;
import controllers.GUIController;
import main.SalsaModel;
import views.GameView;
public class HardSimulationGUIController extends GUIController {
/**
* Constructor for the HardSimulationGUIController that interacts with the HardSimulationView.
*
* @param salsaModel A SalsaModel object that contains the data of the MVC
* @param controllerName A String object representing the name of the controller
* @param gameView A GameView object that will be a HardSimulationView
*/
public HardSimulationGUIController(SalsaModel salsaModel, String controllerName, GameView gameView) {
super(salsaModel, controllerName, gameView);
}
}
|
3e13dc2b9e8863982e0f2b9230dd57dea7e497d2 | 1,244 | java | Java | reactive/akka/src/main/java/com/corp/concepts/reactive/akka/actors/Poller.java | selcuksert/reactive-programming | baafb64218f7101c5690e1b684912704c92bab2e | [
"MIT"
] | null | null | null | reactive/akka/src/main/java/com/corp/concepts/reactive/akka/actors/Poller.java | selcuksert/reactive-programming | baafb64218f7101c5690e1b684912704c92bab2e | [
"MIT"
] | null | null | null | reactive/akka/src/main/java/com/corp/concepts/reactive/akka/actors/Poller.java | selcuksert/reactive-programming | baafb64218f7101c5690e1b684912704c92bab2e | [
"MIT"
] | null | null | null | 28.272727 | 107 | 0.767685 | 8,402 | package com.corp.concepts.reactive.akka.actors;
import java.time.Duration;
import akka.actor.AbstractActorWithTimers;
import akka.actor.ActorRef;
import akka.actor.Props;
public class Poller extends AbstractActorWithTimers {
private static final Object TICK_KEY = "TickKey";
private final ActorRef requestorActor;
private final String cryptoName;
private final int interval;
public Poller(ActorRef requestorActor, String cryptoName, int interval) {
this.requestorActor = requestorActor;
this.cryptoName = cryptoName;
this.interval = interval;
getTimers().startSingleTimer(TICK_KEY, new FirstTick(), Duration.ofMillis(interval));
}
public static Props props(String cryptoName, int interval, ActorRef requestorActor) {
return Props.create(Poller.class, () -> new Poller(requestorActor, cryptoName, interval));
}
@Override
public Receive createReceive() {
return receiveBuilder().match(FirstTick.class, message -> {
getTimers().startTimerAtFixedRate(TICK_KEY, new Tick(), Duration.ofMillis(interval));
}).match(Tick.class, message -> requestorActor.tell(new Requestor.GetCryptoPrice(cryptoName), getSelf()))
.build();
}
private static final class FirstTick {
}
private static final class Tick {
}
}
|
3e13dcc920cd614a890a051426b9d2b9f120206e | 1,203 | java | Java | fhCoreLite/coreLite/src/main/java/pl/fhframework/core/rules/builtin/CsvRows.java | lukasz2029/fh | 9f2740bedaa31ee6090b176c95eb9b82a55103f6 | [
"Apache-2.0"
] | 6 | 2020-03-03T08:02:39.000Z | 2022-02-14T22:36:13.000Z | fhCoreLite/coreLite/src/main/java/pl/fhframework/core/rules/builtin/CsvRows.java | lukasz2029/fh | 9f2740bedaa31ee6090b176c95eb9b82a55103f6 | [
"Apache-2.0"
] | 16 | 2020-08-04T08:47:34.000Z | 2022-03-29T12:59:14.000Z | fhCoreLite/coreLite/src/main/java/pl/fhframework/core/rules/builtin/CsvRows.java | lukasz2029/fh | 9f2740bedaa31ee6090b176c95eb9b82a55103f6 | [
"Apache-2.0"
] | 11 | 2020-03-01T21:10:20.000Z | 2022-03-11T10:49:56.000Z | 35.382353 | 138 | 0.630091 | 8,403 | package pl.fhframework.core.rules.builtin;
import pl.fhframework.core.rules.BusinessRule;
import java.util.ArrayList;
import java.util.List;
/**
* Changes text CSV-like data into CvsRow list. May be used for filling tables in fast prototyping.
* Input data should contain values for columns separated with semicolon and rows separated with pipe | character.
*/
@BusinessRule(categories = {"collection", "csv"})
public class CsvRows {
/**
* Changes text CSV-like data into CvsRow list. May be used for filling tables in fast prototyping.
* @param csvData Input data that should contain values for columns separated with semicolon and rows separated with pipe | character.
* @return list of csv rows
*/
public List<CsvRow> csvRows(String csvData) {
List<CsvRow> rows = new ArrayList<>();
if (csvData != null && !csvData.isEmpty()) {
for (String rowData : csvData.split("\\|")) {
CsvRow row = new CsvRow();
for (String columnData : rowData.split("\\;")) {
row.getValues().add(columnData);
}
rows.add(row);
}
}
return rows;
}
}
|
3e13dd377f1f5e0f070a37f96fb13e201234e12d | 1,056 | java | Java | app/src/main/java/com/example/osos/moviemahmoud/data/MoviesContract.java | mmahmoudothman/MovieMahmoud | 7bbfadb0e6d4e03b559f9704393acdbf246ffa7d | [
"Apache-2.0"
] | 1 | 2018-10-31T19:59:30.000Z | 2018-10-31T19:59:30.000Z | app/src/main/java/com/example/osos/moviemahmoud/data/MoviesContract.java | mmahmoudothman/MovieMahmoud | 7bbfadb0e6d4e03b559f9704393acdbf246ffa7d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/osos/moviemahmoud/data/MoviesContract.java | mmahmoudothman/MovieMahmoud | 7bbfadb0e6d4e03b559f9704393acdbf246ffa7d | [
"Apache-2.0"
] | null | null | null | 32 | 91 | 0.679924 | 8,404 | package com.example.osos.moviemahmoud.data;
import android.net.Uri;
import android.provider.BaseColumns;
public class MoviesContract {
public static final String CONTENT_AUTHORITY = "com.example.osos.moviemahmoud.data";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_FAVOURITE_MOVIES = "favorite";
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_FAVOURITE_MOVIES)
.build();
public static class FavouriteMoviesEntry implements BaseColumns {
public static final String TABLE_NAME = "movies";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_MOVIE_ID = "movie_id";
public static final String COLUMN_OVERVIEW = "overview";
public static final String COLUMN_POSTER_PATH = "poster_path";
public static final String COLUMN_RATING = "rating";
}
}
|
3e13dd88bd75b658197de7eb7bd897032ebbf005 | 4,112 | java | Java | src/main/java/be/idevelop/fiber/ObjectCreator.java | willemsst/fiber | 5d44faaf83c78b931f9640fc29c43c02030769b4 | [
"MIT"
] | null | null | null | src/main/java/be/idevelop/fiber/ObjectCreator.java | willemsst/fiber | 5d44faaf83c78b931f9640fc29c43c02030769b4 | [
"MIT"
] | 1 | 2021-12-18T17:27:17.000Z | 2021-12-18T17:27:36.000Z | src/main/java/be/idevelop/fiber/ObjectCreator.java | AlexRogalskiy/fiber | 5d44faaf83c78b931f9640fc29c43c02030769b4 | [
"MIT"
] | 1 | 2021-12-18T17:27:10.000Z | 2021-12-18T17:27:10.000Z | 41.959184 | 151 | 0.697714 | 8,405 | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Steven Willems
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package be.idevelop.fiber;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Collection;
import static be.idevelop.fiber.ReferenceResolver.REFERENCE_RESOLVER;
class ObjectCreator {
private Constructor[] constructors;
ObjectCreator() {
this.constructors = new Constructor[Short.MAX_VALUE];
}
public void registerClass(Class clazz, short classId) {
if (!Modifier.isAbstract(clazz.getModifiers())) {
if (Collection.class.isAssignableFrom(clazz)) {
constructors[classId] = getCollectionConstructor(clazz);
} else {
constructors[classId] = getDefaultConstructor(clazz);
}
}
}
@SuppressWarnings("unchecked")
public <T> T createNewInstance(short classId) {
return REFERENCE_RESOLVER.addForDeserialize(createNewInstance((Constructor<T>) constructors[classId]));
}
@SuppressWarnings("unchecked")
public <C extends Collection> C createNewCollectionInstance(short classId, short length) {
return REFERENCE_RESOLVER.addForDeserialize(createNewInstance((Constructor<C>) constructors[classId], length));
}
private <C extends Collection> Constructor<C> getCollectionConstructor(Class<C> clazz) {
Constructor<C> constructor;
try {
constructor = clazz.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("No collection constructor found for class " + clazz.getName() + ". Implement a custom serializer.", e);
}
return constructor;
}
private <T> Constructor<T> getDefaultConstructor(Class<T> clazz) {
Constructor<T> constructor;
try {
constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("No default constructor found for class " + clazz.getName() + ". Implement a custom serializer.", e);
}
return constructor;
}
private <T> T createNewInstance(Constructor<T> constructor, Object... param) {
T t;
try {
t = constructor.newInstance(param);
} catch (InstantiationException e) {
throw new IllegalStateException("Could not invoke default constructor for class " + constructor.getDeclaringClass().getName(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not invoke default constructor for class " + constructor.getDeclaringClass().getName(), e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not invoke default constructor for class " + constructor.getDeclaringClass().getName(), e);
}
return t;
}
}
|
3e13de0af3bbde094bc629d9e66139eaf3d70727 | 231 | java | Java | src/test/java/com/fredo/martinez/kafkaproducer/KafkaProducerApplicationTests.java | tofredi/kafka-producer | 80607a8bef820d71317fbceb5de9b3a6e0138121 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/fredo/martinez/kafkaproducer/KafkaProducerApplicationTests.java | tofredi/kafka-producer | 80607a8bef820d71317fbceb5de9b3a6e0138121 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/fredo/martinez/kafkaproducer/KafkaProducerApplicationTests.java | tofredi/kafka-producer | 80607a8bef820d71317fbceb5de9b3a6e0138121 | [
"Apache-2.0"
] | null | null | null | 16.5 | 60 | 0.800866 | 8,406 | package com.fredo.martinez.kafkaproducer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class KafkaProducerApplicationTests {
@Test
void contextLoads() {
}
}
|
3e13de1b4ab2e34cd8ca3a35f292be2503dd9e2d | 431 | java | Java | src/minecraft/de/chrissx/mods/combat/Reach.java | pixelcmtd/CXClient | be74fc762170ad13d1452895f015062749fb59fb | [
"BSD-3-Clause"
] | 12 | 2021-09-28T07:53:15.000Z | 2022-03-21T16:36:05.000Z | src/minecraft/de/chrissx/mods/combat/Reach.java | pixelcmtd/CXClient | be74fc762170ad13d1452895f015062749fb59fb | [
"BSD-3-Clause"
] | 7 | 2021-12-31T20:14:36.000Z | 2022-01-29T01:14:24.000Z | src/minecraft/de/chrissx/mods/combat/Reach.java | pixelcmtd/CXClient | be74fc762170ad13d1452895f015062749fb59fb | [
"BSD-3-Clause"
] | 2 | 2021-11-28T08:35:34.000Z | 2022-02-01T17:52:03.000Z | 21.55 | 77 | 0.705336 | 8,407 | package de.chrissx.mods.combat;
import de.chrissx.mods.Mod;
import de.chrissx.mods.options.FloatOption;
public class Reach extends Mod {
// TODO: hä?! (according to `PlayerControllerMP`, it isn't 6 in vanilla)
FloatOption range = new FloatOption("range", "The range (6 in Vanilla)", 7);
public Reach() {
super("Reach", "Increases your range");
addOption(range);
}
public float getReach() {
return range.value;
}
}
|
3e13df50f3989a3a0a81a8f78d103d74c17c14a0 | 1,195 | java | Java | kaigian-admin/src/main/java/pers/brian/mall/modules/ums/model/entity/UmsRole.java | Brian9725/kaigian-mall | f31d1a6c418235f94ca8daf6435b874db87d03d8 | [
"Apache-2.0"
] | null | null | null | kaigian-admin/src/main/java/pers/brian/mall/modules/ums/model/entity/UmsRole.java | Brian9725/kaigian-mall | f31d1a6c418235f94ca8daf6435b874db87d03d8 | [
"Apache-2.0"
] | 4 | 2021-11-12T01:47:42.000Z | 2022-01-27T02:41:07.000Z | kaigian-admin/src/main/java/pers/brian/mall/modules/ums/model/entity/UmsRole.java | Brian9725/kaigian-mall | f31d1a6c418235f94ca8daf6435b874db87d03d8 | [
"Apache-2.0"
] | null | null | null | 22.980769 | 55 | 0.725523 | 8,408 | package pers.brian.mall.modules.ums.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.util.Date;
/**
* @Description: <p>
* 后台用户角色表
* </p>
* @Author: BrianHu
* @Create: 2021-11-11 11:11
* @Version: 0.0.1
**/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ums_role")
@ApiModel(value = "UmsRole对象", description = "后台用户角色表")
public class UmsRole implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "描述")
private String description;
@ApiModelProperty(value = "后台用户数量")
private Integer adminCount;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "启用状态:0->禁用;1->启用")
private Integer status;
private Integer sort;
}
|
3e13e1a04a02b15b51a6758e4ff05cda73e6980e | 1,562 | java | Java | src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2D.java | jpaulodiniz/mutated-math | ceddbb0e6e2345b03ea21b62132ed53e905bfdfe | [
"Apache-2.0"
] | 5 | 2018-12-13T17:46:39.000Z | 2022-03-29T02:07:47.000Z | src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2D.java | jpaulodiniz/mutated-math | ceddbb0e6e2345b03ea21b62132ed53e905bfdfe | [
"Apache-2.0"
] | 42 | 2019-12-08T18:41:13.000Z | 2021-08-28T13:08:55.000Z | src/main/java/org/apache/commons/math3/geometry/euclidean/twod/hull/ConvexHullGenerator2D.java | jpaulodiniz/mutated-math | ceddbb0e6e2345b03ea21b62132ed53e905bfdfe | [
"Apache-2.0"
] | 8 | 2018-12-25T04:19:01.000Z | 2021-03-24T17:02:44.000Z | 41.105263 | 106 | 0.783611 | 8,409 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.geometry.euclidean.twod.hull;
import java.util.Collection;
import org.apache.commons.math3.exception.ConvergenceException;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.geometry.euclidean.twod.Euclidean2D;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
import org.apache.commons.math3.geometry.hull.ConvexHullGenerator;
/**
* Interface for convex hull generators in the two-dimensional euclidean space.
*
* @since 3.3
*/
public interface ConvexHullGenerator2D extends ConvexHullGenerator<Euclidean2D, Vector2D> {
/** {@inheritDoc} */
ConvexHull2D generate(Collection<Vector2D> points) throws NullArgumentException, ConvergenceException;
}
|
3e13e1e0d5092ff1ae576e84c7bd5d4c42946260 | 1,140 | java | Java | chat/src/main/java/com/queatz/snappy/chat/actions/AdAdd.java | Queatz/snappy | b2a17cbbc75b93e4036702c5d374dde15c028b6e | [
"Apache-2.0"
] | 3 | 2016-07-13T19:37:50.000Z | 2019-11-24T09:18:13.000Z | chat/src/main/java/com/queatz/snappy/chat/actions/AdAdd.java | Queatz/snappy | b2a17cbbc75b93e4036702c5d374dde15c028b6e | [
"Apache-2.0"
] | null | null | null | chat/src/main/java/com/queatz/snappy/chat/actions/AdAdd.java | Queatz/snappy | b2a17cbbc75b93e4036702c5d374dde15c028b6e | [
"Apache-2.0"
] | null | null | null | 29.230769 | 78 | 0.657018 | 8,410 | package com.queatz.snappy.chat.actions;
import com.queatz.chat.ChatKind;
import com.queatz.chat.ChatWorld;
import com.queatz.earth.EarthField;
import com.queatz.earth.EarthThing;
import com.queatz.snappy.as.EarthAs;
import com.queatz.snappy.chat.ChatSession;
import com.queatz.snappy.shared.chat.AdAddChatMessage;
import com.village.things.PersonMine;
/**
* Created by jacob on 8/9/17.
*/
public class AdAdd extends AdAddChatMessage implements ChatMessage {
@Override
public void got(ChatSession chat) {
ChatWorld world = chat.getChat().getWorld();
EarthThing source = new PersonMine(new EarthAs()).byToken(getToken());
// Must have valid account to post ads
if (source == null) {
return;
}
world.add(world.stage(ChatKind.AD_KIND)
.set(EarthField.GEO, chat.getLocation())
.set(EarthField.SOURCE, source.key().name())
.set(EarthField.NAME, getName())
.set(EarthField.ABOUT, getDescription())
.set(EarthField.TOPIC, getTopic()));
chat.getChat().broadcast(chat, this);
}
}
|
3e13e27de312b5313a197c5397f0a3ee8ee29d4f | 2,045 | java | Java | AuthenticatorApp/src/main/java/com/google/android/apps/authenticator/activity/AddAccountActivity.java | xwc1125/Droid-GoogleAuthenticator | 9be98b3164288e24d379a13f1c24379ce1bfb46f | [
"Apache-2.0"
] | null | null | null | AuthenticatorApp/src/main/java/com/google/android/apps/authenticator/activity/AddAccountActivity.java | xwc1125/Droid-GoogleAuthenticator | 9be98b3164288e24d379a13f1c24379ce1bfb46f | [
"Apache-2.0"
] | null | null | null | AuthenticatorApp/src/main/java/com/google/android/apps/authenticator/activity/AddAccountActivity.java | xwc1125/Droid-GoogleAuthenticator | 9be98b3164288e24d379a13f1c24379ce1bfb46f | [
"Apache-2.0"
] | null | null | null | 27.28 | 95 | 0.664223 | 8,411 | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.authenticator.activity;
import com.google.android.apps.authenticator2.R;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* 添加用户
* <p>
* The page of the "Add account" flow that offers the user to add an account.
* The page offers the user to scan a barcode or manually enter the account details.
*
* @author anpch@example.com (Alex Klyubin)
*/
public class AddAccountActivity extends BaseActivity {
@Override
protected void setContentView(Bundle savedInstanceState) {
setContentView(R.layout.add_other_account);
}
@Override
protected void getBundleExtra() {
}
@Override
protected void initViews() {
findViewById(R.id.scan_barcode).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//二维码扫描
}
});
findViewById(R.id.manually_add_account).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//手动添加用户
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(activity, EnterKeyActivity.class);
startActivity(intent);
}
});
}
@Override
protected void initListeners() {
}
@Override
protected void initData() {
}
}
|
3e13e3f4d64699208a3282f52ef4262cb81ad4d3 | 1,898 | java | Java | core/roboconf-dm/src/main/java/net/roboconf/dm/management/exceptions/CommandException.java | roboconf/roboconf-platform | fb11a69941f790efa614e43bc2cabc1ecb93d49b | [
"Apache-2.0"
] | 25 | 2015-02-10T18:08:14.000Z | 2022-01-07T04:43:53.000Z | core/roboconf-dm/src/main/java/net/roboconf/dm/management/exceptions/CommandException.java | roboconf/roboconf-platform | fb11a69941f790efa614e43bc2cabc1ecb93d49b | [
"Apache-2.0"
] | 701 | 2015-01-05T14:54:48.000Z | 2022-01-27T16:16:26.000Z | core/roboconf-dm/src/main/java/net/roboconf/dm/management/exceptions/CommandException.java | roboconf/roboconf-platform | fb11a69941f790efa614e43bc2cabc1ecb93d49b | [
"Apache-2.0"
] | 12 | 2015-02-05T09:00:14.000Z | 2022-02-21T18:16:57.000Z | 28.328358 | 83 | 0.727608 | 8,412 | /**
* Copyright 2015-2017 Linagora, Université Joseph Fourier, Floralis
*
* The present code is developed in the scope of the joint LINAGORA -
* Université Joseph Fourier - Floralis research program and is designated
* as a "Result" pursuant to the terms and conditions of the LINAGORA
* - Université Joseph Fourier - Floralis research program. Each copyright
* holder of Results enumerated here above fully & independently holds complete
* ownership of the complete Intellectual Property rights applicable to the whole
* of said Results, and may freely exploit it in any manner which does not infringe
* the moral rights of the other copyright holders.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.roboconf.dm.management.exceptions;
/**
* @author Vincent Zurczak - Linagora
*/
public class CommandException extends Exception {
private static final long serialVersionUID = 8416460566241473855L;
/**
* Constructor.
*/
public CommandException() {
// nothing
}
/**
* Constructor.
* @param message
*/
public CommandException( String message ) {
super( message );
}
/**
* Constructor.
* @param cause
*/
public CommandException( Throwable cause ) {
super( cause );
}
/**
* Constructor.
* @param message
* @param cause
*/
public CommandException( String message, Throwable cause ) {
super( message, cause );
}
}
|
3e13e4da0797c947c45e7f49e39e04ab39dcc57c | 348 | java | Java | Aula003VisibilidadeOBjetoeClasse/src/aula002objetoeclasse/Aula002.java | CedricArnaud20/Curso_java | bf65e165c86e083a8c051005c71b0e4419353f5f | [
"MIT"
] | null | null | null | Aula003VisibilidadeOBjetoeClasse/src/aula002objetoeclasse/Aula002.java | CedricArnaud20/Curso_java | bf65e165c86e083a8c051005c71b0e4419353f5f | [
"MIT"
] | null | null | null | Aula003VisibilidadeOBjetoeClasse/src/aula002objetoeclasse/Aula002.java | CedricArnaud20/Curso_java | bf65e165c86e083a8c051005c71b0e4419353f5f | [
"MIT"
] | null | null | null | 16.571429 | 44 | 0.508621 | 8,413 |
package aula002objetoeclasse;
public class Aula002 {
public static void main(String[] args) {
Caneta c1 = new Caneta();
c1.modelo = "BIC cristal";
c1.cor = "azul";
// c1.ponta =;
c1.carga = 80;
// c1.tampada = true;
c1.destampar();
c1.status();
c1.rabiscar();
}
}
|
3e13e4f20e929fcb01635f4abfe8a0dd9dccec3f | 1,513 | java | Java | app/src/main/java/com/example/yzbkaka/kakasports/Soccer/SoccerVSAdapter.java | yzbkaka/kakaSports | b6a1e294cb5dd179ca6892569eed0f20d18604aa | [
"Apache-2.0"
] | 1 | 2019-07-19T05:52:43.000Z | 2019-07-19T05:52:43.000Z | app/src/main/java/com/example/yzbkaka/kakasports/Soccer/SoccerVSAdapter.java | yzbkaka/kakaSports | b6a1e294cb5dd179ca6892569eed0f20d18604aa | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/yzbkaka/kakasports/Soccer/SoccerVSAdapter.java | yzbkaka/kakaSports | b6a1e294cb5dd179ca6892569eed0f20d18604aa | [
"Apache-2.0"
] | null | null | null | 29.096154 | 87 | 0.712492 | 8,414 | package com.example.yzbkaka.kakasports.Soccer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.yzbkaka.kakasports.Match;
import com.example.yzbkaka.kakasports.R;
import java.util.List;
/**
* Created by yzbkaka on 19-7-17.
*/
public class SoccerVSAdapter extends ArrayAdapter<Match> {
private int resourceId;
public SoccerVSAdapter(Context context, int id, List<Match> objetcs){
super(context,id,objetcs);
resourceId = id;
}
@Override
public View getView(int position,View convertView,ViewGroup parent){
final Match match = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
TextView startTime = (TextView)view.findViewById(R.id.start_time); //开始时间
TextView firstTeam = (TextView)view.findViewById(R.id.first_team); //主队
TextView secondTeam = (TextView)view.findViewById(R.id.second_team); //客队
TextView vsGrade = (TextView)view.findViewById(R.id.match_grade); //比分
//WebView webView = (WebView)view.findViewById(R.id.webview); //浏览器
startTime.setText(match.getStartTime());
firstTeam.setText(match.getFirstTeam());
secondTeam.setText(match.getSecondTeam());
vsGrade.setText(match.getVsGrade());
return view;
}
}
|
3e13e53b1b3f8ad0e53deb3941679bde1858fc59 | 418 | java | Java | NetBeansProjects/Contas/src/br/com/caelum/contas/main/DesafioArrayList.java | EhODavi/java-e-orientacao-a-objetos | 123cf7ee41cb1cfd0355bddaf8c233a83bbafdde | [
"MIT"
] | null | null | null | NetBeansProjects/Contas/src/br/com/caelum/contas/main/DesafioArrayList.java | EhODavi/java-e-orientacao-a-objetos | 123cf7ee41cb1cfd0355bddaf8c233a83bbafdde | [
"MIT"
] | null | null | null | NetBeansProjects/Contas/src/br/com/caelum/contas/main/DesafioArrayList.java | EhODavi/java-e-orientacao-a-objetos | 123cf7ee41cb1cfd0355bddaf8c233a83bbafdde | [
"MIT"
] | null | null | null | 19.904762 | 48 | 0.538278 | 8,415 | package br.com.caelum.contas.main;
import java.util.ArrayList;
import java.util.List;
public class DesafioArrayList {
public static void main(String[] args) {
List<Integer> lista = new ArrayList<>();
for (int i = 1; i <= 1000; i++) {
lista.add(new Integer(i));
}
for (int i = 999; i >= 0; i--) {
System.out.println(lista.get(i));
}
}
}
|
3e13e5d8c439d826fd020f45da6a7321f62c8790 | 186 | java | Java | src/test/java/org/ognl/test/objects/BaseIndexed.java | jessepav/ognl | aabba386e1b8969237f1b89ed4f3af39198e8c1a | [
"Apache-2.0"
] | 140 | 2015-02-26T00:15:40.000Z | 2022-03-24T08:21:42.000Z | src/test/java/org/ognl/test/objects/BaseIndexed.java | madz0/ognl2 | e87e3d7b2518a0d44082eb8942e543fb07ef9fb8 | [
"Apache-2.0"
] | 115 | 2015-04-22T18:38:54.000Z | 2022-03-31T11:10:38.000Z | src/test/java/org/ognl/test/objects/BaseIndexed.java | madz0/ognl2 | e87e3d7b2518a0d44082eb8942e543fb07ef9fb8 | [
"Apache-2.0"
] | 78 | 2015-03-18T08:24:53.000Z | 2022-03-04T21:25:58.000Z | 14.307692 | 36 | 0.61828 | 8,416 | package org.ognl.test.objects;
/**
* Class used to test inheritance.
*/
public class BaseIndexed {
public Object getLine(int index)
{
return "line:" + index;
}
}
|
3e13e61d4b975c6bd54de71b4eed3d7699186757 | 2,725 | java | Java | fast-validator/src/main/java/cn/iflyapi/validator/aspect/ValidAspect.java | flyhero/fast-validator | e637b45f895a8290cc0a4f011d402b47c8ec0663 | [
"Apache-2.0"
] | null | null | null | fast-validator/src/main/java/cn/iflyapi/validator/aspect/ValidAspect.java | flyhero/fast-validator | e637b45f895a8290cc0a4f011d402b47c8ec0663 | [
"Apache-2.0"
] | null | null | null | fast-validator/src/main/java/cn/iflyapi/validator/aspect/ValidAspect.java | flyhero/fast-validator | e637b45f895a8290cc0a4f011d402b47c8ec0663 | [
"Apache-2.0"
] | null | null | null | 30.965909 | 89 | 0.622752 | 8,417 | package cn.iflyapi.validator.aspect;
import cn.iflyapi.validator.annotation.*;
import cn.iflyapi.validator.handler.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author flyhero
* @date 2019-03-23 8:44 PM
*/
@Aspect
@Component
public class ValidAspect {
private Map<Class<? extends Annotation>, IHandler> handlerMap = new HashMap<>();
{
handlerMap.put(NotEmpty.class, new NotEmptyHandler());
handlerMap.put(On.class, new OnHandler());
handlerMap.put(OnMax.class, new OnMaxHandler());
handlerMap.put(OnMin.class, new OnMinHandler());
handlerMap.put(Email.class, new EmailHandler());
}
@Pointcut(value = "@within(org.springframework.web.bind.annotation.RestController)" +
"|| @within(org.springframework.stereotype.Controller)")
public void pointcut() {
}
/**
* @param joinPoint
* @return
*/
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
boolean present = parameters[i].isAnnotationPresent(FastValid.class);
if (!present) {
continue;
}
Object targetObj = args[i];
Field[] fields = targetObj.getClass().getDeclaredFields();
//遍历所有的属性
for (Field field : fields) {
Annotation[] annotations = field.getDeclaredAnnotations();
if (null == annotations || annotations.length == 0) {
continue;
}
//遍历属性的所有注解去处理
for (Annotation annotation : annotations) {
Class<? extends Annotation> type = annotation.annotationType();
IHandler iHandler = handlerMap.get(type);
if (!Objects.isNull(iHandler)) {
iHandler.handle(annotation, field, targetObj);
}
}
}
}
return joinPoint.proceed();
}
}
|
3e13e6ae447a2c3bab4cde6c3a34ed315ad09b1b | 2,969 | java | Java | source/tools/src/main/java/com/automic/puppet/actions/AbstractHttpAction.java | Automic-Community/puppet-action-pack | eaea899b4dc73df184070b54a0a2185a5166736f | [
"BSD-4-Clause-UC"
] | null | null | null | source/tools/src/main/java/com/automic/puppet/actions/AbstractHttpAction.java | Automic-Community/puppet-action-pack | eaea899b4dc73df184070b54a0a2185a5166736f | [
"BSD-4-Clause-UC"
] | null | null | null | source/tools/src/main/java/com/automic/puppet/actions/AbstractHttpAction.java | Automic-Community/puppet-action-pack | eaea899b4dc73df184070b54a0a2185a5166736f | [
"BSD-4-Clause-UC"
] | null | null | null | 29.989899 | 120 | 0.664197 | 8,418 | package com.automic.puppet.actions;
import java.net.URI;
import java.net.URISyntaxException;
import com.automic.puppet.config.HttpClientConfig;
import com.automic.puppet.constants.Constants;
import com.automic.puppet.constants.ExceptionConstants;
import com.automic.puppet.exception.AutomicException;
import com.automic.puppet.filter.GenericResponseFilter;
import com.automic.puppet.util.CommonUtil;
import com.automic.puppet.util.ConsoleWriter;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/**
* This class defines the execution of any action.It provides some initializations and validations on common inputs .The
* child actions will implement its executeSpecific() method as per their own need.
*/
public abstract class AbstractHttpAction extends AbstractAction {
/**
* Service end point
*/
protected URI baseUrl;
/**
* Username to connect to Puppet
*/
protected String username;
/**
* Option to skip validation
*/
private boolean skipCertValidation;
/**
* Service end point
*/
private Client client;
public AbstractHttpAction() {
addOption(Constants.BASE_URL, true, "Puppet URL");
addOption(Constants.PUPPET_USERNAME, false, "Username");
addOption(Constants.SKIP_CERT_VALIDATION, false, "Skip SSL validation");
}
/**
* This method initializes the arguments and calls the execute method.
*
* @throws AutomicException
* exception while executing an action
*/
public final void execute() throws AutomicException {
prepareCommonInputs();
try {
executeSpecific();
} finally {
if (client != null) {
client.destroy();
}
}
}
private void prepareCommonInputs() throws AutomicException {
String temp = getOptionValue(Constants.BASE_URL);
try {
this.baseUrl = new URI(temp);
this.username = getOptionValue(Constants.PUPPET_USERNAME);
this.skipCertValidation = CommonUtil.convert2Bool(getOptionValue(Constants.SKIP_CERT_VALIDATION));
} catch (URISyntaxException e) {
ConsoleWriter.writeln(e);
String msg = String.format(ExceptionConstants.INVALID_INPUT_PARAMETER, "URL", temp);
throw new AutomicException(msg);
}
}
/**
* Method to execute the action.
*
* @throws AutomicException
*/
protected abstract void executeSpecific() throws AutomicException;
/**
* Method to initialize Client instance.
*
* @throws AutomicException
*
*/
protected WebResource getClient() throws AutomicException {
if (client == null) {
client = HttpClientConfig.getClient(this.skipCertValidation);
client.addFilter(new GenericResponseFilter());
}
return client.resource(baseUrl);
}
} |
3e13e6b3b5dabcbe8a4153f01143512970350fcc | 389 | java | Java | thermo/chem/src/main/java/gigadot/chom/chem/reader/wml/wmlReaderBase.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 21 | 2021-03-08T01:58:25.000Z | 2022-03-09T15:46:16.000Z | thermo/chem/src/main/java/gigadot/chom/chem/reader/wml/wmlReaderBase.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 63 | 2021-05-04T15:05:30.000Z | 2022-03-23T14:32:29.000Z | thermo/chem/src/main/java/gigadot/chom/chem/reader/wml/wmlReaderBase.java | mdhillmancmcl/TheWorldAvatar-CMCL-Fork | 011aee78c016b76762eaf511c78fabe3f98189f4 | [
"MIT"
] | 15 | 2021-03-08T07:52:03.000Z | 2022-03-29T04:46:20.000Z | 22.882353 | 78 | 0.758355 | 8,419 | package gigadot.chom.chem.reader.wml;
import gigadot.chom.chem.structure.Compound;
import java.io.IOException;
import nu.xom.Document;
import org.apache.log4j.Logger;
/**
*
*
* @author Weerapong Phadungsukanan
*/
public abstract class wmlReaderBase {
Logger logger = Logger.getLogger(getClass());
public abstract void read(Document xml, Compound mDoc) throws IOException;
}
|
3e13e78167b5a1744afa57874e1a6c3921609559 | 2,370 | java | Java | samples/snippets/src/test/java/com/example/bigquery/ExtractModelIT.java | pallabiwrites/java-bigquery | 44720219a8b1394cfe97e358af5e2c8ca36d2436 | [
"Apache-2.0"
] | 61 | 2019-12-12T06:05:43.000Z | 2022-03-16T12:28:17.000Z | samples/snippets/src/test/java/com/example/bigquery/ExtractModelIT.java | pallabiwrites/java-bigquery | 44720219a8b1394cfe97e358af5e2c8ca36d2436 | [
"Apache-2.0"
] | 1,259 | 2019-11-19T20:57:13.000Z | 2022-03-31T20:51:08.000Z | samples/snippets/src/test/java/com/example/bigquery/ExtractModelIT.java | pallabiwrites/java-bigquery | 44720219a8b1394cfe97e358af5e2c8ca36d2436 | [
"Apache-2.0"
] | 84 | 2019-12-06T22:26:25.000Z | 2022-03-22T17:27:09.000Z | 30.384615 | 83 | 0.734599 | 8,420 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.bigquery;
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ExtractModelIT {
private final Logger log = Logger.getLogger(this.getClass().getName());
private ByteArrayOutputStream bout;
private PrintStream out;
private PrintStream originalPrintStream;
private static final String GCS_BUCKET = System.getenv("GCS_BUCKET");
private static void requireEnvVar(String varName) {
assertNotNull(
"Environment variable " + varName + " is required to perform these tests.",
System.getenv(varName));
}
@BeforeClass
public static void checkRequirements() {
requireEnvVar("GCS_BUCKET");
}
@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
originalPrintStream = System.out;
System.setOut(out);
}
@After
public void tearDown() {
// restores print statements in the original method
System.out.flush();
System.setOut(originalPrintStream);
log.log(Level.INFO, bout.toString());
}
@Test
public void testExtractModel() throws InterruptedException {
String projectId = "bigquery-public-data";
String datasetName = "samples";
String modelName = "model";
String destinationUri = "gs://" + GCS_BUCKET + "/extractModel";
// Extract model content to GCS
ExtractModel.extractModel(projectId, datasetName, modelName, destinationUri);
assertThat(bout.toString()).contains("Model extract successful");
}
}
|
3e13e84903243f2ea34e2043082a67ddf4bbce4c | 1,183 | java | Java | polardbx-common/src/main/java/com/alibaba/polardbx/common/TrxIdGenerator.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 480 | 2021-10-16T06:00:00.000Z | 2022-03-28T05:54:49.000Z | polardbx-common/src/main/java/com/alibaba/polardbx/common/TrxIdGenerator.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 31 | 2021-10-20T02:59:55.000Z | 2022-03-29T03:38:33.000Z | polardbx-common/src/main/java/com/alibaba/polardbx/common/TrxIdGenerator.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 96 | 2021-10-17T14:19:49.000Z | 2022-03-23T09:25:37.000Z | 29.575 | 83 | 0.719358 | 8,421 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.common;
public class TrxIdGenerator {
private static final TrxIdGenerator INSTANCE = new TrxIdGenerator();
private volatile IdGenerator idGenerator = IdGenerator.getDefaultIdGenerator();
public static TrxIdGenerator getInstance() {
return INSTANCE;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public long nextId() {
return idGenerator.nextId();
}
}
|
3e13e9657727255ac01c8ab77cf599783daa927c | 2,581 | java | Java | src/main/java/org/orekit/propagation/events/handlers/StopOnDecreasing.java | wardev/orekit | 605339fba0889588f96298deb1564794337a4fb6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/orekit/propagation/events/handlers/StopOnDecreasing.java | wardev/orekit | 605339fba0889588f96298deb1564794337a4fb6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/orekit/propagation/events/handlers/StopOnDecreasing.java | wardev/orekit | 605339fba0889588f96298deb1564794337a4fb6 | [
"Apache-2.0"
] | null | null | null | 43.016667 | 100 | 0.742348 | 8,422 | /* Copyright 2013 Applied Defense Solutions, Inc.
* Licensed to CS Communication & Systèmes (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.propagation.events.handlers;
import org.orekit.errors.OrekitException;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
/** Handle a detection event and choose what to do next.
* <p>The implementation behavior is to {@link
* EventHandler.Action#CONTINUE continue} propagation when ascending and to
* {@link EventHandler.Action#STOP stop} propagation when descending.</p>
*
* @author Hank Grabowski
*
* @param <T> class type for the generic version
* @since 6.1
*/
public class StopOnDecreasing <T extends EventDetector> implements EventHandler<T> {
/** Handle a detection event and choose what to do next.
* <p>The implementation behavior is to {@link
* EventHandler.Action#CONTINUE continue} propagation when ascending and to
* {@link EventHandler.Action#STOP stop} propagation when descending.</p>
* @param s the current state information : date, kinematics, attitude
* @param detector the detector object calling this method (not used in the evaluation)
* @param increasing if true, the value of the switching function increases
* when times increases around event
* @return {@link EventHandler.Action#STOP} or {@link EventHandler.Action#CONTINUE}
* @exception OrekitException if some specific error occurs
*/
public Action eventOccurred(final SpacecraftState s, final T detector, final boolean increasing)
throws OrekitException {
return increasing ? Action.CONTINUE : Action.STOP;
}
/** {@inheritDoc} */
@Override
public SpacecraftState resetState(final T detector, final SpacecraftState oldState)
throws OrekitException {
return oldState;
}
}
|
3e13ea3d1e6bd8f9a702ab511b222bf5e0251e62 | 3,514 | java | Java | mogu_admin/src/main/java/com/moxi/mogublog/admin/restapi/UserRestApi.java | ZJQ070932/mogu_blog_v2 | fac7912c1c00455cbbe501f2ace5d58d40a8647b | [
"Apache-2.0"
] | 1,003 | 2019-04-29T07:06:05.000Z | 2022-03-30T07:38:28.000Z | mogu_admin/src/main/java/com/moxi/mogublog/admin/restapi/UserRestApi.java | ZJQ070932/mogu_blog_v2 | fac7912c1c00455cbbe501f2ace5d58d40a8647b | [
"Apache-2.0"
] | 34 | 2019-12-18T02:21:48.000Z | 2022-03-08T07:21:56.000Z | mogu_admin/src/main/java/com/moxi/mogublog/admin/restapi/UserRestApi.java | ZJQ070932/mogu_blog_v2 | fac7912c1c00455cbbe501f2ace5d58d40a8647b | [
"Apache-2.0"
] | 405 | 2019-06-17T03:58:25.000Z | 2022-03-20T06:17:36.000Z | 36.226804 | 114 | 0.722538 | 8,423 | package com.moxi.mogublog.admin.restapi;
import com.moxi.mogublog.admin.annotion.AuthorityVerify.AuthorityVerify;
import com.moxi.mogublog.admin.annotion.OperationLogger.OperationLogger;
import com.moxi.mogublog.utils.ResultUtil;
import com.moxi.mogublog.xo.service.UserService;
import com.moxi.mogublog.xo.vo.UserVO;
import com.moxi.mougblog.base.exception.ThrowableUtils;
import com.moxi.mougblog.base.validator.group.Delete;
import com.moxi.mougblog.base.validator.group.GetList;
import com.moxi.mougblog.base.validator.group.Insert;
import com.moxi.mougblog.base.validator.group.Update;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 用户表 RestApi
*
* @author 陌溪
* @date 2020年1月4日21:29:09
*/
@RestController
@Api(value = "用户相关接口", tags = {"用户相关接口"})
@RequestMapping("/user")
@Slf4j
public class UserRestApi {
@Autowired
private UserService userService;
@AuthorityVerify
@ApiOperation(value = "获取用户列表", notes = "获取用户列表", response = String.class)
@PostMapping("/getList")
public String getList(@Validated({GetList.class}) @RequestBody UserVO userVO, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
log.info("获取用户列表: {}", userVO);
return ResultUtil.successWithData(userService.getPageList(userVO));
}
@AuthorityVerify
@OperationLogger(value = "新增用户")
@ApiOperation(value = "新增用户", notes = "新增用户", response = String.class)
@PostMapping("/add")
public String add(@Validated({Insert.class}) @RequestBody UserVO userVO, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
log.info("新增用户: {}", userVO);
return userService.addUser(userVO);
}
@AuthorityVerify
@OperationLogger(value = "编辑用户")
@ApiOperation(value = "编辑用户", notes = "编辑用户", response = String.class)
@PostMapping("/edit")
public String edit(@Validated({Update.class}) @RequestBody UserVO userVO, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
log.info("编辑用户: {}", userVO);
return userService.editUser(userVO);
}
@AuthorityVerify
@OperationLogger(value = "删除用户")
@ApiOperation(value = "删除用户", notes = "删除用户", response = String.class)
@PostMapping("/delete")
public String delete(@Validated({Delete.class}) @RequestBody UserVO userVO, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
log.info("删除用户: {}", userVO);
return userService.deleteUser(userVO);
}
@AuthorityVerify
@OperationLogger(value = "重置用户密码")
@ApiOperation(value = "重置用户密码", notes = "重置用户密码", response = String.class)
@PostMapping("/resetUserPassword")
public String resetUserPassword(@Validated({Delete.class}) @RequestBody UserVO userVO, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
log.info("重置用户密码: {}", userVO);
return userService.resetUserPassword(userVO);
}
} |
3e13ea4ba39034e6cf90a6efae4e0da1e22ceae0 | 297 | java | Java | codes/pattern/src/main/java/io/github/dunwu/pattern/bridge/Device.java | dunwu/design | b6890287341af5d821f98948304cf8a6f173e705 | [
"Apache-2.0"
] | 64 | 2018-09-19T10:40:03.000Z | 2022-03-30T00:42:29.000Z | codes/pattern/src/main/java/io/github/dunwu/pattern/bridge/Device.java | dunwu/design | b6890287341af5d821f98948304cf8a6f173e705 | [
"Apache-2.0"
] | 5 | 2021-04-29T08:55:27.000Z | 2021-05-13T03:01:59.000Z | codes/pattern/src/main/java/io/github/dunwu/pattern/bridge/Device.java | dunwu/design | b6890287341af5d821f98948304cf8a6f173e705 | [
"Apache-2.0"
] | 25 | 2018-12-12T15:10:26.000Z | 2022-03-21T09:44:03.000Z | 11.88 | 39 | 0.62963 | 8,424 | package io.github.dunwu.pattern.bridge;
/**
* 所有设备的通用接口
*/
public interface Device {
boolean isEnabled();
void enable();
void disable();
int getVolume();
void setVolume(int percent);
int getChannel();
void setChannel(int channel);
void printStatus();
}
|
3e13eacf0b1763e5dfa6781fa01bde1d42d8cb52 | 1,600 | java | Java | src/test/java/com/github/jh3nd3rs0n/httpshuttle/http1dot1/MessageHeaderTest.java | jh3nd3rs0n/httpshuttle | c5c0603c3b496b5e3efd610f770e56149956d2d0 | [
"MIT"
] | null | null | null | src/test/java/com/github/jh3nd3rs0n/httpshuttle/http1dot1/MessageHeaderTest.java | jh3nd3rs0n/httpshuttle | c5c0603c3b496b5e3efd610f770e56149956d2d0 | [
"MIT"
] | null | null | null | src/test/java/com/github/jh3nd3rs0n/httpshuttle/http1dot1/MessageHeaderTest.java | jh3nd3rs0n/httpshuttle | c5c0603c3b496b5e3efd610f770e56149956d2d0 | [
"MIT"
] | null | null | null | 36.363636 | 78 | 0.71125 | 8,425 | package com.github.jh3nd3rs0n.httpshuttle.http1dot1;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MessageHeaderTest {
@Test
public void testNewRequestInstance() {
MessageHeader<RequestLine> messageHeader1 =
MessageHeader.newRequestInstance(
Method.GET, "/hello.txt", "HTTP/1.1",
HeaderField.newInstance(
"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"),
HeaderField.newInstance("Host", "www.example.com"),
HeaderField.newInstance("Accept-Language", "en, mi"));
MessageHeader<RequestLine> messageHeader2 = MessageHeader.newInstance(
messageHeader1.toByteArray(), RequestLine.class);
assertEquals(messageHeader1, messageHeader2);
}
@Test
public void testNewStatusInstance() {
MessageHeader<StatusLine> messageHeader1 =
MessageHeader.newStatusInstance(
"HTTP/1.1", 200, "OK",
HeaderField.newInstance(
"Date", "Mon, 27 Jul 2009 12:28:53 GMT"),
HeaderField.newInstance("Server", "Apache"),
HeaderField.newInstance(
"Last-Modified", "Wed, 22 Jul 2009 19:15:56 GMT"),
HeaderField.newInstance("ETag", "\"34aa387-d-1568eb00\""),
HeaderField.newInstance("Accept-Ranges", "bytes"),
HeaderField.newInstance("Content-Length", "51"),
HeaderField.newInstance("Vary", "Accept-Encoding"),
HeaderField.newInstance("Content-Type", "text/plain"));
MessageHeader<StatusLine> messageHeader2 = MessageHeader.newInstance(
messageHeader1.toByteArray(), StatusLine.class);
assertEquals(messageHeader1, messageHeader2);
}
}
|
3e13eb6fc81558377eb1be5a2594858affa91d50 | 2,797 | java | Java | src/com/nitya/accounter/web/client/ui/customers/ConsultantCenterAction.java | hariPrasad525/Nitya_Annaccounting | 7e259ea4f53ee508455f6fee487240bea2c9e97d | [
"Apache-2.0"
] | null | null | null | src/com/nitya/accounter/web/client/ui/customers/ConsultantCenterAction.java | hariPrasad525/Nitya_Annaccounting | 7e259ea4f53ee508455f6fee487240bea2c9e97d | [
"Apache-2.0"
] | null | null | null | src/com/nitya/accounter/web/client/ui/customers/ConsultantCenterAction.java | hariPrasad525/Nitya_Annaccounting | 7e259ea4f53ee508455f6fee487240bea2c9e97d | [
"Apache-2.0"
] | null | null | null | 24.535088 | 76 | 0.632463 | 8,426 | package com.nitya.accounter.web.client.ui.customers;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.resources.client.ImageResource;
import com.nitya.accounter.web.client.AccounterAsyncCallback;
import com.nitya.accounter.web.client.Global;
import com.nitya.accounter.web.client.core.ClientItem;
import com.nitya.accounter.web.client.ui.Accounter;
import com.nitya.accounter.web.client.ui.MainFinanceWindow;
import com.nitya.accounter.web.client.ui.core.Action;
public class ConsultantCenterAction extends Action {
private String quickAddText;
private boolean isEditable;
public ConsultantCenterAction() {
super();
//super.setToolTip(Global.get().Customer());
}
public ConsultantCenterAction(String quickAddText) {
super();
//super.setToolTip(Global.get().Customer());
this.quickAddText = quickAddText;
}
public ConsultantCenterAction(ClientItem customer,
AccounterAsyncCallback<Object> callback) {
super();
this.catagory = Global.get().customer();
}
public void run() {
runAsync(data, isDependent);
}
public void runAsync(final Object data, final Boolean isDependent) {
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess() {
NewConsultantCenterView view = new NewConsultantCenterView();
MainFinanceWindow.getViewManager().showView(view, data,
isDependent, ConsultantCenterAction.this);
}
public void onFailure(Throwable e) {
Accounter.showError(Global.get().messages()
.unableToshowtheview());
}
});
// AccounterAsync.createAsync(new CreateViewAsyncCallback() {
//
// @Override
// public void onCreated() {
//
//
// }
//
// });
}
public boolean isCustomerViewEditable() {
return isEditable;
}
// @Override
// public ParentCanvas getView() {
// return this.view;
// }
public ImageResource getBigImage() {
// NOTHING TO DO.
return null;
}
public ImageResource getSmallImage() {
return Accounter.getFinanceMenuImages().newCustomer();
}
// @Override
// public String getImageUrl() {
// return "/images/new_customer.png";
// }
@Override
public String getHistoryToken() {
return "consultantCenter";
}
@Override
public String getHelpToken() {
return "consaltant-center";
}
@Override
public String getCatagory() {
return Global.get().consultants();
}
@Override
public String getText() {
return "Consultant center";
}
}
|
3e13eb96e8a8d96461da90dc7f2bf960bff3cc7d | 7,316 | java | Java | src/main/java/apsh/backend/serviceimpl/TimeServiceImpl.java | APS-H/APS-Backend | 7a41421a977b99a4d190830c79f6977ed9eafb76 | [
"MIT"
] | null | null | null | src/main/java/apsh/backend/serviceimpl/TimeServiceImpl.java | APS-H/APS-Backend | 7a41421a977b99a4d190830c79f6977ed9eafb76 | [
"MIT"
] | 1 | 2020-11-01T03:13:25.000Z | 2020-11-01T03:13:25.000Z | src/main/java/apsh/backend/serviceimpl/TimeServiceImpl.java | APS-H/APS-Backend | 7a41421a977b99a4d190830c79f6977ed9eafb76 | [
"MIT"
] | null | null | null | 35.687805 | 118 | 0.624795 | 8,427 | package apsh.backend.serviceimpl;
import apsh.backend.dto.DeviceDto;
import apsh.backend.dto.ManpowerDto;
import apsh.backend.dto.OrderDto;
import apsh.backend.dto.SystemTime;
import apsh.backend.po.Craft;
import apsh.backend.service.*;
import apsh.backend.util.LogFormatter;
import apsh.backend.util.LogFormatterImpl;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Service
public class TimeServiceImpl implements TimeService, GodService {
@Value("${time-server-url}")
private String timeServerUrl;
private final ScheduleService scheduleService;
private final LegacySystemService legacySystemService;
private final OrderService orderService;
private final HumanService humanService;
private final EquipmentService equipmentService;
private final LogFormatter logger = new LogFormatterImpl(LoggerFactory.getLogger(TimeServiceImpl.class));
@Autowired
public TimeServiceImpl(
@Lazy ScheduleService scheduleService,
@Lazy LegacySystemService legacySystemService,
@Lazy OrderService orderService,
@Lazy HumanService humanService,
@Lazy EquipmentService equipmentService
) {
this.scheduleService = scheduleService;
this.legacySystemService = legacySystemService;
this.orderService = orderService;
this.humanService = humanService;
this.equipmentService = equipmentService;
}
@Override
public void updateTime(SystemTime systemTime) {
if (systemTime.getStartTime() == null && systemTime.getTimeSpeed() == null) {
logger.errorService("updateTime", systemTime, "startTime and timeSpeed cannot be both null");
return;
}
systemTime.setTimestamp(LocalDateTime.now());
saveTime(systemTime, true);
}
@Override
public void setTime(SystemTime systemTime, Boolean startSchedule) {
if (systemTime.getStartTime() == null || systemTime.getTimeSpeed() == null) {
logger.errorService("setTime", systemTime, "startTime or timeSpeed cannot be null");
return;
}
systemTime.setTimestamp(LocalDateTime.now());
saveTime(systemTime, startSchedule);
}
@Override
public SystemTime getTime() {
return loadTime();
}
@Override
public LocalDateTime now() {
SystemTime systemTime = loadTime();
assert systemTime != null;
Duration d = Duration.between(systemTime.getTimestamp(), LocalDateTime.now());
return systemTime.getStartTime().plusMinutes((long) (d.toMinutes() * systemTime.getTimeSpeed()));
}
private void saveTime(SystemTime systemTime, Boolean startSchedule) {
Path path = Paths.get(timeServerUrl);
if (!Files.exists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
logger.errorService("saveTime", systemTime, e.getLocalizedMessage());
return;
}
} else if (systemTime.getStartTime() == null || systemTime.getTimeSpeed() == null) {
SystemTime curTime = loadTime();
if (curTime == null) return;
if (systemTime.getStartTime() == null) {
systemTime.setStartTime(curTime.getStartTime());
} else {
systemTime.setTimeSpeed(curTime.getTimeSpeed());
}
}
try {
PrintWriter pw = new PrintWriter(path.toFile());
pw.println(systemTime.getStartTime() + "," + systemTime.getTimeSpeed() + "," + systemTime.getTimestamp());
pw.flush();
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.errorService("saveTime", systemTime, e.getLocalizedMessage());
}
// 调用排程模块重新计算排程
if (startSchedule) this.godBlessMe(scheduleService);
}
// return null if time recorded illegal
private SystemTime loadTime() {
Path path = Paths.get(timeServerUrl);
if (!Files.exists(path)) {
logger.errorService("loadTime", "", "file `" + timeServerUrl + "` doesn't exist");
return null;
}
List<String> lines;
try {
lines = Files.lines(path).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
logger.errorService("loadTime", "", e.getLocalizedMessage());
return null;
}
if (lines.size() != 1) {
logger.errorService("loadTime", "", "broken file `" + timeServerUrl + "`");
return null;
}
String[] values = lines.get(0).split(",");
try {
return new SystemTime(
LocalDateTime.parse(values[0]),
Double.parseDouble(values[1]),
LocalDateTime.parse(values[2])
);
} catch (Exception ignored) {
return null;
}
}
@Override
public Map<String, Craft> prepareCrafts() {
return legacySystemService.getAllCrafts().parallelStream()
.collect(Collectors.toMap(Craft::getProductionId, c -> c));
}
@Override
public List<ManpowerDto> prepareManPowers() {
return humanService.getAll(Integer.MAX_VALUE, 1).parallelStream()
.map(ManpowerDto::new)
.collect(Collectors.toList());
}
@Override
public List<DeviceDto> prepareDevices() {
return equipmentService.getAll(Integer.MAX_VALUE, 1).parallelStream()
.flatMap(e -> IntStream.range(0, e.getCount()).mapToObj(id -> new DeviceDto(id, e)))
.collect(Collectors.toList());
}
@Override
public List<OrderDto> prepareOrders() {
Map<String, Craft> crafts = prepareCrafts();
return orderService.getAll(Integer.MAX_VALUE, 1).parallelStream()
.map(o -> {
Craft craft = crafts.get(String.valueOf(o.getProductId()));
if (craft == null) {
// 说明该订单生产的物料没有对应的工艺,直接去掉该订单
return null;
}
return new OrderDto(o, craft);
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public Date schedulingStartTime() {
LocalDateTime start = getTime().getStartTime();
return Date.from(LocalDateTime.of(start.toLocalDate(), LocalTime.of(start.getHour(), 0))
.atZone(ZoneId.systemDefault()).toInstant());
}
}
|
3e13ee1d1b3e6d6f02af2d48885f581c18bbf0f2 | 893 | java | Java | src/main/sample/org/eop/mybatis/spring/sample/BlogSample.java | lixinjie1985/spring-jotm | 78300ad442ebf22a9c56e7826b21799b84b6772b | [
"Apache-2.0"
] | null | null | null | src/main/sample/org/eop/mybatis/spring/sample/BlogSample.java | lixinjie1985/spring-jotm | 78300ad442ebf22a9c56e7826b21799b84b6772b | [
"Apache-2.0"
] | null | null | null | src/main/sample/org/eop/mybatis/spring/sample/BlogSample.java | lixinjie1985/spring-jotm | 78300ad442ebf22a9c56e7826b21799b84b6772b | [
"Apache-2.0"
] | null | null | null | 26.264706 | 79 | 0.720045 | 8,428 | package org.eop.mybatis.spring.sample;
import org.eop.mybatis.spring.bean.Blog;
import org.eop.mybatis.spring.mapper.BlogMapper;
/**
* @author lixinjie
*/
public class BlogSample {
public static void main(String[] args) throws Exception {
System.out.println(getBlogWithAuthorPosts());
}
public static Blog saveAuthor() throws Exception {
Blog blog = new Blog(null);
blog.setTitle("我的博客_2");
blog.setAuthorId(33);
int count = SqlHolder.getMapper(BlogMapper.class).saveBlog(blog);
System.out.println(count);
return blog;
}
public static Blog getBlogWithTags() throws Exception {
Blog blog = SqlHolder.getMapper(BlogMapper.class).getBlogWithTags(1);
return blog;
}
public static Blog getBlogWithAuthorPosts() throws Exception {
Blog blog = SqlHolder.getMapper(BlogMapper.class).getBlogWithAuthorPosts(1);
return blog;
}
}
|
3e13f0828825de29ad0f8344f443a52e8152e082 | 5,728 | java | Java | kin-hadoop-core/src/main/java/org/kin/hadoop/common/csv/CSVRecordReader.java | huangjianqin/kin-hadoop | 80303fb17768aec8475fd63889c9a04b9f2100f8 | [
"Apache-2.0"
] | 2 | 2019-09-06T10:30:24.000Z | 2022-02-10T06:06:58.000Z | kin-hadoop-core/src/main/java/org/kin/hadoop/common/csv/CSVRecordReader.java | huangjianqin/kin-hadoop | 80303fb17768aec8475fd63889c9a04b9f2100f8 | [
"Apache-2.0"
] | null | null | null | kin-hadoop-core/src/main/java/org/kin/hadoop/common/csv/CSVRecordReader.java | huangjianqin/kin-hadoop | 80303fb17768aec8475fd63889c9a04b9f2100f8 | [
"Apache-2.0"
] | null | null | null | 29.525773 | 131 | 0.571753 | 8,429 | package org.kin.hadoop.common.csv;
import com.opencsv.CSVParser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.kin.hadoop.common.writable.TextCollectionWritable;
import java.io.*;
import java.util.zip.ZipInputStream;
/**
* Created by huangjianqin on 2017/9/4.
*/
public class CSVRecordReader extends RecordReader<LongWritable, TextCollectionWritable> {
private final CSVParser parser = new CSVParser();
private LongWritable cKey;
private TextCollectionWritable cValue;
private boolean isZipFile;
private long start;
private long pos;
private long end;
protected Reader reader;
private InputStream is;
private CompressionCodecFactory compressionCodeces = null;
public CSVRecordReader() {
}
public CSVRecordReader(InputStream is, Configuration conf) {
try {
init(is, conf);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
FileSplit fileSplit = (FileSplit) inputSplit;
Configuration job = taskAttemptContext.getConfiguration();
start = fileSplit.getStart();
end = start + fileSplit.getLength();
Path file = fileSplit.getPath();
compressionCodeces = new CompressionCodecFactory(job);
CompressionCodec compressionCodec = compressionCodeces.getCodec(file);
FileSystem fs = file.getFileSystem(job);
FSDataInputStream fileIs = fs.open(fileSplit.getPath());
if (compressionCodec != null) {
InputStream is = compressionCodec.createInputStream(fileIs);
end = Long.MAX_VALUE;
} else {
if (start != 0) {
fileIs.seek(start);
}
is = fileIs;
}
pos = start;
init(is, job);
}
private void init(InputStream is, Configuration conf) throws IOException {
isZipFile = conf.getBoolean(CSVInputFormat.IS_ZIPFILE, CSVInputFormat.DEFAULT_ZIP);
if (isZipFile) {
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
zis.getNextEntry();
is = zis;
}
this.is = is;
reader = new BufferedReader(new InputStreamReader(is));
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (cKey == null) {
cKey = new LongWritable();
}
cKey.set(pos);
if (cValue == null) {
cValue = new TextCollectionWritable();
}
while (true) {
if (pos >= end) {
return false;
}
long newSize = 0;
newSize = readLine(cValue);
pos += newSize;
if (newSize == 0) {
if (isZipFile) {
ZipInputStream zis = (ZipInputStream) is;
if (zis.getNextEntry() != null) {
is = zis;
reader = new BufferedReader(new InputStreamReader(is));
continue;
}
}
cKey = null;
cValue = null;
return false;
} else {
return true;
}
}
}
private long readLine(TextCollectionWritable cValue) throws IOException {
//clean tha last csv values
cValue.clear();
//read a line
long readed = 0L;
int i;
StringBuilder sb = new StringBuilder();
while ((i = reader.read()) != -1) {
char c = (char) i;
readed++;
sb.append(c);
if (c == '\n') {
break;
}
}
//have content % \n
if (sb.length() > 0 && sb.indexOf("\n") == sb.length() - 1) {
//remove \n
sb.replace(sb.length() - 1, sb.length(), "");
if (sb.indexOf("\r") == sb.length() - 1) {
//windows下编辑的文件
//remove \r
sb.replace(sb.length() - 1, sb.length(), "");
}
}
String csvLine = sb.toString();
//parser a csvLine and fill the container
for (String csvItem : parser.parseLine(csvLine)) {
cValue.add(new Text(csvItem));
}
return readed;
}
@Override
public LongWritable getCurrentKey() throws IOException, InterruptedException {
return cKey;
}
@Override
public TextCollectionWritable getCurrentValue() throws IOException, InterruptedException {
return cValue;
}
@Override
public float getProgress() throws IOException, InterruptedException {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (pos - start) / (float) (end - start));
}
}
@Override
public void close() throws IOException {
if (reader != null) {
reader.close();
reader = null;
}
if (is != null) {
is.close();
is = null;
}
}
}
|
3e13f0debf44594a0f0b5ad2a18a6841da0fbb10 | 3,470 | java | Java | src/main/java/com/restfb/util/StringJsonUtils.java | ViktorSukhonin/restfb | ceea0eccd654898fabbba7341ee8583a8ffe9339 | [
"MIT"
] | 572 | 2015-02-18T16:32:44.000Z | 2022-03-25T17:25:34.000Z | src/main/java/com/restfb/util/StringJsonUtils.java | ViktorSukhonin/restfb | ceea0eccd654898fabbba7341ee8583a8ffe9339 | [
"MIT"
] | 984 | 2015-02-18T13:39:46.000Z | 2022-02-18T10:05:42.000Z | src/main/java/com/restfb/util/StringJsonUtils.java | ViktorSukhonin/restfb | ceea0eccd654898fabbba7341ee8583a8ffe9339 | [
"MIT"
] | 409 | 2015-02-18T12:18:33.000Z | 2022-03-22T02:32:19.000Z | 34.356436 | 97 | 0.682133 | 8,430 | /*
* Copyright (c) 2010-2021 Mark Allen, Norbert Bartels.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.restfb.util;
/**
* Helper class to encapsulate simple checks used in the DefaultJsonMapper.
*/
public class StringJsonUtils {
private StringJsonUtils() {
throw new IllegalStateException("StringJsonUtils must not be instantiated");
}
public static final String EMPTY_OBJECT = "{}";
/**
* Is the given JSON equivalent to the empty list (<code>[]</code>)?
*
* @param jsonString
* The JSON to check.
* @return {@code true} if the JSON is equivalent to the empty list, {@code false} otherwise.
*/
public static boolean isEmptyList(String jsonString) {
return "[]".equals(jsonString);
}
/**
* Checks if the given String start with a <code>[</code> character, so it may be a JsonArray
*
* @param jsonString
* the JSON to check.
* @return {@code true} if the String may be a JSON Array
*/
public static boolean isList(String jsonString) {
return jsonString != null && jsonString.startsWith("[");
}
/**
* Checks if the given String is equals to the String with the content {@code "null"}
*
* @param jsonString
* the JSON to check.
* @return {@code true} if the String is {@code "null"}
*/
public static boolean isNull(String jsonString) {
return "null".equals(jsonString);
}
/**
* Checks if the given String is equals to the String with the content {@code "false"}
*
* @param jsonString
* the JSON to check.
* @return {@code true} if the String is {@code "false"}
*/
public static boolean isFalse(String jsonString) {
return "false".equals(jsonString);
}
/**
* Checks if the given String start with a <code>{</code> character, so it may be a JsonObject
*
* @param jsonString
* the JSON to check.
* @return {@code true} if the String may be a JSON object
*/
public static boolean isObject(String jsonString) {
return jsonString != null && jsonString.startsWith("{");
}
/**
* Is the given JSON equivalent to the empty object (<code>{}</code>)?
*
* @param jsonString
* The JSON to check.
* @return {@code true} if the JSON is equivalent to the empty object, {@code false} otherwise.
*/
public static boolean isEmptyObject(String jsonString) {
return EMPTY_OBJECT.equals(jsonString);
}
}
|
3e13f13d0af7eb22ee171d5fd5e0efc5f7d5c3ad | 1,745 | java | Java | org/w3c/css/properties/css3/CssFloodOpacity.java | antongolub/w3c-css-validator | 5ff753cfef76e57b1ab798ea5c7b2e0cada1e8ab | [
"W3C-19980720",
"W3C-20150513"
] | 1 | 2021-01-03T19:20:22.000Z | 2021-01-03T19:20:22.000Z | org/w3c/css/properties/css3/CssFloodOpacity.java | antongolub/w3c-css-validator | 5ff753cfef76e57b1ab798ea5c7b2e0cada1e8ab | [
"W3C-19980720",
"W3C-20150513"
] | 1 | 2021-03-03T12:24:09.000Z | 2021-03-03T12:24:09.000Z | org/w3c/css/properties/css3/CssFloodOpacity.java | antongolub/w3c-css-validator | 5ff753cfef76e57b1ab798ea5c7b2e0cada1e8ab | [
"W3C-19980720",
"W3C-20150513"
] | null | null | null | 28.540984 | 85 | 0.626651 | 8,431 | // $Id$
// Author: Yves Lafon <lyhxr@example.com>
//
// (c) COPYRIGHT MIT, ERCIM, Keio, Beihang, 2015.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.css.properties.css3;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.values.CssExpression;
import org.w3c.css.values.CssTypes;
import org.w3c.css.values.CssValue;
/**
* @spec http://www.w3.org/TR/2014/WD-filter-effects-1-20141125/#FloodOpacityProperty
*/
public class CssFloodOpacity extends org.w3c.css.properties.css.CssFloodOpacity {
/**
* Create a new CssFloodOpacity
*/
public CssFloodOpacity() {
value = initial;
}
/**
* Creates a new CssFloodOpacity
*
* @param expression The expression for this property
* @throws org.w3c.css.util.InvalidParamException
* Expressions are incorrect
*/
public CssFloodOpacity(ApplContext ac, CssExpression expression, boolean check)
throws InvalidParamException {
if (check && expression.getCount() > 1) {
throw new InvalidParamException("unrecognize", ac);
}
setByUser();
CssValue val = expression.getValue();
switch (val.getType()) {
case CssTypes.CSS_NUMBER:
case CssTypes.CSS_PERCENTAGE:
value = val;
break;
default:
throw new InvalidParamException("value",
val.toString(),
getPropertyName(), ac);
}
}
public CssFloodOpacity(ApplContext ac, CssExpression expression)
throws InvalidParamException {
this(ac, expression, false);
}
}
|
3e13f16894bcc25f33e93aaa93b0aecc06a7f45d | 3,341 | java | Java | server/impl/src/test/java/com/walmartlabs/concord/server/AbstractDaoTest.java | ekmixon/concord | 0e9380258d525c20fdc1fc8b8543b6fc0e5293c2 | [
"Apache-2.0"
] | 158 | 2018-11-21T12:54:58.000Z | 2022-03-27T01:43:03.000Z | server/impl/src/test/java/com/walmartlabs/concord/server/AbstractDaoTest.java | amithkb/concord | 353af4e5ea3568927b0cec65716bb3f6b1547442 | [
"Apache-2.0"
] | 232 | 2018-12-11T20:34:30.000Z | 2022-03-25T11:23:59.000Z | server/impl/src/test/java/com/walmartlabs/concord/server/AbstractDaoTest.java | billmcchesney1/concord | 5478aeeda738bb625d7a100be550b55df120b611 | [
"Apache-2.0"
] | 91 | 2018-12-11T21:01:42.000Z | 2022-03-24T04:46:14.000Z | 27.61157 | 132 | 0.661179 | 8,432 | package com.walmartlabs.concord.server;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2018 Walmart Inc.
* -----
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =====
*/
import com.codahale.metrics.MetricRegistry;
import com.walmartlabs.concord.db.AbstractDao;
import com.walmartlabs.concord.db.DatabaseConfiguration;
import com.walmartlabs.concord.db.DatabaseModule;
import com.walmartlabs.concord.db.MainDBChangeLogProvider;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.impl.DSL;
import org.junit.After;
import org.junit.Before;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Collections;
public abstract class AbstractDaoTest {
private final boolean migrateDb;
public AbstractDaoTest() {
this(true);
}
public AbstractDaoTest(boolean migrateDb) {
this.migrateDb = migrateDb;
}
private DataSource dataSource;
private Configuration cfg;
@Before
public void initDataSource() {
DatabaseConfiguration cfg = new DatabaseConfigurationImpl("jdbc:postgresql://localhost:5432/postgres", "postgres", "q1", 3);
DatabaseModule db = new DatabaseModule(migrateDb);
this.dataSource = db.appDataSource(cfg, new MetricRegistry(), Collections.singleton(new MainDBChangeLogProvider()));
this.cfg = db.appJooqConfiguration(this.dataSource);
}
@After
public void closeDataSource() throws Exception {
Method m = dataSource.getClass().getMethod("close");
m.invoke(dataSource);
}
protected void tx(AbstractDao.Tx t) {
DSL.using(cfg).transaction(cfg -> {
DSLContext tx = DSL.using(cfg);
t.run(tx);
});
}
protected Configuration getConfiguration() {
return cfg;
}
private static final class DatabaseConfigurationImpl implements DatabaseConfiguration {
private final String url;
private final String username;
private final String password;
private final int maxPoolSize;
private DatabaseConfigurationImpl(String url, String username, String password, int maxPoolSize) {
this.url = url;
this.username = username;
this.password = password;
this.maxPoolSize = maxPoolSize;
}
@Override
public String url() {
return url;
}
@Override
public String username() {
return username;
}
@Override
public String password() {
return password;
}
@Override
public int maxPoolSize() {
return maxPoolSize;
}
@Override
public Duration maxLifetime() {
return Duration.ofSeconds(30);
}
}
}
|
3e13f1deae270689ed177ceed111d0c2f8da9da0 | 550 | java | Java | app/src/main/java/tw/realtime/project/lativtest/DeveloperKey.java | vexonelite/RecyclerSnapTest | 217fc1c0d3da8d10cdd72dc6b58a28137b636d35 | [
"MIT"
] | null | null | null | app/src/main/java/tw/realtime/project/lativtest/DeveloperKey.java | vexonelite/RecyclerSnapTest | 217fc1c0d3da8d10cdd72dc6b58a28137b636d35 | [
"MIT"
] | null | null | null | app/src/main/java/tw/realtime/project/lativtest/DeveloperKey.java | vexonelite/RecyclerSnapTest | 217fc1c0d3da8d10cdd72dc6b58a28137b636d35 | [
"MIT"
] | null | null | null | 28.947368 | 87 | 0.732727 | 8,433 | // Copyright 2014 Google Inc. All Rights Reserved.
package tw.realtime.project.lativtest;
/**
* Static container class for holding a reference to your YouTube Developer Key.
*/
public class DeveloperKey {
/**
* Please replace this with a valid API key which is enabled for the
* YouTube Data API v3 service. Go to the
* <a href="https://console.developers.google.com/">Google Developers Console</a>
* to register a new developer key.
*/
public static final String DEVELOPER_KEY = "AIzaSyD5wxTibtP7P00o0TrA9z9oHvOTks-U_B4";
}
|
3e13f1e83dbb10826189cc2d028f38140f3b8afb | 3,399 | java | Java | sylph-runners/batch/src/test/java/ideal/sylph/runner/batch/TestQuartzScheduling.java | haocode/sylph | cd5d060fec6dd0ac1960c4b9307a11cc98bd6602 | [
"Apache-2.0"
] | 1 | 2018-12-03T07:14:15.000Z | 2018-12-03T07:14:15.000Z | sylph-runners/batch/src/test/java/ideal/sylph/runner/batch/TestQuartzScheduling.java | yangxifi/sylph | f1119d0e663efeed8ec798a51431a43a6204d61d | [
"Apache-2.0"
] | null | null | null | sylph-runners/batch/src/test/java/ideal/sylph/runner/batch/TestQuartzScheduling.java | yangxifi/sylph | f1119d0e663efeed8ec798a51431a43a6204d61d | [
"Apache-2.0"
] | null | null | null | 31.472222 | 136 | 0.694322 | 8,434 | /*
* Copyright (C) 2018 The Sylph Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ideal.sylph.runner.batch;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class TestQuartzScheduling
{
private final static Logger logger = LoggerFactory.getLogger(TestQuartzScheduling.class);
private Scheduler scheduler;
@Before
public void setUp()
throws Exception
{
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.getScheduler();
scheduler.start();
Assert.assertTrue(scheduler.isStarted());
}
@After
public void tearDown()
throws Exception
{
scheduler.shutdown();
Assert.assertTrue(scheduler.isShutdown());
}
@Test
public void testAddJob()
throws SchedulerException
{
JobDetail jobDetail = JobBuilder.newJob(HelloQuartzJob.class)
.withIdentity("testJob", Scheduler.DEFAULT_GROUP)
.build();
String cronExpression = "30/5 * * * * ?"; // 每分钟的30s起,每5s触发任务
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
.build();
scheduler.scheduleJob(jobDetail, cronTrigger);
Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
Assert.assertEquals(1, jobKeys.size());
logger.info("job list:{}",jobKeys);
}
@Test
public void testDelete()
throws InterruptedException, SchedulerException
{
TimeUnit.SECONDS.sleep(1);
logger.info("remove job delayDataSchdule");
scheduler.deleteJob(JobKey.jobKey("testJob"));
Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.anyGroup());
Assert.assertEquals(0, jobKeys.size());
}
public static class HelloQuartzJob
implements Job
{
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException
{
logger.info("HelloQuartzJob ....FireTime:{} , ScheduledFireTime:{}", context.getFireTime(), context.getScheduledFireTime());
}
}
}
|
3e13f1f041f1b1c129de4c1b0aa5a39abf2aef46 | 3,071 | java | Java | azure-spring-cloud/piggymetrics/notification-service/src/test/java/com/piggymetrics/notification/controller/RecipientControllerTest.java | a-dvukovic/PiggyMetrics-Improved | c12c69054966c7b13622a6336f85d7c5654c7444 | [
"MIT"
] | null | null | null | azure-spring-cloud/piggymetrics/notification-service/src/test/java/com/piggymetrics/notification/controller/RecipientControllerTest.java | a-dvukovic/PiggyMetrics-Improved | c12c69054966c7b13622a6336f85d7c5654c7444 | [
"MIT"
] | null | null | null | azure-spring-cloud/piggymetrics/notification-service/src/test/java/com/piggymetrics/notification/controller/RecipientControllerTest.java | a-dvukovic/PiggyMetrics-Improved | c12c69054966c7b13622a6336f85d7c5654c7444 | [
"MIT"
] | null | null | null | 35.252874 | 156 | 0.811542 | 8,435 | package com.piggymetrics.notification.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.notification.domain.Frequency;
import com.piggymetrics.notification.domain.NotificationSettings;
import com.piggymetrics.notification.domain.NotificationType;
import com.piggymetrics.notification.domain.Recipient;
import com.piggymetrics.notification.service.RecipientService;
import com.sun.security.auth.UserPrincipal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class RecipientControllerTest {
private static final ObjectMapper mapper = new ObjectMapper();
@InjectMocks
private RecipientController recipientController;
@Mock
private RecipientService recipientService;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(recipientController).build();
}
@Test
public void shouldSaveCurrentRecipientSettings() throws Exception {
Recipient recipient = getStubRecipient();
String json = mapper.writeValueAsString(recipient);
mockMvc.perform(put("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())).contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
@Test
public void shouldGetCurrentRecipientSettings() throws Exception {
Recipient recipient = getStubRecipient();
when(recipientService.findByAccountName(recipient.getAccountName())).thenReturn(recipient);
mockMvc.perform(get("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())))
.andExpect(jsonPath("$.accountName").value(recipient.getAccountName()))
.andExpect(status().isOk());
}
private Recipient getStubRecipient() {
NotificationSettings remind = new NotificationSettings();
remind.setActive(true);
remind.setFrequency(Frequency.WEEKLY);
remind.setLastNotified(null);
NotificationSettings backup = new NotificationSettings();
backup.setActive(false);
backup.setFrequency(Frequency.MONTHLY);
backup.setLastNotified(null);
Recipient recipient = new Recipient();
recipient.setAccountName("test");
recipient.setEmail("nnheo@example.com");
recipient.setScheduledNotifications(ImmutableMap.of(
NotificationType.BACKUP, backup,
NotificationType.REMIND, remind
));
return recipient;
}
} |
3e13f23274fe204659804b4492e751b656223f5f | 437 | java | Java | ui-mode/src/main/java/com/aliya/uimode/apply/ApplyDrawableTop.java | a-liYa/AndroidUiMode | 9c5b2a5b6ef98ca8cb76dea5b343947754ac670b | [
"Apache-2.0"
] | 21 | 2017-06-30T08:22:19.000Z | 2022-02-07T14:28:50.000Z | ui-mode-2.x/src/main/java/com/aliya/uimode/apply/ApplyDrawableTop.java | Androidliuchen/AndroidUiMode-master | 41161d2ef2e1d4fc1796d1795c5f64e2113d9f08 | [
"Apache-2.0"
] | 2 | 2019-02-13T01:43:32.000Z | 2021-06-07T15:48:50.000Z | ui-mode-2.x/src/main/java/com/aliya/uimode/apply/ApplyDrawableTop.java | Androidliuchen/AndroidUiMode-master | 41161d2ef2e1d4fc1796d1795c5f64e2113d9f08 | [
"Apache-2.0"
] | 2 | 2018-03-26T08:55:41.000Z | 2021-01-23T09:57:53.000Z | 23 | 70 | 0.736842 | 8,436 | package com.aliya.uimode.apply;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
/**
* 应用android:drawableTop {@link TextView}
*
* @author a_liYa
* @date 2017/6/26 12:33.
*/
public final class ApplyDrawableTop extends AbsApplyTextViewDrawable {
@Override
protected void setDrawablePolicy(TextView v, Drawable drawable) {
setCompoundDrawablesPolicy(v, null, drawable, null, null);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.