hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
49b965b1e01ae130ad8b358318e696c6da2ddb61 | 2,369 | package org.gusdb.wdk.model.user.dataset;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.gusdb.wdk.model.WdkModel;
import org.gusdb.wdk.model.WdkModelBase;
import org.gusdb.wdk.model.WdkModelException;
public class UserDatasetTypeHandlerPlugin extends WdkModelBase {
private String implementationClass;
private String type;
private String version;
private UserDatasetTypeHandler typeHandler;
public UserDatasetTypeHandler getTypeHandler() { return typeHandler; }
/**
* @return the implementation
*/
public String getImplementation() {
return implementationClass;
}
/**
* @param implementation
* the implementation to set
*/
public void setImplementation(String implementation) {
this.implementationClass = implementation;
}
public void setType(String type) { this.type = type; }
public String getType() { return type; }
public void setVersion(String version) { this.version = version; }
public String getVersion() { return version; }
/**
* @see org.gusdb.wdk.model.WdkModelBase#resolveReferences(WdkModel)
*/
@Override
public void resolveReferences(WdkModel wodkModel) throws WdkModelException {
// try to find implementation class
String msgStart = "Implementation class for userDatasetTypeHandlerPlugin [" + getImplementation() + "] ";
try {
Class<?> implClass = Class.forName(getImplementation());
if (!UserDatasetTypeHandler.class.isAssignableFrom(implClass))
throw new WdkModelException(msgStart + "must implement " + UserDatasetTypeHandler.class.getName());
Constructor<?> constructor = implClass.getConstructor();
typeHandler = (UserDatasetTypeHandler) constructor.newInstance();
if (!typeHandler.getUserDatasetType().getName().equals(type) || !typeHandler.getUserDatasetType().getVersion().equals(version))
throw new WdkModelException(msgStart + " is not compatible with " + type + " " + version);
}
catch (ClassNotFoundException e) {
throw new WdkModelException(msgStart + "cannot be found.", e);
}
catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new WdkModelException(msgStart + "cannot be constructed.", e);
}
}
}
| 34.838235 | 162 | 0.736598 |
44db12d01c5bee1f79020cbaf25bbc987624bc70 | 878 | package prune.feature.csv;
import java.io.File;
import java.io.IOException;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.featureselection.ranking.RecursiveFeatureEliminationSVM;
import net.sf.javaml.featureselection.scoring.GainRatio;
import net.sf.javaml.tools.data.FileHandler;
public class RankFeature {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
/* Load the iris data set */
Dataset data = FileHandler.loadDataset(new File("/home/mihirshekhar/Desktop/Kaggle/Preprocessed_avg_pr.csv"), 18, ",");
GainRatio ga = new GainRatio();
/* Apply the algorithm to the data set */
ga.build(data);
/* Print out the score of each attribute */
for (int i = 0; i < ga.noAttributes(); i++)
System.out.println(i+" "+ga.score(i));
}
}
| 28.322581 | 127 | 0.676538 |
69208059b694699518a42e8a301d23eafc933de6 | 6,112 | package com.example.todolist.ui.fragment;
import android.app.AlarmManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.todolist.AddTipActivity;
import com.example.todolist.Adpter.AddDataAdapter;
import com.example.todolist.AlarmActivity;
import com.example.todolist.HomeActivity;
import com.example.todolist.R;
import com.example.todolist.logic.dao.Target;
import com.example.todolist.service.LongRunningService;
import com.example.todolist.ui.RecyclerItemDecoration;
import org.litepal.LitePalApplication;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class AddTipFragment extends android.app.Fragment {
//InputMethodManager对输入法的控制
private InputMethodManager imm;
private EditText editText;
//private ClickListener mListener;
private RecyclerView rvAddNewView;
private List<String> addViewed = new ArrayList<>(16);
int i = 0;
private AddDataAdapter addDataAdapter;
private EditText et;
private TextView tv;
private TimePicker mTimePicker;
private View view;
//获取目标时间
private String mTimeTarget;
private long mTimeTargetSecond;
//获取目标任务
private String mTaskTarget;
private long timeTarget;
// List<Target>targets;
Target target = new Target();
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_add_tip, container, false);
initItem();
initTp();
return view;
}
private void initItem() {
rvAddNewView = view.findViewById(R.id.rv_add_new_view);
GridLayoutManager linearLayoutManager = new GridLayoutManager(LitePalApplication.getContext(), 4);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvAddNewView.setLayoutManager(linearLayoutManager);
addDataAdapter = new AddDataAdapter(addViewed);
rvAddNewView.addItemDecoration(new RecyclerItemDecoration(20, 4));
rvAddNewView.setAdapter(addDataAdapter);
addDataAdapter.setLongClickListenerRemove(new AddDataAdapter.LongClickListenerRemove() {
@Override
public void setLongClickListener(View view) {
addViewed.remove(rvAddNewView.getChildLayoutPosition(view));
addDataAdapter.notifyDataSetChanged();
target.delete();
}
});
et = view.findViewById(R.id.et);
tv = view.findViewById(R.id.tv);
/**
* 空指针的原因,对应的id都不在activity_add_tip里,都在fragment里
* !!!
* */
addDataAdapter.setAddDataListener(new AddDataAdapter.AddDataListener() {
@Override
public void onAddDataListener(int position) {
if (et.getText().toString() == null) {
Toast.makeText(getActivity(), "关键字为空", Toast.LENGTH_SHORT);
} else {
Intent intent = new Intent(getActivity(), HomeActivity.class);
intent.putExtra("task", et.getText().toString());
mTaskTarget = et.getText().toString();
target.setTaskTarget(mTaskTarget);
target.setTimeTarget(mTimeTarget);
target.setProcess(timeTarget);
target.save();
i++;
addViewed.add(mTimeTarget+" "+mTaskTarget);
addDataAdapter.notifyDataSetChanged();
}
}
});
}
// @RequiresApi(api = Build.VERSION_CODES.M)
private void initTp(){
mTimePicker = view.findViewById(R.id.tp);
//设置点击时间不弹键盘
mTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
//设置显示时间为24小时
mTimePicker.setIs24HourView(true);
//获取当前选择的时间
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int i, int i1) {
mTimeTarget = i+"时"+i1+"分";
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
// calendar.set(Calendar.HOUR_OF_DAY,mTimePicker.getCurrentHour());
// calendar.set(Calendar.MINUTE,mTimePicker.getCurrentMinute());
// mTimeTargetSecond = calendar.getTimeInMillis();
calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE),mTimePicker.getCurrentHour(),mTimePicker.getCurrentMinute());
timeTarget = SystemClock.elapsedRealtime()+calendar.getTimeInMillis() - now.getTimeInMillis();
}
});
/**
* 好像有api在,自动把当前时间设好
* */
//设置当前小时
//mTimePicker.setHour(8);
//设置当前分钟(0-59)
//mTimePicker.setMinute(10);
}
}
| 35.534884 | 176 | 0.661976 |
7ba4b928b62a52470d620fbfa490f06e486275cc | 9,047 | package net.herit.iot.onem2m.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.herit.iot.message.onem2m.format.Enums.CONTENT_TYPE;
import net.herit.iot.onem2m.ae.emul.AppEmulatorHttpListener;
import net.herit.iot.onem2m.ae.emul.AppEmulatorNotiHandler;
import net.herit.iot.onem2m.ae.emul.Constants;
import net.herit.iot.onem2m.ae.lib.AEController;
import net.herit.iot.onem2m.ae.lib.LGUAuthController;
import net.herit.iot.onem2m.ae.lib.dto.LGUAuthData;
import net.herit.iot.onem2m.ae.lib.dto.LGUAuthData.Http;
import net.herit.iot.onem2m.core.util.LogManager;
import net.herit.iot.onem2m.resource.AE;
import net.herit.iot.onem2m.resource.AccessControlPolicy;
import net.herit.iot.onem2m.resource.Subscription.NOTIFICATIONCONTENT_TYPE;
public class AppEmulator {
private LogManager logManager = LogManager.getInstacne();
private Logger log = LoggerFactory.getLogger(AppEmulator.class);
//
// AE 정보 - 미리 가지고 있어야 함.
//
private String aeId = Constants.AS_ENTITY_ID;
private String aeName = Constants.AS_AE_NAME;
private String appId = Constants.AS_APP_ID;
private String appName = Constants.AS_APP_NAME;
//
// AE가 접속할 CSE정보 - 미리 가지고 있어야 함.
//
private String cseAddr = Constants.CSE_ADDR;
private String csebase = Constants.CSE_ID +"/"+ Constants.CSE_BASENAME;
private String csebaseName = Constants.CSE_BASENAME;
private String cseId = Constants.CSE_ID;
// AE IP 주소: Notification 수신에 사용됨
private String ip;
// AE 포트 번호: Notification 수신에 사용됨
private int port;
// CSE가 AE에 Notification 요청을 전송할때 사용하는 네트워크 주소, 예:http://10.101.101.111:8080
// - 서버에 등록되는 AE의 속성 정보임
private String poa = "http://116.124.171.3:9902";
// AE가 구독요청(subscription)을 걸때 Notification 지정하는 Notification 수신 주소
// - AE의 poa와는 별도로 구독별로 지정할 수 있음
// # LGU+는 구독별 notificationUri설정을 허용하지 않으며, notificationUri대신에 AE-ID를 셋팅하여 POA로만 Notification을 수신하도록 함
private String notificationUri = "http://10.101.101.180:9902";
// AE로서 CSE를 연동하는 기능을 제공하는 오브젝트
private AEController aeController;
// LGU+ 인증정보 연동 기능을 제공하는 오브젝트
private LGUAuthController authController;
// Notification 메시지를 처리하는 핸들러 클래스
private AppEmulatorNotiHandler notiHandler;
// HTTP 서버 수신 메시지를 처리하는 핸들러 클래스
private AppEmulatorHttpListener httpListener;
// AE 정보 오브젝트
private AE ae;
// LGU+ 인증연동을 위한 파라미터 정보 - 미리 제공받아야 함
private final String mefAddr = "http://106.103.234.198/mef";
private final String deviceModel = "kidswatch1";
private final String serviceCode = "0078";
private final String m2mmType = "20";
private final String deviceSn = "00000000000000000301";
private final String mac = "";
private final String ctn = "0109999999";
private final String deviceType = "adn";
private final String iccId = "A244A1";
public AppEmulator(String ip, int port) {
try {
this.poa = "http://"+ip+":"+port;
this.notificationUri = "http://"+ip+":"+port+"/notify";
this.ip = ip;
this.port = port;
logManager.initialize(LoggerFactory.getLogger("IITP-IOT-APP-AE"), null);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getCiNotificationUri() {
return notificationUri;
}
public void start() throws Exception {
this.authController = new LGUAuthController(mefAddr, deviceModel, serviceCode, m2mmType, deviceSn, mac, ctn, deviceType, iccId);
// 임시 테스트용 코드
// - 인증결과 정보를 미리 입력하면 authController가 인증서버 연동을 수행하지 않고 제공받은 인증정보를 사용함.
// - 인증서버 연동기능이 테스트되지 않았으므로 임시로 제공받은 인증정보를 활용해서 서버 연동 시험 진행해야함
LGUAuthData authData = new LGUAuthData();
Http httpAuth = new Http();
httpAuth.setEnrmtKey("test");
httpAuth.setEntityId(Constants.AS_ENTITY_ID);
httpAuth.setToken(Constants.AS_AUTH_TOKEN);
authData.setHttp(httpAuth);
authData.setKeId(Constants.AS_AUTH_KEID);
authData.setDeviceModel(Constants.AS_DEVICE_MODEL);
authData.setNetworkInfo(Constants.AS_NETWORK_INFO);
this.authController.setPreSharedAuthData(authData);
// 컨트롤러 및 핸들러 객체 생성
this.aeController = new AEController(cseAddr, cseId, csebaseName, CONTENT_TYPE.RES_XML, authController);
notiHandler = new AppEmulatorNotiHandler(aeController);
httpListener = new AppEmulatorHttpListener(ip, port, aeController, notiHandler);
// Notification 수신을 위한 HTTP 서버 시작
//
// # 애뮬레이터에 사용된 서버는 애뮬레이터 테스트용으로 제작되었으며 상용서버에서는 별도의 WAS 또는 HTTP 어뎁터를 이용하여 HTTP 서버 기능을 구현해야 함!!!!
httpListener.start();
// AE 등록 수행
// - 이미 등록된 경우는 등록된 정보를 조회함
this.ae = aeController.doCreateAE(this.csebase, this.aeId, this.aeName, this.appId, this.appName, this.poa, true);
// ACP 생성
List<String> oriIds = new ArrayList<String>();
oriIds.add(ae.getResourceID());
AccessControlPolicy acp = aeController.doCreateACP(ae.getUri(), this.aeId, "acp-"+ae.getResourceID(), oriIds, 63, oriIds, 63, true);
List<String> acpIds = new ArrayList<String>();
acpIds.add(acp.getResourceID());
while (true) {
System.out.println("Enter command!");
System.out.println("'r:[deviceName]' - device registration");
System.out.println("'s:[deviceName]' [switch status('ON'/'OFF')] - switch control");
System.out.println("'u:[PointOfAccess]' - update PointOfAccess");
System.out.println("'bye': Exit");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
try{
if (s.equalsIgnoreCase("BYE")) {
break;
}
System.out.println(s);
if (s.startsWith("r:")) {
//
// 디바이스에 대한 구독(Subscription) 신청
// - 처음 디바이스가 등록되었을 때 해당 디바이스의 상태를 수신하기 위해서 1회 구독 신청하여야 함
// - 일반적으로 사용자의 디바이스 등록 또는 프로비저닝 단계에서 실행됨
//
String deviceName;
deviceName = s.substring(2);
String aeUri = this.csebase+"/"+deviceName;
//AE ae = aeController.doRetrieveAE(aeUri);
// aeController.doContainerSubscription(aeUri + "/"+Constants.CNT_SWITCH, this.aeId, this.aeId, NOTIFICATIONCONTENT_TYPE.ALL_ATRRIBUTES.Value());
// aeController.doContainerSubscription(aeUri + "/"+Constants.CNT_PHONEBOOK, this.aeId, this.aeId, NOTIFICATIONCONTENT_TYPE.RESOURCE_ID.Value());
// aeController.doContainerSubscription(aeUri + "/"+Constants.CNT_TEMPERATURE, this.aeId, this.aeId, NOTIFICATIONCONTENT_TYPE.ALL_ATRRIBUTES.Value());
// aeController.doContainerSubscription(aeUri + "/"+Constants.CNT_SWITCH_RES, this.aeId, this.aeId, NOTIFICATIONCONTENT_TYPE.ALL_ATRRIBUTES.Value());
aeController.doCreateSubscription(aeUri + "/"+Constants.CNT_SWITCH, this.aeId, "/sub-"+this.ae.getResourceName().replace("-", "_"), this.getCiNotificationUri(), NOTIFICATIONCONTENT_TYPE.ALL_ATRRIBUTES.Value(), acpIds, true);
aeController.doCreateSubscription(aeUri + "/"+Constants.CNT_PHONEBOOK, this.aeId, "/sub-"+this.ae.getResourceName().replace("-", "_"), this.getCiNotificationUri(), NOTIFICATIONCONTENT_TYPE.RESOURCE_ID.Value(), acpIds, true);
aeController.doCreateSubscription(aeUri + "/"+Constants.CNT_TEMPERATURE, this.aeId, "/sub-"+this.ae.getResourceName().replace("-", "_"), this.getCiNotificationUri(), NOTIFICATIONCONTENT_TYPE.ALL_ATRRIBUTES.Value(), acpIds, true);
aeController.doCreateSubscription(aeUri + "/"+Constants.CNT_SWITCH_RES, this.aeId, "/sub-"+this.ae.getResourceName().replace("-", "_"), this.getCiNotificationUri(), NOTIFICATIONCONTENT_TYPE.ALL_ATRRIBUTES.Value(), acpIds, true);
} else if (s.startsWith("s:")) {
//
// 스위치 제어 명령을 전송하는 예제
// - 스위치 제어 명령 전송을 위해서 정의된 CNT_SWITCH_CMD 컨테이너에 contentInstance를 생성하여 제어명령을 전송함
// - 디바이스는 제어명령 수신을 위해서 CNT_SWITCH_CMD 컨테이너에 대해서 구독하고 있어야 함
// - 제어결과는 별도의 컨테이너(CNT_SWITCH_RES)를 통해서 수신하므로 AS는 제어명령을 보내기 전에 결과 수신 컨테이너를 구독하고 있어야 함
// - 제어전송 및 결과 수신은 별도의 메시지 요청/전송을 통해서 일어나므로 해당 메시지에 대한 매핑은 AS에서 구현하여야 함
//
String temp = s.substring(2);
String[] tokens = temp.split(" ");
if (tokens.length != 2) {
System.out.println("Invalid command: "+s);
continue;
}
aeController.doCreateContentInstance(this.csebase+"/"+ tokens[0] +"/"+Constants.CNT_SWITCH_CMD, Constants.CNT_SWITCH_CMD, this.aeId, tokens[1]);
} else if (s.startsWith("u:")) {
//
// AE poa 정보 업데이트 예
// - 입력된 poa정보를 IN-CSE에 전송함
//
String pb = s.substring(2);
aeController.doUpdateAEPoa(this.ae.getUri(), this.aeId, pb);
} else {
System.out.println("Unknown command: "+s);
continue;
}
}
catch(IOException e)
{
System.out.println("Invalid command: "+s);
e.printStackTrace();
continue;
}
}
httpListener.stop();
}
private String getNotificationUri() {
return "http://"+Constants.AS_IP+":"+Constants.AS_PORT+"/notify";
}
// 에뮬레이트 실행 함수
public static void main(String[] args) throws Exception {
new AppEmulator(Constants.AS_IP, Constants.AS_PORT).start();
}
}
| 37.077869 | 234 | 0.700453 |
1f5e9c69609d99a1902d29d4b0e817359fa591d1 | 1,920 | package kassandraApp;
import org.salespointframework.core.DataInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import kassandraApp.model.AudioGuide;
import kassandraApp.model.EventCatalog;
import kassandraApp.model.GreatHall;
import kassandraApp.model.LittleHall;
import kassandraApp.model.Play;
import kassandraApp.model.Tour;
@Component
public class EventDataInitializer implements DataInitializer {
private final EventCatalog eventCatalog;
@Autowired
public EventDataInitializer(EventCatalog eventCatalog){
this.eventCatalog = eventCatalog;
}
@Override
public void initialize() {
this.eventCatalog.save(new AudioGuide("Audioguide", 10));
this.eventCatalog.save(new Play("Schneewittchen", 10, GreatHall.getInstance()));
this.eventCatalog.save(new Play("Winnie Pooh", 8, GreatHall.getInstance()));
this.eventCatalog.save(new Play("Phantom der Oper", 12, LittleHall.getInstance()));
this.eventCatalog.save(new Play("König der Löwen", 20, GreatHall.getInstance()));
this.eventCatalog.save(new Tour("Führung", 12, "Marc Munzert"));
this.eventCatalog.findByName("Führung").iterator().next().addAppointment(2015, 11, 22, 20, 15, 2015, 11, 22, 22, 15, false, false);
this.eventCatalog.findByName("Schneewittchen").iterator().next().addAppointment(2015, 11, 22, 20, 15, 2015, 11, 22, 22, 15, false, false);
this.eventCatalog.findByName("Winnie Pooh").iterator().next().addAppointment(2015, 2, 10, 20, 15, 2015, 2, 10, 22, 15, false, false);
this.eventCatalog.findByName("Phantom der Oper").iterator().next().addAppointment(2015, 6, 1, 20, 15, 2015, 6, 1, 21, 45, false, false);
this.eventCatalog.findByName("König der Löwen").iterator().next().addAppointment(2015, 10, 12, 20, 15, 2015, 11, 12, 22, 00, false, false);
this.eventCatalog.findByName("König der Löwen").iterator().next().setExpired();
}
}
| 43.636364 | 141 | 0.754688 |
1aea0d8b0b2b99b4b05c366c0084370b6da65e46 | 928 | /*
* Copyright (c) 2010-2017, sikuli.org, sikulix.com - MIT license
*/
package org.jdesktop.swingx.tips;
import org.jdesktop.swingx.tips.TipOfTheDayModel.Tip;
/**
* Default {@link org.jdesktop.swingx.tips.TipOfTheDayModel.Tip} implementation.<br>
*
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public class DefaultTip implements Tip {
private String name;
private Object tip;
public DefaultTip() {
}
public DefaultTip(String name, Object tip) {
this.name = name;
this.tip = tip;
}
@Override
public Object getTip() {
return tip;
}
public void setTip(Object tip) {
this.tip = tip;
}
@Override
public String getTipName() {
return name;
}
public void setTipName(String name) {
this.name = name;
}
@Override
public String toString() {
return getTipName();
}
}
| 18.196078 | 84 | 0.615302 |
eef1ada79e433330fd47070b6221cf0df4c2aeed | 561 | package concurrency_patterns;
import org.junit.jupiter.api.Test;
public class TestLeaderFollower {
@Test
void test_single_thread_server() throws Exception {
SingleThreadServer sts = new SingleThreadServer();
sts.start();
}
@Test
void test_half_sync_half_async_server() throws Exception {
HalfSyncHalfAsyncServer server = new HalfSyncHalfAsyncServer();
server.start();
}
@Test
void test_leader_follower_server() throws Exception {
LeaderFollowerServer server = new LeaderFollowerServer();
server.start();
Thread.sleep(100 * 1000);
}
} | 22.44 | 65 | 0.768271 |
1009bb1732531f9edcaa8e6c1f1be25657f553bc | 278 | package com.thaiopensource.xml.dtd.om;
public abstract class EnumGroupMember {
public static final int ENUM_VALUE = 0;
public static final int ENUM_GROUP_REF = 1;
public abstract int getType();
public abstract void accept(EnumGroupVisitor visitor) throws Exception;
}
| 27.8 | 73 | 0.784173 |
7daf380e9aedd150dafde60643e6491a45dc132b | 1,123 | package com.optimaize.wanakana;
/**
* Converts Katakana syllables to Hiragana.
* The conversion is 1:1.
*/
public class KatakanaToHiraganaConverter implements Converter {
private KatakanaToHiraganaConverter() {
}
private static final KatakanaToHiraganaConverter INSTANCE = new KatakanaToHiraganaConverter();
public static KatakanaToHiraganaConverter getInstance() {
return INSTANCE;
}
/**
* Coverts Katakana script to Hiragana script
*/
@Override
public String convert(String kata) {
int unicode;
StringBuilder hiragana = new StringBuilder();
for (int i = 0; i < kata.length(); i++) {
char katakanaChar = kata.charAt(i);
if (Scriber.getInstance().isCharKatakana(katakanaChar)) {
unicode = katakanaChar;
unicode += Constants.HIRAGANA_START - Constants.KATAKANA_START;
hiragana.append(String.valueOf(Character.toChars(unicode)));
} else {
hiragana.append(katakanaChar);
}
}
return hiragana.toString();
}
}
| 26.116279 | 98 | 0.627783 |
f0f017a4a5ab93072095c065368127cb007a3e09 | 214 | package com.kadia.kblogserber.mapper;
import com.kadia.kblogserber.entity.Info;
import org.springframework.data.jpa.repository.JpaRepository;
public interface InfoMapper extends JpaRepository<Info, Integer> {
}
| 23.777778 | 66 | 0.827103 |
0e115f18f3987e76008d3457b90108110eaa59b8 | 114 | /**
* Classes and packages related to the {@link jr.dungeon.Dungeon} - all gameplay code.
*/
package jr.dungeon; | 28.5 | 86 | 0.710526 |
6d38ebf97e3b5502ee9701dedaafe0ea0ea5ad4c | 1,047 | package org.infinispan.protostream.types.protobuf;
import org.infinispan.protostream.GeneratedSchema;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
/**
* @author anistor@redhat.com
* @since 4.4
*/
@AutoProtoSchemaBuilder(
schemaFileName = "any.proto",
schemaFilePath = "/protostream/google/protobuf",
schemaPackageName = "google.protobuf",
includeClasses = AnySchema.Any.class
)
public interface AnySchema extends GeneratedSchema {
final class Any {
private final String typeUrl;
private final byte[] value;
@ProtoFactory
public Any(String typeUrl, byte[] value) {
this.typeUrl = typeUrl;
this.value = value;
}
@ProtoField(value = 1, name = "type_url")
public String getTypeUrl() {
return typeUrl;
}
@ProtoField(2)
public byte[] getValue() {
return value;
}
}
}
| 24.348837 | 69 | 0.680993 |
7d7fbfd879ad1ab1b9484223c52648b68aa297ed | 841 | package org.apache.http.conn;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.http.HttpHost;
import org.apache.http.config.SocketConfig;
import org.apache.http.protocol.HttpContext;
public interface HttpClientConnectionOperator {
void connect(ManagedHttpClientConnection paramManagedHttpClientConnection, HttpHost paramHttpHost, InetSocketAddress paramInetSocketAddress, int paramInt, SocketConfig paramSocketConfig, HttpContext paramHttpContext) throws IOException;
void upgrade(ManagedHttpClientConnection paramManagedHttpClientConnection, HttpHost paramHttpHost, HttpContext paramHttpContext) throws IOException;
}
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/http/conn/HttpClientConnectionOperator.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | 44.263158 | 238 | 0.819263 |
89a493deae023d0e3fde16f092f9c99c9c0b9db3 | 119 | package ru.otus.auth;
public interface ClientAuthService {
boolean authenticate(String login, String password);
}
| 19.833333 | 56 | 0.781513 |
96422ea3ee16c83569cf7c9dda4f7be91af741ee | 16,290 | package green_green_avk.ptyprocess;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.system.ErrnoException;
import android.system.Os;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import java.util.Map;
@Keep
public final class PtyProcess extends Process {
// It seems all Android architectures have the same values...
// Valid for: aarch64, armv7a-eabi, x86_64, i686.
// Actual before API 21 only.
// TODO: A bit tricky, refactor...
public static final int EPERM = 1;
public static final int ENOENT = 2;
public static final int ESRCH = 3;
public static final int EINTR = 4;
public static final int EIO = 5;
public static final int ENXIO = 6;
public static final int E2BIG = 7;
public static final int ENOEXEC = 8;
public static final int EBADF = 9;
public static final int ECHILD = 10;
public static final int EAGAIN = 11;
public static final int ENOMEM = 12;
public static final int EACCES = 13;
public static final int EFAULT = 14;
public static final int ENOTBLK = 15;
public static final int EBUSY = 16;
public static final int EEXIST = 17;
public static final int EXDEV = 18;
public static final int ENODEV = 19;
public static final int ENOTDIR = 20;
public static final int EISDIR = 21;
public static final int EINVAL = 22;
public static final int ENFILE = 23;
public static final int EMFILE = 24;
public static final int ENOTTY = 25;
public static final int ETXTBSY = 26;
public static final int EFBIG = 27;
public static final int ENOSPC = 28;
public static final int ESPIPE = 29;
public static final int EROFS = 30;
public static final int EMLINK = 31;
public static final int EPIPE = 32;
public static final int EDOM = 33;
public static final int ERANGE = 34;
public static final int EDEADLK = 35;
public static final int ENAMETOOLONG = 36;
public static final int ENOLCK = 37;
public static final int ENOSYS = 38;
public static final int ENOTEMPTY = 39;
public static final int ELOOP = 40;
public static final int EWOULDBLOCK = 11;
public static final int ENOMSG = 42;
public static final int EIDRM = 43;
public static final int ECHRNG = 44;
public static final int EL2NSYNC = 45;
public static final int EL3HLT = 46;
public static final int EL3RST = 47;
public static final int ELNRNG = 48;
public static final int EUNATCH = 49;
public static final int ENOCSI = 50;
public static final int EL2HLT = 51;
public static final int EBADE = 52;
public static final int EBADR = 53;
public static final int EXFULL = 54;
public static final int ENOANO = 55;
public static final int EBADRQC = 56;
public static final int EBADSLT = 57;
public static final int EDEADLOCK = 35;
public static final int EBFONT = 59;
public static final int ENOSTR = 60;
public static final int ENODATA = 61;
public static final int ETIME = 62;
public static final int ENOSR = 63;
public static final int ENONET = 64;
public static final int ENOPKG = 65;
public static final int EREMOTE = 66;
public static final int ENOLINK = 67;
public static final int EADV = 68;
public static final int ESRMNT = 69;
public static final int ECOMM = 70;
public static final int EPROTO = 71;
public static final int EMULTIHOP = 72;
public static final int EDOTDOT = 73;
public static final int EBADMSG = 74;
public static final int EOVERFLOW = 75;
public static final int ENOTUNIQ = 76;
public static final int EBADFD = 77;
public static final int EREMCHG = 78;
public static final int ELIBACC = 79;
public static final int ELIBBAD = 80;
public static final int ELIBSCN = 81;
public static final int ELIBMAX = 82;
public static final int ELIBEXEC = 83;
public static final int EILSEQ = 84;
public static final int ERESTART = 85;
public static final int ESTRPIPE = 86;
public static final int EUSERS = 87;
public static final int ENOTSOCK = 88;
public static final int EDESTADDRREQ = 89;
public static final int EMSGSIZE = 90;
public static final int EPROTOTYPE = 91;
public static final int ENOPROTOOPT = 92;
public static final int EPROTONOSUPPORT = 93;
public static final int ESOCKTNOSUPPORT = 94;
public static final int EOPNOTSUPP = 95;
public static final int EPFNOSUPPORT = 96;
public static final int EAFNOSUPPORT = 97;
public static final int EADDRINUSE = 98;
public static final int EADDRNOTAVAIL = 99;
public static final int ENETDOWN = 100;
public static final int ENETUNREACH = 101;
public static final int ENETRESET = 102;
public static final int ECONNABORTED = 103;
public static final int ECONNRESET = 104;
public static final int ENOBUFS = 105;
public static final int EISCONN = 106;
public static final int ENOTCONN = 107;
public static final int ESHUTDOWN = 108;
public static final int ETOOMANYREFS = 109;
public static final int ETIMEDOUT = 110;
public static final int ECONNREFUSED = 111;
public static final int EHOSTDOWN = 112;
public static final int EHOSTUNREACH = 113;
public static final int EALREADY = 114;
public static final int EINPROGRESS = 115;
public static final int ESTALE = 116;
public static final int EUCLEAN = 117;
public static final int ENOTNAM = 118;
public static final int ENAVAIL = 119;
public static final int EISNAM = 120;
public static final int EREMOTEIO = 121;
public static final int EDQUOT = 122;
public static final int ENOMEDIUM = 123;
public static final int EMEDIUMTYPE = 124;
public static final int ECANCELED = 125;
public static final int ENOKEY = 126;
public static final int EKEYEXPIRED = 127;
public static final int EKEYREVOKED = 128;
public static final int EKEYREJECTED = 129;
public static final int EOWNERDEAD = 130;
public static final int ENOTRECOVERABLE = 131;
public static final int ERFKILL = 132;
public static final int EHWPOISON = 133;
public static final int ENOTSUP = 95;
public static final int O_RDONLY = 00000000;
public static final int O_WRONLY = 00000001;
public static final int O_RDWR = 00000002;
public static final int O_CREAT = 00000100;
public static final int O_PATH = 010000000;
public static final int SIGHUP = 1;
public static final int SIGINT = 2;
public static final int SIGQUIT = 3;
static {
System.loadLibrary("ptyprocess");
}
@Keep
private volatile int fdPtm;
@Keep
private final int pid;
@Keep
private PtyProcess(final int fdPtm, final int pid) {
this.fdPtm = fdPtm;
this.pid = pid;
}
public int getPtm() {
return fdPtm;
}
public int getPid() {
return pid;
}
@NonNull
@Keep
public static native PtyProcess execve(@NonNull final String filename, final String[] args,
final String[] env);
@NonNull
public static PtyProcess execve(@NonNull final String filename, final String[] args,
final Map<String, String> env) {
if (env == null) return execve(filename, args, (String[]) null);
final String[] _env = new String[env.size()];
int i = 0;
for (final Map.Entry<String, String> elt : env.entrySet()) {
_env[i] = elt.getKey() + "=" + elt.getValue();
++i;
}
return execve(filename, args, _env);
}
@NonNull
public static PtyProcess execv(@NonNull final String filename, final String[] args) {
return execve(filename, args, (String[]) null);
}
@NonNull
public static PtyProcess execl(@NonNull final String filename,
final Map<String, String> env, final String... args) {
return execve(filename, args, env);
}
@NonNull
public static PtyProcess execl(@NonNull final String filename, final String... args) {
return execv(filename, args);
}
@NonNull
public static PtyProcess system(@Nullable final String command,
@Nullable final Map<String, String> env) {
if (command == null || command.isEmpty())
return execl("/system/bin/sh", env, "-sh", "-l");
return execl("/system/bin/sh", env, "-sh", "-l", "-c", command);
}
@NonNull
public static PtyProcess system(@Nullable final String command) {
return system(command, null);
}
@Override
public OutputStream getOutputStream() {
return input;
}
@Override
public InputStream getInputStream() {
return output;
}
@Override
public InputStream getErrorStream() {
return null;
}
@Override
public int waitFor() {
return 0;
}
@Override
public int exitValue() {
return 0;
}
@Override
@Keep
public native void destroy();
@Keep
public native void sendSignalToForeground(int signal);
@Keep
public native void resize(int width, int height, int widthPx, int heightPx) throws IOException;
// TODO: Or ParcelFileDescriptor / File Streams?
@Keep
private native int readByte() throws IOException;
@Keep
private native int readBuf(byte[] buf, int off, int len) throws IOException;
@Keep
private native void writeByte(int b) throws IOException;
@Keep
private native void writeBuf(byte[] buf, int off, int len) throws IOException;
private final InputStream output = new InputStream() {
@Override
public int read() throws IOException {
return readByte();
}
@Override
public int read(@NonNull final byte[] b, final int off, final int len)
throws IOException {
if (b == null) throw new NullPointerException();
if (off < 0 || len < 0 || off + len > b.length) throw new IndexOutOfBoundsException();
return readBuf(b, off, len);
}
};
private final OutputStream input = new OutputStream() {
@Override
public void write(final int b) throws IOException {
writeByte(b);
}
@Override
public void write(@NonNull final byte[] b, final int off, final int len)
throws IOException {
if (b == null) throw new NullPointerException();
if (off < 0 || len < 0 || off + len > b.length) throw new IndexOutOfBoundsException();
writeBuf(b, off, len);
}
};
// Asynchronous close during read (FileChannel class) seems having some issues
// before Lollipop...
// So, let eat bees.
public static final class InterruptableFileInputStream
extends ParcelFileDescriptor.AutoCloseInputStream {
private volatile boolean closed = false;
private final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
public final ParcelFileDescriptor pfd;
public InterruptableFileInputStream(final ParcelFileDescriptor pfd) throws IOException {
super(pfd);
this.pfd = pfd;
}
private void interrupt() throws IOException {
pipe[1].close();
}
private void interruptQuiet() {
try {
interrupt();
} catch (final IOException ignored) {
}
}
@Override
public void close() throws IOException {
closed = true;
super.close();
interruptQuiet();
}
private boolean check() throws IOException {
try {
return pollForRead(pfd.getFd(), pipe[0].getFd());
} catch (final IllegalStateException e) {
throw new IOException(e.getMessage(), e);
}
}
@Override
public int read() throws IOException {
try {
if (check()) return -1;
return super.read();
} catch (final IOException e) {
if (!closed) throw e;
return -1;
}
}
@Override
public int read(final byte[] b) throws IOException {
if (check()) return -1;
try {
return super.read(b);
} catch (final IOException e) {
if (!closed) throw e;
return -1;
}
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
if (check()) return -1;
try {
return super.read(b, off, len);
} catch (final IOException e) {
if (!closed) throw e;
return -1;
}
}
}
public static final class PfdFileOutputStream
extends ParcelFileDescriptor.AutoCloseOutputStream {
public final ParcelFileDescriptor pfd;
public PfdFileOutputStream(final ParcelFileDescriptor pfd) {
super(pfd);
this.pfd = pfd;
}
}
public static boolean isatty(final InputStream s) {
if (s instanceof InterruptableFileInputStream)
return isatty(((InterruptableFileInputStream) s).pfd.getFd());
throw new IllegalArgumentException("Unsupported stream type");
}
public static void getSize(final OutputStream s, @NonNull int[] result) throws IOException {
if (s instanceof PfdFileOutputStream) {
getSize(((PfdFileOutputStream) s).pfd.getFd(), result);
return;
}
throw new IllegalArgumentException("Unsupported stream type");
}
@NonNull
public static String getPathByFd(final int fd) throws IOException {
final String pp = String.format(Locale.ROOT, "/proc/self/fd/%d", fd);
return new File(pp).getCanonicalPath();
}
// Actual before API 21 only
@Keep
public static native boolean pollForRead(int fd, int intFd) throws IOException;
@Keep
public static native boolean isatty(int fd);
@Keep
public static native void getSize(int fd, @NonNull int[] result) throws IOException;
@Keep
public static native long getArgMax();
/*
* It seems, android.system.Os class is trying to be linked by Dalvik even when inside
* appropriate if statement and raises java.lang.VerifyError on the constructor call...
* API 19 is affected at least.
* Moving to separate class to work it around.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static final class Utils21 {
private Utils21() {
}
private static void close(@NonNull final FileDescriptor fd) throws IOException {
try {
Os.close(fd);
} catch (final ErrnoException e) {
throw new IOException(e.getMessage(), e);
}
}
}
private static final String sCloseWaError = "Cannot close socket: workaround failed";
public static void close(@NonNull final FileDescriptor fd) throws IOException {
if (!fd.valid()) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Utils21.close(fd);
} else {
final int _fd;
try {
_fd = (int) FileDescriptor.class.getMethod("getInt$").invoke(fd);
} catch (final IllegalAccessException e) {
throw new IOException(sCloseWaError);
} catch (final InvocationTargetException e) {
throw new IOException(sCloseWaError);
} catch (final NoSuchMethodException e) {
throw new IOException(sCloseWaError);
}
ParcelFileDescriptor.adoptFd(_fd).close();
}
}
}
| 33.9375 | 99 | 0.631062 |
7cc8a4581e78023922190d26e6374f2dc2cd8192 | 1,850 | /*
* Copyright 2019
* heaven7(donshine723@gmail.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 com.heaven7.java.reflectyio;
import com.heaven7.java.reflecty.member.MethodProxy;
import com.heaven7.java.reflectyio.anno.Since;
import com.heaven7.java.reflectyio.anno.Until;
import java.lang.reflect.Method;
/**
* the method proxy
* @author heaven7
*/
public class ReflectyMethodProxy extends MethodProxy implements VersionMemberProxy {
private final float since;
private final float until;
public ReflectyMethodProxy(Class<?> ownerClass, Method get, Method set, String property) {
super(ownerClass, get, set, property);
Since u = get.getAnnotation(Since.class);
Until n = get.getAnnotation(Until.class);
this.since = u != null ? u.value() : -1f;
this.until = n != null ? n.value() : -1f;
if(until > 0 && until <= since){
throw new IllegalStateException("until must larger than since.");
}
}
@Override
public boolean isVersionMatched(float expectVersion) {
if(since < 0){
return true;
}
if(expectVersion >= since){
if(until >= 0){
return expectVersion < until;
}else {
return true;
}
}
return false;
}
}
| 30.327869 | 94 | 0.655676 |
7e5350e2dd3fe166fd2bb455fd919b3b5f2a9c1f | 1,637 | package ox.softeng.metadatacatalogue.test.restapi.service;
import static org.junit.Assert.assertTrue;
import org.flywaydb.test.annotation.FlywayTest;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import ox.softeng.metadatacatalogue.api.ClassifierApi;
import ox.softeng.metadatacatalogue.domain.core.Classifier;
public class ClassifierServiceIT<ObjectType> extends SharableServiceIT<Classifier> {
@Override
protected Classifier getInstance() throws Exception
{
return ClassifierApi.createClassifier(apiCtx, "My Test Classifier", "My test classifier description");
}
@Override
protected String getServicePath()
{
return "/classifier";
}
@Override
protected Class<? extends Classifier> getClazz()
{
return Classifier.class;
}
@FlywayTest(invokeCleanDB=true, invokeBaselineDB=true)
@Test
public void createClassifier() throws Exception {
LoginResponse lr = doLogin();
Classifier cl = new Classifier();
cl.setLabel("my new classifier");
cl.setDescription("my classifier description");
Classifier clReturned = assertSuccessfulPost("/classifier/create/", lr.cookie, cl, Classifier.class);
assertTrue(clReturned.getLabel().equalsIgnoreCase("my new classifier"));
assertTrue(clReturned.getDescription().equalsIgnoreCase("my classifier description"));
assertTrue(clReturned.getId() != null);
JsonNode jn = apiCtx.getByIdMap(Classifier.class, "classifier.pageview.id", clReturned.getId());
Classifier cl2 = objectMapper.treeToValue(jn, Classifier.class);
assertTrue(cl2.getLabel().equalsIgnoreCase("my new classifier"));
doLogout(lr.cookie);
}
}
| 27.283333 | 104 | 0.770312 |
501e8de0cfdcf702c0010fe36d91de924c00d1b1 | 1,137 | package com.appdirect.challenge.domain.appdirect;
public class Marketplace {
private String partner;
private String baseUrl;
public String getPartner() {
return partner;
}
public void setPartner(String partner) {
this.partner = partner;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((baseUrl == null) ? 0 : baseUrl.hashCode());
result = prime * result + ((partner == null) ? 0 : partner.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Marketplace other = (Marketplace) obj;
if (baseUrl == null) {
if (other.baseUrl != null)
return false;
} else if (!baseUrl.equals(other.baseUrl))
return false;
if (partner == null) {
if (other.partner != null)
return false;
} else if (!partner.equals(other.partner))
return false;
return true;
}
}
| 22.74 | 73 | 0.652595 |
9a8e1bacd876949016af0453039586e172d063fa | 1,182 | package io.github.ulisse1996.jaorm.integration.test.projection;
import io.github.ulisse1996.jaorm.annotation.Column;
import io.github.ulisse1996.jaorm.annotation.Converter;
import io.github.ulisse1996.jaorm.annotation.Projection;
import io.github.ulisse1996.jaorm.entity.converter.BooleanIntConverter;
import java.math.BigDecimal;
import java.util.Date;
@Projection
public class MyProjection {
@Column(name = "ID_COL")
private BigDecimal id;
@Column(name = "SUB_NAME")
private String subName;
@Column(name = "VALID")
@Converter(BooleanIntConverter.class)
private boolean valid;
private Date other;
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public Date getOther() {
return other;
}
public void setOther(Date other) {
this.other = other;
}
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public String getSubName() {
return subName;
}
public void setSubName(String subName) {
this.subName = subName;
}
}
| 20.37931 | 71 | 0.664975 |
555434837c82efa3f1c4f126e288bbf188c49f53 | 1,426 | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.subscription;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* @author Ulf Lilleengen
*/
public class ConfigURITest {
@Test
public void testDefaultUri() {
ConfigURI uri = ConfigURI.createFromId("foo");
assertThat(uri.getConfigId(), is("foo"));
assertTrue(uri.getSource() instanceof ConfigSourceSet);
}
@Test
public void testFileUri() throws IOException {
File file = File.createTempFile("foo", ".cfg");
ConfigURI uri = ConfigURI.createFromId("file:" + file.getAbsolutePath());
assertThat(uri.getConfigId(), is(""));
assertTrue(uri.getSource() instanceof FileSource);
}
@Test
public void testDirUri() throws IOException {
ConfigURI uri = ConfigURI.createFromId("dir:.");
assertThat(uri.getConfigId(), is(""));
assertTrue(uri.getSource() instanceof DirSource);
}
@Test
public void testCustomUri() {
ConfigURI uri = ConfigURI.createFromIdAndSource("foo", new ConfigSet());
assertThat(uri.getConfigId(), is("foo"));
assertTrue(uri.getSource() instanceof ConfigSet);
}
}
| 30.340426 | 118 | 0.676718 |
e48fea15b7f2748ee33dcc87e7ba56df58a946da | 151 | package org.dase.ecii.core;
public enum ECIIVersion {
/**
*
*/
V0,
/**
*
*/
V1,
/**
*
*/
V2
}
| 7.947368 | 27 | 0.324503 |
494b24828a6f50f3e08be0a1652db9a7c5a13caf | 1,739 | package net.astercrono.pcsetup.dataaccess.hibernate;
import java.util.Date;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import net.astercrono.pcsetup.dataaccess.ProfileDao;
import net.astercrono.pcsetup.domain.Profile;
@Repository
public class HibernateProfileDao implements ProfileDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public Profile getProfile(Long id) {
return sessionFactory.getCurrentSession().find(Profile.class, id);
}
@Override
public void createProfile(Profile profile) {
profile.setCreatedTimestamp(new Date());
profile.setModifiedTimestamp(new Date());
profile.setDeleted(false);
sessionFactory.getCurrentSession().persist(profile);
}
@Override
public Profile updateProfile(Profile profile) {
profile.setModifiedTimestamp(new Date());
if (profile.getDeleted() == null) {
profile.setDeleted(false);
}
return (Profile) sessionFactory.getCurrentSession().merge(profile);
}
@Override
public void deleteProfile(Long id) {
String hql = "update Profile set deleted = true where id = :id";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("id", id);
query.executeUpdate();
}
@Override
public boolean profileExists(String username) {
String hql = "select 1 from Profile where username = :username";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("username", username);
try {
query.getSingleResult();
return true;
} catch (NoResultException ex) {
return false;
}
}
}
| 25.955224 | 69 | 0.765957 |
118cd256ddccb06830821cd0ab1cef2e88ccb030 | 2,895 | /*
* ImageCarousel.java
*
* Created on April 12, 2007, 2:45 PM
*
* Copyright 2006-2007 Nigel Hughes
*
* 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.blogofbug.examples.yahooimagesearch;
import com.blogofbug.swing.components.JCarosel;
import com.blogofbug.swing.components.ReflectedImageLabel;
import com.blogofbug.swing.components.effects.ComponentEffect;
import com.blogofbug.swing.components.effects.EffectContainer;
import com.blogofbug.swing.components.effects.EffectEngine;
import com.blogofbug.swing.components.effects.FadeEffect;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.JComponent;
/**
*
* @author nigel
*/
public class ImageCarousel extends JCarosel{
private EffectEngine effectEngine;
private boolean faded = false;
public ImageCarousel(){
super(128);
effectEngine=new EffectEngine(this,false);
}
public void fadeOut(){
faded = true;
}
public void fadeBack(){
faded = false;
}
public void paint(Graphics g) {
super.paint(g);
if (faded){
g.setColor(new Color(0,0,0,196));
g.fillRect(0,0,getWidth(),getHeight());
}
}
/**
* Returns a RelectComponent effect for the specified object, to change the
* exact effect, just over-ride this method
*
* @param forComponent The component to create the effect for
* @param inComponent The container
* @param effectEngine The engine creatingit
* @return The effect, by default a ReflectComponent effect
*/
public ComponentEffect getEffect(JComponent forComponent, Container inComponent, EffectContainer effectEngine) {
String label = "";
if (forComponent instanceof ReflectedImageLabel){
label = ((ReflectedImageLabel) forComponent).getRichText();
} else {
if (forComponent.getToolTipText()!=null){
label = forComponent.getToolTipText();
} else {
label = forComponent.getName();
if (label==null){
label = "";
}
}
}
return new ImageCarouselComponentEffect(inComponent,forComponent,effectEngine,label);
}
}
| 33.275862 | 117 | 0.648705 |
8e7b5b24805bf303fc91b5af18b113f4d69be7a5 | 1,539 | package com.xtech.sunshine_tutorial;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Log.d("Preferences: ", "Setting summary for preference *************");
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
| 30.78 | 102 | 0.688759 |
7742bf79575f71499d9f1f19c642c87b7ad6152b | 2,810 | package party.dabble.redstonemod.util;
import java.util.HashMap;
import org.apache.logging.log4j.LogManager;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public class PowerLookup {
private static HashMap<BlockPos, Byte> powerMap_Overworld = new HashMap<BlockPos, Byte>();
private static HashMap<BlockPos, Byte> powerMap_Nether = new HashMap<BlockPos, Byte>();
private static HashMap<BlockPos, Byte> powerMap_TheEnd = new HashMap<BlockPos, Byte>();
public static byte getPower(BlockPos pos, World world) {
Byte power = getPowerMap(world).get(pos);
return (power == null) ? 0 : power;
}
public static void putPower(BlockPos pos, byte power, World world) {
power = (power < 0) ? 0 : ((power > 15) ? 15 : power);
if (power == 0) {
removePower(pos, world);
return;
}
getPowerMap(world).put(pos, power);
}
public static void removePower(BlockPos pos, World world) {
getPowerMap(world).remove(pos);
}
public static void clearPower(World world) {
HashMap<BlockPos, Byte> powerMap = getPowerMap(world);
if (powerMap.size() > 0) {
LogManager.getLogger().info("Removing the power of " + powerMap.size() + " redstone paste blocks in "
+ world.provider.getDimensionName() + " from memory.");
powerMap.clear();
}
}
public static void clearAllPower() {
if (powerMap_Overworld.size() > 0) {
LogManager.getLogger().info("Removing the power of " + powerMap_Overworld.size() + " redstone paste blocks in "
+ new net.minecraft.world.WorldProviderSurface().getDimensionName() + " from memory.");
powerMap_Overworld.clear();
}
if (powerMap_Nether.size() > 0) {
LogManager.getLogger().info("Removing the power of " + powerMap_Nether.size() + " redstone paste blocks in "
+ new net.minecraft.world.WorldProviderHell().getDimensionName() + " from memory.");
powerMap_Nether.clear();
}
if (powerMap_TheEnd.size() > 0) {
LogManager.getLogger().info("Removing the power of " + powerMap_TheEnd.size() + " redstone paste blocks in "
+ new net.minecraft.world.WorldProviderEnd().getDimensionName() + " from memory.");
powerMap_TheEnd.clear();
}
}
private static long prevTime = System.nanoTime();
private static HashMap<BlockPos, Byte> getPowerMap(World world) {
switch (world.provider.getDimensionId()) {
case 0:
return powerMap_Overworld;
case -1:
return powerMap_Nether;
case 1:
return powerMap_TheEnd;
default:
if (System.nanoTime() - prevTime > 1e10) {
LogManager.getLogger().error("Could not find the dimension with the ID " + world.provider.getDimensionId()
+ ". Redstone Paste's power system will as a result not function properly. Actually, not at all.");
prevTime = System.nanoTime();
}
return new HashMap<BlockPos, Byte>();
}
}
}
| 31.573034 | 114 | 0.696441 |
19fa63c18106b022061065bdb7179fa04e59ec77 | 257 | package designModel.creation.abstractFactory.products;
/**
* @author masuo
* @data 2021/9/6 10:21
* @Description
*/
public class GeliWM extends WM{
@Override
void wash() {
System.out.println("This is a GEli washing machine!");
}
}
| 17.133333 | 62 | 0.653696 |
4c4e94b7f89c9823ee7d664d9408a6c161b4294f | 4,158 | package com.umapathi.greeshma.todoapplication;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.Service;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.content.Intent;
import android.content.Context;
import android.app.PendingIntent;
import android.app.Notification;
/**
* Created by greeshma on 8/23/2017.
*/
public class NotificationService extends IntentService {
private static final String ACTION_SHOW_NOTIFICATION = "my.app.service.action.show";
private static final String ACTION_HIDE_NOTIFICATION = "my.app.service.action.hide";
public NotificationService() {
super("ShowNotificationIntentService");
}
public static void startActionShow(Context context) {
Intent intent = new Intent(context, NotificationService.class);
intent.setAction(ACTION_SHOW_NOTIFICATION);
context.startService(intent);
}
public static void startActionHide(Context context) {
Intent intent = new Intent(context, NotificationService.class);
intent.setAction(ACTION_HIDE_NOTIFICATION);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_SHOW_NOTIFICATION.equals(action)) {
handleActionShow();
} else if (ACTION_HIDE_NOTIFICATION.equals(action)) {
handleActionHide();
}
}
}
private void handleActionShow() {
showStatusBarIcon(NotificationService.this);
}
private void handleActionHide() {
//hideStatusBarIcon(NotificationService.this);
}
public static void showStatusBarIcon(Context ctx) {
Context context = ctx;
android.support.v4.app.NotificationCompat.Builder builder = new android.support.v4.app.NotificationCompat.Builder(ctx)
.setContentTitle("Notif"/*ctx.getString(R.string.notification_message)*/)
.setSmallIcon(R.drawable.calendar)
.setOngoing(true);
Intent intent = new Intent(context, ListAddActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 001, intent, 0);
builder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = builder.build();
notif.flags |= Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(001, notif);
}
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
/*public NotificationService() {
super("NotificationService");
}
Alarm alarm = new Alarm();
public void onStart(Context context,Intent intent, int startId)
{
alarm.SetAlarm(context);
}
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
alarm.SetAlarm(context);
}
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent,flags,startId);
}*/
}
| 34.363636 | 128 | 0.675325 |
41427d18f78ee1b07d8994bfc5519dd4747cf5f0 | 3,676 | /*
* Copyright 2017 Gabor Varadi
*
* 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.zhuinden.simplestack;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.SparseArray;
import com.zhuinden.statebundle.StateBundle;
/**
* A container for the view hierarchy state and an optional Bundle.
* Made to be used with {@link BackstackDelegate}'s view state persistence.
*
* A {@link SavedState} represents the state of the view that is bound to a given key.
*/
public class SavedState {
private Object key;
private SparseArray<Parcelable> viewHierarchyState;
private StateBundle bundle;
private SavedState() {
}
@NonNull
public Object getKey() {
return key;
}
@NonNull
public SparseArray<Parcelable> getViewHierarchyState() {
return viewHierarchyState;
}
public void setViewHierarchyState(SparseArray<Parcelable> viewHierarchyState) {
this.viewHierarchyState = viewHierarchyState;
}
@Nullable
public StateBundle getBundle() {
return bundle;
}
public void setBundle(@Nullable StateBundle bundle) {
this.bundle = bundle;
}
public static Builder builder() {
return new Builder();
}
/**
* A builder class that allows creating SavedState instances.
*
* Keys are not optional.
*/
public static class Builder {
private Object key;
private SparseArray<Parcelable> viewHierarchyState = new SparseArray<>();
private StateBundle bundle;
Builder() {
}
public Builder setKey(@NonNull Object key) {
if(key == null) {
throw new IllegalArgumentException("Key cannot be null");
}
this.key = key;
return this;
}
public Builder setViewHierarchyState(@NonNull SparseArray<Parcelable> viewHierarchyState) {
if(viewHierarchyState == null) {
throw new IllegalArgumentException("Provided sparse array for view hierarchy state cannot be null");
}
this.viewHierarchyState = viewHierarchyState;
return this;
}
public Builder setBundle(@Nullable StateBundle bundle) {
this.bundle = bundle;
return this;
}
public SavedState build() {
if(key == null) {
throw new IllegalStateException("You cannot create a SavedState without associating a Key with it.");
}
SavedState savedState = new SavedState();
savedState.key = key;
savedState.viewHierarchyState = viewHierarchyState;
savedState.bundle = bundle;
return savedState;
}
}
@Override
public boolean equals(Object obj) {
if(obj == null) {
return false;
}
if(!(obj instanceof SavedState)) {
return false;
}
return ((SavedState)obj).getKey().equals(this.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
}
| 28.71875 | 117 | 0.637922 |
c61fb956b90fda6c8e2473bf89d56cbf691b2cd2 | 6,625 | /*
Copyright 2021 Adobe. All rights reserved.
This file is licensed 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package com.adobe.marketing.mobile;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import java.util.Map;
import static com.adobe.marketing.mobile.MessagingConstant.EventDataKeys.Messaging.TRACK_INFO_KEY_ACTION_ID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({MobileCore.class, Intent.class})
public class MessagingTests {
@Mock
Intent mockIntent;
@Before
public void before() {
PowerMockito.mockStatic(MobileCore.class);
}
// ========================================================================================
// extensionVersion
// ========================================================================================
@Test
public void test_extensionVersionAPI() {
// test
String extensionVersion = Messaging.extensionVersion();
Assert.assertEquals("The Extension version API returns the correct value", MessagingConstant.EXTENSION_VERSION,
extensionVersion);
}
// ========================================================================================
// registerExtension
// ========================================================================================
@Test
public void test_registerExtensionAPI() {
// test
Messaging.registerExtension();
final ArgumentCaptor<ExtensionErrorCallback> callbackCaptor = ArgumentCaptor.forClass(ExtensionErrorCallback.class);
// The monitor extension should register with core
PowerMockito.verifyStatic(MobileCore.class, Mockito.times(1));
MobileCore.registerExtension(ArgumentMatchers.eq(MessagingInternal.class), callbackCaptor.capture());
// verify the callback
ExtensionErrorCallback extensionErrorCallback = callbackCaptor.getValue();
Assert.assertNotNull("The extension callback should not be null", extensionErrorCallback);
// should not crash on calling the callback
extensionErrorCallback.error(ExtensionError.UNEXPECTED_ERROR);
}
// ========================================================================================
// addPushTrackingDetails
// ========================================================================================
@Test
public void test_addPushTrackingDetails_WhenParamsAreNull() {
// test
boolean done = Messaging.addPushTrackingDetails(null, null, null);
// verify
Assert.assertFalse(done);
}
@Test
public void test_addPushTrackingDetails() {
String mockMessageId = "mockMessageId";
String mockXDMData = "mockXDMData";
Map<String, String> mockDataMap = new HashMap<>();
mockDataMap.put(MessagingConstant.TrackingKeys._XDM, mockXDMData);
// test
boolean done = Messaging.addPushTrackingDetails(mockIntent, mockMessageId, mockDataMap);
// verify
Assert.assertTrue(done);
verify(mockIntent, times(1)).putExtra(MessagingConstant.EventDataKeys.Messaging.TRACK_INFO_KEY_MESSAGE_ID, mockMessageId);
verify(mockIntent, times(1)).putExtra(MessagingConstant.EventDataKeys.Messaging.TRACK_INFO_KEY_ADOBE_XDM, mockXDMData);
}
// ========================================================================================
// handleNotificationResponse
// ========================================================================================
@Test
public void test_handleNotificationResponse_WhenParamsAreNull() {
// test
Messaging.handleNotificationResponse(null, false, null);
// verify
PowerMockito.verifyStatic(MobileCore.class, Mockito.times(0));
MobileCore.dispatchEvent(any(Event.class), any(ExtensionErrorCallback.class));
}
@Test
public void test_handleNotificationResponse() {
final ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
String mockActionId = "mockActionId";
String mockXdm = "mockXdm";
try {
PowerMockito.whenNew(Intent.class)
.withNoArguments().thenReturn(mockIntent);
} catch (Exception e) {
com.adobe.marketing.mobile.Log.debug("MessagingTest", "Intent exception");
}
when(mockIntent.getStringExtra(anyString())).thenReturn(mockXdm);
// test
Messaging.handleNotificationResponse(mockIntent, true, mockActionId);
// verify
verify(mockIntent, times(2)).getStringExtra(anyString());
PowerMockito.verifyStatic(MobileCore.class, Mockito.times(1));
MobileCore.dispatchEvent(eventCaptor.capture(), any(ExtensionErrorCallback.class));
// verify event
Event event = eventCaptor.getValue();
EventData eventData = event.getData();
assertNotNull(eventData);
assertEquals(MessagingConstant.EventType.MESSAGING.toLowerCase(), event.getEventType().getName());
try {
assertEquals(eventData.getString2(TRACK_INFO_KEY_ACTION_ID), mockActionId);
} catch (VariantException e) {
com.adobe.marketing.mobile.Log.debug("MessagingTest", "getString2 variant exception, error : %s", e.getMessage());
}
}
}
| 40.396341 | 130 | 0.641358 |
6191e664d90b7d702e0cb06a19074736d33c5d1c | 139 | //compile errors
package p;
class A {
void m() {
/*[*/
final int /*]*/
i = 0;
List l;
}
;
}
| 9.266667 | 23 | 0.338129 |
3729cdb7b2e315b8e54dea56bdf60c5c96ffd765 | 1,376 | /*
* Copyright 2010 Internet Archive
*
* 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.archive.jbs.filter;
import java.io.*;
import java.net.*;
import org.archive.jbs.Document;
/**
* Simple DocumentFilter that filters out robots and favicon URLs.
*/
public class RobotsFilter implements DocumentFilter
{
public boolean isAllowed( Document document )
{
String url = document.get( "url" );
try
{
URI uri = new URI( url );
String path = uri.getPath();
// If no path, then trivially *not* robots nor favicon.
if ( path == null ) return true;
path = path.trim();
if ( "/favicon.ico".equals( path ) ||
"/robots.txt" .equals( path ) )
{
return false;
}
} catch ( URISyntaxException e ) { }
return true;
}
}
| 24.571429 | 70 | 0.639535 |
7e3a807c8fc8bdef73b05523332466e65296a308 | 3,567 | package in.co.itlabs.ui.components;
import java.util.Locale;
import com.vaadin.flow.component.ComponentEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.shared.Registration;
import in.co.itlabs.util.CircularFilterParams;
public class CircularFilterForm extends HorizontalLayout {
// ui
private TextField queryField;
private DatePicker fromDatePicker;
private DatePicker toDatePicker;
private Button okButton;
private Button cancelButton;
// non-ui
private Binder<CircularFilterParams> binder;
public CircularFilterForm() {
setAlignItems(Alignment.END);
queryField = new TextField();
configureQueryField();
fromDatePicker = new DatePicker();
configureFromDatePicker();
toDatePicker = new DatePicker();
configureFromToPicker();
okButton = new Button("Filter", VaadinIcon.FILTER.create());
cancelButton = new Button("Clear", VaadinIcon.CLOSE.create());
configureButtons();
binder = new Binder<>(CircularFilterParams.class);
binder.forField(queryField).bind("query");
binder.forField(fromDatePicker).bind("fromDate");
binder.forField(toDatePicker).bind("toDate");
add(queryField, fromDatePicker, toDatePicker, okButton, cancelButton);
}
private void configureFromDatePicker() {
fromDatePicker.setLabel("From");
fromDatePicker.setWidth("120px");
fromDatePicker.setLocale(new Locale("in"));
}
private void configureFromToPicker() {
toDatePicker.setLabel("To");
toDatePicker.setWidth("120px");
toDatePicker.setLocale(new Locale("in"));
}
private void configureButtons() {
okButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
okButton.addClickListener(e -> {
if (binder.validate().isOk()) {
fireEvent(new FilterEvent(this, binder.getBean()));
}
});
cancelButton.addClickListener(e -> {
clearForm();
fireEvent(new FilterEvent(this, binder.getBean()));
});
}
private void clearForm() {
queryField.clear();
fromDatePicker.clear();
toDatePicker.clear();
}
private void configureQueryField() {
queryField.setLabel("Specific circular");
queryField.setPlaceholder("Type subject");
queryField.setWidth("300px");
queryField.setClearButtonVisible(true);
}
public void setFilterParams(CircularFilterParams filterParams) {
binder.setBean(filterParams);
}
public static abstract class CircularFilterFormEvent extends ComponentEvent<CircularFilterForm> {
private CircularFilterParams filterParams;
protected CircularFilterFormEvent(CircularFilterForm source, CircularFilterParams filterParams) {
super(source, false);
this.filterParams = filterParams;
}
public CircularFilterParams getFilterParams() {
return filterParams;
}
}
public static class FilterEvent extends CircularFilterFormEvent {
FilterEvent(CircularFilterForm source, CircularFilterParams filterParams) {
super(source, filterParams);
}
}
public <T extends ComponentEvent<?>> Registration addListener(Class<T> eventType,
ComponentEventListener<T> listener) {
return getEventBus().addListener(eventType, listener);
}
}
| 28.309524 | 100 | 0.743762 |
5ac1a7781bb5f0136186fa08f1c1208cfc2c0831 | 229 | package com.corejava.assignment.threads;
public class PrintMachineSR extends Thread
{
Printer printer;
PrintMachineSR(Printer printer)
{
this.printer=printer;
}
@Override
public void run()
{
printer.print();
}
}
| 12.722222 | 42 | 0.724891 |
74942ed8500e81702cd85398a0e34105ab35d60d | 584 | package com.github.ftrossbach.kiqr.client.service;
import com.github.ftrossbach.kiqr.commons.config.querymodel.requests.Window;
import org.apache.kafka.common.serialization.Serde;
import java.util.Map;
import java.util.Optional;
/**
* Created by ftr on 10/03/2017.
*/
public interface SpecificBlockingKiqrClient<K,V> {
Optional<V> getScalarKeyValue(K key);
Map<K,V> getAllKeyValues();
Map<K,V> getRangeKeyValues(K from, K to);
Map<Long,V> getWindow(K key, long from, long to);
Optional<Long> count(String store);
Map<Window, V> getSession(K key);
}
| 22.461538 | 76 | 0.726027 |
73af0a055e303829b4baf2659091d4f94a9d546d | 19,214 | /*
*
* 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.qpid.protonj2.client.impl;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.qpid.protonj2.client.Client;
import org.apache.qpid.protonj2.client.Connection;
import org.apache.qpid.protonj2.client.ConnectionOptions;
import org.apache.qpid.protonj2.client.exceptions.ClientConnectionSecuritySaslException;
import org.apache.qpid.protonj2.client.test.ImperativeClientTestCase;
import org.apache.qpid.protonj2.test.driver.ProtonTestServer;
import org.apache.qpid.protonj2.test.driver.ProtonTestServerOptions;
import org.apache.qpid.protonj2.types.UnsignedByte;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
@Timeout(20)
public class SaslConnectionTest extends ImperativeClientTestCase {
private static final String ANONYMOUS = "ANONYMOUS";
private static final String PLAIN = "PLAIN";
private static final String CRAM_MD5 = "CRAM-MD5";
private static final String SCRAM_SHA_1 = "SCRAM-SHA-1";
private static final String SCRAM_SHA_256 = "SCRAM-SHA-256";
private static final String SCRAM_SHA_512 = "SCRAM-SHA-512";
private static final String EXTERNAL = "EXTERNAL";
private static final String XOAUTH2 = "XOAUTH2";
private static final UnsignedByte SASL_FAIL_AUTH = UnsignedByte.valueOf((byte) 1);
private static final UnsignedByte SASL_SYS = UnsignedByte.valueOf((byte) 2);
private static final UnsignedByte SASL_SYS_PERM = UnsignedByte.valueOf((byte) 3);
private static final UnsignedByte SASL_SYS_TEMP = UnsignedByte.valueOf((byte) 4);
private static final String BROKER_JKS_KEYSTORE = "src/test/resources/broker-jks.keystore";
private static final String BROKER_JKS_TRUSTSTORE = "src/test/resources/broker-jks.truststore";
private static final String CLIENT_JKS_KEYSTORE = "src/test/resources/client-jks.keystore";
private static final String CLIENT_JKS_TRUSTSTORE = "src/test/resources/client-jks.truststore";
private static final String PASSWORD = "password";
protected ProtonTestServerOptions serverOptions() {
return new ProtonTestServerOptions();
}
protected ConnectionOptions connectionOptions() {
return new ConnectionOptions();
}
@Test
public void testSaslLayerDisabledConnection() throws Exception {
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectAMQPHeader().respondWithAMQPHeader();
peer.expectOpen().respond();
peer.expectClose().respond();
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.saslOptions().saslEnabled(false);
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
connection.openFuture().get(10, TimeUnit.SECONDS);
assertFalse(peer.hasSecureConnection());
assertFalse(peer.isConnectionVerified());
connection.close();
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testSaslExternalConnection() throws Exception {
ProtonTestServerOptions serverOptions = serverOptions();
serverOptions.setKeyStoreLocation(BROKER_JKS_KEYSTORE);
serverOptions.setKeyStorePassword(PASSWORD);
serverOptions.setVerifyHost(false);
serverOptions.setTrustStoreLocation(BROKER_JKS_TRUSTSTORE);
serverOptions.setTrustStorePassword(PASSWORD);
serverOptions.setNeedClientAuth(true);
serverOptions.setSecure(true);
try (ProtonTestServer peer = new ProtonTestServer(serverOptions)) {
peer.expectSaslExternalConnect();
peer.expectOpen().respond();
peer.expectClose().respond();
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.sslOptions()
.sslEnabled(true)
.keyStoreLocation(CLIENT_JKS_KEYSTORE)
.keyStorePassword(PASSWORD)
.trustStoreLocation(CLIENT_JKS_TRUSTSTORE)
.trustStorePassword(PASSWORD);
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
connection.openFuture().get(10, TimeUnit.SECONDS);
assertTrue(peer.hasSecureConnection());
assertTrue(peer.isConnectionVerified());
connection.closeAsync().get(10, TimeUnit.SECONDS);
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testSaslPlainConnection() throws Exception {
final String username = "user";
final String password = "qwerty123456";
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectSASLPlainConnect(username, password);
peer.expectOpen().respond();
peer.expectClose().respond();
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.user(username);
clientOptions.password(password);
clientOptions.traceFrames(true);
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
connection.openFuture().get(10, TimeUnit.SECONDS);
assertFalse(peer.hasSecureConnection());
assertFalse(peer.isConnectionVerified());
connection.close();
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testSaslXOauth2Connection() throws Exception {
final String username = "user";
final String password = "eyB1c2VyPSJ1c2VyIiB9";
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectSaslXOauth2Connect(username, password);
peer.expectOpen().respond();
peer.expectClose().respond();
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.user(username);
clientOptions.password(password);
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
connection.openFuture().get(10, TimeUnit.SECONDS);
connection.close();
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testSaslAnonymousConnection() throws Exception {
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectSASLAnonymousConnect();
peer.expectOpen().respond();
peer.expectClose().respond();
peer.start();
URI remoteURI = peer.getServerURI();
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort());
connection.openFuture().get(10, TimeUnit.SECONDS);
connection.close();
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testSaslFailureCodes() throws Exception {
doSaslFailureCodesTestImpl(SASL_FAIL_AUTH);
doSaslFailureCodesTestImpl(SASL_SYS);
doSaslFailureCodesTestImpl(SASL_SYS_PERM);
doSaslFailureCodesTestImpl(SASL_SYS_TEMP);
}
private void doSaslFailureCodesTestImpl(UnsignedByte saslFailureCode) throws Exception {
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectFailingSASLPlainConnect(saslFailureCode.byteValue(), "PLAIN", "ANONYMOUS");
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.user("username");
clientOptions.password("password");
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
try {
connection.openFuture().get(10, TimeUnit.SECONDS);
} catch (ExecutionException exe) {
assertTrue(exe.getCause() instanceof ClientConnectionSecuritySaslException);
}
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
/**
* Add a small delay after the SASL process fails, test peer will throw if
* any unexpected frames arrive, such as erroneous open+close.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testWaitForUnexpectedFramesAfterSaslFailure() throws Exception {
doMechanismSelectedTestImpl(null, null, ANONYMOUS, new String[] {ANONYMOUS}, true);
}
@Test
public void testAnonymousSelectedWhenNoPasswordWasSupplied() throws Exception {
doMechanismSelectedTestImpl("username", null, ANONYMOUS, new String[] {CRAM_MD5, PLAIN, ANONYMOUS}, false);
}
@Test
public void testCramMd5SelectedWhenCredentialsPresent() throws Exception {
doMechanismSelectedTestImpl("username", "password", CRAM_MD5, new String[] {CRAM_MD5, PLAIN, ANONYMOUS}, false);
}
@Test
public void testScramSha1SelectedWhenCredentialsPresent() throws Exception {
doMechanismSelectedTestImpl("username", "password", SCRAM_SHA_1, new String[] {SCRAM_SHA_1, CRAM_MD5, PLAIN, ANONYMOUS}, false);
}
@Test
public void testScramSha256SelectedWhenCredentialsPresent() throws Exception {
doMechanismSelectedTestImpl("username", "password", SCRAM_SHA_256, new String[] {SCRAM_SHA_256, SCRAM_SHA_1, CRAM_MD5, PLAIN, ANONYMOUS}, false);
}
@Test
public void testScramSha512SelectedWhenCredentialsPresent() throws Exception {
doMechanismSelectedTestImpl("username", "password", SCRAM_SHA_512, new String[] {SCRAM_SHA_512, SCRAM_SHA_256, SCRAM_SHA_1, CRAM_MD5, PLAIN, ANONYMOUS}, false);
}
@Test
public void testXoauth2SelectedWhenCredentialsPresent() throws Exception {
String token = Base64.getEncoder().encodeToString("token".getBytes(StandardCharsets.US_ASCII));
doMechanismSelectedTestImpl("username", token, XOAUTH2, new String[] {XOAUTH2, ANONYMOUS}, false);
}
private void doMechanismSelectedTestImpl(String username, String password, String clientSelectedMech, String[] serverMechs, boolean wait) throws Exception {
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectSaslConnectThatAlwaysFailsAuthentication(serverMechs, clientSelectedMech);
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.user(username);
clientOptions.password(password);
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
try {
connection.openFuture().get(10, TimeUnit.SECONDS);
} catch (ExecutionException exe) {
assertTrue(exe.getCause() instanceof ClientConnectionSecuritySaslException);
}
if (wait) {
Thread.sleep(200);
}
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testExternalSelectedWhenLocalPrincipalPresent() throws Exception {
doMechanismSelectedExternalTestImpl(true, EXTERNAL, new String[] {EXTERNAL, SCRAM_SHA_512, SCRAM_SHA_256, SCRAM_SHA_1, CRAM_MD5, PLAIN, ANONYMOUS});
}
@Test
public void testExternalNotSelectedWhenLocalPrincipalMissing() throws Exception {
doMechanismSelectedExternalTestImpl(false, ANONYMOUS, new String[] {EXTERNAL, SCRAM_SHA_512, SCRAM_SHA_256, SCRAM_SHA_1, CRAM_MD5, PLAIN, ANONYMOUS});
}
private void doMechanismSelectedExternalTestImpl(boolean requireClientCert, String clientSelectedMech, String[] serverMechs) throws Exception {
ProtonTestServerOptions serverOptions = serverOptions();
serverOptions.setKeyStoreLocation(BROKER_JKS_KEYSTORE);
serverOptions.setKeyStorePassword(PASSWORD);
serverOptions.setVerifyHost(false);
serverOptions.setSecure(true);
if (requireClientCert) {
serverOptions.setTrustStoreLocation(BROKER_JKS_TRUSTSTORE);
serverOptions.setTrustStorePassword(PASSWORD);
serverOptions.setNeedClientAuth(requireClientCert);
}
try (ProtonTestServer peer = new ProtonTestServer(serverOptions)) {
peer.expectSaslConnectThatAlwaysFailsAuthentication(serverMechs, clientSelectedMech);
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.sslOptions()
.sslEnabled(true)
.trustStoreLocation(CLIENT_JKS_TRUSTSTORE)
.trustStorePassword(PASSWORD);
if (requireClientCert) {
clientOptions.sslOptions().keyStoreLocation(CLIENT_JKS_KEYSTORE)
.keyStorePassword(PASSWORD);
}
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
try {
connection.openFuture().get(10, TimeUnit.SECONDS);
} catch (ExecutionException exe) {
assertTrue(exe.getCause() instanceof ClientConnectionSecuritySaslException);
}
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testRestrictSaslMechanismsWithSingleMech() throws Exception {
// Check PLAIN gets picked when we don't specify a restriction
doMechanismSelectionRestrictedTestImpl("username", "password", PLAIN, new String[] { PLAIN, ANONYMOUS}, (String) null);
// Check ANONYMOUS gets picked when we do specify a restriction
doMechanismSelectionRestrictedTestImpl("username", "password", ANONYMOUS, new String[] { PLAIN, ANONYMOUS}, ANONYMOUS);
}
@Test
public void testRestrictSaslMechanismsWithMultipleMechs() throws Exception {
// Check CRAM-MD5 gets picked when we dont specify a restriction
doMechanismSelectionRestrictedTestImpl("username", "password", CRAM_MD5, new String[] {CRAM_MD5, PLAIN, ANONYMOUS}, (String) null);
// Check PLAIN gets picked when we specify a restriction with multiple mechs
doMechanismSelectionRestrictedTestImpl("username", "password", PLAIN, new String[] { CRAM_MD5, PLAIN, ANONYMOUS}, "PLAIN", "ANONYMOUS");
}
@Test
public void testRestrictSaslMechanismsWithMultipleMechsNoPassword() throws Exception {
// Check ANONYMOUS gets picked when we specify a restriction with multiple mechs but don't give a password
doMechanismSelectionRestrictedTestImpl("username", null, ANONYMOUS, new String[] { CRAM_MD5, PLAIN, ANONYMOUS}, "PLAIN", "ANONYMOUS");
}
private void doMechanismSelectionRestrictedTestImpl(String username, String password, String clientSelectedMech,
String[] serverMechs, String... allowedClientMechanisms) throws Exception {
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectSaslConnectThatAlwaysFailsAuthentication(serverMechs, clientSelectedMech);
peer.start();
URI remoteURI = peer.getServerURI();
ConnectionOptions clientOptions = connectionOptions();
clientOptions.user(username);
clientOptions.password(password);
for (String mechanism : allowedClientMechanisms) {
if (mechanism != null && !mechanism.isEmpty()) {
clientOptions.saslOptions().addAllowedMechanism(mechanism);
}
}
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort(), clientOptions);
try {
connection.openFuture().get(10, TimeUnit.SECONDS);
} catch (ExecutionException exe) {
assertTrue(exe.getCause() instanceof ClientConnectionSecuritySaslException);
}
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
@Test
public void testMechanismNegotiationFailsToFindMatch() throws Exception {
String[] serverMechs = new String[] { SCRAM_SHA_1, "UNKNOWN", PLAIN};
String breadCrumb = "Could not find a suitable SASL Mechanism. " +
"No supported mechanism, or none usable with the available credentials.";
try (ProtonTestServer peer = new ProtonTestServer(serverOptions())) {
peer.expectSaslMechanismNegotiationFailure(serverMechs);
peer.start();
URI remoteURI = peer.getServerURI();
Client container = Client.create();
Connection connection = container.connect(remoteURI.getHost(), remoteURI.getPort());
try {
connection.openFuture().get(10, TimeUnit.SECONDS);
} catch (ExecutionException exe) {
assertTrue(exe.getCause() instanceof ClientConnectionSecuritySaslException);
assertTrue(exe.getCause().getMessage().contains(breadCrumb));
}
peer.waitForScriptToComplete(5, TimeUnit.SECONDS);
}
}
}
| 42.228571 | 168 | 0.676226 |
efaaf2ce026c4fd495bf406d9ef441f7332e0ccf | 571 | package com.maxmind.minfraud.request;
import com.maxmind.minfraud.request.Shipping.Builder;
import com.maxmind.minfraud.request.Shipping.DeliverySpeed;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ShippingTest extends AbstractLocationTest {
Builder builder() {
return new Builder();
}
@Test
public void testDeliverySpeed() throws Exception {
Shipping loc = this.builder().deliverySpeed(DeliverySpeed.EXPEDITED).build();
assertEquals(DeliverySpeed.EXPEDITED, loc.getDeliverySpeed());
}
} | 28.55 | 85 | 0.747811 |
1bc3038cc57d7403ed28d51e18d31896a60b47a0 | 1,754 | package com.hncboy;
/**
* @author hncboy
* @date 2019/12/9 10:24
* @description 1013.将数组分成和相等的三个部分
* <p>
* 给定一个整数数组 A,只有我们可以将其划分为三个和相等的非空部分时才返回 true,否则返回 false。
* 形式上,如果我们可以找出索引 i+1 < j 且满足
* (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])
* 就可以将数组三等分。
* <p>
* 示例 1:
* 输出:[0,2,1,-6,6,-7,9,1,2,0,1]
* 输出:true
* 解释:0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
* <p>
* 示例 2:
* 输入:[0,2,1,-6,6,7,9,-1,2,0,1]
* 输出:false
* <p>
* 示例 3:
* 输入:[3,3,6,5,-2,2,5,1,-9,4]
* 输出:true
* 解释:3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
* <p>
* 提示:
* 3 <= A.length <= 50000
* -10000 <= A[i] <= 10000
*/
public class PartitionArrayIntoThreePartsWithEqualSum {
public static void main(String[] args) {
PartitionArrayIntoThreePartsWithEqualSum p = new PartitionArrayIntoThreePartsWithEqualSum();
System.out.println(p.canThreePartsEqualSum(new int[]{0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1}));
System.out.println(p.canThreePartsEqualSum(new int[]{0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1}));
System.out.println(p.canThreePartsEqualSum(new int[]{3, 3, 6, 5, -2, 2, 5, 1, -9, 4}));
System.out.println(p.canThreePartsEqualSum(new int[]{10, -10, 10, -10, 10, -10, 10, -10}));
}
private boolean canThreePartsEqualSum(int[] A) {
int sum = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
}
if (sum % 3 != 0) {
return false;
}
int partSum = 0;
int count = 0;
for (int i = 0; i < A.length; i++) {
partSum += A[i];
if (partSum == sum / 3) {
partSum = 0;
count++;
}
}
return count >= 3;
}
}
| 28.290323 | 105 | 0.488597 |
bcacb6def7254644c09d9105fce48726b45983e5 | 3,139 | /*
* MIT License
*
* Copyright (c) 2019 everythingbest
*
* 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.rpcpostman.config;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author everythingbest
* cas拦截点配置
* 因为是前后端分离,在前端检测登陆是否失效,需要在每次进行ajax请求的时候带上ajax-header,
* 在session过期的时候,会执行这个类的commence方法{@link AuthenticationEntryPoint}
* Used by {@link ExceptionTranslationFilter} to commence an authentication scheme.
*/
public class SessionExpireEntryPoint implements AuthenticationEntryPoint {
static final String AJAX_TYPE = "ajax-type";
static final String AJAX_HEADER = "ajax-header";
final CasAuthenticationEntryPoint casAuthenticationEntryPoint;
SessionExpireEntryPoint(final CasAuthenticationEntryPoint casAuthenticationEntryPoint){
this.casAuthenticationEntryPoint = casAuthenticationEntryPoint;
}
/**
* 在cas授权失败的时候会进入这个方法
* @param request
* @param response
* @param authException
* @throws IOException
* @throws ServletException
*/
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//判断请求类型是否是ajax
if(request.getHeader(AJAX_TYPE) != null || request.getParameter(AJAX_TYPE)!=null){
//设置过期标识,让前端js进行处理
response.setHeader(AJAX_HEADER,"time-out");
try {
//直接返回错误信息,前端js进行拦截
response.sendError(HttpServletResponse.SC_OK,"session已经过期");
} catch (IOException e) {
}
}else{
casAuthenticationEntryPoint.commence(request,response,authException);
}
}
}
| 36.5 | 160 | 0.747372 |
c34cd0ea6ddc269aff15891f132874967fa31049 | 284 | package com.nvinas.hnews.ui.comments;
import dagger.Binds;
import dagger.Module;
/**
* Created by nvinas on 10/02/2018.
*/
@Module
public abstract class CommentsModule {
@Binds
abstract CommentsContract.Presenter commentsPresenter(CommentsPresenter commentsPresenter);
}
| 18.933333 | 95 | 0.771127 |
779e76bd073ff26e22bb832d731c79645912cfd2 | 1,882 | package com.entity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "cloudplateform_exam")
public class Exam {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", columnDefinition = "int(11)")
private Long id;
@Column(name = "user_id", columnDefinition = "int(11)")
private Long userId;
@Column(name = "paper_id", columnDefinition = "int(11)")
private Long paperId;
@Column(name = "re_answers", columnDefinition = "varchar(500)")
private String reAnswer;
@Column(name = "state", columnDefinition = "int(1)")
private String state;
@Column(name = "result", columnDefinition = "decimal(5,2)")
private Float result;
@Column(name = "start_time", columnDefinition = "datetime")
private Date startTime;
@Column(name = "end_time", columnDefinition = "datetime")
private Date endTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getPaperId() {
return paperId;
}
public void setPaperId(Long paperId) {
this.paperId = paperId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Float getResult() {
return result;
}
public void setResult(Float result) {
this.result = result;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
}
| 20.456522 | 67 | 0.611052 |
6c9a9e8e222f855b9e71d6251c9c8b3b42fb9635 | 19,672 | /*
* Originally based on io.realm.RealmBaseAdapter
* =============================================
* Copyright 2014 Realm 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.
*/
package io.realm;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.tonicartos.superslim.GridSLM;
import com.tonicartos.superslim.LinearSLM;
import java.util.ArrayList;
import java.util.List;
import co.moonmonkeylabs.realmrecyclerview.LoadMoreListItemView;
import co.moonmonkeylabs.realmrecyclerview.R;
import co.moonmonkeylabs.realmrecyclerview.RealmRecyclerView;
import difflib.Chunk;
import difflib.Delta;
import difflib.DiffUtils;
import difflib.Patch;
import io.realm.internal.ColumnType;
import io.realm.internal.TableOrView;
/**
* The base {@link RecyclerView.Adapter} that includes custom functionality to be used with the
* {@link RealmRecyclerView}.
*/
public abstract class RealmBasedRecyclerViewAdapter
<T extends RealmObject, VH extends RealmViewHolder>
extends RecyclerView.Adapter<RealmViewHolder> {
public class RowWrapper {
public final boolean isRealm;
public final int realmIndex;
public final int sectionHeaderIndex;
public final String header;
public RowWrapper(int realmIndex, int sectionHeaderIndex) {
this(true, realmIndex, sectionHeaderIndex, null);
}
public RowWrapper(int sectionHeaderIndex, String header) {
this(false, -1, sectionHeaderIndex, header);
}
public RowWrapper(boolean isRealm, int realmIndex, int sectionHeaderIndex, String header) {
this.isRealm = isRealm;
this.realmIndex = realmIndex;
this.sectionHeaderIndex = sectionHeaderIndex;
this.header = header;
}
}
private static final List<Long> EMPTY_LIST = new ArrayList<>(0);
private Object loadMoreItem;
protected final int HEADER_VIEW_TYPE = 100;
private final int LOAD_MORE_VIEW_TYPE = 101;
protected LayoutInflater inflater;
protected RealmResults<T> realmResults;
protected List ids;
protected List<RowWrapper> rowWrappers;
private RealmChangeListener listener;
private boolean animateResults;
private boolean addSectionHeaders;
private String headerColumnName;
private long animatePrimaryColumnIndex;
private ColumnType animatePrimaryIdType;
private long animateExtraColumnIndex;
private ColumnType animateExtraIdType;
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults,
String animateExtraColumnName) {
this(
context,
realmResults,
automaticUpdate,
animateResults,
false,
null,
animateExtraColumnName);
}
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults) {
this(context, realmResults, automaticUpdate, animateResults, false, null);
}
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults,
boolean addSectionHeaders,
String headerColumnName) {
this(
context,
realmResults,
automaticUpdate,
animateResults,
addSectionHeaders,
headerColumnName,
null);
}
public RealmBasedRecyclerViewAdapter(
Context context,
RealmResults<T> realmResults,
boolean automaticUpdate,
boolean animateResults,
boolean addSectionHeaders,
String headerColumnName,
String animateExtraColumnName) {
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
this.animateResults = animateResults;
this.addSectionHeaders = addSectionHeaders;
this.headerColumnName = headerColumnName;
this.inflater = LayoutInflater.from(context);
this.listener = (!automaticUpdate) ? null : getRealmChangeListener();
rowWrappers = new ArrayList<>();
// If automatic updates aren't enabled, then animateResults should be false as well.
this.animateResults = (automaticUpdate && animateResults);
if (animateResults) {
animatePrimaryColumnIndex = realmResults.getTable().getTable().getPrimaryKey();
if (animatePrimaryColumnIndex == TableOrView.NO_MATCH) {
throw new IllegalStateException(
"Animating the results requires a primaryKey.");
}
animatePrimaryIdType = realmResults.getTable().getColumnType(animatePrimaryColumnIndex);
if (animatePrimaryIdType != ColumnType.INTEGER &&
animatePrimaryIdType != ColumnType.STRING) {
throw new IllegalStateException(
"Animating requires a primary key of type Integer/Long or String");
}
if (animateExtraColumnName != null) {
animateExtraColumnIndex = realmResults.getTable().getTable()
.getColumnIndex(animateExtraColumnName);
if (animateExtraColumnIndex == TableOrView.NO_MATCH) {
throw new IllegalStateException(
"Animating the results requires a valid animateColumnName.");
}
animateExtraIdType = realmResults.getTable().getColumnType(animateExtraColumnIndex);
if (animateExtraIdType != ColumnType.INTEGER &&
animateExtraIdType != ColumnType.STRING) {
throw new IllegalStateException(
"Animating requires a animateColumnName of type Int/Long or String");
}
} else {
animateExtraColumnIndex = -1;
}
}
if (addSectionHeaders && headerColumnName == null) {
throw new IllegalStateException(
"A headerColumnName is required for section headers");
}
updateRealmResults(realmResults);
}
public abstract VH onCreateRealmViewHolder(ViewGroup viewGroup, int viewType);
public abstract void onBindRealmViewHolder(VH holder, int position);
/**
* DON'T OVERRIDE THIS METHOD. Implement onCreateRealmViewHolder instead.
*/
@Override
public RealmViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == HEADER_VIEW_TYPE) {
View view = inflater.inflate(R.layout.header_item, viewGroup, false);
return new RealmViewHolder((TextView) view);
} else if (viewType == LOAD_MORE_VIEW_TYPE) {
return new RealmViewHolder(new LoadMoreListItemView(viewGroup.getContext()));
}
return onCreateRealmViewHolder(viewGroup, viewType);
}
/**
* DON'T OVERRIDE THIS METHOD. Implement onBindRealmViewHolder instead.
*/
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(RealmViewHolder holder, int position) {
if (getItemViewType(position) == LOAD_MORE_VIEW_TYPE) {
holder.loadMoreView.showSpinner();
} else {
if (addSectionHeaders) {
final String header = rowWrappers.get(position).header;
final GridSLM.LayoutParams layoutParams =
GridSLM.LayoutParams.from(holder.itemView.getLayoutParams());
// Setup the header
if (header != null) {
holder.headerTextView.setText(header);
if (layoutParams.isHeaderInline()) {
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
} else {
layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
layoutParams.isHeader = true;
} else {
onBindRealmViewHolder((VH) holder, position);
}
layoutParams.setSlm(LinearSLM.ID);
if (header != null) {
layoutParams.setFirstPosition(position);
} else {
layoutParams.setFirstPosition(rowWrappers.get(position).sectionHeaderIndex);
}
holder.itemView.setLayoutParams(layoutParams);
} else {
onBindRealmViewHolder((VH) holder, position);
}
}
}
public Object getLastItem() {
if (addSectionHeaders) {
return realmResults.get(rowWrappers.get(rowWrappers.size() - 1).realmIndex);
} else {
return realmResults.get(realmResults.size() - 1);
}
}
@Override
public int getItemCount() {
int loadMoreCount = loadMoreItem == null ? 0 : 1;
if (addSectionHeaders) {
return rowWrappers.size() + loadMoreCount;
}
if (realmResults == null) {
return 0;
}
return realmResults.size() + loadMoreCount;
}
@Override
public int getItemViewType(int position) {
if (loadMoreItem != null && position == getItemCount() - 1) {
return LOAD_MORE_VIEW_TYPE;
} else if (!rowWrappers.isEmpty() && !rowWrappers.get(position).isRealm) {
return HEADER_VIEW_TYPE;
}
return getItemRealmViewType(position);
}
public int getItemRealmViewType(int position) {
return super.getItemViewType(position);
}
/**
* Update the RealmResults associated with the Adapter. Useful when the query has been changed.
* If the query does not change you might consider using the automaticUpdate feature.
*
* @param queryResults the new RealmResults coming from the new query.
*/
public void updateRealmResults(RealmResults<T> queryResults) {
if (listener != null) {
if (this.realmResults != null) {
this.realmResults.getRealm().removeChangeListener(listener);
}
if (queryResults != null) {
queryResults.getRealm().addChangeListener(listener);
}
}
this.realmResults = queryResults;
updateRowWrappers();
ids = getIdsOfRealmResults();
notifyDataSetChanged();
}
/**
* Method that creates the header string that should be used. Override this method to have
* a custom header.
*/
public String createHeaderFromColumnValue(String columnValue) {
return columnValue.substring(0, 1);
}
private List getIdsOfRealmResults() {
if (!animateResults || realmResults.size() == 0) {
return EMPTY_LIST;
}
if (addSectionHeaders) {
List ids = new ArrayList(rowWrappers.size());
for (int i = 0; i < rowWrappers.size(); i++) {
final RowWrapper rowWrapper = rowWrappers.get(i);
if (rowWrapper.isRealm) {
ids.add(getRealmRowId(rowWrappers.get(i).realmIndex));
} else {
ids.add(rowWrappers.get(i).header);
}
}
return ids;
} else {
List ids = new ArrayList(realmResults.size());
for (int i = 0; i < realmResults.size(); i++) {
ids.add(getRealmRowId(i));
}
return ids;
}
}
private Object getRealmRowId(int realmIndex) {
Object rowPrimaryId;
if (animatePrimaryIdType == ColumnType.INTEGER) {
rowPrimaryId = realmResults.get(realmIndex).row.getLong(animatePrimaryColumnIndex);
} else if (animatePrimaryIdType == ColumnType.STRING) {
rowPrimaryId = realmResults.get(realmIndex).row.getString(animatePrimaryColumnIndex);
} else {
throw new IllegalStateException("Unknown animatedIdType");
}
if (animateExtraColumnIndex != -1) {
String rowPrimaryIdStr = (rowPrimaryId instanceof String)
? (String) rowPrimaryId : String.valueOf(rowPrimaryId);
if (animateExtraIdType == ColumnType.INTEGER) {
return rowPrimaryIdStr + String.valueOf(
realmResults.get(realmIndex).row.getLong(animateExtraColumnIndex));
} else if (animateExtraIdType == ColumnType.STRING) {
return rowPrimaryIdStr +
realmResults.get(realmIndex).row.getString(animateExtraColumnIndex);
} else {
throw new IllegalStateException("Unknown animateExtraIdType");
}
} else {
return rowPrimaryId;
}
}
private void updateRowWrappers() {
if (addSectionHeaders) {
String lastHeader = "";
int headerCount = 0;
int sectionFirstPosition = 0;
rowWrappers.clear();
final long headerIndex = realmResults.getTable().getColumnIndex(headerColumnName);
int i = 0;
for (RealmObject result : realmResults) {
String header = createHeaderFromColumnValue(result.row.getString(headerIndex));
if (!TextUtils.equals(lastHeader, header)) {
// Insert new header view and update section data.
sectionFirstPosition = i + headerCount;
lastHeader = header;
headerCount += 1;
rowWrappers.add(new RowWrapper(sectionFirstPosition, header));
}
rowWrappers.add(new RowWrapper(i++, sectionFirstPosition));
}
}
}
private RealmChangeListener getRealmChangeListener() {
return new RealmChangeListener() {
@Override
public void onChange() {
if (animateResults && ids != null && !ids.isEmpty()) {
updateRowWrappers();
List newIds = getIdsOfRealmResults();
// If the list is now empty, just notify the recyclerView of the change.
if (newIds.isEmpty()) {
ids = newIds;
notifyDataSetChanged();
return;
}
Patch patch = DiffUtils.diff(ids, newIds);
List <Delta> deltas = patch.getDeltas();
ids = newIds;
if (deltas.isEmpty()) {
// Nothing has changed - most likely because the notification was for
// a different object/table
} else if (addSectionHeaders) {
// If sectionHeaders are enabled, the animations have some special cases and
// the non-animated rows need to be updated as well.
Delta delta = deltas.get(0);
if (delta.getType() == Delta.TYPE.INSERT) {
if (delta.getRevised().size() == 1) {
notifyItemInserted(delta.getRevised().getPosition());
} else {
final Chunk revised = delta.getRevised();
notifyItemRangeInserted(revised.getPosition(), revised.size());
}
} else if (delta.getType() == Delta.TYPE.DELETE) {
if (delta.getOriginal().size() == 1) {
notifyItemRemoved(delta.getOriginal().getPosition());
} else {
// Note: The position zero check is to hack around a indexOutOfBound
// exception that happens when the zero position is animated out.
if (delta.getOriginal().getPosition() == 0) {
notifyDataSetChanged();
return;
} else {
notifyItemRangeRemoved(
delta.getOriginal().getPosition(),
delta.getOriginal().size());
}
}
if (delta.getOriginal().getPosition() - 1 > 0) {
notifyItemRangeChanged(
0,
delta.getOriginal().getPosition() - 1);
}
if (delta.getOriginal().getPosition() > 0 && newIds.size() > 0) {
notifyItemRangeChanged(
delta.getOriginal().getPosition(),
newIds.size() - 1);
}
} else {
notifyDataSetChanged();
}
} else {
for (Delta delta : deltas) {
if (delta.getType() == Delta.TYPE.INSERT) {
notifyItemRangeInserted(
delta.getRevised().getPosition(),
delta.getRevised().size());
} else if (delta.getType() == Delta.TYPE.DELETE) {
notifyItemRangeRemoved(
delta.getOriginal().getPosition(),
delta.getOriginal().size());
} else {
notifyItemRangeChanged(
delta.getRevised().getPosition(),
delta.getRevised().size());
}
}
}
} else {
notifyDataSetChanged();
ids = getIdsOfRealmResults();
}
}
};
}
/**
* Adds the LoadMore item.
*/
public void addLoadMore() {
if (loadMoreItem != null) {
return;
}
loadMoreItem = new Object();
notifyDataSetChanged();
}
/**
* Removes the LoadMoreItems;
*/
public void removeLoadMore() {
if (loadMoreItem == null) {
return;
}
loadMoreItem = null;
notifyDataSetChanged();
}
}
| 38.87747 | 100 | 0.553172 |
765eb42020cd4d1ea35c9100f75fb81c67fd569a | 1,160 | package com.seal.websocker.controller;
import com.seal.websocker.model.RequestMessage;
import com.seal.websocker.model.ResponseMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
@Controller
public class WebSocketController {
@Resource
private SimpMessagingTemplate messagingTemplate;
@RequestMapping("/index")
public String index() {
return "index";
}
@MessageMapping("/welcome")
public ResponseMessage toTopic(RequestMessage msg) throws Exception {
this.messagingTemplate.convertAndSend("/api/v1/socket/send", msg.getMessage());
return new ResponseMessage("欢迎使用webScoket:" + msg.getMessage());
}
@MessageMapping("/message")
public ResponseMessage toUser(RequestMessage msg) {
this.messagingTemplate.convertAndSendToUser("123", "/message", msg.getMessage());
return new ResponseMessage("欢迎使用webScoket:" + msg.getMessage());
}
}
| 34.117647 | 89 | 0.757759 |
b54c7f47bb420b3763418883bd7e9f38578bd43c | 390 | package com.lenovo.compass;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication
@EnableOpenApi
public class CompassApplication {
public static void main(String[] args) {
SpringApplication.run(CompassApplication.class, args);
}
}
| 24.375 | 68 | 0.833333 |
88793e1d51442dc8e2663c28bbf52de185f454e8 | 5,005 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security.action.interceptor;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.Operations;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authz.AuthorizationServiceField;
import org.elasticsearch.xpack.core.security.authz.accesscontrol.IndicesAccessControl;
import org.elasticsearch.xpack.core.security.authz.permission.Role;
import org.elasticsearch.xpack.core.security.support.Exceptions;
import org.elasticsearch.xpack.security.audit.AuditTrailService;
import java.util.HashMap;
import java.util.Map;
public final class IndicesAliasesRequestInterceptor implements RequestInterceptor<IndicesAliasesRequest> {
private final ThreadContext threadContext;
private final XPackLicenseState licenseState;
private final AuditTrailService auditTrailService;
public IndicesAliasesRequestInterceptor(ThreadContext threadContext, XPackLicenseState licenseState,
AuditTrailService auditTrailService) {
this.threadContext = threadContext;
this.licenseState = licenseState;
this.auditTrailService = auditTrailService;
}
@Override
public void intercept(IndicesAliasesRequest request, Authentication authentication, Role userPermissions, String action) {
final XPackLicenseState frozenLicenseState = licenseState.copyCurrentLicenseState();
if (frozenLicenseState.isAuthAllowed()) {
if (frozenLicenseState.isDocumentAndFieldLevelSecurityAllowed()) {
IndicesAccessControl indicesAccessControl = threadContext.getTransient(AuthorizationServiceField.INDICES_PERMISSIONS_KEY);
for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) {
if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) {
for (String index : aliasAction.indices()) {
IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index);
if (indexAccessControl != null) {
final boolean fls = indexAccessControl.getFieldPermissions().hasFieldLevelSecurity();
final boolean dls = indexAccessControl.getQueries() != null;
if (fls || dls) {
throw new ElasticsearchSecurityException("Alias requests are not allowed for users who have " +
"field or document level security enabled on one of the indices", RestStatus.BAD_REQUEST);
}
}
}
}
}
}
Map<String, Automaton> permissionsMap = new HashMap<>();
for (IndicesAliasesRequest.AliasActions aliasAction : request.getAliasActions()) {
if (aliasAction.actionType() == IndicesAliasesRequest.AliasActions.Type.ADD) {
for (String index : aliasAction.indices()) {
Automaton indexPermissions =
permissionsMap.computeIfAbsent(index, userPermissions.indices()::allowedActionsMatcher);
for (String alias : aliasAction.aliases()) {
Automaton aliasPermissions =
permissionsMap.computeIfAbsent(alias, userPermissions.indices()::allowedActionsMatcher);
if (Operations.subsetOf(aliasPermissions, indexPermissions) == false) {
// TODO we've already audited a access granted event so this is going to look ugly
auditTrailService.accessDenied(authentication, action, request, userPermissions.names());
throw Exceptions.authorizationError("Adding an alias is not allowed when the alias " +
"has more permissions than any of the indices");
}
}
}
}
}
}
}
@Override
public boolean supports(TransportRequest request) {
return request instanceof IndicesAliasesRequest;
}
}
| 56.235955 | 138 | 0.656943 |
9b6ff498fda5b1b0702c610cf918ac67cc7507b2 | 1,243 | package simulations;
import cells.Cell;
import cells.ParameterBundle;
import grids.AbstractGrid;
import javafx.scene.layout.Pane;
/**
* Generic Simulation -- handles most cases where cells don't move
*
* Holds a grid of cells
*
* Depends on Cell, AbstractGrid, Pane, ParameterBundle
*
* @author Ian Eldridge-Allegra
*
*/
public class Simulation {
protected AbstractGrid cells;
protected ParameterBundle parameters;
public Simulation(AbstractGrid cells, ParameterBundle parBundle) {
this.cells = cells;
parameters = parBundle;
}
/**
* Steps each cell, then updates their state
*
*/
public void step() {
stepAllCells();
updateAllCells();
}
protected void updateAllCells() {
for (Cell cell : cells)
cell.update();
}
protected void stepAllCells() {
for (int i = 0; i < cells.getSize(); i++)
cells.get(i).step(cells.getNeighbors(i));
}
public String toString() {
return cells.toString();
}
public Pane getParameterPane(double width, double height) {
return parameters.getOptionPane(width, height);
}
public Pane getView(double width, double height) {
return cells.getView(width, height);
}
public void save(String file) {
cells.save(file, parameters.getParameters());
}
}
| 20.048387 | 67 | 0.706356 |
f037d70654377b4c1c97c71a724d93933f7c49e0 | 19,836 | /*
* Copyright 2014 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 org.uribeacon.scan.compat;
import static android.content.Context.ALARM_SERVICE;
import static android.content.Context.BLUETOOTH_SERVICE;
import static android.test.MoreAsserts.assertEmpty;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.BALANCED_ACTIVE_MILLIS;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.BALANCED_IDLE_MILLIS;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.LOW_LATENCY_ACTIVE_MILLIS;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.LOW_LATENCY_IDLE_MILLIS;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.LOW_POWER_ACTIVE_MILLIS;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.LOW_POWER_IDLE_MILLIS;
import static org.uribeacon.scan.compat.JbBluetoothLeScannerCompat.SCAN_LOST_CYCLES;
import static org.uribeacon.scan.compat.ScanSettings.CALLBACK_TYPE_ALL_MATCHES;
import static org.uribeacon.scan.compat.ScanSettings.CALLBACK_TYPE_FIRST_MATCH;
import static org.uribeacon.scan.compat.ScanSettings.CALLBACK_TYPE_MATCH_LOST;
import static org.uribeacon.scan.compat.ScanSettings.SCAN_MODE_BALANCED;
import static org.uribeacon.scan.compat.ScanSettings.SCAN_MODE_LOW_LATENCY;
import static org.uribeacon.scan.compat.ScanSettings.SCAN_MODE_LOW_POWER;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.uribeacon.scan.compat.JbBluetoothLeScannerCompat;
import org.uribeacon.scan.compat.ScanCallback;
import org.uribeacon.scan.compat.ScanFilter;
import org.uribeacon.scan.compat.ScanRecord;
import org.uribeacon.scan.compat.ScanResult;
import org.uribeacon.scan.compat.ScanSettings;
import org.uribeacon.scan.testing.FakeClock;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothManager;
import android.test.AndroidTestCase;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Unit tests for the {@link org.uribeacon.scan.compat.JbBluetoothLeScannerCompat},
* the core adapter class of the scan compat library.
*/
public class JbBluetoothLeScannerCompatTest extends AndroidTestCase {
private static final ScanSettings SLOW = builder().setScanMode(SCAN_MODE_LOW_POWER).build();
private static final ScanSettings MEDIUM = builder().setScanMode(SCAN_MODE_BALANCED).build();
private static final ScanSettings FAST = builder().setScanMode(SCAN_MODE_LOW_LATENCY).build();
private static final ScanSettings BATCH = builder().setReportDelayMillis(1).build();
private static final ScanSettings FOUND = buildScanSettingsForType(CALLBACK_TYPE_FIRST_MATCH);
private static final ScanSettings ALL = buildScanSettingsForType(CALLBACK_TYPE_ALL_MATCHES);
private static final ScanSettings LOST = buildScanSettingsForType(CALLBACK_TYPE_MATCH_LOST);
private static final List<ScanFilter> NO_FILTER =
new ArrayList<ScanFilter>();
private static final List<ScanFilter> BERT_FILTER =
new ArrayList<ScanFilter>() {{
add(new ScanFilter.Builder().setDeviceName("Bert").build());
}};
private static final List<ScanFilter> ERNIE_FILTER =
new ArrayList<ScanFilter>() {{
add(new ScanFilter.Builder().setDeviceName("Ernie").build());
}};
@Mock private AlarmManager alarmManagerMock;
private BluetoothManager bluetoothManager;
private AlarmManager alarmManager;
private JbBluetoothLeScannerCompat scanner;
private FakeClock clock;
private TestingCallback callback;
@Override
public void setUp() throws Exception {
super.setUp();
bluetoothManager = (BluetoothManager) getContext().getSystemService(BLUETOOTH_SERVICE);
alarmManager = (AlarmManager) getContext().getSystemService(ALARM_SERVICE);
clock = new FakeClock();
scanner = new JbBluetoothLeScannerCompat(
bluetoothManager, alarmManager, clock, null /* pending intent */);
callback = new TestingCallback();
}
/**
* Make sure the 'simple' startScan() call--the one that takes no filters or settings,
* just a callback--works.
*/
public void testSimpleStartScan() {
scanner.startScan(callback);
assertEquals(0, callback.found);
// We see a beacon
onScan("address", 0);
assertEquals(1, callback.found);
}
/**
* Verify that the hashsets used to track ScanSettings don't accidentally merge them.
*/
public void testSettingsAreUnique() {
ScanCallback callback1 = new TestingCallback();
ScanCallback callback2 = new TestingCallback();
assertTrue(scanner.startScan(NO_FILTER, MEDIUM, callback1));
assertTrue(scanner.startScan(NO_FILTER, MEDIUM, callback2));
assertEquals(2, scanner.serialClients.size());
scanner.stopScan(callback1);
assertEquals(1, scanner.serialClients.size());
scanner.stopScan(callback2);
assertEquals(0, scanner.serialClients.size());
}
/**
* Verify that we default to balanced performance. (Checks against the constants in
* the source file, so if those constants change this test will still pass.)
*/
public void testScanDefaults() {
assertEquals(BALANCED_ACTIVE_MILLIS, scanner.getScanActiveMillis());
assertEquals(BALANCED_IDLE_MILLIS, scanner.getScanIdleMillis());
}
/**
* Verify that we return to defaults when there are no listeners after removing a serial listener.
*/
public void testScanDefaultsRestored() {
assertEquals(BALANCED_IDLE_MILLIS, scanner.getScanIdleMillis());
scanner.startScan(NO_FILTER, FAST, callback);
scanner.stopScan(callback);
assertEquals(BALANCED_IDLE_MILLIS, scanner.getScanIdleMillis());
}
/**
* Verify that we return to defaults when there are no listeners after removing a batch listener.
*/
public void testScanDefaultsRestoredFromBatch() {
assertEquals(BALANCED_IDLE_MILLIS, scanner.getScanIdleMillis());
scanner.startScan(NO_FILTER, BATCH, callback);
scanner.stopScan(callback);
assertEquals(BALANCED_IDLE_MILLIS, scanner.getScanIdleMillis());
}
/**
* Verify that multiple scan requests uses the most critical preset timing values.
*/
public void testMultipleScanTiming() {
ScanCallback slow = new TestingCallback();
ScanCallback medium = new TestingCallback();
ScanCallback fast = new TestingCallback();
// Slow
scanner.startScan(NO_FILTER, SLOW, slow);
assertEquals(LOW_POWER_ACTIVE_MILLIS, scanner.getScanActiveMillis());
assertEquals(LOW_POWER_IDLE_MILLIS, scanner.getScanIdleMillis());
// Slow and Medium
scanner.startScan(NO_FILTER, MEDIUM, medium);
assertEquals(BALANCED_ACTIVE_MILLIS, scanner.getScanActiveMillis());
assertEquals(BALANCED_IDLE_MILLIS, scanner.getScanIdleMillis());
// Slow, Medium, Fast
scanner.startScan(NO_FILTER, FAST, fast);
assertEquals(LOW_LATENCY_ACTIVE_MILLIS, scanner.getScanActiveMillis());
assertEquals(LOW_LATENCY_IDLE_MILLIS, scanner.getScanIdleMillis());
// Back it off--stop Medium and Fast, keep Slow
scanner.stopScan(medium);
scanner.stopScan(fast);
assertEquals(LOW_POWER_ACTIVE_MILLIS, scanner.getScanActiveMillis());
assertEquals(LOW_POWER_IDLE_MILLIS, scanner.getScanIdleMillis());
}
/**
* Verify updating the scan timing with custom values.
*/
public void testScanTimingOverride() {
ScanSettings settings = builder().build();
scanner.setCustomScanTiming(123, 456, -1); // (Third parameter is unused.)
scanner.startScan(NO_FILTER, settings, callback);
assertEquals(123, scanner.getScanActiveMillis());
assertEquals(456, scanner.getScanIdleMillis());
assertEquals(clock.currentTimeMillis() - SCAN_LOST_CYCLES * (123 + 456),
scanner.getLostTimestampMillis());
}
/**
* Verify the time values sent to the alarm scheduler instance.
*/
public void testAlarmTiming() {
if (true) {
return;
}
ScanCallback slow = new TestingCallback();
ScanCallback medium = new TestingCallback();
ScanCallback fast = new TestingCallback();
long slowCycle = LOW_POWER_ACTIVE_MILLIS + LOW_POWER_IDLE_MILLIS;
long mediumCycle = BALANCED_ACTIVE_MILLIS + BALANCED_IDLE_MILLIS;
long fastCycle = LOW_LATENCY_ACTIVE_MILLIS + LOW_LATENCY_IDLE_MILLIS;
// This line enables debugging Android/mockito tests through Eclipse.
// See https://code.google.com/p/dexmaker/issues/detail?id=2.
System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath());
MockitoAnnotations.initMocks(this);
scanner = new JbBluetoothLeScannerCompat(
bluetoothManager, alarmManagerMock, clock, null /* pending intent */);
// Slow
scanner.startScan(NO_FILTER, SLOW, slow);
verify(alarmManagerMock).setRepeating(eq(AlarmManager.RTC_WAKEUP),
eq(clock.currentTimeMillis()), eq(slowCycle), any(PendingIntent.class));
// Slow and Medium
scanner.startScan(NO_FILTER, MEDIUM, medium);
verify(alarmManagerMock).setRepeating(eq(AlarmManager.RTC_WAKEUP),
eq(clock.currentTimeMillis()), eq(mediumCycle), any(PendingIntent.class));
// Slow, Medium, Fast
scanner.startScan(NO_FILTER, FAST, fast);
verify(alarmManagerMock).setRepeating(eq(AlarmManager.RTC_WAKEUP),
eq(clock.currentTimeMillis()), eq(fastCycle), any(PendingIntent.class));
// Stop Medium, should still be fast, so nothing should change
scanner.stopScan(medium);
verifyNoMoreInteractions(alarmManagerMock);
}
/**
* Verify that the alarm is canceled when there are no listeners.
*/
public void testCancel() {
if (true) {
return;
}
long slowCycle = LOW_POWER_ACTIVE_MILLIS + LOW_POWER_IDLE_MILLIS;
System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath());
MockitoAnnotations.initMocks(this);
scanner = new JbBluetoothLeScannerCompat(
bluetoothManager, alarmManagerMock, clock, null /* pending intent */);
scanner.startScan(NO_FILTER, SLOW, callback);
verify(alarmManagerMock).setRepeating(eq(AlarmManager.RTC_WAKEUP),
eq(clock.currentTimeMillis()), eq(slowCycle), any(PendingIntent.class));
scanner.stopScan(callback);
verify(alarmManagerMock).cancel(any(PendingIntent.class));
}
/**
* Test found events vs updated events.
*/
public void testFoundEventVsUpdatedEvent() {
TestingCallback foundCallback = new TestingCallback();
TestingCallback updatedCallback = new TestingCallback();
scanner.startScan(NO_FILTER, FOUND, foundCallback);
scanner.startScan(NO_FILTER, ALL, updatedCallback);
// We see a beacon; only the found callback fires.
onScan("address", 0);
assertEquals(1, foundCallback.found);
assertEquals(0, updatedCallback.updated);
// Same beacon again; only the second callback fires
onScan("address", 0);
assertEquals(1, foundCallback.found);
assertEquals(1, updatedCallback.updated);
}
/**
* Test lost events over time.
*/
public void testLostEvent() {
scanner.startScan(NO_FILTER, LOST, callback);
onScan("address", nowMillis());
// If a cycle completes instantly, we haven't "lost" the beacon yet.
scanner.onScanCycleComplete();
assertEquals(0, callback.lost);
// Time rolls forward, but not enough time to cause the sighting to be lost
long expectedTimeoutToLoseSightingMillis =
clock.currentTimeMillis() - scanner.getLostTimestampMillis();
clock.advance(expectedTimeoutToLoseSightingMillis - 5);
scanner.onScanCycleComplete();
assertEquals(0, callback.lost);
// Another few milliseconds and we've lost the beacon
clock.advance(10);
scanner.onScanCycleComplete();
assertEquals(1, callback.lost);
assertEmpty(scanner.recentScanResults);
}
public void testSetScanLostOverride() {
long scanLostOverrideMillis = 15 * 1000;
scanner.setScanLostOverride(scanLostOverrideMillis);
scanner.startScan(NO_FILTER, LOST, callback);
onScan("address", nowMillis());
// If a cycle completes instantly, we haven't "lost" the beacon yet.
scanner.onScanCycleComplete();
assertEquals(0, callback.lost);
// Time rolls forward, but not enough time to cause the sighting to be lost
long expectedTimeoutToLoseSightingMillis =
clock.currentTimeMillis() - scanner.getLostTimestampMillis();
// The lost timestamp includes our override.
assertEquals(clock.currentTimeMillis() - scanLostOverrideMillis,
scanner.getLostTimestampMillis());
clock.advance(expectedTimeoutToLoseSightingMillis - 5);
scanner.onScanCycleComplete();
assertEquals(0, callback.lost);
// Another few milliseconds and we've lost the beacon
clock.advance(10);
scanner.onScanCycleComplete();
assertEquals(1, callback.lost);
assertEmpty(scanner.recentScanResults);
}
/**
* Test lost events are deferred if we keep seeing the beacon.
*/
public void testLostEventPostponed() {
scanner.startScan(NO_FILTER, ALL, callback);
// As time goes by, so long as we keep seeing the beacon it should never be lost
long oneCycleMillis = scanner.getScanCycleMillis();
for (int i = 0; i < SCAN_LOST_CYCLES * 10; i++) {
onScan("address", nowMillis());
clock.advance(oneCycleMillis);
scanner.onScanCycleComplete();
assertEquals(1, callback.found);
assertEquals(i, callback.updated);
assertEquals(0, callback.lost);
}
// Once enough time passes, it's lost
int noMoreUpdates = callback.updated;
clock.advance(SCAN_LOST_CYCLES * oneCycleMillis);
scanner.onScanCycleComplete();
assertEquals(1, callback.lost);
assertEquals(noMoreUpdates, callback.updated);
}
/**
* Test the mathematics of the "we've lost a beacon" timer cutoff code.
* <P>
* Note that this is something of a no-op test, because each of the three modes actually
* happen to all run at the same cycle today (1.5 seconds). This test will become
* more relevant if that ever changes.
*/
public void testCutoffTimestamp() {
long now = clock.currentTimeMillis();
ScanCallback slow = new TestingCallback();
ScanCallback medium = new TestingCallback();
ScanCallback fast = new TestingCallback();
// Slow
scanner.startScan(NO_FILTER, SLOW, slow);
assertEquals(now - SCAN_LOST_CYCLES * (LOW_POWER_ACTIVE_MILLIS + LOW_POWER_IDLE_MILLIS),
scanner.getLostTimestampMillis());
// Medium
scanner.startScan(NO_FILTER, MEDIUM, medium);
assertEquals(now - SCAN_LOST_CYCLES * (BALANCED_ACTIVE_MILLIS + BALANCED_IDLE_MILLIS),
scanner.getLostTimestampMillis());
// Fast
scanner.startScan(NO_FILTER, FAST, fast);
assertEquals(now - SCAN_LOST_CYCLES * (LOW_LATENCY_ACTIVE_MILLIS + LOW_LATENCY_IDLE_MILLIS),
scanner.getLostTimestampMillis());
}
/**
* Test scan filters.
* <P>
* The filters themselves are already unit-tested pretty extensively, so it's enough here
* to test that filters are passed through correctly.
*/
public void testFilters() {
List<ScanFilter> filters = new ArrayList<ScanFilter>() {{
add(new ScanFilter.Builder().setDeviceName("foo").build());
add(new ScanFilter.Builder().setDeviceName("bar").build());
}};
scanner.startScan(filters, FOUND, callback);
onScan("not foo or bar", 0);
assertEquals(0, callback.found);
onScan("foo", 0);
assertEquals(1, callback.found);
onScan("bar", 0);
assertEquals(2, callback.found);
onScan("something else that isn't foo or bar", 0);
assertEquals(2, callback.found);
}
/**
* Test multiple scan listeners with filters.
*/
public void testMultipleFilters() {
final boolean[] bert = { false };
final boolean[] ernie = { false };
scanner.startScan(BERT_FILTER, FOUND, new TestingCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
bert[0] = true;
}
});
scanner.startScan(ERNIE_FILTER, FOUND, new TestingCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
ernie[0] = true;
}
});
onScan("Bert", 0);
assertTrue(bert[0]);
assertFalse(ernie[0]);
bert[0] = false;
onScan("Ernie", 0);
assertFalse(bert[0]);
assertTrue(ernie[0]);
}
/**
* Test new registrations get past sightings.
*/
public void testNewListenersGetPastSightings() {
onScan("address", nowMillis());
scanner.onScanCycleComplete();
assertEquals(0, callback.found);
scanner.startScan(NO_FILTER, FOUND, callback);
assertEquals(1, callback.found);
}
/**
* Test new registrations don't get past sightings from too long ago.
*/
public void testNewListenersDontGetOldSightings() {
onScan("address", scanner.getLostTimestampMillis() - 1);
scanner.onScanCycleComplete();
scanner.startScan(NO_FILTER, FOUND, callback);
assertEquals(0, callback.found);
}
/**
* Test new registrations get recent finds per their filters.
*/
public void testNewListenersGetRecentPastSightingsCorrectlyFiltered() {
onScan("Bert", nowMillis());
onScan("Ernie", nowMillis());
clock.advance(10);
scanner.startScan(BERT_FILTER, FOUND, callback);
assertEquals(1, callback.found);
}
/////////////////////////////////////////////////////////////////////////////
private static class TestingCallback extends ScanCallback {
int found = 0;
int updated = 0;
int lost = 0;
int batched = 0;
@Override
public void onScanResult(int callbackType, ScanResult result) {
switch (callbackType) {
case ScanSettings.CALLBACK_TYPE_ALL_MATCHES:
updated++;
break;
case ScanSettings.CALLBACK_TYPE_FIRST_MATCH:
found++;
break;
case ScanSettings.CALLBACK_TYPE_MATCH_LOST:
lost++;
break;
default:
fail("Unrecognized callback type constant received: " + callbackType);
}
}
@Override
public void onBatchScanResults(List<ScanResult> scans) {
batched += scans.size();
}
}
private void onScan(String address, long timeMillis) {
byte[] addressBytes = address.getBytes();
byte[] scanRecordBytes = new byte[addressBytes.length + 2];
scanRecordBytes[0] = (byte) (addressBytes.length + 1);
scanRecordBytes[1] = 0x09; // Value of private ScanRecord.DATA_TYPE_LOCAL_NAME_COMPLETE;
System.arraycopy(addressBytes, 0, scanRecordBytes, 2, addressBytes.length);
scanner.onScanResult(address,
new ScanResult(
null /* BluetoothDevice */,
ScanRecord.parseFromBytes(scanRecordBytes),
0 /* rssi */,
TimeUnit.MILLISECONDS.toNanos(timeMillis)));
}
private long nowMillis() {
return clock.currentTimeMillis();
}
private static ScanSettings.Builder builder() {
return new ScanSettings.Builder();
}
private static ScanSettings buildScanSettingsForType(int callbackType) {
return builder().setCallbackType(callbackType).build();
}
}
| 36 | 100 | 0.722928 |
17163abd244e6ae60dc07d63162e066652eb21ea | 328 | package com.tqmars.requisition.domain.Specification;
/**
* 与规约类型
* @author jjh
* @param <T>
* 满足规约的对象
* @date 2015-12-16 16:54
*
*/
public class AndSpecification<T> extends CompositeSpecification<T>{
public AndSpecification(ISpecification<T> left, ISpecification<T> right,Class<T> t) {
super(left, right,t);
}
}
| 18.222222 | 86 | 0.70122 |
fd4059759d258d232695ef3dfe73901c3c46b370 | 6,217 | package org.main.smartmirror.smartmirror;
import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.provider.Settings;
import android.util.Log;
/**
* NsdHelper provides support for registering the device via NetworkServiceDiscovery
*/
public class NsdHelper {
Context mContext;
NsdManager mNsdManager;
//NsdManager.ResolveListener mResolveListener;
NsdManager.DiscoveryListener mDiscoveryListener;
NsdManager.RegistrationListener mRegistrationListener;
private boolean serviceRegistered = false;
public static final String SERVICE_TYPE = "_http._tcp.";
public static final String TAG = "NsdHelper";
// unique device name
public String mDeviceName = APP_NAME;
// name given to this instance by the service
public String mServiceName;
public static final String APP_NAME = "SmartMirror";
NsdServiceInfo mService;
public NsdHelper(Context context) {
mContext = context;
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
// The device name is of the form "SmartMirror_ID" where ID is the device's system ID
// This is used to distinguish this machine from other broadcasters on the network.
mDeviceName += "_" + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
//initializeRegistrationListener();
}
public class MyDiscoveryListener implements NsdManager.DiscoveryListener {
@Override
public void onDiscoveryStarted(String regType) {
Log.d(TAG, "onDiscoveryStarted()");
}
@Override
public void onServiceFound(NsdServiceInfo service) {
Log.d(TAG, "service found :: " + service);
if (!service.getServiceType().equals(SERVICE_TYPE)) {
Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
} else if (service.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same machine: " + mServiceName);
} else if (service.getServiceName().contains(APP_NAME)) {
mNsdManager.resolveService(service, new MyResolveListener());
}
}
@Override
public void onServiceLost(NsdServiceInfo service) {
Log.e(TAG, "service lost :: " + service);
if (mService == service) {
mService = null;
}
}
@Override
public void onDiscoveryStopped(String serviceType) {
Log.i(TAG, "Discovery stopped:" + serviceType);
}
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e(TAG, "Discovery failed: Error code:" + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
}
private class MyResolveListener implements NsdManager.ResolveListener {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
Log.e(TAG, "Resolve failed" + errorCode);
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.d(TAG, "Resolve Succeeded :: " + serviceInfo.getHost().toString());
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP :: " + serviceInfo.getHost().toString());
return;
}
mService = serviceInfo;
//((MainActivity)mContext).connectToRemote(mService); //Only if we want mirrors to initiate connections
}
}
public class MyRegistrationListener implements NsdManager.RegistrationListener {
@Override
public void onServiceRegistered(NsdServiceInfo nsdServiceInfo) {
mServiceName = nsdServiceInfo.getServiceName();
Log.d(TAG, "service registered as :: " + nsdServiceInfo);
serviceRegistered = true;
}
@Override
public void onRegistrationFailed(NsdServiceInfo arg0, int arg1) {
serviceRegistered = false;
Log.e(TAG, "Registration Failed :: " + arg1);
}
@Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
serviceRegistered = false;
Log.d(TAG, "ServiceUnregistered :: " + arg0);
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
serviceRegistered = true;
}
}
public void registerService(int port) {
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(port);
//serviceInfo.setHost(host);
serviceInfo.setServiceName(mDeviceName);
serviceInfo.setServiceType(SERVICE_TYPE);
Log.d(TAG, "serviceInfo :: " + serviceInfo);
unregisterService();
mRegistrationListener = new MyRegistrationListener();
mNsdManager.registerService(
serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
public void unregisterService(){
if (mRegistrationListener != null && serviceRegistered) {
Log.d(TAG, "unregistering Nsd Service");
mNsdManager.unregisterService(mRegistrationListener);
}
}
public void discoverServices() {
if (serviceRegistered) {
Log.i(TAG, "NsdHelper.discoverServices :: " + mDiscoveryListener);
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
} else {
Log.e(TAG, "NsdHelper.discoverServices SERVICE NOT REGISTERED");
}
}
public void stopDiscovery() {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}
public NsdServiceInfo getChosenServiceInfo() {
return mService;
}
public void tearDown() {
unregisterService();
//mResolveListener = null;
}
}
| 34.538889 | 115 | 0.641467 |
3d9a393f1a3a19788707444435f4a13159bde5fb | 568 |
package com.alibaba.alink.operator.batch.dataproc.format;
import com.alibaba.alink.operator.common.dataproc.format.FormatType;
import com.alibaba.alink.params.dataproc.format.KvToColumnsParams;
import org.apache.flink.ml.api.misc.param.Params;
public class KvToColumnsBatchOp extends BaseFormatTransBatchOp<KvToColumnsBatchOp>
implements KvToColumnsParams<KvToColumnsBatchOp> {
public KvToColumnsBatchOp() {
this(new Params());
}
public KvToColumnsBatchOp(Params params) {
super(FormatType.KV, FormatType.COLUMNS, params);
}
}
| 29.894737 | 82 | 0.774648 |
480d4dff5acb68aa4d84fa0a626b1dd2999ddfe3 | 1,121 | package com.android.task2.ui.base;
import androidx.databinding.ObservableBoolean;
import androidx.lifecycle.ViewModel;
import java.lang.ref.WeakReference;
import io.reactivex.disposables.CompositeDisposable;
public abstract class BaseViewModel<N> extends ViewModel {
private CompositeDisposable mCompositeDisposable;
private WeakReference<N> mNavigator;
private final ObservableBoolean mIsLoading = new ObservableBoolean(false);
public BaseViewModel() {
this.mCompositeDisposable = new CompositeDisposable();
}
public N getNavigator() {
return mNavigator.get();
}
public void setNavigator(N navigator) {
this.mNavigator = new WeakReference<>(navigator);
}
@Override
protected void onCleared() {
mCompositeDisposable.dispose();
super.onCleared();
}
public CompositeDisposable getCompositeDisposable() {
return mCompositeDisposable;
}
public ObservableBoolean getIsLoading() {
return mIsLoading;
}
public void setIsLoading(boolean isLoading) {
mIsLoading.set(false);
}
}
| 22.42 | 78 | 0.708296 |
2962adbe9822901ec78cd419ac645bd90ab5cdc1 | 7,219 | package python;
import cutcode.BlockCodeCompilerErrorException;
import cutcode.LogicalBlock;
import cutcode.GraphicalBlock;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import cutcode.InvalidNestException;
import java.util.ArrayList;
import java.util.HashMap;
public class GraphicalWhileBlock extends GraphicalBlock {
private GraphicalBooleanBinaryOperatorBlock condition;
private VBox[] nestBoxes;
private HashMap<VBox, double[]> nestDimensions;
private double initWidth, initHeight;
@Override
public VBox[] getNestBoxes() {
return nestBoxes;
}
public GraphicalWhileBlock(double width, double height) {
super(width, height);
this.initWidth = width;
this.initHeight = height;
nestDimensions = new HashMap<>();
this.setPadding(new Insets(height / 5));
this.setBackground(new Background(new BackgroundFill(Color.web("#6F73D2"), CornerRadii.EMPTY, Insets.EMPTY)));
HBox topLine = new HBox();
topLine.setSpacing(height / 5);
Label label = new Label("while");
label.setTextFill(Color.WHITE);
topLine.getChildren().add(label);
VBox bottomLine = new VBox();
bottomLine.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
bottomLine.setMinWidth(initWidth * 0.88);
bottomLine.setMaxWidth(bottomLine.getMinWidth());
bottomLine.setMinHeight(initHeight / 3);
bottomLine.setMaxHeight(bottomLine.getMinHeight());
double[] bottomLineDimensions = { bottomLine.getMinWidth(), bottomLine.getMinHeight() };
nestDimensions.put(bottomLine, bottomLineDimensions);
VBox conditionSpace = new VBox();
conditionSpace.setMinHeight(initHeight / 3);
conditionSpace.setMaxHeight(conditionSpace.getMinHeight());
conditionSpace.setMinWidth(initWidth * 0.55);
conditionSpace.setMaxWidth(conditionSpace.getMinWidth());
double[] conditionSpaceDimensions = { conditionSpace.getMinWidth(), conditionSpace.getMinHeight() };
nestDimensions.put(conditionSpace, conditionSpaceDimensions);
conditionSpace.setBackground(
new Background(new BackgroundFill(Color.web("#E6E6E6"), CornerRadii.EMPTY, Insets.EMPTY)));
topLine.getChildren().add(conditionSpace);
this.getChildren().addAll(topLine, bottomLine);
nestBoxes = new VBox[2];
nestBoxes[0] = conditionSpace;
nestBoxes[1] = bottomLine;
}
@Override
public LogicalBlock getLogicalBlock() throws BlockCodeCompilerErrorException {
if (nestBoxes[0].getChildren().size() != 1) {
tagErrorOnBlock();
throw new BlockCodeCompilerErrorException();
}
ArrayList<LogicalBlock> executeBlocks = new ArrayList<>();
for (Node n : nestBoxes[1].getChildren()) { // gets all the blocks to be executed if the if statement evaluates
// to true
((GraphicalBlock) n).setIndentFactor(getIndentFactor() + 1);
executeBlocks.add(((GraphicalBlock) n).getLogicalBlock());
}
return logicalFactory.createWhileLoop(getIndentFactor(),
((GraphicalBlock) nestBoxes[0].getChildren().get(0)).getLogicalBlock(), executeBlocks);
}
@Override
public GraphicalBlock cloneBlock() {
return new GraphicalWhileBlock(initWidth, initHeight);
}
/**
* @return an array of 2 points, the top left of the slots of the operand
* spaces, regardless of whether something is already nested there or
* not.
*/
@Override
public Point2D[] getNestables() {
Point2D[] ret = new Point2D[nestBoxes.length];
ret[0] = nestBoxes[0].localToScene(nestBoxes[0].getLayoutBounds().getMinX(),
nestBoxes[0].getLayoutBounds().getMinY());
double secondaryIncrementY = 0;
for (Node n : nestBoxes[1].getChildren())
secondaryIncrementY += ((GraphicalBlock) n).getHeight();
ret[1] = nestBoxes[1].localToScene(nestBoxes[1].getLayoutBounds().getMinX(),
nestBoxes[0].getLayoutBounds().getMinY() + secondaryIncrementY);
return ret;
}
@Override
public void nest(int index, GraphicalBlock nest) throws InvalidNestException {
if (index == 0) {
VBox box = nestBoxes[0];
if (nestBoxes[index].getChildren().size() != 0)
throw new InvalidNestException();
increment(box, nest);
box.getChildren().add(nest);
} else if (index == 1) {
VBox box = nestBoxes[1];
increment(box, nest);
box.getChildren().add(nest);
} else
throw new InvalidNestException();
nest.setNestedIn(this);
}
@Override
public void unnest(VBox box, GraphicalBlock rem) throws InvalidNestException {
// resets sizes of block and fields
box.getChildren().remove(rem);
double[] dimensions = nestDimensions.get(box);
if (dimensions != null && dimensions.length == 2) {
rem.minHeightProperty().removeListener(super.heightListeners.get(rem));
rem.minWidthProperty().removeListener(super.widthListeners.get(rem));
super.heightListeners.remove(rem);
super.widthListeners.remove(rem);
box.getChildren().remove(rem);
double boxHeight = box.getMaxHeight();
if (box.getChildren().size() > 0) {
double newBoxWidth = 0;
for (Node n : box.getChildren()) {
GraphicalBlock b = (GraphicalBlock) n;
if (b.getMaxWidth() > newBoxWidth) {
newBoxWidth = b.getMaxWidth();
}
}
double deltaWidth = box.getMaxWidth() - newBoxWidth;
double deltaHeight = rem.getMinHeight(); // no need for subtraction since there's more than one nested
// block
double farthestOut = 0;
for(VBox b : this.nestBoxes) {
double farOut = b.getMaxWidth() + b.getLayoutX();
if(farOut > farthestOut) {
farthestOut = farOut;
}
}
box.setMaxWidth(newBoxWidth);
box.setMinWidth(box.getMaxWidth());
box.setMaxHeight(boxHeight - rem.getMinHeight());
box.setMinHeight(box.getMaxHeight());
this.setSize(this.getMaxWidth() - deltaWidth, this.getMinHeight() - deltaHeight);
} else {
double newWidth = this.getMinWidth() - (box.getMaxWidth() - this.nestDimensions.get(box)[0]);
double newHeight = this.getMinHeight() - (box.getMaxHeight() - this.nestDimensions.get(box)[1]);
box.setMaxWidth(this.nestDimensions.get(box)[0]);
box.setMinWidth(box.getMaxWidth());
box.setMaxHeight(this.nestDimensions.get(box)[1]);
box.setMinHeight(box.getMaxHeight());
this.setSize(newWidth, newHeight);
}
}
}
@Override
public int putInHashMap(HashMap<Integer, GraphicalBlock> lineLocations) {
lineLocations.put(getLineNumber(), this);
int ret = getLineNumber() + 1;
for (Node n : nestBoxes[1].getChildren()) {
if (n instanceof GraphicalBlock) {
((GraphicalBlock) n).setLineNumber(ret);
ret = ((GraphicalBlock) n).putInHashMap(lineLocations);
}
}
return ret + logicalFactory.getEndingBrace(); // Block class reused for java so might have ending brace
}
@Override
public ArrayList<GraphicalBlock> getChildBlocks() {
ArrayList<GraphicalBlock> ret = new ArrayList<>();
for (VBox box : nestBoxes) {
for (Node b : box.getChildren()) {
if (b instanceof GraphicalBlock) {
ret.add((GraphicalBlock) b);
}
}
}
return ret;
}
@Override
public VBox[] getIndependentNestBoxes() {
VBox[] ret = new VBox[1];
ret[0] = nestBoxes[1];
return ret;
}
}
| 33.267281 | 113 | 0.715196 |
c3b9236d852b25d13e7ac30e3e1d2492042d7332 | 357 | package it.lisik.itunesreceiptvalidator;
public enum Environment {
PRODUCTION("https://buy.itunes.apple.com"),
SANDBOX("https://sandbox.itunes.apple.com");
private final String serviceUrl;
Environment(String serviceUrl) {
this.serviceUrl = serviceUrl;
}
public String getServiceUrl() {
return serviceUrl;
}
}
| 21 | 48 | 0.677871 |
d9fd20bab4154246446cb081fc753a3aa710b79c | 633 | package com.yin.springboot.user.center.mapper;
import com.yin.springboot.user.center.domain.TbPermission;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface TbPermissionMapper extends Mapper<TbPermission>, MySqlMapper<TbPermission> {
int updateBatch(List<TbPermission> list);
int batchInsert(@Param("list") List<TbPermission> list);
int insertOrUpdate(TbPermission record);
int insertOrUpdateSelective(TbPermission record);
List<TbPermission> selectByUserId(@Param("userId") Long userId);
} | 35.166667 | 93 | 0.794629 |
eafffea76597872b120d1d562cdcc6ac3da7533a | 846 | package org.narrative.network.shared.services;
import org.narrative.network.core.cluster.partition.HighPriorityRunnable;
import org.narrative.network.core.cluster.partition.PartitionGroup;
/**
* Created by IntelliJ IDEA.
* User: jonmark
* Date: 5/9/16
* Time: 3:26 PM
*/
public interface DelayedResultRunnable extends HighPriorityRunnable {
static void process(DelayedResultRunnable runnable, Runnable errorRunnable) {
// we only need to delay the result if this is a writable PartitionGroup. if it's read-only, let's just send the response now.
if (PartitionGroup.getCurrentPartitionGroup().isReadOnly()) {
runnable.run();
return;
}
PartitionGroup.addEndOfPartitionGroupRunnable(runnable);
PartitionGroup.addEndOfPartitionGroupRunnableForError(errorRunnable);
}
}
| 33.84 | 134 | 0.736407 |
113c8bee349f8f2691f81c23a1fa5a1455e55aa4 | 327 | package net.optifine.entity.model.anim;
public class Constant implements IExpression
{
private float value;
public Constant(float value)
{
this.value = value;
}
public float eval()
{
return this.value;
}
public String toString()
{
return "" + this.value;
}
}
| 14.863636 | 44 | 0.590214 |
05b03665e8903fd8baed2e3d0df6edf3e2569c02 | 1,130 | package ru.job4j.chess.firuges.black;
import org.junit.Test;
import ru.job4j.chess.firuges.Cell;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
public class BishopBlackTest {
@Test
public void truePosition() {
BishopBlack bishopBlack = new BishopBlack(Cell.C1);
Cell exp = bishopBlack.position();
assertThat(exp, is(Cell.C1) );
}
@Test
public void hasWay() {
BishopBlack bishopBlack = new BishopBlack(Cell.C1);
Cell[] out = bishopBlack.way(Cell.G5);
Cell[] expected = {Cell.D2, Cell.E3, Cell.F4, Cell.G5};
assertThat(out, is(expected));
}
@Test
public void dontHasDiagonal() {
BishopBlack bishopBlack = new BishopBlack(Cell.C1);
Cell position = bishopBlack.position();
assertFalse(bishopBlack.isDiagonal(position, Cell.H1));
}
@Test
public void hasCopy() {
BishopBlack bishopBlack = new BishopBlack(Cell.C1);
Cell exp = bishopBlack.copy(Cell.D3).position();
assertThat(exp, is(Cell.D3));
}
} | 28.25 | 63 | 0.655752 |
5b5fb32020a7803c6e4d2960c80ae45f26ac1028 | 7,968 | package org.camunda.demo.camel;
import java.util.Properties;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import static org.camunda.bpm.camel.component.CamundaBpmConstants.*;
import org.camunda.demo.camel.dto.Order;
import org.camunda.demo.camel.processor.MapToOrderProcessor;
import org.camunda.demo.camel.processor.OrderToMapProcessor;
/**
*
* @author Nils Preusker - nils.preusker@camunda.com
* @author Rafael Cordones - rafael@cordones.me
* @author Bernd Ruecker
*
*/
public class OpenAccountRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
/*
* Get hot-folder configuration from a properties file
*
* TODO: maybe we can use http://camel.apache.org/using-propertyplaceholder.html
*/
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("route.properties"));
String ordersFolder = properties.getProperty("folder.orders");
String postidentFolder = properties.getProperty("folder.postident");
if(ordersFolder == null || postidentFolder == null) {
throw new RuntimeException("could not read properties for camel route, make sure there" +
" is a file called route.properties in the root or the resoureces folder of your " +
"application that contains the properties folder.orders and folder.postident");
}
/*
* There are two ways of starting the open-account process:
*
* - placing an XML file in a hot folder (see route.properties for folder location)
* - sending a JSON order to a REST web service (see README.txt for instructions)
*/
// This route handles files placed in the incoming orders folder (see route.properties file)
// and routes the XML to a JMS queue:
from("file://" + ordersFolder).
routeId("hot-folder order route").
log("=======================").
log("Received order from hot-folder").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("Delivering order to JMS XML queue").
to("jms:xmlQueue");
// Order objects that are sent to the REST web service are placed in a JMS queue called
// orderQueue (see README.txt about setting up the JMS queue). This route listens for
// incoming messages on that queue, transforms the object to XML using the marshalling
// feature that is built into camel and delivers the resulting XML to the same queue the
// incoming XML documents are placed in:
from("jms:orderQueue").
routeId("order to xml route").
log("=======================").
log("received order from orderQueue").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("transforming order object to xml").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
marshal(new JaxbDataFormat(Order.class.getPackage().getName())).
log("=======================").
log("delivering order xml to xmlQueue").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
to("jms:xmlQueue");
/*
* This route listens for incoming messages on the JMS queue named xmlQueue. When a message
* arrives, a CDI bean called incomingOrderService is used to extract the data from the XML
* into a HashMap that will be passed on to the camunda BPM engine when the process instance
* is started. The HashMap is the same as a variable map that can be passed on to process
* instances via the camunda BPM API.
*/
from("jms:xmlQueue").
routeId("start order process route").
log("=======================").
log("received order xml from xmlQueue").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("setting order # to '" + CAMUNDA_BPM_BUSINESS_KEY + "' property").
setProperty(CAMUNDA_BPM_BUSINESS_KEY).xpath("//@ordernumber").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("transforming order xml to order object").
unmarshal(new JaxbDataFormat(Order.class.getPackage().getName())).
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("transforming order object to variable map (java.util.Map) as input for the camunda BPM process").
process(new OrderToMapProcessor()).
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("starting open-account process").
to("camunda-bpm:start?processDefinitionKey=open-account").
log("=======================").
log("open-account process started").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true")
;
/*
* If the order was rejected, we'll send a mail to the customer to inform him that his
* application will not be processed.
*/
from("direct:inform-customer").
routeId("inform customer route").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
beanRef("emailService");
/*
* When the order is approved, it can be passed to the accountService to create an account
* object and persist it to the database. Since the order was split up into values in a
* java.util.Map, we'll first pass the map to the MapToOrderProcessor.
*/
from("direct:setup-account").
routeId("set up account route").
log("=======================").
log("transforming process variable map to order object: ${body}").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
process(new MapToOrderProcessor()).
log("=======================").
log("calling accountService to create account from incoming order").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
beanRef("accountService");
/*
* Finally, this route waits for incoming postident scans to be placed in a hot folder.
* When a document is placed there (edit route.properties to configure the location of
* the folder), the order number is extracted from the file name and used as correlation
* id to send a signal to the waiting process instance.
*/
from("file://" + postidentFolder).
routeId("incoming postident route").
log("=======================").
log("received postident document").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("extracting order number from file name").
process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String businessKey = exchange.getIn().getHeader("CamelFileName").toString().split("-")[1].substring(0, 4);
exchange.setProperty(CAMUNDA_BPM_BUSINESS_KEY, businessKey);
}
}).
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
log("correlating document with process instance").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true").
log("=======================").
to("camunda-bpm://message?processDefinitionKey=open-account&activityId=wait_for_postident").
to("log:org.camunda.demo.camel.route?level=INFO&showAll=true&multiline=true");
}
} | 47.712575 | 116 | 0.642947 |
ed259830505f3f5ed3193e8513b6d976ba2feb32 | 339 |
package com.profittracker;
import net.runelite.client.RuneLite;
import net.runelite.client.externalplugins.ExternalPluginManager;
public class ProfitTrackerTest
{
public static void main(String[] args) throws Exception
{
ExternalPluginManager.loadBuiltin(ProfitTrackerPlugin.class);
RuneLite.main(args);
}
}
| 22.6 | 69 | 0.761062 |
774c54888539b9f8981aec97c246716f0fcef7cf | 504 | package day06;
/**
* @ClassName Solution
* @Author zhanghaorui
* @Date 2021/5/31 1:51 下午
* @Description
* 给你一个整数 n,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。
*
* 如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/power-of-two
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Version 1.0
*/
public class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
| 21 | 77 | 0.569444 |
0134ecd25e00ae615fca7d4a8bf6714ada381fa6 | 3,282 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.core.services.impl.placeholder.standard;
import io.github.nucleuspowered.nucleus.core.services.interfaces.IPlayerDisplayNameService;
import net.kyori.adventure.text.Component;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.Server;
import org.spongepowered.api.SystemSubject;
import org.spongepowered.api.placeholder.PlaceholderContext;
import org.spongepowered.api.placeholder.PlaceholderParser;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
public class NamePlaceholder<T> implements PlaceholderParser {
private static final Component CONSOLE = Component.text("-");
private final IPlayerDisplayNameService playerDisplayNameService;
private final boolean consoleFilter;
private final BiFunction<IPlayerDisplayNameService, T, Component> parser;
private final ResourceKey resourceKey;
private final Class<T> clazz;
public NamePlaceholder(
final Class<T> clazz,
final IPlayerDisplayNameService playerDisplayNameService,
final BiFunction<IPlayerDisplayNameService, T, Component> parser,
final String id) {
this(clazz, playerDisplayNameService, parser, id, false);
}
public NamePlaceholder(
final Class<T> clazz,
final IPlayerDisplayNameService playerDisplayNameService,
final BiFunction<IPlayerDisplayNameService, T, Component> parser,
final String id,
final boolean consoleFilter) {
this.clazz = clazz;
this.playerDisplayNameService = playerDisplayNameService;
this.parser = parser;
this.consoleFilter = consoleFilter;
this.resourceKey = ResourceKey.resolve(id);
}
@Override
public Component parse(final PlaceholderContext placeholder) {
final Optional<Object> associated = placeholder.associatedObject();
if (associated.isPresent()) {
if (this.consoleFilter && associated.get() instanceof SystemSubject || associated.get() instanceof Server) {
return CONSOLE;
} else if (this.clazz.isInstance(associated.get())) {
return this.parser.apply(this.playerDisplayNameService, this.clazz.cast(associated.get()));
}
}
return Component.empty();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || this.getClass() != o.getClass()) {
return false;
}
final NamePlaceholder<?> that = (NamePlaceholder<?>) o;
return this.consoleFilter == that.consoleFilter && Objects.equals(this.playerDisplayNameService, that.playerDisplayNameService)
&& Objects.equals(this.parser, that.parser) && Objects.equals(this.resourceKey, that.resourceKey) && Objects
.equals(this.clazz, that.clazz);
}
@Override
public int hashCode() {
return Objects.hash(this.playerDisplayNameService, this.consoleFilter, this.parser, this.resourceKey, this.clazz);
}
}
| 40.518519 | 135 | 0.693784 |
45ac34a223a080ecf2bd3e4260391e6fd853c96f | 1,120 |
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.stream.*;
class DataSource {
void go() throws Exception {
Path file = Paths.get("data1000.csv");
try (Stream<String> lines = Files.lines(file, Charset.defaultCharset())) {
lines.forEachOrdered(System.out::println);
}
}
Stream<String> getStream() throws Exception {
Path file = Paths.get("data1000.csv");
Stream<String> lines = Files.lines(file, Charset.defaultCharset());
return lines;
}
}
class Worker {
void process(String s) {
System.out.println(s);
}
}
public class Quick {
void go() throws Exception {
new DataSource().go();
}
void doWork() throws Exception {
DataSource dataSource = new DataSource();
Stream<String> lines = dataSource.getStream();
Worker worker = new Worker();
lines.forEach( line -> worker.process(line) );
lines.close();
}
public static void main(String... args) throws Exception {
Quick quick = new Quick();
quick.doWork();
}
}
| 23.829787 | 82 | 0.600893 |
a543e858e923c62b990b906b150cb3bfa6617307 | 1,025 | // Copyright Eagle Legacy Modernization LLC, 2010-date
// Original author: Steven A. O'Hara, Sep 1, 2011
package com.eagle.programmar.CMD.Statements;
import com.eagle.programmar.CMD.Terminals.CMD_Argument;
import com.eagle.programmar.CMD.Terminals.CMD_Keyword;
import com.eagle.tokens.TokenChooser;
import com.eagle.tokens.TokenList;
import com.eagle.tokens.TokenSequence;
import com.eagle.tokens.punctuation.PunctuationSlash;
public class CMD_Rmdir_Statement extends TokenSequence
{
public @DOC("rmdir.mspx") CMD_Keyword RMDIR = new CMD_Keyword("rmdir");
public @OPT TokenList<CMD_Rmdir_Option> opts;
public CMD_Argument dir;
public static class CMD_Rmdir_Option extends TokenChooser
{
public @CHOICE static class CMD_Rmdir_Option_Q extends TokenSequence
{
public PunctuationSlash slash;
public CMD_Keyword Q = new CMD_Keyword("q");
}
public @CHOICE static class CMD_Rmdir_Option_S extends TokenSequence
{
public PunctuationSlash slash;
public CMD_Keyword S = new CMD_Keyword("s");
}
}
}
| 30.147059 | 72 | 0.788293 |
d8a72e438d1021117445414ef062fae6a76b9e81 | 861 | package msifeed.mc.core;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import java.util.Map;
@IFMLLoadingPlugin.DependsOn("forge")
@IFMLLoadingPlugin.TransformerExclusions({"msifeed.mc.core"})
public class MoreCorePlugin implements IFMLLoadingPlugin {
static boolean isDevEnv = false;
@Override
public String[] getASMTransformerClass() {
return new String[] {
JourneymapTransformer.class.getName()
};
}
@Override
public String getModContainerClass() {
return null;
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
isDevEnv = !(boolean) data.get("runtimeDeobfuscationEnabled");
}
@Override
public String getAccessTransformerClass() {
return null;
}
}
| 22.076923 | 70 | 0.666667 |
150a7c5a5fb158e7d44be635e17698382ac069fb | 4,051 | package nachos.threads;
import nachos.machine.Machine;
public class RoundRobinSchedulerTest {
public static void runTest() {
System.out.println("###############################");
System.out.println("## RoundRobin testing begins ##");
System.out.println("###############################");
/* Run a simple test of the scheduler */
runBasicTest();
/* Run a test with mixed CPU and I/O simulation */
runMixedTest();
/* Run any other tests */
// runComplexTest();
// runAnotherComplexTest();
// ...
System.out.println("#############################");
System.out.println("## RoundRobin testing ends ##");
System.out.println("#############################\n");
}
private static class ThreadTask implements Runnable {
private final int id;
private boolean terminated;
private boolean io;
public ThreadTask(int id, boolean io) {
this.id = id;
this.terminated = false;
this.io = io;
}
public void terminate() {
this.terminated = true;
}
@Override
public void run() {
System.out.println("thread " + KThread.currentThread().getName()
+ " started");
while (!terminated) {
// Remember this is a thread running inside the kernel,
// so there's no automatic preemption -- you need to
// manually yield to other threads.
if (io) { // simulate I/O job
// do I/O lasting 200 ticks
long ioTime = 200;
// this blocks the thread until ioTime has passed
ThreadedKernel.alarm.waitUntil(ioTime);
System.out.print("i" + id);
} else { // simulate CPU job
// do 800 ticks of 'computation'
Machine.interrupt().tick(800);
System.out.print("c" + id);
}
}
}
}
private static void runBasicTest() {
System.out.println("\n### Running basic RR test ###");
// create workers to specify what the threads will do
ThreadTask worker1 = new ThreadTask(1, false);
ThreadTask worker2 = new ThreadTask(2, false);
ThreadTask worker3 = new ThreadTask(3, false);
// initialize the new threads to run the workers
KThread thread1 = new KThread(worker1);
KThread thread2 = new KThread(worker2);
KThread thread3 = new KThread(worker3);
// name the threads for debugging and identification
thread1.setName("t1");
thread2.setName("t2");
thread3.setName("t3");
// start running the threads in parallel
thread1.fork();
thread2.fork();
thread3.fork();
// let the threads run for 5000 ticks
ThreadedKernel.alarm.waitUntil(5000);
// signal the threads to exit
worker1.terminate();
worker2.terminate();
worker3.terminate();
// wait until all threads are finished
thread1.join();
thread2.join();
thread3.join();
System.out.println("\n### Basic RR test finished ###\n");
}
private static void runMixedTest() {
System.out.println("\n### Running mixed RR test ###");
// create workers to specify what the threads will do
ThreadTask worker1 = new ThreadTask(1, false);
ThreadTask worker2 = new ThreadTask(2, true);
ThreadTask worker3 = new ThreadTask(3, false);
// initialize the new threads to run the workers
KThread thread1 = new KThread(worker1);
KThread thread2 = new KThread(worker2);
KThread thread3 = new KThread(worker3);
// name the threads for debugging and identification
thread1.setName("t1");
thread2.setName("t2");
thread3.setName("t3");
// start running the threads in parallel
thread1.fork();
thread2.fork();
thread3.fork();
// let the threads run for 5000 ticks
ThreadedKernel.alarm.waitUntil(5000);
// signal the threads to exit
worker1.terminate();
worker2.terminate();
worker3.terminate();
// wait until all threads are finished
thread1.join();
thread2.join();
thread3.join();
System.out.println("\n### Mixed RR test finished ###\n");
}
}
| 26.651316 | 70 | 0.609232 |
2360d857594f340f4645f02de109e559017e8db6 | 3,057 | /*
* The MIT License (MIT)
* Copyright (c) 2017 Nicholas Wright
* http://opensource.org/licenses/MIT
*/
package com.github.dozedoff.commonj.string;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
public class ConvertTest {
@BeforeClass
public static void createInstance() {
new Convert(); // Used to get 100% coverage for static only classes
}
@Test
public final void testByteToHexNull() {
String hex = Convert.byteToHex(null);
assertNull(hex);
}
@Test
public final void testByteToHex00() {
String hex = Convert.byteToHex(Byte.decode("0"));
assertThat(hex, is("00"));
}
@Test
public final void testByteToHex01() {
String hex = Convert.byteToHex(Byte.decode("1"));
assertThat(hex, is("01"));
}
@Test
public final void testByteToHexFF() {
String hex = Convert.byteToHex(Byte.decode("-1"));
assertThat(hex, is("FF"));
}
@Test
public final void testByteToHexAA() {
String hex = Convert.byteToHex(Byte.decode("-86"));
assertThat(hex, is("AA"));
}
@Test
public final void testByteToHexC0() {
String hex = Convert.byteToHex(Byte.decode("-64"));
assertThat(hex, is("C0"));
}
@Test
public final void testStringToIntNull() {
int value = Convert.stringToInt(null, 3);
assertThat(value, is(3));
}
@Test
public final void testStringToIntEmpty() {
int value = Convert.stringToInt("", 3);
assertThat(value, is(3));
}
@Test
public final void testStringToIntNaN() {
int value = Convert.stringToInt("jakdfhakjh", 3);
assertThat(value, is(3));
}
@Test
public final void testStringToIntFloat() {
int value = Convert.stringToInt("2.56", 3);
assertThat(value, is(3));
}
@Test
public final void testStringToInt() {
int value = Convert.stringToInt("5", 3);
assertThat(value, is(5));
}
@Test
public final void testStringToIntNegative() {
int value = Convert.stringToInt("-7", 3);
assertThat(value, is(-7));
}
@Test
public void testStringToBooleanNullDefaultFalse() {
boolean value = Convert.stringToBoolean(null, false);
assertThat(value, is(false));
}
@Test
public void testStringToBooleanNullDefaultTrue() {
boolean value = Convert.stringToBoolean(null, true);
assertThat(value, is(true));
}
@Test
public void testStringToBooleanAllCaps() {
boolean value = Convert.stringToBoolean("TRUE", false);
assertThat(value, is(true));
}
@Test
public void testStringToBooleanTrueCamelCase() {
boolean value = Convert.stringToBoolean("TrUe", false);
assertThat(value, is(true));
}
@Test
public void testStringToBooleanFalseCamelCase() {
boolean value = Convert.stringToBoolean("fAlSE", true);
assertThat(value, is(false));
}
@Test
public void testStringToBooleanEmpty() {
boolean value = Convert.stringToBoolean("", true);
assertThat(value, is(false));
}
@Test
public void testStringToBooleanInvalid() {
boolean value = Convert.stringToBoolean("foo", true);
assertThat(value, is(false));
}
} | 22.644444 | 69 | 0.706248 |
d1b29f32d980a4a56aeb8e5c2595bbb4a54dbc84 | 446 | package org.sana.android.procedure;
/**
* An Exception to throw when parsing a Procedure declared in text form.
*
* @author Sana Development Team
*
*/
public class ProcedureParseException extends Exception {
private static final long serialVersionUID = 1L;
/**
* A new Exception with a message.
*
* @param text the message.
*/
public ProcedureParseException(String text) {
super(text);
}
} | 22.3 | 72 | 0.659193 |
98e8e8fcea9f535f0d2dc6bdb086189488c0c05d | 1,661 | package io.github.zero88.qwe.iot.connector.bacnet.mixin.adjuster;
import org.junit.Assert;
import org.junit.Test;
import com.serotonin.bacnet4j.type.constructed.PriorityArray;
import com.serotonin.bacnet4j.type.constructed.PriorityValue;
import com.serotonin.bacnet4j.type.enumerated.AbortReason;
import com.serotonin.bacnet4j.type.primitive.Boolean;
import com.serotonin.bacnet4j.type.primitive.CharacterString;
import com.serotonin.bacnet4j.type.primitive.Null;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
public class PriorityValuesAdjusterTest {
@Test
public void test_adjust_unmatched_value() {
final PriorityArray array = new PriorityArray();
array.put(2, new UnsignedInteger(100));
final PriorityArray values = new PriorityValuesAdjuster().apply(Boolean.TRUE, array);
final PriorityValue base1 = values.getBase1(1);
Assert.assertNotNull(base1);
Assert.assertEquals(Null.instance, base1.getConstructedValue());
final PriorityValue base2 = values.getBase1(2);
Assert.assertNotNull(base2);
Assert.assertEquals(new UnsignedInteger(100), base2.getConstructedValue());
}
@Test
public void test_adjust_matched_value() {
final PriorityArray array = new PriorityArray();
array.put(1, new CharacterString(AbortReason.outOfResources.toString()));
final PriorityArray values = new PriorityValuesAdjuster().apply(AbortReason.other, array);
final PriorityValue base1 = values.getBase1(1);
Assert.assertNotNull(base1);
Assert.assertEquals(AbortReason.outOfResources, base1.getConstructedValue());
}
}
| 41.525 | 98 | 0.751957 |
f5399a9bbc87dbfc5bd5599baad57214d4c98c16 | 1,824 | /* Copyright 2020 The FedLearn Authors. 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.jdt.fedlearn.core.entity.secureInference;
import com.jdt.fedlearn.common.entity.core.Message;
/**
* @author zhangwenxi
*/
public class SecureInferenceReq2 implements Message {
private int[] leaves;
private String[][] cipher0;
private String[][] cipher1;
private byte[][] wArray;
public SecureInferenceReq2() {
}
public SecureInferenceReq2(int[] leaves) {
this.leaves = leaves;
}
public SecureInferenceReq2(int[] leaves, String[][] cipher0, String[][] cipher1) {
this.leaves = leaves;
this.cipher0 = cipher0;
this.cipher1 = cipher1;
}
public SecureInferenceReq2(String[][] cipher0, String[][] cipher1, byte[][] wArray) {
this.cipher0 = cipher0;
this.cipher1 = cipher1;
this.wArray = wArray;
}
public int[] getLeaves() {
return leaves;
}
public void setLeaves(int[] leaves) {
this.leaves = leaves;
}
public String[][] getCipher0() {
return cipher0;
}
public byte[][] getwArray() {
return wArray;
}
public void setwArray(byte[][] wArray) {
this.wArray = wArray;
}
public String[][] getCipher1() {
return cipher1;
}
}
| 26.057143 | 89 | 0.662829 |
736ff4f6e41637c4c3135fe6da2e296bc6a52efb | 8,366 | /******************************************************************
* File: BaseAction.java
* Created by: Dave Reynolds
* Created on: 20 Apr 2014
*
* (c) Copyright 2014, Epimorphics Limited
*
*****************************************************************/
package com.epimorphics.appbase.tasks.impl;
import static com.epimorphics.appbase.tasks.ActionJsonFactorylet.*;
import static com.epimorphics.json.JsonUtil.*;
import java.util.Map.Entry;
import org.apache.jena.atlas.json.JsonObject;
import org.apache.jena.atlas.json.JsonString;
import org.apache.jena.atlas.json.JsonValue;
import com.epimorphics.appbase.core.AppConfig;
import com.epimorphics.appbase.tasks.Action;
import com.epimorphics.appbase.tasks.ActionJsonFactorylet;
import com.epimorphics.appbase.tasks.ActionManager;
import com.epimorphics.appbase.tasks.ActionTrigger;
import com.epimorphics.json.JsonUtil;
import com.epimorphics.tasks.ProgressMonitorReporter;
import com.epimorphics.util.EpiException;
/**
* Base class for implementing generic, configurable actions.
*/
public abstract class BaseAction implements Action {
protected JsonObject configuration;
protected Action onError;
protected Action onSuccess;
protected ActionTrigger trigger;
public BaseAction() {
configuration = new JsonObject();
}
public BaseAction(JsonObject config) {
configuration = makeJson(config);
}
public void setConfig(String key, Object value) {
configuration.put(key, asJson(value));
}
public void setConfig(JsonObject config) {
mergeInto(configuration, config);
}
@Override
public JsonObject getConfig() {
return configuration;
}
public Object getConfig(String key) {
return configuration.get(key);
}
public String getStringConfig(String key, String deflt) {
return getStringValue(configuration, key, deflt);
}
public int getIntConfig(String key, int deflt) {
return getIntValue(configuration, key, deflt);
}
public boolean getBooleanConfig(String key, boolean deflt) {
return getBooleanValue(configuration, key, deflt);
}
@Override
public String getName() {
return getStringConfig(NAME_KEY, "BaseAction");
}
@Override
public void setName(String name) {
setConfig(NAME_KEY, name);
}
public String getDescription() {
return getStringConfig(DESCRIPTION_KEY, "");
}
@Override
public int getTimeout() {
return getIntConfig(TIMEOUT_KEY, -1);
}
public JsonValue getParameter(JsonObject parameters, String key) {
JsonValue value = parameters.get(key);
// No longer needed, doRun should always see the merged configuration plus parameters
// if (value == null) {
// value = configuration.get(key);
// }
return value;
}
public JsonValue getRequiredParameter(JsonObject parameters, String key) {
JsonValue v = getParameter(parameters, key);
if (v == null) {
throw new EpiException("Action could not find required parameter: " + key);
}
return v;
}
public String getStringParameter(JsonObject parameters, String key, String deflt) {
JsonValue v = getParameter(parameters, key);
if (v != null && v.isString()) {
return v.getAsString().value();
} else {
return deflt;
}
}
public String getStringParameter(JsonObject parameters, String key) {
JsonValue v = getParameter(parameters, key);
if (v != null && v.isString()) {
return v.getAsString().value();
} else {
throw new EpiException("Action could not find required parameter: " + key);
}
}
public int getIntParameter(JsonObject parameters, String key, int deflt) {
JsonValue v = getParameter(parameters, key);
if (v != null && v.isNumber()) {
return v.getAsNumber().value().intValue();
} else {
return deflt;
}
}
public boolean getBooleanParameter(JsonObject parameters, String key, boolean deflt) {
JsonValue v = getParameter(parameters, key);
if (v != null && v.isBoolean()) {
return v.getAsBoolean().value();
} else {
return deflt;
}
}
public Action getActionNamed(String name) {
ActionManager am = AppConfig.getApp().getA(ActionManager.class);
Action a = am.get(name);
if (a == null) {
throw new EpiException("Can't find the action named: " + name);
}
return a;
}
@Override
public Action getOnError() {
return onError;
}
@Override
public Action getOnSuccess() {
return onSuccess;
}
public void setOnError(Action onError) {
this.onError = onError;
}
public void setOnSuccess(Action onSuccess) {
this.onSuccess = onSuccess;
}
@Override
public void resolve(ActionManager am) {
if (onError == null) {
onError = resolveAction(am, getConfig(ON_ERROR_KEY));
}
if (onSuccess == null) {
onSuccess = resolveAction(am, getConfig(ON_SUCCESS_KEY));
}
}
protected Action resolveAction(ActionManager am, Object action) {
Action resolved;
if (action == null) {
return null;
} else if (action instanceof String) {
resolved = am.get((String)action);
} else if (action instanceof JsonString) {
resolved = am.get( ((JsonString)action).value() );
} else if (action instanceof Action) {
resolved = (Action)action;
} else if (action instanceof JsonObject) {
resolved = ActionJsonFactorylet.parseAction((JsonObject)action);
} else {
throw new EpiException("Unexpected type for bound action (should be String or Action): " + action);
}
if (resolved == null) {
return null;
}
resolved.resolve(am);
return resolved;
}
@Override
public ActionTrigger getTrigger() {
return trigger;
}
public void setTrigger(ActionTrigger trigger) {
this.trigger = trigger;
}
@Override
public JsonObject run(JsonObject parameters, ProgressMonitorReporter monitor) {
return doRun( mergedCall(parameters), monitor);
}
protected abstract JsonObject doRun(JsonObject parameters, ProgressMonitorReporter monitor);
/**
* Merge a set of configurations for a base action into this configuration,
* not overriding any current settings
*/
public void mergeBaseConfiguration(Action base) {
if (base instanceof BaseAction) {
configuration = merge(((BaseAction)base).configuration, configuration);
}
if (onError == null) {
onError = base.getOnError();
}
if (onSuccess == null) {
onSuccess = base.getOnSuccess();
}
}
public JsonObject error(String message, ProgressMonitorReporter monitor) {
monitor.reportError(message);
return JsonUtil.emptyObject();
}
/**
* In calls the non-@ configuration overrides parameters to allow us e.g. bind a messages into a message action
* and not have it overridden with messages for other actions when chaining.
*/
protected JsonObject mergedCall(JsonObject parameters) {
JsonObject call = JsonUtil.makeJson(parameters);
for (Entry<String, JsonValue> e : configuration.entrySet()) {
String key = e.getKey();
if ( ! key.startsWith("@") || ! call.hasKey(key)) {
call.put(key, e.getValue());
}
}
return call;
}
/**
* Utility to strip @-configuration keys for a call to make it safe
* to use in invoking a nested action
*/
public JsonObject makeSafe(JsonObject params) {
JsonObject safe = new JsonObject();
for ( Entry<String, JsonValue> e : params.entrySet()) {
if (!e.getKey().startsWith("@")) {
safe.put(e.getKey(), e.getValue());
}
}
return safe;
}
}
| 30.532847 | 115 | 0.607698 |
4c03a2cb980198eb0261afda9079733af93d7311 | 471 | package lucius.justtest.java.concurrency.chapter2.lock.exp1;
/**
* Created by Lucius on 8/8/18.
*/
public class Main {
public static void main(String[] args) {
PrintQueue printQueue = new PrintQueue();
Thread[] thread = new Thread[10];
for (int i = 0; i < 10; i++) {
thread[i] = new Thread(new Job(printQueue), "Thread " + i);
}
for (int i = 0; i < 10; i++) {
thread[i].start();
}
}
}
| 22.428571 | 71 | 0.528662 |
8c033c2bf9ba4eb0dae5b9a5846ab9ecc6836325 | 587 | /**
* This is interface was provided by UMUC as part of their
* CMSC451 course.
*
* Credit goes to them, apart from the noted modifcations below.
*/
public interface SortInterface {
public void recursiveSort(int[] list);
public void iterativeSort(int[] list);
// public int getCount();
/**
* NOTE(larsbutler): I had to change this interface to return a long
* because the samples I used and the critical operations I chose
* yielded operation counts way beyond the max "int" value.
*/
public long getCount();
public long getTime();
}
| 25.521739 | 72 | 0.67632 |
ddb2ecabd5a3e0d863bc39e4e97a420612ac5918 | 1,145 |
/**
*
* Write a function to find the longest common prefix string amongst an array of strings.
*
* @author Lisong Guo <lisong.guo@me.com>
* @date Jan 1, 2015
*
*/
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0){
return "";
}
int minLen = Integer.MAX_VALUE;
for(String str : strs){
minLen = Math.min(minLen, str.length());
}
boolean isFound = false;
int pc = 0;
while(! isFound && pc < minLen){
int c = strs[0].charAt(pc);
for(int i=1; i<strs.length; ++i){
if(c != strs[i].charAt(pc)){
isFound = true;
break;
}
}
++pc;
}
return strs[0].substring(0, isFound ? pc-1 : pc);
}
public static void main(String[] args) {
//String [] strs = {"ABC", "ABCD", "ABC"};
String [] strs = {"a", "b"};
//String [] strs = {};
LongestCommonPrefix solution = new LongestCommonPrefix();
System.out.println(solution.longestCommonPrefix(strs));
}
}
| 19.083333 | 89 | 0.520524 |
0bb48f41dc47ddfc14edd37a9fbc17e3001e5cc5 | 798 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.intellilang.model;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsGlobal;
import org.jetbrains.jps.service.JpsServiceManager;
/**
* @author Eugene Zhuravlev
*/
public abstract class JpsIntelliLangExtensionService {
public static JpsIntelliLangExtensionService getInstance() {
return JpsServiceManager.getInstance().getService(JpsIntelliLangExtensionService.class);
}
@NotNull
public abstract JpsIntelliLangConfiguration getConfiguration(@NotNull JpsGlobal project);
public abstract void setConfiguration(@NotNull JpsGlobal project, @NotNull JpsIntelliLangConfiguration extension);
} | 39.9 | 140 | 0.815789 |
1495fdaa115edd3c86290a2986768453c190af0f | 23,943 | /*
* 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.openide.text;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectStreamException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.JEditorPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.text.Caret;
import javax.swing.text.Document;
import org.netbeans.modules.openide.text.Installer;
import org.openide.awt.UndoRedo;
import org.openide.cookies.EditorCookie;
import org.openide.util.*;
import org.openide.windows.*;
/** Cloneable top component to hold the editor kit.
*/
public class CloneableEditor extends CloneableTopComponent implements CloneableEditorSupport.Pane {
private static final String HELP_ID = "editing.editorwindow"; // !!! NOI18N
static final long serialVersionUID = -185739563792410059L;
/** editor pane */
protected JEditorPane pane;
/** Asociated editor support */
private CloneableEditorSupport support;
/**
* Flag to detect if component is opened or closed to control return value
* of getEditorPane. If component creation starts this flag is set to true and
* getEditorPane() waits till initialization finishes.
*/
private boolean componentCreated = false;
/** Position of cursor. Used to keep the value between deserialization
* and initialization time. */
private int cursorPosition = -1;
private final boolean[] CLOSE_LAST_LOCK = new boolean[1];
/** Custom editor component, which is used if specified by document
* which implements <code>NbDocument.CustomEditor</code> interface.
* @see NbDocument.CustomEditor#createEditor */
private Component customComponent;
private CloneableEditorInitializer initializer;
static final Logger LOG = Logger.getLogger("org.openide.text.CloneableEditor"); // NOI18N
/** For externalization of subclasses only */
public CloneableEditor() {
this(null);
}
/** Creates new editor component associated with
* support object.
* @param support support that holds the document and operations above it
*/
public CloneableEditor(CloneableEditorSupport support) {
this(support, false);
}
/** Creates new editor component associated with
* support object (possibly also with its
* {@link CloneableEditorSupport#CloneableEditorSupport(org.openide.text.CloneableEditorSupport.Env, org.openide.util.Lookup) lookup}.
*
* @param support support that holds the document and operations above it
* @param associateLookup true, if {@link #getLookup()} should return the lookup
* associated with {@link CloneableEditorSupport}.
*/
public CloneableEditor(CloneableEditorSupport support, boolean associateLookup) {
super();
this.support = support;
updateName();
_setCloseOperation();
setMinimumSize(new Dimension(10, 10));
if (associateLookup) {
associateLookup(support.getLookup());
}
}
@SuppressWarnings("deprecation")
private void _setCloseOperation() {
setCloseOperation(CLOSE_EACH);
}
/** Gives access to {@link CloneableEditorSupport} object under
* this <code>CloneableEditor</code> component.
* @return the {@link CloneableEditorSupport} object
* that holds the document or <code>null</code>, what means
* this component is not in valid state yet and can be discarded */
protected CloneableEditorSupport cloneableEditorSupport() {
return support;
}
/** Overriden to explicitely set persistence type of CloneableEditor
* to PERSISTENCE_ONLY_OPENED */
@Override
public int getPersistenceType() {
return TopComponent.PERSISTENCE_ONLY_OPENED;
}
/** Get context help for this editor pane.
* If the registered editor kit provides a help ID in bean info
* according to the protocol described for {@link HelpCtx#findHelp},
* then that it used, else general help on the editor is provided.
* @return context help
*/
@Override
public HelpCtx getHelpCtx() {
Object kit = support.cesKit();
HelpCtx fromKit = kit == null ? null : HelpCtx.findHelp(kit);
if (fromKit != null) {
return fromKit;
} else {
return new HelpCtx(HELP_ID);
}
}
/**
* Indicates whether this component can be closed.
* Adds scheduling of "emptying" editor pane and removing all sub components.
* {@inheritDoc}
*/
@Override
public boolean canClose() {
boolean result = super.canClose();
return result;
}
/** Overrides superclass method. In case it is called first time,
* initializes this <code>CloneableEditor</code>. */
@Override
protected void componentShowing() {
super.componentShowing();
initialize();
}
/**
* Performs needed initialization.
* The method should only be invoked from EDT.
*/
private void initialize() {
// Only called form EDT
if (pane != null || discard()) {
return;
}
QuietEditorPane tmp = new QuietEditorPane();
tmp.putClientProperty("usedByCloneableEditor", true);
this.pane = tmp;
synchronized (getInitializerLock()) {
this.componentCreated = true;
initializer = new CloneableEditorInitializer(this, support, pane);
}
initializer.start(); // Initializer variable will be cleared by the initializer task itself later.
}
private Object getInitializerLock() {
return CloneableEditorInitializer.edtRequests;
}
boolean isInitializationRunning() {
synchronized (getInitializerLock()) {
boolean running = (initializer != null);
return running;
}
}
boolean isProvideUnfinishedPane() {
synchronized (getInitializerLock()) {
return (initializer != null) && initializer.isProvideUnfinishedPane();
}
}
void markInitializationFinished(boolean success) {
synchronized (getInitializerLock()) {
initializer = null;
if (!success) {
pane = null;
}
// Notify possible waiting clients that initialization is finished
CloneableEditorInitializer.notifyEDTRequestsMonitor();
}
}
/** Asks the associated {@link CloneableEditorSupport} to initialize
* this editor via its {@link CloneableEditorSupport#initializeCloneableEditor(org.openide.text.CloneableEditor)}
* method. By default called from the support on various occasions including
* shortly after creation and
* after the {@link CloneableEditor} has been deserialized.
*
* @since 6.37
*/
protected final void initializeBySupport() {
cloneableEditorSupport().initializeCloneableEditor(this);
}
void setCustomComponent(Component customComponent) {
this.customComponent = customComponent;
}
int getCursorPosition() {
return cursorPosition;
}
void setCursorPosition(int cursorPosition) {
this.cursorPosition = cursorPosition;
}
@Override
protected CloneableTopComponent createClonedObject() {
return support.createCloneableTopComponent();
}
/** Descendants overriding this method must either call
* this implementation or fire the
* {@link org.openide.cookies.EditorCookie.Observable#PROP_OPENED_PANES}
* property change on their own.
*/
@Override
protected void componentOpened() {
super.componentOpened();
CloneableEditorSupport ces = cloneableEditorSupport();
if (ces != null) {
ces.firePropertyChange(EditorCookie.Observable.PROP_OPENED_PANES, null, null);
Document d = ces.getDocument();
if (d != null) {
String mimeType = (String) d.getProperty("mimeType"); //NOI18N
Installer.add(mimeType);
}
}
}
/** Descendants overriding this method must either call
* this implementation or fire the
* {@link org.openide.cookies.EditorCookie.Observable#PROP_OPENED_PANES}
* property change on their own.
*/
@Override
protected void componentClosed() {
// #23486: pane could not be initialized yet.
if (pane != null) {
// #114608 - commenting out setting of the empty document
// Document doc = support.createStyledDocument(pane.getEditorKit());
// pane.setDocument(doc);
// #138611 - this calls kit.deinstall, which is what our kits expect,
// calling it with null does not impact performance, because the pane
// will not create new document and typically nobody listens on "editorKit" prop change
pane.setEditorKit(null);
pane.putClientProperty("usedByCloneableEditor", false);
}
synchronized (getInitializerLock()) {
customComponent = null;
pane = null;
componentCreated = false;
}
super.componentClosed();
CloneableEditorSupport ces = cloneableEditorSupport();
if (ces != null) {
ces.firePropertyChange(EditorCookie.Observable.PROP_OPENED_PANES, null, null);
}
if (ces.getAnyEditor() == null) {
ces.close(false);
}
}
/** When closing last view, also close the document.
* Calls {@link #closeLast(boolean) closeLast(true)}.
* @return <code>true</code> if close succeeded
*/
@Override
protected boolean closeLast() {
return closeLast(true);
}
/** Utility method to close the document.
*
* @param ask verify and ask the user whether a document can be closed or not?
* @return true if the document was successfully closed
* @since 6.37
*/
protected final boolean closeLast(boolean ask) {
if (ask) {
if (!support.canClose()) {
// if we cannot close the last window
return false;
}
}
// close everything and do not ask
synchronized (CLOSE_LAST_LOCK) {
if (CLOSE_LAST_LOCK[0]) {
CLOSE_LAST_LOCK[0] = false;
} else {
support.notifyClosed();
}
}
if (support.getLastSelected() == this) {
support.setLastSelected(null);
}
return true;
}
/** The undo/redo manager of the support.
* @return the undo/redo manager shared by all editors for this support
*/
@Override
public UndoRedo getUndoRedo() {
return support.getUndoRedo();
}
@Override
public Action[] getActions() {
List<Action> actions = new ArrayList<Action>(Arrays.asList(super.getActions()));
// XXX nicer to use MimeLookup for type-specific actions, but not easy; see org.netbeans.modules.editor.impl.EditorActionsProvider
actions.add(null);
actions.addAll(Utilities.actionsForPath("Editors/TabActions"));
return actions.toArray(new Action[actions.size()]);
}
/** Transfer the focus to the editor pane.
*/
@Deprecated
@Override
public void requestFocus() {
super.requestFocus();
if (pane != null) {
if ((customComponent != null) && !SwingUtilities.isDescendingFrom(pane, customComponent)) {
customComponent.requestFocus();
} else {
pane.requestFocus();
}
}
}
/** Transfer the focus to the editor pane.
*/
@Deprecated
@Override
public boolean requestFocusInWindow() {
super.requestFocusInWindow();
if (pane != null) {
if ((customComponent != null) && !SwingUtilities.isDescendingFrom(pane, customComponent)) {
return customComponent.requestFocusInWindow();
} else {
return pane.requestFocusInWindow();
}
}
return false;
}
@Deprecated
@Override
public boolean requestDefaultFocus() {
if ((customComponent != null) && !SwingUtilities.isDescendingFrom(pane, customComponent)) {
return customComponent.requestFocusInWindow();
} else if (pane != null) {
return pane.requestFocusInWindow();
}
return false;
}
// XXX is this method really needed?
/** @return Preferred size of editor top component */
@Override
public Dimension getPreferredSize() {
@SuppressWarnings("deprecation")
Rectangle bounds = WindowManager.getDefault().getCurrentWorkspace().getBounds();
return new Dimension(bounds.width / 2, bounds.height / 2);
}
@Override
public void open() {
boolean wasNull = getClientProperty( "TopComponentAllowDockAnywhere" ) == null; //NOI18N
super.open();
if( wasNull ) {
//since we don't define a mode to dock this editor to, the window
//system thinks we're an uknown component allowed to dock anywhere
//but editor windows can dock into editor modes only, so let's clear
//the 'special' flag
putClientProperty( "TopComponentAllowDockAnywhere", null); //NOI18N
}
}
/**
* Overrides superclass method. Remembers last selected component of
* support belonging to this component.
*
* Descendants overriding this method must call this implementation to set last
* selected pane otherwise <code>CloneableEditorSupport.getRecentPane</code> and
* <code>CloneableEditorSupport.getOpenedPanes</code> will be broken.
*
* @see #componentDeactivated
*/
@Override
protected void componentActivated() {
support.setLastSelected(this);
}
/** Updates the name and tooltip of this <code>CloneableEditor</code>
* {@link org.openide.windows.TopComponent TopCompoenent}
* according to the support retrieved from {@link #cloneableEditorSupport}
* method. The name and tooltip are in case of support presence
* updated thru its {@link CloneableEditorSupport#messageName} and
* {@link CloneableEditorSupport#messageToolTip} methods.
* @see #cloneableEditorSupport() */
public void updateName() {
final CloneableEditorSupport ces = cloneableEditorSupport();
if (ces != null) {
Mutex.EVENT.writeAccess(
new Runnable() {
public void run() {
String name = ces.messageHtmlName();
setHtmlDisplayName(name);
name = ces.messageName();
setDisplayName(name);
setName(name); // XXX compatibility
setToolTipText(ces.messageToolTip());
}
}
);
}
}
// override for simple and consistent IDs
@Override
protected String preferredID() {
final CloneableEditorSupport ces = cloneableEditorSupport();
if (ces != null) {
return ces.documentID();
}
return "";
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
// Save environent if support is non-null.
// XXX #13685: When support is null, the tc will be discarded
// after deserialization.
out.writeObject((support != null) ? support.cesEnv() : null);
// #16461 Caret could be null?!,
// hot fix - making it robust for that case.
int pos = 0;
// 19559 Even pane could be null! Better solution would be put
// writeReplace method in place also, but it is a API change. For
// the time be just robust here.
JEditorPane p = pane;
if (p != null) {
Caret caret = p.getCaret();
if (caret != null) {
pos = caret.getDot();
} else {
if (p instanceof QuietEditorPane) {
int lastPos = ((QuietEditorPane) p).getLastPosition();
if (lastPos == -1) {
Logger.getLogger(CloneableEditor.class.getName()).log(Level.WARNING, null,
new java.lang.IllegalStateException("Pane=" +
p +
"was not initialized yet!"));
} else {
pos = lastPos;
}
} else {
Document doc = ((support != null) ? support.getDocument() : null);
// Relevant only if document is non-null?!
if (doc != null) {
Logger.getLogger(CloneableEditor.class.getName()).log(Level.WARNING, null,
new java.lang.IllegalStateException("Caret is null in editor pane=" +
p +
"\nsupport=" +
support +
"\ndoc=" +
doc));
}
}
}
}
out.writeObject(new Integer(pos));
out.writeBoolean(getLookup() == support.getLookup());
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
int offset;
Object firstObject = in.readObject();
// New deserialization that uses Env environment,
// and which could be null(!) see writeExternal.
if (firstObject instanceof CloneableOpenSupport.Env) {
CloneableOpenSupport.Env env = (CloneableOpenSupport.Env) firstObject;
CloneableOpenSupport os = env.findCloneableOpenSupport();
support = (CloneableEditorSupport) os;
}
// load cursor position
offset = ((Integer) in.readObject()).intValue();
if (!discard()) {
cursorPosition = offset;
}
updateName();
componentCreated = true;
if (in.available() > 0) {
boolean associate = in.readBoolean();
if (associate && support != null) {
associateLookup(support.getLookup());
}
}
}
/**
* Replaces serializing object. Overrides superclass method. Adds checking
* for object validity. In case this object is invalid
* throws {@link java.io.NotSerializableException NotSerializableException}.
* @throws ObjectStreamException When problem during serialization occures.
* @throws NotSerializableException When this <code>CloneableEditor</code>
* is invalid and doesn't want to be serialized. */
@Override
protected Object writeReplace() throws ObjectStreamException {
if (discard()) {
throw new NotSerializableException("Serializing component is invalid: " + this); // NOI18N
}
return super.writeReplace();
}
/**
* Resolves deserialized object. Overrides superclass method. Adds checking
* for object validity. In case this object is invalid
* throws {@link java.io.InvalidObjectException InvalidObjectException}.
* @throws ObjecStreamException When problem during serialization occures.
* @throws InvalidObjectException When deserialized <code>CloneableEditor</code>
* is invalid and shouldn't be used. */
protected Object readResolve() throws ObjectStreamException {
if (discard()) {
throw new java.io.InvalidObjectException("Deserialized component is invalid: " + this); // NOI18N
} else {
initializeBySupport();
return this;
}
}
/** This component should be discarded if the associated environment
* is not valid.
*/
private boolean discard() {
return (support == null) || !support.cesEnv().isValid();
}
//
// Implements the CloneableEditorSupport.Pane interface
//
public CloneableTopComponent getComponent() {
return this;
}
/**
* #168415: Returns true if creation of editor pane is finished. It is used
* to avoid blocking AWT thread by call of getEditorPane.
*/
boolean isEditorPaneReady () {
assert SwingUtilities.isEventDispatchThread();
return isEditorPaneReadyImpl();
}
/** Used from test only. Can be called out of AWT */
boolean isEditorPaneReadyTest () {
return isEditorPaneReadyImpl();
}
private boolean isEditorPaneReadyImpl() {
return (pane != null) && !isInitializationRunning();
}
/** Returns editor pane. Returns null if document loading was canceled by user
* through answering UserQuestionException or when CloneableEditor is closed.
*
* @return editor pane or null
*/
public JEditorPane getEditorPane() {
assert SwingUtilities.isEventDispatchThread();
//User selected not to load document
if (!componentCreated) {
return null;
}
//#175528: This case should not happen as modal dialog handling UQE should
//not be displayed during IDE start ie. during component deserialization.
if (CloneableEditorInitializer.modalDialog) {
LOG.log(Level.WARNING,"AWT is blocked by modal dialog. Return null from CloneableEditor.getEditorPane."
+ " Please report this to IZ.");
LOG.log(Level.WARNING,"support:" + support.getClass().getName());
Exception ex = new Exception();
StringWriter sw = new StringWriter(500);
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
LOG.log(Level.WARNING,sw.toString());
return null;
}
initialize();
CloneableEditorInitializer.waitForFinishedInitialization(this);
return pane;
}
/**
* callback for the Pane implementation to adjust itself to the openAt() request.
*/
@Override
public void ensureVisible() {
open();
requestVisible();
}
}
| 34.902332 | 138 | 0.610366 |
bbb57441fd10c3fbf78143a51d40edecb8955f41 | 18,128 | package com.team3.bra;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* The manager screen to be able to edit , add and delete items and categories
*
*/
public class ManagerMenu extends Activity {
ScrollView scrollItems, scrollCategories;
LinearLayout addCateg,addItem;
TextView txtItemTitle,txtCatTitle;
Button btnItemDelete,btnCatDelete,btnCatSave,btnItemSave;
EditText etItemName,etItemDesc,etItemPrice,etCatName,etCatDesc,etCatVat;
Spinner spnItemCat,spnrFoodDrink;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manager_menu_layout);
scrollCategories = (ScrollView) findViewById(R.id.scrollCat);
scrollItems = (ScrollView) findViewById(R.id.scrollSide);
scrollItems.setVisibility(View.GONE);
addCateg = (LinearLayout) findViewById(R.id.addCat);
addCateg.setVisibility(View.GONE);
addItem= (LinearLayout) findViewById(R.id.addItem);
addItem.setVisibility(View.GONE);
txtItemTitle = (TextView) findViewById(R.id.txtItemTitle);
txtCatTitle = (TextView) findViewById(R.id.txtCatTitle);
btnItemDelete = (Button) findViewById(R.id.btnItemDelete);
btnCatDelete = (Button) findViewById(R.id.btnCatDelete);
btnCatSave = (Button) findViewById(R.id.btnCatSave);
btnItemSave = (Button) findViewById(R.id.btnItemSave);
etItemName= (EditText) findViewById(R.id.etItemName);
etItemDesc= (EditText) findViewById(R.id.etItemDesc);
etItemPrice= (EditText) findViewById(R.id.etItemPrice);
spnItemCat= (Spinner) findViewById(R.id.spnItemCat);
etCatName= (EditText) findViewById(R.id.etCatName);
etCatDesc= (EditText) findViewById(R.id.etCatDesc);
etCatVat= (EditText) findViewById(R.id.etCatVat);
spnrFoodDrink= (Spinner) findViewById(R.id.spnr_foodDrink);
showCategories();
}
/**
*
* @param sp the spinner to add the category
* @param cat the category to be added
*/
private void fillSpinner(Spinner sp,Category cat){
ArrayAdapter<Category> dataAdapter = new ArrayAdapter<Category>(this, android.R.layout.simple_spinner_item, Category.categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(dataAdapter);
sp.setSelection(Category.categories.indexOf(cat));
}
/**
* return to the main menu of the manager
* @param v the view that clicked the button
*/
public void orderBackManager(View v){
finish();
}
/**
* Show the selected category items
* @param v the view that clicked the button
* @param cat the category to be shown
*/
public void editCategory(View v,final Category cat){
scrollItems.setVisibility(View.VISIBLE);
scrollCategories.setVisibility(View.GONE);
addCateg.setVisibility(View.VISIBLE);
btnCatDelete.setVisibility(View.VISIBLE);
txtCatTitle.setText("Edit Category");
etCatName.setText(cat.getName());
etCatDesc.setText(cat.getDescription());
etCatVat.setText(cat.getVat()+"");
spnrFoodDrink.setSelection(cat.isFood());
btnCatDelete.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
catDeleteClicked(v,cat.getId());
}
});
btnCatSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
catSaveClicked(v,cat.getId());
}
});
}
/**
* Go back the the category menu
* @param v the view that clicked the button
*/
public void orderBackToCategManager(View v){
scrollItems.setVisibility(View.GONE);
scrollCategories.setVisibility(View.VISIBLE);
addCateg.setVisibility(View.GONE);
addItem.setVisibility(View.GONE);
}
/**
* Open the form to add a new category
* @param v the view that clicked the button
*/
public void addCategory(View v){
txtCatTitle.setText("New Category");
etCatName.setText("");
etCatDesc.setText("");
etCatVat.setText("");
spnrFoodDrink.setSelection(1);
addCateg.setVisibility(View.VISIBLE);
btnCatDelete.setVisibility(View.GONE);
btnCatSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
catSaveClicked(v,-1);
}
});
}
/**
* Add a new item to the category
* @param v the view that clicked the button
* @param cat the category to add the item
*/
public void addItem(View v,final Category cat){
txtItemTitle.setText("New Item");
addItem.setVisibility(View.VISIBLE);
btnItemDelete.setVisibility(View.GONE);
fillSpinner(spnItemCat,cat);
etItemPrice.setText("");
etItemName.setText("");
etItemDesc.setText("");
btnItemSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
itemSaveClicked(v,-1,cat);
}
});
}
/**
* Open the form to edit an Item
* @param v the view that clicked the button
* @param item the item to load the data of it
* @param cat the category of the item
*/
public void editItem(View v,final Item item,final Category cat){
txtItemTitle.setText("Edit Item");
addItem.setVisibility(View.VISIBLE);
btnItemDelete.setVisibility(View.VISIBLE);
fillSpinner(spnItemCat,cat);
etItemPrice.setText(item.getPrice()+"");
etItemName.setText(item.getName());
etItemDesc.setText(item.getDescription());
btnItemDelete.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
itemDeleteClicked(v,item.getId(),cat);
}
});
btnItemSave.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
itemSaveClicked(v,item.getId(),cat);
}
});
}
/**
* Save the changes of the item to the database
* @param v the view that clicked the button
* @param itemID the item id
* @param cat the category to save the item to
*/
public void itemSaveClicked(View v,int itemID,Category cat){
String a[] = { itemID+"",etItemName.getText().toString(),etItemPrice.getText().toString(), etItemDesc.getText().toString(),((Category)spnItemCat.getSelectedItem()).getId()+"" };
JDBC.callProcedure("AddItem", a);
showItems(cat);//Will refresh current viewed category only.
Toast toast = Toast.makeText(getApplicationContext(), "Item saved", Toast.LENGTH_SHORT);
toast.show();
addItem.setVisibility(View.GONE);
}
/**
* Save the category changes to the database
* @param v the view that clicked the button
* @param selectedID the selected category id
*/
public void catSaveClicked(View v,int selectedID){
int pos=((Spinner)findViewById(R.id.spnr_foodDrink)).getSelectedItemPosition();
String a[] = { selectedID+"",etCatName.getText().toString(),etCatVat.getText().toString(), etCatDesc.getText().toString(),pos+"" };
JDBC.callProcedure("AddCategory", a);
showCategories();
Toast toast = Toast.makeText(getApplicationContext(), "Category saved", Toast.LENGTH_SHORT);
toast.show();
addCateg.setVisibility(View.GONE);
}
/**
* Cancel the change of an item or category
* @param v the view that clicked the button
*/
public void cancelClicked(View v){
addCateg.setVisibility(View.GONE);
addItem.setVisibility(View.GONE);
}
/**
* Delete the item after confirmation of the user
* @param v the view that clicked the button
* @param itemID the item's id to be deleted
* @param cat the category of the item
*/
public void itemDeleteClicked(View v,final int itemID,final Category cat){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
String a[] = {itemID+""};
JDBC.callProcedure("RemoveItem", a);
showItems(cat); //Will refresh current viewed category only.
Toast toast = Toast.makeText(getApplicationContext(), "Item deleted", Toast.LENGTH_SHORT);
toast.show();
addItem.setVisibility(View.GONE);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete "+etItemName.getText().toString()+"?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
/**
* Delete category after confirmation
* @param v the view that clicked the button
* @param selectedID the category's to be deleted id
*/
public void catDeleteClicked(View v,final int selectedID){
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
String a[] = {selectedID+""};
JDBC.callProcedure("RemoveCategory", a);
showCategories();
Toast toast = Toast.makeText(getApplicationContext(), "Category deleted", Toast.LENGTH_SHORT);
toast.show();
addCateg.setVisibility(View.GONE);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete "+etCatName.getText().toString()+"?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
/**
* Show all the categories to the screen of the manager
*/
public void showCategories(){
scrollItems.setVisibility(View.GONE);
scrollCategories.setVisibility(View.VISIBLE);
Category.findCategories();
final ArrayList<Category> categories=Category.categories;
final float scale = getResources().getDisplayMetrics().density;
LinearLayout ll = (LinearLayout) findViewById(R.id.categoryLayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,(int)(80*scale),1.0f);
lp.gravity= Gravity.TOP | Gravity.BOTTOM;
int i=-2;
int count=0;
ll.removeAllViews();
LinearLayout newLayout = new LinearLayout(this);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
ll.addView(newLayout);
while(categories.size()>i){
Button b = new Button(this);
b.getBackground().setColorFilter(ContextCompat.getColor(this,R.color.transparent), PorterDuff.Mode.MULTIPLY);
if (i==-2) {
b.setText("BACK");
b.setTextColor(Color.RED);
newLayout.addView(b,lp);
i++;
count++;
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
orderBackManager(v);
}
});
continue;
}
else if (i==-1) {
b.getBackground().setColorFilter(ContextCompat.getColor(this,R.color.orange), PorterDuff.Mode.MULTIPLY);
b.setText("ADD CATEGORY");
newLayout.addView(b,lp);
i++;
count++;
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
addCategory(v);
}
});
continue;
}else {//NEW category.
if(categories.get(i).isFood()==0)
b.getBackground().setColorFilter(ContextCompat.getColor(this,R.color.yellow), PorterDuff.Mode.MULTIPLY);
b.setText(categories.get(i).getName());
final int t = i;
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showItems(categories.get(t));
}
});
}
if(count < 3){
newLayout.addView(b,lp);
}
else{
newLayout = new LinearLayout(this);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
ll.addView(newLayout);
count=0;
newLayout.addView(b,lp);
}
i++;
count++;
}
while(count == 1 || count ==2) {
newLayout.addView(new TextView(this), lp);
count++;
}
}
/**
* Show all the items of a selected category
* @param cat the selected category
*/
public void showItems(final Category cat){
cat.fillCategory();
final ArrayList<Item> items=cat.getItems();
final float scale = getResources().getDisplayMetrics().density;
LinearLayout ll = (LinearLayout) findViewById(R.id.itemLayout);
ll.removeAllViews();
TextView categoryName = new TextView(this);
categoryName.setText(cat.getName());
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
categoryName.setGravity(Gravity.CENTER);
categoryName.setTextSize(18);
categoryName.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
editCategory(v,cat);
}
});
ll.addView(categoryName,lparam);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,(int)(80*scale),1.0f);
lp.gravity= Gravity.TOP | Gravity.BOTTOM;
int i=-2;
int count=0;
LinearLayout newLayout = new LinearLayout(this);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
ll.addView(newLayout);
while(items.size()>i){
Button b = new Button(this);
b.getBackground().setColorFilter(ContextCompat.getColor(this,R.color.transparent), PorterDuff.Mode.MULTIPLY);
//insert BACK button
if (i==-2) {
b.setText("BACK");
b.setTextColor(Color.RED);
newLayout.addView(b,lp);
i++;
count++;
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
orderBackToCategManager(v);
}
});
continue;
}
//insery ADD ITEM button
else if (i==-1) {
b.setText("ADD ITEM");
newLayout.addView(b, lp);
i++;
count++;
b.getBackground().setColorFilter(ContextCompat.getColor(this,R.color.orange), PorterDuff.Mode.MULTIPLY);
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
addItem(v,cat);
}
});
continue;
}
//insert food item buttons
b.setText(items.get(i).getName());
final int t=i;
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
editItem(v,items.get(t),cat);
}
});
if(count < 3){
newLayout.addView(b,lp);
}
else{
newLayout = new LinearLayout(this);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
ll.addView(newLayout);
count=0;
newLayout.addView(b,lp);
}
i++;
count++;
}
//fll the empty spaces
while(count == 1 || count ==2) {
newLayout.addView(new TextView(this), lp);
count++;
}
scrollItems.setVisibility(View.VISIBLE);
scrollCategories.setVisibility(View.GONE);
addCateg.setVisibility(View.GONE);
}
} | 37.300412 | 185 | 0.588372 |
b3cfbc97d156b7e2c75359fa0ff89a77ca867df4 | 1,356 | package com.fasterxml.jackson.failing;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;
// Not sure if this is valid, but for what it's worth, shows
// the thing wrt [databind#1311]. May be removed if we can't find
// improvements.
public class TestSubtypes1311 extends com.fasterxml.jackson.databind.BaseMapTest
{
// [databind#1311]
@JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME, defaultImpl = Factory1311ImplA.class)
interface Factory1311 { }
@JsonTypeName("implA")
static class Factory1311ImplA implements Factory1311 { }
@JsonTypeName("implB")
static class Factory1311ImplB implements Factory1311 { }
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
// [databind#1311]
public void testSubtypeAssignmentCheck() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.registerSubtypes(Factory1311ImplA.class, Factory1311ImplB.class);
Factory1311ImplB result = mapper.readValue("{\"type\":\"implB\"}", Factory1311ImplB.class);
assertNotNull(result);
assertEquals(Factory1311ImplB.class, result.getClass());
}
}
| 34.769231 | 102 | 0.65413 |
7f62819fd3c652ebc6c6907b1f7d55a4740e4f5e | 4,779 | /**
The MIT License (MIT)
Copyright (c) 2010-2021 head systems, ltd
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 su.interference.persistent;
import su.interference.core.*;
import su.interference.mgmt.MgmtColumn;
import su.interference.exception.InternalException;
import javax.persistence.*;
import java.io.Serializable;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
/**
* @author Yuriy Glotanov
* @since 1.0
*/
@Entity
@SystemEntity
@DisableSync
public class TransFrame implements Comparable, FilePartitioned, Serializable {
@Column
@MgmtColumn(width=10, show=true, form=false, edit=false)
private long transId;
@Column
@MgmtColumn(width=10, show=true, form=false, edit=false)
private int objectId;
@Column
@MgmtColumn(width=10, show=true, form=false, edit=false)
private long cframeId;
@Column
@MgmtColumn(width=10, show=true, form=false, edit=false)
private long uframeId;
@Column
@MgmtColumn(width=10, show=true, form=false, edit=false)
private int diff;
@Id
@MapColumn
@MgmtColumn(width=10, show=true, form=false, edit=false)
@Transient
private transient TransFrameId frameId;
@Transient
public static final int CLASS_ID = 8;
@Transient
private final static long serialVersionUID = 948324870766513223L;
public static int getCLASS_ID() {
return CLASS_ID;
}
public TransFrameId getFrameId() {
if (frameId == null) {
frameId = new TransFrameId(cframeId, uframeId, transId);
}
return frameId;
}
public TransFrame() {
}
public TransFrame(long tr, int obj, long cp, long up) {
this.transId = tr;
this.objectId = obj;
this.cframeId = cp;
this.uframeId = up;
this.frameId = new TransFrameId(cframeId, uframeId, transId);
}
public int compareTo(Object obj) {
TransFrame c = (TransFrame)obj;
if (this.cframeId < c.getCframeId()) {
return -1;
} else if (this.cframeId > c.getCframeId()) {
return 1;
}
return 0;
}
public String toString() {
return transId+":"+objectId+":"+cframeId+":"+uframeId;
}
//constructor for low-level storage function (initial first-time load table descriptions from datafile)
public TransFrame(DataChunk chunk) throws ClassNotFoundException, IllegalAccessException, InternalException, MalformedURLException {
final Object[] dcs = chunk.getDcs().getValueSet();
final Class c = this.getClass();
final java.lang.reflect.Field[] f = c.getDeclaredFields();
int x = 0;
for (int i=0; i<f.length; i++) {
final Transient ta = f[i].getAnnotation(Transient.class);
if (ta==null) {
final int m = f[i].getModifiers();
if (Modifier.isPrivate(m)) {
f[i].setAccessible(true);
}
f[i].set(this, dcs[x]);
x++;
}
}
}
public int getFile() {
return (int) this.getFile_();
}
private long getFile_() {
return this.cframeId%4096;
}
public long getTransId() {
return transId;
}
public int getObjectId() {
return objectId;
}
public long getCframeId() {
return cframeId;
}
public long getUframeId() {
return uframeId;
}
public int getDiff() {
return diff;
}
public void setDiff(int diff) {
this.diff = diff;
}
}
| 29.68323 | 137 | 0.626909 |
95668033b6aa37a212cd6dbf77b2d1a033f9f5de | 567 | package org.apache.spark.sql.execution.columnar;
public class CachedRDDBuilder$ extends scala.runtime.AbstractFunction5<java.lang.Object, java.lang.Object, org.apache.spark.storage.StorageLevel, org.apache.spark.sql.execution.SparkPlan, scala.Option<java.lang.String>, org.apache.spark.sql.execution.columnar.CachedRDDBuilder> implements scala.Serializable {
/**
* Static reference to the singleton instance of this Scala object.
*/
public static final CachedRDDBuilder$ MODULE$ = null;
public CachedRDDBuilder$ () { throw new RuntimeException(); }
}
| 63 | 310 | 0.784832 |
ba81b197da130819cae90a1caa65a7a566884bf8 | 4,416 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.util.r;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;
public class RTest {
public static void main(String[] args) {
// just making sure we have the right version of everything
if (!Rengine.versionCheck()) {
System.err
.println("** Version mismatch - Java files don't match library version.");
System.exit(1);
}
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
Rengine re = new Rengine(args, false, new RConsole());
System.out.println("Rengine created, waiting for R");
// the engine creates R is a new thread, so we should wait until it's
// ready
if (!re.waitForR()) {
System.out.println("Cannot load R");
return;
}
/*
* High-level API - do not use RNI methods unless there is no other way
* to accomplish what you want
*/
try {
REXP test;
int[] array = new int[] { 5, 6, 7 };
int[] array_2 = new int[] { 1, 2, 3 };
re.assign("my_array", array);
re.assign("my_array_2", array_2);
System.out.println("Array: " + re.eval("my_array"));
System.out.println("Array 2: " + re.eval("my_array_2"));
test = re.eval("t.test(my_array,my_array_2)");
System.out.println("T-Test result: " + test);
// REXP x;
// re.eval("data(iris)",false);
// System.out.println(x=re.eval("iris"));
//
// // generic vectors are RVector to accomodate names
// RVector v = x.asVector();
// if (v.getNames()!=null) {
// System.out.println("has names:");
// for (Enumeration e = v.getNames().elements() ;
// e.hasMoreElements() ;) {
// System.out.println(e.nextElement());
// }
// }
// // for compatibility with Rserve we allow casting of vectors to
// lists
// RList vl = x.asList();
// String[] k = vl.keys();
// if (k!=null) {
// System.out.println("and once again from the list:");
// int i=0; while (i<k.length) System.out.println(k[i++]);
// }
//
// // get boolean array
// System.out.println(x=re.eval("iris[[1]]>mean(iris[[1]])"));
// // R knows about TRUE/FALSE/NA, so we cannot use boolean[] this
// way
// // instead, we use int[] which is more convenient (and what R
// uses internally anyway)
// int[] bi = x.asIntArray();
// {
// int i = 0; while (i<bi.length) {
// System.out.print(bi[i]==0?"F ":(bi[i]==1?"T ":"NA ")); i++; }
// System.out.println("");
// }
//
// // push a boolean array
// boolean by[] = { true, false, false };
// re.assign("bool", by);
// System.out.println(x=re.eval("bool"));
// // asBool returns the first element of the array as RBool
// // (mostly useful for boolean arrays of the length 1). is should
// return true
// System.out.println("isTRUE? "+x.asBool().isTRUE());
//
// // now for a real dotted-pair list:
// System.out.println(x=re.eval("pairlist(a=1,b='foo',c=1:5)"));
// RList l = x.asList();
// if (l!=null) {
// int i=0;
// String [] a = l.keys();
// System.out.println("Keys:");
// while (i<a.length) System.out.println(a[i++]);
// System.out.println("Contents:");
// i=0;
// while (i<a.length) System.out.println(l.at(i++));
// }
// System.out.println(re.eval("sqrt(36)"));
} catch (Exception e) {
System.out.println("EX:" + e);
e.printStackTrace();
}
{
REXP x = re.eval("1:10");
System.out.println("REXP result = " + x);
int d[] = x.asIntArray();
if (d != null) {
int i = 0;
while (i < d.length) {
System.out.print(((i == 0) ? "" : ", ") + d[i]);
i++;
}
System.out.println("");
}
}
re.eval("print(1:10/3)");
if (true) {
// so far we used R as a computational slave without REPL
// now we start the loop, so the user can use the console
System.out.println("Now the console is yours ... have fun");
re.startMainLoop();
}
}
} | 32.955224 | 80 | 0.572464 |
5708c74385526d94d520847302ff2bbc0c2cc951 | 5,612 | /*
* Copyright (c) 2017 Carbon Security Ltd. <opensource@carbonsecurity.co.uk>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.enterprisepasswordsafe.ui.web.servlets;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.enterprisepasswordsafe.engine.database.PasswordRestriction;
import com.enterprisepasswordsafe.engine.database.PasswordRestrictionDAO;
import com.enterprisepasswordsafe.ui.web.utils.ServletUtils;
/**
* Adds a password restriction to the system
*/
public final class PasswordRestrictionsEditStage2 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 7902867050803032684L;
/**
* The parameter holding the id of this restriction.
*/
public static final String ID_PARAMETER = "id";
/**
* The parameter holding the name of this restriction.
*/
public static final String NAME_PARAMETER = "name";
/**
* The parameter holding the lifetime for the password.
*/
public static final String LIFETIME_PARAMETER = "lifetime";
/**
* The generic error message for this servlet.
*/
private static final String GENERIC_ERROR_MESSAGE = "The restriction could not be added.";
/**
* The page users are directed to if there is an error.
*/
private static final String ERROR_PAGE = "/admin/PasswordRestrictionsEditStage1";
/**
* @see com.enterprisepasswordsafe.passwordsafe.servlets.NoResponseBaseServlet#serviceRequest
* (java.sql.Connection, javax.servlet.http.HTTPServletResponse)
*/
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter(ID_PARAMETER);
PasswordRestrictionDAO prDAO = PasswordRestrictionDAO.getInstance();
PasswordRestriction restriction;
try {
restriction = prDAO.getById(id);
} catch(SQLException ex) {
request.setAttribute("error_page", ERROR_PAGE);
throw new ServletException(GENERIC_ERROR_MESSAGE, ex);
}
try {
restriction.setMinSpecial(Integer.parseInt(request.getParameter(PasswordRestrictionsAddStage2.SPECIAL_COUNT_PARAMETER)));
} catch(NumberFormatException nfe) {
throw new ServletException( "The minimum number of special characters must be an integer value.");
}
try {
restriction.setMinNumeric(Integer.parseInt(request.getParameter(PasswordRestrictionsAddStage2.NUMERIC_COUNT_PARAMETER)));
} catch(NumberFormatException nfe) {
throw new ServletException( "The minimum number of numeric characters must be an integer value.");
}
try {
restriction.setMinUpper(Integer.parseInt(request.getParameter(PasswordRestrictionsAddStage2.UPPER_COUNT_PARAMETER)));
} catch(NumberFormatException nfe) {
throw new ServletException( "The minimum number of upper case characters must be an integer value.");
}
try {
restriction.setMinLower(Integer.parseInt(request.getParameter(PasswordRestrictionsAddStage2.LOWER_COUNT_PARAMETER)));
} catch(NumberFormatException nfe) {
throw new ServletException( "The minimum number of lower case characters must be an integer value.");
}
try {
restriction.setMinLength(Integer.parseInt(request.getParameter(PasswordRestrictionsAddStage2.MIN_SIZE_PARAMETER)));
} catch(NumberFormatException nfe) {
throw new ServletException( "The minimum length must be an integer value.");
}
try {
restriction.setMaxLength(Integer.parseInt(request.getParameter("size_max")));
} catch(NumberFormatException nfe) {
throw new ServletException( "The maximum length must be an integer value.");
}
try {
restriction.setLifetime(Integer.parseInt(request.getParameter(LIFETIME_PARAMETER)));
} catch(NumberFormatException nfe) {
throw new ServletException( "The default validity must be an integer value.");
}
restriction.setSpecialCharacters(request.getParameter(PasswordRestrictionsAddStage2.SPECIAL_CHARACTERS_PARAMETER));
restriction.setName(request.getParameter(NAME_PARAMETER));
try {
prDAO.update(restriction);
} catch(SQLException ex) {
request.setAttribute("error_page", ERROR_PAGE);
throw new ServletException(GENERIC_ERROR_MESSAGE, ex);
}
ServletUtils.getInstance().generateMessage(request, restriction.getName()+" has been updated.");
response.sendRedirect(request.getContextPath()+"/admin/PasswordRestrictions");
}
/**
* @see javax.servlet.Servlet#getServletInfo()
*/
@Override
public String getServletInfo() {
return "Adds a password restriction to the system.";
}
}
| 36.206452 | 127 | 0.738418 |
6f8b85a8a7c95ec93a1211c9c3113ac68c57b55b | 1,136 | package com.github.ysl3000.twitchapi.impl;
import com.github.ysl3000.twitchapi.api.StreamResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.parser.ParseException;
import java.io.IOException;
/**
* Created by ysl3000
*/
public class SyncTwitchConnector {
private HttpClient httpClient = HttpClientBuilder.create().build();
private String clientID;
public SyncTwitchConnector(String clientID) {
this.clientID = clientID;
}
public boolean isStreamingOnline(String twitchUserName) throws IOException, ParseException {
return connectToStream(twitchUserName).getStream() != null;
}
public StreamResponse connectToStream(String twitchUserName) throws IOException, ParseException {
HttpGet request = new HttpGet("https://api.twitch.tv/kraken/streams/" + twitchUserName + "?client_id=" + clientID);
HttpResponse response = httpClient.execute(request);
return new StreamResponseImpl(response);
}
}
| 29.128205 | 123 | 0.753521 |
432e86448e9426342750d483a413c1ad1d8c9ad7 | 3,119 | /*
* USE - UML based specification environment
* Copyright (C) 1999-2010 Mark Richters, University of Bremen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// $Id$
package org.tzi.use.gui.util;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.tzi.use.util.Log;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Provides easy to use XML methods
* @author Lars Hamann
*/
public class PersistHelper {
XPathFactory factory = XPathFactory.newInstance();
public PersistHelper() { }
/**
* Appends a child element to <code>parent</code> with the
* given name and a text element with the value given by <code>value</code>
* @param tagName
* @param value
* @return
*/
public Element appendChild(Element parent, String tagName, String value) {
Element e = parent.getOwnerDocument().createElement(tagName);
e.appendChild(parent.getOwnerDocument().createTextNode(value));
parent.appendChild(e);
return e;
}
public String getElementStringValue(Element parent, String childName) {
NodeList elems = parent.getElementsByTagName(childName);
if (elems.getLength() > 0)
return elems.item(0).getTextContent();
else
return null;
}
public boolean getElementBooleanValue(Element parent, String childName) {
return Boolean.valueOf(getElementStringValue(parent, childName));
}
public double getElementDoubleValue(Element parent, String childName) {
return Double.valueOf(getElementStringValue(parent, childName));
}
public int getElementIntegerValue(Element parent, String childName) {
return Integer.valueOf(getElementStringValue(parent, childName));
}
public NodeList getChildElementsByTagName( Element parent, String childName) {
return (NodeList)evaluateXPathSave(parent, "./" + childName, XPathConstants.NODESET);
}
public Element getElementByExpression( Element currentElement, String xpathExpr ) {
return (Element)evaluateXPathSave(currentElement, xpathExpr, XPathConstants.NODE);
}
public Object evaluateXPathSave( Element currentElement, String xpathExpr, QName resultType) {
XPath xpath = factory.newXPath();
try {
return xpath.evaluate(xpathExpr, currentElement, resultType);
} catch (XPathExpressionException e) {
Log.error("Invalid XPath expression: " + xpathExpr);
return null;
}
}
}
| 32.489583 | 95 | 0.74992 |
5a658524225a40d1b93177ed4a86ecfe74f5ad17 | 976 | package de.justsoftware.toolbox.mybatis;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* enum for easy accessing the used jdbc driver
*/
@ParametersAreNonnullByDefault
public enum SupportedJdbcDriver {
POSTGRES("org.postgresql.Driver"),
ORACLE("oracle.jdbc.driver.OracleDriver"),
;
private final String _driverClassName;
SupportedJdbcDriver(final String driverClassName) {
_driverClassName = driverClassName;
}
@Nonnull
public static SupportedJdbcDriver driverFromUrl(final String url) {
if (url.startsWith("jdbc:postgresql:")) {
return POSTGRES;
} else if (url.startsWith("jdbc:oracle")) {
return ORACLE;
} else {
throw new UnsupportedOperationException("Don't know the driver for the url " + url);
}
}
@Nonnull
public String getDriverClassName() {
return _driverClassName;
}
}
| 24.4 | 96 | 0.673156 |
874b041657bedb254aae602f16c6dd3e9818cb6f | 2,334 | /*
* Copyright (c) 2005 Biomatters LTD. All Rights Reserved.
*/
package org.virion.jam.framework;
import javax.swing.*;
import java.awt.event.KeyEvent;
/**
* @author rambaut
* Date: Dec 26, 2004
* Time: 11:01:06 AM
*/
public class DefaultFileMenuFactory implements MenuFactory {
private final boolean isMultiDocument;
public DefaultFileMenuFactory(boolean isMultiDocument) {
this.isMultiDocument = isMultiDocument;
}
public String getMenuName() {
return "File";
}
public void populateMenu(JMenu menu, AbstractFrame frame) {
JMenuItem item;
Application application = Application.getApplication();
menu.setMnemonic('F');
if (isMultiDocument) {
item = new JMenuItem(application.getNewAction());
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, MenuBarFactory.MENU_MASK));
menu.add(item);
}
item = new JMenuItem(application.getOpenAction());
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, MenuBarFactory.MENU_MASK));
menu.add(item);
item = new JMenuItem(frame.getSaveAction());
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, MenuBarFactory.MENU_MASK));
menu.add(item);
item = new JMenuItem(frame.getSaveAsAction());
menu.add(item);
if (frame.getImportAction() != null || frame.getExportAction() != null) {
menu.addSeparator();
if (frame.getImportAction() != null) {
item = new JMenuItem(frame.getImportAction());
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, MenuBarFactory.MENU_MASK));
menu.add(item);
}
if (frame.getExportAction() != null) {
item = new JMenuItem(frame.getExportAction());
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, MenuBarFactory.MENU_MASK));
menu.add(item);
}
}
menu.addSeparator();
item = new JMenuItem(frame.getPrintAction());
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, MenuBarFactory.MENU_MASK));
menu.add(item);
item = new JMenuItem(application.getPageSetupAction());
menu.add(item);
menu.addSeparator();
if (application.getRecentFileMenu() != null) {
JMenu subMenu = application.getRecentFileMenu();
menu.add(subMenu);
menu.addSeparator();
}
item = new JMenuItem(application.getExitAction());
menu.add(item);
}
public int getPreferredAlignment() {
return LEFT;
}
}
| 25.369565 | 89 | 0.718509 |
9d980e9f69eeba32612f19225357b8fc284f8d60 | 2,942 | package org.carlspring.maven.littleproxy.mojo;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.util.EntityUtils;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.junit.Ignore;
/**
* @author Martin Todorov (carlspring@gmail.com)
*/
@Ignore
public abstract class AbstractLittleProxyMojoTest
extends AbstractMojoTestCase
{
protected static final String TARGET_TEST_CLASSES = "target/test-classes";
protected static final String POM_PLUGIN = TARGET_TEST_CLASSES + "/poms/pom-start.xml";
protected CloseableHttpClient getCloseableHttpClientWithAuthenticatedProxy(HttpHost proxy)
{
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("testuser", "password");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), AuthScope.ANY_PORT), credentials);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.useSystemProperties();
clientBuilder.setProxy(proxy);
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
return clientBuilder.build();
}
protected void retrieveUrl(HttpHost target,
HttpHost proxy,
CloseableHttpClient client)
throws IOException
{
try
{
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet request = new HttpGet("/");
request.setConfig(config);
System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = client.execute(target, request);
try
{
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
}
finally
{
response.close();
}
assertEquals(200, response.getStatusLine().getStatusCode());
}
finally
{
client.close();
}
}
}
| 35.02381 | 116 | 0.680489 |
5204a20449f7f80e69d6020b6edfe6504963867b | 1,979 | package org.sql.assistant.select.join;
import org.sql.assistant.common.SqlProvider;
import org.sql.assistant.common.column.Column;
import org.sql.assistant.common.condition.Condition;
/**
* @author menfre
*/
public interface Join extends SqlProvider {
/**
* 左链接
*
* @param join 待链接对象
* @param condition 链接条件
* @return 链接对象
*/
default Join left(Join join, Condition condition) {
return completeJoin(join, condition, JoinType.LEFT);
}
/**
* 右链接
*
* @param join 待链接对象
* @param condition 链接条件
* @return 链接对象
*/
default Join right(Join join, Condition condition) {
return completeJoin(join, condition, JoinType.RIGHT);
}
/**
* 内链接
*
* @param join 待链接对象
* @param condition 链接条件
* @return 链接对象
*/
default Join inner(Join join, Condition condition) {
return completeJoin(join, condition, JoinType.INNER);
}
/**
* 全链接
*
* @param join 待链接对象
* @param condition 链接条件
* @return 链接对象
*/
default Join full(Join join, Condition condition) {
return completeJoin(join, condition, JoinType.FULL);
}
/**
* 完成 Join 操作
*
* @param join 待链接对象
* @param condition 链接条件
* @param joinType 链接类型
* @return 链接对象
*/
default Join completeJoin(Join join, Condition condition, JoinType joinType) {
return new CompleteJoin(this, join, joinType, condition);
}
/**
* Join 构造入口
*
* @param table 表名称
* @return 链接对象
*/
static Join of(String table) {
return of(Column.of(table));
}
/**
* Join 构造入口
*
* @param table 表字段
* @return 链接对象
*/
static Join of(Column table) {
return new JoinTable(table);
}
/**
* 获得参数
*
* @return 空参数组
*/
@Override
default Object[] getArgs() {
return new Object[0];
}
}
| 20.402062 | 82 | 0.561395 |
7a986b67023562d1afc3ab043b404453b8f8695d | 95 | package me.qinmian.emun;
public enum DataType {
String,Date,Number,Boolean,Link,None;
}
| 15.833333 | 39 | 0.726316 |
60cea5a846beab8170040bfaf18066cd3741240d | 14,474 | package cn.taroco.common.redis.template;
import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.Charset;
import java.util.*;
/**
* Redis Repository
* redis 基本操作 可扩展,基本够用了
* @author liuht
*/
@SuppressWarnings("ConstantConditions")
@Slf4j
public class TarocoRedisRepository {
/**
* 默认编码
*/
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
/**
* key序列化
*/
private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
/**
* value 序列化
*/
private static final JdkSerializationRedisSerializer OBJECT_SERIALIZER = new JdkSerializationRedisSerializer();
/**
* Spring Redis Template
*/
private RedisTemplate<String, String> redisTemplate;
public TarocoRedisRepository(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
this.redisTemplate.setKeySerializer(STRING_SERIALIZER);
this.redisTemplate.setValueSerializer(OBJECT_SERIALIZER);
}
/**
* 获取链接工厂
*/
public RedisConnectionFactory getConnectionFactory() {
return this.redisTemplate.getConnectionFactory();
}
/**
* 获取 RedisTemplate对象
*/
public RedisTemplate<String, String> getRedisTemplate() {
return redisTemplate;
}
/**
* 清空DB
*
* @param node redis 节点
*/
public void flushDB(RedisClusterNode node) {
this.redisTemplate.opsForCluster().flushDb(node);
}
/**
* 添加到带有 过期时间的 缓存
*
* @param key redis主键
* @param value 值
* @param time 过期时间
*/
public void setExpire(final byte[] key, final byte[] value, final long time) {
redisTemplate.execute((RedisCallback<Long>) connection -> {
connection.set(key, value);
connection.expire(key, time);
log.debug("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为{}秒", key, time);
return 1L;
});
}
/**
* 添加到带有 过期时间的 缓存
*
* @param key redis主键
* @param value 值
* @param time 过期时间
*/
public void setExpire(final String key, final String value, final long time) {
redisTemplate.execute((RedisCallback<Long>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = serializer.serialize(value);
connection.set(keys, values);
connection.expire(keys, time);
log.debug("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为{}秒", key, time);
return 1L;
});
}
/**
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
*
* @param keys redis主键数组
* @param values 值数组
* @param time 过期时间
*/
public void setExpire(final String[] keys, final String[] values, final long time) {
redisTemplate.execute((RedisCallback<Long>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
for (int i = 0; i < keys.length; i++) {
byte[] bKeys = serializer.serialize(keys[i]);
byte[] bValues = serializer.serialize(values[i]);
connection.set(bKeys, bValues);
connection.expire(bKeys, time);
log.debug("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为:{}秒", keys[i], time);
}
return 1L;
});
}
/**
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
*
* @param keys the keys
* @param values the values
*/
public void set(final String[] keys, final String[] values) {
redisTemplate.execute((RedisCallback<Long>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
for (int i = 0; i < keys.length; i++) {
byte[] bKeys = serializer.serialize(keys[i]);
byte[] bValues = serializer.serialize(values[i]);
connection.set(bKeys, bValues);
log.debug("[redisTemplate redis]放入 缓存 url:{}", keys[i]);
}
return 1L;
});
}
/**
* 添加到缓存
*
* @param key the key
* @param value the value
*/
public void set(final String key, final String value) {
redisTemplate.execute((RedisCallback<Long>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = serializer.serialize(value);
connection.set(keys, values);
log.debug("[redisTemplate redis]放入 缓存 url:{}", key);
return 1L;
});
}
/**
* 查询在这个时间段内即将过期的key
*
* @param key the key
* @param time the time
* @return the list
*/
public List<String> willExpire(final String key, final long time) {
final List<String> keysList = new ArrayList<>();
redisTemplate.execute((RedisCallback<List<String>>) connection -> {
Set<String> keys = redisTemplate.keys(key + "*");
for (String key1 : keys) {
Long ttl = connection.ttl(key1.getBytes(DEFAULT_CHARSET));
if (0 <= ttl && ttl <= 2 * time) {
keysList.add(key1);
}
}
return keysList;
});
return keysList;
}
/**
* 查询在以keyPatten的所有 key
*
* @param keyPatten the key patten
* @return the set
*/
public Set<String> keys(final String keyPatten) {
return redisTemplate.execute((RedisCallback<Set<String>>) connection -> redisTemplate.keys(keyPatten + "*"));
}
/**
* 根据key获取对象
*
* @param key the key
* @return the byte [ ]
*/
public byte[] get(final byte[] key) {
byte[] result = redisTemplate.execute((RedisCallback<byte[]>) connection -> connection.get(key));
log.debug("[redisTemplate redis]取出 缓存 url:{} ", key);
return result;
}
/**
* 根据key获取对象
*
* @param key the key
* @return the string
*/
public String get(final String key) {
String resultStr = redisTemplate.execute((RedisCallback<String>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = connection.get(keys);
return serializer.deserialize(values);
});
log.debug("[redisTemplate redis]取出 缓存 url:{} ", key);
return resultStr;
}
/**
* 根据key获取对象
*
* @param keyPatten the key patten
* @return the keys values
*/
public Map<String, String> getKeysValues(final String keyPatten) {
log.debug("[redisTemplate redis] getValues() patten={} ", keyPatten);
return redisTemplate.execute((RedisCallback<Map<String, String>>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
Map<String, String> maps = new HashMap<>(16);
Set<String> keys = redisTemplate.keys(keyPatten + "*");
if (CollUtil.isNotEmpty(keys)) {
for (String key : keys) {
byte[] bKeys = serializer.serialize(key);
byte[] bValues = connection.get(bKeys);
String value = serializer.deserialize(bValues);
maps.put(key, value);
}
}
return maps;
});
}
/**
* Ops for hash hash operations.
*
* @return the hash operations
*/
public HashOperations<String, String, String> opsForHash() {
return redisTemplate.opsForHash();
}
/**
* 对HashMap操作
*
* @param key the key
* @param hashKey the hash key
* @param hashValue the hash value
*/
public void putHashValue(String key, String hashKey, String hashValue) {
log.debug("[redisTemplate redis] putHashValue() key={},hashKey={},hashValue={} ", key, hashKey, hashValue);
opsForHash().put(key, hashKey, hashValue);
}
/**
* 获取单个field对应的值
*
* @param key the key
* @param hashKey the hash key
* @return the hash values
*/
public Object getHashValues(String key, String hashKey) {
log.debug("[redisTemplate redis] getHashValues() key={},hashKey={}", key, hashKey);
return opsForHash().get(key, hashKey);
}
/**
* 根据key值删除
*
* @param key the key
* @param hashKeys the hash keys
*/
public void delHashValues(String key, Object... hashKeys) {
log.debug("[redisTemplate redis] delHashValues() key={}", key);
opsForHash().delete(key, hashKeys);
}
/**
* key只匹配map
*
* @param key the key
* @return the hash value
*/
public Map<String, String> getHashValue(String key) {
log.debug("[redisTemplate redis] getHashValue() key={}", key);
return opsForHash().entries(key);
}
/**
* 批量添加
*
* @param key the key
* @param map the map
*/
public void putHashValues(String key, Map<String, String> map) {
opsForHash().putAll(key, map);
}
/**
* 集合数量
*
* @return the long
*/
public long dbSize() {
return redisTemplate.execute(RedisServerCommands::dbSize);
}
/**
* 清空redis存储的数据
*
* @return the string
*/
public String flushDB() {
return redisTemplate.execute((RedisCallback<String>) connection -> {
connection.flushDb();
return "ok";
});
}
/**
* 判断某个主键是否存在
*
* @param key the key
* @return the boolean
*/
public boolean exists(final String key) {
return redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.exists(key.getBytes(DEFAULT_CHARSET)));
}
/**
* 删除key
*
* @param keys the keys
* @return the long
*/
public long del(final String... keys) {
return redisTemplate.execute((RedisCallback<Long>) connection -> {
long result = 0;
for (String key : keys) {
result = connection.del(key.getBytes(DEFAULT_CHARSET));
}
return result;
});
}
/**
* 获取 RedisSerializer
*
* @return the redis serializer
*/
protected RedisSerializer<String> getRedisSerializer() {
return redisTemplate.getStringSerializer();
}
/**
* 对某个主键对应的值加一,value值必须是全数字的字符串
*
* @param key the key
* @return the long
*/
public long incr(final String key) {
return redisTemplate.execute((RedisCallback<Long>) connection -> {
RedisSerializer<String> redisSerializer = getRedisSerializer();
return connection.incr(redisSerializer.serialize(key));
});
}
/**
* redis List 引擎
*
* @return the list operations
*/
public ListOperations<String, String> opsForList() {
return redisTemplate.opsForList();
}
/**
* redis List数据结构 : 将一个或多个值 value 插入到列表 key 的表头
*
* @param key the key
* @param value the value
* @return the long
*/
public Long leftPush(String key, String value) {
return opsForList().leftPush(key, value);
}
/**
* redis List数据结构 : 移除并返回列表 key 的头元素
*
* @param key the key
* @return the string
*/
public String leftPop(String key) {
return opsForList().leftPop(key);
}
/**
* redis List数据结构 :将一个或多个值 value 插入到列表 key 的表尾(最右边)。
*
* @param key the key
* @param value the value
* @return the long
*/
public Long in(String key, String value) {
return opsForList().rightPush(key, value);
}
/**
* redis List数据结构 : 移除并返回列表 key 的末尾元素
*
* @param key the key
* @return the string
*/
public String rightPop(String key) {
return opsForList().rightPop(key);
}
/**
* redis List数据结构 : 返回列表 key 的长度 ; 如果 key 不存在,则 key 被解释为一个空列表,返回 0 ; 如果 key 不是列表类型,返回一个错误。
*
* @param key the key
* @return the long
*/
public Long length(String key) {
return opsForList().size(key);
}
/**
* redis List数据结构 : 根据参数 i 的值,移除列表中与参数 value 相等的元素
*
* @param key the key
* @param i the
* @param value the value
*/
public void remove(String key, long i, String value) {
opsForList().remove(key, i, value);
}
/**
* redis List数据结构 : 将列表 key 下标为 index 的元素的值设置为 value
*
* @param key the key
* @param index the index
* @param value the value
*/
public void set(String key, long index, String value) {
opsForList().set(key, index, value);
}
/**
* redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。
*
* @param key the key
* @param start the start
* @param end the end
* @return the list
*/
public List<String> getList(String key, int start, int end) {
return opsForList().range(key, start, end);
}
/**
* redis List数据结构 : 批量存储
*
* @param key the key
* @param list the list
* @return the long
*/
public Long leftPushAll(String key, List<String> list) {
return opsForList().leftPushAll(key, list);
}
/**
* redis List数据结构 : 将值 value 插入到列表 key 当中,位于值 index 之前或之后,默认之后。
*
* @param key the key
* @param index the index
* @param value the value
*/
public void insert(String key, long index, String value) {
opsForList().set(key, index, value);
}
}
| 28.324853 | 126 | 0.579522 |
6e16565fc9669302843cce470b081a3a735c3eb6 | 553 | package com.easy.restful.activiti.service;
import com.easy.restful.activiti.model.Historic;
import com.easy.restful.activiti.model.Task;
import java.util.List;
/**
* 流程历史活动记录
*
* @author tengchong
* @date 2020/5/7
*/
public interface HistoricService {
/**
* 查询
*
* @param processInstanceId 流程实例ID
* @return List<Historic>
*/
List<Historic> select(String processInstanceId);
/**
* 根据业务id查询流程实例
*
* @param businessKey 业务id
* @return 流程实例
*/
Task selectTask(String businessKey);
}
| 17.83871 | 52 | 0.64557 |
eb71920202ba46b2485826d84b499548b574b0b9 | 3,929 | /*
* Copyright (c) 2017 sadikovi
*
* 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.github.sadikovi.riff.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.xerial.snappy.Snappy;
public class SnappyCodec implements CompressionCodec {
// snappy size for temporary buffer
private static final int SNAPPY_BUFFER_SIZE = 4096;
// temporary byte array to reuse between compress calls
private byte[] buffer;
public SnappyCodec() {
// snappy buffer size is default size, it is reallocated if we need larger buffer
this.buffer = new byte[SNAPPY_BUFFER_SIZE];
}
@Override
public boolean compress(ByteBuffer in, ByteBuffer out, ByteBuffer overflow) throws IOException {
// find out approximate number of bytes we need for compression, note that this number can be
// higher than input size, but actual compressed bytes are smaller than input size
int compressedBytes = Snappy.maxCompressedLength(in.remaining());
// resize buffer if necessary
if (buffer.length < compressedBytes) {
buffer = new byte[compressedBytes];
}
// compress into allocated array and update compressed bytes
compressedBytes = Snappy.compress(in.array(), in.arrayOffset() + in.position(),
in.remaining(), buffer, 0);
// check if it is still better to keep data compressed, this check is done assuming that in
// buffer is not modified until this point
if (compressedBytes >= in.remaining()) {
out.position(out.limit());
if (overflow != null) {
overflow.position(overflow.limit());
}
return false;
} else {
// copy bytes into out and overflow buffers
int len = Math.min(compressedBytes, out.remaining());
out.put(buffer, 0, len);
compressedBytes -= len;
if (compressedBytes > 0) {
if (overflow == null || overflow.remaining() == 0) return false;
overflow.put(buffer, len, compressedBytes);
}
return true;
}
}
@Override
public void decompress(ByteBuffer in, ByteBuffer out) throws IOException {
int uncompressedBytes = Snappy.uncompressedLength(in.array(), in.arrayOffset() + in.position(),
in.remaining());
if (uncompressedBytes > out.remaining()) {
throw new IOException("Output buffer is too short, could not insert more bytes from " +
"compressed byte buffer");
}
// this does not update positions in in or out buffers, we will have to do manually after
// decompression.
uncompressedBytes = Snappy.uncompress(in.array(), in.arrayOffset() + in.position(),
in.remaining(), out.array(), out.arrayOffset() + out.position());
out.position(out.position() + uncompressedBytes);
// prepare for read
out.flip();
in.position(in.limit());
}
@Override
public void reset() {
// no-op
}
@Override
public void close() {
buffer = null;
}
}
| 38.519608 | 99 | 0.702723 |
6faf15a3bf92c0b1778731737728befdd2fb8427 | 2,323 | package com.varone.web.vo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class TasksVO {
private int index;
private int id;
private int attempt;
private String launchTime;
private String finishTime;
private String status;
private String duration;
private String locality;
private String gcTime;
private long resultSize;
private String executorID;
private String host;
private String inputSize;
private String records;
private long runTime;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAttempt() {
return attempt;
}
public void setAttempt(int attempt) {
this.attempt = attempt;
}
public String getLaunchTime() {
return launchTime;
}
public void setLaunchTime(String launchTime) {
this.launchTime = launchTime;
}
public String getFinishTime() {
return finishTime;
}
public void setFinishTime(String finishTime) {
this.finishTime = finishTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getGcTime() {
return gcTime;
}
public void setGcTime(String gcTime) {
this.gcTime = gcTime;
}
public String getInputSize() {
return inputSize;
}
public void setInputSize(String inputSize) {
this.inputSize = inputSize;
}
public long getRunTime() {
return runTime;
}
public void setRunTime(long runTime) {
this.runTime = runTime;
}
public long getResultSize() {
return resultSize;
}
public void setResultSize(long resultSize) {
this.resultSize = resultSize;
}
public String getRecords() {
return records;
}
public void setRecords(String records) {
this.records = records;
}
public String getExecutorID() {
return executorID;
}
public void setExecutorID(String executorID) {
this.executorID = executorID;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
| 19.521008 | 48 | 0.72062 |
db872bdd75ac41609383292104161bf5686794ee | 654 | package com.uuhnaut69.cdc.constant;
/**
* @author uuhnaut
* @project mall
*/
public class CDCTableConstant {
public static final String PRODUCT_TABLE = "product";
public static final String USER_TABLE = "users";
public static final String USER_PRODUCT_TABLE = "user_product";
public static final String USER_TAG_TABLE = "user_tag";
public static final String PRODUCT_TAG_TABLE = "product_tag";
public static final String TAG_TABLE = "tag";
public static final String CATEGORY_TABLE = "category";
public static final String PRODUCT_CATEGORY_TABLE = "product_category";
private CDCTableConstant() {
}
}
| 23.357143 | 75 | 0.7263 |
ae4eff84bf225a6e7cf43ecac50698430daa1b13 | 2,344 | package com.qxy.common.Do;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.util.Date;
/**
* @Author:qxy
* @Date:2020/4/7 9:41
*/
public class StudentDo implements InitializingBean, BeanPostProcessor {
private ClassDo classDo;
private Integer studentId;
private String studentName;
private Integer studentAge;
private Integer classId;
private String mobile;
private String address;
private Date createTime;
private Date operateTime;
public ClassDo getClassDo() {
return classDo;
}
public void setClassDo(ClassDo classDo) {
this.classDo = classDo;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Integer getStudentAge() {
return studentAge;
}
public void setStudentAge(Integer studentAge) {
this.studentAge = studentAge;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getOperateTime() {
return operateTime;
}
public void setOperateTime(Date operateTime) {
this.operateTime = operateTime;
}
@Override
public void afterPropertiesSet() throws Exception {
this.setClassId(11111);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
this.setAddress("beanPostProcessor");
return bean;
}
}
| 20.561404 | 102 | 0.65785 |
203527abcd1cbb50dd6cc132bb3872895be7b588 | 801 | package com.zhongyp.concurrency.thread.latchcyclicbarrier.latch;
import java.util.concurrent.*;
/**
* project: demo
* author: zhongyp
* date: 2018/3/29
* mail: zhongyp001@163.com
*/
public class Test {
public static void main(String[] args){
Executor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
CountDownLatch countDownLatch = new CountDownLatch(3);
Work work1 = new Work(countDownLatch,"one");
Work work2 = new Work(countDownLatch,"two");
Work work3 = new Work(countDownLatch,"three");
Boss boss = new Boss(countDownLatch);
executor.execute(boss);
executor.execute(work1);
executor.execute(work2);
executor.execute(work3);
}
}
| 24.272727 | 129 | 0.667915 |
d5f386730134347fdc45ec6400941ed3b14f058c | 2,258 | package io.resys.thena.docdb.spi.pgsql;
/*-
* #%L
* thena-docdb-mongo
* %%
* Copyright (C) 2021 Copyright 2021 ReSys OÜ
* %%
* 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.
* #L%
*/
import io.resys.thena.docdb.spi.ClientQuery;
import io.resys.thena.docdb.spi.pgsql.builders.PgBlobQuery;
import io.resys.thena.docdb.spi.pgsql.builders.PgCommitQuery;
import io.resys.thena.docdb.spi.pgsql.builders.PgRefQuery;
import io.resys.thena.docdb.spi.pgsql.builders.PgTagQuery;
import io.resys.thena.docdb.spi.pgsql.builders.PgTreeQuery;
import io.resys.thena.docdb.spi.pgsql.support.ClientWrapper;
import io.resys.thena.docdb.spi.sql.SqlBuilder;
import io.resys.thena.docdb.spi.sql.SqlMapper;
public class PgClientQuery implements ClientQuery {
private final ClientWrapper wrapper;
private final SqlBuilder sqlBuilder;
private final SqlMapper sqlMapper;
public PgClientQuery(ClientWrapper wrapper, SqlMapper sqlMapper, SqlBuilder sqlBuilder) {
this.wrapper = wrapper;
this.sqlBuilder = sqlBuilder;
this.sqlMapper = sqlMapper;
}
@Override
public TagQuery tags() {
return new PgTagQuery(wrapper.getClient(), wrapper.getNames(), sqlMapper, sqlBuilder);
}
@Override
public CommitQuery commits() {
return new PgCommitQuery(wrapper.getClient(), wrapper.getNames(), sqlMapper, sqlBuilder);
}
@Override
public RefQuery refs() {
return new PgRefQuery(wrapper.getClient(), wrapper.getNames(), sqlMapper, sqlBuilder);
}
@Override
public TreeQuery trees() {
return new PgTreeQuery(wrapper.getClient(), wrapper.getNames(), sqlMapper, sqlBuilder);
}
@Override
public BlobQuery blobs() {
return new PgBlobQuery(wrapper.getClient(), wrapper.getNames(), sqlMapper, sqlBuilder);
}
}
| 32.257143 | 93 | 0.745793 |
f42a9c53a6b589e3c4c75b4d77f8e8633a5fc69b | 1,693 | /* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.mybatis;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class MyBatisBeanEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
MyBatisBeanEndpoint target = (MyBatisBeanEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "executortype":
case "executorType": target.setExecutorType(property(camelContext, org.apache.ibatis.session.ExecutorType.class, value)); return true;
case "inputheader":
case "inputHeader": target.setInputHeader(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "outputheader":
case "outputHeader": target.setOutputHeader(property(camelContext, java.lang.String.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
}
| 48.371429 | 142 | 0.744241 |
63295438fc1465736f0546503c150c9214981d7f | 1,509 | /*
* Copyright 2008-2009 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 egovframework.dev.imp.ide.wizards.model;
/**
* 신규 웹 프로젝트 컨택스트 클래스
* @author 개발환경 개발팀 이흥주
* @since 2009.06.01
* @version 1.0
* @see <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.02.20 이흥주 최초 생성
*
*
* </pre>
*/
public class NewWebProjectContext extends NewProjectContext {
/** 서블릿 버젼 */
private String servletVersion;
/** 서버 런타임 명 */
private String runtimeName;
public String getRuntimeName() {
return runtimeName;
}
public void setRuntimeName(String runtimeName) {
this.runtimeName = runtimeName;
}
public String getServletVersion() {
return servletVersion;
}
public void setServletVersion(String servletVersion) {
this.servletVersion = servletVersion;
}
}
| 26.473684 | 75 | 0.646786 |
52544cb69e881e8fe9564ff2c934e5dde78bd34d | 31,439 | /*
* Tencent is pleased to support the open source community by making Tinker available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.tinker.lib.patch;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.SystemClock;
import com.tencent.tinker.commons.dexpatcher.DexPatchApplier;
import com.tencent.tinker.commons.resutil.ResUtil;
import com.tencent.tinker.commons.ziputil.TinkerZipEntry;
import com.tencent.tinker.commons.ziputil.TinkerZipFile;
import com.tencent.tinker.commons.ziputil.TinkerZipOutputStream;
import com.tencent.tinker.lib.tinker.Tinker;
import com.tencent.tinker.lib.util.TinkerLog;
import com.tencent.tinker.loader.TinkerDexOptimizer;
import com.tencent.tinker.loader.TinkerRuntimeException;
import com.tencent.tinker.loader.shareutil.ShareConstants;
import com.tencent.tinker.loader.shareutil.ShareDexDiffPatchInfo;
import com.tencent.tinker.loader.shareutil.ShareElfFile;
import com.tencent.tinker.loader.shareutil.SharePatchFileUtil;
import com.tencent.tinker.loader.shareutil.ShareSecurityCheck;
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* Created by zhangshaowen on 16/4/12.
*/
public class DexDiffPatchInternal extends BasePatchInternal {
protected static final String TAG = "Tinker.DexDiffPatchInternal";
protected static final int WAIT_ASYN_OAT_TIME = 15 * 1000;
protected static final int MAX_WAIT_COUNT = 30;
private static ArrayList<File> optFiles = new ArrayList<>();
private static ArrayList<ShareDexDiffPatchInfo> patchList = new ArrayList<>();
private static HashMap<ShareDexDiffPatchInfo, File> classNDexInfo = new HashMap<>();
private static boolean isVmArt = ShareTinkerInternals.isVmArt();
protected static boolean tryRecoverDexFiles(Tinker manager, ShareSecurityCheck checker, Context context,
String patchVersionDirectory, File patchFile) {
if (!manager.isEnabledForDex()) {
TinkerLog.w(TAG, "patch recover, dex is not enabled");
return true;
}
String dexMeta = checker.getMetaContentMap().get(DEX_META_FILE);
if (dexMeta == null) {
TinkerLog.w(TAG, "patch recover, dex is not contained");
return true;
}
long begin = SystemClock.elapsedRealtime();
boolean result = patchDexExtractViaDexDiff(context, patchVersionDirectory, dexMeta, patchFile);
long cost = SystemClock.elapsedRealtime() - begin;
TinkerLog.i(TAG, "recover dex result:%b, cost:%d", result, cost);
return result;
}
protected static boolean waitAndCheckDexOptFile(File patchFile, Tinker manager) {
if (optFiles.isEmpty()) {
return true;
}
// should use patch list size
int size = patchList.size() * 8;
if (size > MAX_WAIT_COUNT) {
size = MAX_WAIT_COUNT;
}
TinkerLog.i(TAG, "raw dex count: %d, dex opt dex count: %d, final wait times: %d", patchList.size(), optFiles.size(), size);
for (int i = 0; i < size; i++) {
if (!checkAllDexOptFile(optFiles, i + 1)) {
try {
Thread.sleep(WAIT_ASYN_OAT_TIME);
} catch (InterruptedException e) {
TinkerLog.e(TAG, "thread sleep InterruptedException e:" + e);
}
}
}
List<File> failDexFiles = new ArrayList<>();
// check again, if still can be found, just return
for (File file : optFiles) {
TinkerLog.i(TAG, "check dex optimizer file exist: %s, size %d", file.getPath(), file.length());
if (!SharePatchFileUtil.isLegalFile(file)) {
TinkerLog.e(TAG, "final parallel dex optimizer file %s is not exist, return false", file.getName());
failDexFiles.add(file);
}
}
if (!failDexFiles.isEmpty()) {
manager.getPatchReporter().onPatchDexOptFail(patchFile, failDexFiles,
new TinkerRuntimeException(ShareConstants.CHECK_DEX_OAT_EXIST_FAIL));
return false;
}
if (Build.VERSION.SDK_INT >= 21) {
Throwable lastThrowable = null;
for (File file : optFiles) {
TinkerLog.i(TAG, "check dex optimizer file format: %s, size %d", file.getName(), file.length());
int returnType;
try {
returnType = ShareElfFile.getFileTypeByMagic(file);
} catch (IOException e) {
// read error just continue
continue;
}
if (returnType == ShareElfFile.FILE_TYPE_ELF) {
ShareElfFile elfFile = null;
try {
elfFile = new ShareElfFile(file);
} catch (Throwable e) {
TinkerLog.e(TAG, "final parallel dex optimizer file %s is not elf format, return false", file.getName());
failDexFiles.add(file);
lastThrowable = e;
} finally {
if (elfFile != null) {
try {
elfFile.close();
} catch (IOException ignore) {
}
}
}
}
}
if (!failDexFiles.isEmpty()) {
Throwable returnThrowable = lastThrowable == null
? new TinkerRuntimeException(ShareConstants.CHECK_DEX_OAT_FORMAT_FAIL)
: new TinkerRuntimeException(ShareConstants.CHECK_DEX_OAT_FORMAT_FAIL, lastThrowable);
manager.getPatchReporter().onPatchDexOptFail(patchFile, failDexFiles,
returnThrowable);
return false;
}
}
return true;
}
private static boolean patchDexExtractViaDexDiff(Context context, String patchVersionDirectory, String meta, final File patchFile) {
String dir = patchVersionDirectory + "/" + DEX_PATH + "/";
if (!extractDexDiffInternals(context, dir, meta, patchFile, TYPE_DEX)) {
TinkerLog.w(TAG, "patch recover, extractDiffInternals fail");
return false;
}
File dexFiles = new File(dir);
File[] files = dexFiles.listFiles();
List<File> dexList = files != null ? Arrays.asList(files) : null;
final String optimizeDexDirectory = patchVersionDirectory + "/" + DEX_OPTIMIZE_PATH + "/";
return dexOptimizeDexFiles(context, dexList, optimizeDexDirectory, patchFile);
}
private static boolean checkClassNDexFiles(final String dexFilePath) {
if (patchList.isEmpty() || !isVmArt) {
return false;
}
ShareDexDiffPatchInfo testInfo = null;
File testFile = null;
for (ShareDexDiffPatchInfo info : patchList) {
File dexFile = new File(dexFilePath + info.realName);
String fileName = dexFile.getName();
if (ShareConstants.CLASS_N_PATTERN.matcher(fileName).matches()) {
classNDexInfo.put(info, dexFile);
}
if (info.rawName.startsWith(ShareConstants.TEST_DEX_NAME)) {
testInfo = info;
testFile = dexFile;
}
}
if (testInfo != null) {
classNDexInfo.put(ShareTinkerInternals.changeTestDexToClassN(testInfo, classNDexInfo.size() + 1), testFile);
}
File classNFile = new File(dexFilePath, ShareConstants.CLASS_N_APK_NAME);
boolean result = true;
if (classNFile.exists()) {
for (ShareDexDiffPatchInfo info : classNDexInfo.keySet()) {
if (!SharePatchFileUtil.verifyDexFileMd5(classNFile, info.rawName, info.destMd5InArt)) {
TinkerLog.e(TAG, "verify dex file md5 error, entry name; %s, file len: %d", info.rawName, classNFile.length());
result = false;
break;
}
}
if (!result) {
SharePatchFileUtil.safeDeleteFile(classNFile);
}
} else {
result = false;
}
return result;
}
private static boolean mergeClassNDexFiles(final Context context, final File patchFile, final String dexFilePath) {
// only merge for art vm
if (patchList.isEmpty() || !isVmArt) {
return true;
}
File classNFile = new File(dexFilePath, ShareConstants.CLASS_N_APK_NAME);
// repack just more than one classN.dex
if (classNDexInfo.isEmpty()) {
TinkerLog.w(TAG, "classNDexInfo size: %d, no need to merge classN dex files", classNDexInfo.size());
return true;
}
long start = System.currentTimeMillis();
boolean result = true;
TinkerZipOutputStream out = null;
try {
out = new TinkerZipOutputStream(new BufferedOutputStream(new FileOutputStream(classNFile)));
for (ShareDexDiffPatchInfo info : classNDexInfo.keySet()) {
File dexFile = classNDexInfo.get(info);
if (info.isJarMode) {
TinkerZipFile dexZipFile = new TinkerZipFile(dexFile);
TinkerZipEntry rawDexZipEntry = dexZipFile.getEntry(ShareConstants.DEX_IN_JAR);
TinkerZipEntry newDexZipEntry = new TinkerZipEntry(rawDexZipEntry, info.rawName);
InputStream inputStream = dexZipFile.getInputStream(rawDexZipEntry);
try {
ResUtil.extractTinkerEntry(newDexZipEntry, inputStream, out);
} finally {
SharePatchFileUtil.closeQuietly(inputStream);
}
} else {
TinkerZipEntry dexZipEntry = new TinkerZipEntry(info.rawName);
ResUtil.extractLargeModifyFile(dexZipEntry, dexFile, Long.parseLong(info.newDexCrC), out);
}
}
} catch (Throwable throwable) {
TinkerLog.printErrStackTrace(TAG, throwable, "merge classN file");
result = false;
} finally {
SharePatchFileUtil.closeQuietly(out);
}
if (result) {
for (ShareDexDiffPatchInfo info : classNDexInfo.keySet()) {
if (!SharePatchFileUtil.verifyDexFileMd5(classNFile, info.rawName, info.destMd5InArt)) {
result = false;
TinkerLog.e(TAG, "verify dex file md5 error, entry name; %s, file len: %d", info.rawName, classNFile.length());
break;
}
}
}
if (result) {
for (File dexFile : classNDexInfo.values()) {
SharePatchFileUtil.safeDeleteFile(dexFile);
}
} else {
TinkerLog.e(TAG, "merge classN dex error, try delete temp file");
SharePatchFileUtil.safeDeleteFile(classNFile);
Tinker.with(context).getPatchReporter().onPatchTypeExtractFail(patchFile, classNFile, classNFile.getName(), TYPE_CLASS_N_DEX);
}
TinkerLog.i(TAG, "merge classN dex file %s, result: %b, size: %d, use: %dms",
classNFile.getPath(), result, classNFile.length(), (System.currentTimeMillis() - start));
return result;
}
private static boolean dexOptimizeDexFiles(Context context, List<File> dexFiles, String optimizeDexDirectory, final File patchFile) {
final Tinker manager = Tinker.with(context);
optFiles.clear();
if (dexFiles != null) {
File optimizeDexDirectoryFile = new File(optimizeDexDirectory);
if (!optimizeDexDirectoryFile.exists() && !optimizeDexDirectoryFile.mkdirs()) {
TinkerLog.w(TAG, "patch recover, make optimizeDexDirectoryFile fail");
return false;
}
// add opt files
for (File file : dexFiles) {
String outputPathName = SharePatchFileUtil.optimizedPathFor(file, optimizeDexDirectoryFile);
optFiles.add(new File(outputPathName));
}
TinkerLog.i(TAG, "patch recover, try to optimize dex file count:%d, optimizeDexDirectory:%s", dexFiles.size(), optimizeDexDirectory);
// only use parallel dex optimizer for art
// for Android O version, it is very strange. If we use parallel dex optimizer, it won't work
final List<File> failOptDexFile = new Vector<>();
final Throwable[] throwable = new Throwable[1];
// try parallel dex optimizer
TinkerDexOptimizer.optimizeAll(
dexFiles, optimizeDexDirectoryFile,
new TinkerDexOptimizer.ResultCallback() {
long startTime;
@Override
public void onStart(File dexFile, File optimizedDir) {
startTime = System.currentTimeMillis();
TinkerLog.i(TAG, "start to parallel optimize dex %s, size: %d", dexFile.getPath(), dexFile.length());
}
@Override
public void onSuccess(File dexFile, File optimizedDir, File optimizedFile) {
// Do nothing.
TinkerLog.i(TAG, "success to parallel optimize dex %s, opt file:%s, opt file size: %d, use time %d",
dexFile.getPath(), optimizedFile.getPath(), optimizedFile.length(), (System.currentTimeMillis() - startTime));
}
@Override
public void onFailed(File dexFile, File optimizedDir, Throwable thr) {
TinkerLog.i(TAG, "fail to parallel optimize dex %s use time %d",
dexFile.getPath(), (System.currentTimeMillis() - startTime));
failOptDexFile.add(dexFile);
throwable[0] = thr;
}
}
);
if (!failOptDexFile.isEmpty()) {
manager.getPatchReporter().onPatchDexOptFail(patchFile, failOptDexFile, throwable[0]);
return false;
}
}
return true;
}
/**
* for ViVo or some other rom, they would make dex2oat asynchronous
* so we need to check whether oat file is actually generated.
*
* @param files
* @param count
* @return
*/
private static boolean checkAllDexOptFile(ArrayList<File> files, int count) {
for (File file : files) {
if (!SharePatchFileUtil.isLegalFile(file)) {
TinkerLog.e(TAG, "parallel dex optimizer file %s is not exist, just wait %d times", file.getName(), count);
return false;
}
}
return true;
}
private static boolean extractDexDiffInternals(Context context, String dir, String meta, File patchFile, int type) {
//parse
patchList.clear();
ShareDexDiffPatchInfo.parseDexDiffPatchInfo(meta, patchList);
if (patchList.isEmpty()) {
TinkerLog.w(TAG, "extract patch list is empty! type:%s:", ShareTinkerInternals.getTypeString(type));
return true;
}
File directory = new File(dir);
if (!directory.exists()) {
directory.mkdirs();
}
//I think it is better to extract the raw files from apk
Tinker manager = Tinker.with(context);
ZipFile apk = null;
ZipFile patch = null;
try {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if (applicationInfo == null) {
// Looks like running on a test Context, so just return without patching.
TinkerLog.w(TAG, "applicationInfo == null!!!!");
return false;
}
String apkPath = applicationInfo.sourceDir;
apk = new ZipFile(apkPath);
patch = new ZipFile(patchFile);
if (checkClassNDexFiles(dir)) {
TinkerLog.w(TAG, "class n dex file %s is already exist, and md5 match, just continue", ShareConstants.CLASS_N_APK_NAME);
return true;
}
for (ShareDexDiffPatchInfo info : patchList) {
long start = System.currentTimeMillis();
final String infoPath = info.path;
String patchRealPath;
if (infoPath.equals("")) {
patchRealPath = info.rawName;
} else {
patchRealPath = info.path + "/" + info.rawName;
}
String dexDiffMd5 = info.dexDiffMd5;
String oldDexCrc = info.oldDexCrC;
if (!isVmArt && info.destMd5InDvm.equals("0")) {
TinkerLog.w(TAG, "patch dex %s is only for art, just continue", patchRealPath);
continue;
}
String extractedFileMd5 = isVmArt ? info.destMd5InArt : info.destMd5InDvm;
if (!SharePatchFileUtil.checkIfMd5Valid(extractedFileMd5)) {
TinkerLog.w(TAG, "meta file md5 invalid, type:%s, name: %s, md5: %s", ShareTinkerInternals.getTypeString(type), info.rawName, extractedFileMd5);
manager.getPatchReporter().onPatchPackageCheckFail(patchFile, BasePatchInternal.getMetaCorruptedCode(type));
return false;
}
File extractedFile = new File(dir + info.realName);
//check file whether already exist
if (extractedFile.exists()) {
if (SharePatchFileUtil.verifyDexFileMd5(extractedFile, extractedFileMd5)) {
//it is ok, just continue
TinkerLog.w(TAG, "dex file %s is already exist, and md5 match, just continue", extractedFile.getPath());
continue;
} else {
TinkerLog.w(TAG, "have a mismatch corrupted dex " + extractedFile.getPath());
extractedFile.delete();
}
} else {
extractedFile.getParentFile().mkdirs();
}
ZipEntry patchFileEntry = patch.getEntry(patchRealPath);
ZipEntry rawApkFileEntry = apk.getEntry(patchRealPath);
if (oldDexCrc.equals("0")) {
if (patchFileEntry == null) {
TinkerLog.w(TAG, "patch entry is null. path:" + patchRealPath);
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
//it is a new file, but maybe we need to repack the dex file
if (!extractDexFile(patch, patchFileEntry, extractedFile, info)) {
TinkerLog.w(TAG, "Failed to extract raw patch file " + extractedFile.getPath());
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
} else if (dexDiffMd5.equals("0")) {
// skip process old dex for real dalvik vm
if (!isVmArt) {
continue;
}
if (rawApkFileEntry == null) {
TinkerLog.w(TAG, "apk entry is null. path:" + patchRealPath);
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
//check source crc instead of md5 for faster
String rawEntryCrc = String.valueOf(rawApkFileEntry.getCrc());
if (!rawEntryCrc.equals(oldDexCrc)) {
TinkerLog.e(TAG, "apk entry %s crc is not equal, expect crc: %s, got crc: %s", patchRealPath, oldDexCrc, rawEntryCrc);
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
// Small patched dex generating strategy was disabled, we copy full original dex directly now.
//patchDexFile(apk, patch, rawApkFileEntry, null, info, smallPatchInfoFile, extractedFile);
extractDexFile(apk, rawApkFileEntry, extractedFile, info);
if (!SharePatchFileUtil.verifyDexFileMd5(extractedFile, extractedFileMd5)) {
TinkerLog.w(TAG, "Failed to recover dex file when verify patched dex: " + extractedFile.getPath());
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
SharePatchFileUtil.safeDeleteFile(extractedFile);
return false;
}
} else {
if (patchFileEntry == null) {
TinkerLog.w(TAG, "patch entry is null. path:" + patchRealPath);
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
if (!SharePatchFileUtil.checkIfMd5Valid(dexDiffMd5)) {
TinkerLog.w(TAG, "meta file md5 invalid, type:%s, name: %s, md5: %s", ShareTinkerInternals.getTypeString(type), info.rawName, dexDiffMd5);
manager.getPatchReporter().onPatchPackageCheckFail(patchFile, BasePatchInternal.getMetaCorruptedCode(type));
return false;
}
if (rawApkFileEntry == null) {
TinkerLog.w(TAG, "apk entry is null. path:" + patchRealPath);
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
//check source crc instead of md5 for faster
String rawEntryCrc = String.valueOf(rawApkFileEntry.getCrc());
if (!rawEntryCrc.equals(oldDexCrc)) {
TinkerLog.e(TAG, "apk entry %s crc is not equal, expect crc: %s, got crc: %s", patchRealPath, oldDexCrc, rawEntryCrc);
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
return false;
}
patchDexFile(apk, patch, rawApkFileEntry, patchFileEntry, info, extractedFile);
if (!SharePatchFileUtil.verifyDexFileMd5(extractedFile, extractedFileMd5)) {
TinkerLog.w(TAG, "Failed to recover dex file when verify patched dex: " + extractedFile.getPath());
manager.getPatchReporter().onPatchTypeExtractFail(patchFile, extractedFile, info.rawName, type);
SharePatchFileUtil.safeDeleteFile(extractedFile);
return false;
}
TinkerLog.w(TAG, "success recover dex file: %s, size: %d, use time: %d",
extractedFile.getPath(), extractedFile.length(), (System.currentTimeMillis() - start));
}
}
if (!mergeClassNDexFiles(context, patchFile, dir)) {
return false;
}
} catch (Throwable e) {
throw new TinkerRuntimeException("patch " + ShareTinkerInternals.getTypeString(type) + " extract failed (" + e.getMessage() + ").", e);
} finally {
SharePatchFileUtil.closeZip(apk);
SharePatchFileUtil.closeZip(patch);
}
return true;
}
/**
* repack dex to jar
*
* @param zipFile
* @param entryFile
* @param extractTo
* @param targetMd5
* @return boolean
* @throws IOException
*/
private static boolean extractDexToJar(ZipFile zipFile, ZipEntry entryFile, File extractTo, String targetMd5) throws IOException {
int numAttempts = 0;
boolean isExtractionSuccessful = false;
while (numAttempts < MAX_EXTRACT_ATTEMPTS && !isExtractionSuccessful) {
numAttempts++;
FileOutputStream fos = new FileOutputStream(extractTo);
InputStream in = zipFile.getInputStream(entryFile);
ZipOutputStream zos = null;
BufferedInputStream bis = null;
TinkerLog.i(TAG, "try Extracting " + extractTo.getPath());
try {
zos = new ZipOutputStream(new
BufferedOutputStream(fos));
bis = new BufferedInputStream(in);
byte[] buffer = new byte[ShareConstants.BUFFER_SIZE];
ZipEntry entry = new ZipEntry(ShareConstants.DEX_IN_JAR);
zos.putNextEntry(entry);
int length = bis.read(buffer);
while (length != -1) {
zos.write(buffer, 0, length);
length = bis.read(buffer);
}
zos.closeEntry();
} finally {
SharePatchFileUtil.closeQuietly(bis);
SharePatchFileUtil.closeQuietly(zos);
}
isExtractionSuccessful = SharePatchFileUtil.verifyDexFileMd5(extractTo, targetMd5);
TinkerLog.i(TAG, "isExtractionSuccessful: %b", isExtractionSuccessful);
if (!isExtractionSuccessful) {
extractTo.delete();
if (extractTo.exists()) {
TinkerLog.e(TAG, "Failed to delete corrupted dex " + extractTo.getPath());
}
}
}
return isExtractionSuccessful;
}
// /**
// * reject dalvik vm, but sdk version is larger than 21
// */
// private static void checkVmArtProperty() {
// boolean art = ShareTinkerInternals.isVmArt();
// if (!art && Build.VERSION.SDK_INT >= 21) {
// throw new TinkerRuntimeException(ShareConstants.CHECK_VM_PROPERTY_FAIL + ", it is dalvik vm, but sdk version " + Build.VERSION.SDK_INT + " is larger than 21!");
// }
// }
private static boolean extractDexFile(ZipFile zipFile, ZipEntry entryFile, File extractTo, ShareDexDiffPatchInfo dexInfo) throws IOException {
final String fileMd5 = isVmArt ? dexInfo.destMd5InArt : dexInfo.destMd5InDvm;
final String rawName = dexInfo.rawName;
final boolean isJarMode = dexInfo.isJarMode;
//it is raw dex and we use jar mode, so we need to zip it!
if (SharePatchFileUtil.isRawDexFile(rawName) && isJarMode) {
return extractDexToJar(zipFile, entryFile, extractTo, fileMd5);
}
return extract(zipFile, entryFile, extractTo, fileMd5, true);
}
/**
* Generate patched dex file (May wrapped it by a jar if needed.)
*
* @param baseApk OldApk.
* @param patchPkg Patch package, it is also a zip file.
* @param oldDexEntry ZipEntry of old dex.
* @param patchFileEntry ZipEntry of patch file. (also ends with .dex) This could be null.
* @param patchInfo Parsed patch info from package-meta.txt
* @param patchedDexFile Patched dex file, may be a jar.
* <p>
* <b>Notice: patchFileEntry and smallPatchInfoFile cannot both be null.</b>
* @throws IOException
*/
private static void patchDexFile(
ZipFile baseApk, ZipFile patchPkg, ZipEntry oldDexEntry, ZipEntry patchFileEntry,
ShareDexDiffPatchInfo patchInfo, File patchedDexFile) throws IOException {
InputStream oldDexStream = null;
InputStream patchFileStream = null;
try {
oldDexStream = new BufferedInputStream(baseApk.getInputStream(oldDexEntry));
patchFileStream = (patchFileEntry != null ? new BufferedInputStream(patchPkg.getInputStream(patchFileEntry)) : null);
final boolean isRawDexFile = SharePatchFileUtil.isRawDexFile(patchInfo.rawName);
if (!isRawDexFile || patchInfo.isJarMode) {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(patchedDexFile)));
zos.putNextEntry(new ZipEntry(ShareConstants.DEX_IN_JAR));
// Old dex is not a raw dex file.
if (!isRawDexFile) {
ZipInputStream zis = null;
try {
zis = new ZipInputStream(oldDexStream);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (ShareConstants.DEX_IN_JAR.equals(entry.getName())) break;
}
if (entry == null) {
throw new TinkerRuntimeException("can't recognize zip dex format file:" + patchedDexFile.getAbsolutePath());
}
new DexPatchApplier(zis, patchFileStream).executeAndSaveTo(zos);
} finally {
SharePatchFileUtil.closeQuietly(zis);
}
} else {
new DexPatchApplier(oldDexStream, patchFileStream).executeAndSaveTo(zos);
}
zos.closeEntry();
} finally {
SharePatchFileUtil.closeQuietly(zos);
}
} else {
new DexPatchApplier(oldDexStream, patchFileStream).executeAndSaveTo(patchedDexFile);
}
} finally {
SharePatchFileUtil.closeQuietly(oldDexStream);
SharePatchFileUtil.closeQuietly(patchFileStream);
}
}
}
| 45.89635 | 174 | 0.576895 |
1cc5765fe523f360e33214dde63e053023d70db9 | 1,583 | package com.librarymanagement.application.backend.controller;
import com.librarymanagement.application.backend.dto.Member;
import com.librarymanagement.application.backend.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
public class MemberController {
@Autowired
MemberService memberService;
//creating a get mapping that retrieves all the members detail from the database
@GetMapping("/members")
private List<Member> getAllMember()
{
return memberService.findAll();
}
//creating a get mapping that retrieves the detail of a specific member
@GetMapping("/members/{memberId}")
private Optional <Member> getMember(@PathVariable("memberId") int memberId)
{
return memberService.get(memberId);
}
//creating a delete mapping that deletes a specified member
@DeleteMapping("/members/{memberId}")
private void deleteMember(@PathVariable("memberId") int memberId)
{
memberService.delete(memberId);
}
//creating post mapping that post the member detail in the database
@PostMapping("/members")
private Member saveMember(@RequestBody Member member)
{
memberService.save(member);
return member;
}
//creating put mapping that updates the member detail
@PutMapping("/members")
private Member update(@RequestBody Member member)
{
memberService.save(member);
return member;
}
}
| 32.306122 | 84 | 0.723942 |
4b21b09b164629c711724e2a33fa21660f0b120d | 5,057 | package org.netlight.encoding;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.TooLongFrameException;
import java.util.List;
/**
* @author ahmad
*/
public class JsonObjectDecoder extends ByteToMessageDecoder {
private static final int ST_CORRUPTED = -1;
private static final int ST_INIT = 0;
private static final int ST_DECODING_NORMAL = 1;
private static final int ST_DECODING_ARRAY_STREAM = 2;
private final int maxObjectLength;
private final boolean streamArrayElements;
private int openBraces;
private int idx;
private int state;
private boolean insideString;
public JsonObjectDecoder() {
this(1024 * 1024);
}
public JsonObjectDecoder(int maxObjectLength) {
this(maxObjectLength, false);
}
public JsonObjectDecoder(boolean streamArrayElements) {
this(1024 * 1024, streamArrayElements);
}
public JsonObjectDecoder(int maxObjectLength, boolean streamArrayElements) {
if (maxObjectLength < 1) {
throw new IllegalArgumentException("maxObjectLength must be a positive int");
}
this.maxObjectLength = maxObjectLength;
this.streamArrayElements = streamArrayElements;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (state == ST_CORRUPTED) {
in.skipBytes(in.readableBytes());
return;
}
int idx = this.idx;
int wrtIdx = in.writerIndex();
if (wrtIdx > maxObjectLength) {
in.skipBytes(in.readableBytes());
reset();
throw new TooLongFrameException("object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
}
for (; idx < wrtIdx; idx++) {
byte c = in.getByte(idx);
if (state == ST_DECODING_NORMAL) {
decodeByte(c, in, idx);
if (openBraces == 0) {
ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
if (json != null) {
out.add(json);
}
in.readerIndex(idx + 1);
reset();
}
} else if (state == ST_DECODING_ARRAY_STREAM) {
decodeByte(c, in, idx);
if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
in.skipBytes(1);
}
int idxNoSpaces = idx - 1;
while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
idxNoSpaces--;
}
ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
if (json != null) {
out.add(json);
}
in.readerIndex(idx + 1);
if (c == ']') {
reset();
}
}
} else if (c == '{' || c == '[') {
initDecoding(c);
if (state == ST_DECODING_ARRAY_STREAM) {
in.skipBytes(1);
}
} else if (Character.isWhitespace(c)) {
in.skipBytes(1);
} else {
state = ST_CORRUPTED;
throw new CorruptedFrameException("invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
}
}
if (in.readableBytes() == 0) {
this.idx = 0;
} else {
this.idx = idx;
}
}
@SuppressWarnings("UnusedParameters")
protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
return buffer.slice(index, length).retain();
}
private void decodeByte(byte c, ByteBuf in, int idx) {
if ((c == '{' || c == '[') && !insideString) {
openBraces++;
} else if ((c == '}' || c == ']') && !insideString) {
openBraces--;
} else if (c == '"') {
if (!insideString) {
insideString = true;
} else if (in.getByte(idx - 1) != '\\') {
insideString = false;
}
}
}
private void initDecoding(byte openingBrace) {
openBraces = 1;
if (openingBrace == '[' && streamArrayElements) {
state = ST_DECODING_ARRAY_STREAM;
} else {
state = ST_DECODING_NORMAL;
}
}
private void reset() {
insideString = false;
state = ST_INIT;
openBraces = 0;
}
} | 34.401361 | 132 | 0.528179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.