hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e11e0c928b94103d326df335066cbc8e86f1325 | 1,351 | java | Java | components/camel-spring/src/test/java/org/apache/camel/spring/cloud/LegacyServiceCallConfigurationTest.java | b2kalyan/camel | d225ef928bf3cfaddeb45c075926bffa64f81e84 | [
"Apache-2.0"
] | 2 | 2019-02-22T03:59:18.000Z | 2019-09-04T13:56:30.000Z | components/camel-spring/src/test/java/org/apache/camel/spring/cloud/LegacyServiceCallConfigurationTest.java | b2kalyan/camel | d225ef928bf3cfaddeb45c075926bffa64f81e84 | [
"Apache-2.0"
] | 9 | 2020-12-21T17:08:47.000Z | 2022-02-01T01:08:09.000Z | components/camel-spring/src/test/java/org/apache/camel/spring/cloud/LegacyServiceCallConfigurationTest.java | b2kalyan/camel | d225ef928bf3cfaddeb45c075926bffa64f81e84 | [
"Apache-2.0"
] | 202 | 2020-07-23T14:34:26.000Z | 2022-03-04T18:41:20.000Z | 43.580645 | 123 | 0.771281 | 7,534 | /**
* 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.camel.spring.cloud;
import org.apache.camel.spring.SpringCamelContext;
import org.junit.Test;
public class LegacyServiceCallConfigurationTest extends ServiceCallConfigurationTest {
@Test
public void testServiceDiscoveryConfiguration() {
SpringCamelContext context = createContext("org/apache/camel/spring/cloud/LegacyServiceCallConfigurationTest.xml");
testConfiguration1(context.getServiceCallConfiguration("conf1"));
testConfiguration2(context.getServiceCallConfiguration("conf2"));
}
}
|
3e11e0de01ddbba644a8cb366cfe9987a695cdd6 | 7,922 | java | Java | src/com/hrsst/smarthome/demo/PushDemoReceiver.java | bingo1118/bees_dtsj | c15ffed2ab0055a36588d87b264ad76926a07e2b | [
"Apache-2.0"
] | null | null | null | src/com/hrsst/smarthome/demo/PushDemoReceiver.java | bingo1118/bees_dtsj | c15ffed2ab0055a36588d87b264ad76926a07e2b | [
"Apache-2.0"
] | null | null | null | src/com/hrsst/smarthome/demo/PushDemoReceiver.java | bingo1118/bees_dtsj | c15ffed2ab0055a36588d87b264ad76926a07e2b | [
"Apache-2.0"
] | null | null | null | 41.260417 | 128 | 0.624842 | 7,535 | package com.hrsst.smarthome.demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
import com.hrsst.smarthome.dtsj.R;
import com.hrsst.smarthome.activity.AlarmActivity;
import com.hrsst.smarthome.activity.SystemMessageActivity;
import com.hrsst.smarthome.global.Constants;
import com.hrsst.smarthome.global.MyApp;
import com.hrsst.smarthome.net.SocketUDP;
import com.hrsst.smarthome.order.SendServerOrder;
import com.hrsst.smarthome.order.UnPackServer;
import com.hrsst.smarthome.pojo.Contact;
import com.hrsst.smarthome.pojo.UnPackageFromServer;
import com.hrsst.smarthome.util.SharedPreferencesManager;
import com.igexin.sdk.PushConsts;
public class PushDemoReceiver extends BroadcastReceiver {
/**
* 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
*/
public static StringBuilder payloadData = new StringBuilder();
public static final int NOTIFICATION_ID = 0x53256561;
private Contact mContact;
private SocketUDP mSocketUDPClient;
private byte[] payload;
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
switch (bundle.getInt(PushConsts.CMD_ACTION)) {
case PushConsts.GET_MSG_DATA:
// 获取透传数据
// String appid = bundle.getString("appid");
payload = bundle.getByteArray("payload");
if(payload!=null&&payload.length>8){
int type = payload[0];
if(type==1){//报警@@
regFilter();
if(payload.length>12){
byte[] mac = new byte[12];
for (int i = 0; i < 12; i++) {
mac[i] = payload[i + 2];
}
String macStr = new String(mac).trim();
String userNum = SharedPreferencesManager.getInstance().getData(context, Constants.UserInfo.USER_NUMBER);
mSocketUDPClient = SocketUDP.newInstance(Constants.SeverInfo.SERVER
, Constants.SeverInfo.PORT);
mSocketUDPClient.startAcceptMessage();
byte[] orderSend = SendServerOrder.ifUserOwnCamera(userNum,macStr);
mSocketUDPClient.sendMsg(orderSend);
}
}
if(type==2){//共享设备。。
byte[] receive = new byte[payload.length-1];
for(int i = 0;i<receive.length;i++){
receive[i] = payload[i+1];
}
String ss = new String(receive);
String toUserNum = SharedPreferencesManager.getInstance().getData(context, Constants.UserInfo.USER_NUMBER);
showDownNotification(context,toUserNum,ss);
}
}
break;
case PushConsts.GET_CLIENTID:
String cid = bundle.getString("clientid");
SharedPreferencesManager.getInstance().putData(MyApp.app,
SharedPreferencesManager.SP_FILE_GWELL,
SharedPreferencesManager.CID,
cid);
Intent i = new Intent();
i.setAction("STOP_PUSH_INIT_SERVICE");
context.sendBroadcast(i);
break;
default:
break;
}
}
@SuppressWarnings("deprecation")
private void showDownNotification(Context context,String toUserNum,String ss){
long when = System.currentTimeMillis();
//从系统服务中获得通知管理器
NotificationManager nm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//定义notification
Notification mNotification = new Notification(
R.drawable.notification,
context.getResources().getString(R.string.app_name),
when);
mNotification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_AUTO_CANCEL;
RemoteViews contentView = new RemoteViews(context.getPackageName(),
R.layout.share_notify);
contentView.setImageViewResource(R.id.share_icon,
R.drawable.notification);
// contentView.setTextViewText(R.id.share_text, toUserNum+context.getString(R.string.get_device_share_massage));
// contentView.setTextViewText(R.id.share_text, getfromusername(ss)+"鍙戞潵璁惧鍏变韩娑堟伅");
contentView.setTextViewText(R.id.share_text, context.getString(R.string.get_device_share_massage));
//通知消息与Intent关联
Intent it=new Intent(context,SystemMessageActivity.class);
it.putExtra("toUserNum", toUserNum);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent=PendingIntent.getActivity(context, 100, it, PendingIntent.FLAG_CANCEL_CURRENT);
//具体的通知内容
mNotification.contentView = contentView;
mNotification.contentIntent = contentIntent;
mNotification.defaults = Notification.DEFAULT_SOUND;
//执行通知
nm.notify(NOTIFICATION_ID, mNotification);
}
private String getfromusername(String str) {
String str2="";
if(str != null && !"".equals(str)){
for(int i=0;i<str.length();i++){
if(str.charAt(i)>=48 && str.charAt(i)<=57){
str2+=str.charAt(i);
}
}
}
return str2;
}
private void regFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction("Constants.Action.unIfUserOwnCamera");
MyApp.app.registerReceiver(mReceiver, filter);
}
private BroadcastReceiver mReceiver=new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
//收到广播,是否用户拥有摄像机。。
if(arg1.getAction().equals("Constants.Action.unIfUserOwnCamera")){
byte[] datas = arg1.getExtras().getByteArray("datasByte");
UnPackageFromServer mUnPackageFromServer = UnPackServer.unIfUserOwnCamera(datas);
if(null!=mUnPackageFromServer){
String result = mUnPackageFromServer.result;
if("yes".equals(result)){
mContact = new Contact();
mContact.contactId = mUnPackageFromServer.devMac;
mContact.contactPassword = mUnPackageFromServer.devPwd;
mContact.contactName = mUnPackageFromServer.devName;
String ifWatching = SharedPreferencesManager.getInstance().getData(arg0, Constants.WatchAction.IF_WATCH);
String cameraId = SharedPreferencesManager.getInstance().getData(arg0, Constants.WatchAction.CAMERA_ID);
if(null!=ifWatching&&ifWatching.equals("yes")&&null!=cameraId&&cameraId.equals(mContact.contactId)){
}else{
Intent i =new Intent(arg0,AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("payload", payload);
i.putExtra("mContact", mContact);
arg0.startActivity(i);
}
}else{
Intent i =new Intent(arg0,AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("payload", payload);
i.putExtra("mContact", mContact);
arg0.startActivity(i);
}
}else{
Intent i =new Intent(arg0,AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("payload", payload);
i.putExtra("mContact", mContact);
arg0.startActivity(i);
}
arg0.unregisterReceiver(mReceiver);
}
}
};
}
|
3e11e13c874614e6a814dbe09e0afd72a928b043 | 807 | java | Java | gmall-coupon/src/main/java/com/gxyan/gmall/coupon/entity/HomeSubjectEntity.java | Hitout/gmall | 093d19b6f78fd1d6459a8189a12bf405dd19e2b5 | [
"Apache-2.0"
] | null | null | null | gmall-coupon/src/main/java/com/gxyan/gmall/coupon/entity/HomeSubjectEntity.java | Hitout/gmall | 093d19b6f78fd1d6459a8189a12bf405dd19e2b5 | [
"Apache-2.0"
] | 4 | 2020-11-29T16:09:39.000Z | 2021-09-20T21:01:20.000Z | gmall-coupon/src/main/java/com/gxyan/gmall/coupon/entity/HomeSubjectEntity.java | Hitout/gmall | 093d19b6f78fd1d6459a8189a12bf405dd19e2b5 | [
"Apache-2.0"
] | null | null | null | 14.410714 | 56 | 0.669145 | 7,536 | package com.gxyan.gmall.coupon.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 首页专题表【jd首页下面很多专题,每个专题链接新的页面,展示专题商品信息】
*
* @author gxyan
* @date 2020-07-30 21:22:55
*/
@Data
@TableName("sms_home_subject")
public class HomeSubjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 专题名字
*/
private String name;
/**
* 专题标题
*/
private String title;
/**
* 专题副标题
*/
private String subTitle;
/**
* 显示状态
*/
private Integer status;
/**
* 详情连接
*/
private String url;
/**
* 排序
*/
private Integer sort;
/**
* 专题图片地址
*/
private String img;
}
|
3e11e18043d54a077be8f61d39d52848a1d84861 | 2,140 | java | Java | rebot-telegram-api/rebot-telegram-api/src/main/java/xyz/rebasing/rebot/telegram/api/message/Processor.java | spolti/rebot | 90e8c3b8ab1db1223feda5d0452b4ef298058c51 | [
"MIT"
] | 18 | 2019-04-05T23:56:47.000Z | 2021-01-04T23:58:12.000Z | rebot-telegram-api/rebot-telegram-api/src/main/java/xyz/rebasing/rebot/telegram/api/message/Processor.java | spolti/rebot | 90e8c3b8ab1db1223feda5d0452b4ef298058c51 | [
"MIT"
] | 14 | 2021-03-05T02:42:41.000Z | 2021-12-26T05:29:14.000Z | rebot-telegram-api/rebot-telegram-api/src/main/java/xyz/rebasing/rebot/telegram/api/message/Processor.java | rebase-it/rebot | 90e8c3b8ab1db1223feda5d0452b4ef298058c51 | [
"MIT"
] | 3 | 2018-03-02T22:06:35.000Z | 2021-02-06T10:36:01.000Z | 41.153846 | 108 | 0.728037 | 7,537 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Rebasing.xyz ReBot
*
* 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 xyz.rebasing.rebot.telegram.api.message;
import xyz.rebasing.rebot.api.domain.MessageUpdate;
public interface Processor {
/**
* Filter all the updates and process it.
* If any plugin or service can process the update, it will be processed and a reply will be sent by the
* plugin or service that processed the update.
* @param messageUpdate Message to be processed
*/
void process(MessageUpdate messageUpdate);
/**
* Process the commands, anything started with / will be considered a command
* @param messageUpdate Message to be processed
*/
void commandProcessor(MessageUpdate messageUpdate);
/**
* Process everything, usually it is filtered by the plugins, i.e karma plugin.
* If the message processed matches a plugin condition, it will be processed.
* @param messageUpdate Message to be processed
*/
void nonCommandProcessor(MessageUpdate messageUpdate);
}
|
3e11e18b71264a2c6f87345ea8db8ce7ad71c2b4 | 1,248 | java | Java | app/src/main/java/com/example/stefan/piatra_hartie_foarfece/Rezultat.java | Alistar02/Ica | 4b332564569e825c82874fe17111dd6aad4f8ba0 | [
"MIT"
] | 2 | 2019-02-06T19:04:25.000Z | 2019-02-07T16:01:36.000Z | app/src/main/java/com/example/stefan/piatra_hartie_foarfece/Rezultat.java | Alistar02/Ica | 4b332564569e825c82874fe17111dd6aad4f8ba0 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/stefan/piatra_hartie_foarfece/Rezultat.java | Alistar02/Ica | 4b332564569e825c82874fe17111dd6aad4f8ba0 | [
"MIT"
] | 1 | 2019-02-07T15:43:10.000Z | 2019-02-07T15:43:10.000Z | 33.72973 | 91 | 0.746795 | 7,538 | package com.example.stefan.piatra_hartie_foarfece;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class Rezultat extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultat);
ImageView jucator_output = (ImageView)findViewById(R.id.jucator_output) ;
ImageView adversar_output = (ImageView)findViewById(R.id.adversar_output);
Intent second_intent_text = getIntent();
TextView text_output;
String mesaj = second_intent_text.getStringExtra("raspuns");
text_output = (TextView)findViewById(R.id.output);
text_output.setText(mesaj);
Bundle extras_jucator = getIntent().getExtras();
Bitmap imagineJucator = (Bitmap) extras_jucator.getParcelable("imagine_jucator");
Bitmap imagineAdversar = (Bitmap) extras_jucator.getParcelable("imagine_adversar");
jucator_output.setImageBitmap(imagineJucator);
adversar_output.setImageBitmap(imagineAdversar);
}
}
|
3e11e274c14a35c9d45d12005031b161f072331a | 7,399 | java | Java | SVIEngine/src/com/github/sviengine/performance/NoneAniPropertyActivity.java | Samsung/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | 27 | 2015-04-24T07:14:55.000Z | 2020-01-24T16:16:37.000Z | SVIEngine/src/com/github/sviengine/performance/NoneAniPropertyActivity.java | teeraporn39/SVIEngine | 87e379a1e1906025660e9de8da8ff908faf0a976 | [
"Apache-2.0"
] | null | null | null | SVIEngine/src/com/github/sviengine/performance/NoneAniPropertyActivity.java | teeraporn39/SVIEngine | 87e379a1e1906025660e9de8da8ff908faf0a976 | [
"Apache-2.0"
] | 15 | 2015-12-08T14:46:19.000Z | 2020-01-21T19:26:41.000Z | 26.237589 | 135 | 0.72226 | 7,539 | package com.github.sviengine.performance;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
public class NoneAniPropertyActivity extends TestCaseBaseActivity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout rootLayout = new LinearLayout(this);
rootLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
rootLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout subLayout = new LinearLayout(this);
subLayout.setGravity(Gravity.BOTTOM);
subLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
prevText = new TextView(this);
currentText = new TextView(this);
nextText = new TextView(this);
mTextViewLog = new TextView(this);
prevText.setText(menuArray[0]);
currentText.setText(menuArray[1]);
nextText.setText(menuArray[2]);
mTextViewLog.setText("");
prevText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
currentText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
nextText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
mTextViewLog.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f));
String sideColor = "#000000";
prevText.setTextColor(Color.parseColor(sideColor));
nextText.setTextColor(Color.parseColor(sideColor));
mTextViewLog.setTextColor(Color.parseColor(sideColor));
prevText.setTextSize(sideTextSize);
nextText.setTextSize(sideTextSize);
currentText.setTextSize(centerTextSize);
mTextViewLog.setTextSize(sideTextSize);
String centerColor = "#ff0000";
currentText.setTextColor(Color.parseColor(centerColor));
prevText.setGravity(Gravity.BOTTOM|Gravity.LEFT);
nextText.setGravity(Gravity.BOTTOM|Gravity.RIGHT);
currentText.setGravity(Gravity.BOTTOM|Gravity.CENTER);
mTextViewLog.setGravity(Gravity.TOP|Gravity.RIGHT);
prevText.setId(0);
nextText.setId(1);
currentText.setId(2);
prevText.setOnClickListener(this);
nextText.setOnClickListener(this);
currentText.setOnClickListener(this);
subLayout.addView(prevText);
subLayout.addView(currentText);
subLayout.addView(nextText);
rootLayout.addView(mTextViewLog);
rootLayout.addView(subLayout);
addContentView(rootLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT) );
propertyText = new TextView(this);
propertyText.setText("Explicit");
propertyText.setTextSize(60.0f);
addContentView(propertyText, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
mCheckBoxList = new CheckBox[menuArray.length-2];
((NoneAniPropertyWindow)mWindow).setTextViewLog(mTextViewLog);
}
@Override
public void onClick(View v) {
int temp = (int)v.getId();
originWindow.removeall();
switch(temp){
case 0:
if(mIndex>0){
nextText.setText(menuArray[mIndex+1]);
currentText.setText(menuArray[mIndex]);
prevText.setText(menuArray[mIndex-1]);
mIndex--;
}
break;
case 1:
if(mIndex<menuArray.length-3){
mIndex++;
prevText.setText(menuArray[mIndex]);
currentText.setText(menuArray[mIndex+1]);
nextText.setText(menuArray[mIndex+2]);
}
break;
case 2:
Log.i("test",menuArray[mIndex+1]+"");
break;
default :
Log.i("test",menuArray[mIndex+1]+"");
}
originWindow.mProperty = mIndex;
originWindow.buildSubSlide();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onDestroy() {
originWindow.release();
originWindow = null;
super.onDestroy();
}
@Override
boolean createWindow() {
mWindow = new NoneAniPropertyWindow(this);
originWindow = (NoneAniPropertyWindow)mWindow;
if(mWindow == null)
return false;
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, COMBINATION, 0, "combination");
return true;
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case COMBINATION:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for(int j=0; j<mCheckBoxList.length; j++) {
mCheckBoxList[j] = new CheckBox(this);
mCheckBoxList[j].setText(menuArray[j+1]);
linearLayout.addView(mCheckBoxList[j]);
}
return new AlertDialog.Builder(this)
.setTitle("Non-animatable property list")
.setView(linearLayout)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
boolean[] checkedList = new boolean[menuArray.length-2];
for(int i=0; i<checkedList.length; i++) {
checkedList[i] = mCheckBoxList[i].isChecked();
}
((NoneAniPropertyWindow)mWindow).setCheckedList(checkedList);
((NoneAniPropertyWindow)mWindow).setNonAnimatableProperties();
}
})
.create();
default:
return super.onCreateDialog(id);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
// Handle item selection
switch (item.getItemId()) {
case COMBINATION:
showDialog(COMBINATION);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected TextView prevText;
protected TextView currentText;
protected TextView nextText;
protected TextView propertyText;
protected TextView mTextViewLog;
protected int mIndex =0;
final protected float sideTextSize = 30.0f;
final protected float centerTextSize = 50.0f;
protected String[] menuArray = {
"==",
"CLIP_SUB_SLIDE",
"ZORDER_TYPE",
"ORTHOGONAL",
"HOLD_OPACITY",
"HOLD_SCALE",
"BLEND_TYPE",
"LIGHT_TYPE",
"IMAGESCALETYPE",
"=="
};
NoneAniPropertyWindow originWindow = null;
protected static final int COMBINATION = 0;
protected CheckBox[] mCheckBoxList;
}
|
3e11e28a7c259dd8b9518db9585e8a075650c58d | 1,260 | java | Java | spring-tbf/src/main/java/springmvctestdemo/MyTomcatServer.java | tang-bf/spring-framework-4.3.x | 68b45d1f7768b9a827908c3b7a63b80c2b2867fa | [
"Apache-2.0"
] | null | null | null | spring-tbf/src/main/java/springmvctestdemo/MyTomcatServer.java | tang-bf/spring-framework-4.3.x | 68b45d1f7768b9a827908c3b7a63b80c2b2867fa | [
"Apache-2.0"
] | null | null | null | spring-tbf/src/main/java/springmvctestdemo/MyTomcatServer.java | tang-bf/spring-framework-4.3.x | 68b45d1f7768b9a827908c3b7a63b80c2b2867fa | [
"Apache-2.0"
] | null | null | null | 27.391304 | 124 | 0.634127 | 7,540 | package springmvctestdemo;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
//import org.springframework.context.event.EventListener;
/**
* @ProjectName: tbhStudy
* @Package: springmvctestdemo.test
* @ClassName: MyTomcatServer
* @Description:
* @Author: tbf
* @CreateDate: 2020-06-27 23:11
* @UpdateUser: Administrator
* @UpdateDate: 2020-06-27 23:11
* @UpdateRemark:
* @Version: 1.0
*/
public class MyTomcatServer {
public static void main(String[] args) {
//java.util.EventObject
//EventListener
//EventListener
Tomcat tomcat = new Tomcat();
tomcat.setPort(9898);
tomcat.addWebapp("/","d:\\tomc\\");//
// tomcat.addContext("/","") ;不会调用mydispatcherservlet的onstartup方法
// 只会去初始化一个context的资源目录 并不会加载web的声明周期
/**解决办法
* Context context = tomcat.addContext("/", "");
* context.addLifecycleListener((LifecycleListener) Class.forName(tomcat.getHost().getConfigClass()).newInstance());
*/
try {
tomcat.start();
} catch (LifecycleException ex) {
ex.printStackTrace();
}
//tomcat就是一个socket连接.所以要使其阻塞
tomcat.getServer().await();
}
}
|
3e11e298c82c06a63632d25187fee3087e821ff0 | 1,518 | java | Java | fundraising/src/main/java/com/gdut/fundraising/service/UserService.java | 46zhang/blockchain | ef3065e44b437c0bad9c4ac9a0a6f17d5611a0ca | [
"MIT"
] | 4 | 2021-02-23T15:14:19.000Z | 2021-03-29T08:01:05.000Z | fundraising/src/main/java/com/gdut/fundraising/service/UserService.java | 46zhang/blockchain | ef3065e44b437c0bad9c4ac9a0a6f17d5611a0ca | [
"MIT"
] | null | null | null | fundraising/src/main/java/com/gdut/fundraising/service/UserService.java | 46zhang/blockchain | ef3065e44b437c0bad9c4ac9a0a6f17d5611a0ca | [
"MIT"
] | null | null | null | 32.297872 | 98 | 0.8083 | 7,541 | package com.gdut.fundraising.service;
import com.gdut.fundraising.dto.*;
import com.gdut.fundraising.entities.FundFlowEntity;
import com.gdut.fundraising.entities.ProjectTblEntity;
import com.gdut.fundraising.entities.UserTblEntity;
import com.gdut.fundraising.exception.BaseException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
public interface UserService {
Map<String, Object> register(UserTblEntity userTblEntity);
LoginResult login(UserTblEntity userTblEntity) throws BaseException;
ProjectTblEntity launch(String token, ProjectTblEntity projectTblEntity) throws BaseException;
Map uploadPhoto(String token, MultipartFile file) throws BaseException;
Map readProjectList(int pageIndex , int pageSize);
ProjectTblEntity readProjectDetail(String projectId);
List<NodeQueryResult> readNodeList();
List<UserTblEntity> readUserList();
@Transactional
Map contribution(String token, String projectId, int money) throws BaseException;
List<ReadDonationResult> readDonation(String projectId);
List<ReadExpenditureResult> readExpenditureResult(String projectId);
List<FundFlowEntity> getUserContribution(String token, String userId);
List<FundFlowEntity> getUserOneProjectFund(String token, String projectId, String userId);
FundFlowGraphResult getUserOneProjectFundGraph(String token, String projectId, String userId);
}
|
3e11e2d4c33d998cf85b35163f525e404e9f3e74 | 227 | java | Java | src/main/java/dk/in2isoft/onlineobjects/modules/importing/ImportTransport.java | Humanise/onlineobjects | 18c9e7bcbac50eecdf1efba1a1010ba8982852c4 | [
"Unlicense"
] | 1 | 2018-03-16T17:11:50.000Z | 2018-03-16T17:11:50.000Z | src/main/java/dk/in2isoft/onlineobjects/modules/importing/ImportTransport.java | Humanise/onlineobjects | 18c9e7bcbac50eecdf1efba1a1010ba8982852c4 | [
"Unlicense"
] | 21 | 2018-03-09T22:49:20.000Z | 2022-02-16T00:55:18.000Z | src/main/java/dk/in2isoft/onlineobjects/modules/importing/ImportTransport.java | Humanise/onlineobjects | 18c9e7bcbac50eecdf1efba1a1010ba8982852c4 | [
"Unlicense"
] | null | null | null | 17.461538 | 72 | 0.788546 | 7,542 | package dk.in2isoft.onlineobjects.modules.importing;
import dk.in2isoft.onlineobjects.modules.importing.ImportSession.Status;
public interface ImportTransport {
void start();
Status getStatus();
Object getResult();
}
|
3e11e2ee80d5f2f8bf8d3102e516d26296ffead4 | 1,111 | java | Java | integration/client/src/main/java/org/overlord/rtgov/client/ActivityValidator.java | ivanthelad/rtgov | 1ee5350b624941c0d5b8972cad0def495b63c7b3 | [
"Apache-2.0"
] | null | null | null | integration/client/src/main/java/org/overlord/rtgov/client/ActivityValidator.java | ivanthelad/rtgov | 1ee5350b624941c0d5b8972cad0def495b63c7b3 | [
"Apache-2.0"
] | null | null | null | integration/client/src/main/java/org/overlord/rtgov/client/ActivityValidator.java | ivanthelad/rtgov | 1ee5350b624941c0d5b8972cad0def495b63c7b3 | [
"Apache-2.0"
] | null | null | null | 30.861111 | 75 | 0.732673 | 7,543 | /*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* 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.overlord.rtgov.client;
import org.overlord.rtgov.activity.model.ActivityType;
/**
* This interface represents the capability for validating
* activity information from an application.
*
*/
public interface ActivityValidator {
/**
* This method validates the activity event.
*
* @param actType The activity type
* @throws Exception Failed to validate activity
*/
public void validate(ActivityType actType) throws Exception;
}
|
3e11e3d59171da86909d42616d726ddcd4f951ac | 5,334 | java | Java | src/main/java/jaist/ac/jp/NodeFinder/echonet/object/utils/eDeviceType.java | Cupham/NodeFinder | db9f97692f489dc36be31ef6a408c2256a67f867 | [
"Apache-2.0"
] | null | null | null | src/main/java/jaist/ac/jp/NodeFinder/echonet/object/utils/eDeviceType.java | Cupham/NodeFinder | db9f97692f489dc36be31ef6a408c2256a67f867 | [
"Apache-2.0"
] | null | null | null | src/main/java/jaist/ac/jp/NodeFinder/echonet/object/utils/eDeviceType.java | Cupham/NodeFinder | db9f97692f489dc36be31ef6a408c2256a67f867 | [
"Apache-2.0"
] | null | null | null | 34.192308 | 80 | 0.671541 | 7,544 | /*******************************************************************************
* Copyright 2019 Cu Pham
*
* 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 jaist.ac.jp.NodeFinder.echonet.object.utils;
public enum eDeviceType {
GasLeakSensor(0x00 << 8 | 0x01),
CrimePreventionSensor(0x00 << 8 | 0x02),
EmergencyButton(0x00 << 8 | 0x03),
FirstAidSensor(0x00 << 8 | 0x04),
EarthquakeSensor(0x00 << 8 | 0x05),
ElectricLeakSensor(0x00 << 8 | 0x06),
HumanDetectionSensor(0x00 << 8 | 0x07),
VisitorDetectionSensor(0x00 << 8 | 0x08),
CallSensor(0x00 << 8 | 0x09),
CondensationSensor(0x00 << 8 | 0x0A),
AirPollutionSensor(0x00 << 8 | 0x0B),
OxygenSensor(0x00 << 8 | 0x0C),
IlluminanceSensor(0x00 << 8 | 0x0D),
SoundSensor(0x00 << 8 | 0x0E),
MailingSensor(0x00 << 8 | 0x0F),
WeightSensor(0x00 << 8 | 0x10),
TemperatureSensor(0x00 << 8 | 0x11),
HumiditySensor(0x00 << 8 | 0x12),
RainSensor(0x00 << 8 | 0x13),
WaterLevelSensor(0x00 << 8 | 0x14),
BathWaterLevelSensor(0x00 << 8 | 0x15),
BathHeatingStatusSensor(0x00 << 8 | 0x16),
WaterLeakSensor(0x00 << 8 | 0x17),
WaterOverFlowSensor(0x00 << 8 | 0x18),
FireSensor(0x00 << 8 | 0x19),
CigaretteSmokeSensor(0x00 << 8 | 0x1A),
CO2Sensor(0x00 << 8 | 0x1B),
GasSensor(0x00 << 8 | 0x1C),
VOCSensor(0x00 << 8 | 0x1D),
DifferentialPressureSensor(0x00 << 8 | 0x1E),
AirSpeedSensor(0x00 << 8 | 0x1F),
OdorSensor(0x00 << 8 | 0x20),
FlameSensor(0x00 << 8 | 0x21),
ElectricEnergySensor(0x00 << 8 | 0x22),
CurrentValueSensor(0x00 << 8 | 0x23),
WaterFlowRateSensor(0x00 << 8 | 0x25),
MicroMotionSensor(0x00 << 8 | 0x26),
PassageSensor(0x00 << 8 | 0x27),
BedPresenceSensor(0x00 << 8 | 0x28),
OpenCloseSensor(0x00 << 8 | 0x29),
ActivityMountSensor(0x00 << 8 | 0x2A),
HumanBodyLocationSensor(0x00 << 8 | 0x2B),
SnowSensor(0x00 << 8 | 0x2C),
AirPressureSensor(0x00 << 8 | 0x2D),
HomeAirconditioner(0x01 << 8 | 0x30),
VentilationFan(0x01 << 8 | 0x33),
AirconditionerVentilationFan(0x01 << 8 | 0x34),
AirCleaner(0x01 << 8 | 0x35),
Humidifier(0x01 << 8 | 0x39),
ElectricHeater(0x01 << 8 | 0x42),
FanHeater(0x01 << 8 | 0x43),
ElectricStorageHeater(0x01 << 8 | 0x55),
CommercialAirconditionerIndoorUnit(0x01 << 8 | 0x56),
CommercialAirconditionerOutdoorUnit(0x01 << 8 | 0x57),
GasHeatCommercialAirconditionerIndoorUnit(0x01 << 8 | 0x58),
GasHeatCommercialAirconditionerOutdoorUnit(0x01 << 8 | 0x59),
ElectricBlind(0x02 << 8 | 0x60),
ElectricShutter(0x02 << 8 | 0x61),
ElectricCurtain(0x02 << 8 | 0x62),
ElectricRainSlidingDoor(0x02 << 8 | 0x63),
ElectricGate(0x02 << 8 | 0x64),
ElectricWindow(0x02 << 8 | 0x65),
ElectricEntranceDoor(0x02 << 8 | 0x66),
GardenSprinkler(0x02 << 8 | 0x67),
ElectricWaterHeater(0x02 << 8 | 0x6B),
BidetEquippedToilet(0x02 << 8 | 0x6E),
ElectricLock(0x02 << 8 | 0x6F),
InstantaneousWaterHeater(0x02 << 8 | 0x72),
BathRoomDryer(0x02 << 8 | 0x73),
HomeSolarPowerGeneration(0x02 << 8 | 0x79),
ColdHotWaterHeatSourceEquipment(0x02 << 8 | 0x7A),
FloorHeater(0x02 << 8 | 0x7B),
FuelCell(0x02 << 8 | 0x7C),
StorageBattery(0x02 << 8 | 0x7D),
ElectricVehicleChargerDischarger(0x02 << 8 | 0x7E),
EngineCogeneration(0x02 << 8 | 0x7F),
ElectricEnergyMeter(0x02 << 8 | 0x80),
WaterFlowMeter(0x02 << 8 | 0x81),
GasMeter(0x02 << 8 | 0x82),
LPGasMeter(0x02 << 8 | 0x83),
DistributionPanelMetering(0x02 << 8 | 0x87),
LowVoltageSmartElectricEnergyMeter(0x02 << 8 | 0x88),
SmartGasMeter(0x02 << 8 | 0x89),
HighVoltageSmartElectricEnergyMeter(0x02 << 8 | 0x8A),
KeroseneMeter(0x02 << 8 | 0x8B),
SmartKeroseneMeter(0x02 << 8 | 0x8C),
GeneralLight(0x02 << 8 | 0x90),
SingleFunctionLighting(0x02 << 8 | 0x91),
LightingForSolidLightEmittingSource(0x02 << 8 | 0x92),
Buzzer(0x02 << 8 | 0xA0),
ElectricVehicleCharger(0x02 << 8 | 0xA1),
HouseholdSmallWindTurbinePowerGeneration(0x02 << 8 | 0xA2),
ExtendedLightingSystem(0x02 << 8 | 0xA4),
MultipleInputPCS(0x02 << 8 | 0xA5),
HotWaterPot(0x03 << 8 | 0xB2),
Refrigerator(0x03 << 8 | 0xB7),
MicrowaveOven(0x03 << 8 | 0xB8),
CookingHeater(0x03 << 8 | 0xB9),
RiceCooker(0x03 << 8 | 0xBB),
WashingMachine(0x03 << 8 | 0xC5),
ClothesDryer(0x03 << 8 | 0xC6),
CommercialShowcase(0x03 << 8 | 0xCE),
WasherDryer(0x03 << 8 | 0xD3),
CommercialShowcaseOutdoorUnit(0x03 << 8 | 0xD4),
WeighingMachine(0x04 <<8 |0x01),
Switch(0x05 <<8 | 0xFD),
Controller(0x05 <<8 | 0xFF),
DREventController(0x05 <<8 | 0xFB),
ParallelProcessingCombinationTypePowerControl(0x05 <<8 | 0xFA),
Display(0x06 << 8 | 0x01),
Television(0x06 << 8 | 0x02),
Audio(0x06 << 8 | 0x03),
NetworkCamera(0x06 << 8 | 0x04),
Profile(0x0e << 8 | 0xf0),
SuperObject(0xffff);
private int code;
private eDeviceType(int code) {
this.code = code;
}
public byte code() {
return (byte) code;
}
}
|
3e11e591a68ed690bf6ffbfc5c34704ebbfa3e86 | 308 | java | Java | my-bots/ai-core/src/main/java/avdw/java/entelect/core/state/GameDetails.java | avanderw/alysm | c1b88fc6daacca5c7f1097daa49b31ae5e64f044 | [
"MIT"
] | null | null | null | my-bots/ai-core/src/main/java/avdw/java/entelect/core/state/GameDetails.java | avanderw/alysm | c1b88fc6daacca5c7f1097daa49b31ae5e64f044 | [
"MIT"
] | 2 | 2018-05-15T11:45:27.000Z | 2018-05-15T20:34:08.000Z | my-bots/ai-core/src/main/java/avdw/java/entelect/core/state/GameDetails.java | avanderw/alysm | c1b88fc6daacca5c7f1097daa49b31ae5e64f044 | [
"MIT"
] | 1 | 2018-05-15T07:28:57.000Z | 2018-05-15T07:28:57.000Z | 22 | 57 | 0.75974 | 7,545 | package avdw.java.entelect.core.state;
import java.util.HashMap;
public class GameDetails {
public int round;
public int mapWidth;
public int mapHeight;
public HashMap<BuildingType, Integer> buildingPrices;
public int roundIncomeEnergy;
public IronCurtainStats ironCurtainStats;
}
|
3e11e5e14e5e2361a8609bdb424db265713e31de | 9,340 | java | Java | src/main/java/com/example/demo/config/DatabaseSeederRunner.java | eh3rrera/spring-data-mongodb-example | 8a3074bbf22e5ebd73f45843918982574d49def7 | [
"MIT"
] | null | null | null | src/main/java/com/example/demo/config/DatabaseSeederRunner.java | eh3rrera/spring-data-mongodb-example | 8a3074bbf22e5ebd73f45843918982574d49def7 | [
"MIT"
] | 1 | 2021-09-26T01:00:15.000Z | 2021-09-26T01:00:15.000Z | src/main/java/com/example/demo/config/DatabaseSeederRunner.java | AlexRogalskiy/spring-data-mongodb-example | 8a3074bbf22e5ebd73f45843918982574d49def7 | [
"MIT"
] | 1 | 2021-09-26T01:00:08.000Z | 2021-09-26T01:00:08.000Z | 59.871795 | 629 | 0.699251 | 7,546 | package com.example.demo.config;
import com.example.demo.domain.DifficultyLevel;
import com.example.demo.domain.Ingredient;
import com.example.demo.domain.Recipe;
import com.example.demo.util.Counter;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Component
@Order(1)
public class DatabaseSeederRunner implements CommandLineRunner {
private MongoTemplate mongoTemplate;
private MongoConverter mongoConverter;
public DatabaseSeederRunner(MongoTemplate mongoTemplate, MongoConverter mongoConverter) {
this.mongoTemplate = mongoTemplate;
this.mongoConverter = mongoConverter;
}
@Override
public void run(String... args) {
createIndexes();
loadData();
}
private void createIndexes() {
MappingContext mappingContext = this.mongoConverter.getMappingContext();
if (mappingContext instanceof MongoMappingContext) {
MongoMappingContext mongoMappingContext = (MongoMappingContext) mappingContext;
for (BasicMongoPersistentEntity<?> persistentEntity : mongoMappingContext.getPersistentEntities()) {
Class clazz = persistentEntity.getType();
if (clazz.isAnnotationPresent(Document.class)) {
var resolver = new MongoPersistentEntityIndexResolver(mongoMappingContext);
var indexOps = this.mongoTemplate.indexOps(clazz);
resolver.resolveIndexFor(clazz).forEach(indexOps::ensureIndex);
}
}
}
}
private void loadData() {
// Recipe 1 - https://www.bbcgoodfood.com/recipes/summer-winter-chicken
List<Ingredient> ingredients1 = new ArrayList<>();
ingredients1.add(new Ingredient(1.0, "tbsp", "olive oil"));
ingredients1.add(new Ingredient(4.0, "", "boneless skinless chicken breasts"));
ingredients1.add(new Ingredient(200.0, "grams", "pack cherry tomatoes"));
ingredients1.add(new Ingredient(3.0, "tbsp", "pesto"));
ingredients1.add(new Ingredient(3.0, "tbsp", "crème fraîche "));
ingredients1.add(new Ingredient(1.0, "", "fresh basil Basil if you have it"));
Recipe recipe1 = new Recipe();
recipe1.setDifficultyLevel(DifficultyLevel.EASY);
recipe1.setInstructions("Heat the oil in a frying pan, preferably non-stick. Add the chicken and fry without moving it until it takes on a bit of colour. Turn the chicken and cook on the other side. Continue cooking for 12-15 mins until the chicken is cooked through. Season all over with a little salt and pepper. Halve the tomatoes and throw them into the pan, stirring them around for a couple of minutes until they start to soften. Reduce the heat and stir in the pesto and crème fraîche until it makes a sauce. Scatter with a few basil leaves if you have them, then serve with rice and salad or mash and broccoli.");
recipe1.setPreparationTimeMin(10);
recipe1.setRecipeId(Counter.getValue());
recipe1.setIngredients(ingredients1);
recipe1.setTitle("Seasoned Chicken");
// Recipe 2 - https://www.bbcgoodfood.com/recipes/super-quick-fish-curry
List<Ingredient> ingredients2 = new ArrayList<>();
ingredients2.add(new Ingredient(1.0, "tbsp", "vegetable oil"));
ingredients2.add(new Ingredient(1.0, "", "large onion, chopped"));
ingredients2.add(new Ingredient(1.0, "", "garlic clove, chopped"));
ingredients2.add(new Ingredient(1.0, "tbsp", "curry paste"));
ingredients2.add(new Ingredient(400.0, "grams", "can tomato"));
ingredients2.add(new Ingredient(200.0, "ml", "vegetable stock"));
ingredients2.add(new Ingredient(0.0, "", "white fish fillets, skinned and cut into big chunks"));
ingredients2.add(new Ingredient(0.0, "", "rice or naan bread"));
Recipe recipe2 = new Recipe();
recipe2.setDifficultyLevel(DifficultyLevel.NORMAL);
recipe2.setInstructions("Heat the oil in a deep pan and gently fry the onion and garlic for about 5 mins until soft. Add the curry paste and stir-fry for 1-2 mins, then tip in the tomatoes and stock. Bring to a simmer, then add the fish. Gently cook for 4-5 mins until the fish flakes easily. Serve immediately with rice.");
recipe2.setPreparationTimeMin(7);
recipe2.setRecipeId(Counter.getValue());
recipe2.setIngredients(ingredients2);
recipe2.setTitle("Fish Curry");
// Recipe 3 - https://www.bbcgoodfood.com/recipes/asparagus-meatball-orzo
List<Ingredient> ingredients3 = new ArrayList<>();
ingredients3.add(new Ingredient(12.0, "", "pork meatballs"));
ingredients3.add(new Ingredient(500.0, "grams", "orzo pasta"));
ingredients3.add(new Ingredient(0.0, "", "asparagus sliced in half lengthways"));
ingredients3.add(new Ingredient(200.0, "grams", "tub crème fraîche"));
Recipe recipe3 = new Recipe();
recipe3.setDifficultyLevel(DifficultyLevel.HARD);
recipe3.setInstructions("Heat oven to 180C/160C fan/gas 4. Put the meatballs on a tray lined with foil, season and cook for 20 mins until cooked through. Meanwhile, bring a pan of salted water to the boil, add the orzo and cook for 4 mins, then add the asparagus and simmer for 4 mins more. Drain, then tip back into the pan along with the meatballs and crème fraîche, mix and season well.");
recipe3.setPreparationTimeMin(25);
recipe3.setRecipeId(Counter.getValue());
recipe3.setIngredients(ingredients3);
recipe3.setTitle("Asparagus and meatball orzo");
// Recipe 4 - https://www.bbcgoodfood.com/recipes/easy-teriyaki-chicken
List<Ingredient> ingredients4 = new ArrayList<>();
ingredients4.add(new Ingredient(2.0, "tbsp", "toasted sesame oil"));
ingredients4.add(new Ingredient(6.0, "", "skinless and boneless chicken thighs, sliced"));
ingredients4.add(new Ingredient(2.0, "", "large garlic cloves, crushed"));
ingredients4.add(new Ingredient(1.0, "", "thumb-sized piece ginger, grated"));
ingredients4.add(new Ingredient(50.0, "grams", "runny honey"));
ingredients4.add(new Ingredient(30.0, "ml", "light soy sauce"));
ingredients4.add(new Ingredient(1.0, "tbsp", "rice wine vinegar"));
ingredients4.add(new Ingredient(1.0, "tbsp", "sesame seeds, to serve"));
ingredients4.add(new Ingredient(4.0, "", "spring onions, shredded, to serve"));
ingredients4.add(new Ingredient(0.0, "", "sticky rice, to serve"));
ingredients4.add(new Ingredient(0.0, "", "steamed bok choi or spring greens, to serve"));
Recipe recipe4 = new Recipe();
recipe4.setDifficultyLevel(DifficultyLevel.NORMAL);
recipe4.setInstructions("Heat the oil in a non-stick pan over a medium heat. Add the chicken and fry for 7 mins, or until golden. Add the garlic and ginger and fry for 2 mins. Stir in the honey, soy sauce, vinegar and 100ml water. Bring to the boil and cook for 2 - 5 mins over a medium heat until the chicken is sticky and coated in a thick sauce. Scatter over the spring onions and sesame seeds, then serve the chicken with the rice and steamed veg.");
recipe4.setPreparationTimeMin(15);
recipe4.setRecipeId(Counter.getValue());
recipe4.setIngredients(ingredients4);
recipe4.setTitle("Teriyaki chicken");
// Recipe 5 - https://www.bbcgoodfood.com/recipes/butter-bean-chorizo-stew
List<Ingredient> ingredients5 = new ArrayList<>();
ingredients5.add(new Ingredient(200.0, "grams", "chorizo"));
ingredients5.add(new Ingredient(800.0, "grams", "chopped tomatoes"));
ingredients5.add(new Ingredient(800.0, "grams", "drained butter beans"));
ingredients5.add(new Ingredient(1.0, "tub", "fresh pesto"));
Recipe recipe5 = new Recipe();
recipe5.setDifficultyLevel(DifficultyLevel.EASY);
recipe5.setInstructions("Slice the chorizo and tip into a large saucepan over a medium heat. Fry gently for 5 mins or until starting to turn dark brown. Add the tomatoes and butter beans, bring to the boil, then simmer for 10 mins. Swirl through the pesto, season lightly and ladle into four bowls.");
recipe5.setPreparationTimeMin(17);
recipe5.setRecipeId(Counter.getValue());
recipe5.setIngredients(ingredients5);
recipe5.setTitle("Butter bean and chorizo stew");
List<Recipe> flights = Arrays.asList(
recipe1,
recipe2,
recipe3,
recipe4,
recipe5
);
this.mongoTemplate.insertAll(flights);
}
}
|
3e11e61626a9b97c59eb32fd4568b74e9fc1e2cb | 3,605 | java | Java | guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java | maidh91/guava-libraries.jdk5backport | 2be6eaab8c09eaa54debe3a6622d2ce68b0768d0 | [
"Apache-2.0"
] | null | null | null | guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java | maidh91/guava-libraries.jdk5backport | 2be6eaab8c09eaa54debe3a6622d2ce68b0768d0 | [
"Apache-2.0"
] | null | null | null | guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java | maidh91/guava-libraries.jdk5backport | 2be6eaab8c09eaa54debe3a6622d2ce68b0768d0 | [
"Apache-2.0"
] | null | null | null | 28.385827 | 97 | 0.667684 | 7,547 | /*
* Copyright (C) 2011 The Guava 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 com.google.common.hash;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashTestUtils.RandomHasherAction;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* Tests for AbstractNonStreamingHashFunction.
*/
public class AbstractNonStreamingHashFunctionTest extends TestCase {
/**
* Constructs two trivial HashFunctions (output := input), one streaming and one non-streaming,
* and checks that their results are identical, no matter which newHasher version we used.
*/
public void test() {
List<Hasher> hashers = ImmutableList.of(
new StreamingVersion().newHasher(),
new StreamingVersion().newHasher(52),
new NonStreamingVersion().newHasher(),
new NonStreamingVersion().newHasher(123));
Random random = new Random(0);
for (int i = 0; i < 200; i++) {
RandomHasherAction.pickAtRandom(random).performAction(random, hashers);
}
HashCode[] codes = new HashCode[hashers.size()];
for (int i = 0; i < hashers.size(); i++) {
codes[i] = hashers.get(i).hash();
}
for (int i = 1; i < codes.length; i++) {
assertEquals(codes[i - 1], codes[i]);
}
}
static class StreamingVersion extends AbstractStreamingHashFunction {
@Override
public int bits() {
return 32;
}
@Override
public Hasher newHasher() {
return new AbstractStreamingHasher(4, 4) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
@Override
HashCode makeHash() {
return HashCodes.fromBytes(out.toByteArray());
}
@Override
protected void process(ByteBuffer bb) {
while (bb.hasRemaining()) {
out.write(bb.get());
}
}
@Override
protected void processRemaining(ByteBuffer bb) {
while (bb.hasRemaining()) {
out.write(bb.get());
}
}
};
}
}
static class NonStreamingVersion extends AbstractNonStreamingHashFunction {
@Override
public int bits() {
return 32;
}
@Override
public HashCode hashBytes(byte[] input) {
return HashCodes.fromBytes(input);
}
@Override
public HashCode hashBytes(byte[] input, int off, int len) {
return HashCodes.fromBytes(Arrays.copyOfRange(input, off, off + len));
}
@Override
public HashCode hashString(CharSequence input) {
throw new UnsupportedOperationException();
}
@Override
public HashCode hashString(CharSequence input, Charset charset) {
throw new UnsupportedOperationException();
}
@Override
public HashCode hashLong(long input) {
throw new UnsupportedOperationException();
}
@Override
public HashCode hashInt(int input) {
throw new UnsupportedOperationException();
}
}
}
|
3e11e7c891ecee64179e7893048ac09fc7ebf29b | 161 | java | Java | rxdownload/src/main/java/io/github/mayunfei/rxdownload/function/DownloadHelper.java | MaYunFei/simple-rx-download | 5a8a0ecd9fe1388f8a1e11c676fcea93187cf822 | [
"Apache-2.0"
] | null | null | null | rxdownload/src/main/java/io/github/mayunfei/rxdownload/function/DownloadHelper.java | MaYunFei/simple-rx-download | 5a8a0ecd9fe1388f8a1e11c676fcea93187cf822 | [
"Apache-2.0"
] | null | null | null | rxdownload/src/main/java/io/github/mayunfei/rxdownload/function/DownloadHelper.java | MaYunFei/simple-rx-download | 5a8a0ecd9fe1388f8a1e11c676fcea93187cf822 | [
"Apache-2.0"
] | null | null | null | 14.636364 | 47 | 0.73913 | 7,548 | package io.github.mayunfei.rxdownload.function;
/**
* Created by mayunfei on 17-3-24.
*/
public class DownloadHelper {
private DownloadApi downloadApi;
}
|
3e11e8bad436e0f4bcc7415ac1d77732ec1514e3 | 1,360 | java | Java | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java | a13237009879/incubator-dubbo | e90d95c0d9f1d0fecf411ccf9066d74c88442c6e | [
"Apache-2.0"
] | 4 | 2019-02-17T16:44:31.000Z | 2019-08-26T23:17:15.000Z | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java | runkityboy/incubator-dubbo | 3623f52cc1452c00360b1b90883a4b4e2c2f6289 | [
"Apache-2.0"
] | 12 | 2018-09-25T15:32:45.000Z | 2022-03-31T20:45:22.000Z | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/merger/MapMerger.java | runkityboy/incubator-dubbo | 3623f52cc1452c00360b1b90883a4b4e2c2f6289 | [
"Apache-2.0"
] | 2 | 2018-08-27T14:26:53.000Z | 2018-08-28T01:37:35.000Z | 33.170732 | 75 | 0.666912 | 7,549 | /*
* 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.dubbo.rpc.cluster.merger;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.HashMap;
import java.util.Map;
public class MapMerger implements Merger<Map<?, ?>> {
@Override
public Map<?, ?> merge(Map<?, ?>... items) {
if (items.length == 0) {
return null;
}
Map<Object, Object> result = new HashMap<Object, Object>();
for (Map<?, ?> item : items) {
if (item != null) {
result.putAll(item);
}
}
return result;
}
}
|
3e11e8c7c2c40b0db51a230b989d4cf614f7db36 | 12,777 | java | Java | api/src/com/cloud/network/lb/LoadBalancingRule.java | bvbharatk/cloud-stack | 9acfc0307726204b444cc5e81abecb849eca23d9 | [
"Apache-2.0"
] | 2 | 2016-03-18T09:44:07.000Z | 2019-01-12T06:52:08.000Z | api/src/com/cloud/network/lb/LoadBalancingRule.java | bvbharatk/cloud-stack | 9acfc0307726204b444cc5e81abecb849eca23d9 | [
"Apache-2.0"
] | 1 | 2016-03-04T09:58:31.000Z | 2016-03-08T17:31:56.000Z | api/src/com/cloud/network/lb/LoadBalancingRule.java | bvbharatk/cloud-stack | 9acfc0307726204b444cc5e81abecb849eca23d9 | [
"Apache-2.0"
] | 1 | 2021-12-23T09:22:28.000Z | 2021-12-23T09:22:28.000Z | 26.786164 | 125 | 0.626047 | 7,550 | // 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 com.cloud.network.lb;
import java.util.List;
import com.cloud.network.as.AutoScalePolicy;
import com.cloud.network.as.AutoScaleVmGroup;
import com.cloud.network.as.AutoScaleVmProfile;
import com.cloud.network.as.Condition;
import com.cloud.network.as.Counter;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.utils.Pair;
public class LoadBalancingRule implements FirewallRule, LoadBalancer {
private LoadBalancer lb;
private List<LbDestination> destinations;
private List<LbStickinessPolicy> stickinessPolicies;
private LbAutoScaleVmGroup autoScaleVmGroup;
private List<LbHealthCheckPolicy> healthCheckPolicies;
public LoadBalancingRule(LoadBalancer lb, List<LbDestination> destinations,
List<LbStickinessPolicy> stickinessPolicies, List<LbHealthCheckPolicy> healthCheckPolicies) {
this.lb = lb;
this.destinations = destinations;
this.stickinessPolicies = stickinessPolicies;
this.healthCheckPolicies = healthCheckPolicies;
}
@Override
public long getId() {
return lb.getId();
}
@Override
public long getAccountId() {
return lb.getAccountId();
}
@Override
public long getDomainId() {
return lb.getDomainId();
}
@Override
public String getName() {
return lb.getName();
}
@Override
public String getDescription() {
return lb.getDescription();
}
@Override
public int getDefaultPortStart() {
return lb.getDefaultPortStart();
}
@Override
public int getDefaultPortEnd() {
return lb.getDefaultPortEnd();
}
@Override
public String getAlgorithm() {
return lb.getAlgorithm();
}
@Override
public String getUuid() {
return lb.getUuid();
}
@Override
public String getXid() {
return lb.getXid();
}
@Override
public Long getSourceIpAddressId() {
return lb.getSourceIpAddressId();
}
@Override
public Integer getSourcePortStart() {
return lb.getSourcePortStart();
}
@Override
public Integer getSourcePortEnd() {
return lb.getSourcePortEnd();
}
@Override
public String getProtocol() {
return lb.getProtocol();
}
@Override
public Purpose getPurpose() {
return Purpose.LoadBalancing;
}
@Override
public State getState() {
return lb.getState();
}
@Override
public long getNetworkId() {
return lb.getNetworkId();
}
public LoadBalancer getLb() {
return lb;
}
public void setDestinations(List<LbDestination> destinations) {
this.destinations = destinations;
}
public List<LbDestination> getDestinations() {
return destinations;
}
public List<LbStickinessPolicy> getStickinessPolicies() {
return stickinessPolicies;
}
public void setHealthCheckPolicies(List<LbHealthCheckPolicy> healthCheckPolicies) {
this.healthCheckPolicies = healthCheckPolicies;
}
public List<LbHealthCheckPolicy> getHealthCheckPolicies() {
return healthCheckPolicies;
}
public interface Destination {
String getIpAddress();
int getDestinationPortStart();
int getDestinationPortEnd();
boolean isRevoked();
}
public static class LbStickinessPolicy {
private String _methodName;
private List<Pair<String, String>> _params;
private boolean _revoke;
public LbStickinessPolicy(String methodName, List<Pair<String, String>> params, boolean revoke) {
this._methodName = methodName;
this._params = params;
this._revoke = revoke;
}
public LbStickinessPolicy(String methodName, List<Pair<String, String>> params) {
this._methodName = methodName;
this._params = params;
this._revoke = false;
}
public String getMethodName() {
return _methodName;
}
public List<Pair<String, String>> getParams() {
return _params;
}
public boolean isRevoked() {
return _revoke;
}
}
public static class LbHealthCheckPolicy {
private String pingpath;
private String description;
private int responseTime;
private int healthcheckInterval;
private int healthcheckThresshold;
private int unhealthThresshold;
private boolean _revoke;
public LbHealthCheckPolicy(String pingpath, String description, int responseTime, int healthcheckInterval,
int healthcheckThresshold, int unhealthThresshold) {
this(pingpath, description, responseTime, healthcheckInterval, healthcheckThresshold, unhealthThresshold, false);
}
public LbHealthCheckPolicy(String pingpath, String description, int responseTime, int healthcheckInterval,
int healthcheckThresshold, int unhealthThresshold, boolean revoke) {
this.pingpath = pingpath;
this.description = description;
this.responseTime = responseTime;
this.healthcheckInterval = healthcheckInterval;
this.healthcheckThresshold = healthcheckThresshold;
this.unhealthThresshold = unhealthThresshold;
this._revoke = revoke;
}
public LbHealthCheckPolicy() {
}
public String getpingpath() {
return pingpath;
}
public String getDescription() {
return description;
}
public int getResponseTime() {
return responseTime;
}
public int getHealthcheckInterval() {
return healthcheckInterval;
}
public int getHealthcheckThresshold() {
return healthcheckThresshold;
}
public int getUnhealthThresshold() {
return unhealthThresshold;
}
public boolean isRevoked() {
return _revoke;
}
}
public static class LbDestination implements Destination {
private int portStart;
private int portEnd;
private String ip;
boolean revoked;
public LbDestination(int portStart, int portEnd, String ip, boolean revoked) {
this.portStart = portStart;
this.portEnd = portEnd;
this.ip = ip;
this.revoked = revoked;
}
@Override
public String getIpAddress() {
return ip;
}
@Override
public int getDestinationPortStart() {
return portStart;
}
@Override
public int getDestinationPortEnd() {
return portEnd;
}
@Override
public boolean isRevoked() {
return revoked;
}
public void setRevoked(boolean revoked) {
this.revoked = revoked;
}
}
@Override
public Integer getIcmpCode() {
return null;
}
@Override
public Integer getIcmpType() {
return null;
}
@Override
public List<String> getSourceCidrList() {
return null;
}
@Override
public Long getRelated() {
return null;
}
@Override
public TrafficType getTrafficType() {
return null;
}
@Override
public FirewallRuleType getType() {
return FirewallRuleType.User;
}
public LbAutoScaleVmGroup getAutoScaleVmGroup() {
return autoScaleVmGroup;
}
public boolean isAutoScaleConfig() {
return this.autoScaleVmGroup != null;
}
public void setAutoScaleVmGroup(LbAutoScaleVmGroup autoScaleVmGroup) {
this.autoScaleVmGroup = autoScaleVmGroup;
}
public static class LbCondition {
private final Condition condition;
private final Counter counter;
public LbCondition(Counter counter, Condition condition) {
this.condition = condition;
this.counter = counter;
}
public Condition getCondition() {
return condition;
}
public Counter getCounter() {
return counter;
}
}
public static class LbAutoScalePolicy {
private final List<LbCondition> conditions;
private final AutoScalePolicy policy;
private boolean revoked;
public LbAutoScalePolicy(AutoScalePolicy policy, List<LbCondition> conditions) {
this.policy = policy;
this.conditions = conditions;
}
public List<LbCondition> getConditions() {
return conditions;
}
public AutoScalePolicy getPolicy() {
return policy;
}
public boolean isRevoked() {
return revoked;
}
public void setRevoked(boolean revoked) {
this.revoked = revoked;
}
}
public static class LbAutoScaleVmProfile {
AutoScaleVmProfile profile;
private final String autoScaleUserApiKey;
private final String autoScaleUserSecretKey;
private final String csUrl;
private final String zoneId;
private final String domainId;
private final String serviceOfferingId;
private final String templateId;
private final String networkId;
private final String vmName;
public LbAutoScaleVmProfile(AutoScaleVmProfile profile, String autoScaleUserApiKey,
String autoScaleUserSecretKey, String csUrl, String zoneId, String domainId, String serviceOfferingId,
String templateId, String vmName, String networkId) {
this.profile = profile;
this.autoScaleUserApiKey = autoScaleUserApiKey;
this.autoScaleUserSecretKey = autoScaleUserSecretKey;
this.csUrl = csUrl;
this.zoneId = zoneId;
this.domainId = domainId;
this.serviceOfferingId = serviceOfferingId;
this.templateId = templateId;
this.vmName = vmName;
this.networkId = networkId;
}
public AutoScaleVmProfile getProfile() {
return profile;
}
public String getAutoScaleUserApiKey() {
return autoScaleUserApiKey;
}
public String getAutoScaleUserSecretKey() {
return autoScaleUserSecretKey;
}
public String getCsUrl() {
return csUrl;
}
public String getZoneId() {
return zoneId;
}
public String getDomainId() {
return domainId;
}
public String getServiceOfferingId() {
return serviceOfferingId;
}
public String getTemplateId() {
return templateId;
}
public String getVmName() {
return vmName;
}
public String getNetworkId() {
return networkId;
}
}
public static class LbAutoScaleVmGroup {
AutoScaleVmGroup vmGroup;
private final List<LbAutoScalePolicy> policies;
private final LbAutoScaleVmProfile profile;
private final String currentState;
public LbAutoScaleVmGroup(AutoScaleVmGroup vmGroup, List<LbAutoScalePolicy> policies,
LbAutoScaleVmProfile profile, String currentState) {
this.vmGroup = vmGroup;
this.policies = policies;
this.profile = profile;
this.currentState = currentState;
}
public AutoScaleVmGroup getVmGroup() {
return vmGroup;
}
public List<LbAutoScalePolicy> getPolicies() {
return policies;
}
public LbAutoScaleVmProfile getProfile() {
return profile;
}
public String getCurrentState() {
return currentState;
}
}
}
|
3e11e992ca1db2229ea2036b8f37bc631e2a1ab9 | 56,894 | java | Java | src/main/java/biz/szydlowski/db4zabbix/web/ServerWorkerRunnable.java | TheDynamicsCode/db4Zabbix | 24935618a3d09a15d050f2448be5e13bea0a75d6 | [
"MIT"
] | null | null | null | src/main/java/biz/szydlowski/db4zabbix/web/ServerWorkerRunnable.java | TheDynamicsCode/db4Zabbix | 24935618a3d09a15d050f2448be5e13bea0a75d6 | [
"MIT"
] | null | null | null | src/main/java/biz/szydlowski/db4zabbix/web/ServerWorkerRunnable.java | TheDynamicsCode/db4Zabbix | 24935618a3d09a15d050f2448be5e13bea0a75d6 | [
"MIT"
] | null | null | null | 46.830453 | 266 | 0.40129 | 7,551 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package biz.szydlowski.db4zabbix.web;
import static biz.szydlowski.db4zabbix.DB4ZabbixDaemon.APP_NAME;
import static biz.szydlowski.utils.Constans.UPDATE_STR;
import static biz.szydlowski.db4zabbix.WorkingObjects.*;
import biz.szydlowski.db4zabbix.Version;
import biz.szydlowski.db4zabbix.api.DBApi;
import biz.szydlowski.db4zabbix.api.DataSource;
import biz.szydlowski.db4zabbix.api.JdbcDriverApi;
import biz.szydlowski.db4zabbix.sqlType;
import biz.szydlowski.utils.AutorestartConfig;
import biz.szydlowski.utils.ZabbixStatistics;
import static biz.szydlowski.utils.tasks.TasksWorkspace.absolutePath;
import static biz.szydlowski.utils.tasks.TasksWorkspace.autorestartApi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.Socket;
import java.net.URLDecoder;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
/**
*
* @author Dominik
*/
public class ServerWorkerRunnable implements Runnable {
static final Logger logger = LogManager.getLogger("biz.szydlowski.db4zabbix.web.ServerWorkerRunnable");
protected Socket clientSocket = null;
protected SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private boolean isApi=false;
public ServerWorkerRunnable(Socket clientSocket, boolean api) {
this.clientSocket = clientSocket;
this.isApi=api;
}
@Override
public void run() {
try {
String address = clientSocket.getInetAddress().getHostAddress();
InputStream input = this.clientSocket.getInputStream();
String userInput = "default";
BufferedReader stdIn = null;
try {
stdIn = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
userInput = stdIn.readLine();
} catch (IOException ex) {
logger.error(ex);
}
if (userInput == null) userInput = "DEFAULT";
PrintWriter out = new PrintWriter(this.clientSocket.getOutputStream(), true);
boolean isGet=true;
boolean isPost=false;
if (!isApi) {
logger.info("The following client was rejected: "+ address);
String data="<h1>401 UNAUTHORIZED. Authentication required.</h1><b><br/>Sorry, you are not allowed to access this page.</b><br/>";
String response = "HTTP/1.1 401 UNAUTHORIZED\r\n" +
"Content-Length: "+data.length()+"\r\n" +
"Content-Type: text/html\r\n\r\n" +
data;
out.print(response);
out.flush();
out.close();
input.close();
return;
} else {
logger.info("The following client has connected: "+ address);
}
if ( !userInput.contains("GET")){
isGet=false;
} else {
isGet=true;
}
String postData = "";
if ( userInput.contains("POST")){
isPost=true;
String line;
int postDataI=0;
while ((line = stdIn.readLine()) != null && (line.length() != 0)) {
logger.debug("HTTP-HEADER: " + line);
if (line.contains("Content-Length:")) {
postDataI = Integer.parseInt(line.substring(line.indexOf("Content-Length:") + 16, line.length()));
}
}
postData = "";
// read the post data
if (postDataI > 0) {
char[] charArray = new char[postDataI];
stdIn.read(charArray, 0, postDataI);
postData = new String(charArray);
}
postData = replaceURL(postData );
logger.debug("post DATA after replace " + postData);
} else {
isPost=false;
}
if (isGet || isPost){
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("<html>\n");
out.println("<head><meta charset=\"UTF-8\">");
out.println("<title>DB4Zabbix</title>");
out.println("</head>\n");
}
userInput = userInput.replace("GET", "");
userInput = userInput.replace("HTTP/1.1", "");
userInput = userInput.replace("/favicon.ico", "");
userInput = replaceURL(userInput);
if (userInput.length() == 0){
return;
}
if (isGet){
if (userInput.contains("hosts")){
printHosts(out);
} else if (userInput.contains("jdbc")){
printJdbc(out);
} else if (userInput.contains("config_tests")){
printConfigTests(out);
} else if (userInput.contains("tests")){
printTests(out);
} else if (userInput.contains("jobs")){
printJobs(out);
} else if (userInput.contains("threads")){
printAllThreads(out);
} else if (userInput.contains("version")){
printVersion(out);
} else if (userInput.contains("pid")){
printPID(out);
} else if (userInput.contains("ping")){
if (isGet) out.println(new StringBuilder().append("PONG").append("<br/>").toString());
else out.println(new StringBuilder().append("PONG").append("<br/>").toString());
} else if (userInput.contains("jvm")){
printJVM(out);
} else if (userInput.contains("statistics")) {
ZabbixStatistics _Statistics = new ZabbixStatistics (absolutePath +"setting/stats");
_Statistics.loadStats();
String stat = _Statistics.readStatsToHTMLString();
out.println(stat);
printHomeAndBack(out);
} else if (userInput.contains("autorestart")) {
AutorestartConfig autorestartConfig = new AutorestartConfig(absolutePath +"setting/autorestart.setting");
out.println(autorestartConfig.readAutorestartToHTMLString());
printHomeAndBack(out);
} else if (userInput.replaceAll("\\s+", "").equals("/")){
out.println(new StringBuilder().append("<b>Diagnostic console for ").append(Version.getVersion()).append("</b>").toString());
if (!APP_NAME.equals("DEFAULT")) out.println(new StringBuilder().append("<br/><b>App ").append(APP_NAME).toString());
out.println(new StringBuilder().append("<br/><br/>> <a href=\"version\">Version</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"pid\">PID</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"jvm\">JVM</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"statistics\">Show statistics</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"autorestart\">Display autorestart setting</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"hosts\">Display and change status of HOSTS</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"jdbc\">Display and change status of JDBC</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"tests\">Display and change status of all tests</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"config_tests\">Display configuration of all tests</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"threads\">Display threads</a><br/>").toString());
out.println(new StringBuilder().append("> <a href=\"jobs\">Display jobs</a><br/>").toString());
printRestartAndKill(out);
} else {
out.println(new StringBuilder().append("Page not found").append("<br/>").toString());
}
out.println("</br> SUPPORT TEAM <b> <a href=\"mailto:anpch@example.com?subject="+ Version.getVersion()+"\">support@szydlowski.biz</a></b>");
} else if (isPost){
// postData;
if ( userInput.contains("actions.api") ){
String[] spliter = postData.split("&");
String action="default";
String alias="default";
String id="default";
if ( spliter.length >= 3 && isPost) {
for (String spliter1 : spliter) {
String[] _sp = spliter1.split("=");
if (_sp.length==2){
if (_sp[0].equalsIgnoreCase("action")){
action = _sp[1];
} else if (_sp[0].equalsIgnoreCase("alias")){
alias = _sp[1];
} else if (_sp[0].equalsIgnoreCase("id")){
id = _sp[1];
} else {
out.write(new StringBuilder().append("ERROR: Server problem detected (E410)<br/>\n").toString());
}
} else {
}
}
}
if (action.equalsIgnoreCase("host_reverse")){
boolean _active = !unique_hostname.get(alias);
unique_hostname.put(alias, _active);
int dot = alias.indexOf(".");
String agent = "default";
String host="default";
if (dot > 0 && dot+1<alias.length()){
agent = alias.substring(0, dot);
host=alias.substring(dot+1, alias.length());
}
if (dot > 0 && dot+1<alias.length()){
for (DBApi dbApi : DBApiList){
if (dbApi.getZabbixHost().equals(host) && dbApi.getZabbixServerName().equals(agent)){
//System.out.println(dbApi.getZabbixKey());
sqlType type = dbApi.getSqlType();
if (_active) {
dbApi.setToActiveMode();
} else dbApi.setToInactiveMode();
}
}
} //end if ok
if ( !_active ){
out.write(new StringBuilder().append("<font color=\"red\">INACTIVE</font>").toString());
} else {
out.write(new StringBuilder().append("<font color=\"green\">ACTIVE</font>").toString());
}
} //end reverse
else if (action.equalsIgnoreCase("jdbc_reverse")){
int _id =0;
_id = Integer.parseInt(id);
String interfaceName = JdbcDriverApiList.get(_id).getInterfaceName();
boolean _setToActive = !JdbcDriverApiList.get(_id).isActiveMode();
if (_setToActive){
if (JdbcDriverApiList.get(_id).getInterfaceType().equalsIgnoreCase("pool")){
try {
DataSource.retry( JdbcDriverApiList.get(_id));
} catch (Exception e){
logger.error(e);
}
logger.debug("OPEN pool " + interfaceName);
}
JdbcDriverApiList.get(_id).setToActiveMode();
} else {
if (JdbcDriverApiList.get(_id).getInterfaceType().equalsIgnoreCase("pool")){
for (DataSource ds : DataSource.getInstances(JdbcDriverApiList.get(_id).getPoolIndex())){
ds.closePool();
}
logger.debug("Close pool " + interfaceName);
}
JdbcDriverApiList.get(_id).setToInactiveMode();
}
for (DBApi dbApi : DBApiList){
sqlType type = dbApi.getSqlType();
if (dbApi.getJdbc_driverSize()>0){
if (dbApi.getJdbc_driver(0).getInterfaceName().equals(interfaceName)){
//System.out.println(dbApi.getZabbixKey());
if ( _setToActive) {
dbApi.setToActiveMode();
} else dbApi.setToInactiveMode();
}
}
}
if ( ! _setToActive ){
out.write(new StringBuilder().append("<font color=\"red\">INACTIVE</font>").toString());
} else {
out.write(new StringBuilder().append("<font color=\"green\">ACTIVE</font>").toString());
}
} else if (action.equalsIgnoreCase("db_reverse")){
boolean _active = false;
int _id =0;
_id = Integer.parseInt(id);
sqlType type = DBApiList.get(_id).getSqlType();
_active = !DBApiList.get(_id).isActiveMode();
if (_active) {
DBApiList.get(_id).setToActiveMode();
} else DBApiList.get(_id).setToInactiveMode();
if ( !_active ){
out.write(new StringBuilder().append("<font color=\"red\">INACTIVE</font>").toString());
} else {
out.write(new StringBuilder().append("<font color=\"red\">INACTIVE</font>").toString());
}
}
else if (action.equalsIgnoreCase("db_refresh")){
int _id =0;
_id = Integer.parseInt(id);
sqlType type = DBApiList.get(_id).getSqlType();
String getout="";
getout = _DBQuartz.refreshTask(_id);
out.write(new StringBuilder().append("<font color=\"blue\">").append(getout).append("</font>").toString());
} else {
out.write(new StringBuilder().append("<font color=\"red\">DO NOTHING</font>").toString());
}
} else if ( userInput.contains("restart.api") ){
String[] _sp = postData.split("=");
if (_sp.length==2){
if (_sp[1].equals("restart")){
out.write(new StringBuilder().append("<font color=\"red\">RESTART DAEMON</font>").toString());
out.flush();
autorestartApi.restart();
} else if (_sp[1].equals("kill")){
out.write(new StringBuilder().append("<font color=\"red\">KILL DAEMON</font>").toString());
out.flush();
autorestartApi.kill();
} else {
out.write(new StringBuilder().append("<font color=\"red\">DO NOTHING</font>").toString());
}
} else {
logger.error("_sp.length!=2");
}
} else {
if (isGet) out.println(new StringBuilder().append("Page/Command not found").append("<br/>").toString());
else out.println(new StringBuilder().append("The command not found").append("<br/>").toString());
}
}
if (isGet || isPost){
out.println("</html>");
}
out.flush();
out.close();
input.close();
logger.debug("Request processed/completed...");
}
catch (IOException e) {
logger.error(e);
}
}
private void printHosts(PrintWriter out) {
out.print("<h2>HOSTS</h2>\n");
out.println("<style>\n table, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n }\n th, td {\n padding: 5px;\n");
out.println(" text-align: left; \n}\n </style>");
// out.println("<font color=\"red\"><p id=\"info\"></p></font>");
Set set = unique_hostname.entrySet();
Iterator iterator = set.iterator();
out.println("<table style=\"width:90%\">");
out.println("<tr>\n <th>Server</th>\n <th>Host</th>\n <th>Status</th>\n <th>Action</th>\n </tr>");
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
String key = mentry.getKey().toString();
int dot = key.indexOf(".");
String server = "default";
String host="default";
if (dot > 0 && dot+1<key.length()){
server = key.substring(0, dot);
host= key.substring(dot+1, key.length());
}
out.println("<tr>");
out.println("<td>");
out.print( server );
out.println("</td>");
out.println("<td>");
out.print( host );
out.println("</td>");
out.println("<td id=\""+mentry.getKey()+"\">");
if (mentry.getValue().toString().equals("true")){
out.println("<font color=\"green\">ACTIVE</font>");
} else {
out.println("<font color=\"red\">INACTIVE</font>");
}
out.println("<td><button onclick=\"Action('host_reverse','"+mentry.getKey()+"', 'no')\">Active/Deactive</button><br/></td>");
out.println("</tr>");
}
out.println("</table>");
printApiFunction(out);
printHomeAndBack(out);
}
private void printJdbc(PrintWriter out) {
out.print("<h2>JDBC</h2>\n");
out.println("<style>\n table, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n }\n th, td {\n padding: 5px;\n");
out.println(" text-align: left; \n}\n </style>");
out.println("<table style=\"width:90%\">");
out.println("<tr>\n <th>JDBC Interface</th> <th>Interface type</th>\n <th>Status</th>\n <th>host:port</th>\n <th>Connection timeout</th>\n <th>Connection retry</th>\n <th>Pool key's</th>\n <th>Action</th>\n </tr>");
int i=0;
for (JdbcDriverApi jdbcApi : JdbcDriverApiList) {
out.println("<tr>");
out.println("<td>");
out.print(jdbcApi.getInterfaceName());
out.println("</td>");
out.println("<td>");
out.print(jdbcApi.getInterfaceType());
out.println("</td>");
out.println("<td id=\""+jdbcApi.getInterfaceName()+"\">");
if (jdbcApi.isActiveMode()){
out.println("<font color=\"green\">ACTIVE</font>");
} else {
out.println("<font color=\"red\">INACTIVE</font>");
}
out.println("<td>");
out.print(jdbcApi.getHost()+":"+jdbcApi.getStringPort());
out.println("</td>");
out.println("<td>");
if (jdbcApi.getInterfaceType().equalsIgnoreCase("single")) out.print(jdbcApi.getLoginTimeout());
else out.println("look at pool key");
out.println("</td>");
out.println("<td>");
if (jdbcApi.getInterfaceType().equalsIgnoreCase("single")) out.print(jdbcApi.getConnectionRetry());
else out.println("look at pool key");
out.println("</td>");
out.println("<td>");
if (jdbcApi.getInterfaceType().equalsIgnoreCase("pool")){
out.println("MinPoolSize=");
out.println(jdbcApi.getMinPoolSize());
out.println("</br>");
out.println("MaxPoolSize=");
out.println(jdbcApi.getMaxPoolSize());
out.println("</br>");
out.println("MaxStatements=");
out.println(jdbcApi.getMaxStatements());
out.println("</br>");
out.println("AcquireIncrement=");
out.println(jdbcApi.getAcquireIncrement());
out.println("</br>");
out.println("LoginTimeout=");
out.println(jdbcApi.getLoginTimeout());
out.println("</br>");
out.println("PoolIndex=");
out.println(jdbcApi.getPoolIndex());
out.println("</br>");
} else out.println("not pooling");
out.println("</td>");
out.println("<td><button onclick=\"Action('jdbc_reverse','"+jdbcApi.getInterfaceName()+"', '"+i+"')\">Active/Deactive</button><br/></td>");
out.println("</tr>");
i++;
}
out.println("</table>");
printApiFunction(out);
printHomeAndBack(out);
}
private void printTests(PrintWriter out) {
out.print("<h2>TESTS</h2>\n");
out.println("<style>\n table, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n }\n th, td {\n padding: 5px;\n");
out.println(" text-align: left; \n}\n </style>");
out.println("<table style=\"width:90%\">");
out.println("<tr>\n <th>ID</th>\n <th>Zabbix server</th>\n <th>Zabbix host</th>\n <th>Zabbix key</th>\n <th>Type</th>\n <th>VALUE</th>\n <th>Status</th>\n <th>Last execution time</th>\n <th>Action</th>\n <th>Refresh</th>\n </tr>");
int idx=0;
for (DBApi dbApi : DBApiList){
out.println("<tr>");
out.println("<td>");
out.print( idx );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getZabbixServerName() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getZabbixHost() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getZabbixKey() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getSqlType() );
out.println("</td>");
out.println("<td>");
boolean discovered=false;
boolean multicolumn=false;
if (dbApi.getSqlType()==sqlType.DISCOVERY_QUERY ||
dbApi.getSqlType()==sqlType.PURE_WITH_MULTIPLE ||
dbApi.getSqlType()==sqlType.DISCOVERY_STATIC ){
discovered=true;
} else if (dbApi.getSqlType()==sqlType.PURE_WITH_REVERSE_MULTIPLE ){
multicolumn=true;
}
if (dbApi.isNowExecuting()){
out.print( "EXECUTING..." );
} else if (dbApi.isNowRefreshing()){
out.print( "REFRESHING..." );
} else if (dbApi.getDiagnosticReturnListValue().isEmpty() && !discovered && !multicolumn){
out.print( "RETURNED NOTHING" );
} else if (dbApi.getDiscoveryMap().isEmpty() && discovered && !multicolumn){
out.print( "RETURNED NOTHING" );
} else if (discovered){
List<List<String>> getData = dbApi.getDiscoveryMap();
List<String> metaData = dbApi.getDiscoveryMetaData();
for(int kk=0; kk<metaData.size(); kk++) {
out.print(metaData.get(kk));
out.print(" ");
}
out.print("</br>");
for(int kk=0; kk<getData.size(); kk++) {
List <String> keys_value = getData.get(kk);
for (int kl=0; kl<keys_value.size();kl++){
out.print(keys_value.get(kl));
out.print(" ");
}
out.print("</br>");
}
} else if ( multicolumn){
if (dbApi.getDiscoveryMap()!=null){
if (!dbApi.getDiscoveryMap().isEmpty()){
//out.println(dbApi.getDiscoveryMetaData());
//out.println("<br>");
//out.println(dbApi.getDiscoveryMap());
int stat=-1;
String zbkey = dbApi.getZabbixKey();
String zbkeytmp = "";
if (zbkey.contains("{#STAT}")) stat=1;
if (stat>-1){
String [] pcolumns = dbApi.getDatabaseProperty("paramsColumn", "DefaultColumn").toUpperCase().split(",");
int [] pcolumnsMap = new int [pcolumns.length];
//prepare
for (int h=0; h<pcolumns.length;h++){
pcolumnsMap[h]=-1;
}
//prepare
for (int h=0; h<pcolumns.length;h++){
for (int l=0; l<dbApi.getDiscoveryMetaData().size();l++){
if (dbApi.getDiscoveryMetaData().get(l).equalsIgnoreCase(pcolumns[h])){
pcolumnsMap[h]=l;
logger.debug(">> FOUND STAT -> " + l + " " + dbApi.getDiscoveryMetaData().get(l));
// break;
}
}
}
for(int i=0; i<dbApi.getDiscoveryMap().size(); i++) { //i-ty wiersz z kolejki
zbkey = dbApi.getZabbixKey(); //reset
if (dbApi.getDiscoveryMap().get(i).size()!=dbApi.getDiscoveryMetaData().size()){
logger.error("Consist error metaData");
continue;
}
String mtd = "";
//zmiany w kolumach z parametrem statycznym
for (int h=0; h<pcolumnsMap.length;h++){
if (pcolumnsMap[h]>-1) {
mtd="{#"+dbApi.getDiscoveryMetaData().get(pcolumnsMap[h])+"}";
zbkey=zbkey.replace(mtd.toUpperCase(), dbApi.getDiscoveryMap().get(i).get(pcolumnsMap[h]));
}
}
for (int j=0; j<dbApi.getDiscoveryMap().get(i).size();j++){ //każda kolumna j-ta i-ty wiersz
if (!checkParmsColumn(dbApi.getDiscoveryMetaData().get(j), pcolumns)){ //kolumna params
zbkeytmp=zbkey.replace("{#STAT}", dbApi.getDiscoveryMetaData().get(j));
out.println(zbkeytmp);
out.println(" ");
out.println(dbApi.getDiscoveryMap().get(i).get(j));
out.println("<br>");
//System.out.println(dataObject.toString());
//logger.debug(dataObject.toString());
} else {
logger.debug(">> !STAT " + dbApi.getDiscoveryMetaData().get(j));
}
}
}
} else {
logger.error("Value STAT not found!!!");
}
} else {
out.println("dbApi.getDiscoveryMap isEmpty() ");
}
} else {
out.println("dbApi.getDiscoveryMap is NULL");
}
} else {
for (int j=0; j<dbApi.getDiagnosticReturnListValue().size(); j++){
out.print(dbApi.getDiagnosticReturnListValue().get(j));
}
}
out.println("</td>");
out.println("<td id=\""+idx+"."+dbApi.getAlias()+"\">");
if (dbApi.isActiveMode()){
out.println("<font color=\"green\">ACTIVE</font>");
} else {
out.println("<font color=\"red\">INACTIVE</font>");
}
out.println("</td>");
out.println("<td>");
out.print( dbApi.getLastExecuteTime() );
out.println("</td>");
out.println("<td><button onclick=\"Action('db_reverse','"+idx+"."+dbApi.getAlias()+"', '"+idx+"')\">Active/Deactive</button><br/></td>");
out.println("<td><button onclick=\"Action('db_refresh','"+idx+"."+dbApi.getAlias()+"', '"+idx+"')\">Refresh</button><br/></td>");
out.println("</tr>");
idx++;
}
out.println("</table>");
printApiFunction(out);
printHomeAndBack(out);
}
private boolean checkParmsColumn(String col, String [] params){
boolean ret=false;
for (String s:params){
if (s.equalsIgnoreCase(col)) {
ret=true;
break;
}
}
return ret;
}
private void printConfigTests(PrintWriter out) {
out.print("<h2>TESTS CONFIGURATION</h2>\n");
out.println("<style>\n table, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n }\n th, td {\n padding: 5px;\n");
out.println(" text-align: left; \n}\n </style>");
out.println("<table style=\"width:90%\">");
out.println("<tr>\n <th>ID</th>\n <th>Zabbix server</th>\n <th>Zabbix host</th>\n <th>Zabbix key</th>\n <th>Jdbc interface</th>\n <th>Type</th>\n <th>Sql query</th>\n <th>Cron expression</th>\n <th>Configure errors</th>\n <th>Filename</th>\n </tr>");
int i=1;
for (DBApi dbApi : DBApiList){
out.println("<tr>");
out.println("<td>");
out.print( i );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getZabbixServerName() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getZabbixHost() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getZabbixKey() );
out.println("</td>");
out.println("<td>");
if (dbApi.getJdbc_driverSize()>0) out.print( dbApi.getJdbc_driver(0).getInterfaceName() );
else out.print( "-----------" );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getSqlType() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getSqlQuery() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getCronExpression() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.printConfigErrorList() );
out.println("</td>");
out.println("<td>");
out.print( dbApi.getSettingFile() );
out.println("</td>");
out.println("</tr>");
i++;
}
out.println("</table>");
printHomeAndBack(out);
}
private void printAllThreads(PrintWriter out){
out.print("<h2>THREADS</h2>\n");
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
out.println("<style>\n table, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n }\n th, td {\n padding: 5px;\n");
out.println(" text-align: left; \n}\n </style>");
out.println("<table style=\"width:90%\">");
out.println("<tr>\n <th>ID</th>\n <th>Thread ID</th>\n <th>Thread name</th>\n <th>Thread state</th>\n <th>Thread priority</th>\n </tr>");
for (int i = 0; i < noThreads; i++){
out.println("<tr>");
out.println("<td>");
out.print(i);
out.println("</td>");
out.println("<td>");
out.print(lstThreads[i].getId());
out.println("</td>");
out.println("<td>");
out.print(lstThreads[i].getName());
out.println("</td>");
out.println("<td>");
out.print(lstThreads[i].getState());
out.println("</td>");
out.println("<td>");
out.print(lstThreads[i].getPriority());
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
printHomeAndBack(out);
}
private void printJobs(PrintWriter out){
out.print("<h2>JOBS</h2>\n");
out.println("<style>\n table, th, td {\n border: 1px solid black;\n border-collapse: collapse;\n }\n th, td {\n padding: 5px;\n");
out.println(" text-align: left; \n}\n </style>");
out.println("<table style=\"width:90%\">");
out.println("<tr>\n <th>ID</th>\n <th>job groupName</th>\n <th>job key</th>\n <th>Next fire time</th>\n <th>State</th>\n </tr>");
Scheduler scheduler;
int i=0;
try {
scheduler = new StdSchedulerFactory().getScheduler();
for (String groupName : scheduler.getJobGroupNames()) {
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
out.println("<tr>");
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
out.print("<td>");
out.print(i);
out.println("</td>");
i++;
out.print("<td>");
out.print(jobGroup);
out.println("</td>");
out.print("<td>");
out.print(jobName );
out.println("</td>");
if (scheduler.getTriggersOfJob(jobKey).isEmpty()){
out.print("<td>");
out.print( "Empty job" );
out.println("</td>");
continue;
}
String triggerStatus = "default";
try {
triggerStatus = scheduler.getTriggerState(scheduler.getTriggersOfJob(jobKey).get(0).getKey()).toString();
Date nextFireTime = scheduler.getTriggersOfJob(jobKey).get(0).getNextFireTime();
if (nextFireTime==null){
out.print("<td>");
out.print("Run once");
out.println("</td>");
} else {
out.print("<td>");
out.print(format.format(nextFireTime));
out.println("</td>");
}
out.print("<td>");
out.print(triggerStatus);
out.println("</td>");
} catch (SchedulerException e){
out.print("<td>");
out.print("Error " + e);
out.println("</td>");
logger.error("Error and continue " + e);
continue;
}
out.println("</tr>");
}
}
} catch (SchedulerException ex) {
out.println(ex);
}
out.println("</table>");
printHomeAndBack(out);
}
private String replaceURL(String postData){
try {
postData = URLDecoder.decode(postData, "UTF-8");
} catch (UnsupportedEncodingException ex) {
logger.error("replaceURL decoder");
}
postData = postData.replaceAll("%C4%84", "A");
postData = postData.replaceAll("%C4%85", "a");
postData = postData.replaceAll("%C4%87", "C");
postData = postData.replaceAll("%C4%88", "c");
postData = postData.replaceAll("%C4%98", "E");
postData = postData.replaceAll("%C4%99", "e");
postData = postData.replaceAll("%C5%81", "L");
postData = postData.replaceAll("%C5%82", "l");
postData = postData.replaceAll("%C5%83", "N");
postData = postData.replaceAll("%C5%84", "n");
postData = postData.replaceAll("%C3%B3", "o");
postData = postData.replaceAll("%C3%93", "O");
postData = postData.replaceAll("%C5%9A", "S");
postData = postData.replaceAll("%C5%9B", "s");
postData = postData.replaceAll("%C5%B9", "Z");
postData = postData.replaceAll("%C5%BA", "z");
postData = postData.replaceAll("%C5%BB", "Z");
postData = postData.replaceAll("%C5%BC", "z");
postData = postData.replaceAll("%20", " ");
postData = postData.replaceAll("%5B", "[");
postData = postData.replaceAll("%5C", "\\");
postData = postData.replaceAll("%5D", "]");
postData = postData.replaceAll("%21", "!");
postData = postData.replaceAll("%22", "\"");
postData = postData.replaceAll("%23", "#");
postData = postData.replaceAll("%24", "$");
postData = postData.replaceAll("%28", "(");
postData = postData.replaceAll("%29", ")");
postData = postData.replaceAll("%40", "@");
postData = postData.replaceAll("%3F", "?");
postData = postData.replaceAll("%25", "%");
return postData;
}
private boolean isApi( PrintWriter out, boolean isGet ){
if (!isApi){
if (isGet) {
String data="<h1>401 UNAUTHORIZED</h1>";
String response = "HTTP/1.1 401 UNAUTHORIZED\r\n" +
"Content-Length: "+data.length()+"\r\n" +
"Content-Type: text/html\r\n\r\n" + data;
out.println(response);
out.println("<b>Sorry, you are not allowed to access this page.</b><br/>");
}
else out.println("Sorry, you are not allowed to access this page.\n");
}
return isApi;
}
private void printRestartApiFunction(PrintWriter out){
out.println("<font color=\"red\"><p id=\"info\"></p></font>");
out.println(new StringBuilder().append("<script>\n").append("function Restart(type) {\n")
.append( " var txt = \'Action\';\n")
.append( " if (type === 'restart') {\n")
.append( " txt = \"Are you sure you want to daemon?\";\n")
.append( " } else if (type === 'kill') {\n")
.append( " txt = \"Are you sure you want to kill daemon?\";\n")
.append( " } \n")
.append( " var r = confirm(txt);\n")
.append( " if (r == true) {\n")
.append( " var xhttp = new XMLHttpRequest();\n")
.append( " xhttp.onreadystatechange = function() {\n")
.append( " if (this.status == 200) {")
.append( " document.getElementById(\"info\").innerHTML = this.responseText;\n")
.append( " }\n")
.append( " };\n")
.append( " xhttp.open(\"POST\", \"restart.api\", true);")
.append( " xhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n")
.append( " xhttp.send(\"action=\"+type);\n ")
.append( " } else {\n")
.append( " }\n")
.append( " }\n")
.append( " </script>").toString());
}
private void printApiFunction(PrintWriter out){
out.println("<font color=\"red\"><p id=\"info\"></p></font>");
out.println(new StringBuilder().append("<script>\n").append("function Action(type, alias, id) {\n")
.append( " var txt = \'Action\';\n")
.append( " if (type === 'host_reverse' ) {\n")
.append( " txt = \"Are you sure you want active/deactive host \" + alias + \"?\"; \n")
.append( " } ")
.append( " else if ( type === 'jdbc_reverse') {\n")
.append( " txt = \"Are you sure you want active/deactive jdbc \" + alias + \"?\"; \n")
.append( " } ")
.append( " else if ( type === 'db_reverse') {\n")
.append( " txt = \"Are you sure you want active/deactive test \" + alias + \"?\"; \n")
.append( " } ")
.append( " else if ( type === 'db_refresh') {\n")
.append( " txt = \"Are you sure you want refresh test \" + alias + \"?\"; \n")
.append( " } ")
.append( " var r = confirm(txt);\n")
.append( " if (r == true) {\n")
.append( " var xhttp = new XMLHttpRequest();\n")
.append( " xhttp.onreadystatechange = function() {\n")
.append( " if ( type === 'db_reverse' || type === 'db_refresh' || type === 'host_reverse' || type === 'jdbc_reverse') {\n")
.append( " if (this.status == 200) {\n")
.append( " document.getElementById(alias).innerHTML = this.responseText;\n")
.append( " }\n")
.append( " }\n")
.append( " else {")
.append( " if (this.status == 200) {\n")
.append( " document.getElementById(id+\".\"+alias).innerHTML = this.responseText;\n")
.append( " }\n")
.append( " }\n")
.append( " };\n")
.append( " xhttp.open(\"POST\", \"actions.api\", true);\n")
.append( " xhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n")
.append( " xhttp.send(\"action=\"+type+\"&alias=\"+alias+\"&id=\"+id);\n ")
.append( " } else {\n")
.append( " }\n")
.append( " }\n")
.append( " </script>").toString());
}
private void printRestartAndKill(PrintWriter out){
out.println("");
out.println("<br/><button onclick=\"Restart('restart')\">Restart DAEMON</button><br/>");
out.println("");
out.println("<button onclick=\"Restart('kill')\">Kill DAEMON</button><br/>");
printRestartApiFunction(out);
}
private void printHomeAndBack(PrintWriter out){
out.println("<br/><button onclick=\"goHome()\">HOME</button>\n");
out.println(" ");
out.println("<script>\n");
out.println("function goHome() {\n");
out.println(" window.location = '/';\n");
out.println("}\n" );
out.println( "</script>");
out.println("<button onclick=\"goBack()\">Go Back</button><br/>\n");
out.println("\n");
out.println("<script>\n");
out.println("function goBack() {\n");
out.println(" window.history.back();\n");
out.println("}\n" );
out.println( "</script>");
}
private void printPID(PrintWriter out) {
String processName = ManagementFactory.getRuntimeMXBean().getName();
out.println("<b> CURRENT PID ");
out.println(Long.parseLong(processName.split("@")[0]));
out.println(" </b><br/>");
printHomeAndBack(out);
}
private void printVersion(PrintWriter out) {
out.println("<b><h3> VERSION " +Version.getName()+ " </h3>" );
out.println(" </b>");
out.println(Version.getVersion());
out.println("<br/>");
out.println(Version.getAuthor());
out.println("<br/>");
out.println("DEV_VERSION_EXPIRE_STR: ");
out.println(Version.DEV_VERSION_EXPIRE_STR);
out.println("<br/>");
out.println(UPDATE_STR.toString());
printHomeAndBack(out);
}
private void printJVM(PrintWriter out) {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long usedMem = allocatedMemory - freeMemory;
long totalMem = runtime.totalMemory();
long mb=1024;
out.println("<b><h3>Heap utilization statistics [MB] </h3>" );
out.println(" </b>");
out.println("Total Memory: " + totalMem / mb);
out.println("<br/>");
out.println("Free Memory: " + freeMemory / mb);
out.println("<br/>");
out.println("Used Memory: " + usedMem / mb);
out.println("<br/>");
out.println("Max Memory: " + maxMemory / mb);
out.println("<br/>");
out.println("<b><h3>SystemMXBean statistics</h3></b>" );
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
value = e;
} // try
out.println(method.getName() + " = " + value);
out.println("<br/>");
} // if
} // for
printHomeAndBack(out);
}
} |
3e11eaad816cc48411abff94faa79dac7f3f2795 | 2,936 | java | Java | blueflood-core/src/main/java/com/rackspacecloud/blueflood/utils/QueryDiscoveryModuleLoader.java | GeorgeJahad/blueflood | f6daf3dc6be1781d94b2b82f508b0c048d4f7f65 | [
"Apache-2.0"
] | null | null | null | blueflood-core/src/main/java/com/rackspacecloud/blueflood/utils/QueryDiscoveryModuleLoader.java | GeorgeJahad/blueflood | f6daf3dc6be1781d94b2b82f508b0c048d4f7f65 | [
"Apache-2.0"
] | null | null | null | blueflood-core/src/main/java/com/rackspacecloud/blueflood/utils/QueryDiscoveryModuleLoader.java | GeorgeJahad/blueflood | f6daf3dc6be1781d94b2b82f508b0c048d4f7f65 | [
"Apache-2.0"
] | null | null | null | 39.675676 | 105 | 0.673365 | 7,552 | /*
* Copyright 2015 Rackspace
*
* 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.rackspacecloud.blueflood.utils;
import com.rackspacecloud.blueflood.io.DiscoveryIO;
import com.rackspacecloud.blueflood.service.Configuration;
import com.rackspacecloud.blueflood.service.CoreConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class QueryDiscoveryModuleLoader {
private static final Logger log = LoggerFactory.getLogger(QueryDiscoveryModuleLoader.class);
private static DiscoveryIO discoveryInstance;
public static synchronized void loadDiscoveryModule() {
if (discoveryInstance != null) {
log.warn("Discovery module %s already loaded", discoveryInstance.getClass());
return;
}
List<String> modules = Configuration.getInstance().getListProperty(CoreConfig.DISCOVERY_MODULES);
if (modules.isEmpty())
return;
if (!modules.isEmpty() && modules.size() != 1) {
throw new RuntimeException("Cannot load query service with more than one discovery module");
}
ClassLoader classLoader = DiscoveryIO.class.getClassLoader();
String module = modules.get(0);
log.info("Loading metric discovery module " + module);
try {
Class discoveryClass = classLoader.loadClass(module);
discoveryInstance = (DiscoveryIO) discoveryClass.newInstance();
log.info("Registering metric discovery module " + module);
} catch (InstantiationException e) {
log.error("Unable to create instance of metric discovery class for: " + module, e);
} catch (IllegalAccessException e) {
log.error("Error starting metric discovery module: " + module, e);
} catch (ClassNotFoundException e) {
log.error("Unable to locate metric discovery module: " + module, e);
} catch (RuntimeException e) {
log.error("Error starting metric discovery module: " + module, e);
} catch (Throwable e) {
log.error("Error starting metric discovery module: " + module, e);
}
}
public static DiscoveryIO getDiscoveryInstance() {
if (discoveryInstance == null) {
// Try loading the discovery module instance
loadDiscoveryModule();
}
return discoveryInstance;
}
}
|
3e11ead305f928361fbf429185d65f655e9f3723 | 576 | java | Java | domain-api/jbb-system-api/src/main/java/org/jbb/system/api/logging/model/LogLevelFilter.java | jbb-project/jbb | cefa12cda40804395b2d6e8bea0fb8352610b761 | [
"Apache-2.0"
] | 4 | 2017-02-23T15:35:33.000Z | 2020-08-03T22:00:17.000Z | domain-api/jbb-system-api/src/main/java/org/jbb/system/api/logging/model/LogLevelFilter.java | jbb-project/jbb | cefa12cda40804395b2d6e8bea0fb8352610b761 | [
"Apache-2.0"
] | 1 | 2019-05-14T18:54:24.000Z | 2019-05-14T18:54:24.000Z | domain-api/jbb-system-api/src/main/java/org/jbb/system/api/logging/model/LogLevelFilter.java | jbb-project/jbb | cefa12cda40804395b2d6e8bea0fb8352610b761 | [
"Apache-2.0"
] | 3 | 2018-03-29T15:51:09.000Z | 2019-11-25T02:46:41.000Z | 23.04 | 67 | 0.75 | 7,553 | /*
* Copyright (C) 2017 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.system.api.logging.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class LogLevelFilter implements LogFilter {
private LogLevel logLevel;
}
|
3e11eb07053921ccdd6d810f81f1842b8521f74c | 186 | java | Java | testfiles/CFG/EntryPoints/Class/Class02/Class02.java | challe535/IntraJ | 357a62afd3737a477148616a80734c03c3668b9b | [
"BSD-3-Clause"
] | 2 | 2022-02-21T08:23:26.000Z | 2022-02-22T10:12:49.000Z | testfiles/CFG/EntryPoints/Class/Class02/Class02.java | challe535/IntraJ | 357a62afd3737a477148616a80734c03c3668b9b | [
"BSD-3-Clause"
] | 1 | 2021-08-18T18:47:59.000Z | 2021-08-18T18:47:59.000Z | testfiles/CFG/EntryPoints/Class/Class02/Class02.java | challe535/IntraJ | 357a62afd3737a477148616a80734c03c3668b9b | [
"BSD-3-Clause"
] | 1 | 2021-11-15T08:56:58.000Z | 2021-11-15T08:56:58.000Z | 15.5 | 30 | 0.456989 | 7,554 | public class Class02 {
Sub x;
class Sub {
static final int q = 3;
{ int j = 0; }
Sub() { this(q); }
int x = 0;
Sub(int x) {}
}
Class02() { x = new Sub(); }
} |
3e11ef7b520c9a4de42cc6ba93d614867c411171 | 12,085 | java | Java | querydsl-sql/src/main/java/com/querydsl/sql/dml/AbstractSQLUpdateClause.java | thanhthong022002/querydsl | db60d57bf158be7ed5563fa2d3137e8cecee3f97 | [
"Apache-2.0"
] | 3,579 | 2015-01-01T18:13:48.000Z | 2022-03-31T18:28:45.000Z | querydsl-sql/src/main/java/com/querydsl/sql/dml/AbstractSQLUpdateClause.java | Camork/querydsl | 7ca3d9b24ee7d81af1e90c49223652b874d92102 | [
"Apache-2.0"
] | 1,828 | 2015-01-04T10:52:58.000Z | 2022-03-31T14:45:10.000Z | querydsl-sql/src/main/java/com/querydsl/sql/dml/AbstractSQLUpdateClause.java | Camork/querydsl | 7ca3d9b24ee7d81af1e90c49223652b874d92102 | [
"Apache-2.0"
] | 867 | 2015-01-07T21:46:24.000Z | 2022-03-29T12:56:31.000Z | 34.138418 | 141 | 0.621763 | 7,555 | /*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* 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.querydsl.sql.dml;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Logger;
import java.util.function.Supplier;
import org.jetbrains.annotations.Range;
import com.querydsl.core.*;
import com.querydsl.core.QueryFlag.Position;
import com.querydsl.core.dml.UpdateClause;
import com.querydsl.core.types.ConstantImpl;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.sql.Configuration;
import com.querydsl.sql.RelationalPath;
import com.querydsl.sql.SQLBindings;
import com.querydsl.sql.SQLSerializer;
import com.querydsl.sql.types.Null;
/**
* Provides a base class for dialect-specific UPDATE clauses.
*
* @author tiwe
* @param <C> The type extending this class.
*
*/
public abstract class AbstractSQLUpdateClause<C extends AbstractSQLUpdateClause<C>> extends AbstractSQLClause<C> implements UpdateClause<C> {
protected static final Logger logger = Logger.getLogger(AbstractSQLUpdateClause.class.getName());
protected final RelationalPath<?> entity;
protected final List<SQLUpdateBatch> batches = new ArrayList<SQLUpdateBatch>();
protected Map<Path<?>, Expression<?>> updates = new LinkedHashMap<>();
protected QueryMetadata metadata = new DefaultQueryMetadata();
protected transient String queryString;
protected transient List<Object> constants;
public AbstractSQLUpdateClause(Connection connection, Configuration configuration, RelationalPath<?> entity) {
super(configuration, connection);
this.entity = entity;
metadata.addJoin(JoinType.DEFAULT, entity);
}
public AbstractSQLUpdateClause(Supplier<Connection> connection, Configuration configuration, RelationalPath<?> entity) {
super(configuration, connection);
this.entity = entity;
metadata.addJoin(JoinType.DEFAULT, entity);
}
/**
* Add the given String literal at the given position as a query flag
*
* @param position position
* @param flag query flag
* @return the current object
*/
public C addFlag(Position position, String flag) {
metadata.addFlag(new QueryFlag(position, flag));
return (C) this;
}
/**
* Add the given Expression at the given position as a query flag
*
* @param position position
* @param flag query flag
* @return the current object
*/
public C addFlag(Position position, Expression<?> flag) {
metadata.addFlag(new QueryFlag(position, flag));
return (C) this;
}
/**
* Add the current state of bindings as a batch item
*
* @return the current object
*/
public C addBatch() {
batches.add(new SQLUpdateBatch(metadata, updates));
updates = new LinkedHashMap<>();
metadata = new DefaultQueryMetadata();
metadata.addJoin(JoinType.DEFAULT, entity);
return (C) this;
}
@Override
public void clear() {
batches.clear();
updates = new LinkedHashMap<>();
metadata = new DefaultQueryMetadata();
metadata.addJoin(JoinType.DEFAULT, entity);
}
protected PreparedStatement createStatement() throws SQLException {
listeners.preRender(context);
SQLSerializer serializer = createSerializer();
serializer.serializeUpdate(metadata, entity, updates);
queryString = serializer.toString();
constants = serializer.getConstants();
logQuery(logger, queryString, constants);
context.addSQL(createBindings(metadata, serializer));
listeners.prepared(context);
listeners.prePrepare(context);
PreparedStatement stmt = connection().prepareStatement(queryString);
setParameters(stmt, serializer.getConstants(), serializer.getConstantPaths(), metadata.getParams());
context.addPreparedStatement(stmt);
listeners.prepared(context);
return stmt;
}
protected Collection<PreparedStatement> createStatements() throws SQLException {
boolean addBatches = !configuration.getUseLiterals();
listeners.preRender(context);
SQLSerializer serializer = createSerializer();
serializer.serializeUpdate(batches.get(0).getMetadata(), entity, batches.get(0).getUpdates());
queryString = serializer.toString();
constants = serializer.getConstants();
logQuery(logger, queryString, constants);
context.addSQL(createBindings(metadata, serializer));
listeners.rendered(context);
Map<String, PreparedStatement> stmts = new HashMap<>();
// add first batch
listeners.prePrepare(context);
PreparedStatement stmt = connection().prepareStatement(queryString);
setParameters(stmt, serializer.getConstants(), serializer.getConstantPaths(), metadata.getParams());
if (addBatches) {
stmt.addBatch();
}
stmts.put(serializer.toString(), stmt);
context.addPreparedStatement(stmt);
listeners.prepared(context);
// add other batches
for (int i = 1; i < batches.size(); i++) {
listeners.preRender(context);
serializer = createSerializer();
serializer.serializeUpdate(batches.get(i).getMetadata(), entity, batches.get(i).getUpdates());
context.addSQL(createBindings(metadata, serializer));
listeners.rendered(context);
stmt = stmts.get(serializer.toString());
if (stmt == null) {
listeners.prePrepare(context);
stmt = connection().prepareStatement(serializer.toString());
stmts.put(serializer.toString(), stmt);
context.addPreparedStatement(stmt);
listeners.prepared(context);
}
setParameters(stmt, serializer.getConstants(), serializer.getConstantPaths(), metadata.getParams());
if (addBatches) {
stmt.addBatch();
}
}
return stmts.values();
}
@Override
public long execute() {
context = startContext(connection(), metadata, entity);
PreparedStatement stmt = null;
Collection<PreparedStatement> stmts = null;
try {
if (batches.isEmpty()) {
stmt = createStatement();
listeners.notifyUpdate(entity, metadata, updates);
listeners.preExecute(context);
int rc = stmt.executeUpdate();
listeners.executed(context);
return rc;
} else {
stmts = createStatements();
listeners.notifyUpdates(entity, batches);
listeners.preExecute(context);
long rc = executeBatch(stmts);
listeners.executed(context);
return rc;
}
} catch (SQLException e) {
onException(context,e);
throw configuration.translate(queryString, constants, e);
} finally {
if (stmt != null) {
close(stmt);
}
if (stmts != null) {
close(stmts);
}
reset();
endContext(context);
}
}
@Override
public List<SQLBindings> getSQL() {
if (batches.isEmpty()) {
SQLSerializer serializer = createSerializer();
serializer.serializeUpdate(metadata, entity, updates);
return Collections.singletonList(createBindings(metadata, serializer));
} else {
List<SQLBindings> builder = new ArrayList<>();
for (SQLUpdateBatch batch : batches) {
SQLSerializer serializer = createSerializer();
serializer.serializeUpdate(batch.getMetadata(), entity, batch.getUpdates());
builder.add(createBindings(metadata, serializer));
}
return Collections.unmodifiableList(builder);
}
}
@Override
public <T> C set(Path<T> path, T value) {
if (value instanceof Expression<?>) {
updates.put(path, (Expression<?>) value);
} else if (value != null) {
updates.put(path, ConstantImpl.create(value));
} else {
setNull(path);
}
return (C) this;
}
@Override
public <T> C set(Path<T> path, Expression<? extends T> expression) {
if (expression != null) {
updates.put(path, expression);
} else {
setNull(path);
}
return (C) this;
}
@Override
public <T> C setNull(Path<T> path) {
updates.put(path, Null.CONSTANT);
return (C) this;
}
@Override
public C set(List<? extends Path<?>> paths, List<?> values) {
for (int i = 0; i < paths.size(); i++) {
if (values.get(i) instanceof Expression) {
updates.put(paths.get(i), (Expression<?>) values.get(i));
} else if (values.get(i) != null) {
updates.put(paths.get(i), ConstantImpl.create(values.get(i)));
} else {
updates.put(paths.get(i), Null.CONSTANT);
}
}
return (C) this;
}
public C where(Predicate p) {
metadata.addWhere(p);
return (C) this;
}
@Override
public C where(Predicate... o) {
for (Predicate p : o) {
metadata.addWhere(p);
}
return (C) this;
}
public C limit(@Range(from = 0, to = Integer.MAX_VALUE) long limit) {
metadata.setModifiers(QueryModifiers.limit(limit));
return (C) this;
}
@Override
public String toString() {
SQLSerializer serializer = createSerializer();
serializer.serializeUpdate(metadata, entity, updates);
return serializer.toString();
}
/**
* Populate the UPDATE clause with the properties of the given bean.
* The properties need to match the fields of the clause's entity instance.
* Primary key columns are skipped in the population.
*
* @param bean bean to use for population
* @return the current object
*/
@SuppressWarnings("unchecked")
public C populate(Object bean) {
return populate(bean, DefaultMapper.DEFAULT);
}
/**
* Populate the UPDATE clause with the properties of the given bean using the given Mapper.
*
* @param obj object to use for population
* @param mapper mapper to use
* @return the current object
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> C populate(T obj, Mapper<T> mapper) {
Collection<? extends Path<?>> primaryKeyColumns = entity.getPrimaryKey() != null
? entity.getPrimaryKey().getLocalColumns()
: Collections.<Path<?>>emptyList();
Map<Path<?>, Object> values = mapper.createMap(entity, obj);
for (Map.Entry<Path<?>, Object> entry : values.entrySet()) {
if (!primaryKeyColumns.contains(entry.getKey())) {
set((Path) entry.getKey(), entry.getValue());
}
}
return (C) this;
}
@Override
public boolean isEmpty() {
return updates.isEmpty() && batches.isEmpty();
}
@Override
public int getBatchCount() {
return batches.size();
}
}
|
3e11ef86885145d7a99f1faf15f26062cbef9147 | 61 | java | Java | src/main/java/chronosacaria/mcdm/entities/bases.java | chronosacaria/MinecraftDungeonsMobs | 9abe0cd8d79c2328473d8f760a8f20c930582e86 | [
"MIT"
] | null | null | null | src/main/java/chronosacaria/mcdm/entities/bases.java | chronosacaria/MinecraftDungeonsMobs | 9abe0cd8d79c2328473d8f760a8f20c930582e86 | [
"MIT"
] | null | null | null | src/main/java/chronosacaria/mcdm/entities/bases.java | chronosacaria/MinecraftDungeonsMobs | 9abe0cd8d79c2328473d8f760a8f20c930582e86 | [
"MIT"
] | null | null | null | 12.2 | 36 | 0.786885 | 7,556 | package chronosacaria.mcdm.entities;
public class bases {
}
|
3e11efc4db7c30df4ea9b396a8c94f878b848803 | 20,497 | java | Java | jphp-runtime/src/php/runtime/ext/core/classes/lib/SharedUtils.java | shisheng-1/jphp | eefaac6d8195025ba53c2b7b0996a9c128b2ffb7 | [
"Apache-2.0"
] | 903 | 2015-01-02T18:49:24.000Z | 2018-05-02T14:44:25.000Z | jphp-runtime/src/php/runtime/ext/core/classes/lib/SharedUtils.java | shisheng-1/jphp | eefaac6d8195025ba53c2b7b0996a9c128b2ffb7 | [
"Apache-2.0"
] | 137 | 2018-05-11T20:47:24.000Z | 2022-02-24T23:21:21.000Z | jphp-runtime/src/php/runtime/ext/core/classes/lib/SharedUtils.java | shisheng-1/jphp | eefaac6d8195025ba53c2b7b0996a9c128b2ffb7 | [
"Apache-2.0"
] | 129 | 2015-01-06T06:34:03.000Z | 2018-04-22T10:00:35.000Z | 29.115057 | 126 | 0.516954 | 7,557 | package php.runtime.ext.core.classes.lib;
import php.runtime.Memory;
import php.runtime.annotation.Reflection;
import php.runtime.annotation.Reflection.Arg;
import php.runtime.annotation.Reflection.Name;
import php.runtime.annotation.Reflection.Signature;
import php.runtime.env.Environment;
import php.runtime.env.TraceInfo;
import php.runtime.invoke.Invoker;
import php.runtime.lang.BaseObject;
import php.runtime.lang.ForeachIterator;
import php.runtime.lang.spl.Countable;
import php.runtime.lang.spl.Traversable;
import php.runtime.memory.ArrayMemory;
import php.runtime.memory.LongMemory;
import php.runtime.memory.ObjectMemory;
import php.runtime.memory.StringMemory;
import php.runtime.reflection.ClassEntity;
import java.util.*;
import static php.runtime.annotation.Reflection.Nullable;
@Name("php\\util\\Shared")
public class SharedUtils extends BaseObject {
protected static final Map<String, SharedValue> globalValue = new HashMap<String, SharedValue>();
public SharedUtils(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
private void __construct() {
}
@Signature
public static void resetAll() {
synchronized (globalValue) {
globalValue.clear();
}
}
@Signature
public static SharedValue reset(String name) {
synchronized (globalValue) {
return globalValue.remove(name);
}
}
@Signature
public static SharedValue value(Environment env, String name) throws Throwable {
return value(env, name, null);
}
@Signature
public static SharedValue value(Environment env, String name, @Nullable Invoker creator) throws Throwable {
SharedValue value = globalValue.get(name);
if (value != null) {
return value;
}
synchronized (globalValue) {
value = new SharedValue(env, (Memory) null);
SharedValue oldValue = globalValue.get(name);
if (oldValue != null) {
return oldValue;
}
if (creator != null) {
value.set(creator.call());
}
globalValue.put(name, value);
return value;
}
}
@Name("php\\util\\SharedMemory")
abstract public static class SharedMemory extends BaseObject {
public SharedMemory(Environment env) {
super(env);
}
public SharedMemory(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
synchronized public Memory synchronize(Invoker sync) throws Throwable {
if (sync.getArgumentCount() > 0) {
return sync.call(ObjectMemory.valueOf(this));
} else {
return sync.call();
}
}
}
@Name("php\\lang\\ThreadLocal")
public static class SharedThreadLocal extends BaseObject {
private ThreadLocal<Memory> local;
public SharedThreadLocal(Environment env, ThreadLocal<Memory> local) {
super(env);
this.local = local;
}
public SharedThreadLocal(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
public Memory __debugInfo(Environment env, Memory... args) {
ArrayMemory info = new ArrayMemory();
info.refOfIndex("*value").assign(local.get());
return info.toConstant();
}
@Signature(@Arg(value = "value", optional = @Reflection.Optional("null")))
public Memory __construct(Environment env, Memory... args) {
this.local = new ThreadLocal<Memory>() {
@Override
protected Memory initialValue() {
return args[0];
}
};
return Memory.NULL;
}
@Signature
public Memory get(Environment env, Memory... args) {
return this.local.get();
}
@Signature(@Arg("value"))
public Memory set(Environment env, Memory... args) {
this.local.set(args[0]);
return Memory.NULL;
}
@Signature
public Memory remove(Environment env, Memory... args) {
this.local.remove();
return Memory.NULL;
}
}
@Name("php\\util\\SharedValue")
public static class SharedValue extends SharedMemory {
protected Memory value = null;
public SharedValue(Environment env, Memory value) {
super(env);
this.value = value;
}
public SharedValue(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
synchronized public void __construct() {
value = null;
}
@Signature
synchronized public void __construct(Memory value) {
this.value = value;
}
@Signature
synchronized public Memory __debugInfo(Environment env, Memory... args) {
ArrayMemory info = new ArrayMemory();
info.refOfIndex("*value").assign(value);
return info.toConstant();
}
@Signature
synchronized public boolean isEmpty() {
return value == null;
}
@Signature
synchronized public Memory get() {
return value == null ? Memory.UNDEFINED : value;
}
@Signature
public Memory set(Memory value) {
return set(value, true);
}
@Signature
synchronized public Memory set(Memory value, boolean override) {
Memory result = this.value;
if (value == null || override) {
this.value = value;
}
return result == null ? Memory.UNDEFINED : result;
}
@Signature
synchronized public Memory remove() {
Memory result = value;
value = null;
return result == null ? Memory.UNDEFINED : result;
}
@Signature
synchronized public Memory getAndSet(Invoker update) throws Throwable {
Memory result = value == null ? Memory.UNDEFINED : value;
value = update.call(result);
return result;
}
@Signature
synchronized public Memory setAndGet(Invoker update) throws Throwable {
value = value == null ? Memory.UNDEFINED : value;
value = update.call(value);
return value;
}
@Signature
synchronized public Memory synchronize(Invoker sync) throws Throwable {
if (sync.getArgumentCount() > 0) {
return sync.call(ObjectMemory.valueOf(this));
} else {
return sync.call();
}
}
@Signature
synchronized public void __clone(Environment env, TraceInfo trace) throws Throwable {
if (value == null) {
this.value = null;
} else if (value.isObject()) {
this.value = value.clone(env, trace);
} else {
this.value = value.fast_toImmutable();
}
}
}
@Name("php\\util\\SharedCollection")
abstract public static class SharedCollection extends SharedMemory implements Countable, Traversable {
public SharedCollection(Environment env) {
super(env);
}
public SharedCollection(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
abstract public boolean isEmpty();
@Signature
abstract public void clear();
}
@Name("php\\util\\SharedQueue")
public static class SharedQueue extends SharedCollection {
protected Queue<Memory> queue;
public SharedQueue(Environment env, Queue<Memory> queue) {
super(env);
this.queue = queue;
}
public SharedQueue(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
public void __construct() {
queue = new LinkedList<Memory>();
}
@Signature
synchronized public Memory __debugInfo(Environment env, Memory... args) {
ArrayMemory info = new ArrayMemory();
info.refOfIndex("*queue").assign(ArrayMemory.ofCollection(queue));
return info.toConstant();
}
@Signature
public void __construct(ForeachIterator iterator) {
queue = new LinkedList<Memory>();
while (iterator.next()) {
queue.add(iterator.getValue().fast_toImmutable());
}
}
@Signature
synchronized public boolean isEmpty() {
return queue.isEmpty();
}
@Override
@Signature
synchronized public void clear() {
queue.clear();
}
@Signature
synchronized public boolean add(Memory value) {
return queue.offer(value);
}
@Signature
synchronized public Memory remove() {
return queue.remove();
}
@Signature
synchronized public Memory peek() {
return queue.peek();
}
@Signature
synchronized public Memory poll() {
return queue.poll();
}
@Override
@Signature
synchronized public Memory count(Environment env, Memory... args) {
return LongMemory.valueOf(queue.size());
}
@Override
synchronized public ForeachIterator getNewIterator(Environment env, boolean getReferences, boolean getKeyReferences) {
final Object mutex = this;
return new ForeachIterator(getReferences, getKeyReferences, false) {
private Iterator<Memory> iterator;
protected int index;
@Override
protected boolean init() {
reset();
synchronized (mutex) {
return !queue.isEmpty();
}
}
@Override
protected boolean nextValue() {
synchronized (mutex) {
if (iterator.hasNext()) {
index += 1;
currentKeyMemory = LongMemory.valueOf(index);
currentKey = currentKeyMemory;
currentValue = iterator.next();
if (!getReferences) {
currentValue = currentValue.toValue();
}
return true;
} else {
return false;
}
}
}
@Override
protected boolean prevValue() {
return false;
}
@Override
public void reset() {
synchronized (mutex) {
currentKeyMemory = Memory.CONST_INT_M1;
currentKey = currentKeyMemory;
index = -1;
iterator = queue.iterator();
}
}
};
}
@Override
public ForeachIterator getNewIterator(Environment env) {
return getNewIterator(env, false, false);
}
}
@Name("php\\util\\SharedStack")
public static class SharedStack extends SharedCollection {
protected Stack<Memory> stack;
public SharedStack(Environment env, Stack<Memory> stack) {
super(env);
this.stack = stack;
}
public SharedStack(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
public void __construct(ForeachIterator iterator) {
stack = new Stack<Memory>();
while (iterator.next()) {
stack.push(iterator.getValue().fast_toImmutable());
}
}
@Signature
public void __construct() {
stack = new Stack<Memory>();
}
@Signature
synchronized public Memory __debugInfo(Environment env, Memory... args) {
ArrayMemory info = new ArrayMemory();
info.refOfIndex("*stack").assign(ArrayMemory.ofCollection(stack));
return info.toConstant();
}
@Override
@Signature
synchronized public Memory count(Environment env, Memory... args) {
return LongMemory.valueOf(stack.size());
}
@Signature
synchronized public Memory push(Memory arg) {
return stack.push(arg);
}
@Signature
synchronized public boolean isEmpty() {
return stack.empty();
}
@Signature
synchronized public Memory pop() {
if (stack.empty()) {
return Memory.NULL;
}
return stack.pop();
}
@Signature
synchronized public Memory peek() {
if (stack.empty()) {
return Memory.NULL;
}
return stack.peek();
}
@Signature
synchronized public void clear() {
stack.clear();
}
@Signature
synchronized public void __clone() {
Stack<Memory> old = this.stack;
this.stack = new Stack<Memory>();
stack.addAll(old);
}
@Override
synchronized public ForeachIterator getNewIterator(Environment env, boolean getReferences, boolean getKeyReferences) {
final Object mutex = this;
return new ForeachIterator(getReferences, getKeyReferences, false) {
protected Iterator<Memory> iterator;
protected int index;
@Override
protected boolean init() {
reset();
synchronized (mutex) {
return !stack.isEmpty();
}
}
@Override
protected boolean nextValue() {
synchronized (mutex) {
if (iterator.hasNext()) {
index += 1;
currentKeyMemory = LongMemory.valueOf(index);
currentKey = currentKeyMemory;
currentValue = iterator.next();
if (!getReferences) {
currentValue = currentValue.toValue();
}
return true;
} else {
return false;
}
}
}
@Override
protected boolean prevValue() {
return false;
}
@Override
public void reset() {
synchronized (mutex) {
index = -1;
currentKeyMemory = Memory.CONST_INT_M1;
currentKey = currentKeyMemory;
iterator = stack.iterator();
}
}
};
}
@Override
public ForeachIterator getNewIterator(Environment env) {
return getNewIterator(env, false, false);
}
}
@Name("php\\util\\SharedMap")
public static class SharedMap extends SharedCollection {
protected Map<String, Memory> map;
public SharedMap(Environment env, Map<String, Memory> map) {
super(env);
this.map = map;
}
public SharedMap(Environment env, ClassEntity clazz) {
super(env, clazz);
}
@Signature
public void __construct(ForeachIterator iterator) {
map = new LinkedHashMap<String, Memory>();
while (iterator.next()) {
map.put(iterator.getKey().toString(), iterator.getValue().fast_toImmutable());
}
}
@Signature
public void __construct() {
map = new LinkedHashMap<String, Memory>();
}
@Signature
synchronized public Memory __debugInfo(Environment env, Memory... args) {
ArrayMemory info = new ArrayMemory();
info.refOfIndex("*map").assign(ArrayMemory.ofMap(map));
return info.toConstant();
}
@Override
@Signature
synchronized public boolean isEmpty() {
return map.isEmpty();
}
@Signature
synchronized public boolean has(String key) {
return map.containsKey(key);
}
@Signature
synchronized public Memory count(Environment env, Memory... args) {
return LongMemory.valueOf(map.size());
}
@Signature
synchronized public Memory get(String key) {
return get(key, Memory.UNDEFINED);
}
@Signature
synchronized public Memory getOrCreate(String key, Invoker create) throws Throwable {
Memory result = map.get(key);
if (result == null) {
result = create.call();
map.put(key, result);
}
return result;
}
@Signature
synchronized public Memory get(String key, Memory defaultValue) {
Memory result = map.get(key);
return result == null ? defaultValue : result;
}
@Signature
synchronized public Memory set(String key, Memory value, boolean override) {
if (override || map.get(key) == null) {
Memory result = map.put(key, value);
return result == null ? Memory.UNDEFINED : result;
}
return Memory.NULL;
}
@Signature
public Memory set(String key, Memory value) {
return set(key, value, true);
}
@Signature
synchronized public Memory remove(String key) {
Memory memory = map.remove(key);
return memory == null ? Memory.UNDEFINED : memory;
}
@Signature
synchronized public void clear() {
map.clear();
}
@Signature
synchronized public void __clone() {
this.map = new LinkedHashMap<String, Memory>(map);
}
@Override
synchronized public ForeachIterator getNewIterator(Environment env, boolean getReferences, boolean getKeyReferences) {
final Object mutex = this;
return new ForeachIterator(getReferences, getKeyReferences, false) {
private Iterator<Map.Entry<String, Memory>> entries;
@Override
protected boolean init() {
reset();
synchronized (mutex) {
return !map.isEmpty();
}
}
@Override
protected boolean nextValue() {
synchronized (mutex) {
if (entries.hasNext()) {
Map.Entry<String, Memory> entry = entries.next();
currentKey = entry.getKey();
currentKeyMemory = StringMemory.valueOf(currentKey.toString());
currentValue = entry.getValue();
if (!getReferences) {
currentValue = currentValue.toValue();
}
return true;
}
return false;
}
}
@Override
protected boolean prevValue() {
return false;
}
@Override
public void reset() {
synchronized (mutex) {
entries = map.entrySet().iterator();
}
}
};
}
@Override
public ForeachIterator getNewIterator(Environment env) {
return getNewIterator(env, false, false);
}
}
}
|
3e11f00397ed89035346900a1601ad1fead93e3e | 2,867 | java | Java | gui/src/main/java/org/dew/ljsa/gui/SessionManager.java | giosil/LJSA | a06f3270d63aa7f9bed62fcaca8c67b8f5dee195 | [
"Apache-2.0"
] | null | null | null | gui/src/main/java/org/dew/ljsa/gui/SessionManager.java | giosil/LJSA | a06f3270d63aa7f9bed62fcaca8c67b8f5dee195 | [
"Apache-2.0"
] | null | null | null | gui/src/main/java/org/dew/ljsa/gui/SessionManager.java | giosil/LJSA | a06f3270d63aa7f9bed62fcaca8c67b8f5dee195 | [
"Apache-2.0"
] | null | null | null | 22.224806 | 115 | 0.668992 | 7,558 | package org.dew.ljsa.gui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dew.rpc.util.Base64Coder;
import org.dew.swingup.ISessionManager;
import org.dew.swingup.ResourcesMgr;
import org.dew.swingup.User;
import org.dew.swingup.rpc.IRPCClient;
import org.dew.util.WUtil;
public
class SessionManager implements ISessionManager
{
private User user;
@Override
public
boolean isActive()
{
return user != null;
}
@Override
public
String getUserMessage()
{
return null;
}
@Override
public
User getUser()
{
return user;
}
@Override
public
void login(String sIdService, String sUserName, String sPassword, String sIdClient)
throws Exception
{
user = null;
AppUtil.clear();
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("Authorization", "Basic " + Base64Coder.encodeString(sUserName + ":" + sPassword));
String sWS_URL = ResourcesMgr.config.getProperty(ResourcesMgr.sAPP_RPC_URL);
String sWS_BAK = ResourcesMgr.config.getProperty(ResourcesMgr.sAPP_RPC_BAK);
IRPCClient rpcClient = ResourcesMgr.createIRPCClient();
rpcClient.init(sWS_URL, sWS_BAK);
rpcClient.setHeaders(headers);
List<String> services = null;
try {
services = WUtil.toListOfString(rpcClient.execute("CREDENZIALI.getServicesEnabled", Collections.EMPTY_LIST));
}
catch(Exception ex) {
String message = ex.getMessage();
System.err.println("Exception: " + ex);
if(message != null && message.length() > 0) {
if(message.indexOf("401") >= 0 || message.indexOf("403") >= 0) {
return;
}
}
throw new Exception("Servizio non disponibile");
}
if(services == null || services.size() == 0) {
return;
}
ResourcesMgr.setDefaultRPCClient(rpcClient);
user = new User();
user.setUserName(sUserName);
user.setPassword(sPassword);
user.setRole("admin");
user.setDatePassword(new Date());
user.setDateLastAccess(new Date());
user.setCurrentIdClient(sIdClient);
AppUtil.setServiziAbilitati(services);
}
@Override
public
void login(String sIdService, byte[] abSignature, String sIdClient)
throws Exception
{
user = null;
AppUtil.clear();
}
@Override
public
void logout()
{
user = null;
AppUtil.clear();
}
@Override
public
void changePassword(String sNewPassword)
throws Exception
{
throw new UnsupportedOperationException();
}
@Override
public
List<String> getClients(String sIdServices)
throws Exception
{
List<String> listResult = new ArrayList<String>(1);
listResult.add("DEFAULT");
return listResult;
}
}
|
3e11f0db7c7cb349bd8343c4a38738d8a4e2ff1f | 1,949 | java | Java | core/src/main/java/org/mobilitydata/gtfsvalidator/notice/InvalidEmailNotice.java | jasonad123/gtfs-validator | b8debd92c1b3e482d3203e7223c3e444001635d1 | [
"Apache-2.0"
] | 95 | 2020-03-16T13:17:41.000Z | 2022-03-31T07:45:17.000Z | core/src/main/java/org/mobilitydata/gtfsvalidator/notice/InvalidEmailNotice.java | jasonad123/gtfs-validator | b8debd92c1b3e482d3203e7223c3e444001635d1 | [
"Apache-2.0"
] | 836 | 2020-03-11T13:20:01.000Z | 2022-03-31T03:36:48.000Z | core/src/main/java/org/mobilitydata/gtfsvalidator/notice/InvalidEmailNotice.java | Trillium-Solutions/gtfs-validator | 7f8bc5d001211ee41900650052668f9cce59a20d | [
"Apache-2.0"
] | 55 | 2020-05-05T23:41:29.000Z | 2022-03-29T16:12:55.000Z | 34.192982 | 96 | 0.735762 | 7,559 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mobilitydata.gtfsvalidator.notice;
/**
* A field contains a malformed email address.
*
* <p>Definitions for valid emails are quite vague. We perform strict validation in the upstream
* using the Apache Commons EmailValidator.
*
* <p><a href="https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md">GTFS
* reference</a> does not provide any special requirements or standards.
*/
public class InvalidEmailNotice extends ValidationNotice {
private final String filename;
private final long csvRowNumber;
private final String fieldName;
private final String fieldValue;
/**
* Constructs a notice with given severity. This constructor may be used by users that want to
* lower the priority to {@code WARNING}.
*/
public InvalidEmailNotice(
String filename,
long csvRowNumber,
String fieldName,
String fieldValue,
SeverityLevel severityLevel) {
super(severityLevel);
this.filename = filename;
this.csvRowNumber = csvRowNumber;
this.fieldName = fieldName;
this.fieldValue = fieldValue;
}
/** Constructs a notice with the default severity {@code ERROR}. */
public InvalidEmailNotice(
String filename, long csvRowNumber, String fieldName, String fieldValue) {
this(filename, csvRowNumber, fieldName, fieldValue, SeverityLevel.ERROR);
}
}
|
3e11f13e6539c11aa0746740590e5c29e106b94f | 853 | java | Java | src/main/java/com/webank/wecross/restserver/RestRequest.java | qwdarrenyin/WeCross | 0519119a6adba89a3d482420afe89135c80a8b43 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/webank/wecross/restserver/RestRequest.java | qwdarrenyin/WeCross | 0519119a6adba89a3d482420afe89135c80a8b43 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/webank/wecross/restserver/RestRequest.java | qwdarrenyin/WeCross | 0519119a6adba89a3d482420afe89135c80a8b43 | [
"Apache-2.0"
] | null | null | null | 17.06 | 44 | 0.570926 | 7,560 | package com.webank.wecross.restserver;
public class RestRequest<T> {
private String version;
private String uri;
private String method;
private String sig;
private T data;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getSig() {
return sig;
}
public void setSig(String sig) {
this.sig = sig;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
3e11f2ff7059392efb9edd65d8d0eeb966413570 | 2,095 | java | Java | DecoHeads-Plugin/src/main/java/me/rayzr522/decoheads/gui/system/ClickEvent.java | crashdemons/DecoHeads | 5284a56195bcb37d43a8607e46caef6981c057c8 | [
"MIT"
] | 6 | 2016-06-10T19:00:02.000Z | 2021-03-12T16:46:27.000Z | DecoHeads-Plugin/src/main/java/me/rayzr522/decoheads/gui/system/ClickEvent.java | crashdemons/DecoHeads | 5284a56195bcb37d43a8607e46caef6981c057c8 | [
"MIT"
] | 37 | 2016-08-04T07:19:04.000Z | 2021-03-06T01:55:30.000Z | DecoHeads-Plugin/src/main/java/me/rayzr522/decoheads/gui/system/ClickEvent.java | crashdemons/DecoHeads | 5284a56195bcb37d43a8607e46caef6981c057c8 | [
"MIT"
] | 7 | 2018-01-09T17:11:48.000Z | 2021-04-16T17:32:24.000Z | 19.764151 | 90 | 0.578043 | 7,561 | /**
*
*/
package me.rayzr522.decoheads.gui.system;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
/**
* @author Rayzr
*/
public class ClickEvent {
private Player player;
private GUI gui;
private ItemStack item;
private ClickType type;
private int offsetX;
private int offsetY;
private boolean cancelled = true;
private boolean shouldClose = false;
ClickEvent(Player player, GUI gui, ItemStack item, ClickType type, Dimension offset) {
this.player = player;
this.gui = gui;
this.item = item;
this.type = type;
this.offsetX = offset.getX();
this.offsetY = offset.getY();
}
/**
* @return the player
*/
public Player getPlayer() {
return player;
}
/**
* @return the item
*/
public ItemStack getItem() {
return item;
}
/**
* @return the type
*/
public ClickType getType() {
return type;
}
/**
* @return the offsetX
*/
public int getOffsetX() {
return offsetX;
}
/**
* @return the offsetY
*/
public int getOffsetY() {
return offsetY;
}
/**
* @return Whether or not the event is cancelled. By default this is
* {@code true}.
*/
public boolean isCancelled() {
return cancelled;
}
/**
* @param cancelled whether or not the event should be cancelled
*/
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
/**
* @return Whether or not the GUI should close. By default this is
* {@code false}.
*/
public boolean shouldClose() {
return shouldClose;
}
/**
* @param shouldClose whether or not the GUI should close
*/
public void setShouldClose(boolean shouldClose) {
this.shouldClose = shouldClose;
}
/**
* @return The GUI that this event is associated with
*/
public GUI getGui() {
return gui;
}
}
|
3e11f4a796ab36d3b3ea0b10ba69f0268a3ccba0 | 459 | java | Java | jdroid-android/src/main/java/com/jdroid/android/usecase/listener/MuteUseCaseListener.java | vaginessa/jdroid | 9841989dc0834c10d8df044f808b2d25d966aad0 | [
"Apache-2.0"
] | null | null | null | jdroid-android/src/main/java/com/jdroid/android/usecase/listener/MuteUseCaseListener.java | vaginessa/jdroid | 9841989dc0834c10d8df044f808b2d25d966aad0 | [
"Apache-2.0"
] | null | null | null | jdroid-android/src/main/java/com/jdroid/android/usecase/listener/MuteUseCaseListener.java | vaginessa/jdroid | 9841989dc0834c10d8df044f808b2d25d966aad0 | [
"Apache-2.0"
] | null | null | null | 17 | 73 | 0.751634 | 7,562 | package com.jdroid.android.usecase.listener;
import com.jdroid.java.exception.AbstractException;
public class MuteUseCaseListener implements UseCaseListener {
@Override
public void onStartUseCase() {
// Do nothing
}
@Override
public void onUpdateUseCase() {
// Do nothing
}
@Override
public void onFinishFailedUseCase(AbstractException abstractException) {
// Do nothing
}
@Override
public void onFinishUseCase() {
// Do nothing
}
}
|
3e11f4aeb6b5c81b3ac90f6f39bacf4c77c3eee5 | 2,148 | java | Java | swagger/swagger_raw_autocode/tapi-topo/src/gen/java/es/tid/topologyModuleBase/TAPITopoModel/model/GetNodeEdgePointDetailsRPCOutputSchema.java | muaj07/Netphony-Protocols | 4b9fc46765f83b632f20484d0b745ec92a208a67 | [
"Apache-2.0"
] | 1 | 2021-02-19T16:11:47.000Z | 2021-02-19T16:11:47.000Z | swagger/swagger_raw_autocode/tapi-topo/src/gen/java/es/tid/topologyModuleBase/TAPITopoModel/model/GetNodeEdgePointDetailsRPCOutputSchema.java | muaj07/Netphony-Protocols | 4b9fc46765f83b632f20484d0b745ec92a208a67 | [
"Apache-2.0"
] | null | null | null | swagger/swagger_raw_autocode/tapi-topo/src/gen/java/es/tid/topologyModuleBase/TAPITopoModel/model/GetNodeEdgePointDetailsRPCOutputSchema.java | muaj07/Netphony-Protocols | 4b9fc46765f83b632f20484d0b745ec92a208a67 | [
"Apache-2.0"
] | 1 | 2020-11-23T12:34:33.000Z | 2020-11-23T12:34:33.000Z | 27.538462 | 137 | 0.723929 | 7,563 | package es.tid.topologyModuleBase.TAPITopoModel.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import es.tid.topologyModuleBase.TAPITopoModel.model.NodeEdgePoint;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* GetNodeEdgePointDetailsRPCOutputSchema
*/
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2017-02-10T14:31:20.668+01:00")
public class GetNodeEdgePointDetailsRPCOutputSchema {
private NodeEdgePoint nodeEdgePoint = null;
public GetNodeEdgePointDetailsRPCOutputSchema nodeEdgePoint(NodeEdgePoint nodeEdgePoint) {
this.nodeEdgePoint = nodeEdgePoint;
return this;
}
/**
* Get nodeEdgePoint
* @return nodeEdgePoint
**/
@ApiModelProperty(value = "")
public NodeEdgePoint getNodeEdgePoint() {
return nodeEdgePoint;
}
public void setNodeEdgePoint(NodeEdgePoint nodeEdgePoint) {
this.nodeEdgePoint = nodeEdgePoint;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetNodeEdgePointDetailsRPCOutputSchema getNodeEdgePointDetailsRPCOutputSchema = (GetNodeEdgePointDetailsRPCOutputSchema) o;
return Objects.equals(this.nodeEdgePoint, getNodeEdgePointDetailsRPCOutputSchema.nodeEdgePoint);
}
@Override
public int hashCode() {
return Objects.hash(nodeEdgePoint);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GetNodeEdgePointDetailsRPCOutputSchema {\n");
sb.append(" nodeEdgePoint: ").append(toIndentedString(nodeEdgePoint)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e11f4e59227cac52f93d28a4e08b4752b15db58 | 592 | java | Java | src/main/java/at/codetales/iotflux/IotfluxApplication.java | Chakrakin/iotflux | 629fe43ad7e5005585cfffae000afc3d8e42b9e1 | [
"MIT"
] | 10 | 2020-02-07T17:47:57.000Z | 2021-12-11T23:08:05.000Z | src/main/java/at/codetales/iotflux/IotfluxApplication.java | Chakrakin/iotflux | 629fe43ad7e5005585cfffae000afc3d8e42b9e1 | [
"MIT"
] | null | null | null | src/main/java/at/codetales/iotflux/IotfluxApplication.java | Chakrakin/iotflux | 629fe43ad7e5005585cfffae000afc3d8e42b9e1 | [
"MIT"
] | 2 | 2020-03-22T20:10:08.000Z | 2021-04-27T07:12:44.000Z | 42.285714 | 111 | 0.858108 | 7,564 | package at.codetales.iotflux;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
public class IotfluxApplication {
public static void main(String[] args) {
SpringApplication.run(IotfluxApplication.class, args);
}
}
|
3e11f52c9a6466a390a9b096ffe198f82dd25f7f | 1,441 | java | Java | fluent-job/fluent-job-api/src/main/java/org/apache/oozie/fluentjob/api/factory/WorkflowFactory.java | martin-g/oozie | b6575162a7979ee655c2397b8a5ba3153fc03ae9 | [
"Apache-2.0"
] | 589 | 2015-01-12T09:17:08.000Z | 2022-03-31T03:05:40.000Z | fluent-job/fluent-job-api/src/main/java/org/apache/oozie/fluentjob/api/factory/WorkflowFactory.java | martin-g/oozie | b6575162a7979ee655c2397b8a5ba3153fc03ae9 | [
"Apache-2.0"
] | 33 | 2015-05-22T08:11:00.000Z | 2022-02-22T09:19:19.000Z | fluent-job/fluent-job-api/src/main/java/org/apache/oozie/fluentjob/api/factory/WorkflowFactory.java | martin-g/oozie | b6575162a7979ee655c2397b8a5ba3153fc03ae9 | [
"Apache-2.0"
] | 495 | 2015-01-07T04:29:58.000Z | 2022-03-23T02:50:16.000Z | 40.027778 | 109 | 0.766135 | 7,565 | /**
* 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.oozie.fluentjob.api.factory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.oozie.fluentjob.api.workflow.Workflow;
/**
* A marker interface telling callers the implementor can and will create a {@link Workflow} instance.
* <p>
* All classes meant to be used as an input for {@code OozieCLI}'s Jobs API {@code .jar} checking, submission
* or running methods must implement {@code WorkflowFactory}.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public interface WorkflowFactory {
Workflow create();
}
|
3e11f55c2c5cfa21f25f6dbaecb8d7f2c61fb04a | 2,721 | java | Java | src/it/projects/step-by-step/src/main/java/ru/akman/hello/Main.java | HGuillemet/jpackage-maven-plugin | 07a8394114ccfcbb1228f9c51111213044ae004b | [
"Apache-2.0"
] | 12 | 2020-07-21T15:13:54.000Z | 2022-03-15T13:15:52.000Z | src/it/projects/step-by-step/src/main/java/ru/akman/hello/Main.java | HGuillemet/jpackage-maven-plugin | 07a8394114ccfcbb1228f9c51111213044ae004b | [
"Apache-2.0"
] | 6 | 2020-10-02T19:55:54.000Z | 2022-03-05T14:07:26.000Z | src/it/projects/step-by-step/src/main/java/ru/akman/hello/Main.java | HGuillemet/jpackage-maven-plugin | 07a8394114ccfcbb1228f9c51111213044ae004b | [
"Apache-2.0"
] | 5 | 2021-12-01T11:17:48.000Z | 2022-03-10T12:18:06.000Z | 22.303279 | 74 | 0.658581 | 7,566 | /*
Copyright (C) 2020 - 2021 Alexander Kapitman
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 ru.akman.hello;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import static ru.akman.hello.Util.*;
/**
* Main application class
*/
@Command(
name = "hello",
mixinStandardHelpOptions = true,
version = "Version 1.0",
description = "Simple JavaFX application"
)
public class Main extends Application implements Callable<Integer> {
/**
* Default logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
/**
* Debug mode.
*/
@Option(
names = {"-d", "--debug"},
description = "Log in debug mode."
)
private boolean isDebugEnabled = false;
/**
* GUI mode.
*/
@Option(
names = {"-g", "--gui"},
description = "Run application in GUI mode."
)
private boolean isGUIEnabled = false;
/**
* Entry point.
*/
public static void main(String... args) {
int exitCode = new CommandLine(new Main()).execute(args);
System.exit(exitCode);
}
/**
* Command line user interface.
*
* @return Exit code
*/
@Override
public Integer call() throws Exception {
if (isDebugEnabled) {
setRootLoggerLevelToDebug();
}
if (LOG.isDebugEnabled()) {
LOG.debug("BEGIN");
}
if (isGUIEnabled) {
Application.launch();
}
if (LOG.isDebugEnabled()) {
LOG.debug("END");
}
return 0;
}
/**
* Graphic user interface start.
*
* @param stage Main stage
*/
@Override
public void start(final Stage stage) {
if (LOG.isDebugEnabled()) {
LOG.debug("GUI start");
}
stage.setTitle("Hello Modular Application");
stage.setScene(new Scene(new Group(), 800, 600));
stage.centerOnScreen();
stage.show();
}
/**
* Graphic user interface stop.
*/
@Override
public void stop() {
if (LOG.isDebugEnabled()) {
LOG.debug("GUI stop");
}
}
}
|
3e11f5bbbe3f7b3c352b1cc69a0057026f7c2c02 | 11,412 | java | Java | src/main/java/edu/harvard/seas/pl/abcdatalog/engine/bottomup/sequential/SemiNaiveEvalManager.java | HarvardPL/AbcDatalog | f60f3f9373b97da98ecf442f1908981553437829 | [
"BSD-3-Clause"
] | 15 | 2021-09-07T21:39:05.000Z | 2022-03-15T22:32:08.000Z | src/main/java/edu/harvard/seas/pl/abcdatalog/engine/bottomup/sequential/SemiNaiveEvalManager.java | HarvardPL/AbcDatalog | f60f3f9373b97da98ecf442f1908981553437829 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/edu/harvard/seas/pl/abcdatalog/engine/bottomup/sequential/SemiNaiveEvalManager.java | HarvardPL/AbcDatalog | f60f3f9373b97da98ecf442f1908981553437829 | [
"BSD-3-Clause"
] | 1 | 2021-11-19T19:36:40.000Z | 2021-11-19T19:36:40.000Z | 38.295302 | 107 | 0.747985 | 7,567 | package edu.harvard.seas.pl.abcdatalog.engine.bottomup.sequential;
/*-
* #%L
* AbcDatalog
* %%
* Copyright (C) 2016 - 2021 President and Fellows of Harvard College
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the President and Fellows of Harvard College nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import edu.harvard.seas.pl.abcdatalog.ast.BinaryDisunifier;
import edu.harvard.seas.pl.abcdatalog.ast.BinaryUnifier;
import edu.harvard.seas.pl.abcdatalog.ast.Clause;
import edu.harvard.seas.pl.abcdatalog.ast.NegatedAtom;
import edu.harvard.seas.pl.abcdatalog.ast.PositiveAtom;
import edu.harvard.seas.pl.abcdatalog.ast.PredicateSym;
import edu.harvard.seas.pl.abcdatalog.ast.Premise;
import edu.harvard.seas.pl.abcdatalog.ast.validation.DatalogValidationException;
import edu.harvard.seas.pl.abcdatalog.ast.validation.DatalogValidator;
import edu.harvard.seas.pl.abcdatalog.ast.validation.StratifiedNegationValidator;
import edu.harvard.seas.pl.abcdatalog.ast.validation.StratifiedProgram;
import edu.harvard.seas.pl.abcdatalog.ast.validation.UnstratifiedProgram;
import edu.harvard.seas.pl.abcdatalog.ast.validation.DatalogValidator.ValidClause;
import edu.harvard.seas.pl.abcdatalog.ast.visitors.HeadVisitor;
import edu.harvard.seas.pl.abcdatalog.ast.visitors.PremiseVisitor;
import edu.harvard.seas.pl.abcdatalog.ast.visitors.PremiseVisitorBuilder;
import edu.harvard.seas.pl.abcdatalog.engine.bottomup.AnnotatedAtom;
import edu.harvard.seas.pl.abcdatalog.engine.bottomup.ClauseEvaluator;
import edu.harvard.seas.pl.abcdatalog.engine.bottomup.EvalManagerWithProvenance;
import edu.harvard.seas.pl.abcdatalog.engine.bottomup.SemiNaiveClauseAnnotator;
import edu.harvard.seas.pl.abcdatalog.engine.bottomup.SemiNaiveClauseAnnotator.SemiNaiveClause;
import edu.harvard.seas.pl.abcdatalog.util.Utilities;
import edu.harvard.seas.pl.abcdatalog.util.datastructures.ConcurrentFactIndexer;
import edu.harvard.seas.pl.abcdatalog.util.datastructures.FactIndexer;
import edu.harvard.seas.pl.abcdatalog.util.datastructures.FactIndexerFactory;
import edu.harvard.seas.pl.abcdatalog.util.datastructures.IndexableFactCollection;
import edu.harvard.seas.pl.abcdatalog.util.substitution.ClauseSubstitution;
import edu.harvard.seas.pl.abcdatalog.util.substitution.SubstitutionUtils;
public class SemiNaiveEvalManager implements EvalManagerWithProvenance {
private final ConcurrentFactIndexer<Set<PositiveAtom>> allFacts = FactIndexerFactory
.createConcurrentSetFactIndexer();
private final List<StratumEvaluator> stratumEvals = new ArrayList<>();
private final boolean collectProv;
private final ConcurrentHashMap<PositiveAtom, Clause> justifications = new ConcurrentHashMap<>();
public SemiNaiveEvalManager(boolean collectProv) {
this.collectProv = collectProv;
}
@SuppressWarnings("unchecked")
@Override
public synchronized void initialize(Set<Clause> program) throws DatalogValidationException {
UnstratifiedProgram prog = (new DatalogValidator()).withBinaryDisunificationInRuleBody()
.withBinaryUnificationInRuleBody().withAtomNegationInRuleBody().validate(program);
StratifiedProgram stratProg = StratifiedNegationValidator.validate(prog);
List<Set<PredicateSym>> strata = stratProg.getStrata();
int nstrata = strata.size();
Map<PredicateSym, Set<SemiNaiveClause>>[] firstRoundRules = new HashMap[nstrata];
Map<PredicateSym, Set<SemiNaiveClause>>[] laterRoundRules = new HashMap[nstrata];
Set<PositiveAtom>[] initialIdbFacts = new HashSet[nstrata];
for (int i = 0; i < nstrata; ++i) {
firstRoundRules[i] = new HashMap<>();
laterRoundRules[i] = new HashMap<>();
initialIdbFacts[i] = new HashSet<>();
}
Map<PredicateSym, Integer> predToStratumMap = stratProg.getPredToStratumMap();
HeadVisitor<Void, PredicateSym> getHeadPred = new HeadVisitor<Void, PredicateSym>() {
@Override
public PredicateSym visit(PositiveAtom atom, Void state) {
return atom.getPred();
}
};
for (ValidClause clause : prog.getRules()) {
PredicateSym pred = clause.getHead().accept(getHeadPred, null);
int stratum = predToStratumMap.get(pred);
// Treat IDB predicates from earlier strata as EDB predicates.
Set<PredicateSym> idbs = strata.get(stratum);
PremiseVisitor<Boolean, Boolean> checkForIdbPred = (new PremiseVisitorBuilder<Boolean, Boolean>())
.onPositiveAtom((atom, idb) -> idbs.contains(atom.getPred()) || idb).or((premise, idb) -> idb);
SemiNaiveClauseAnnotator annotator = new SemiNaiveClauseAnnotator(idbs);
boolean hasIdbPred = false;
for (Premise c : clause.getBody()) {
hasIdbPred = c.accept(checkForIdbPred, hasIdbPred);
}
for (SemiNaiveClause rule : annotator.annotate(clause)) {
PredicateSym bodyPred = rule.getFirstAtom().getPred();
if (hasIdbPred) {
Utilities.getSetFromMap(laterRoundRules[stratum], bodyPred).add(rule);
} else {
Utilities.getSetFromMap(firstRoundRules[stratum], bodyPred).add(rule);
}
}
}
Set<PredicateSym> edbs = prog.getEdbPredicateSyms();
for (PositiveAtom fact : prog.getInitialFacts()) {
if (edbs.contains(fact.getPred())) {
allFacts.add(fact);
} else {
initialIdbFacts[predToStratumMap.get(fact.getPred())].add(fact);
}
if (collectProv) {
justifications.put(fact, new Clause(fact, Collections.emptyList()));
}
}
for (int i = 0; i < nstrata; ++i) {
stratumEvals.add(new StratumEvaluator(firstRoundRules[i], laterRoundRules[i], initialIdbFacts[i]));
}
}
@Override
public synchronized IndexableFactCollection eval() {
for (StratumEvaluator se : stratumEvals) {
se.eval();
}
return allFacts;
}
@Override
public Clause getJustification(PositiveAtom fact) {
return justifications.get(fact);
}
public static Clause stripSemiNaiveClause(SemiNaiveClause cl) {
List<Premise> newBody = new ArrayList<>();
for (Premise p : cl.getBody()) {
newBody.add(p.accept(new PremiseVisitor<Void, Premise>() {
@Override
public Premise visit(PositiveAtom atom, Void state) {
return atom;
}
@Override
public Premise visit(AnnotatedAtom atom, Void state) {
return atom.asUnannotatedAtom();
}
@Override
public Premise visit(BinaryUnifier u, Void state) {
return u;
}
@Override
public Premise visit(BinaryDisunifier u, Void state) {
return u;
}
@Override
public Premise visit(NegatedAtom atom, Void state) {
return atom;
}
}, null));
}
return new Clause(cl.getHead(), newBody);
}
private class StratumEvaluator {
private ConcurrentFactIndexer<Set<PositiveAtom>> idbsPrev = FactIndexerFactory
.createConcurrentSetFactIndexer();
private ConcurrentFactIndexer<Set<PositiveAtom>> deltaOld = FactIndexerFactory
.createConcurrentSetFactIndexer();
private ConcurrentFactIndexer<Set<PositiveAtom>> deltaNew = FactIndexerFactory
.createConcurrentSetFactIndexer();
private final Map<PredicateSym, Set<ClauseEvaluator>> firstRoundEvals;
private final Map<PredicateSym, Set<ClauseEvaluator>> laterRoundEvals;
private final Set<PositiveAtom> initialIdbFacts;
public StratumEvaluator(Map<PredicateSym, Set<SemiNaiveClause>> firstRoundRules,
Map<PredicateSym, Set<SemiNaiveClause>> laterRoundRules, Set<PositiveAtom> initialIdbFacts) {
Function<Map<PredicateSym, Set<SemiNaiveClause>>, Map<PredicateSym, Set<ClauseEvaluator>>> translate = (
clauseMap) -> {
Map<PredicateSym, Set<ClauseEvaluator>> evalMap = new HashMap<>();
for (Map.Entry<PredicateSym, Set<SemiNaiveClause>> entry : clauseMap.entrySet()) {
Set<ClauseEvaluator> s = new HashSet<>();
for (SemiNaiveClause cl : entry.getValue()) {
Clause stripped = stripSemiNaiveClause(cl);
s.add(new ClauseEvaluator(cl, (fact, subst) -> addFact(fact, subst, stripped), this::getFacts));
}
evalMap.put(entry.getKey(), s);
}
return evalMap;
};
firstRoundEvals = translate.apply(firstRoundRules);
laterRoundEvals = translate.apply(laterRoundRules);
this.initialIdbFacts = initialIdbFacts;
}
public void eval() {
deltaNew.addAll(this.initialIdbFacts);
evalOneRound(allFacts, firstRoundEvals);
while (evalOneRound(deltaOld, laterRoundEvals)) {
// Loop...
}
}
private boolean evalOneRound(FactIndexer index, Map<PredicateSym, Set<ClauseEvaluator>> rules) {
for (PredicateSym pred : index.getPreds()) {
Set<ClauseEvaluator> evals = rules.get(pred);
if (evals != null) {
for (ClauseEvaluator eval : evals) {
for (PositiveAtom fact : index.indexInto(pred)) {
eval.evaluate(fact);
}
}
}
}
if (deltaNew.isEmpty()) {
return false;
}
idbsPrev.addAll(deltaOld);
allFacts.addAll(deltaNew);
deltaOld = deltaNew;
deltaNew = FactIndexerFactory.createConcurrentSetFactIndexer();
return true;
}
private boolean addFact(PositiveAtom fact, ClauseSubstitution subst, Clause stripped) {
fact = fact.applySubst(subst);
Set<PositiveAtom> set = allFacts.indexInto(fact);
if (!set.contains(fact)) {
deltaNew.add(fact);
if (collectProv) {
justifications.put(fact, SubstitutionUtils.applyToClause(subst, stripped));
}
return true;
}
return false;
}
private Iterable<PositiveAtom> getFacts(AnnotatedAtom atom, ClauseSubstitution subst) {
Set<PositiveAtom> r = null;
PositiveAtom unannotated = atom.asUnannotatedAtom();
switch (atom.getAnnotation()) {
case EDB:
// Fall through...
case IDB:
r = allFacts.indexInto(unannotated, subst);
break;
case IDB_PREV:
r = idbsPrev.indexInto(unannotated, subst);
break;
case DELTA:
r = deltaOld.indexInto(unannotated, subst);
break;
default:
assert false;
}
return r;
}
}
}
|
3e11f60579ef3ed2806daff6dd9feb753be336ea | 522 | java | Java | data-center/data-broker/src/main/java/com/liuyao/cloud/host/manager/api/beans/Beats.java | liuyao2303/edge | 9ab73af5693c722ba64ac914744211fdd98559c0 | [
"Apache-2.0"
] | null | null | null | data-center/data-broker/src/main/java/com/liuyao/cloud/host/manager/api/beans/Beats.java | liuyao2303/edge | 9ab73af5693c722ba64ac914744211fdd98559c0 | [
"Apache-2.0"
] | null | null | null | data-center/data-broker/src/main/java/com/liuyao/cloud/host/manager/api/beans/Beats.java | liuyao2303/edge | 9ab73af5693c722ba64ac914744211fdd98559c0 | [
"Apache-2.0"
] | null | null | null | 16.3125 | 48 | 0.565134 | 7,568 | package com.liuyao.cloud.host.manager.api.beans;
public class Beats {
private String name;
private String addr;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
3e11f657119b26e6c28b3d3375040a6dc6929b18 | 2,012 | java | Java | src/main/java/com/tencentcloudapi/emr/v20190103/models/LoginSettings.java | tencent-carryfan/tencentcloud-sdk-java | 45d07c9910a1614ba03caddae6a158abe0a6bce6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tencentcloudapi/emr/v20190103/models/LoginSettings.java | tencent-carryfan/tencentcloud-sdk-java | 45d07c9910a1614ba03caddae6a158abe0a6bce6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tencentcloudapi/emr/v20190103/models/LoginSettings.java | tencent-carryfan/tencentcloud-sdk-java | 45d07c9910a1614ba03caddae6a158abe0a6bce6 | [
"Apache-2.0"
] | null | null | null | 24.839506 | 83 | 0.664016 | 7,569 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.emr.v20190103.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class LoginSettings extends AbstractModel{
/**
* Password
*/
@SerializedName("Password")
@Expose
private String Password;
/**
* Public Key
*/
@SerializedName("PublicKeyId")
@Expose
private String PublicKeyId;
/**
* 获取Password
* @return Password Password
*/
public String getPassword() {
return this.Password;
}
/**
* 设置Password
* @param Password Password
*/
public void setPassword(String Password) {
this.Password = Password;
}
/**
* 获取Public Key
* @return PublicKeyId Public Key
*/
public String getPublicKeyId() {
return this.PublicKeyId;
}
/**
* 设置Public Key
* @param PublicKeyId Public Key
*/
public void setPublicKeyId(String PublicKeyId) {
this.PublicKeyId = PublicKeyId;
}
/**
* 内部实现,用户禁止调用
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "Password", this.Password);
this.setParamSimple(map, prefix + "PublicKeyId", this.PublicKeyId);
}
}
|
3e11f68111b5bcd74072c794cf52b3a71ab7ca5c | 689 | java | Java | grpc-adapter/src/main/java/de/cotto/lndmanagej/grpc/GrpcPolicy.java | C-Otto/lnd-manageJ | c06487faeb47f153199beb5b71da737d358ad1c5 | [
"MIT"
] | 6 | 2022-03-09T23:32:29.000Z | 2022-03-21T23:04:29.000Z | grpc-adapter/src/main/java/de/cotto/lndmanagej/grpc/GrpcPolicy.java | C-Otto/lnd-manageJ | c06487faeb47f153199beb5b71da737d358ad1c5 | [
"MIT"
] | 12 | 2022-03-09T22:47:51.000Z | 2022-03-27T16:34:37.000Z | grpc-adapter/src/main/java/de/cotto/lndmanagej/grpc/GrpcPolicy.java | C-Otto/lnd-manageJ | c06487faeb47f153199beb5b71da737d358ad1c5 | [
"MIT"
] | null | null | null | 28.708333 | 70 | 0.676343 | 7,570 | package de.cotto.lndmanagej.grpc;
import de.cotto.lndmanagej.model.Coins;
import de.cotto.lndmanagej.model.Policy;
import lnrpc.RoutingPolicy;
import org.springframework.stereotype.Component;
@Component
public class GrpcPolicy {
public GrpcPolicy() {
// default constructor
}
public Policy toPolicy(RoutingPolicy routingPolicy) {
return new Policy(
routingPolicy.getFeeRateMilliMsat(),
Coins.ofMilliSatoshis(routingPolicy.getFeeBaseMsat()),
!routingPolicy.getDisabled(),
routingPolicy.getTimeLockDelta(),
Coins.ofMilliSatoshis(routingPolicy.getMaxHtlcMsat())
);
}
}
|
3e11f6cf1b24ef94c41cb9ad630454bb8209fcd5 | 848 | java | Java | plugins/jreleaser-maven-plugin/src/main/java/org/jreleaser/maven/plugin/Releaser.java | mthmulders/jreleaser | 495d8697fd03c7ec34cc5035264b5b412cbb65b6 | [
"Apache-2.0"
] | 455 | 2021-03-22T16:53:44.000Z | 2022-03-29T12:52:53.000Z | plugins/jreleaser-maven-plugin/src/main/java/org/jreleaser/maven/plugin/Releaser.java | mthmulders/jreleaser | 495d8697fd03c7ec34cc5035264b5b412cbb65b6 | [
"Apache-2.0"
] | 656 | 2021-03-20T14:04:54.000Z | 2022-03-29T19:04:29.000Z | plugins/jreleaser-maven-plugin/src/main/java/org/jreleaser/maven/plugin/Releaser.java | mthmulders/jreleaser | 495d8697fd03c7ec34cc5035264b5b412cbb65b6 | [
"Apache-2.0"
] | 43 | 2021-03-28T18:59:44.000Z | 2022-03-12T17:50:48.000Z | 30.285714 | 75 | 0.740566 | 7,571 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2020-2022 The JReleaser 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jreleaser.maven.plugin;
import org.jreleaser.model.TimeoutAware;
/**
* @author Andres Almiray
* @since 0.1.0
*/
public interface Releaser extends EnabledAware, TimeoutAware {
}
|
3e11f73f8407af66fc359829a8a94ce0adb2e9ef | 6,233 | java | Java | src/main/java/de/tum/in/www1/artemis/repository/ModelingSubmissionRepository.java | mahdi-dhaini/Artemis | 6d63c0eb7c8057dcead9dc16348de7ebba5e7ee3 | [
"MIT"
] | 213 | 2019-06-20T19:22:05.000Z | 2022-03-29T14:49:53.000Z | src/main/java/de/tum/in/www1/artemis/repository/ModelingSubmissionRepository.java | mahdi-dhaini/Artemis | 6d63c0eb7c8057dcead9dc16348de7ebba5e7ee3 | [
"MIT"
] | 2,992 | 2019-06-19T13:40:38.000Z | 2022-03-31T21:17:12.000Z | src/main/java/de/tum/in/www1/artemis/repository/ModelingSubmissionRepository.java | mahdi-dhaini/Artemis | 6d63c0eb7c8057dcead9dc16348de7ebba5e7ee3 | [
"MIT"
] | 365 | 2019-07-30T11:30:58.000Z | 2022-03-22T07:23:16.000Z | 62.33 | 233 | 0.776673 | 7,572 | package de.tum.in.www1.artemis.repository;
import static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import de.tum.in.www1.artemis.domain.modeling.ModelingSubmission;
import de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;
/**
* Spring Data JPA repository for the ModelingSubmission entity.
*/
@SuppressWarnings("unused")
@Repository
public interface ModelingSubmissionRepository extends JpaRepository<ModelingSubmission, Long> {
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.results r left join fetch r.assessor where submission.id = :#{#submissionId}")
Optional<ModelingSubmission> findByIdWithEagerResult(@Param("submissionId") Long submissionId);
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.results r left join fetch r.feedbacks left join fetch r.assessor where submission.id = :#{#submissionId}")
Optional<ModelingSubmission> findByIdWithEagerResultAndAssessorAndFeedback(@Param("submissionId") Long submissionId);
/**
* Load the modeling submission with the given id together with its result, the feedback list of the result, the assessor of the result, its participation and all results of
* the participation.
*
* @param submissionId the id of the modeling submission that should be loaded from the database
* @return the modeling submission with its result, the feedback list of the result, the assessor of the result, its participation and all results of the participation
*/
@EntityGraph(type = LOAD, attributePaths = { "results", "results.feedbacks", "results.assessor", "participation", "participation.results" })
Optional<ModelingSubmission> findWithResultsFeedbacksAssessorAndParticipationResultsById(Long submissionId);
@EntityGraph(type = LOAD, attributePaths = { "results" })
Optional<ModelingSubmission> findWithEagerResultById(Long submissionId);
/**
* Load all modeling submissions with the given ids. Load every submission together with its result, the feedback list of the result, the assessor of the result, its
* participation and all results of the participation.
*
* @param submissionIds the ids of the modeling submissions that should be loaded from the database
* @return the list of modeling submissions with their results, the feedback list of the results, the assessor of the results, their participation and all results of the
* participations
*/
@EntityGraph(type = LOAD, attributePaths = { "results", "results.feedbacks", "results.assessor", "participation", "participation.results" })
List<ModelingSubmission> findWithEagerResultsFeedbacksAssessorAndParticipationResultsByIdIn(Collection<Long> submissionIds);
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.results r left join fetch r.feedbacks where submission.participation.exercise.id = :#{#exerciseId} and submission.submitted = true")
List<ModelingSubmission> findSubmittedByExerciseIdWithEagerResultsAndFeedback(@Param("exerciseId") Long exerciseId);
@Query("select distinct submission from ModelingSubmission submission left join fetch submission.results r left join fetch r.feedbacks where submission.exampleSubmission = true and submission.id = :#{#submissionId}")
Optional<ModelingSubmission> findExampleSubmissionByIdWithEagerResult(@Param("submissionId") Long submissionId);
/**
* @param courseId the course we are interested in
* @param submitted boolean to check if an exercise has been submitted or not
* @return number of submissions belonging to courseId with submitted status
*/
long countByParticipation_Exercise_Course_IdAndSubmitted(Long courseId, boolean submitted);
/**
* Get the modeling submission with the given id from the database. Throws an EntityNotFoundException if no submission could be found for the given id.
*
* @param submissionId the id of the submission that should be loaded from the database
* @return the modeling submission with the given id
*/
default ModelingSubmission findOne(Long submissionId) {
return findById(submissionId).orElseThrow(() -> new EntityNotFoundException("Modeling Submission", submissionId));
}
/**
* Get the modeling submission with the given id from the database. The submission is loaded together with its result, the feedback of the result and the assessor of the
* result. Throws an EntityNotFoundException if no submission could be found for the given id.
*
* @param submissionId the id of the submission that should be loaded from the database
* @return the modeling submission with the given id
*/
default ModelingSubmission findOneWithEagerResultAndFeedback(Long submissionId) {
return findByIdWithEagerResultAndAssessorAndFeedback(submissionId).orElseThrow(() -> new EntityNotFoundException("Modeling Submission", submissionId));
}
/**
* Get the modeling submission with the given id from the database. The submission is loaded together with its result, the feedback of the result, the assessor of the result,
* its participation and all results of the participation. Throws an EntityNotFoundException if no submission could be found for the given id.
*
* @param submissionId the id of the submission that should be loaded from the database
* @return the modeling submission with the given id
*/
default ModelingSubmission findOneWithEagerResultAndFeedbackAndAssessorAndParticipationResults(Long submissionId) {
return findWithResultsFeedbacksAssessorAndParticipationResultsById(submissionId).orElseThrow(() -> new EntityNotFoundException("Modeling Submission", submissionId));
}
}
|
3e11f899cfe44f32f880a892855022edac51a105 | 874 | java | Java | sample/webservice/eBayDemoApp/src/com/ebay/finding/api/ItemFilter.java | 4everalone/nano | 71779b1ad546663ee90a29f1c2d4236a6948a621 | [
"Apache-2.0"
] | 3 | 2016-01-27T20:05:27.000Z | 2018-01-16T13:11:38.000Z | sample/ebay-demo-app/src/main/java/com/ebay/finding/api/ItemFilter.java | maxep/NanoKit | 7bb39fdd456f9af4f2d2dad937d482620c797a4e | [
"Apache-2.0"
] | null | null | null | sample/ebay-demo-app/src/main/java/com/ebay/finding/api/ItemFilter.java | maxep/NanoKit | 7bb39fdd456f9af4f2d2dad937d482620c797a4e | [
"Apache-2.0"
] | 1 | 2015-09-02T02:40:36.000Z | 2015-09-02T02:40:36.000Z | 20.325581 | 213 | 0.7254 | 7,573 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.finding.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
/**
*
* Contains the specifications for limiting the number of items returned by a find request. Use <b class="con">itemFilter</b> to specify name/value pairs. You can include multiple item filters in a single request.
*
*/
public class ItemFilter implements Serializable {
private static final long serialVersionUID = -1L;
@Element
@Order(value=0)
public String paramName;
@Element
@Order(value=1)
public String paramValue;
@Element
@Order(value=2)
public ItemFilterType name;
@Element
@Order(value=3)
public List<String> value;
@Element
@Order(value=4)
public String delimiter;
@AnyElement
@Order(value=5)
public List<Object> any;
} |
3e11f8a6e5483f38e65aac6e8dd9b66658b75f07 | 2,695 | java | Java | iron-inttest/src/test/java/io/axway/iron/core/FakeStoreManagerBuilderImpl.java | gvauvert/iron | 35b011bced0ad74c651dff755fc630296922f174 | [
"Apache-2.0"
] | 12 | 2017-07-17T08:29:03.000Z | 2020-09-02T04:03:00.000Z | iron-inttest/src/test/java/io/axway/iron/core/FakeStoreManagerBuilderImpl.java | gvauvert/iron | 35b011bced0ad74c651dff755fc630296922f174 | [
"Apache-2.0"
] | 40 | 2017-07-27T13:33:29.000Z | 2021-09-20T12:42:01.000Z | iron-inttest/src/test/java/io/axway/iron/core/FakeStoreManagerBuilderImpl.java | Axway/iron | 35b011bced0ad74c651dff755fc630296922f174 | [
"Apache-2.0"
] | 14 | 2017-07-15T11:23:35.000Z | 2022-03-27T08:31:20.000Z | 37.957746 | 151 | 0.759184 | 7,574 | package io.axway.iron.core;
import java.util.function.*;
import io.axway.iron.Command;
import io.axway.iron.StoreManager;
import io.axway.iron.spi.model.snapshot.SerializableSnapshot;
import io.axway.iron.spi.serializer.SnapshotSerializer;
import io.axway.iron.spi.serializer.TransactionSerializer;
import io.axway.iron.spi.storage.SnapshotStore;
import io.axway.iron.spi.storage.TransactionStore;
import static io.axway.alf.assertion.Assertion.checkState;
public class FakeStoreManagerBuilderImpl implements StoreManagerBuilder {
public TransactionSerializer m_transactionSerializer;
public TransactionStore m_transactionStore;
public SnapshotSerializer m_snapshotSerializer;
public SnapshotStore m_snapshotStore;
private BiFunction<SerializableSnapshot, String, SerializableSnapshot> m_snapshotPostProcessor;
@Override
public StoreManagerBuilder withEntityClass(Class<?> entityClass) {
return null; // not implement here
}
@Override
public StoreManagerBuilder withCommandClass(Class<? extends Command<?>> commandClass) {
return null; // not implement here
}
@Override
public StoreManagerBuilder withTransactionSerializer(TransactionSerializer transactionSerializer) {
checkState(m_transactionSerializer == null, "Transaction serializer has been already set");
m_transactionSerializer = transactionSerializer;
return this;
}
@Override
public StoreManagerBuilder withTransactionStore(TransactionStore transactionStore) {
checkState(m_transactionStore == null, "Transaction store factory has been already set");
m_transactionStore = transactionStore;
return this;
}
@Override
public StoreManagerBuilder withSnapshotSerializer(SnapshotSerializer snapshotSerializer) {
checkState(m_snapshotSerializer == null, "Snapshot serializer has been already set");
m_snapshotSerializer = snapshotSerializer;
return this;
}
@Override
public StoreManagerBuilder withSnapshotStore(SnapshotStore snapshotStore) {
checkState(m_snapshotStore == null, "Snapshot store has been already set");
m_snapshotStore = snapshotStore;
return this;
}
@Override
public StoreManagerBuilder withSnapshotLoadingPostProcessor(BiFunction<SerializableSnapshot, String, SerializableSnapshot> snapshotPostProcessor) {
checkState(m_snapshotPostProcessor == null, "Snapshot post processor function has been already set");
m_snapshotPostProcessor = snapshotPostProcessor;
return this;
}
@Override
public StoreManager build() {
return null; // not implement here
}
}
|
3e11f9105a7769c788173b046e78b13e15d1b16f | 2,516 | java | Java | src/test/java/com/yahoo/bullet/storm/ReflectionUtilsTest.java | cugu-stars/bullet-storm | f7893c4714e101948bcb0a4683a5e9b43aee72a0 | [
"Apache-2.0"
] | 30 | 2016-12-19T05:09:27.000Z | 2018-04-11T01:00:45.000Z | src/test/java/com/yahoo/bullet/storm/ReflectionUtilsTest.java | cugu-stars/bullet-storm | f7893c4714e101948bcb0a4683a5e9b43aee72a0 | [
"Apache-2.0"
] | 43 | 2016-12-12T21:10:25.000Z | 2018-04-12T18:28:57.000Z | src/test/java/com/yahoo/bullet/storm/ReflectionUtilsTest.java | cugu-stars/bullet-storm | f7893c4714e101948bcb0a4683a5e9b43aee72a0 | [
"Apache-2.0"
] | 15 | 2016-12-16T22:38:57.000Z | 2018-02-17T00:29:51.000Z | 42.644068 | 115 | 0.765501 | 7,575 | /*
* Copyright 2018, Yahoo Inc.
* Licensed under the terms of the Apache License, Version 2.0.
* See the LICENSE file associated with the project for terms.
*/
package com.yahoo.bullet.storm;
import com.yahoo.bullet.storm.testing.CustomIMetricsConsumer;
import com.yahoo.bullet.storm.testing.CustomIRichSpout;
import com.yahoo.bullet.storm.testing.TestSpout;
import org.apache.storm.Config;
import org.apache.storm.metric.LoggingMetricsConsumer;
import org.apache.storm.topology.IRichSpout;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Collections;
public class ReflectionUtilsTest {
@Test(expectedExceptions = ClassNotFoundException.class)
public void testGettingNonExistentSpout() throws Exception {
ReflectionUtils utils = new ReflectionUtils();
utils.getSpout("does.not.exist", null);
}
@Test
public void testGettingSpoutWithDefaultConstructor() throws Exception {
IRichSpout spout = ReflectionUtils.getSpout(CustomIRichSpout.class.getName(), null);
Assert.assertTrue(spout instanceof CustomIRichSpout);
}
@Test
public void testGettingSpoutWithArguments() throws Exception {
IRichSpout spout = ReflectionUtils.getSpout(TestSpout.class.getName(), Collections.singletonList("foo"));
Assert.assertTrue(spout instanceof TestSpout);
Assert.assertEquals(((TestSpout) spout).getArgs(), Collections.singletonList("foo"));
}
@Test
public void testIsIMetricsConsumer() {
Assert.assertFalse(ReflectionUtils.isIMetricsConsumer(LoggingMetricsConsumer.class.getName()));
Assert.assertTrue(ReflectionUtils.isIMetricsConsumer(CustomIMetricsConsumer.class.getName()));
}
@Test
public void testRegisteringIMetricsConsumer() {
Config config = new Config();
BulletStormConfig bulletStormConfig = new BulletStormConfig();
Assert.assertNull(bulletStormConfig.get(CustomIMetricsConsumer.CUSTOM_METRICS_REGISTERED));
ReflectionUtils.registerMetricsConsumer(LoggingMetricsConsumer.class.getName(), config, bulletStormConfig);
Assert.assertNull(config.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER));
ReflectionUtils.registerMetricsConsumer(CustomIMetricsConsumer.class.getName(), config, bulletStormConfig);
Assert.assertNotNull(config.get(Config.TOPOLOGY_METRICS_CONSUMER_REGISTER));
Assert.assertTrue((Boolean) bulletStormConfig.get(CustomIMetricsConsumer.CUSTOM_METRICS_REGISTERED));
}
}
|
3e11f91c4bcea5e275e6191a9319aa70dbf8d045 | 49,017 | java | Java | modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorQuerySearchIT.java | GaiserChan/elasticsearch | dcd4667e955666837e2cd9b6177ffb9ebfdcc249 | [
"Apache-2.0"
] | 1,125 | 2016-09-11T17:27:35.000Z | 2022-03-29T13:41:58.000Z | modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorQuerySearchIT.java | ericli1989/elasticsearch | f5d4550e93e4ae84f42b9512a3a3f7344cd62be3 | [
"Apache-2.0"
] | 346 | 2016-12-03T18:37:07.000Z | 2022-03-29T08:33:04.000Z | modules/percolator/src/test/java/org/elasticsearch/percolator/PercolatorQuerySearchIT.java | ericli1989/elasticsearch | f5d4550e93e4ae84f42b9512a3a3f7344cd62be3 | [
"Apache-2.0"
] | 190 | 2016-12-15T13:46:19.000Z | 2022-03-04T05:17:11.000Z | 57.396956 | 135 | 0.597895 | 7,576 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.percolator;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ESIntegTestCase;
import java.util.Arrays;
import java.util.Collections;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.smileBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.yamlBuilder;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.commonTermsQuery;
import static org.elasticsearch.index.query.QueryBuilders.geoBoundingBoxQuery;
import static org.elasticsearch.index.query.QueryBuilders.geoDistanceQuery;
import static org.elasticsearch.index.query.QueryBuilders.geoPolygonQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.spanNearQuery;
import static org.elasticsearch.index.query.QueryBuilders.spanNotQuery;
import static org.elasticsearch.index.query.QueryBuilders.spanTermQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsNull.notNullValue;
public class PercolatorQuerySearchIT extends ESIntegTestCase {
public void testPercolatorQuery() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", "type=keyword", "field2", "type=keyword", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.get();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "value")).endObject())
.get();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "value"))
.must(matchQuery("field2", "value"))
).endObject()).get();
client().admin().indices().prepareRefresh().get();
BytesReference source = BytesReference.bytes(jsonBuilder().startObject().endObject());
logger.info("percolating empty doc");
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
source = BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").endObject());
logger.info("percolating doc with 1 field");
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(response, 2);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getFields().get("_percolator_document_slot").getValue(), equalTo(0));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(1).getFields().get("_percolator_document_slot").getValue(), equalTo(0));
source = BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").field("field2", "value").endObject());
logger.info("percolating doc with 2 fields");
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(response, 3);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getFields().get("_percolator_document_slot").getValue(), equalTo(0));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(1).getFields().get("_percolator_document_slot").getValue(), equalTo(0));
assertThat(response.getHits().getAt(2).getId(), equalTo("3"));
assertThat(response.getHits().getAt(2).getFields().get("_percolator_document_slot").getValue(), equalTo(0));
logger.info("percolating doc with 2 fields");
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", Arrays.asList(
BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").endObject()),
BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").field("field2", "value").endObject())
), XContentType.JSON))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(response, 3);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getFields().get("_percolator_document_slot").getValues(), equalTo(Arrays.asList(0, 1)));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(1).getFields().get("_percolator_document_slot").getValues(), equalTo(Arrays.asList(0, 1)));
assertThat(response.getHits().getAt(2).getId(), equalTo("3"));
assertThat(response.getHits().getAt(2).getFields().get("_percolator_document_slot").getValues(), equalTo(Arrays.asList(1)));
}
public void testPercolatorRangeQueries() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", "type=long", "field2", "type=double", "field3", "type=ip", "field4", "type=date",
"query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", rangeQuery("field1").from(10).to(12)).endObject())
.get();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query", rangeQuery("field1").from(20).to(22)).endObject())
.get();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(rangeQuery("field1").from(10).to(12))
.must(rangeQuery("field1").from(12).to(14))
).endObject()).get();
client().admin().indices().prepareRefresh().get();
client().prepareIndex("test", "type", "4")
.setSource(jsonBuilder().startObject().field("query", rangeQuery("field2").from(10).to(12)).endObject())
.get();
client().prepareIndex("test", "type", "5")
.setSource(jsonBuilder().startObject().field("query", rangeQuery("field2").from(20).to(22)).endObject())
.get();
client().prepareIndex("test", "type", "6")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(rangeQuery("field2").from(10).to(12))
.must(rangeQuery("field2").from(12).to(14))
).endObject()).get();
client().admin().indices().prepareRefresh().get();
client().prepareIndex("test", "type", "7")
.setSource(jsonBuilder().startObject()
.field("query", rangeQuery("field3").from("192.168.1.0").to("192.168.1.5"))
.endObject())
.get();
client().prepareIndex("test", "type", "8")
.setSource(jsonBuilder().startObject()
.field("query", rangeQuery("field3").from("192.168.1.20").to("192.168.1.30"))
.endObject())
.get();
client().prepareIndex("test", "type", "9")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(rangeQuery("field3").from("192.168.1.0").to("192.168.1.5"))
.must(rangeQuery("field3").from("192.168.1.5").to("192.168.1.10"))
).endObject()).get();
client().prepareIndex("test", "type", "10")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(rangeQuery("field4").from("2010-01-01").to("2018-01-01"))
.must(rangeQuery("field4").from("2010-01-01").to("now"))
).endObject()).get();
client().admin().indices().prepareRefresh().get();
// Test long range:
BytesReference source = BytesReference.bytes(jsonBuilder().startObject().field("field1", 12).endObject());
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
logger.info("response={}", response);
assertHitCount(response, 2);
assertThat(response.getHits().getAt(0).getId(), equalTo("3"));
assertThat(response.getHits().getAt(1).getId(), equalTo("1"));
source = BytesReference.bytes(jsonBuilder().startObject().field("field1", 11).endObject());
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
// Test double range:
source = BytesReference.bytes(jsonBuilder().startObject().field("field2", 12).endObject());
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 2);
assertThat(response.getHits().getAt(0).getId(), equalTo("6"));
assertThat(response.getHits().getAt(1).getId(), equalTo("4"));
source = BytesReference.bytes(jsonBuilder().startObject().field("field2", 11).endObject());
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("4"));
// Test IP range:
source = BytesReference.bytes(jsonBuilder().startObject().field("field3", "192.168.1.5").endObject());
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 2);
assertThat(response.getHits().getAt(0).getId(), equalTo("9"));
assertThat(response.getHits().getAt(1).getId(), equalTo("7"));
source = BytesReference.bytes(jsonBuilder().startObject().field("field3", "192.168.1.4").endObject());
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("7"));
// Test date range:
source = BytesReference.bytes(jsonBuilder().startObject().field("field4", "2016-05-15").endObject());
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("10"));
}
public void testPercolatorGeoQueries() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", "type=geo_point", "field2", "type=geo_shape", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query",
geoDistanceQuery("field1").point(52.18, 4.38).distance(50, DistanceUnit.KILOMETERS))
.endObject()).get();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query",
geoBoundingBoxQuery("field1").setCorners(52.3, 4.4, 52.1, 4.6))
.endObject()).get();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query",
geoPolygonQuery("field1", Arrays.asList(new GeoPoint(52.1, 4.4), new GeoPoint(52.3, 4.5), new GeoPoint(52.1, 4.6))))
.endObject()).get();
refresh();
BytesReference source = BytesReference.bytes(jsonBuilder().startObject()
.startObject("field1").field("lat", 52.20).field("lon", 4.51).endObject()
.endObject());
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.addSort("_id", SortOrder.ASC)
.get();
assertHitCount(response, 3);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(2).getId(), equalTo("3"));
}
public void testPercolatorQueryExistingDocument() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", "type=keyword", "field2", "type=keyword", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.get();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "value")).endObject())
.get();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "value"))
.must(matchQuery("field2", "value"))
).endObject()).get();
client().prepareIndex("test", "type", "4").setSource("{}", XContentType.JSON).get();
client().prepareIndex("test", "type", "5").setSource("field1", "value").get();
client().prepareIndex("test", "type", "6").setSource("field1", "value", "field2", "value").get();
client().admin().indices().prepareRefresh().get();
logger.info("percolating empty doc");
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", "test", "type", "1", null, null, null))
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
logger.info("percolating doc with 1 field");
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", "test", "type", "5", null, null, null))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(response, 2);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
logger.info("percolating doc with 2 fields");
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", "test", "type", "6", null, null, null))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(response, 3);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(2).getId(), equalTo("3"));
}
public void testPercolatorQueryExistingDocumentSourceDisabled() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "_source", "enabled=false", "field1", "type=keyword", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.get();
client().prepareIndex("test", "type", "2").setSource("{}", XContentType.JSON).get();
client().admin().indices().prepareRefresh().get();
logger.info("percolating empty doc with source disabled");
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", "test", "type", "1", null, null, null))
.get();
});
assertThat(e.getMessage(), containsString("source disabled"));
}
public void testPercolatorSpecificQueries() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", "type=text", "field2", "type=text", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", commonTermsQuery("field1", "quick brown fox")).endObject())
.get();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query", multiMatchQuery("quick brown fox", "field1", "field2")
.type(MultiMatchQueryBuilder.Type.CROSS_FIELDS)).endObject())
.get();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query",
spanNearQuery(spanTermQuery("field1", "quick"), 0)
.addClause(spanTermQuery("field1", "brown"))
.addClause(spanTermQuery("field1", "fox"))
.inOrder(true)
).endObject())
.get();
client().admin().indices().prepareRefresh().get();
client().prepareIndex("test", "type", "4")
.setSource(jsonBuilder().startObject().field("query",
spanNotQuery(
spanNearQuery(spanTermQuery("field1", "quick"), 0)
.addClause(spanTermQuery("field1", "brown"))
.addClause(spanTermQuery("field1", "fox"))
.inOrder(true),
spanNearQuery(spanTermQuery("field1", "the"), 0)
.addClause(spanTermQuery("field1", "lazy"))
.addClause(spanTermQuery("field1", "dog"))
.inOrder(true)).dist(2)
).endObject())
.get();
// doesn't match
client().prepareIndex("test", "type", "5")
.setSource(jsonBuilder().startObject().field("query",
spanNotQuery(
spanNearQuery(spanTermQuery("field1", "quick"), 0)
.addClause(spanTermQuery("field1", "brown"))
.addClause(spanTermQuery("field1", "fox"))
.inOrder(true),
spanNearQuery(spanTermQuery("field1", "the"), 0)
.addClause(spanTermQuery("field1", "lazy"))
.addClause(spanTermQuery("field1", "dog"))
.inOrder(true)).dist(3)
).endObject())
.get();
client().admin().indices().prepareRefresh().get();
BytesReference source = BytesReference.bytes(jsonBuilder().startObject()
.field("field1", "the quick brown fox jumps over the lazy dog")
.field("field2", "the quick brown fox falls down into the well")
.endObject());
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(response, 4);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getScore(), equalTo(Float.NaN));
assertThat(response.getHits().getAt(1).getId(), equalTo("2"));
assertThat(response.getHits().getAt(1).getScore(), equalTo(Float.NaN));
assertThat(response.getHits().getAt(2).getId(), equalTo("3"));
assertThat(response.getHits().getAt(2).getScore(), equalTo(Float.NaN));
assertThat(response.getHits().getAt(3).getId(), equalTo("4"));
assertThat(response.getHits().getAt(3).getScore(), equalTo(Float.NaN));
}
public void testPercolatorQueryWithHighlighting() throws Exception {
StringBuilder fieldMapping = new StringBuilder("type=text")
.append(",store=").append(randomBoolean());
if (randomBoolean()) {
fieldMapping.append(",term_vector=with_positions_offsets");
} else if (randomBoolean()) {
fieldMapping.append(",index_options=offsets");
}
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", fieldMapping, "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "brown fox")).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "lazy dog")).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "jumps")).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "4")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "dog")).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "5")
.setSource(jsonBuilder().startObject().field("query", termQuery("field1", "fox")).endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh().get();
BytesReference document = BytesReference.bytes(jsonBuilder().startObject()
.field("field1", "The quick brown fox jumps over the lazy dog")
.endObject());
SearchResponse searchResponse = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", document, XContentType.JSON))
.highlighter(new HighlightBuilder().field("field1"))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(searchResponse, 5);
assertThat(searchResponse.getHits().getAt(0).getHighlightFields().get("field1").fragments()[0].string(),
equalTo("The quick <em>brown</em> <em>fox</em> jumps over the lazy dog"));
assertThat(searchResponse.getHits().getAt(1).getHighlightFields().get("field1").fragments()[0].string(),
equalTo("The quick brown fox jumps over the <em>lazy</em> <em>dog</em>"));
assertThat(searchResponse.getHits().getAt(2).getHighlightFields().get("field1").fragments()[0].string(),
equalTo("The quick brown fox <em>jumps</em> over the lazy dog"));
assertThat(searchResponse.getHits().getAt(3).getHighlightFields().get("field1").fragments()[0].string(),
equalTo("The quick brown fox jumps over the lazy <em>dog</em>"));
assertThat(searchResponse.getHits().getAt(4).getHighlightFields().get("field1").fragments()[0].string(),
equalTo("The quick brown <em>fox</em> jumps over the lazy dog"));
BytesReference document1 = BytesReference.bytes(jsonBuilder().startObject()
.field("field1", "The quick brown fox jumps")
.endObject());
BytesReference document2 = BytesReference.bytes(jsonBuilder().startObject()
.field("field1", "over the lazy dog")
.endObject());
searchResponse = client().prepareSearch()
.setQuery(boolQuery()
.should(new PercolateQueryBuilder("query", document1, XContentType.JSON).setName("query1"))
.should(new PercolateQueryBuilder("query", document2, XContentType.JSON).setName("query2"))
)
.highlighter(new HighlightBuilder().field("field1"))
.addSort("_uid", SortOrder.ASC)
.get();
logger.info("searchResponse={}", searchResponse);
assertHitCount(searchResponse, 5);
assertThat(searchResponse.getHits().getAt(0).getHighlightFields().get("query1_field1").fragments()[0].string(),
equalTo("The quick <em>brown</em> <em>fox</em> jumps"));
assertThat(searchResponse.getHits().getAt(1).getHighlightFields().get("query2_field1").fragments()[0].string(),
equalTo("over the <em>lazy</em> <em>dog</em>"));
assertThat(searchResponse.getHits().getAt(2).getHighlightFields().get("query1_field1").fragments()[0].string(),
equalTo("The quick brown fox <em>jumps</em>"));
assertThat(searchResponse.getHits().getAt(3).getHighlightFields().get("query2_field1").fragments()[0].string(),
equalTo("over the lazy <em>dog</em>"));
assertThat(searchResponse.getHits().getAt(4).getHighlightFields().get("query1_field1").fragments()[0].string(),
equalTo("The quick brown <em>fox</em> jumps"));
searchResponse = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", Arrays.asList(
BytesReference.bytes(jsonBuilder().startObject().field("field1", "dog").endObject()),
BytesReference.bytes(jsonBuilder().startObject().field("field1", "fox").endObject()),
BytesReference.bytes(jsonBuilder().startObject().field("field1", "jumps").endObject()),
BytesReference.bytes(jsonBuilder().startObject().field("field1", "brown fox").endObject())
), XContentType.JSON))
.highlighter(new HighlightBuilder().field("field1"))
.addSort("_uid", SortOrder.ASC)
.get();
assertHitCount(searchResponse, 5);
assertThat(searchResponse.getHits().getAt(0).getFields().get("_percolator_document_slot").getValues(),
equalTo(Arrays.asList(1, 3)));
assertThat(searchResponse.getHits().getAt(0).getHighlightFields().get("1_field1").fragments()[0].string(),
equalTo("<em>fox</em>"));
assertThat(searchResponse.getHits().getAt(0).getHighlightFields().get("3_field1").fragments()[0].string(),
equalTo("<em>brown</em> <em>fox</em>"));
assertThat(searchResponse.getHits().getAt(1).getFields().get("_percolator_document_slot").getValues(),
equalTo(Collections.singletonList(0)));
assertThat(searchResponse.getHits().getAt(1).getHighlightFields().get("0_field1").fragments()[0].string(),
equalTo("<em>dog</em>"));
assertThat(searchResponse.getHits().getAt(2).getFields().get("_percolator_document_slot").getValues(),
equalTo(Collections.singletonList(2)));
assertThat(searchResponse.getHits().getAt(2).getHighlightFields().get("2_field1").fragments()[0].string(),
equalTo("<em>jumps</em>"));
assertThat(searchResponse.getHits().getAt(3).getFields().get("_percolator_document_slot").getValues(),
equalTo(Collections.singletonList(0)));
assertThat(searchResponse.getHits().getAt(3).getHighlightFields().get("0_field1").fragments()[0].string(),
equalTo("<em>dog</em>"));
assertThat(searchResponse.getHits().getAt(4).getFields().get("_percolator_document_slot").getValues(),
equalTo(Arrays.asList(1, 3)));
assertThat(searchResponse.getHits().getAt(4).getHighlightFields().get("1_field1").fragments()[0].string(),
equalTo("<em>fox</em>"));
assertThat(searchResponse.getHits().getAt(4).getHighlightFields().get("3_field1").fragments()[0].string(),
equalTo("brown <em>fox</em>"));
searchResponse = client().prepareSearch()
.setQuery(boolQuery()
.should(new PercolateQueryBuilder("query", Arrays.asList(
BytesReference.bytes(jsonBuilder().startObject().field("field1", "dog").endObject()),
BytesReference.bytes(jsonBuilder().startObject().field("field1", "fox").endObject())
), XContentType.JSON).setName("query1"))
.should(new PercolateQueryBuilder("query", Arrays.asList(
BytesReference.bytes(jsonBuilder().startObject().field("field1", "jumps").endObject()),
BytesReference.bytes(jsonBuilder().startObject().field("field1", "brown fox").endObject())
), XContentType.JSON).setName("query2"))
)
.highlighter(new HighlightBuilder().field("field1"))
.addSort("_uid", SortOrder.ASC)
.get();
logger.info("searchResponse={}", searchResponse);
assertHitCount(searchResponse, 5);
assertThat(searchResponse.getHits().getAt(0).getFields().get("_percolator_document_slot_query1").getValues(),
equalTo(Collections.singletonList(1)));
assertThat(searchResponse.getHits().getAt(0).getFields().get("_percolator_document_slot_query2").getValues(),
equalTo(Collections.singletonList(1)));
assertThat(searchResponse.getHits().getAt(0).getHighlightFields().get("query1_1_field1").fragments()[0].string(),
equalTo("<em>fox</em>"));
assertThat(searchResponse.getHits().getAt(0).getHighlightFields().get("query2_1_field1").fragments()[0].string(),
equalTo("<em>brown</em> <em>fox</em>"));
assertThat(searchResponse.getHits().getAt(1).getFields().get("_percolator_document_slot_query1").getValues(),
equalTo(Collections.singletonList(0)));
assertThat(searchResponse.getHits().getAt(1).getHighlightFields().get("query1_0_field1").fragments()[0].string(),
equalTo("<em>dog</em>"));
assertThat(searchResponse.getHits().getAt(2).getFields().get("_percolator_document_slot_query2").getValues(),
equalTo(Collections.singletonList(0)));
assertThat(searchResponse.getHits().getAt(2).getHighlightFields().get("query2_0_field1").fragments()[0].string(),
equalTo("<em>jumps</em>"));
assertThat(searchResponse.getHits().getAt(3).getFields().get("_percolator_document_slot_query1").getValues(),
equalTo(Collections.singletonList(0)));
assertThat(searchResponse.getHits().getAt(3).getHighlightFields().get("query1_0_field1").fragments()[0].string(),
equalTo("<em>dog</em>"));
assertThat(searchResponse.getHits().getAt(4).getFields().get("_percolator_document_slot_query1").getValues(),
equalTo(Collections.singletonList(1)));
assertThat(searchResponse.getHits().getAt(4).getFields().get("_percolator_document_slot_query2").getValues(),
equalTo(Collections.singletonList(1)));
assertThat(searchResponse.getHits().getAt(4).getHighlightFields().get("query1_1_field1").fragments()[0].string(),
equalTo("<em>fox</em>"));
assertThat(searchResponse.getHits().getAt(4).getHighlightFields().get("query2_1_field1").fragments()[0].string(),
equalTo("brown <em>fox</em>"));
}
public void testTakePositionOffsetGapIntoAccount() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field", "type=text,position_increment_gap=5", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query",
new MatchPhraseQueryBuilder("field", "brown fox").slop(4)).endObject())
.get();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query",
new MatchPhraseQueryBuilder("field", "brown fox").slop(5)).endObject())
.get();
client().admin().indices().prepareRefresh().get();
SearchResponse response = client().prepareSearch().setQuery(
new PercolateQueryBuilder("query", new BytesArray("{\"field\" : [\"brown\", \"fox\"]}"), XContentType.JSON)
).get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("2"));
}
public void testManyPercolatorFields() throws Exception {
String queryFieldName = randomAlphaOfLength(8);
assertAcked(client().admin().indices().prepareCreate("test1")
.addMapping("type", queryFieldName, "type=percolator", "field", "type=keyword")
);
assertAcked(client().admin().indices().prepareCreate("test2")
.addMapping("type", queryFieldName, "type=percolator", "second_query_field", "type=percolator", "field", "type=keyword")
);
assertAcked(client().admin().indices().prepareCreate("test3")
.addMapping("type", jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("field")
.field("type", "keyword")
.endObject()
.startObject("object_field")
.field("type", "object")
.startObject("properties")
.startObject(queryFieldName)
.field("type", "percolator")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject().endObject())
);
}
public void testWithMultiplePercolatorFields() throws Exception {
String queryFieldName = randomAlphaOfLength(8);
assertAcked(client().admin().indices().prepareCreate("test1")
.addMapping("type", queryFieldName, "type=percolator", "field", "type=keyword"));
assertAcked(client().admin().indices().prepareCreate("test2")
.addMapping("type", jsonBuilder().startObject().startObject("type").startObject("properties")
.startObject("field")
.field("type", "keyword")
.endObject()
.startObject("object_field")
.field("type", "object")
.startObject("properties")
.startObject(queryFieldName)
.field("type", "percolator")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject().endObject())
);
// Acceptable:
client().prepareIndex("test1", "type", "1")
.setSource(jsonBuilder().startObject().field(queryFieldName, matchQuery("field", "value")).endObject())
.get();
client().prepareIndex("test2", "type", "1")
.setSource(jsonBuilder().startObject().startObject("object_field")
.field(queryFieldName, matchQuery("field", "value"))
.endObject().endObject())
.get();
client().admin().indices().prepareRefresh().get();
BytesReference source = BytesReference.bytes(jsonBuilder().startObject().field("field", "value").endObject());
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder(queryFieldName, source, XContentType.JSON))
.setIndices("test1")
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getType(), equalTo("type"));
assertThat(response.getHits().getAt(0).getIndex(), equalTo("test1"));
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("object_field." + queryFieldName, source, XContentType.JSON))
.setIndices("test2")
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("1"));
assertThat(response.getHits().getAt(0).getType(), equalTo("type"));
assertThat(response.getHits().getAt(0).getIndex(), equalTo("test2"));
// Unacceptable:
MapperParsingException e = expectThrows(MapperParsingException.class, () -> {
client().prepareIndex("test2", "type", "1")
.setSource(jsonBuilder().startObject().startArray("object_field")
.startObject().field(queryFieldName, matchQuery("field", "value")).endObject()
.startObject().field(queryFieldName, matchQuery("field", "value")).endObject()
.endArray().endObject())
.get();
});
assertThat(e.getCause(), instanceOf(IllegalArgumentException.class));
assertThat(e.getCause().getMessage(), equalTo("a document can only contain one percolator query"));
}
public void testPercolateQueryWithNestedDocuments() throws Exception {
XContentBuilder mapping = XContentFactory.jsonBuilder();
mapping.startObject().startObject("properties").startObject("query").field("type", "percolator").endObject()
.startObject("companyname").field("type", "text").endObject().startObject("employee").field("type", "nested")
.startObject("properties").startObject("name").field("type", "text").endObject().endObject().endObject().endObject()
.endObject();
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("employee", mapping)
);
client().prepareIndex("test", "employee", "q1").setSource(jsonBuilder().startObject()
.field("query", QueryBuilders.nestedQuery("employee",
QueryBuilders.matchQuery("employee.name", "virginia potts").operator(Operator.AND), ScoreMode.Avg)
).endObject())
.get();
// this query should never match as it doesn't use nested query:
client().prepareIndex("test", "employee", "q2").setSource(jsonBuilder().startObject()
.field("query", QueryBuilders.matchQuery("employee.name", "virginia")).endObject())
.get();
client().admin().indices().prepareRefresh().get();
SearchResponse response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("companyname", "stark")
.startArray("employee")
.startObject().field("name", "virginia potts").endObject()
.startObject().field("name", "tony stark").endObject()
.endArray()
.endObject()), XContentType.JSON))
.addSort("_doc", SortOrder.ASC)
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("q1"));
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("companyname", "notstark")
.startArray("employee")
.startObject().field("name", "virginia stark").endObject()
.startObject().field("name", "tony stark").endObject()
.endArray()
.endObject()), XContentType.JSON))
.addSort("_doc", SortOrder.ASC)
.get();
assertHitCount(response, 0);
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("companyname", "notstark").endObject()),
XContentType.JSON))
.addSort("_doc", SortOrder.ASC)
.get();
assertHitCount(response, 0);
response = client().prepareSearch()
.setQuery(new PercolateQueryBuilder("query", Arrays.asList(
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("companyname", "stark")
.startArray("employee")
.startObject().field("name", "virginia potts").endObject()
.startObject().field("name", "tony stark").endObject()
.endArray()
.endObject()),
BytesReference.bytes(XContentFactory.jsonBuilder()
.startObject().field("companyname", "stark")
.startArray("employee")
.startObject().field("name", "peter parker").endObject()
.startObject().field("name", "virginia potts").endObject()
.endArray()
.endObject())
), XContentType.JSON))
.addSort("_doc", SortOrder.ASC)
.get();
assertHitCount(response, 1);
assertThat(response.getHits().getAt(0).getId(), equalTo("q1"));
assertThat(response.getHits().getAt(0).getFields().get("_percolator_document_slot").getValues(), equalTo(Arrays.asList(0, 1)));
}
public void testPercolatorQueryViaMultiSearch() throws Exception {
assertAcked(client().admin().indices().prepareCreate("test")
.addMapping("type", "field1", "type=text", "query", "type=percolator")
);
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "b")).field("a", "b").endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("query", matchQuery("field1", "c")).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "3")
.setSource(jsonBuilder().startObject().field("query", boolQuery()
.must(matchQuery("field1", "b"))
.must(matchQuery("field1", "c"))
).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "4")
.setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "5")
.setSource(jsonBuilder().startObject().field("field1", "c").endObject())
.execute().actionGet();
client().admin().indices().prepareRefresh().get();
MultiSearchResponse response = client().prepareMultiSearch()
.add(client().prepareSearch("test")
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(jsonBuilder().startObject().field("field1", "b").endObject()), XContentType.JSON)))
.add(client().prepareSearch("test")
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(yamlBuilder().startObject().field("field1", "c").endObject()), XContentType.YAML)))
.add(client().prepareSearch("test")
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(smileBuilder().startObject().field("field1", "b c").endObject()), XContentType.SMILE)))
.add(client().prepareSearch("test")
.setQuery(new PercolateQueryBuilder("query",
BytesReference.bytes(jsonBuilder().startObject().field("field1", "d").endObject()), XContentType.JSON)))
.add(client().prepareSearch("test")
.setQuery(new PercolateQueryBuilder("query", "test", "type", "5", null, null, null)))
.add(client().prepareSearch("test") // non existing doc, so error element
.setQuery(new PercolateQueryBuilder("query", "test", "type", "6", null, null, null)))
.get();
MultiSearchResponse.Item item = response.getResponses()[0];
assertHitCount(item.getResponse(), 2L);
assertSearchHits(item.getResponse(), "1", "4");
assertThat(item.getFailureMessage(), nullValue());
item = response.getResponses()[1];
assertHitCount(item.getResponse(), 2L);
assertSearchHits(item.getResponse(), "2", "4");
assertThat(item.getFailureMessage(), nullValue());
item = response.getResponses()[2];
assertHitCount(item.getResponse(), 4L);
assertSearchHits(item.getResponse(), "1", "2", "3", "4");
assertThat(item.getFailureMessage(), nullValue());
item = response.getResponses()[3];
assertHitCount(item.getResponse(), 1L);
assertSearchHits(item.getResponse(), "4");
assertThat(item.getFailureMessage(), nullValue());
item = response.getResponses()[4];
assertHitCount(item.getResponse(), 2L);
assertSearchHits(item.getResponse(), "2", "4");
assertThat(item.getFailureMessage(), nullValue());
item = response.getResponses()[5];
assertThat(item.getResponse(), nullValue());
assertThat(item.getFailureMessage(), notNullValue());
assertThat(item.getFailureMessage(), containsString("[test/type/6] couldn't be found"));
}
}
|
3e11f9624c4595fba45761eda4cd775be6554e57 | 274 | java | Java | IslandCraft-Common/src/main/java/com/github/hoqhuuep/islandcraft/core/ICLogger.java | Atten007/IslandCraft | ebd95dadcbcbb36212987091ed2dd70fe00970e0 | [
"MIT"
] | 22 | 2015-01-07T12:42:15.000Z | 2022-01-27T02:29:57.000Z | IslandCraft-Common/src/main/java/com/github/hoqhuuep/islandcraft/core/ICLogger.java | Atten007/IslandCraft | ebd95dadcbcbb36212987091ed2dd70fe00970e0 | [
"MIT"
] | 27 | 2015-01-05T21:52:27.000Z | 2021-02-21T21:24:24.000Z | IslandCraft-Common/src/main/java/com/github/hoqhuuep/islandcraft/core/ICLogger.java | Atten007/IslandCraft | ebd95dadcbcbb36212987091ed2dd70fe00970e0 | [
"MIT"
] | 28 | 2015-01-16T17:53:47.000Z | 2022-01-30T23:04:20.000Z | 27.4 | 49 | 0.748175 | 7,577 | package com.github.hoqhuuep.islandcraft.core;
public abstract class ICLogger {
public static ICLogger logger = null;
public abstract void info(String message);
public abstract void warning(String message);
public abstract void error(String message);
}
|
3e11fa1355f53f122d5c219502729f174b8a1704 | 1,339 | java | Java | java/shop/src/test/java/de/epages/ws/productattribute/ProductAttributeServiceTest.java | ogoranskyy/soapclient | 5a5f075df39271789b90a7e63302f5811e4291b5 | [
"Apache-2.0"
] | null | null | null | java/shop/src/test/java/de/epages/ws/productattribute/ProductAttributeServiceTest.java | ogoranskyy/soapclient | 5a5f075df39271789b90a7e63302f5811e4291b5 | [
"Apache-2.0"
] | null | null | null | java/shop/src/test/java/de/epages/ws/productattribute/ProductAttributeServiceTest.java | ogoranskyy/soapclient | 5a5f075df39271789b90a7e63302f5811e4291b5 | [
"Apache-2.0"
] | null | null | null | 34.333333 | 162 | 0.690814 | 7,578 | package de.epages.ws.productattribute;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import de.epages.ws.ShopWebServiceTestConfiguration;
import de.epages.ws.productattribute.model.TGetInfoList_Return;
public class ProductAttributeServiceTest {
private static final ProductAttributeServiceClientImpl productAttributeService = new ProductAttributeServiceClientImpl(new ShopWebServiceTestConfiguration());
/**
* Get a list of all product attributes
*/
@Test
public void testGetList() {
TGetInfoList_Return[] allAttributes = productAttributeService.getInfoList();
// test if transfer was successful
assertTrue("number of attributes > 10", allAttributes.length > 10);
// test if the attribute "Color" exists in product type "Jacket"
boolean existsAttribute = false;
for( TGetInfoList_Return attributeInfo : allAttributes )
{
if( attributeInfo.getAlias().equals("Color") &&
attributeInfo.getProductType().equals("Jacket") )
{
existsAttribute = true;
assertTrue("attribute 'Color' is a variation attribute", attributeInfo.getIsVariationAttribute());
}
}
assertTrue("attribute 'Color' exists in class 'Jacket'", existsAttribute);
}
}
|
3e11fa86ce2f5611c7cf38839b7dfec797b228f9 | 1,092 | java | Java | src/main/java/com/martinwj/controller/web/WebAction.java | dfwefeg/video | 6281d78caba17c21dbb44c7ef87092e282435b50 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/martinwj/controller/web/WebAction.java | dfwefeg/video | 6281d78caba17c21dbb44c7ef87092e282435b50 | [
"Apache-2.0"
] | 2 | 2021-01-21T01:42:29.000Z | 2021-12-09T22:52:40.000Z | src/main/java/com/martinwj/controller/web/WebAction.java | dfwefeg/video | 6281d78caba17c21dbb44c7ef87092e282435b50 | [
"Apache-2.0"
] | null | null | null | 21.411765 | 62 | 0.684982 | 7,579 | package com.martinwj.controller.web;
import com.martinwj.entity.Result;
import com.martinwj.entity.Web;
import com.martinwj.service.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @ClassName: WebAction
* @Description: TODO
* @author: martin-wj
* @createDate: 2020-12-23
*/
@Controller
@RequestMapping("web")
public class WebAction {
@Autowired
private WebService webService;
/**
* 查询站点信息
*/
@RequestMapping("edit.action")
public String edit(ModelMap map) {
Web web = webService.selectWebInfo();
map.put("webInfo", web);
return "admin/web_info/edit";
}
/**
* 保存站点信息配置
* @param web
* @return
*/
@RequestMapping("save.json")
@ResponseBody
public Result save(Web web) {
webService.save(web);
return Result.success();
}
}
|
3e11faf0e3cc02bfde71ee1788135f88e3bee1ca | 3,774 | java | Java | projects/OG-Analytics/tests/unit/com/opengamma/financial/instrument/ConventionTest.java | gsteri1/OG-Platform | e682c31e69cadde06dd3776544913dde17fe41ba | [
"Apache-2.0"
] | 1 | 2021-02-27T21:05:05.000Z | 2021-02-27T21:05:05.000Z | projects/OG-Analytics/tests/unit/com/opengamma/financial/instrument/ConventionTest.java | gsteri1/OG-Platform | e682c31e69cadde06dd3776544913dde17fe41ba | [
"Apache-2.0"
] | null | null | null | projects/OG-Analytics/tests/unit/com/opengamma/financial/instrument/ConventionTest.java | gsteri1/OG-Platform | e682c31e69cadde06dd3776544913dde17fe41ba | [
"Apache-2.0"
] | null | null | null | 38.907216 | 143 | 0.771065 | 7,580 | /**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.financial.instrument;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import javax.time.calendar.LocalDate;
import org.testng.annotations.Test;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventionFactory;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.calendar.MondayToFridayCalendar;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCountFactory;
/**
*
*/
public class ConventionTest {
private static final int SETTLEMENT_DAYS = 2;
private static final DayCount DAY_COUNT = DayCountFactory.INSTANCE.getDayCount("Actual/360");
private static final BusinessDayConvention BUSINESS_DAY = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Following");
private static final Calendar CALENDAR = new MondayToFridayCalendar("A");
private static final String NAME = "CONVENTION";
private static final Convention CONVENTION = new Convention(SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, CALENDAR, NAME);
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNegativeSettlementDays() {
new Convention(-SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, CALENDAR, NAME);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullDayCount() {
new Convention(SETTLEMENT_DAYS, null, BUSINESS_DAY, CALENDAR, NAME);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullBusinessDayConvention() {
new Convention(SETTLEMENT_DAYS, DAY_COUNT, null, CALENDAR, NAME);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullCalendar() {
new Convention(SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, null, NAME);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullName() {
new Convention(SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, CALENDAR, null);
}
@Test
public void testGetters() {
assertEquals(CONVENTION.getBusinessDayConvention(), BUSINESS_DAY);
assertEquals(CONVENTION.getDayCount(), DAY_COUNT);
assertEquals(CONVENTION.getName(), NAME);
assertEquals(CONVENTION.getSettlementDays(), SETTLEMENT_DAYS);
assertEquals(CONVENTION.getWorkingDayCalendar(), CALENDAR);
}
@Test
public void testHashCodeAndEquals() {
Convention other = new Convention(SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, CALENDAR, NAME);
assertEquals(CONVENTION, other);
assertEquals(CONVENTION.hashCode(), other.hashCode());
other = new Convention(SETTLEMENT_DAYS + 1, DAY_COUNT, BUSINESS_DAY, CALENDAR, NAME);
assertFalse(CONVENTION.equals(other));
other = new Convention(SETTLEMENT_DAYS, DayCountFactory.INSTANCE.getDayCount("Actual/365"), BUSINESS_DAY, CALENDAR, NAME);
assertFalse(CONVENTION.equals(other));
other = new Convention(SETTLEMENT_DAYS, DAY_COUNT, BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("None"), CALENDAR, NAME);
assertFalse(CONVENTION.equals(other));
other = new Convention(SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, new Calendar() {
@Override
public boolean isWorkingDay(final LocalDate date) {
return false;
}
@Override
public String getConventionName() {
return null;
}
}, NAME);
assertFalse(CONVENTION.equals(other));
other = new Convention(SETTLEMENT_DAYS, DAY_COUNT, BUSINESS_DAY, CALENDAR, NAME + ")");
assertFalse(CONVENTION.equals(other));
}
}
|
3e11fbb97b002a58de2bf3e377fd1d13f9df10b9 | 6,412 | java | Java | src/main/java/net/sf/jabref/logic/net/URLDownload.java | h3691512/jabref | 7d6ee2b66477bd6b1c443f03b594130805c99082 | [
"MIT"
] | null | null | null | src/main/java/net/sf/jabref/logic/net/URLDownload.java | h3691512/jabref | 7d6ee2b66477bd6b1c443f03b594130805c99082 | [
"MIT"
] | null | null | null | src/main/java/net/sf/jabref/logic/net/URLDownload.java | h3691512/jabref | 7d6ee2b66477bd6b1c443f03b594130805c99082 | [
"MIT"
] | null | null | null | 30.679426 | 116 | 0.640206 | 7,581 | package net.sf.jabref.logic.net;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* URL download to a string.
* <p>
* Example:
* URLDownload dl = new URLDownload(URL);
* String content = dl.downloadToString(ENCODING);
* dl.downloadToFile(FILE); // available in FILE
* String contentType = dl.determineMimeType();
*
* Each call to a public method creates a new HTTP connection. Nothing is cached.
*
* @author Erik Putrycz erik.putrycz-at-nrc-cnrc.gc.ca
* @author Simon Harrer
*/
public class URLDownload {
private final URL source;
private static final Log LOGGER = LogFactory.getLog(URLDownload.class);
private final Map<String, String> parameters = new HashMap<>();
private String postData = "";
public static URLDownload createURLDownloadWithBrowserUserAgent(String address) throws MalformedURLException {
URLDownload downloader = new URLDownload(address);
downloader.addParameters("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
return downloader;
}
/**
* @param address the URL to download from
* @throws MalformedURLException if no protocol is specified in the address, or an unknown protocol is found
*/
public URLDownload(String address) throws MalformedURLException {
this(new URL(address));
}
/**
* @param source The URL to download.
*/
public URLDownload(URL source) {
this.source = source;
addParameters("User-Agent", "JabRef");
}
public URL getSource() {
return source;
}
public String determineMimeType() throws IOException {
// this does not cause a real performance issue as the underlying HTTP/TCP connection is reused
URLConnection urlConnection = openConnection();
try {
return urlConnection.getContentType();
} finally {
try {
urlConnection.getInputStream().close();
} catch (IOException ignored) {
// Ignored
}
}
}
public void addParameters(String key, String value) {
parameters.put(key, value);
}
public void setPostData(String postData) {
if (postData != null) {
this.postData = postData;
}
}
private URLConnection openConnection() throws IOException {
URLConnection connection = source.openConnection();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
if (!postData.isEmpty()) {
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(postData);
}
}
// this does network i/o: GET + read returned headers
connection.connect();
return connection;
}
/**
*
* @return the downloaded string
* @throws IOException
*/
public String downloadToString(Charset encoding) throws IOException {
try (InputStream input = new BufferedInputStream(openConnection().getInputStream());
Writer output = new StringWriter()) {
copy(input, output, encoding);
return output.toString();
} catch (IOException e) {
LOGGER.warn("Could not copy input", e);
throw e;
}
}
public List<HttpCookie> getCookieFromUrl() throws IOException {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
URLConnection con = openConnection();
con.getHeaderFields(); // must be read to store the cookie
try {
return cookieManager.getCookieStore().get(source.toURI());
} catch (URISyntaxException e) {
LOGGER.error("Unable to convert download URL to URI", e);
return Collections.emptyList();
}
}
private void copy(InputStream in, Writer out, Charset encoding) throws IOException {
InputStream monitoredInputStream = monitorInputStream(in);
Reader r = new InputStreamReader(monitoredInputStream, encoding);
try (BufferedReader read = new BufferedReader(r)) {
String line;
while ((line = read.readLine()) != null) {
out.write(line);
out.write("\n");
}
}
}
public void downloadToFile(File destination) throws IOException {
try (InputStream input = new BufferedInputStream(openConnection().getInputStream());
OutputStream output = new BufferedOutputStream(new FileOutputStream(destination))) {
copy(input, output);
} catch (IOException e) {
LOGGER.warn("Could not copy input", e);
throw e;
}
}
private void copy(InputStream in, OutputStream out) throws IOException {
try (InputStream monitorInputStream = monitorInputStream(in)) {
byte[] buffer = new byte[512];
while (true) {
int bytesRead = monitorInputStream.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
}
}
}
protected InputStream monitorInputStream(InputStream in) {
return in;
}
@Override
public String toString() {
return "URLDownload{" + "source=" + source + '}';
}
}
|
3e11fc0d909735f4cf69e2751469f67320593bf1 | 5,561 | java | Java | core/target/java/org/apache/spark/util/ThreadUtils.java | jessicarychen/598project | 0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | core/target/java/org/apache/spark/util/ThreadUtils.java | jessicarychen/598project | 0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | core/target/java/org/apache/spark/util/ThreadUtils.java | jessicarychen/598project | 0ef1eb6f10539fadaf69d3474cebb0a4f90e14c0 | [
"BSD-3-Clause-Open-MPI",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"MIT-0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause-Clear",
"PostgreSQL",
"BSD-3-Clause"
] | null | null | null | 53.990291 | 240 | 0.737637 | 7,582 | package org.apache.spark.util;
public class ThreadUtils {
static private scala.concurrent.ExecutionContextExecutorService sameThreadExecutionContext () { throw new RuntimeException(); }
/**
* An <code>ExecutionContextExecutor</code> that runs each task in the thread that invokes <code>execute/submit</code>.
* The caller should make sure the tasks running in this <code>ExecutionContextExecutor</code> are short and
* never block.
* @return (undocumented)
*/
static public scala.concurrent.ExecutionContextExecutor sameThread () { throw new RuntimeException(); }
/**
* Create a thread factory that names threads with a prefix and also sets the threads to daemon.
* @param prefix (undocumented)
* @return (undocumented)
*/
static public java.util.concurrent.ThreadFactory namedThreadFactory (java.lang.String prefix) { throw new RuntimeException(); }
/**
* Wrapper over newCachedThreadPool. Thread names are formatted as prefix-ID, where ID is a
* unique, sequentially assigned integer.
* @param prefix (undocumented)
* @return (undocumented)
*/
static public java.util.concurrent.ThreadPoolExecutor newDaemonCachedThreadPool (java.lang.String prefix) { throw new RuntimeException(); }
/**
* Create a cached thread pool whose max number of threads is <code>maxThreadNumber</code>. Thread names
* are formatted as prefix-ID, where ID is a unique, sequentially assigned integer.
* @param prefix (undocumented)
* @param maxThreadNumber (undocumented)
* @param keepAliveSeconds (undocumented)
* @return (undocumented)
*/
static public java.util.concurrent.ThreadPoolExecutor newDaemonCachedThreadPool (java.lang.String prefix, int maxThreadNumber, int keepAliveSeconds) { throw new RuntimeException(); }
/**
* Wrapper over newFixedThreadPool. Thread names are formatted as prefix-ID, where ID is a
* unique, sequentially assigned integer.
* @param nThreads (undocumented)
* @param prefix (undocumented)
* @return (undocumented)
*/
static public java.util.concurrent.ThreadPoolExecutor newDaemonFixedThreadPool (int nThreads, java.lang.String prefix) { throw new RuntimeException(); }
/**
* Wrapper over newSingleThreadExecutor.
* @param threadName (undocumented)
* @return (undocumented)
*/
static public java.util.concurrent.ExecutorService newDaemonSingleThreadExecutor (java.lang.String threadName) { throw new RuntimeException(); }
/**
* Wrapper over ScheduledThreadPoolExecutor.
* @param threadName (undocumented)
* @return (undocumented)
*/
static public java.util.concurrent.ScheduledExecutorService newDaemonSingleThreadScheduledExecutor (java.lang.String threadName) { throw new RuntimeException(); }
/**
* Run a piece of code in a new thread and return the result. Exception in the new thread is
* thrown in the caller thread with an adjusted stack trace that removes references to this
* method for clarity. The exception stack traces will be like the following
* <p>
* SomeException: exception-message
* at CallerClass.body-method (sourcefile.scala)
* at ... run in separate thread using org.apache.spark.util.ThreadUtils ... ()
* at CallerClass.caller-method (sourcefile.scala)
* ...
* @param threadName (undocumented)
* @param isDaemon (undocumented)
* @param body (undocumented)
* @return (undocumented)
*/
static public <T extends java.lang.Object> T runInNewThread (java.lang.String threadName, boolean isDaemon, scala.Function0<T> body) { throw new RuntimeException(); }
/**
* Construct a new Scala ForkJoinPool with a specified max parallelism and name prefix.
* @param prefix (undocumented)
* @param maxThreadNumber (undocumented)
* @return (undocumented)
*/
static public scala.concurrent.forkjoin.ForkJoinPool newForkJoinPool (java.lang.String prefix, int maxThreadNumber) { throw new RuntimeException(); }
/**
* Preferred alternative to <code>Await.result()</code>.
* <p>
* This method wraps and re-throws any exceptions thrown by the underlying <code>Await</code> call, ensuring
* that this thread's stack trace appears in logs.
* <p>
* In addition, it calls <code>Awaitable.result</code> directly to avoid using <code>ForkJoinPool</code>'s
* <code>BlockingContext</code>. Codes running in the user's thread may be in a thread of Scala ForkJoinPool.
* As concurrent executions in ForkJoinPool may see some {@link ThreadLocal} value unexpectedly, this
* method basically prevents ForkJoinPool from running other tasks in the current waiting thread.
* In general, we should use this method because many places in Spark use {@link ThreadLocal} and it's
* hard to debug when {@link ThreadLocal}s leak to other tasks.
* @param awaitable (undocumented)
* @param atMost (undocumented)
* @return (undocumented)
*/
static public <T extends java.lang.Object> T awaitResult (scala.concurrent.Awaitable<T> awaitable, scala.concurrent.duration.Duration atMost) throws org.apache.spark.SparkException { throw new RuntimeException(); }
/**
* Preferred alternative to <code>Await.ready()</code>.
* <p>
* @see awaitResult
* @param awaitable (undocumented)
* @param atMost (undocumented)
* @return (undocumented)
*/
static public <T extends java.lang.Object> scala.concurrent.Awaitable awaitReady (scala.concurrent.Awaitable<T> awaitable, scala.concurrent.duration.Duration atMost) throws org.apache.spark.SparkException { throw new RuntimeException(); }
}
|
3e11fcaba8cac359954e32fce468c1355cbbd4c0 | 347 | java | Java | priest-user/priest-user-http/src/test/java/com/little/g/user/web/PriestDemoHttpApplicationTests.java | vivigiggle409/priest | d2fd1c91b4cc0b9916dc0d2077371e8a3f52a4d3 | [
"Apache-2.0"
] | 1 | 2019-12-16T09:17:31.000Z | 2019-12-16T09:17:31.000Z | priest-user/priest-user-http/src/test/java/com/little/g/user/web/PriestDemoHttpApplicationTests.java | vivigiggle409/priest | d2fd1c91b4cc0b9916dc0d2077371e8a3f52a4d3 | [
"Apache-2.0"
] | null | null | null | priest-user/priest-user-http/src/test/java/com/little/g/user/web/PriestDemoHttpApplicationTests.java | vivigiggle409/priest | d2fd1c91b4cc0b9916dc0d2077371e8a3f52a4d3 | [
"Apache-2.0"
] | null | null | null | 19.277778 | 60 | 0.806916 | 7,583 | package com.little.g.user.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PriestDemoHttpApplicationTests {
@Test
public void contextLoads() {
}
}
|
3e11fcaf5f77083758323a9c6862b47153393d8b | 1,623 | java | Java | src/main/java/org/items/rules_book.java | person1234-ux/evanserver | c0fa721133f1956dd948fc0e5d830b6dfc6ad937 | [
"CC-BY-4.0"
] | null | null | null | src/main/java/org/items/rules_book.java | person1234-ux/evanserver | c0fa721133f1956dd948fc0e5d830b6dfc6ad937 | [
"CC-BY-4.0"
] | 2 | 2021-02-11T04:42:18.000Z | 2021-02-21T02:22:52.000Z | src/main/java/org/items/rules_book.java | person1234-ux/evanserver | c0fa721133f1956dd948fc0e5d830b6dfc6ad937 | [
"CC-BY-4.0"
] | null | null | null | 43.864865 | 266 | 0.78435 | 7,584 | /*
* Copyright (c) $today.year.EvanServer is licensed under Attribution 4.0 International. (https://creativecommons.org/licenses/by/4.0/?ref=chooser-v1) (https://github.com/person1234-ux/evanserver).
*/
package org.items;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
public class rules_book implements Listener {
private ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
private BookMeta meta = (BookMeta) book.getItemMeta();
public void get_rules_book(Player pLayer){
//todo make the rule book look better.S
meta.addPage("No stealing\nNo Griefing property or players\nDo not be toxic or bully others\nNo potty words\nNo inappropriate builds\nNo cheating or using mods outside of client like lunar or bad lion\nNo duplicating items\nAll damaged property must be replaced");
meta.addPage("Shops must be fairly priced and no stealing or taking items without paying.\nDo not make lag farms or builds intended to cause major lag.\nNo hogging, hoarding or intentionally killing animals to prevent others from obtaining them.");
meta.addPage("No talking to people using there real life name");
meta.setAuthor("Person1");
meta.setDisplayName("rules");
meta.setTitle("Rules");
meta.addEnchant(Enchantment.VANISHING_CURSE, 1, true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
book.setItemMeta(meta);
pLayer.getInventory().setItemInMainHand(book);
}
}
|
3e11fe91cda8aab7d1263a52bac3ef10bec95ca6 | 754 | java | Java | src/main/java/Main.java | wi19b075/MaintMonit | 5e83016cd9194eabe271d8d4a27ae08c2b2cae6b | [
"MIT"
] | null | null | null | src/main/java/Main.java | wi19b075/MaintMonit | 5e83016cd9194eabe271d8d4a27ae08c2b2cae6b | [
"MIT"
] | 7 | 2021-05-16T17:43:04.000Z | 2021-05-16T17:44:59.000Z | src/main/java/Main.java | wi19b075/MaintMonit | 5e83016cd9194eabe271d8d4a27ae08c2b2cae6b | [
"MIT"
] | null | null | null | 29 | 108 | 0.659151 | 7,585 | import com.sun.net.httpserver.HttpServer;
import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import java.io.IOException;
import java.net.URI;
public class Main {
public static void main(String[] args) {
System.out.println("Starting REST service...");
ResourceConfig rc = new ResourceConfig().packages("controller");
HttpServer server = JdkHttpServerFactory.createHttpServer(URI.create("http://localhost:8080/"), rc);
System.out.println("Server started");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
server.stop( 0);
System.out.println("Server stopped");
}
}
|
3e11feca077acf9ac7263fe948502697e0853f05 | 76 | java | Java | HerbalistApp/src/generic/package-info.java | aqeeph/Aqeeph | a3d5e89235f63f5f05c892cbbe3720e0784b1f5d | [
"MIT"
] | 1 | 2020-12-30T22:59:17.000Z | 2020-12-30T22:59:17.000Z | HerbalistApp/src/generic/package-info.java | aqeeph/Aqeeph | a3d5e89235f63f5f05c892cbbe3720e0784b1f5d | [
"MIT"
] | null | null | null | HerbalistApp/src/generic/package-info.java | aqeeph/Aqeeph | a3d5e89235f63f5f05c892cbbe3720e0784b1f5d | [
"MIT"
] | null | null | null | 9.5 | 36 | 0.565789 | 7,586 | /**
*
*/
/**
* @author MEHMET AKIF ILYASOGULLARI
*
*/
package generic; |
3e11fee5c316f733a92598d152691cac3fd452af | 412 | java | Java | java/java-indexing-api/src/com/intellij/openapi/roots/ModulePackageIndex.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2019-04-28T07:48:50.000Z | 2020-12-11T14:18:08.000Z | java/java-indexing-api/src/com/intellij/openapi/roots/ModulePackageIndex.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 2 | 2022-02-19T09:45:05.000Z | 2022-02-27T20:32:55.000Z | java/java-indexing-api/src/com/intellij/openapi/roots/ModulePackageIndex.java | nvartolomei/intellij-community | 1aac326dadacf65d45decc25cef21f94f7b80d69 | [
"Apache-2.0"
] | 1 | 2020-10-15T05:56:42.000Z | 2020-10-15T05:56:42.000Z | 37.454545 | 140 | 0.796117 | 7,587 | // Copyright 2000-2020 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 com.intellij.openapi.roots;
import com.intellij.openapi.module.Module;
public abstract class ModulePackageIndex extends PackageIndex {
public static ModulePackageIndex getInstance(Module module) {
return module.getService(ModulePackageIndex.class);
}
}
|
3e11ffe223899b95cbc45a833c905b4ca7a5317b | 549 | java | Java | src/org/usfirst/frc/team4256/robot/Autonomous/O_Encoder.java | Team4256/4256-18-Faraday | 2167dba21f3e070210e37a9b5e0e82afd7e9e109 | [
"MIT"
] | 1 | 2018-08-03T11:38:56.000Z | 2018-08-03T11:38:56.000Z | src/org/usfirst/frc/team4256/robot/Autonomous/O_Encoder.java | Team4256/4256-18-Faraday | 2167dba21f3e070210e37a9b5e0e82afd7e9e109 | [
"MIT"
] | null | null | null | src/org/usfirst/frc/team4256/robot/Autonomous/O_Encoder.java | Team4256/4256-18-Faraday | 2167dba21f3e070210e37a9b5e0e82afd7e9e109 | [
"MIT"
] | 4 | 2018-07-10T07:15:06.000Z | 2019-10-19T21:26:04.000Z | 27.45 | 68 | 0.770492 | 7,588 | package org.usfirst.frc.team4256.robot.Autonomous;
import org.usfirst.frc.team4256.robot.SwerveModule;
import com.cyborgcats.reusable.Autonomous.Odometer;
public final class O_Encoder extends Odometer {
private SwerveModule module;
public O_Encoder(final SwerveModule module) {this.module = module;}
public void updateX() {x.increment(module.deltaXDistance());}
public void updateY() {y.increment(module.deltaYDistance());}
@Override
public void completeLoopUpdate() {updateX();updateY();}
@Override
public void init() {}//unused
}
|
3e1200369ec4c5625eb8155b53a3d7f10bd8efca | 3,366 | java | Java | aliyun-java-sdk-dcdn/src/main/java/com/aliyuncs/dcdn/transform/v20180115/DescribeDcdnDomainIspDataResponseUnmarshaller.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 3 | 2020-04-26T09:15:45.000Z | 2020-05-09T03:10:26.000Z | aliyun-java-sdk-dcdn/src/main/java/com/aliyuncs/dcdn/transform/v20180115/DescribeDcdnDomainIspDataResponseUnmarshaller.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 27 | 2021-06-11T21:08:40.000Z | 2022-03-11T21:25:09.000Z | aliyun-java-sdk-dcdn/src/main/java/com/aliyuncs/dcdn/transform/v20180115/DescribeDcdnDomainIspDataResponseUnmarshaller.java | cctvzd7/aliyun-openapi-java-sdk | b8e4dce2a61ca968615c9b910bedebaea71781ae | [
"Apache-2.0"
] | 1 | 2020-03-05T07:30:16.000Z | 2020-03-05T07:30:16.000Z | 60.107143 | 156 | 0.808378 | 7,589 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.dcdn.transform.v20180115;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.dcdn.model.v20180115.DescribeDcdnDomainIspDataResponse;
import com.aliyuncs.dcdn.model.v20180115.DescribeDcdnDomainIspDataResponse.IspProportionData;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeDcdnDomainIspDataResponseUnmarshaller {
public static DescribeDcdnDomainIspDataResponse unmarshall(DescribeDcdnDomainIspDataResponse describeDcdnDomainIspDataResponse, UnmarshallerContext _ctx) {
describeDcdnDomainIspDataResponse.setRequestId(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.RequestId"));
describeDcdnDomainIspDataResponse.setDomainName(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.DomainName"));
describeDcdnDomainIspDataResponse.setDataInterval(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.DataInterval"));
describeDcdnDomainIspDataResponse.setStartTime(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.StartTime"));
describeDcdnDomainIspDataResponse.setEndTime(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.EndTime"));
List<IspProportionData> value = new ArrayList<IspProportionData>();
for (int i = 0; i < _ctx.lengthValue("DescribeDcdnDomainIspDataResponse.Value.Length"); i++) {
IspProportionData ispProportionData = new IspProportionData();
ispProportionData.setIsp(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].Isp"));
ispProportionData.setProportion(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].Proportion"));
ispProportionData.setIspEname(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].IspEname"));
ispProportionData.setAvgObjectSize(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].AvgObjectSize"));
ispProportionData.setAvgResponseTime(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].AvgResponseTime"));
ispProportionData.setBps(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].Bps"));
ispProportionData.setQps(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].Qps"));
ispProportionData.setAvgResponseRate(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].AvgResponseRate"));
ispProportionData.setTotalBytes(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].TotalBytes"));
ispProportionData.setBytesProportion(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].BytesProportion"));
ispProportionData.setTotalQuery(_ctx.stringValue("DescribeDcdnDomainIspDataResponse.Value["+ i +"].TotalQuery"));
value.add(ispProportionData);
}
describeDcdnDomainIspDataResponse.setValue(value);
return describeDcdnDomainIspDataResponse;
}
} |
3e12006b5cb083a8b0a118c8a5374f37657b8bd5 | 3,392 | java | Java | core/sparqlbuilder/src/test/java/org/eclipse/rdf4j/sparqlbuilder/examples/sparql11spec/Section4Test.java | yanaspaula/rdf4j | e75f8940c48caf9847dd775fd6a67866dc9b9dcd | [
"BSD-3-Clause"
] | 312 | 2016-01-14T20:04:24.000Z | 2022-03-30T22:21:41.000Z | core/sparqlbuilder/src/test/java/org/eclipse/rdf4j/sparqlbuilder/examples/sparql11spec/Section4Test.java | yanaspaula/rdf4j | e75f8940c48caf9847dd775fd6a67866dc9b9dcd | [
"BSD-3-Clause"
] | 2,611 | 2016-01-18T22:32:22.000Z | 2022-03-31T17:38:43.000Z | core/sparqlbuilder/src/test/java/org/eclipse/rdf4j/sparqlbuilder/examples/sparql11spec/Section4Test.java | yanaspaula/rdf4j | e75f8940c48caf9847dd775fd6a67866dc9b9dcd | [
"BSD-3-Clause"
] | 186 | 2016-01-14T21:18:37.000Z | 2022-03-22T12:32:33.000Z | 36.085106 | 102 | 0.686616 | 7,590 | /*******************************************************************************
Copyright (c) 2018 Eclipse RDF4J contributors.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Distribution License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sparqlbuilder.examples.sparql11spec;
import static org.eclipse.rdf4j.sparqlbuilder.rdf.Rdf.iri;
import org.eclipse.rdf4j.sparqlbuilder.core.Prefix;
import org.eclipse.rdf4j.sparqlbuilder.core.SparqlBuilder;
import org.eclipse.rdf4j.sparqlbuilder.core.Variable;
import org.eclipse.rdf4j.sparqlbuilder.examples.BaseExamples;
import org.eclipse.rdf4j.sparqlbuilder.graphpattern.GraphPatterns;
import org.eclipse.rdf4j.sparqlbuilder.graphpattern.TriplePattern;
import org.eclipse.rdf4j.sparqlbuilder.rdf.Iri;
import org.eclipse.rdf4j.sparqlbuilder.rdf.Rdf;
import org.eclipse.rdf4j.sparqlbuilder.rdf.RdfBlankNode;
import org.eclipse.rdf4j.sparqlbuilder.rdf.RdfBlankNode.PropertiesBlankNode;
import org.eclipse.rdf4j.sparqlbuilder.rdf.RdfLiteral.StringLiteral;
import org.eclipse.rdf4j.sparqlbuilder.rdf.RdfPredicate;
import org.junit.Test;
public class Section4Test extends BaseExamples {
Prefix foaf = SparqlBuilder.prefix("foaf", iri(FOAF_NS));
Variable x = SparqlBuilder.var("x"), name = SparqlBuilder.var("name");
@Test
public void example_4_1_4() {
Prefix defPrefix = SparqlBuilder.prefix(iri(DC_NS));
// [ :p "v" ] .
PropertiesBlankNode bnode = Rdf.bNode(defPrefix.iri("p"), Rdf.literalOf("v"));
p(bnode.toTp());
// [] :p "v" .
TriplePattern tp = Rdf.bNode().has(defPrefix.iri("p"), Rdf.literalOf("v"));
p(tp);
// [ :p "v" ] :q "w" .
tp = bnode.has(defPrefix.iri("q"), Rdf.literalOf("w"));
p(tp);
// :x :q [ :p "v" ] .
tp = defPrefix.iri("x").has(defPrefix.iri("q"), bnode);
p(tp);
RdfBlankNode labelledNode = Rdf.bNode("b57");
p(defPrefix.iri("x").has(defPrefix.iri("q"), labelledNode));
p(labelledNode.has(defPrefix.iri("p"), "v"));
// [ foaf:name ?name ;
// foaf:mbox <mailto:hzdkv@example.com> ]
bnode = Rdf.bNode(foaf.iri("name"), name).andHas(foaf.iri("mbox"), iri("mailto:hzdkv@example.com"));
p(bnode);
}
@Test
public void example_4_2_1() {
Variable mbox = SparqlBuilder.var("mbox");
TriplePattern tp = GraphPatterns.tp(x, foaf.iri("name"), name).andHas(foaf.iri("mbox"), mbox);
p(tp);
}
@Test
public void example_4_2_2() {
Prefix foaf = SparqlBuilder.prefix("foaf", iri(FOAF_NS));
Variable x = SparqlBuilder.var("x"), name = SparqlBuilder.var("name");
Iri nick = foaf.iri("nick");
StringLiteral aliceNick = Rdf.literalOf("Alice"), alice_Nick = Rdf.literalOf("Alice_");
TriplePattern tp = GraphPatterns.tp(x, nick, alice_Nick, aliceNick);
p(tp);
tp = x.has(nick, aliceNick, alice_Nick).andHas(foaf.iri("name"), name);
p(tp);
}
@Test
public void example_4_2_4() {
Prefix defPrefix = SparqlBuilder.prefix(iri(DC_NS));
// isA() is a shortcut method to create triples using the "a" keyword
p(SparqlBuilder.var("x").isA(defPrefix.iri("Class1")));
// the isA predicate is a static member of RdfPredicate
p(Rdf.bNode(RdfPredicate.a, defPrefix.iri("appClass")).has(defPrefix.iri("p"), "v"));
}
}
|
3e1200beaeafe73a04ef668c98fd4394998bd227 | 1,489 | java | Java | org.onexus.collection.api/src/main/java/org/onexus/collection/api/query/NotEqual.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 2 | 2015-10-09T13:14:20.000Z | 2016-05-05T01:38:29.000Z | org.onexus.collection.api/src/main/java/org/onexus/collection/api/query/NotEqual.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 9 | 2020-06-30T22:53:38.000Z | 2022-01-21T23:10:11.000Z | org.onexus.collection.api/src/main/java/org/onexus/collection/api/query/NotEqual.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 1 | 2016-02-24T12:11:20.000Z | 2016-02-24T12:11:20.000Z | 29.78 | 93 | 0.672263 | 7,591 | /**
* Copyright 2012 Universitat Pompeu Fabra.
*
* 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.onexus.collection.api.query;
/**
* This filter, filters out the collection 'collectionAlias' entities that the 'fieldId'
* have a exact match of the given 'value'.
*/
public class NotEqual extends AtomicFilter {
/**
* Keep this constructor for JAXB compatibility.
*/
@SuppressWarnings("UnusedDeclaration")
public NotEqual() {
super();
}
/**
* Create a NOT EQUAL filter.
*
* @param collectionAlias The collection alias to filter.
* @param fieldId The filter id to filter.
* @param value The value to use when filtering.
*/
public NotEqual(final String collectionAlias, final String fieldId, final Object value) {
super(collectionAlias, fieldId, value);
}
@Override
public final String getOperandSymbol() {
return "!=";
}
}
|
3e12013c96d4a37cadeaba4c9b1f88610d16d830 | 1,469 | java | Java | activiti-api/activiti-task-model-api/src/main/java/org/activiti/runtime/api/model/builders/CreateTaskPayloadBuilder.java | zlj0626/Activiti | b76df4941aa931f7d2be251c8e95e36acf047a96 | [
"Apache-2.0"
] | 1 | 2018-08-08T07:51:23.000Z | 2018-08-08T07:51:23.000Z | activiti-api/activiti-task-model-api/src/main/java/org/activiti/runtime/api/model/builders/CreateTaskPayloadBuilder.java | mnloveyx/Activiti | b76df4941aa931f7d2be251c8e95e36acf047a96 | [
"Apache-2.0"
] | null | null | null | activiti-api/activiti-task-model-api/src/main/java/org/activiti/runtime/api/model/builders/CreateTaskPayloadBuilder.java | mnloveyx/Activiti | b76df4941aa931f7d2be251c8e95e36acf047a96 | [
"Apache-2.0"
] | null | null | null | 26.709091 | 75 | 0.610619 | 7,592 | package org.activiti.runtime.api.model.builders;
import java.util.Date;
import org.activiti.runtime.api.model.payloads.CreateTaskPayload;
public class CreateTaskPayloadBuilder {
private String name;
private String description;
private Date dueDate;
private int priority;
private String assignee;
private String parentTaskId;
public CreateTaskPayloadBuilder withName(String name) {
this.name = name;
return this;
}
public CreateTaskPayloadBuilder withDescription(String description) {
this.description = description;
return this;
}
public CreateTaskPayloadBuilder withDueDate(Date dueDate) {
this.dueDate = dueDate;
return this;
}
public CreateTaskPayloadBuilder withPriority(int priority) {
this.priority = priority;
return this;
}
public CreateTaskPayloadBuilder withAssignee(String assignee) {
this.assignee = assignee;
return this;
}
public CreateTaskPayloadBuilder withParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
return this;
}
public CreateTaskPayload build() {
return new CreateTaskPayload(name,
description,
dueDate,
priority,
assignee,
parentTaskId);
}
}
|
3e120205aab612cee180bd38ad94a04aa18dc7f3 | 903 | java | Java | src/test/java/house1706jin/ProCityDisTest.java | jyj019/java_hss_HouseSystem | cc0a23e67d5b723b642cdec31b8c80db74ed2426 | [
"Apache-2.0"
] | null | null | null | src/test/java/house1706jin/ProCityDisTest.java | jyj019/java_hss_HouseSystem | cc0a23e67d5b723b642cdec31b8c80db74ed2426 | [
"Apache-2.0"
] | null | null | null | src/test/java/house1706jin/ProCityDisTest.java | jyj019/java_hss_HouseSystem | cc0a23e67d5b723b642cdec31b8c80db74ed2426 | [
"Apache-2.0"
] | null | null | null | 23.153846 | 71 | 0.781838 | 7,593 | package house1706jin;
import static org.junit.Assert.*;
import java.util.Date;
import org.hibernate.Session;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.jyj019.service.UserService;
import com.jyj019.util.HibernateUtil;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app.xml")
public class ProCityDisTest {
@Autowired
private UserService userService;
@Test
public void test() {
Session session = HibernateUtil.getSession();
session.beginTransaction();
// session.persist(user);
// session.persist(login);
// session.persist(idCard);
// session.save(idCard2);
session.getTransaction().commit();
session.close();
}
}
|
3e120229b8ec6177778ef55849bf83855d0e0651 | 659 | java | Java | src/husacct/analyse/task/analyser/java/SkippedTypes.java | senkz/HUSACCT | 4888062b1a933c5e8458a6d087a3c6f3781207e7 | [
"MIT"
] | null | null | null | src/husacct/analyse/task/analyser/java/SkippedTypes.java | senkz/HUSACCT | 4888062b1a933c5e8458a6d087a3c6f3781207e7 | [
"MIT"
] | null | null | null | src/husacct/analyse/task/analyser/java/SkippedTypes.java | senkz/HUSACCT | 4888062b1a933c5e8458a6d087a3c6f3781207e7 | [
"MIT"
] | 1 | 2021-02-02T12:58:55.000Z | 2021-02-02T12:58:55.000Z | 19.969697 | 76 | 0.579666 | 7,594 | package husacct.analyse.task.analyser.java;
import java.util.EnumSet;
enum SkippedTypes {
STRING("String"),
INT("int"),
BOOLEAN("boolean"),
OBJECT("Object"),
BYTE("byte"),
CHAR("char");
private final String type;
private SkippedTypes(String type) {
this.type = type;
}
@Override
public String toString() {
return type;
}
public static boolean isSkippable(String type) {
for (SkippedTypes skippedType : EnumSet.allOf(SkippedTypes.class)) {
if (skippedType.toString().equals(type)) {
return true;
}
}
return false;
}
}
|
3e1202cde85ebf988041d06026633d9414a2b6ea | 8,546 | java | Java | org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java | WANdisco/j | 93c05566da91d1870964f9b6d86e605d91a80e24 | [
"Apache-2.0"
] | 2 | 2016-05-24T09:37:14.000Z | 2021-02-22T16:44:25.000Z | org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java | WANdisco/j | 93c05566da91d1870964f9b6d86e605d91a80e24 | [
"Apache-2.0"
] | 13 | 2021-02-03T19:27:07.000Z | 2022-01-04T16:56:15.000Z | org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java | WANdisco/jgit | 93c05566da91d1870964f9b6d86e605d91a80e24 | [
"Apache-2.0"
] | null | null | null | 35.645833 | 106 | 0.749386 | 7,595 | /*
* Copyright (C) 2012-2013, Robin Rosenberg <ychag@example.com>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.util;
import static java.time.Instant.EPOCH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.time.Duration;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.errors.CommandFailedException;
import org.eclipse.jgit.junit.MockSystemReader;
import org.eclipse.jgit.junit.RepositoryTestCase;
import org.eclipse.jgit.lib.RepositoryCache;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
public class FSTest {
private File trash;
@Before
public void setUp() throws Exception {
SystemReader.setInstance(new MockSystemReader());
trash = File.createTempFile("tmp_", "");
trash.delete();
assertTrue("mkdir " + trash, trash.mkdir());
}
@After
public void tearDown() throws Exception {
FileUtils.delete(trash, FileUtils.RECURSIVE | FileUtils.RETRY);
}
/**
* The old File methods traverse symbolic links and look at the targets.
* With symbolic links we usually want to modify/look at the link. For some
* reason the executable attribute seems to always look at the target, but
* for the other attributes like lastModified, hidden and exists we must
* differ between the link and the target.
*
* @throws IOException
* @throws InterruptedException
*/
@Test
public void testSymlinkAttributes() throws IOException, InterruptedException {
Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
FS fs = FS.DETECTED;
File link = new File(trash, "ä");
File target = new File(trash, "å");
fs.createSymLink(link, "å");
assertTrue(fs.exists(link));
String targetName = fs.readSymLink(link);
assertEquals("å", targetName);
assertTrue(fs.lastModifiedInstant(link).compareTo(EPOCH) > 0);
assertTrue(fs.exists(link));
assertFalse(fs.canExecute(link));
assertEquals(2, fs.length(link));
assertFalse(fs.exists(target));
assertFalse(fs.isFile(target));
assertFalse(fs.isDirectory(target));
assertFalse(fs.canExecute(target));
RepositoryTestCase.fsTick(link);
// Now create the link target
FileUtils.createNewFile(target);
assertTrue(fs.exists(link));
assertTrue(fs.lastModifiedInstant(link).compareTo(EPOCH) > 0);
assertTrue(fs.lastModifiedInstant(target)
.compareTo(fs.lastModifiedInstant(link)) > 0);
assertFalse(fs.canExecute(link));
fs.setExecute(target, true);
assertFalse(fs.canExecute(link));
assumeTrue(fs.supportsExecute());
assertTrue(fs.canExecute(target));
}
@Test
public void testExecutableAttributes() throws Exception {
FS fs = FS.DETECTED.newInstance();
// If this assumption fails the test is halted and ignored.
assumeTrue(fs instanceof FS_POSIX);
((FS_POSIX) fs).setUmask(0022);
File f = new File(trash, "bla");
assertTrue(f.createNewFile());
assertFalse(fs.canExecute(f));
Set<PosixFilePermission> permissions = readPermissions(f);
assertTrue(!permissions.contains(PosixFilePermission.OTHERS_EXECUTE));
assertTrue(!permissions.contains(PosixFilePermission.GROUP_EXECUTE));
assertTrue(!permissions.contains(PosixFilePermission.OWNER_EXECUTE));
fs.setExecute(f, true);
permissions = readPermissions(f);
assertTrue("'owner' execute permission not set",
permissions.contains(PosixFilePermission.OWNER_EXECUTE));
assertTrue("'group' execute permission not set",
permissions.contains(PosixFilePermission.GROUP_EXECUTE));
assertTrue("'others' execute permission not set",
permissions.contains(PosixFilePermission.OTHERS_EXECUTE));
((FS_POSIX) fs).setUmask(0033);
fs.setExecute(f, false);
assertFalse(fs.canExecute(f));
fs.setExecute(f, true);
permissions = readPermissions(f);
assertTrue("'owner' execute permission not set",
permissions.contains(PosixFilePermission.OWNER_EXECUTE));
assertFalse("'group' execute permission set",
permissions.contains(PosixFilePermission.GROUP_EXECUTE));
assertFalse("'others' execute permission set",
permissions.contains(PosixFilePermission.OTHERS_EXECUTE));
}
private Set<PosixFilePermission> readPermissions(File f) throws IOException {
return Files
.getFileAttributeView(f.toPath(), PosixFileAttributeView.class)
.readAttributes().permissions();
}
@Test(expected = CommandFailedException.class)
public void testReadPipePosixCommandFailure()
throws CommandFailedException {
FS fs = FS.DETECTED.newInstance();
assumeTrue(fs instanceof FS_POSIX);
FS.readPipe(fs.userHome(),
new String[] { "/bin/sh", "-c", "exit 1" },
Charset.defaultCharset().name());
}
@Test(expected = CommandFailedException.class)
public void testReadPipeCommandStartFailure()
throws CommandFailedException {
FS fs = FS.DETECTED.newInstance();
FS.readPipe(fs.userHome(),
new String[] { "this-command-does-not-exist" },
Charset.defaultCharset().name());
}
@Test
public void testFsTimestampResolution() throws Exception {
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("uuuu-MMM-dd HH:mm:ss.nnnnnnnnn", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
Path dir = Files.createTempDirectory("probe-filesystem");
Duration resolution = FS.getFileStoreAttributes(dir)
.getFsTimestampResolution();
long resolutionNs = resolution.toNanos();
assertTrue(resolutionNs > 0);
for (int i = 0; i < 10; i++) {
Path f = null;
try {
f = dir.resolve("testTimestampResolution" + i);
Files.createFile(f);
FileUtils.touch(f);
FileTime t1 = Files.getLastModifiedTime(f);
TimeUnit.NANOSECONDS.sleep(resolutionNs);
FileUtils.touch(f);
FileTime t2 = Files.getLastModifiedTime(f);
assertTrue(String.format(
"expected t2=%s to be larger than t1=%s\nsince file timestamp resolution was measured to be %,d ns",
formatter.format(t2.toInstant()),
formatter.format(t1.toInstant()),
Long.valueOf(resolutionNs)), t2.compareTo(t1) > 0);
} finally {
Files.delete(f);
}
}
}
// bug 548682
@Test
public void testRepoCacheRelativePathUnbornRepo() {
assertFalse(RepositoryCache.FileKey
.isGitRepository(new File("repo.git"), FS.DETECTED));
}
}
|
3e12041996bb32da081f06d95f57df16871ec40c | 1,881 | java | Java | mavenDemo2/src/main/java/com/itdr/pojo/Order.java | SAKURAFLY0910/javaweb-jy5 | d93f54297b133da05af9ec8049a1e6a72e6ea234 | [
"Apache-2.0"
] | 1 | 2020-06-04T08:18:00.000Z | 2020-06-04T08:18:00.000Z | mavenDemo2/src/main/java/com/itdr/pojo/Order.java | SAKURAFLY0910/javaweb-jy5 | d93f54297b133da05af9ec8049a1e6a72e6ea234 | [
"Apache-2.0"
] | 5 | 2021-12-09T22:53:09.000Z | 2021-12-14T21:54:46.000Z | mavenDemo2/src/main/java/com/itdr/pojo/Order.java | TAOYONG12138/javaweb-jy5 | d93f54297b133da05af9ec8049a1e6a72e6ea234 | [
"Apache-2.0"
] | null | null | null | 22.129412 | 64 | 0.570973 | 7,596 | package com.itdr.pojo;
public class Order {
private Integer id;
private Integer status;
private String orderNo;
private double payment;
private Integer paymentType;
private String paymentTypeDesc;
private String productName;
// private Integer status;
// private long createTime;
// private long updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public double getPayment() {
return payment;
}
public void setPayment(double payment) {
this.payment = payment;
}
public Integer getPaymentType() {
return paymentType;
}
public void setPaymentType(Integer paymentType) {
this.paymentType = paymentType;
}
public String getPaymentTypeDesc() {
return paymentTypeDesc;
}
public void setPaymentTypeDesc(String paymentTypeDesc) {
this.paymentTypeDesc = paymentTypeDesc;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", status=" + status +
", orderNo='" + orderNo + '\'' +
", payment=" + payment +
", paymentType=" + paymentType +
", paymentTypeDesc='" + paymentTypeDesc + '\'' +
", productName='" + productName + '\'' +
'}';
}
}
|
3e12046585d51d73ff82004bbd195fa8036f68d9 | 453 | java | Java | piflow-web/src/main/java/cn/cnic/component/testData/vo/TestDataSchemaVo.java | zrsaber/piflow-web | 5998fbe73dd0a5a05dc8709e2ead4dc0cd84c870 | [
"Apache-2.0"
] | 58 | 2018-12-20T10:12:43.000Z | 2022-03-07T08:25:53.000Z | piflow-web/src/main/java/cn/cnic/component/testData/vo/TestDataSchemaVo.java | zrsaber/piflow-web | 5998fbe73dd0a5a05dc8709e2ead4dc0cd84c870 | [
"Apache-2.0"
] | 11 | 2019-07-31T03:45:03.000Z | 2022-03-02T09:44:16.000Z | piflow-web/src/main/java/cn/cnic/component/testData/vo/TestDataSchemaVo.java | zrsaber/piflow-web | 5998fbe73dd0a5a05dc8709e2ead4dc0cd84c870 | [
"Apache-2.0"
] | 31 | 2018-12-20T10:13:00.000Z | 2022-03-10T03:20:32.000Z | 19.695652 | 80 | 0.761589 | 7,597 | package cn.cnic.component.testData.vo;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class TestDataSchemaVo {
private String id;
private String fieldName;
private String fieldType;
private String fieldDescription;
private int fieldSoft;
private TestDataVo testDataVo;
private List<TestDataSchemaValuesVo> schemaValuesVoList = new ArrayList<>();
}
|
3e1204d083b18a70a0696f15a91f5f0251b10bde | 541 | java | Java | src/sune/ssp/etc/ServerClientInfo.java | sunecz/SSP | 5e241b33efba625a92b0afb0a0e387f9512798d0 | [
"MIT"
] | null | null | null | src/sune/ssp/etc/ServerClientInfo.java | sunecz/SSP | 5e241b33efba625a92b0afb0a0e387f9512798d0 | [
"MIT"
] | 4 | 2016-02-11T13:37:25.000Z | 2016-03-27T09:29:23.000Z | src/sune/ssp/etc/ServerClientInfo.java | sunecz/SSP | 5e241b33efba625a92b0afb0a0e387f9512798d0 | [
"MIT"
] | null | null | null | 20.807692 | 74 | 0.700555 | 7,598 | package sune.ssp.etc;
import sune.ssp.data.Data;
public class ServerClientInfo extends Data {
private static final long serialVersionUID = 2611084921759964621L;
public ServerClientInfo(String ipAddress, String uuid, String username) {
super("ipAddress", ipAddress,
"uuid", uuid,
"username", username);
}
public String getIP() {
return (String) getData("ipAddress");
}
public String getUUID() {
return (String) getData("uuid");
}
public String getUsername() {
return (String) getData("username");
}
} |
3e1205140918a0b50bb0aab4da5ea8e63e0de77b | 308 | java | Java | src/main/java/com/virtualsoundnw/resume/repository/AuthorityRepository.java | BulkSecurityGeneratorProject/resume-system | de336878c05a1a058f7864bc47547731c7a9433f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/virtualsoundnw/resume/repository/AuthorityRepository.java | BulkSecurityGeneratorProject/resume-system | de336878c05a1a058f7864bc47547731c7a9433f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/virtualsoundnw/resume/repository/AuthorityRepository.java | BulkSecurityGeneratorProject/resume-system | de336878c05a1a058f7864bc47547731c7a9433f | [
"Apache-2.0"
] | 1 | 2020-09-18T15:13:18.000Z | 2020-09-18T15:13:18.000Z | 25.666667 | 79 | 0.814935 | 7,599 | package com.virtualsoundnw.resume.repository;
import com.virtualsoundnw.resume.domain.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the Authority entity.
*/
public interface AuthorityRepository extends JpaRepository<Authority, String> {
}
|
3e1205668ba437afe848d62e3c877450fbd92837 | 11,837 | java | Java | JavaSimulator/lib/frodo2/src/frodo2/algorithms/MASparser.java | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 3 | 2020-04-10T09:13:17.000Z | 2021-04-08T07:14:03.000Z | JavaSimulator/lib/frodo2/src/frodo2/algorithms/MASparser.java | Adamas-Polaris/DCOP-Decentralised-Control-of-Intelligent-Devices | c634a8be59b93f2e6fc03118c2047403d15be0c5 | [
"MIT"
] | 8 | 2020-09-26T00:55:30.000Z | 2022-01-13T02:32:04.000Z | JavaSimulator/lib/frodo2/src/frodo2/algorithms/MASparser.java | Adamas-Polaris/DCOP-Decentralised-Control-of-Intelligent-Devices | c634a8be59b93f2e6fc03118c2047403d15be0c5 | [
"MIT"
] | 2 | 2020-04-12T10:08:15.000Z | 2022-01-20T09:34:50.000Z | 31.481383 | 130 | 0.717243 | 7,600 | /*
FRODO: a FRamework for Open/Distributed Optimization
Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek
FRODO is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FRODO 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
How to contact the authors:
<http://frodo2.sourceforge.net/>
*/
package frodo2.algorithms;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaders;
import frodo2.solutionSpaces.Addable;
import frodo2.solutionSpaces.AddableInteger;
import frodo2.solutionSpaces.MASProblemInterface;
import frodo2.solutionSpaces.ProblemInterface;
/** A MASproblem parser that is able to handle multiple types of agents
* @author Brammert Ottens, 8 jun 2010
* @param <U> the type used for decision values
* @param <V> the type used for utility values
*/
@SuppressWarnings("unchecked")
public class MASparser <V extends Addable<V>, U extends Addable<U>> implements MASProblemInterface<V, U> {
/** Used for serialization */
private static final long serialVersionUID = 5407324017599034300L;
/** the JDOM root element*/
protected Element root;
/** the name of the agent owning the problem, if applicable */
private String agentName;
/** the type of the agent owning this problem */
protected String type;
/** The class to be used for variable values */
protected Class<V> domClass = (Class<V>) AddableInteger.class;
/** The class to be used for utility values */
protected Class<U> utilClass = (Class<U>) AddableInteger.class;
/** Whether to count constraint checks */
protected final boolean countNCCCs;
/** a set of spaces for which ncccs should be ignored */
protected HashSet<String> spacesToIgnoreNcccs;
/** The NCCC count */
private long ncccCount;
/** Creates a JDOM Document out of the input XML file
* @param file the XML file
* @return a JDOM Document resulting from the parsing of the input file
* @throws JDOMException if a parsing error occurs while reading the file
* @throws IOException if an I/O error occurs while accessing the file
* @author Thomas Leaute
*/
public static Document parse (File file) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
builder.setFeature("http://apache.org/xml/features/xinclude", true);
return builder.build(file);
}
/** Creates a JDOM Document out of the input XML file path in XCSP format
* @param path the XML file path
* @return a JDOM Document resulting from the parsing of the input file
* @throws JDOMException if a parsing error occurs while reading the file
* @throws IOException if an I/O error occurs while accessing the file
*/
public static Document parse (String path) throws JDOMException, IOException {
return parse(new File (path));
}
/** Creates a JDOM Document out of the input XML stream in XCSP format
* @param stream the XML stream
* @return a JDOM Document resulting from the parsing of the input file
* @throws JDOMException if a parsing error occurs while reading the file
* @throws IOException if an I/O error occurs while accessing the file
* @author Thomas Leaute
*/
public static Document parse (InputStream stream) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
builder.setFeature("http://apache.org/xml/features/xinclude", true);
return builder.build(stream);
}
/** Constructor from a JDOM root Element
* @param root the JDOM root Element
*/
public MASparser(Element root) {
this.root = root;
this.countNCCCs = false;
this.spacesToIgnoreNcccs = new HashSet<String>();
}
/** Constructor from a JDOM root Element
* @param root the JDOM root Element
* @param countNCCCs \c true when NCCCs should be counted
*/
public MASparser(Element root, boolean countNCCCs) {
this.root = root;
this.countNCCCs = countNCCCs;
this.spacesToIgnoreNcccs = new HashSet<String>();
}
/** Constructor from a JDOM root Element
* @param agentName the name of the agent owning the input subproblem
* @param type the type of the agent
* @param root the JDOM root Element
* @param countNCCCs \c true when NCCCs should be counted
* @param spacesToIgnoreNcccs the list of spaces who's NCCCs should not be counted
*/
public MASparser(String agentName, String type, Element root, boolean countNCCCs, HashSet<String> spacesToIgnoreNcccs) {
this.root = root;
this.type = type;
this.countNCCCs = countNCCCs;
this.agentName = agentName;
this.spacesToIgnoreNcccs = spacesToIgnoreNcccs;
}
/** Constructor from a JDOM root Element
* @param agentName the name of the agent owning the input subproblem
* @param type the type of the agent
* @param root the JDOM root Element
* @param countNCCCs \c true when NCCCs should be counted
*/
public MASparser(String agentName, String type, Element root, boolean countNCCCs) {
this.root = root;
this.type = type;
this.countNCCCs = countNCCCs;
this.agentName = agentName;
this.spacesToIgnoreNcccs = new HashSet<String>();
}
/** Constructor from a JDOM Document
* @param doc the JDOM Document
*/
public MASparser(Document doc) {
this(doc.getRootElement());
}
/** Constructor
* @param doc the JDOM Document
* @param params the parameters of the parser
*/
public MASparser(Document doc, Element params) {
this.root = doc.getRootElement();
// Parse the class of U
String utilClassName = params.getAttributeValue("utilClass");
if (utilClassName == null)
this.setUtilClass((Class<U>) AddableInteger.class);
else {
try {
this.setUtilClass((Class<U>) Class.forName(utilClassName));
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
// Parse whether we should count NCCCs
String ncccString = params.getAttributeValue("countNCCCs");
if (ncccString == null)
this.countNCCCs = false;
else
this.countNCCCs = Boolean.parseBoolean(ncccString);
// Parse which spaces should be ignored
spacesToIgnoreNcccs = new HashSet<String>();
Element spacesToIgnore = params.getChild("ignoreNCCCs");
if(spacesToIgnore != null) {
List<Element> list = spacesToIgnore.getChildren();
for(Element classElmt : list)
this.spacesToIgnoreNcccs.add(classElmt.getText());
}
}
/**
* @see frodo2.solutionSpaces.MASProblemInterface#getType()
*/
public String getType() {
return type;
}
/**
* @see frodo2.solutionSpaces.ProblemInterface#getAgent()
*/
public String getAgent() {
return this.agentName;
}
/**
* @see frodo2.solutionSpaces.ProblemInterface#getAgents()
*/
public Set<String> getAgents() {
List<Element> agentElmts = (List<Element>)root.getChildren("agent");
Set<String> agents = new HashSet<String>(agentElmts.size());
for(Element e : agentElmts)
agents.add(e.getAttributeValue("name"));
return agents;
}
/** @see frodo2.solutionSpaces.ProblemInterface#getZeroUtility() */
public U getZeroUtility () {
try {
return (U) utilClass.newInstance().getZero();
} catch (InstantiationException e) {
System.err.println("Failed calling the nullary constructor for the class " + utilClass.getName() + " used for utility values");
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
System.err.println("Failed calling the nullary constructor for the class " + utilClass.getName() + " used for utility values");
e.printStackTrace();
return null;
}
}
/** @see frodo2.solutionSpaces.ProblemInterface#getPlusInfUtility() */
public U getPlusInfUtility () {
try {
return (U) utilClass.newInstance().getPlusInfinity();
} catch (InstantiationException e) {
System.err.println("Failed calling the nullary constructor for the class " + utilClass.getName() + " used for utility values");
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
System.err.println("Failed calling the nullary constructor for the class " + utilClass.getName() + " used for utility values");
e.printStackTrace();
return null;
}
}
/** @see frodo2.solutionSpaces.ProblemInterface#getMinInfUtility() */
public U getMinInfUtility () {
try {
return (U) utilClass.newInstance().getMinInfinity();
} catch (InstantiationException e) {
System.err.println("Failed calling the nullary constructor for the class " + utilClass.getName() + " used for utility values");
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
System.err.println("Failed calling the nullary constructor for the class " + utilClass.getName() + " used for utility values");
e.printStackTrace();
return null;
}
}
/**
* @author Brammert Ottens, 10 jun 2010
* @return the local problem of the agent
* @warning should only be called by agents!
*/
public Element getLocalProblem() {
assert root.getChildren().size() == 1;
return root.getChild("agent").getChild("problem");
}
/**
* @see frodo2.solutionSpaces.ProblemInterface#getSubProblem(java.lang.String)
*/
public MASparser<V, U> getSubProblem(String agent) {
// extract the problem owned by the agent
Element subProb = null;
for(Element e : (List<Element>)root.getChildren())
if(e.getAttributeValue("name").equals(agent)) {
subProb = e;
break;
}
String agentType = subProb.getAttributeValue("type");
Element masProblem = new Element("MASproblem");
masProblem.setAttribute("numberOfAgents", "1");
subProb.detach();
masProblem.addContent(subProb);
return new MASparser<V, U>(agent, agentType, masProblem, this.countNCCCs, this.spacesToIgnoreNcccs);
}
/**
* @see frodo2.solutionSpaces.ProblemInterface#multipleTypes()
*/
public boolean multipleTypes() {
return true;
}
/**
* @see frodo2.solutionSpaces.ProblemInterface#reset(frodo2.solutionSpaces.ProblemInterface)
*/
public void reset(ProblemInterface<V, U> newProblem) {
// @todo Auto-generated method stub
}
/** @see ProblemInterface#setDomClass(java.lang.Class) */
public void setDomClass(Class<V> domClass) {
this.domClass = domClass;
}
/** @see ProblemInterface#getDomClass() */
@Override
public Class<V> getDomClass() {
return this.domClass;
}
/**
* @see frodo2.solutionSpaces.ProblemInterface#setUtilClass(java.lang.Class)
*/
public void setUtilClass(Class<U> utilClass) {
this.utilClass = utilClass;
}
/** @see MASProblemInterface#utilInstance() */
public U utilInstance() {
try {
return utilClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/** @see ProblemInterface#incrNCCCs(long) */
public void incrNCCCs (long incr) {
if (this.countNCCCs)
this.ncccCount += incr;
}
/** @see ProblemInterface#setNCCCs(long) */
public void setNCCCs (long ncccs) {
if (this.countNCCCs)
this.ncccCount = ncccs;
}
/** @see ProblemInterface#getNCCCs() */
public long getNCCCs () {
return this.ncccCount;
}
}
|
3e1205f7384174531e626fca37b1d4129fa548f7 | 9,817 | java | Java | src/main/java/com/google/devtools/build/lib/analysis/WorkspaceStatusAction.java | jongerrish/bazel | 6db5f931c3d0cd6de4869470c460ab114a60c915 | [
"Apache-2.0"
] | 16,989 | 2015-09-01T19:57:15.000Z | 2022-03-31T23:54:00.000Z | src/main/java/com/google/devtools/build/lib/analysis/WorkspaceStatusAction.java | jongerrish/bazel | 6db5f931c3d0cd6de4869470c460ab114a60c915 | [
"Apache-2.0"
] | 12,562 | 2015-09-01T09:06:01.000Z | 2022-03-31T22:26:20.000Z | src/main/java/com/google/devtools/build/lib/analysis/WorkspaceStatusAction.java | jongerrish/bazel | 6db5f931c3d0cd6de4869470c460ab114a60c915 | [
"Apache-2.0"
] | 3,707 | 2015-09-02T19:20:01.000Z | 2022-03-31T17:06:14.000Z | 37.613027 | 100 | 0.730671 | 7,601 | // Copyright 2014 The Bazel 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.google.devtools.build.lib.analysis;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.WorkspaceStatus;
import com.google.devtools.build.lib.server.FailureDetails.WorkspaceStatus.Code;
import com.google.devtools.build.lib.skyframe.WorkspaceInfoFromDiff;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.OptionsUtils;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.common.options.Converter;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParsingException;
import com.google.devtools.common.options.OptionsProvider;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* An action writing the workspace status files.
*
* <p>These files represent information about the environment the build was run in. They are used by
* language-specific build info factories to make the data in them available for individual
* languages (e.g. by turning them into .h files for C++)
*
* <p>The format of these files a list of key-value pairs, one for each line. The key and the value
* are separated by a space.
*
* <p>There are two of these files: volatile and stable. Changes in the volatile file do not cause
* rebuilds if no other file is changed. This is useful for frequently-changing information that
* does not significantly affect the build, e.g. the current time.
*/
public abstract class WorkspaceStatusAction extends AbstractAction {
/** Options controlling the workspace status command. */
public static class Options extends OptionsBase {
@Option(
name = "embed_label",
defaultValue = "",
converter = OneLineStringConverter.class,
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help = "Embed source control revision or release label in binary")
public String embedLabel;
@Option(
name = "workspace_status_command",
defaultValue = "",
converter = OptionsUtils.PathFragmentConverter.class,
valueHelp = "<path>",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
help =
"A command invoked at the beginning of the build to provide status "
+ "information about the workspace in the form of key/value pairs. "
+ "See the User's Manual for the full specification. Also see "
+ "tools/buildstamp/get_workspace_status for an example.")
public PathFragment workspaceStatusCommand;
}
/** The type of a workspace status action key. */
public enum KeyType {
INTEGER,
STRING,
}
/**
* Action context required by the workspace status action as well as language-specific actions
* that write workspace status artifacts.
*/
public interface Context extends ActionContext {
ImmutableMap<String, Key> getStableKeys();
ImmutableMap<String, Key> getVolatileKeys();
// TODO(ulfjack): Maybe move these to a separate ActionContext interface?
WorkspaceStatusAction.Options getOptions();
ImmutableMap<String, String> getClientEnv();
com.google.devtools.build.lib.shell.Command getCommand();
}
/** A key in the workspace status info file. */
public static class Key {
private final KeyType type;
private final String defaultValue;
private final String redactedValue;
private Key(KeyType type, String defaultValue, String redactedValue) {
this.type = type;
this.defaultValue = defaultValue;
this.redactedValue = redactedValue;
}
public KeyType getType() {
return type;
}
public String getDefaultValue() {
return defaultValue;
}
public String getRedactedValue() {
return redactedValue;
}
public static Key of(KeyType type, String defaultValue, String redactedValue) {
return new Key(type, defaultValue, redactedValue);
}
}
/**
* Parses the output of the workspace status action.
*
* <p>The output is a text file with each line representing a workspace status info key. The key
* is the part of the line before the first space and should consist of the characters [A-Z_]
* (although this is not checked). Everything after the first space is the value.
*/
public static Map<String, String> parseValues(Path file) throws IOException {
HashMap<String, String> result = new HashMap<>();
Splitter lineSplitter = Splitter.on(' ').limit(2);
for (String line :
Splitter.on('\n').split(new String(FileSystemUtils.readContentAsLatin1(file)))) {
List<String> items = lineSplitter.splitToList(line);
if (items.size() != 2) {
continue;
}
result.put(items.get(0), items.get(1));
}
return ImmutableMap.copyOf(result);
}
/** Environment for the {@link Factory} to create the workspace status action. */
public interface Environment {
Artifact createStableArtifact(String name);
Artifact createVolatileArtifact(String name);
}
/**
* Environment for the {@link Factory} to create the dummy workspace status information. This is a
* subset of the information provided by CommandEnvironment. However, we cannot reference the
* CommandEnvironment from here due to layering.
*/
public interface DummyEnvironment {
Path getWorkspace();
/** Returns optional precomputed workspace info to include in the build info event. */
@Nullable
WorkspaceInfoFromDiff getWorkspaceInfoFromDiff();
String getBuildRequestId();
OptionsProvider getOptions();
}
/** Factory for {@link WorkspaceStatusAction}. */
public interface Factory {
/**
* Creates the workspace status action.
*
* <p>The action is never re-created, but the same action object is executed on every build. Use
* {@link Context} to access any non-hermetic data.
*/
WorkspaceStatusAction createWorkspaceStatusAction(Environment env);
/**
* Creates a dummy workspace status map. Used in cases where the build failed, so that part of
* the workspace status is nevertheless available.
*/
Map<String, String> createDummyWorkspaceStatus(DummyEnvironment env);
}
private final String workspaceStatusDescription;
protected WorkspaceStatusAction(
ActionOwner owner,
NestedSet<Artifact> inputs,
ImmutableSet<Artifact> outputs,
String workspaceStatusDescription) {
super(owner, inputs, outputs);
this.workspaceStatusDescription = workspaceStatusDescription;
}
/**
* The volatile status artifact containing items that may change even if nothing changed between
* the two builds, e.g. current time.
*/
public abstract Artifact getVolatileStatus();
/**
* The stable status artifact containing items that change only if information relevant to the
* build changes, e.g. the name of the user running the build or the hostname.
*/
public abstract Artifact getStableStatus();
protected ActionExecutionException createExecutionException(Exception e, Code detailedCode) {
String message = "Failed to determine " + workspaceStatusDescription + ": " + e.getMessage();
DetailedExitCode code = createDetailedExitCode(message, detailedCode);
return new ActionExecutionException(message, e, this, false, code);
}
public static DetailedExitCode createDetailedExitCode(String message, Code detailedCode) {
return DetailedExitCode.of(
FailureDetail.newBuilder()
.setMessage(message)
.setWorkspaceStatus(WorkspaceStatus.newBuilder().setCode(detailedCode))
.build());
}
/** Converter for {@code --embed_label} which rejects strings that span multiple lines. */
public static final class OneLineStringConverter implements Converter<String> {
@Override
public String convert(String input) throws OptionsParsingException {
if (input.contains("\n")) {
throw new OptionsParsingException("Value must not contain multiple lines");
}
return input;
}
@Override
public String getTypeDescription() {
return "a one-line string";
}
}
}
|
3e12061b401c93ad06291094523fa3ebdfbf9209 | 2,360 | java | Java | limelight_importer/src/main/java/org/yeastrc/limelight/limelight_importer/searcher/ProjectStateSearcher.java | guoci/limelight-core | 6ce269903ebc5948dd844047d5a2b5580fdc5432 | [
"Apache-2.0"
] | 3 | 2019-02-21T21:23:04.000Z | 2021-07-12T18:30:03.000Z | limelight_importer/src/main/java/org/yeastrc/limelight/limelight_importer/searcher/ProjectStateSearcher.java | guoci/limelight-core | 6ce269903ebc5948dd844047d5a2b5580fdc5432 | [
"Apache-2.0"
] | 5 | 2020-11-13T01:30:36.000Z | 2021-11-24T22:18:53.000Z | limelight_importer/src/main/java/org/yeastrc/limelight/limelight_importer/searcher/ProjectStateSearcher.java | guoci/limelight-core | 6ce269903ebc5948dd844047d5a2b5580fdc5432 | [
"Apache-2.0"
] | 3 | 2021-01-31T18:42:54.000Z | 2021-07-11T20:33:07.000Z | 31.891892 | 107 | 0.730085 | 7,602 | /*
* Original author: Daniel Jaschob <djaschob .at. uw.edu>
*
* Copyright 2018 University of Washington - Seattle, WA
*
* 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.yeastrc.limelight.limelight_importer.searcher;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.slf4j.LoggerFactory;
import org.yeastrc.limelight.limelight_importer_runimporter_shared.db.ImportRunImporterDBConnectionFactory;
import org.slf4j.Logger;
/**
* Retrieve info on flags on project_tbl
*
*/
public class ProjectStateSearcher {
private static final Logger log = LoggerFactory.getLogger( ProjectStateSearcher.class );
private ProjectStateSearcher() { }
public static ProjectStateSearcher getInstance() { return new ProjectStateSearcher(); }
/**
* @param projectId
* @return null if projectId not found
* @throws Exception
*/
public ProjectStateSearcherResults getProjectState( int projectId ) throws Exception {
ProjectStateSearcherResults result = null;
final String sql = "SELECT project_locked, enabled, marked_for_deletion FROM project_tbl WHERE id = ?";
try ( Connection dbConnection = ImportRunImporterDBConnectionFactory.getInstance().getConnection() ) {
try ( PreparedStatement pstmt = dbConnection.prepareStatement( sql ) ) {
pstmt.setInt( 1, projectId );
try ( ResultSet rs = pstmt.executeQuery() ) {
if ( rs.next() ) {
result = new ProjectStateSearcherResults();
result.setProjectLocked( rs.getBoolean( "project_locked" ) );
result.setProjectEnabled( rs.getBoolean( "enabled" ) );
result.setProjectMarkedForDeletion( rs.getBoolean( "marked_for_deletion" ) );
}
}
}
} catch ( Exception e ) {
log.error( "ERROR: getProjectState(...) sql: " + sql, e );
throw e;
}
return result;
}
}
|
3e1206cd1008a2ca21c6bcc6e7de77f06879f5db | 732 | java | Java | src/test/java/com/github/llyb120/json/selector/ObjectWalkerTest.java | llyb120/json | 81da9a30a53d391c733bdb9a6b2b9fc19b943b81 | [
"MIT"
] | 4 | 2020-01-11T14:01:18.000Z | 2020-07-31T08:03:49.000Z | src/test/java/com/github/llyb120/json/selector/ObjectWalkerTest.java | llyb120/json | 81da9a30a53d391c733bdb9a6b2b9fc19b943b81 | [
"MIT"
] | null | null | null | src/test/java/com/github/llyb120/json/selector/ObjectWalkerTest.java | llyb120/json | 81da9a30a53d391c733bdb9a6b2b9fc19b943b81 | [
"MIT"
] | null | null | null | 22.875 | 49 | 0.489071 | 7,603 | package com.github.llyb120.json.selector;
import com.github.llyb120.json.Obj;
import org.junit.Test;
import static com.github.llyb120.json.Json.a;
import static com.github.llyb120.json.Json.o;
import static org.junit.Assert.*;
public class ObjectWalkerTest {
@Test
public void walk() {
//测试回溯是否会出错
Obj par;
Obj item = o(
"a", 1,
"b", o(
"c", a(1, par = o(
"d", "fff"
))
)
);
par.put("par", par);
ObjectWalker walker = new ObjectWalker();
walker.walk(item);
// assertEquals(walker.result.size(), 3);
// int d = 2;
}
} |
3e1206ddeb4ee85b4b322b2ebde760aff94e7a9c | 8,114 | java | Java | wemirr-platform-tools/src/main/java/com/wemirr/platform/tools/service/impl/MySqlDynamicReleaseServiceImpl.java | lvpv/wemirr-platform | 33a23b4d74a2a8e6acf1d838efc8acec437d7d97 | [
"Apache-2.0"
] | 22 | 2021-08-18T10:27:39.000Z | 2022-03-23T09:39:57.000Z | wemirr-platform-tools/src/main/java/com/wemirr/platform/tools/service/impl/MySqlDynamicReleaseServiceImpl.java | lvpv/wemirr-platform | 33a23b4d74a2a8e6acf1d838efc8acec437d7d97 | [
"Apache-2.0"
] | null | null | null | wemirr-platform-tools/src/main/java/com/wemirr/platform/tools/service/impl/MySqlDynamicReleaseServiceImpl.java | lvpv/wemirr-platform | 33a23b4d74a2a8e6acf1d838efc8acec437d7d97 | [
"Apache-2.0"
] | 4 | 2021-09-27T06:47:56.000Z | 2022-02-23T14:04:59.000Z | 44.097826 | 164 | 0.713951 | 7,604 | package com.wemirr.platform.tools.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.wemirr.framework.commons.StringUtils;
import com.wemirr.framework.commons.exception.CheckedException;
import com.wemirr.framework.db.mybatis.conditions.Wraps;
import com.wemirr.framework.db.page.PageRequest;
import com.wemirr.platform.tools.domain.entity.DynamicReleaseColumn;
import com.wemirr.platform.tools.domain.entity.DynamicReleaseGrid;
import com.wemirr.platform.tools.domain.entity.ExportExcelReq;
import com.wemirr.platform.tools.domain.enums.Expression;
import com.wemirr.platform.tools.domain.req.DynamicReleaseGridColumnReq;
import com.wemirr.platform.tools.domain.req.DynamicReleaseQuery;
import com.wemirr.platform.tools.domain.req.DynamicReleaseQueryDrag;
import com.wemirr.platform.tools.domain.resp.DynamicReleaseCurdOptionResp;
import com.wemirr.platform.tools.domain.resp.DynamicReleaseLogTrackResp;
import com.wemirr.platform.tools.mapper.DynamicReleaseColumnMapper;
import com.wemirr.platform.tools.mapper.DynamicReleaseGridMapper;
import com.wemirr.platform.tools.mapper.DynamicReleaseMapper;
import com.wemirr.platform.tools.service.DynamicReleaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author Levin
*/
@Slf4j
@Service("mySqlDynamicReleaseServiceImpl")
@RequiredArgsConstructor
public class MySqlDynamicReleaseServiceImpl implements DynamicReleaseService<Long> {
private final DynamicReleaseGridMapper dynamicReleaseGridMapper;
private final DynamicReleaseMapper dynamicReleaseMapper;
private final DynamicReleaseColumnMapper dynamicReleaseColumnMapper;
@Override
public DynamicReleaseCurdOptionResp curdOptions(String model) {
DynamicReleaseGrid releaseGrid = getDynamicReleaseGridByCode(model);
final List<DynamicReleaseColumn> dynamicReleaseColumns = this.dynamicReleaseColumnMapper.selectList(Wraps.<DynamicReleaseColumn>lbQ()
.eq(DynamicReleaseColumn::getGridId, releaseGrid.getId()));
if (CollUtil.isEmpty(dynamicReleaseColumns)) {
throw CheckedException.notFound("动态发布的模型字段不存在");
}
final List<DynamicReleaseCurdOptionResp.DynamicReleaseColumnResp> columnRespList = dynamicReleaseColumns.stream().map(dynamic -> {
log.warn("暂时没想好 dict 怎么做成最优方案....");
return DynamicReleaseCurdOptionResp.DynamicReleaseColumnResp.builder()
.key(dynamic.getKey()).width(dynamic.getWidth()).title(dynamic.getTitle()).type(dynamic.getType())
.disabled(dynamic.getDisabled())
.showOverflowTooltip(dynamic.getShowOverflowTooltip())
.search(JSONUtil.toBean(dynamic.getSearch(), DynamicReleaseCurdOptionResp.DynamicReleaseColumnSearchResp.class))
.form(JSONUtil.toBean(dynamic.getForm(), DynamicReleaseCurdOptionResp.DynamicReleaseColumnFormResp.class))
.dict(buildDict(dynamic.getDict()))
.build();
}).collect(Collectors.toList());
return DynamicReleaseCurdOptionResp.builder().columns(columnRespList).build();
}
@Override
public IPage<?> pages(String model, PageRequest request, Map<String, Object> params) {
// 防止生成的动态SQL出问题
if (MapUtil.isNotEmpty(params)) {
params.remove("current");
params.remove("size");
}
DynamicReleaseGrid releaseGrid = getDynamicReleaseGridByCode(model);
final List<DynamicReleaseColumn> releaseColumns = this.dynamicReleaseColumnMapper.selectList(Wraps.<DynamicReleaseColumn>lbQ()
.eq(DynamicReleaseColumn::getGridId, releaseGrid.getId()));
String tableName = releaseGrid.getTableName();
final SQL buildSql = new SQL().SELECT("*").FROM(tableName);
if (CollectionUtil.isEmpty(releaseColumns)) {
return dynamicReleaseMapper.dynamicPageList(request.buildPage(), buildSql.toString());
}
releaseColumns.stream()
.filter(Objects::nonNull)
.map(column -> {
final DynamicReleaseGridColumnReq.DynamicReleaseGridColumnSearch search = JSON.parseObject(column.getSearch(),
DynamicReleaseGridColumnReq.DynamicReleaseGridColumnSearch.class);
final Object val = params.get(column.getKey());
if (search == null || search.isDisabled() || StringUtils.isBlank(search.getExpression()) || Objects.isNull(val)) {
return null;
}
return DynamicReleaseQuery.builder().column(column.getKey()).expression(Expression.of(search.getExpression())).value(val).build().toCondition();
}).filter(Objects::nonNull).forEach(buildSql::WHERE);
final String sql = buildSql.toString();
log.info("[编译的SQL] - {}", sql);
return dynamicReleaseMapper.dynamicPageList(request.buildPage(), sql);
}
@Override
public IPage<?> pages(String model, DynamicReleaseQueryDrag drag) {
throw CheckedException.badRequest("未实现");
}
@Override
public void batchDeleteByKeys(String model, List<Long> ids) {
}
@Override
public void exportExcel(String model, ExportExcelReq req, HttpServletResponse response) {
}
@Override
public void deleteById(String model, Long id) {
DynamicReleaseGrid releaseGrid = getDynamicReleaseGridByCode(model);
this.dynamicReleaseMapper.deleteById(releaseGrid.getTableName(), id);
}
@Override
public void save(String model, Map<String, Object> map) {
DynamicReleaseGrid releaseGrid = getDynamicReleaseGridByCode(model);
this.dynamicReleaseMapper.insertMap(releaseGrid.getTableName(), map);
}
@Override
public List<DynamicReleaseLogTrackResp<Long>> logTrack(String model, Long id) {
return Lists.newArrayList();
}
@Override
public void pushTrack(String model, Long id) {
}
@Override
public void updateById(String model, Long id, Map<String, Object> map) {
DynamicReleaseGrid releaseGrid = getDynamicReleaseGridByCode(model);
this.dynamicReleaseMapper.updateByMap(releaseGrid.getTableName(), id, map);
}
private DynamicReleaseGrid getDynamicReleaseGridByCode(String model) {
final DynamicReleaseGrid releaseGrid = this.dynamicReleaseGridMapper.selectOne(Wraps.<DynamicReleaseGrid>lbQ()
.eq(DynamicReleaseGrid::getModel, model));
if (Objects.isNull(releaseGrid)) {
throw CheckedException.notFound("动态发布的模型表单不存在");
}
return releaseGrid;
}
public static String build(DynamicReleaseQuery param) {
return ("`" + param.getColumn() + "` " + param.getExpression() + " " + param.getValue() + "");
}
private DynamicReleaseCurdOptionResp.DynamicReleaseColumnDictResp buildDict(String dict) {
if (StringUtils.isBlank(dict)) {
return null;
}
final DynamicReleaseCurdOptionResp.DynamicReleaseColumnDictResp.DynamicReleaseColumnDictRespBuilder builder =
DynamicReleaseCurdOptionResp.DynamicReleaseColumnDictResp.builder();
final JSONObject object = JSON.parseObject(dict);
final String code = object.getString("code");
if (StringUtils.isNotBlank(code)) {
builder.value("code").label("name").url("/authority/dictionaries/" + code + "/list");
} else {
builder.url(object.getString("url"));
}
return builder.build();
}
}
|
3e120755cc5c58ca95e1ef56f571d6d5e14b7957 | 4,655 | java | Java | opt4j-satdecoding/src/main/java/org/opt4j/satdecoding/MixedSATManager.java | keszocze/opt4j | 513d2c0122dfce707b681889836378e45d385576 | [
"MIT"
] | 14 | 2018-01-26T18:20:16.000Z | 2021-01-27T08:20:46.000Z | opt4j-satdecoding/src/main/java/org/opt4j/satdecoding/MixedSATManager.java | keszocze/opt4j | 513d2c0122dfce707b681889836378e45d385576 | [
"MIT"
] | 47 | 2018-02-10T17:13:52.000Z | 2020-06-04T13:26:00.000Z | opt4j-satdecoding/src/main/java/org/opt4j/satdecoding/MixedSATManager.java | keszocze/opt4j | 513d2c0122dfce707b681889836378e45d385576 | [
"MIT"
] | 11 | 2018-01-17T13:37:06.000Z | 2019-12-18T14:52:41.000Z | 30.227273 | 99 | 0.667454 | 7,605 | /*******************************************************************************
* Copyright (c) 2014 Opt4J
*
* 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 org.opt4j.satdecoding;
import java.util.List;
import java.util.Map;
import org.opt4j.core.Genotype;
import org.opt4j.core.genotype.BooleanGenotype;
import org.opt4j.core.genotype.BooleanMapGenotype;
import org.opt4j.core.genotype.DoubleBounds;
import org.opt4j.core.genotype.DoubleGenotype;
import org.opt4j.core.genotype.DoubleMapGenotype;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* The {@link MixedSATManager} encodes the decision strategy into two vectors:
* One binary vector for the phase and one double vector for the priority.
*
* @author lukasiewycz
*
*/
@Singleton
public class MixedSATManager implements SATManager {
protected final Solver solver;
/**
* Constructs a {@link MixedSATManager}.
*
* @param solver
* the solver
*/
@Inject
public MixedSATManager(Solver solver) {
this.solver = solver;
}
/*
* (non-Javadoc)
*
* @see org.opt4j.sat.SATManager#createSATGenotype(java.util.List,
* java.util.Map, java.util.Map)
*/
@Override
public Genotype createSATGenotype(List<Object> variables, Map<Object, Double> lowerBounds,
Map<Object, Double> upperBounds, Map<Object, Double> priorities, Map<Object, Boolean> phases) {
int size = variables.size();
double[] lower = new double[size];
double[] upper = new double[size];
for (int i = 0; i < size; i++) {
Object variable = variables.get(i);
Double lb = lowerBounds.get(variable);
Double ub = upperBounds.get(variable);
if (lb == null) {
lb = 0.0;
}
if (ub == null) {
ub = 1.0;
}
lower[i] = lb;
upper[i] = ub;
}
DoubleBounds doubleBounds = new DoubleBounds(lower, upper);
DoubleGenotype doubleVector = new DoubleMapGenotype<>(variables, doubleBounds);
BooleanGenotype booleanVector = new BooleanMapGenotype<>(variables);
SATGenotype satGenotype = new SATGenotype(booleanVector, doubleVector);
for (Object variable : variables) {
double priority = priorities.get(variable);
boolean phase = phases.get(variable);
doubleVector.add(priority);
booleanVector.add(phase);
}
return satGenotype;
}
/*
* (non-Javadoc)
*
* @see org.opt4j.sat.SATManager#decodeSATGenotype(java.util.List,
* org.opt4j.core.Genotype)
*/
@Override
public Model decodeSATGenotype(List<Object> variables, Genotype genotype) {
SATGenotype satGenotype = (SATGenotype) genotype;
BooleanGenotype booleanVector = satGenotype.getBooleanVector();
DoubleGenotype doubleVector = satGenotype.getDoubleVector();
VarOrder varorder = new VarOrder();
for (int i = 0; i < variables.size(); i++) {
Object var = variables.get(i);
varorder.setActivity(var, doubleVector.get(i));
varorder.setPhase(var, booleanVector.get(i));
}
varorder.setVarInc(1.0 / (2.0 * variables.size()));
varorder.setVarDecay(1.0 / 0.95);
Model model = null;
try {
model = solver.solve(varorder);
if (model == null) {
throw new ContradictionException("no satisfying solution left");
}
} catch (TimeoutException e) {
System.err.println("timeout");
}
return model;
}
/*
* (non-Javadoc)
*
* @see org.opt4j.sat.SATManager#getSolver()
*/
@Override
public Solver getSolver() {
return solver;
}
}
|
3e1207eadbfc3e5efb27d98230d37d369a6e876a | 1,795 | java | Java | jdfusion/src/main/java/com/jdcloud/sdk/service/jdfusion/model/VmKeypairCollection.java | zhangycjob/jdcloud-sdk-java | 662c7617574ddfcac5c769dc0c7cf3a7eedadcff | [
"Apache-2.0"
] | 38 | 2018-04-19T09:53:59.000Z | 2021-11-08T12:52:15.000Z | jdfusion/src/main/java/com/jdcloud/sdk/service/jdfusion/model/VmKeypairCollection.java | zhangycjob/jdcloud-sdk-java | 662c7617574ddfcac5c769dc0c7cf3a7eedadcff | [
"Apache-2.0"
] | 22 | 2018-04-24T12:17:20.000Z | 2022-03-31T10:39:18.000Z | jdfusion/src/main/java/com/jdcloud/sdk/service/jdfusion/model/VmKeypairCollection.java | zhangycjob/jdcloud-sdk-java | 662c7617574ddfcac5c769dc0c7cf3a7eedadcff | [
"Apache-2.0"
] | 53 | 2018-04-19T10:48:05.000Z | 2022-03-16T09:15:16.000Z | 21.117647 | 76 | 0.631755 | 7,606 | /*
* Copyright 2018 JDCLOUD.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.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.jdfusion.model;
import java.util.List;
import java.util.ArrayList;
/**
* vmKeypairCollection
*/
public class VmKeypairCollection implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* keypairs
*/
private List<KeypairInfo> keypairs;
/**
* get keypairs
*
* @return
*/
public List<KeypairInfo> getKeypairs() {
return keypairs;
}
/**
* set keypairs
*
* @param keypairs
*/
public void setKeypairs(List<KeypairInfo> keypairs) {
this.keypairs = keypairs;
}
/**
* set keypairs
*
* @param keypairs
*/
public VmKeypairCollection keypairs(List<KeypairInfo> keypairs) {
this.keypairs = keypairs;
return this;
}
/**
* add item to keypairs
*
* @param keypair
*/
public void addKeypair(KeypairInfo keypair) {
if (this.keypairs == null) {
this.keypairs = new ArrayList<>();
}
this.keypairs.add(keypair);
}
} |
3e1207f7f216d95ee177673dcf0083cb390ce7f0 | 1,009 | java | Java | skyBot/src/main/groovy/io/deniffel/bot/workspace/Room.java | tom-010/bot | 6b925b8a94dfe01613a95f8991e449c8cc16e52d | [
"BSD-3-Clause"
] | 1 | 2018-09-07T05:44:46.000Z | 2018-09-07T05:44:46.000Z | skyBot/src/main/groovy/io/deniffel/bot/workspace/Room.java | tom-010/bot | 6b925b8a94dfe01613a95f8991e449c8cc16e52d | [
"BSD-3-Clause"
] | null | null | null | skyBot/src/main/groovy/io/deniffel/bot/workspace/Room.java | tom-010/bot | 6b925b8a94dfe01613a95f8991e449c8cc16e52d | [
"BSD-3-Clause"
] | null | null | null | 19.784314 | 56 | 0.587711 | 7,607 | package io.deniffel.bot.workspace;
import io.deniffel.bot.base.Listener;
import io.deniffel.bot.base.Message;
import java.util.*;
public class Room {
private final String id;
private Set<Listener> listeners = new HashSet<>();
private List<Message> messages = new LinkedList<>();
public Room(String id) {
this.id = id;
}
public void addListener(Listener listener) {
if(listener != null)
listeners.add(listener);
}
public String getId() {
return id;
}
public int listenersCount() {
return listeners.size();
}
public void send(Message message) {
send(message, this);
}
public void send(Message message, Object sender) {
if(message == null)
return;
if(messages.contains(message))
return;
messages.add(message);
message.setRoomId(this.id);
for(Listener l : listeners) {
l.receive(message.clone());
}
}
}
|
3e12086e1830508593977e10ac854e1469e9d24c | 3,039 | java | Java | spring-cloud-aws-context/src/main/java/org/springframework/cloud/aws/context/config/AmazonEc2InstanceDataPropertySourcePostProcessor.java | valli-dr/spring-cloud-aws | 8d1675bd900071094ed92e638e8ff2ca093a6633 | [
"Apache-2.0"
] | 613 | 2015-02-04T01:14:22.000Z | 2022-01-06T13:07:17.000Z | spring-cloud-aws-context/src/main/java/org/springframework/cloud/aws/context/config/AmazonEc2InstanceDataPropertySourcePostProcessor.java | valli-dr/spring-cloud-aws | 8d1675bd900071094ed92e638e8ff2ca093a6633 | [
"Apache-2.0"
] | 664 | 2015-01-02T03:56:29.000Z | 2022-01-16T08:47:41.000Z | spring-cloud-aws-context/src/main/java/org/springframework/cloud/aws/context/config/AmazonEc2InstanceDataPropertySourcePostProcessor.java | valli-dr/spring-cloud-aws | 8d1675bd900071094ed92e638e8ff2ca093a6633 | [
"Apache-2.0"
] | 461 | 2015-01-12T08:20:08.000Z | 2022-01-17T06:06:02.000Z | 33.395604 | 104 | 0.804212 | 7,608 | /*
* Copyright 2013-2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.aws.context.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.cloud.aws.core.env.ec2.AmazonEc2InstanceDataPropertySource;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
/**
* @author Agim Emruli
*/
public class AmazonEc2InstanceDataPropertySourcePostProcessor
implements PriorityOrdered, EnvironmentAware, BeanFactoryPostProcessor {
static final String INSTANCE_DATA_PROPERTY_SOURCE_NAME = "InstanceData";
private static final Logger LOGGER = LoggerFactory
.getLogger(AmazonEc2InstanceDataPropertySourcePostProcessor.class);
private Environment environment;
private String valueSeparator;
private String attributeSeparator;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
public void setValueSeparator(String valueSeparator) {
this.valueSeparator = valueSeparator;
}
public void setAttributeSeparator(String attributeSeparator) {
this.attributeSeparator = attributeSeparator;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.environment instanceof ConfigurableEnvironment) {
AmazonEc2InstanceDataPropertySource propertySource = new AmazonEc2InstanceDataPropertySource(
INSTANCE_DATA_PROPERTY_SOURCE_NAME);
if (StringUtils.hasText(this.valueSeparator)) {
propertySource.setUserDataValueSeparator(this.valueSeparator);
}
if (StringUtils.hasText(this.attributeSeparator)) {
propertySource.setUserDataAttributeSeparator(this.attributeSeparator);
}
((ConfigurableEnvironment) this.environment).getPropertySources().addLast(propertySource);
}
else {
LOGGER.warn("Environment is not of type '{}' property source with instance data is not available",
ConfigurableEnvironment.class.getName());
}
}
}
|
3e12094dc4fbee413ea1638864e78b32ce3866e8 | 6,500 | java | Java | modules/virtualan-plugin/src/main/java/io/virtualan/core/util/VirtualServiceParamComparator.java | virtualansoftware/virtualan | c5835876cc265ed4c89f809a9485929e31da39af | [
"Apache-2.0"
] | 14 | 2020-07-15T11:28:29.000Z | 2022-03-06T23:15:38.000Z | modules/virtualan-plugin/src/main/java/io/virtualan/core/util/VirtualServiceParamComparator.java | virtualansoftware/virtualan | c5835876cc265ed4c89f809a9485929e31da39af | [
"Apache-2.0"
] | 316 | 2020-07-19T17:42:45.000Z | 2022-03-27T18:48:28.000Z | modules/virtualan-plugin/src/main/java/io/virtualan/core/util/VirtualServiceParamComparator.java | virtualansoftware/virtualan | c5835876cc265ed4c89f809a9485929e31da39af | [
"Apache-2.0"
] | 2 | 2020-08-27T14:18:17.000Z | 2021-01-26T16:05:55.000Z | 40.625 | 120 | 0.633385 | 7,609 | /*
*
* Copyright 2018 Virtualan Contributors (https://virtualan.io)
*
* 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.virtualan.core.util;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import io.virtualan.core.model.MockRequest;
import io.virtualan.core.model.MockServiceRequest;
import io.virtualan.core.model.VirtualServiceKeyValue;
import io.virtualan.params.Param;
import io.virtualan.params.ParamTypes;
/**
*
* @author Elan Thangamani
*
**/
@Service("virtualServiceParamComparator")
public class VirtualServiceParamComparator {
public boolean isAllParamPresent(final MockServiceRequest mockServiceRequest,
final ReturnMockResponse rMockResponse) {
for (final VirtualServiceKeyValue virtualServiceKeyValue : rMockResponse.getMockRequest()
.getAvailableParams()) {
if (mockServiceRequest.getParams().containsKey(virtualServiceKeyValue.getKey())
&& mockServiceRequest.getParams().get(virtualServiceKeyValue.getKey())
.equals(virtualServiceKeyValue.getValue())) {
mockServiceRequest.getParams().remove(virtualServiceKeyValue.getKey());
} else {
if (mockServiceRequest.getHeaderParams() != null
&& mockServiceRequest.getHeaderParams()
.get(virtualServiceKeyValue.getKey().toLowerCase()) != null && !mockServiceRequest.getHeaderParams()
.get(virtualServiceKeyValue.getKey().toLowerCase())
.contains(virtualServiceKeyValue.getValue())) {
return false;
}
}
}
return mockServiceRequest.getParams().isEmpty();
}
private int isParameterMatch(MockRequest mockRequest, MockServiceRequest mockServiceRequest) {
int numberOfMatch = 0;
for (final VirtualServiceKeyValue mockKeyValueParams : mockRequest.getAvailableParams()) {
Class type = null;
if (mockServiceRequest.getParamsType() != null) {
type = mockServiceRequest.getParamsType().get(mockKeyValueParams.getKey());
}
final Param param = new Param();
if (mockServiceRequest.getParams().containsKey(mockKeyValueParams.getKey())) {
param.setActualValue(
mockServiceRequest.getParams().get(mockKeyValueParams.getKey()));
} else {
param.setActualValue(mockServiceRequest.getHeaderParams()
.get(mockKeyValueParams.getKey().toLowerCase()));
}
param.setExpectedValue(mockKeyValueParams.getValue());
param.setName(mockKeyValueParams.getKey());
numberOfMatch = getNumberOfMatch(mockRequest, numberOfMatch, mockKeyValueParams, type,
param);
}
return numberOfMatch;
}
private int getNumberOfMatch(MockRequest mockRequest, int numberOfMatch,
VirtualServiceKeyValue mockKeyValueParams, Class type, Param param) {
if (mockRequest.getExcludeSet() == null
|| !mockRequest.getExcludeSet().contains(mockKeyValueParams.getKey())) {
if (type == null) {
if (ParamTypes.DEFAULT.compareParam(param)) {
numberOfMatch++;
}
} else if (ParamTypes.fromString(type.getCanonicalName()).compareParam(param)) {
numberOfMatch++;
}
}
return numberOfMatch;
}
public int isParameterMatch(MockRequest mockRequest, Map<String, String> actualQueryMap) {
final Map<String, String> filteredActualQueryMap = new HashMap<>();
int noumberOfMatch = 0;
getResp(actualQueryMap, filteredActualQueryMap);
if (mockRequest.getAvailableParams().size() == filteredActualQueryMap.size()) {
for (final VirtualServiceKeyValue vsKeyValueParams : mockRequest.getAvailableParams()) {
if (mockRequest.getExcludeSet() == null
|| !mockRequest.getExcludeSet().contains(vsKeyValueParams.getKey())) {
if (vsKeyValueParams.getValue()
.equals(filteredActualQueryMap.get(vsKeyValueParams.getKey()))) {
noumberOfMatch++;
} else {
return noumberOfMatch;
}
}
}
}
return noumberOfMatch;
}
public void getResp(Map<String, String> actualQueryMap,
Map<String, String> filteredActualQueryMap) {
for (final Map.Entry<String, String> mapEntry : actualQueryMap.entrySet()) {
if (mapEntry.getValue() != null && !"null".equals(mapEntry.getValue())) {
filteredActualQueryMap.put(mapEntry.getKey(), mapEntry.getValue());
}
}
}
public int compareQueryParams(MockRequest mockRequest, MockServiceRequest mockServiceRequest) {
if (mockRequest.getAvailableParams() == null
|| mockRequest.getAvailableParams().isEmpty()) {
return isEmptyRequest(mockServiceRequest.getParams());
} else {
return isParameterMatch(mockRequest, mockServiceRequest);
}
}
public int compareQueryParams(MockRequest mockRequest, Map<String, String> actualQueryMap) {
if (mockRequest.getAvailableParams() == null
|| mockRequest.getAvailableParams().isEmpty()) {
return isEmptyRequest(actualQueryMap);
} else {
return isParameterMatch(mockRequest, actualQueryMap);
}
}
public int isEmptyRequest(Map<String, String> actualQueryMap) {
if(actualQueryMap != null) {
for (final Map.Entry<String, String> checkEmpty : actualQueryMap.entrySet()) {
if (!"null".equals(checkEmpty.getValue())) {
return 0;
}
}
}
return 1;
}
}
|
3e1209d7198ba90b1d9da9c84234f71c142ce306 | 5,978 | java | Java | app/org/hadatac/console/controllers/studies/StudyForceFieldGraph.java | marcellobax/hadatac | 81f798812198cf5794746f50f4e62ff43bbb6a4f | [
"Apache-2.0"
] | 14 | 2015-08-13T15:46:40.000Z | 2020-06-17T15:04:25.000Z | app/org/hadatac/console/controllers/studies/StudyForceFieldGraph.java | marcellobax/hadatac | 81f798812198cf5794746f50f4e62ff43bbb6a4f | [
"Apache-2.0"
] | 111 | 2015-08-11T16:42:55.000Z | 2021-07-30T20:32:02.000Z | app/org/hadatac/console/controllers/studies/StudyForceFieldGraph.java | marcellobax/hadatac | 81f798812198cf5794746f50f4e62ff43bbb6a4f | [
"Apache-2.0"
] | 84 | 2015-09-09T15:43:20.000Z | 2022-03-25T16:44:51.000Z | 35.583333 | 172 | 0.570759 | 7,610 | package org.hadatac.console.controllers.studies;
import org.hadatac.console.controllers.objectcollections.OCNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.hadatac.entity.pojo.Study;
import org.hadatac.entity.pojo.StudyObject;
import org.hadatac.entity.pojo.ObjectCollection;
import org.hadatac.metadata.loader.URIUtils;
import org.hadatac.console.controllers.objects.ObjectForceFieldGraph;
public class StudyForceFieldGraph {
List<OCNode> nodes = null;
Study study = null;
List<ObjectCollection> socList = null;
Map<String,OCNode> socs = null;
Map<String,OCNode> objects = null;
public StudyForceFieldGraph(String study_uri, int maxObjs) {
if (study_uri == null || study_uri.equals("")) {
return;
}
nodes = new ArrayList<OCNode>();
socs = new HashMap<String, OCNode>();
objects = new HashMap<String, OCNode>();
study = Study.find(study_uri);
if (study == null) {
return;
}
addStudy(study, "", "", maxObjs);
}
private void addStudy(Study study, String toLabel, String fromLabel, int maxObjs) {
// Verify if study has already been added
if (getNodeWithUri(study.getUri()) != null) {
return;
}
// add study itself and its attributes
socList = ObjectCollection.findByStudyUri(study.getUri());
String nameNode = "Study " + study.getId();
OCNode studyNode = new OCNode(nameNode, study.getUri(), OCNode.STUDY, studyHtml(nameNode, study), new ArrayList<>());
nodes.add(studyNode);
for (ObjectCollection soc : socList) {
if (soc.getHasScopeUri() == null || soc.getHasScopeUri().equals("")) {
addStudySOC(soc, studyNode, maxObjs);
}
}
}
private void addStudySOC(ObjectCollection soc, OCNode dependedOn, int maxObjs) {
String socLabel = "";
// to add role label
socLabel += soc.getRoleLabel();
OCNode socNode = new OCNode(socLabel, soc.getUri(), OCNode.SOC, socHtml(soc), new ArrayList<>(Arrays.asList(dependedOn.getName())));
nodes.add(socNode);
List<StudyObject> objList = StudyObject.findByCollectionWithPages(soc, maxObjs, 0);
for (StudyObject obj: objList) {
addSOCObject(obj,socNode);
}
String scopeUri = "";
if (soc != null && soc.getUri() != null) {
scopeUri = soc.getUri();
}
for (ObjectCollection subSoc : socList) {
if (subSoc.getHasScopeUri() != null && subSoc.getHasScopeUri().equals(scopeUri)) {
addStudySOC(subSoc, socNode, maxObjs);
}
}
}
private void addSOCObject(StudyObject obj, OCNode dependedOn) {
if (obj != null) {
String objLabel = obj.getLabel();
OCNode objNode = new OCNode(objLabel, obj.getUri(), OCNode.OBJECT, ObjectForceFieldGraph.objectHtml(obj), new ArrayList<>(Arrays.asList(dependedOn.getName())));
nodes.add(objNode);
}
}
private OCNode getNodeWithUri(String uri) {
if (nodes.size() > 0) {
for (OCNode nd: nodes) {
if (nd.getURI() != null && nd.getURI().equals(uri)) {
return nd;
}
}
}
return null;
}
private String studyHtml(String id, Study study) {
String html = "";
html += "<h3>Study Details</h3>";
html += "<b>Id</b>: " + id + "<br>";
html += "<b>Title</b>: " + study.getTitle() + "<br>";
html += "<b>Description</b>: " + study.getComment() + "<br>";
html += "<b>URI</b>: " + URIUtils.replaceNameSpace(study.getUri()) + "<br>";
return html;
}
private String socHtml(ObjectCollection soc) {
String html = "";
html += "<h3>Semantic Object Collection Details</h3>";
html += "<b>Role</b>: " + soc.getRoleLabel() + "<br>";
if (soc.getGroundingLabel() != null && !soc.getGroundingLabel().equals("")) {
html += "<b>Grounding Label</b>: " + soc.getGroundingLabel() + "<br>";
html += "<b>Reference</b>: " + soc.getSOCReference() + "<br>";
}
return html;
}
@SuppressWarnings("unchecked")
public String toJson() {
JSONObject dag = new JSONObject();
JSONObject ndstudy = new JSONObject();
Iterator<OCNode> studys = nodes.iterator();
while (studys.hasNext()) {
OCNode tmpObject = studys.next();
JSONObject object = new JSONObject();
//System.out.println(tmpstudyect.getName());
String nodeType = null;
if (tmpObject.getType() == OCNode.STUDY) {
nodeType = "study";
} else if (tmpObject.getType() == OCNode.SOC) {
nodeType = "soc";
} else if (tmpObject.getType() == OCNode.OBJECT) {
nodeType = "object";
} else {
nodeType = "";
}
object.put("type", nodeType);
object.put("name", tmpObject.getName());
object.put("docs", tmpObject.getHtmlDoc());
JSONArray depList = new JSONArray();
if (tmpObject.getMemberOf() != null && tmpObject.getMemberOf().size() > 0) {
for (String str : tmpObject.getMemberOf()) {
depList.add(str);
}
}
object.put("depends", depList);
object.put("dependedOnBy", new JSONArray());
ndstudy.put(tmpObject.getName(),object);
}
dag.put("data", ndstudy);
dag.put("errors", new JSONArray());
//System.out.println(dag.toJSONString());
return dag.toJSONString();
}
}
|
3e120a99fe99e492bc0b3d37d49a845dc8560793 | 1,610 | java | Java | references/bcb_chosen_clones/selected#1193653#131#173.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 23 | 2018-10-03T15:02:53.000Z | 2021-09-16T11:07:36.000Z | references/bcb_chosen_clones/selected#1193653#131#173.java | cragkhit/elasticsearch | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 18 | 2019-02-10T04:52:54.000Z | 2022-01-25T02:14:40.000Z | references/bcb_chosen_clones/selected#1193653#131#173.java | cragkhit/Siamese | 05567b30c5bde08badcac1bf421454e5d995eb91 | [
"Apache-2.0"
] | 19 | 2018-11-16T13:39:05.000Z | 2021-09-05T23:59:30.000Z | 36.590909 | 108 | 0.501863 | 7,611 | @Override
public String resolveItem(String oldJpgFsPath) throws DatabaseException {
if (oldJpgFsPath == null || "".equals(oldJpgFsPath)) throw new NullPointerException("oldJpgFsPath");
try {
getConnection().setAutoCommit(false);
} catch (SQLException e) {
LOGGER.warn("Unable to set autocommit off", e);
}
PreparedStatement statement = null;
String ret = null;
try {
statement = getConnection().prepareStatement(SELECT_ITEM_STATEMENT);
statement.setString(1, oldJpgFsPath);
ResultSet rs = statement.executeQuery();
int i = 0;
int id = -1;
int rowsAffected = 0;
while (rs.next()) {
id = rs.getInt("id");
ret = rs.getString("imageFile");
i++;
}
if (id != -1 && new File(ret).exists()) {
statement = getConnection().prepareStatement(UPDATE_ITEM_STATEMENT);
statement.setInt(1, id);
rowsAffected = statement.executeUpdate();
} else {
return null;
}
if (rowsAffected == 1) {
getConnection().commit();
LOGGER.debug("DB has been updated.");
} else {
getConnection().rollback();
LOGGER.error("DB has not been updated -> rollback!");
}
} catch (SQLException e) {
LOGGER.error(e);
} finally {
closeConnection();
}
return ret;
}
|
3e120c50d58944bb1a11c83548e1b5581212b314 | 5,786 | java | Java | springboot/springboot-email/src/main/java/com/example/springbootemail/service/MailSenderService.java | offline7LY/demo | c6b8f21a305a5e5f21730549eff3056026acba69 | [
"Apache-2.0"
] | null | null | null | springboot/springboot-email/src/main/java/com/example/springbootemail/service/MailSenderService.java | offline7LY/demo | c6b8f21a305a5e5f21730549eff3056026acba69 | [
"Apache-2.0"
] | null | null | null | springboot/springboot-email/src/main/java/com/example/springbootemail/service/MailSenderService.java | offline7LY/demo | c6b8f21a305a5e5f21730549eff3056026acba69 | [
"Apache-2.0"
] | null | null | null | 38.566667 | 124 | 0.654451 | 7,612 | package com.example.springbootemail.service;
import com.example.springbootemail.domain.MailBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* @author zhaozhiwei
* @version V1.0
* @Title: null.java
* @Package com.example.springbootemail.service
* @Description: TODO
* @date 2022/4/1 下午3:21
*/
@Service
public class MailSenderService {
@Autowired
private JavaMailSender javaMailSender;
private static final String MAIL_SENDER = "efpyi@example.com";
// 发送一个简单格式的邮件
public void sendSimpleMail(MailBean mailBean) {
try {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//邮件发送人
simpleMailMessage.setFrom(MAIL_SENDER);
//邮件接收人
simpleMailMessage.setTo(mailBean.getRecipient());
//邮件主题
simpleMailMessage.setSubject(mailBean.getSubject());
//邮件内容
simpleMailMessage.setText(mailBean.getContent());
javaMailSender.send(simpleMailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
//2.4 发送一个HTML格式的邮件
public void sendHTMLMail(MailBean mailBean) {
MimeMessage mimeMailMessage = null;
try {
mimeMailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom(MAIL_SENDER);
mimeMessageHelper.setTo(mailBean.getRecipient());
mimeMessageHelper.setSubject(mailBean.getSubject());
StringBuilder sb = new StringBuilder();
sb.append("<h1>SpirngBoot测试邮件HTML</h1>")
.append("\"<p style='color:#F00'>你是真的太棒了!</p>")
.append("<p style='text-align:right'>右对齐</p>");
mimeMessageHelper.setText(sb.toString(), true);
javaMailSender.send(mimeMailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
//2.5 发送带附件格式的邮件
public void sendAttachmentMail(MailBean mailBean) {
MimeMessage mimeMailMessage = null;
try {
mimeMailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom(MAIL_SENDER);
mimeMessageHelper.setTo(mailBean.getRecipient());
mimeMessageHelper.setSubject(mailBean.getSubject());
mimeMessageHelper.setText(mailBean.getContent());
//文件路径
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/mail.png"));
mimeMessageHelper.addAttachment("mail.png", file);
javaMailSender.send(mimeMailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
// 2.6 发送带静态资源的邮件
public void sendInlineMail(MailBean mailBean) {
MimeMessage mimeMailMessage = null;
try {
mimeMailMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
mimeMessageHelper.setFrom(MAIL_SENDER);
mimeMessageHelper.setTo(mailBean.getRecipient());
mimeMessageHelper.setSubject(mailBean.getSubject());
mimeMessageHelper.setText("<html><body>带静态资源的邮件内容,这个一张IDEA配置的照片:<img src='cid:picture' /></body></html>", true);
//文件路径
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/mail.png"));
mimeMessageHelper.addInline("picture", file);
javaMailSender.send(mimeMailMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
//2.7 发送基于Freemarker模板的邮件
// public void sendTemplateMail(MailBean mailBean) {
// MimeMessage mimeMailMessage = null;
// try {
// mimeMailMessage = javaMailSender.createMimeMessage();
// MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
// mimeMessageHelper.setFrom(MAIL_SENDER);
// mimeMessageHelper.setTo(mailBean.getRecipient());
// mimeMessageHelper.setSubject(mailBean.getSubject());
//
// Map<String, Object> model = new HashMap<String, Object>();
// model.put("content", mailBean.getContent());
// model.put("title", "标题Mail中使用了FreeMarker");
// Template template = configuration.getTemplate("mail.ftl");
// String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
// mimeMessageHelper.setText(text, true);
//
// javaMailSender.send(mimeMailMessage);
// } catch (Exception e) {
// logger.error("邮件发送失败", e);
// }
// }
@Autowired
private TemplateEngine templateEngine;
public void sendTemplateMail() {
//创建邮件正文
Context context = new Context();
context.setVariable("id", "006");
String emailContent = templateEngine.process("emailTemplate", context);
final MailBean mailBean = new MailBean();
mailBean.setSubject("thymeleaf 模板邮件测试");
mailBean.setContent(emailContent);
mailBean.setRecipient(MAIL_SENDER);
this.sendHTMLMail(mailBean);
}
}
|
3e120c95b06272c22b9979ea53c9b570b05a16d7 | 556 | java | Java | src/de/timmyrs/suprdiscordbot/structures/Reaction.java | timmyrs/SuprDiscordBot | b653f00f267159ff76e9d1aa3fcfa7729c58c7db | [
"MIT"
] | 6 | 2017-04-10T17:43:30.000Z | 2018-05-28T16:45:40.000Z | src/de/timmyrs/suprdiscordbot/structures/Reaction.java | timmyRS/SuprDiscordBot | b653f00f267159ff76e9d1aa3fcfa7729c58c7db | [
"MIT"
] | 4 | 2017-04-30T14:19:24.000Z | 2019-03-06T19:18:50.000Z | src/de/timmyrs/suprdiscordbot/structures/Reaction.java | timmyRS/SuprDiscordBot | b653f00f267159ff76e9d1aa3fcfa7729c58c7db | [
"MIT"
] | 2 | 2017-05-06T12:57:05.000Z | 2017-11-18T21:50:47.000Z | 16.352941 | 58 | 0.658273 | 7,613 | package de.timmyrs.suprdiscordbot.structures;
/**
* Reaction Structure.
*
* @author timmyRS
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class Reaction extends Structure
{
/**
* The amount of times this Emoji has been used to react.
*/
public int count;
/**
* Has this user/bot reacted with this Emoji?
*/
public boolean me;
/**
* The Emoji.
*/
public Emoji emoji;
public Reaction[] getArray(int size)
{
return new Reaction[size];
}
public String toString()
{
return "{Reaction " + emoji.toString() + "}";
}
}
|
3e1211177d629a8a18466071e45a12dd99c02ed0 | 1,924 | java | Java | src/main/java/name/robertburrelldonkin/personal/fetchpop/app/ExitCode.java | RobertBurrellDonkin/fetchpop | 8d33ca5bf35f8244faf3a41604961b3ffbe144d3 | [
"MIT"
] | null | null | null | src/main/java/name/robertburrelldonkin/personal/fetchpop/app/ExitCode.java | RobertBurrellDonkin/fetchpop | 8d33ca5bf35f8244faf3a41604961b3ffbe144d3 | [
"MIT"
] | 22 | 2018-02-20T18:53:55.000Z | 2020-09-25T14:44:17.000Z | src/main/java/name/robertburrelldonkin/personal/fetchpop/app/ExitCode.java | RobertBurrellDonkin/fetchpop | 8d33ca5bf35f8244faf3a41604961b3ffbe144d3 | [
"MIT"
] | null | null | null | 36.301887 | 81 | 0.726611 | 7,614 | /*
* MIT License
*
* Copyright (c) 2018-2020 Robert Burrell Donkin
*
* 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 name.robertburrelldonkin.personal.fetchpop.app;
public enum ExitCode {
STATUS_CALL_FAILED("STATUS call failed.", 8),
STATUS_MISSING("Missing STATUS.", 9),
RETRIEVE_MESSAGE_CALL_FAILED("Retrieve message call failed.", 10),
LOGIN_FAILED("Login failed.", 11),
LOGIN_REJECTED("Login rejected by server.", 12),
CONNECTION_FAILED("Could not connect to server.", 13),
LIST_MESSAGES_CALL_FAILED("List messages call failed.", 14);
private final String description;
private final int code;
ExitCode(String description, int code) {
this.description = description;
this.code = code;
}
public String getDescription() {
return description;
}
public int getCode() {
return code;
}
}
|
3e1211d8adedeab8a8a0d6716f5ed1f74d2338f7 | 8,387 | java | Java | SuperAdapter/adapter/src/main/java/com/heaven7/adapter/QuickRecycleViewAdapter2.java | LightSun/SuperAdapter | 062396100a6b1afb62f897f2752a7ed9cdfa9fad | [
"Apache-2.0"
] | null | null | null | SuperAdapter/adapter/src/main/java/com/heaven7/adapter/QuickRecycleViewAdapter2.java | LightSun/SuperAdapter | 062396100a6b1afb62f897f2752a7ed9cdfa9fad | [
"Apache-2.0"
] | null | null | null | SuperAdapter/adapter/src/main/java/com/heaven7/adapter/QuickRecycleViewAdapter2.java | LightSun/SuperAdapter | 062396100a6b1afb62f897f2752a7ed9cdfa9fad | [
"Apache-2.0"
] | null | null | null | 31.649057 | 138 | 0.619769 | 7,615 | package com.heaven7.adapter;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import com.heaven7.adapter.util.CommonItemDecoration;
import com.heaven7.adapter.util.ViewHelper2;
import com.heaven7.core.util.ViewHelper;
import java.util.List;
/**
* most sample as {@linkplain QuickRecycleViewAdapter}.
* but there are three different.
* <li> first,
* use new {@linkplain Selector} with not record position, just record the item data.
* the old selector is {@linkplain SelectHelper}.
* </li>
* <li> second,
* add {@linkplain #setItemTypeDelegate(ItemTypeDelegate)}.
* <p>see {@linkplain ItemTypeDelegate} </p>
* </li>
* <li>
* support multi adapter share a selector.
* <p>see {@linkplain #QuickRecycleViewAdapter2(int, List, Selector)}</p>
* </li>
* @param <T> the item type
* @since 2.0.7
*/
public class QuickRecycleViewAdapter2<T extends ISelectable> extends HeaderFooterAdapter
implements AdapterManager.IAdapterManagerCallback, AdapterManager.IHeaderFooterManager,
AdapterManager.IAdapterManagerCallback2, HeaderFooterAdapter.Callback ,
CommonItemDecoration.AdapterDelegate {
private int mLayoutId = 0;
private AdapterManager<T> mAdapterManager;
private ItemTypeDelegate<T> mTypeDelegate;
/**
* create QuickRecycleViewAdapter with the layout id. if layoutId==0, the method
* {@link #getItemLayoutId(int, ISelectable)} will be called.
*
* @param layoutId the layout id you want to inflate, or 0 if you want multi item.
* @param mDatas the datas
*/
public QuickRecycleViewAdapter2(int layoutId, List<T> mDatas) {
this(layoutId, mDatas, ISelectable.SELECT_MODE_SINGLE);
}
/**
* create QuickRecycleViewAdapter with the layout id. if layoutId==0, the method
* {@link #getItemLayoutId(int, ISelectable)} will be called.
*
* @param layoutId the layout id you want to inflate, or 0 if you want multi item.
* @param mDatas the datas
* @param selectMode select mode . {@link ISelectable#SELECT_MODE_SINGLE} or {@link ISelectable#SELECT_MODE_MULTI}
*/
public QuickRecycleViewAdapter2(int layoutId, List<T> mDatas, int selectMode) {
super();
if (layoutId < 0) {
throw new IllegalArgumentException("layoutId can't be negative ");
}
this.mLayoutId = layoutId;
mAdapterManager = new AdapterManager<T>(mDatas, selectMode, this, true) {
@Override
public IHeaderFooterManager getHeaderFooterManager() {
return QuickRecycleViewAdapter2.this;
}
};
setCallback(this);
onFinalInit();
}
/**
* create adapter with a shared selector.
* @param layoutId the default layout id
* @param mDatas the data
* @param selector the shared selector
* @since 2.1.01
*/
public QuickRecycleViewAdapter2(int layoutId, List<T> mDatas, Selector<T> selector) {
super();
this.mLayoutId = layoutId;
mAdapterManager = new AdapterManager<T>(mDatas, this, selector) {
@Override
public IHeaderFooterManager getHeaderFooterManager() {
return QuickRecycleViewAdapter2.this;
}
};
setCallback(this);
onFinalInit();
}
@Override
public List getListItems() {
return getAdapterManager().getItems();
}
@Override
public int getActuallyItemSize() {
return mAdapterManager.getItemSize();
}
public void setItemTypeDelegate(ItemTypeDelegate<T> mTypeDelegate) {
this.mTypeDelegate = mTypeDelegate;
}
/**
* get selector
* @return the selector
*/
public Selector<T> getSelector(){
return mAdapterManager.getSelector();
}
/**
* called before {@link #notifyDataSetChanged()}
*/
@Override
public void beforeNotifyDataChanged() {
}
/**
* this is callled after data {@link #notifyDataSetChanged()}
*/
@Override
public void afterNotifyDataChanged() {
}
/**
* the init operation of the last, called in constructor
*/
protected void onFinalInit() {
}
@Override
public final boolean isRecyclable() {
return true;
}
public final T getItem(int position) {
return mAdapterManager.getItems().get(position);
}
//====================== begin items ========================//
@Override
public AdapterManager<T> getAdapterManager() {
return mAdapterManager;
}
//====================== end items ========================//
//extract for swipe adapter
protected int getItemViewTypeImpl(HeaderFooterHelper hfHelper, int position) {
int layoutId = getItemLayoutId(position, getItem(position));
if (hfHelper != null)
hfHelper.recordLayoutId(layoutId);
return layoutId;
}
@Override
public final void onBindViewHolderImpl(RecyclerView.ViewHolder holder, int position) {
// Logger.w("QuickRecycleViewAdapter", "onBindViewHolder", "position_1 = " + position);
//not in header or footer populate it
final T item = getItem(position);
final int layoutId = ((IRecyclerViewHolder) holder).getLayoutId();
final ViewHelper helper = ((IRecyclerViewHolder) holder).getViewHelper();
onBindDataImpl(holder, position, item);
if (getAdapterManager().getPostRunnableCallbacks() != null) {
final int pos = position;
for (final AdapterManager.IPostRunnableCallback<T> callback : getAdapterManager()
.getPostRunnableCallbacks()) {
holder.itemView.post(new Runnable() {
@Override
public void run() {
callback.onPostCallback(pos, item, layoutId, helper);
}
});
}
}
}
protected void onBindDataImpl(RecyclerView.ViewHolder holder, int position, T item) {
final ViewHolder vh = (ViewHolder) holder;
onBindData(vh.getContext(), position, item, vh.getLayoutId(), vh.getViewHelper());
}
/**
* if you use multi item ,override this
*
* @param position the position exclude header
* @param t the data
* @return this item layout id
**/
protected
int getItemLayoutId(int position, T t) {
if(mTypeDelegate != null){
return mTypeDelegate.getItemLayoutId(position, t);
}
return mLayoutId;
}
/**
* called on bind data.
* @param context the context
* @param position the position
* @param item the item
* @param itemLayoutId the layoutId
* @param helper the view helper.
* @since 1.8.9
*/
protected void onBindData(Context context, int position, T item, int itemLayoutId, ViewHelper2 helper){
if(mTypeDelegate != null){
mTypeDelegate.onBindData(this, context, position, item, itemLayoutId, helper);
}
}
/**
* item type delegate
* @param <T> the item type
*/
public interface ItemTypeDelegate<T extends ISelectable> {
/**
* get item layout id
*
* @param item the item
* @param position the position exclude header
* @return the item layout id.
*/
int getItemLayoutId(int position, T item);
/**
* called on bind parent data
*
* @param context the context
* @param position the position exclude header
* @param item the item
* @param itemLayoutId the item layout id
* @param helper the helper
*/
void onBindData(QuickRecycleViewAdapter2<T> adapter, Context context, int position, T item, int itemLayoutId, ViewHelper2 helper);
}
/**
* item type delegate
* @param <T> the item type
*/
public static abstract class BaseItemTypeDelegate<T extends ISelectable> implements ItemTypeDelegate<T>{
private final int layoutId;
public BaseItemTypeDelegate(int layoutId) {
this.layoutId = layoutId;
}
@Override
public int getItemLayoutId(int position, T item) {
return layoutId;
}
}
}
|
3e12163d29509080441ec363e3e772207098a1f7 | 1,409 | java | Java | com.io7m.r2.lights/src/main/java/com/io7m/r2/lights/R2LightVolumeSingleType.java | io7m/r2 | 4bc17f03d5447bf9e37a138f668c0aeb88b2ec5c | [
"ISC"
] | 4 | 2016-06-20T18:30:24.000Z | 2020-09-24T03:29:03.000Z | com.io7m.r2.lights/src/main/java/com/io7m/r2/lights/R2LightVolumeSingleType.java | io7m/r2 | 4bc17f03d5447bf9e37a138f668c0aeb88b2ec5c | [
"ISC"
] | 99 | 2016-01-05T17:04:41.000Z | 2017-06-29T17:03:15.000Z | com.io7m.r2.lights/src/main/java/com/io7m/r2/lights/R2LightVolumeSingleType.java | io7m/r2 | 4bc17f03d5447bf9e37a138f668c0aeb88b2ec5c | [
"ISC"
] | 1 | 2020-11-14T07:52:19.000Z | 2020-11-14T07:52:19.000Z | 35.125 | 78 | 0.764413 | 7,616 | /*
* Copyright © 2016 <nnheo@example.com> http://io7m.com
*
* Permission to use, copy, modify, and/or 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.io7m.r2.lights;
import com.io7m.jfunctional.PartialBiFunctionType;
/**
* The type of single-instance lights that operate using light volumes.
*/
public interface R2LightVolumeSingleType extends
R2LightVolumeSingleReadableType,
R2LightVolumeSingleWritableType,
R2LightSingleType
{
@Override
default <A, B, E extends Throwable> B matchLightSingle(
final A context,
final PartialBiFunctionType<A, R2LightVolumeSingleType, B, E> on_volume,
final PartialBiFunctionType<A, R2LightScreenSingleType, B, E> on_screen)
throws E
{
return on_volume.call(context, this);
}
}
|
3e12165aba74771daa274cd1cc7ff45487b313a2 | 87 | java | Java | src/main/java/com/alibaba/druid/sql/ast/ClusteringType.java | linghengqian/druid | 1bc59b62fb81b1c9204161594652832425c6fa72 | [
"Apache-2.0"
] | 6 | 2018-04-17T09:26:05.000Z | 2021-05-08T14:07:22.000Z | src/main/java/com/alibaba/druid/sql/ast/ClusteringType.java | linghengqian/druid | 1bc59b62fb81b1c9204161594652832425c6fa72 | [
"Apache-2.0"
] | 5 | 2021-12-14T20:57:52.000Z | 2022-02-16T01:15:35.000Z | src/main/java/com/alibaba/druid/sql/ast/ClusteringType.java | linghengqian/druid | 1bc59b62fb81b1c9204161594652832425c6fa72 | [
"Apache-2.0"
] | 4 | 2017-07-06T14:51:09.000Z | 2021-06-03T02:17:57.000Z | 12.428571 | 34 | 0.701149 | 7,617 | package com.alibaba.druid.sql.ast;
public enum ClusteringType {
Range,
Hash
}
|
3e121665a6f9b3147c92431edaf4a7880300f614 | 2,481 | java | Java | src/main/java/mx/nic/rdap/renderer/json/writer/NameserverJsonWriter.java | NICMx/rdap-json-renderer | 25533ff11961a88df6e6a6e571e4a08ec13c8069 | [
"Apache-2.0"
] | null | null | null | src/main/java/mx/nic/rdap/renderer/json/writer/NameserverJsonWriter.java | NICMx/rdap-json-renderer | 25533ff11961a88df6e6a6e571e4a08ec13c8069 | [
"Apache-2.0"
] | 4 | 2017-10-19T20:33:32.000Z | 2018-09-24T22:39:46.000Z | src/main/java/mx/nic/rdap/renderer/json/writer/NameserverJsonWriter.java | NICMx/rdap-json-renderer | 25533ff11961a88df6e6a6e571e4a08ec13c8069 | [
"Apache-2.0"
] | null | null | null | 27.876404 | 105 | 0.756147 | 7,618 | package mx.nic.rdap.renderer.json.writer;
import java.net.InetAddress;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import mx.nic.rdap.core.db.IpAddress;
import mx.nic.rdap.core.db.Nameserver;
import mx.nic.rdap.core.db.struct.NameserverIpAddressesStruct;
import mx.nic.rdap.renderer.util.RendererUtil;
public class NameserverJsonWriter {
public static JsonArray getJsonArray(List<Nameserver> nameserver) {
JsonArrayBuilder builder = Json.createArrayBuilder();
for (Nameserver ns : nameserver) {
builder.add(getJson(ns));
}
return builder.build();
}
public static JsonObject getJson(Nameserver nameserver) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("objectClassName", "nameserver");
JsonUtil.fillCommonRdapJsonObject(builder, nameserver);
String key = "ldhName";
String value = nameserver.getFqdnLdhName();
if (RendererUtil.isObjectVisible(value))
builder.add(key, value);
key = "unicodeName";
value = nameserver.getFqdnUnicodeName();
if (RendererUtil.isObjectVisible(value))
builder.add(key, value);
fillIpAddresses(builder, nameserver.getIpAddresses());
return builder.build();
}
private static void fillIpAddresses(JsonObjectBuilder builder, NameserverIpAddressesStruct ipAdresses) {
String key = "ipAddresses";
if (!RendererUtil.isObjectVisible(ipAdresses))
return;
JsonObjectBuilder addressBuilder = Json.createObjectBuilder();
boolean insertIpAddresses = false;
key = "v4";
List<IpAddress> ipv4List = ipAdresses.getIpv4Adresses();
if (RendererUtil.isObjectVisible(ipv4List)) {
addressBuilder.add(key, getIpAddressJsonArray(ipv4List));
insertIpAddresses = true;
}
key = "v6";
List<IpAddress> ipv6List = ipAdresses.getIpv6Adresses();
if (RendererUtil.isObjectVisible(ipv6List)) {
addressBuilder.add(key, getIpAddressJsonArray(ipv6List));
insertIpAddresses = true;
}
if (insertIpAddresses) {
key = "ipAddresses";
builder.add(key, addressBuilder.build());
}
}
private static JsonArray getIpAddressJsonArray(List<IpAddress> addresses) {
JsonArrayBuilder builder = Json.createArrayBuilder();
for (IpAddress address : addresses) {
InetAddress inetA = address.getAddress();
if (RendererUtil.isObjectVisible(inetA)) {
builder.add(inetA.getHostAddress());
}
}
return builder.build();
}
}
|
3e1216fa89cf3aa918e88703990c9f4f0241758f | 828 | java | Java | api/src/main/java/org/hippoecm/hst/content/beans/query/exceptions/package-info.java | liurenjin/hippo-site-toolkit | cc975644122657aa3c0b5513744fe585eb92e29b | [
"Apache-2.0"
] | null | null | null | api/src/main/java/org/hippoecm/hst/content/beans/query/exceptions/package-info.java | liurenjin/hippo-site-toolkit | cc975644122657aa3c0b5513744fe585eb92e29b | [
"Apache-2.0"
] | 28 | 2020-10-29T15:59:43.000Z | 2022-03-02T12:50:38.000Z | site-toolkit/api/src/main/java/org/hippoecm/hst/content/beans/query/exceptions/package-info.java | ajbanck/brxm | 79d55e2d88a320719a78e3b4534799495336b572 | [
"Apache-2.0"
] | null | null | null | 37.636364 | 121 | 0.731884 | 7,619 | /*
* Copyright 2010-2013 Hippo B.V. (http://www.onehippo.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.
*/
/**
* The org.hippoecm.hst.content.beans.query.exceptions package defines the API for the HST Content Beans Query Exceptions
*/
package org.hippoecm.hst.content.beans.query.exceptions;
|
3e12179ec8cda89775932a9fe501abf5c44f8c50 | 1,756 | java | Java | src/controller/JoinController.java | yang-junehee/semi_project | c86f9e2995435a5c0e5dc105416e8d01cb883d50 | [
"MIT"
] | null | null | null | src/controller/JoinController.java | yang-junehee/semi_project | c86f9e2995435a5c0e5dc105416e8d01cb883d50 | [
"MIT"
] | null | null | null | src/controller/JoinController.java | yang-junehee/semi_project | c86f9e2995435a5c0e5dc105416e8d01cb883d50 | [
"MIT"
] | null | null | null | 28.322581 | 123 | 0.724943 | 7,620 | package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dto.MemberDTO;
import service.JoinService;
@WebServlet("/memberJoin")
public class JoinController extends HttpServlet {
private static final long serialVersionUID = 1L;
public JoinController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String id = request.getParameter("ID");
String pw = request.getParameter("PW");
String name = request.getParameter("NAMES");
String fArtist = request.getParameter("fArtist");
MemberDTO member=new MemberDTO();
member.setId(id);
member.setPw(pw);
member.setName(name);
member.setfArtist(fArtist);
JoinService joinsvc=new JoinService();
int joinResult=joinsvc.memberJoin(member);
if(joinResult>0) {
response.sendRedirect("Main.jsp");
}else {
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("alert('회원가입 실패')");
out.println("</script>");
}
}
}
|
3e1217b29e0d7aa95e575d27fabdb818078bcc4f | 2,329 | java | Java | src/com/aaron/binarytree/printer/InorderPrinter.java | aaronzzx/BinaryTree | ee469b5d413c203c66e707bc528cc04134546e7c | [
"Apache-2.0"
] | null | null | null | src/com/aaron/binarytree/printer/InorderPrinter.java | aaronzzx/BinaryTree | ee469b5d413c203c66e707bc528cc04134546e7c | [
"Apache-2.0"
] | null | null | null | src/com/aaron/binarytree/printer/InorderPrinter.java | aaronzzx/BinaryTree | ee469b5d413c203c66e707bc528cc04134546e7c | [
"Apache-2.0"
] | null | null | null | 25.877778 | 59 | 0.523401 | 7,621 | package com.aaron.binarytree.printer;
/**
* ┌──800
* ┌──760
* │ └──600
* ┌──540
* │ └──476
* │ └──445
* ┌──410
* │ └──394
* 381
* │ ┌──190
* │ │ └──146
* │ ┌──40
* │ │ └──35
* └──12
* └──9
*
* @author MJ Lee https://github.com/CoderMJLee/BinaryTrees
*/
public class InorderPrinter extends Printer {
private static String rightAppend;
private static String leftAppend;
private static String blankAppend;
private static String lineAppend;
static {
int length = 2;
rightAppend = "┌" + Strings.repeat("─", length);
leftAppend = "└" + Strings.repeat("─", length);
blankAppend = Strings.blank(length + 1);
lineAppend = "│" + Strings.blank(length);
}
public InorderPrinter(BinaryTreeInfo tree) {
super(tree);
}
@Override
public String printString() {
StringBuilder string = new StringBuilder(
printString(tree.root(), "", "", ""));
string.deleteCharAt(string.length() - 1);
return string.toString();
}
/**
* 生成node节点的字符串
*
* @param nodePrefix node那一行的前缀字符串
* @param leftPrefix node整棵左子树的前缀字符串
* @param rightPrefix node整棵右子树的前缀字符串
* @return
*/
private String printString(
Object node,
String nodePrefix,
String leftPrefix,
String rightPrefix) {
Object left = tree.left(node);
Object right = tree.right(node);
String string = tree.string(node).toString();
int length = string.length();
if (length % 2 == 0) {
length--;
}
length >>= 1;
String nodeString = "";
if (right != null) {
rightPrefix += Strings.blank(length);
nodeString += printString(right,
rightPrefix + rightAppend,
rightPrefix + lineAppend,
rightPrefix + blankAppend);
}
nodeString += nodePrefix + string + "\n";
if (left != null) {
leftPrefix += Strings.blank(length);
nodeString += printString(left,
leftPrefix + leftAppend,
leftPrefix + blankAppend,
leftPrefix + lineAppend);
}
return nodeString;
}
}
|
3e1218561fc00fa702a1fd3e9f972973486c1258 | 10,116 | java | Java | src/android/LocalNotification.java | rsimba/android-local-notifications | 5ec360ff2d17ff6eed27b091062c47649b827ef1 | [
"Apache-2.0"
] | null | null | null | src/android/LocalNotification.java | rsimba/android-local-notifications | 5ec360ff2d17ff6eed27b091062c47649b827ef1 | [
"Apache-2.0"
] | null | null | null | src/android/LocalNotification.java | rsimba/android-local-notifications | 5ec360ff2d17ff6eed27b091062c47649b827ef1 | [
"Apache-2.0"
] | 1 | 2020-10-21T21:55:54.000Z | 2020-10-21T21:55:54.000Z | 33.058824 | 188 | 0.623665 | 7,622 | /*
Copyright 2013-2014 appPlant UG
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 de.appplant.cordova.plugin.localnotification;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* This plugin utilizes the Android AlarmManager in combination with StatusBar
* notifications. When a local notification is scheduled the alarm manager takes
* care of firing the event. When the event is processed, a notification is put
* in the Android status bar.
*/
public class LocalNotification extends CordovaPlugin {
protected final static String PLUGIN_NAME = "LocalNotification";
private static CordovaWebView webView = null;
protected static Context context = null;
private static ArrayList<String> callbackQueue = new ArrayList<String>();
@Override
public void initialize (CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
LocalNotification.webView = super.webView;
LocalNotification.context = super.cordova.getActivity().getApplicationContext();
execPendingCallbacks();
}
@Override
public boolean execute (String action, final JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equalsIgnoreCase("add")) {
cordova.getThreadPool().execute( new Runnable() {
public void run() {
JSONObject arguments = args.optJSONObject(0);
Options options = new Options(context).parse(arguments);
persist(options.getId(), args);
add(options, true);
}
});
return true;
}
if (action.equalsIgnoreCase("cancel")) {
cordova.getThreadPool().execute( new Runnable() {
public void run() {
String id = args.optString(0);
cancel(id);
unpersist(id);
}
});
return true;
}
if (action.equalsIgnoreCase("cancelAll")) {
cordova.getThreadPool().execute( new Runnable() {
public void run() {
cancelAll();
unpersistAll();
}
});
return true;
}
// Returning false results in a "MethodNotFound" error.
return false;
}
/**
* Set an alarm.
*
* @param options
* The options that can be specified per alarm.
* @param doFireEvent
* If the onadd callback shall be called.
*/
public static void add (Options options, boolean doFireEvent) {
long triggerTime = options.getDate();
Intent intent = new Intent(context, Receiver.class)
.setAction("" + options.getId())
.putExtra(Receiver.OPTIONS, options.getJSONObject().toString());
AlarmManager am = getAlarmManager();
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
if (doFireEvent) {
fireEvent("add", options.getId(), options.getJSON());
}
am.set(AlarmManager.RTC_WAKEUP, triggerTime, pi);
}
/**
* Cancel a specific notification that was previously registered.
*
* @param notificationId
* The original ID of the notification that was used when it was
* registered using add()
*/
public static void cancel (String notificationId) {
/*
* Create an intent that looks similar, to the one that was registered
* using add. Making sure the notification id in the action is the same.
* Now we can search for such an intent using the 'getService' method
* and cancel it.
*/
Intent intent = new Intent(context, Receiver.class)
.setAction("" + notificationId);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = getAlarmManager();
NotificationManager nc = getNotificationManager();
am.cancel(pi);
try {
nc.cancel(Integer.parseInt(notificationId));
} catch (Exception e) {}
fireEvent("cancel", notificationId, "");
}
/**
* Cancel all notifications that were created by this plugin.
*
* Android can only unregister a specific alarm. There is no such thing
* as cancelAll. Therefore we rely on the Shared Preferences which holds
* all our alarms to loop through these alarms and unregister them one
* by one.
*/
public static void cancelAll() {
SharedPreferences settings = getSharedPreferences();
NotificationManager nc = getNotificationManager();
Map<String, ?> alarms = settings.getAll();
Set<String> alarmIds = alarms.keySet();
for (String alarmId : alarmIds) {
cancel(alarmId);
}
nc.cancelAll();
}
/**
* Persist the information of this alarm to the Android Shared Preferences.
* This will allow the application to restore the alarm upon device reboot.
* Also this is used by the cancelAll method.
*
* @param alarmId
* The Id of the notification that must be persisted.
* @param args
* The assumption is that parse has been called already.
*/
public static void persist (String alarmId, JSONArray args) {
Editor editor = getSharedPreferences().edit();
if (alarmId != null) {
editor.putString(alarmId, args.toString());
editor.commit();
}
}
/**
* Remove a specific alarm from the Android shared Preferences.
*
* @param alarmId
* The Id of the notification that must be removed.
*/
public static void unpersist (String alarmId) {
Editor editor = getSharedPreferences().edit();
if (alarmId != null) {
editor.remove(alarmId);
editor.commit();
}
}
/**
* Clear all alarms from the Android shared Preferences.
*/
public static void unpersistAll () {
Editor editor = getSharedPreferences().edit();
editor.clear();
editor.commit();
}
/**
* Fires the given event.
*
* @param {String} event The Name of the event
* @param {String} id The ID of the notification
* @param {String} json A custom (JSON) string
*/
public static void fireEvent (String event, String id, String json) {
String state = isInBackground() ? "background" : "foreground";
String params = "\"" + id + "\",\"" + state + "\",\\'" + JSONObject.quote(json) + "\\'.replace(/(^\"|\"$)/g, \\'\\')";
String js = "setTimeout('plugin.notification.local.on" + event + "(" + params + ")',0)";
// after reboot, LocalNotification.webView is always be null
// call background callback later
if (webView == null) {
callbackQueue.add(js);
} else {
webView.sendJavascript(js);
}
}
/**
* Set the application context if not already set.
*/
protected static void setContext (Context context) {
if (LocalNotification.context == null) {
LocalNotification.context = context;
}
}
/**
* The Local storage for the application.
*/
protected static SharedPreferences getSharedPreferences () {
return context.getSharedPreferences(PLUGIN_NAME, Context.MODE_PRIVATE);
}
/**
* The alarm manager for the application.
*/
protected static AlarmManager getAlarmManager () {
return (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
}
/**
* The notification manager for the application.
*/
protected static NotificationManager getNotificationManager () {
return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
/**
* Gibt an, ob die App im Hintergrund läuft.
*/
private static boolean isInBackground () {
try {
return !context.getPackageName().equalsIgnoreCase(((ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName());
} catch (Exception e) {
return true;
}
}
/**
* Calls all pending callbacks after the webview was created.
*/
private void execPendingCallbacks () {
for (String js : callbackQueue) {
webView.sendJavascript(js);
}
callbackQueue.clear();
}
} |
3e121858fb14e2a8c07fd32dcc5df6399046d8f3 | 958 | java | Java | spark-indexer/src/test/java/org/uniprot/store/spark/indexer/suggest/mapper/flatfile/FlatFileToOrganismTest.java | ebi-uniprot/uniprot-indexer | 6787e2107f60b7a3bb86cac5540c8d4287cfd249 | [
"Apache-2.0"
] | 1 | 2019-07-16T00:06:12.000Z | 2019-07-16T00:06:12.000Z | spark-indexer/src/test/java/org/uniprot/store/spark/indexer/suggest/mapper/flatfile/FlatFileToOrganismTest.java | ebi-uniprot/uniprot-store | fca441acb80188d6608acd2bf30bc9746c5644af | [
"Apache-2.0"
] | 38 | 2019-08-22T14:51:19.000Z | 2022-01-04T16:57:25.000Z | spark-indexer/src/test/java/org/uniprot/store/spark/indexer/suggest/mapper/flatfile/FlatFileToOrganismTest.java | ebi-uniprot/uniprot-indexer | 6787e2107f60b7a3bb86cac5540c8d4287cfd249 | [
"Apache-2.0"
] | null | null | null | 30.903226 | 104 | 0.611691 | 7,623 | package org.uniprot.store.spark.indexer.suggest.mapper.flatfile;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import scala.Tuple2;
/**
* @author lgonzales
* @since 2020-01-21
*/
class FlatFileToOrganismTest {
@Test
void testFlatFileToOrganism() throws Exception {
FlatFileToOrganism mapper = new FlatFileToOrganism();
String input =
"AC Q66798;\n"
+ "OS Sudan ebolavirus (strain Maleo-79) (SEBOV) (Sudan Ebola virus).\n"
+ "OC Viruses; Riboviria; Negarnaviricota; Haploviricotina; Monjiviricetes;\n"
+ "OC Mononegavirales; Filoviridae; Ebolavirus.\n"
+ "OX NCBI_TaxID=128949;";
Tuple2<String, String> result = mapper.call(input);
assertNotNull(result);
assertEquals("128949", result._1);
assertEquals("128949", result._2);
}
}
|
3e1218ebb80bcae4ca175ddd21e9cd2ab6e4d102 | 1,106 | java | Java | sonar-report-core/src/main/java/fr/sii/sonar/report/core/coverage/save/DelegateAndConvertMeasureBuilder.java | sleroy/sonar-web-frontend-plugin | f2e742a205289543497556d4dcf965779d84ab72 | [
"Apache-2.0"
] | 123 | 2015-10-28T09:47:04.000Z | 2020-11-12T08:03:29.000Z | sonar-report-core/src/main/java/fr/sii/sonar/report/core/coverage/save/DelegateAndConvertMeasureBuilder.java | sleroy/sonar-web-frontend-plugin | f2e742a205289543497556d4dcf965779d84ab72 | [
"Apache-2.0"
] | 45 | 2015-10-14T13:32:11.000Z | 2020-12-01T10:32:26.000Z | sonar-report-core/src/main/java/fr/sii/sonar/report/core/coverage/save/DelegateAndConvertMeasureBuilder.java | groupe-sii/sonar-web-client-plugin | f2e742a205289543497556d4dcf965779d84ab72 | [
"Apache-2.0"
] | 37 | 2015-10-23T16:12:55.000Z | 2022-02-03T06:53:24.000Z | 24.577778 | 97 | 0.794756 | 7,624 | package fr.sii.sonar.report.core.coverage.save;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.sonar.api.measures.CoverageMeasuresBuilder;
import org.sonar.api.measures.Measure;
import org.sonar.api.measures.Metric;
public abstract class DelegateAndConvertMeasureBuilder implements CoverageMeasureBuilder {
private CoverageMeasuresBuilder delegate;
public DelegateAndConvertMeasureBuilder() {
this.delegate = CoverageMeasuresBuilder.create();
}
@Override
public CoverageMeasureBuilder setHits(int lineId, int hits) {
delegate.setHits(lineId, hits);
return this;
}
@Override
public CoverageMeasureBuilder setConditions(int lineId, int conditions, int coveredConditions) {
delegate.setConditions(lineId, conditions, coveredConditions);
return this;
}
@Override
public Collection<Measure> createMeasures() {
return convert(delegate.createMeasures());
}
protected abstract Collection<Measure> convert(Collection<Measure> createMeasures);
@Override
public CoverageMeasureBuilder reset() {
delegate.reset();
return this;
}
}
|
3e121a7181d9c234494544cb92da7a1e0cd5c85c | 4,427 | java | Java | omnidroid/src/edu/nyu/cs/omnidroid/app/controller/Filter.java | rigelhope/omnidroid | 36571d7d04835337614a4ca105ffe613d575c4ac | [
"Apache-2.0"
] | 1 | 2018-03-27T16:05:10.000Z | 2018-03-27T16:05:10.000Z | omnidroid/src/edu/nyu/cs/omnidroid/app/controller/Filter.java | rigelhope/omnidroid | 36571d7d04835337614a4ca105ffe613d575c4ac | [
"Apache-2.0"
] | null | null | null | omnidroid/src/edu/nyu/cs/omnidroid/app/controller/Filter.java | rigelhope/omnidroid | 36571d7d04835337614a4ca105ffe613d575c4ac | [
"Apache-2.0"
] | null | null | null | 41.764151 | 97 | 0.671787 | 7,625 | /*******************************************************************************
* Copyright 2009 Omnidroid - http://code.google.com/p/omnidroid
*
* 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 edu.nyu.cs.omnidroid.app.controller;
import android.util.Log;
import edu.nyu.cs.omnidroid.app.controller.datatypes.DataType;
import edu.nyu.cs.omnidroid.app.controller.datatypes.FactoryDataType;
/**
* This class contains a user defined filter, which will be checked against an event's attribute
* data to see if the event matches the user defined {@link Rule}.
*/
public class Filter {
/** Filter parameters used to construct two OmniType objects and perform a comparison */
public final String eventAttribute;
public final String filterOnDataType;
public final String filter;
public final String compareWithDataType;
public final String compareWithData;
/**
* Creates a new {@link Filter} on an event's attribute data
*
* @param eventAttribute
* the event attribute data field to be filtered
* @param filterOnDataType
* the Omnidroid class name of the data type of the event attribute field
* @param filter
* the comparison to be made between the event attribute and the user filter data
* @param compareWithDataTyp
* the Omnidroid class name of the data type of the user filter data
* @param compareWithdata
* the user defined data to check against the event attribute
* @throws IllegalArgumentException
* if any parameters are null
*/
public Filter(String eventAttribute, String filterOnDataType, String filter,
String compareWithDataType, String compareWithdata) {
if (eventAttribute == null || filterOnDataType == null || filter == null
|| compareWithDataType == null || compareWithdata == null) {
throw new IllegalArgumentException();
}
this.eventAttribute = eventAttribute;
this.filterOnDataType = filterOnDataType;
this.filter = filter;
this.compareWithDataType = compareWithDataType;
this.compareWithData = compareWithdata;
}
/**
* Compares the data in the event attribute to the user filter data
*
* @param event
* the event whose attributes will be used for the comparison
* @return true if the event data passes the filter, false otherwise
*/
public boolean match(Event event) {
String eventAttributeData = event.getAttribute(eventAttribute);
//the attribute data we get from the event
DataType leftHandSide = FactoryDataType.createObject(filterOnDataType, eventAttributeData);
DataType.Filter comparisonFilter = FactoryDataType.getFilterFromString(filterOnDataType,
filter);
Log.d("match", "filterOnDataType is : " + filterOnDataType + " comparison is : " + filter);
DataType rightHandSide = FactoryDataType.createObject(compareWithDataType, compareWithData);
return leftHandSide.matchFilter(comparisonFilter, rightHandSide);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Filter)) {
return false;
}
Filter that = (Filter) o;
return that.compareWithData.equals(compareWithData) && that.filter.equals(filter)
&& that.filterOnDataType.equals(filterOnDataType)
&& that.eventAttribute.equals(eventAttribute);
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + eventAttribute.hashCode();
result = 37 * result + filterOnDataType.hashCode();
result = 37 * result + filter.hashCode();
result = 37 * result + compareWithDataType.hashCode();
result = 37 * result + compareWithData.hashCode();
return result;
}
}
|
3e121ad7340dcf566108dd63969da2424fcad274 | 194 | java | Java | org.jhotdraw8.application/src/main/java/org.jhotdraw8.application/org/jhotdraw8/concurrent/package-info.java | simplysuvi/jhotdraw8 | 8867b019b6cd408fb933f09008d89e5a43960c4a | [
"MIT"
] | null | null | null | org.jhotdraw8.application/src/main/java/org.jhotdraw8.application/org/jhotdraw8/concurrent/package-info.java | simplysuvi/jhotdraw8 | 8867b019b6cd408fb933f09008d89e5a43960c4a | [
"MIT"
] | null | null | null | org.jhotdraw8.application/src/main/java/org.jhotdraw8.application/org/jhotdraw8/concurrent/package-info.java | simplysuvi/jhotdraw8 | 8867b019b6cd408fb933f09008d89e5a43960c4a | [
"MIT"
] | 2 | 2022-02-28T02:16:35.000Z | 2022-03-19T23:38:29.000Z | 21.555556 | 74 | 0.71134 | 7,626 | /*
* @(#)package-info.java
* Copyright © 2021 The authors and contributors of JHotDraw. MIT License.
*/
/**
* Provides utility classes for concurrency.
*/
package org.jhotdraw8.concurrent;
|
3e121ae45a808a6bd88027360c11a29b2f10456f | 681 | java | Java | com/google/api/client/googleapis/auth/clientlogin/ClientLoginResponseException.java | RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak | 942bb61216fbb47f7909372d5c733e13d103e0ed | [
"MIT"
] | 3 | 2019-11-19T15:30:49.000Z | 2020-11-26T18:01:15.000Z | com/google/api/client/googleapis/auth/clientlogin/ClientLoginResponseException.java | RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak | 942bb61216fbb47f7909372d5c733e13d103e0ed | [
"MIT"
] | 1 | 2019-11-18T01:05:41.000Z | 2019-11-18T23:28:24.000Z | com/google/api/client/googleapis/auth/clientlogin/ClientLoginResponseException.java | RIPBackdoored/Backdoored-1.7-Deobf-Source-Leak | 942bb61216fbb47f7909372d5c733e13d103e0ed | [
"MIT"
] | 1 | 2021-06-07T22:14:35.000Z | 2021-06-07T22:14:35.000Z | 32.428571 | 103 | 0.795888 | 7,627 | package com.google.api.client.googleapis.auth.clientlogin;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpResponseException$Builder;
import com.google.api.client.util.Beta;
@Beta
public class ClientLoginResponseException extends HttpResponseException {
private static final long serialVersionUID = 4974317674023010928L;
private final transient ClientLogin$ErrorInfo details;
ClientLoginResponseException(HttpResponseException$Builder builder, ClientLogin$ErrorInfo details) {
super(builder);
this.details = details;
}
public final ClientLogin$ErrorInfo getDetails() {
return this.details;
}
}
|
3e121b9a3959b80f1ab87f69f3e0c78ec19ddc87 | 4,453 | java | Java | src/main/java/com/hz/tgb/mq/rabbitmq/template/AmqpListenerTemplate.java | qmhl/common-utils | ea4b8ffdc2ff15b8caa5377fced4e120efda8638 | [
"MIT"
] | 1 | 2020-10-16T03:39:10.000Z | 2020-10-16T03:39:10.000Z | src/main/java/com/hz/tgb/mq/rabbitmq/template/AmqpListenerTemplate.java | qmhl/common-utils | ea4b8ffdc2ff15b8caa5377fced4e120efda8638 | [
"MIT"
] | 10 | 2020-05-15T22:23:28.000Z | 2022-02-16T01:07:50.000Z | src/main/java/com/hz/tgb/mq/rabbitmq/template/AmqpListenerTemplate.java | Master-LC/Java-Utils | a71781f2409b793d425fac4116690ba51fa9a76a | [
"MIT"
] | 1 | 2020-08-13T10:11:14.000Z | 2020-08-13T10:11:14.000Z | 31.359155 | 185 | 0.607456 | 7,628 | package com.hz.tgb.mq.rabbitmq.template;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.hz.tgb.thread.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* AMQ消息监听模板
*
* @author Yaphis 2017年4月12日 下午8:04:52
*/
public abstract class AmqpListenerTemplate<T> implements MessageListener {
protected Logger LOG = LoggerFactory.getLogger(getClass());
@Override
public void onMessage(Message message) {
long startTime = System.currentTimeMillis();
Map<String, Object> messageHeader = new HashMap<String, Object>();
String messageBody = "";
try {
ThreadUtil.initThreadName();
if (null == message) {
LOG.warn("message:{} is null!", message);
return;
}
messageHeader = getMessageHeader(message);
messageBody = getMessageBody(message);
T t = parseMessage2Bean(messageHeader, messageBody);
if (!verify(t)) {
LOG.info("messageBean:{},verify fail!", t);// 校验失败
return;
}
execute(t);
} catch (Exception e) {
LOG.error("receiveMessage throws Exception:", e);
handleException(messageBody, e);
} finally {
LOG.info("{},messageHeader:{},messageBody:{} cost:{}", new Object[] { this.getClass().getSimpleName(), messageHeader, messageBody, System.currentTimeMillis() - startTime });
ThreadUtil.clearMDC();
}
}
/**
* 解析消息头
*
* @param message
* @return
*/
protected Map<String, Object> getMessageHeader(Message message) {
if (null != message.getMessageProperties()) {
return message.getMessageProperties().getHeaders();
}
LOG.warn("messageProperties:{} is null!", message.getMessageProperties());
return null;
}
/**
* 解析消息体
*
* @param message
* @return
* @throws UnsupportedEncodingException
*/
protected String getMessageBody(Message message) throws UnsupportedEncodingException {
byte[] bodyByte = message.getBody();
if (null != bodyByte && bodyByte.length > 0) {
return new String(bodyByte, "UTF-8");
} else {
LOG.error("bodyByte:{} is null or empty!", new Object[] { Arrays.toString(bodyByte) });
return "";
}
}
/**
* 校验消息 如果返回false 会抛弃该消息
*
* @param messageBean
*/
public abstract boolean verify(T messageBean);
/**
* 将来源消息转换为实体
*
* @param messageHeader
* @param messageBody
* @return
*/
public abstract T parseMessage2Bean(Map<String, Object> messageHeader, String messageBody);
/**
* 处理消息实体
*
* @param messageBean
*/
public abstract void execute(T messageBean);
/**
* 异常处理
*
* @param messageBody
* @param e
*/
protected void handleException(String messageBody, Exception e) {
LOG.warn("handleException,messageBody:{}", messageBody);
LOG.error("", e);
}
/**
* 从消息头中取值
*
* @param messageHeader 消息头
* @param headerKey 头索引
* @param defaultValue 默认值,当消息头为空或者消息头中包含头索引时返回该值
* @return
*/
protected Object getMessageHeaderValue(Map<String, Object> messageHeader, String headerKey, Object defaultValue) {
if (CollectionUtils.isEmpty(messageHeader)) {
LOG.info("messageHeader:{} is empty! return defaultValue:{}", new Object[] { messageHeader, defaultValue });
return defaultValue;
}
if (StringUtils.isEmpty(headerKey)) {
LOG.info("headerKey:{} is blank!return defaultValue:{}", new Object[] { headerKey, defaultValue });
return defaultValue;
}
if (messageHeader.containsKey(headerKey) && null != messageHeader.get(headerKey)) {
return messageHeader.get(headerKey);
} else {
LOG.info("messageHeader:{} does not contains headerKey:{} return defaultValue:{}", new Object[] { messageHeader, headerKey, defaultValue });
return defaultValue;
}
}
} |
3e121bfe68544f9cebc6d1991fa981744c1ec8e8 | 380 | java | Java | gwt/src/test/java/com/jpattern/gwt/client/serializer/ITestBean1ListFactory.java | ufoscout/jpattern | 844110ed595ad1c8e3edb610c447d99a5aafef45 | [
"Apache-2.0"
] | null | null | null | gwt/src/test/java/com/jpattern/gwt/client/serializer/ITestBean1ListFactory.java | ufoscout/jpattern | 844110ed595ad1c8e3edb610c447d99a5aafef45 | [
"Apache-2.0"
] | 1 | 2018-05-15T06:41:31.000Z | 2018-05-15T09:46:18.000Z | gwt/src/test/java/com/jpattern/gwt/client/serializer/ITestBean1ListFactory.java | ufoscout/jpattern | 844110ed595ad1c8e3edb610c447d99a5aafef45 | [
"Apache-2.0"
] | null | null | null | 16.521739 | 61 | 0.731579 | 7,629 | package com.jpattern.gwt.client.serializer;
import com.google.web.bindery.autobean.shared.AutoBean;
/**
*
* @author Francesco Cina'
*
* 23/ago/2011
*/
public interface ITestBean1ListFactory extends IBeanFactory {
AutoBean<IBean> bean1();
AutoBean<IBean> bean1(IBean obj);
AutoBean<IBean1List> bean1List();
AutoBean<IBean1List> bean1List(IBean1List obj);
}
|
3e121c239dc9c23870b205684bf9595294ac88aa | 5,272 | java | Java | unify-web/src/test/java/com/tcdng/unify/web/PathInfoRepositoryTest.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 5 | 2019-01-06T21:32:02.000Z | 2021-09-26T04:13:49.000Z | unify-web/src/test/java/com/tcdng/unify/web/PathInfoRepositoryTest.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 5 | 2020-01-02T11:09:48.000Z | 2021-05-03T12:12:53.000Z | unify-web/src/test/java/com/tcdng/unify/web/PathInfoRepositoryTest.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 3 | 2020-04-07T11:20:04.000Z | 2021-01-15T17:37:28.000Z | 43.213115 | 109 | 0.724962 | 7,630 | /*
* Copyright 2018-2020 The Code Department.
*
* 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.tcdng.unify.web;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Path information repository test.
*
* @author Lateef Ojulari
* @since 1.0
*/
public class PathInfoRepositoryTest extends AbstractUnifyWebTest {
private PathInfoRepository pir;
@Test
public void testGetPathPartsNoAction() throws Exception {
ControllerPathParts controllerPathParts = pir.getControllerPathParts("/testauthor");
assertNotNull(controllerPathParts);
assertEquals("/testauthor", controllerPathParts.getControllerPath());
assertEquals("/testauthor", controllerPathParts.getControllerPathId());
assertEquals("/testauthor", controllerPathParts.getControllerName());
assertNull(controllerPathParts.getPathVariable());
assertNull(controllerPathParts.getActionName());
assertFalse(controllerPathParts.isSessionless());
assertFalse(controllerPathParts.isActionPath());
assertFalse(controllerPathParts.isVariablePath());
}
@Test
public void testGetPathPartsWithAction() throws Exception {
ControllerPathParts controllerPathParts = pir.getControllerPathParts("/testauthor/createAuthor");
assertNotNull(controllerPathParts);
assertEquals("/testauthor/createAuthor", controllerPathParts.getControllerPath());
assertEquals("/testauthor", controllerPathParts.getControllerPathId());
assertEquals("/testauthor", controllerPathParts.getControllerName());
assertNull(controllerPathParts.getPathVariable());
assertEquals("/createAuthor", controllerPathParts.getActionName());
assertFalse(controllerPathParts.isSessionless());
assertTrue(controllerPathParts.isActionPath());
assertFalse(controllerPathParts.isVariablePath());
}
@Test
public void testGetPathPartsVariablePathNoAction() throws Exception {
ControllerPathParts controllerPathParts = pir.getControllerPathParts("/testauthor:20");
assertNotNull(controllerPathParts);
assertEquals("/testauthor:20", controllerPathParts.getControllerPath());
assertEquals("/testauthor:20", controllerPathParts.getControllerPathId());
assertEquals("/testauthor", controllerPathParts.getControllerName());
assertEquals("20", controllerPathParts.getPathVariable());
assertNull(controllerPathParts.getActionName());
assertFalse(controllerPathParts.isSessionless());
assertFalse(controllerPathParts.isActionPath());
assertTrue(controllerPathParts.isVariablePath());
}
@Test
public void testGetPathPartsVariablePathWithAction() throws Exception {
ControllerPathParts controllerPathParts = pir.getControllerPathParts("/testauthor:35/createAuthor");
assertNotNull(controllerPathParts);
assertEquals("/testauthor:35/createAuthor", controllerPathParts.getControllerPath());
assertEquals("/testauthor:35", controllerPathParts.getControllerPathId());
assertEquals("/testauthor", controllerPathParts.getControllerName());
assertEquals("35", controllerPathParts.getPathVariable());
assertEquals("/createAuthor", controllerPathParts.getActionName());
assertFalse(controllerPathParts.isSessionless());
assertTrue(controllerPathParts.isActionPath());
assertTrue(controllerPathParts.isVariablePath());
}
@Test
public void testGetPathPartsReuse() throws Exception {
ControllerPathParts pathParts1 = pir.getControllerPathParts("/testauthor:35/createAuthor");
ControllerPathParts pathParts2 = pir.getControllerPathParts("/testauthor:35/createAuthor");
assertNotNull(pathParts1);
assertNotNull(pathParts2);
assertTrue(pathParts1 == pathParts2);
ControllerPathParts pathParts3 = pir.getControllerPathParts("/testauthor/createAuthor");
ControllerPathParts pathParts4 = pir.getControllerPathParts("/testauthor/createAuthor");
assertNotNull(pathParts3);
assertNotNull(pathParts4);
assertTrue(pathParts3 == pathParts4);
}
@Override
protected void onSetup() throws Exception {
pir = (PathInfoRepository) getComponent(WebApplicationComponents.APPLICATION_PATHINFOREPOSITORY);
}
@Override
protected void onTearDown() throws Exception {
}
}
|
3e121c764c857fa1a4e56a3714e8875d947844b0 | 6,598 | java | Java | chrome/android/java/src/org/chromium/chrome/browser/tabmodel/OffTheRecordTabModel.java | rzr/chromium-crosswalk | d391344809adf7b4f39764ac0e15c378169b805f | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | chrome/android/java/src/org/chromium/chrome/browser/tabmodel/OffTheRecordTabModel.java | eth-sri/ChromeER | 002512fd4168c50bd7613c38a322e2862c9ffd89 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/android/java/src/org/chromium/chrome/browser/tabmodel/OffTheRecordTabModel.java | eth-sri/ChromeER | 002512fd4168c50bd7613c38a322e2862c9ffd89 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | 29.324444 | 99 | 0.672022 | 7,631 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tabmodel;
import org.chromium.base.ObserverList;
import org.chromium.base.ThreadUtils;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.profiles.Profile;
/**
* A TabModel implementation that handles off the record tabs.
*
* <p>
* This is not thread safe and must only be operated on the UI thread.
*
* <p>
* The lifetime of this object is not tied to that of the native TabModel. This ensures the
* native TabModel is present when at least one incognito Tab has been created and added. When
* no Tabs remain, the native model will be destroyed and only rebuilt when a new incognito Tab
* is created.
*/
public class OffTheRecordTabModel implements TabModel {
/** Creates TabModels for use in OffTheRecordModel. */
public interface OffTheRecordTabModelDelegate {
/** Creates a fully working TabModel to delegate calls to. */
TabModel createTabModel();
/** @return The number of existing OffTheRecord Tabs. */
int getOffTheRecordTabCount();
}
private final OffTheRecordTabModelDelegate mDelegate;
private final ObserverList<TabModelObserver> mObservers = new ObserverList<TabModelObserver>();
private TabModel mDelegateModel;
/**
* Constructor for OffTheRecordTabModel.
*/
public OffTheRecordTabModel(OffTheRecordTabModelDelegate tabModelCreator) {
mDelegate = tabModelCreator;
mDelegateModel = EmptyTabModel.getInstance();
}
/**
* Ensures that the real TabModel has been created.
*/
protected void ensureTabModelImpl() {
ThreadUtils.assertOnUiThread();
if (!(mDelegateModel instanceof EmptyTabModel)) return;
mDelegateModel = mDelegate.createTabModel();
for (TabModelObserver observer : mObservers) {
mDelegateModel.addObserver(observer);
}
}
/**
* @return The TabModel that this {@link OffTheRecordTabModel} is delegating calls to.
*/
protected TabModel getDelegateModel() {
return mDelegateModel;
}
/**
* Destroys the Incognito profile when all Incognito tabs have been closed. Also resets the
* delegate TabModel to be a stub EmptyTabModel.
*/
protected void destroyIncognitoIfNecessary() {
ThreadUtils.assertOnUiThread();
if (!isEmpty() || mDelegateModel instanceof EmptyTabModel) {
return;
}
Profile profile = getProfile();
mDelegateModel.destroy();
// Only delete the incognito profile if there are no incognito tabs open in any tab
// model selector as the profile is shared between them.
if (profile != null && mDelegate.getOffTheRecordTabCount() == 0) {
profile.destroyWhenAppropriate();
}
mDelegateModel = EmptyTabModel.getInstance();
}
private boolean isEmpty() {
return getComprehensiveModel().getCount() == 0;
}
@Override
public Profile getProfile() {
if (mDelegateModel instanceof TabModelJniBridge) {
TabModelJniBridge tabModel = (TabModelJniBridge) mDelegateModel;
return tabModel.isNativeInitialized() ? tabModel.getProfile() : null;
}
return mDelegateModel.getProfile();
}
@Override
public boolean isIncognito() {
return true;
}
@Override
public boolean closeTab(Tab tab) {
boolean retVal = mDelegateModel.closeTab(tab);
destroyIncognitoIfNecessary();
return retVal;
}
@Override
public boolean closeTab(Tab tab, boolean animate, boolean uponExit, boolean canUndo) {
boolean retVal = mDelegateModel.closeTab(tab, animate, uponExit, canUndo);
destroyIncognitoIfNecessary();
return retVal;
}
@Override
public Tab getNextTabIfClosed(int id) {
return mDelegateModel.getNextTabIfClosed(id);
}
@Override
public void closeAllTabs() {
mDelegateModel.closeAllTabs();
destroyIncognitoIfNecessary();
}
@Override
public void closeAllTabs(boolean allowDelegation, boolean uponExit) {
mDelegateModel.closeAllTabs(allowDelegation, uponExit);
destroyIncognitoIfNecessary();
}
@Override
public int getCount() {
return mDelegateModel.getCount();
}
@Override
public Tab getTabAt(int index) {
return mDelegateModel.getTabAt(index);
}
@Override
public int indexOf(Tab tab) {
return mDelegateModel.indexOf(tab);
}
@Override
public int index() {
return mDelegateModel.index();
}
@Override
public void setIndex(int i, TabSelectionType type) {
mDelegateModel.setIndex(i, type);
}
@Override
public void moveTab(int id, int newIndex) {
mDelegateModel.moveTab(id, newIndex);
}
@Override
public void destroy() {
mDelegateModel.destroy();
}
@Override
public boolean isClosurePending(int tabId) {
return mDelegateModel.isClosurePending(tabId);
}
@Override
public boolean supportsPendingClosures() {
return mDelegateModel.supportsPendingClosures();
}
@Override
public TabList getComprehensiveModel() {
return mDelegateModel.getComprehensiveModel();
}
@Override
public void commitAllTabClosures() {
// Return early if no tabs are open. In particular, we don't want to destroy the incognito
// tab model, in case we are about to add a tab to it.
if (isEmpty()) return;
mDelegateModel.commitAllTabClosures();
destroyIncognitoIfNecessary();
}
@Override
public void commitTabClosure(int tabId) {
mDelegateModel.commitTabClosure(tabId);
destroyIncognitoIfNecessary();
}
@Override
public void cancelTabClosure(int tabId) {
mDelegateModel.cancelTabClosure(tabId);
}
@Override
public void addTab(Tab tab, int index, TabLaunchType type) {
ensureTabModelImpl();
mDelegateModel.addTab(tab, index, type);
}
@Override
public void addObserver(TabModelObserver observer) {
mObservers.addObserver(observer);
mDelegateModel.addObserver(observer);
}
@Override
public void removeObserver(TabModelObserver observer) {
mObservers.removeObserver(observer);
mDelegateModel.removeObserver(observer);
}
}
|
3e121d689158fede502f8b4ef8470c9e3d25b0cc | 488 | java | Java | src/main/java/org/rapidpm/vaadin/v10/tb/demo/views/v03/View003.java | Java-Publications/vaadin-v10-dynamic-page-title | 8fbbefb39480d6674aabfee45f70ef78a0525955 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rapidpm/vaadin/v10/tb/demo/views/v03/View003.java | Java-Publications/vaadin-v10-dynamic-page-title | 8fbbefb39480d6674aabfee45f70ef78a0525955 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rapidpm/vaadin/v10/tb/demo/views/v03/View003.java | Java-Publications/vaadin-v10-dynamic-page-title | 8fbbefb39480d6674aabfee45f70ef78a0525955 | [
"Apache-2.0"
] | null | null | null | 30.5 | 67 | 0.80123 | 7,632 | package org.rapidpm.vaadin.v10.tb.demo.views.v03;
import org.rapidpm.dependencies.core.logger.HasLogger;
import org.rapidpm.vaadin.v10.tb.demo.views.v03.i18n.I18NPageTitle;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.Route;
@Route(View003.VIEW_003)
@I18NPageTitle(messageKey = "view.title")
public class View003 extends Composite<Div> implements HasLogger {
public static final String VIEW_003 = "view003";
}
|
3e121d9121c23337347f5d91622db7cb472747bc | 756 | java | Java | codegenerator/codeGenGradle/src/test/java/test/gen/game/StateMatcher.java | Rubentxu/entitas-java | 0e76929b7cb5928310acade09a5d753828f8e9e8 | [
"MIT"
] | 40 | 2016-11-05T18:25:20.000Z | 2022-02-16T05:22:19.000Z | codegenerator/codeGenGradle/src/test/java/test/gen/game/StateMatcher.java | Rubentxu/entitas-java | 0e76929b7cb5928310acade09a5d753828f8e9e8 | [
"MIT"
] | 3 | 2017-03-08T16:28:53.000Z | 2020-07-27T05:25:21.000Z | codegenerator/codeGenGradle/src/test/java/test/gen/game/StateMatcher.java | Rubentxu/entitas-java | 0e76929b7cb5928310acade09a5d753828f8e9e8 | [
"MIT"
] | 11 | 2018-04-03T07:00:34.000Z | 2022-02-10T06:13:37.000Z | 30.24 | 80 | 0.570106 | 7,633 | package test.gen.game;
import ilargia.entitas.matcher.Matcher;
/**
* //-------------------------------------------------------------------------//
* <auto-generated>// This code was generated by {0}.//// Changes to this file
* may cause incorrect behavior and will be lost if// the code is regenerated.//
* </auto-generated>//----------------------------------------------------------
* ---------------
*/
public class StateMatcher {
private static Matcher _matcherScore;
public static Matcher Score() {
if (_matcherScore == null) {
Matcher matcher = (Matcher) Matcher
.AllOf(StateComponentsLookup.Score);
matcher.componentNames = StateComponentsLookup.componentNames();
_matcherScore = matcher;
}
return _matcherScore;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.