hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
6df02c1edcc744b24a96f1afc2ad671b2cc528d7 | 7,278 | /*
* Copyright 2016
*
* 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 timeline;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang3.StringEscapeUtils;
import twitter4j.JSONException;
import misc.Misc;
import threader.ThreadPrintStream;
/**
* Lists Followers IDs
*
* @author Sohail Ahmed - sohail.ahmed21 at gmail.com
*/
public class FilesThreader {
static String input = null;
static String output = null;
static String totalJobsStr = null;
static String pause_STR = null;
static String numberOfTweetsStr = null;
static int pause = 0;
static Misc helpers = new Misc();
boolean runnable;
public FilesThreader() {
runnable = true;
}
public boolean isRunnable() {
return runnable;
}
public static void main(String[] args) throws InterruptedException {
// Check how many arguments were passed in
if ((args == null) || (args.length < 5)) {
System.err.println("5 Parameters are required to launch a Job.");
System.err.println("First: String 'input: "
+ "/path/to/perline/screen_names/files/'");
System.err.println("Second: String 'output: /output/path/'");
System.err.println("Third: (int) Total Number Of Jobs");
System.err.println("Fourth: (int) Number of seconds to pause");
System.err
.println("Fifth: (int) Number of Tweets to get. Max 3200");
System.err
.println("Example: fileToRun /input/path/ "
+ "/output/path/ 10 2 3200");
System.exit(-1);
}
// to write output in a file
ThreadPrintStream.replaceSystemOut();
try {
input = StringEscapeUtils.escapeJava(args[0]);
} catch (Exception e) {
System.err.println("Argument" + args[0] + " must be an String.");
System.exit(-1);
}
try {
output = StringEscapeUtils.escapeJava(args[1]);
} catch (Exception e) {
System.err.println("Argument" + args[1] + " must be an String.");
System.exit(-1);
}
try {
totalJobsStr = StringEscapeUtils.escapeJava(args[2]);
} catch (Exception e) {
System.err.println("Argument" + args[2] + " must be an integer.");
System.exit(-1);
}
try {
pause_STR = StringEscapeUtils.escapeJava(args[3]);
} catch (Exception e) {
System.err.println("Argument" + args[3] + " must be an integer.");
System.exit(-1);
}
try {
pause = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[3] + " must be an integer.");
System.exit(-1);
}
try {
numberOfTweetsStr = StringEscapeUtils.escapeJava(args[4]);
} catch (Exception e) {
System.err.println("Argument" + args[3] + " must be an integer.");
System.exit(-1);
}
int TOTAL_JOBS_INT = 3200;
try {
TOTAL_JOBS_INT = Integer.parseInt(totalJobsStr);
} catch (NumberFormatException e) {
System.err.println("Argument" + totalJobsStr
+ " must be an integer.");
System.exit(-1);
}
System.out
.println("Going to launch jobs. "
+ "Please see logs files to track jobs.");
ExecutorService threadPool = Executors
.newFixedThreadPool(TOTAL_JOBS_INT);
for (int i = 0; i < TOTAL_JOBS_INT; i++) {
final String jobNo = Integer.toString(i);
threadPool.submit(new Runnable() {
public void run() {
try {
// Create a text file where System.out.println()
// will send its data for this thread.
String threadName = Thread.currentThread().getName();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(threadName + "-logs.txt");
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(0);
}
// Create a PrintStream that will write to the new file.
PrintStream stream = new PrintStream(
new BufferedOutputStream(fos));
// Install the PrintStream to be used as System.out for
// this thread.
((ThreadPrintStream) System.out).setThreadOut(stream);
// Output three messages to System.out.
System.out.println(threadName);
System.out.println();
System.out.println();
FilesThreader.execTask(
input,
output,
totalJobsStr,
jobNo,
pause_STR,
numberOfTweetsStr,
threadName);
} catch (IOException |
ClassNotFoundException |
SQLException |
JSONException e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
});
helpers.pause(pause);
}
threadPool.shutdown();
}
public static void execTask(
String input,
String output,
String totalJobsStr,
String jobNo,
String pause,
String numberOfTweetsStr,
String threadName)
throws ClassNotFoundException, SQLException, JSONException,
IOException {
String[] args = {input, output, totalJobsStr, jobNo, pause,
numberOfTweetsStr, threadName};
timeline.FilesThreaderParser.main(args);
}
}
| 34.009346 | 82 | 0.51058 |
6685bf1757458d908e32d4069f7a8a22a28c28d7 | 4,376 | package net.minecraft.server.commands;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import java.util.Collection;
import java.util.Iterator;
import net.minecraft.commands.CommandListenerWrapper;
import net.minecraft.commands.arguments.ArgumentEntity;
import net.minecraft.commands.arguments.item.ArgumentItemStack;
import net.minecraft.commands.arguments.item.ArgumentPredicateItemStack;
import net.minecraft.network.chat.ChatMessage;
import net.minecraft.server.level.EntityPlayer;
import net.minecraft.sounds.SoundCategory;
import net.minecraft.sounds.SoundEffects;
import net.minecraft.world.entity.item.EntityItem;
import net.minecraft.world.entity.player.EntityHuman;
import net.minecraft.world.item.ItemStack;
public class CommandGive {
public static void a(CommandDispatcher<CommandListenerWrapper> commanddispatcher) {
commanddispatcher.register((LiteralArgumentBuilder) ((LiteralArgumentBuilder) net.minecraft.commands.CommandDispatcher.a("give").requires((commandlistenerwrapper) -> {
return commandlistenerwrapper.hasPermission(2);
})).then(net.minecraft.commands.CommandDispatcher.a("targets", (ArgumentType) ArgumentEntity.d()).then(((RequiredArgumentBuilder) net.minecraft.commands.CommandDispatcher.a("item", (ArgumentType) ArgumentItemStack.a()).executes((commandcontext) -> {
return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentItemStack.a(commandcontext, "item"), ArgumentEntity.f(commandcontext, "targets"), 1);
})).then(net.minecraft.commands.CommandDispatcher.a("count", (ArgumentType) IntegerArgumentType.integer(1)).executes((commandcontext) -> {
return a((CommandListenerWrapper) commandcontext.getSource(), ArgumentItemStack.a(commandcontext, "item"), ArgumentEntity.f(commandcontext, "targets"), IntegerArgumentType.getInteger(commandcontext, "count"));
})))));
}
private static int a(CommandListenerWrapper commandlistenerwrapper, ArgumentPredicateItemStack argumentpredicateitemstack, Collection<EntityPlayer> collection, int i) throws CommandSyntaxException {
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
EntityPlayer entityplayer = (EntityPlayer) iterator.next();
int j = i;
while (j > 0) {
int k = Math.min(argumentpredicateitemstack.a().getMaxStackSize(), j);
j -= k;
ItemStack itemstack = argumentpredicateitemstack.a(k, false);
boolean flag = entityplayer.inventory.pickup(itemstack);
EntityItem entityitem;
if (flag && itemstack.isEmpty()) {
itemstack.setCount(1);
entityitem = entityplayer.drop(itemstack, false);
if (entityitem != null) {
entityitem.s();
}
entityplayer.world.playSound((EntityHuman) null, entityplayer.locX(), entityplayer.locY(), entityplayer.locZ(), SoundEffects.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.2F, ((entityplayer.getRandom().nextFloat() - entityplayer.getRandom().nextFloat()) * 0.7F + 1.0F) * 2.0F);
entityplayer.defaultContainer.c();
} else {
entityitem = entityplayer.drop(itemstack, false);
if (entityitem != null) {
entityitem.n();
entityitem.setOwner(entityplayer.getUniqueID());
}
}
}
}
if (collection.size() == 1) {
commandlistenerwrapper.sendMessage(new ChatMessage("commands.give.success.single", new Object[]{i, argumentpredicateitemstack.a(i, false).C(), ((EntityPlayer) collection.iterator().next()).getScoreboardDisplayName()}), true);
} else {
commandlistenerwrapper.sendMessage(new ChatMessage("commands.give.success.single", new Object[]{i, argumentpredicateitemstack.a(i, false).C(), collection.size()}), true);
}
return collection.size();
}
}
| 56.102564 | 296 | 0.693327 |
f6e4a48c131328736f34cb9e43606e3dd2420cc7 | 506 | package com.example.reactiveweb.model;
import lombok.*;
import org.springframework.data.annotation.Id;
@Data
@NoArgsConstructor
public class Employee {
@Id
private Long id;
private String name;
private String email;
private String phone;
private int department;
public Employee(String name, String email, String phone, int department) {
this.name = name;
this.email = email;
this.phone = phone;
this.department = department;
}
}
| 17.448276 | 78 | 0.664032 |
73bea4b706f4f7ab4c009ae1c057921eeb02bec0 | 1,911 | package ren.crux.rainbow.core.parser;
import com.sun.javadoc.FieldDoc;
import org.apache.commons.lang3.tuple.Pair;
import ren.crux.rainbow.core.interceptor.CombinationInterceptor;
import ren.crux.rainbow.core.model.EntryField;
import ren.crux.rainbow.core.module.Context;
import ren.crux.rainbow.core.utils.EntryUtils;
import java.lang.reflect.Field;
import java.util.Optional;
public class EntryFieldParser extends AbstractEnhanceParser<Pair<Field, FieldDoc>, EntryField> {
private final AnnotationParser annotationParser;
private final CommentTextParser commentTextParser;
public EntryFieldParser(AnnotationParser annotationParser, CommentTextParser commentTextParser) {
this.annotationParser = annotationParser;
this.commentTextParser = commentTextParser;
}
public EntryFieldParser(CombinationInterceptor<Pair<Field, FieldDoc>, EntryField> combinationInterceptor, AnnotationParser annotationParser, CommentTextParser commentTextParser) {
super(combinationInterceptor);
this.annotationParser = annotationParser;
this.commentTextParser = commentTextParser;
}
/**
* 内部解析方法
*
* @param context 上下文
* @param source 源
* @return 目标
*/
@Override
protected Optional<EntryField> parse0(Context context, Pair<Field, FieldDoc> source) {
if (source == null || source.getLeft() == null) {
return Optional.empty();
}
Field field = source.getLeft();
FieldDoc fieldDoc = source.getRight();
EntryField entryField = new EntryField();
entryField.setName(field.getName());
entryField.setType(EntryUtils.build(field));
entryField.setAnnotations(annotationParser.parse(context, field.getAnnotations()));
commentTextParser.parse(context, fieldDoc).ifPresent(entryField::setCommentText);
return Optional.of(entryField);
}
}
| 37.470588 | 183 | 0.729461 |
29cb1b57edd3858302a8e86a626559e10df20098 | 19,750 | /*
* @author Hallaz ~ [email protected]
*
* Please do not modify without any agreement between end user and the author.
*
* Copyright (C) 2009 - 2013 AChartEngine - The 4ViewSoft Company
*
* 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.
*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.pertamina.tbbm.rewulu.ecodriving.fragment;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.pertamina.tbbm.rewulu.ecodriving.R;
import com.pertamina.tbbm.rewulu.ecodriving.databases.TripDataAdapter;
import com.pertamina.tbbm.rewulu.ecodriving.dialogs.UserInputDialog;
import com.pertamina.tbbm.rewulu.ecodriving.helpers.ResultData;
import com.pertamina.tbbm.rewulu.ecodriving.listener.OnDialogListener;
import com.pertamina.tbbm.rewulu.ecodriving.listener.OnMainListener;
import com.pertamina.tbbm.rewulu.ecodriving.utils.Api;
import com.pertamina.tbbm.rewulu.ecodriving.utils.Api.Builder;
import com.pertamina.tbbm.rewulu.ecodriving.utils.Constant;
import com.pertamina.tbbm.rewulu.ecodriving.utils.Loggers;
import com.pertamina.tbbm.rewulu.ecodriving.utils.Utils;
public class ResultFragment extends Fragment implements OnClickListener,
OnDialogListener {
private static final int USER_SAVE_BACKPRESSED_INPUT_ID = 54540545;
private static final int USER_ACTION_SAVE_ID = 92785;
private static final int USER_ACTION_SHARE_ID = 75864;
private static final int USER_ACTION_DELETE_ID = 81346;
private ResultData resultData;
private LinearLayout chartContainer;
private LinearLayout leftT, centerT, rightT;
private LinearLayout leftB, centerB, rightB;
private boolean fromTrip;
// research
private final String[] graphModel = new String[] {
"waktu (detik) - jarak (km)", "kecepatan (km/h) - jarak (km)" };
private OnMainListener callback;
private UserInputDialog userDialog = new UserInputDialog(
USER_SAVE_BACKPRESSED_INPUT_ID);
public void setData(ResultData resultData, OnMainListener callback) {
this.resultData = resultData;
this.callback = callback;
fromTrip = Backstack.isOnMaintracking();
}
public void onBackPressed() {
if (!resultData.getTripdata().isSaved() && userDialog != null)
initDialogSaveBackPressed();
else if (fromTrip)
callback.startMainMenu();
else
callback.startHistory();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_result_tracking,
container, false);
Backstack.onResult();
((ImageView) rootView.findViewById(R.id.back_action_bar))
.setOnClickListener(this);
Loggers.i("fuel start", Utils.decimalFormater(resultData.getDataLogs()
.get(0).getFuel()));
Loggers.i(
"fuel end",
Utils.decimalFormater(resultData.getDataLogs()
.get(resultData.getDataLogs().size() - 1).getFuel()));
((ImageButton) rootView.findViewById(R.id.btn_share_result))
.setOnClickListener(this);
((ImageButton) rootView.findViewById(R.id.btn_save_result))
.setOnClickListener(this);
((ImageButton) rootView.findViewById(R.id.btn_delete_result))
.setOnClickListener(this);
((TextView) rootView.findViewById(R.id.text_jarak_tempuh_result))
.setText(String.format("%.2f", resultData.getTotalDistance())
+ " km");
Loggers.i("totalDistance",
Utils.decimalFormater(resultData.getTotalDistance()));
((TextView) rootView.findViewById(R.id.text_av_speed_result))
.setText(resultData.getAvSpeed() + " km/h");
((TextView) rootView.findViewById(R.id.text_konsumsi_bbm_result))
.setText(String.format("%.2f", resultData.getTotalTripFuel())
+ " L");
Loggers.i("totalTripFuel",
Utils.decimalFormater(resultData.getTotalTripFuel()));
((TextView) rootView.findViewById(R.id.text_sisa_bbm_result))
.setText(String.format("%.2f", resultData.getRemainingFuel())
+ " L");
Loggers.i("remainingFuel",
Utils.decimalFormater(resultData.getRemainingFuel()));
// ==============================================================
// ==============================================================
((TextView) rootView.findViewById(R.id.text_jarak_tempuh_eco_result))
.setText(String.format("%.2f", resultData.getEcoDistance())
+ " km");
Loggers.i("ecoDistance",
Utils.decimalFormater(resultData.getEcoDistance()));
((TextView) rootView.findViewById(R.id.text_konsumsi_bbm_eco_result))
.setText(String.format("%.2f", resultData.getEcoFuel()) + " L");
Loggers.i("ecoFuel", Utils.decimalFormater(resultData.getEcoFuel()));
((TextView) rootView.findViewById(R.id.text_hemat_bbm_result))
.setText(String.format("%.2f", resultData.getSave_ecoFuel())
+ " L");
Loggers.i("save_ecoFuel",
Utils.decimalFormater(resultData.getSave_ecoFuel()));
((TextView) rootView.findViewById(R.id.text_hemat_emisi_result))
.setText(String.format("%.2f",
(resultData.getSave_ecoFuel() * Constant.FAKTOR_EMISI))
+ " kgCO2eq");
Loggers.i(
"text_hemat_emisi_result",
Utils.decimalFormater(resultData.getSave_ecoFuel()
* Constant.FAKTOR_EMISI));
((TextView) rootView
.findViewById(R.id.text_konsumsi_bbm_if_non_eco_result))
.setText(String.format("%.2f", resultData.getVice_ecoFuel())
+ " L");
Loggers.i("vice_ecoFuel",
Utils.decimalFormater(resultData.getVice_ecoFuel()));
// ==============================================================
// ==============================================================
Loggers.i("nonEcoDistance",
Utils.decimalFormater(resultData.getNonEcoDistance()));
((TextView) rootView
.findViewById(R.id.text_jarak_tempuh_non_eco_result))
.setText(String.format("%.2f", resultData.getNonEcoDistance())
+ " km");
Loggers.i("boros_nonEcoFuel",
Utils.decimalFormater(resultData.getBoros_nonEcoFuel()));
((TextView) rootView.findViewById(R.id.text_boros_bbm_result))
.setText(String.format("%.2f", resultData.getBoros_nonEcoFuel())
+ " L");
Loggers.i(
"text_boros_emisi_result",
Utils.decimalFormater(Constant.FAKTOR_EMISI
* resultData.getBoros_nonEcoFuel()));
((TextView) rootView.findViewById(R.id.text_boros_emisi_result))
.setText(String.format("%.2f",
(Constant.FAKTOR_EMISI * resultData
.getBoros_nonEcoFuel()))
+ " kgCO2eq");
Loggers.i("vice_nonEcoFuel",
Utils.decimalFormater(resultData.getVice_nonEcoFuel()));
((TextView) rootView
.findViewById(R.id.text_konsumsi_bbm_if_eco_non_eco_result))
.setText(String.format("%.2f", resultData.getVice_nonEcoFuel())
+ " L");
Loggers.i("nonEcoFuel",
Utils.decimalFormater(resultData.getNonEcoFuel()));
((TextView) rootView
.findViewById(R.id.text_konsumsi_bbm_non_eco_result))
.setText(String.format("%.2f", resultData.getNonEcoFuel())
+ " L");
// ==============================================================
// ==============================================================
((TextView) rootView.findViewById(R.id.text_jarak_tempuh_eco_result))
.setOnClickListener(this);
((TextView) rootView
.findViewById(R.id.text_jarak_tempuh_eco_result_title))
.setOnClickListener(this);
((TextView) rootView
.findViewById(R.id.text_jarak_tempuh_non_eco_result))
.setOnClickListener(this);
((TextView) rootView
.findViewById(R.id.text_jarak_tempuh_non_eco_result_title))
.setOnClickListener(this);
chartContainer = (LinearLayout) rootView
.findViewById(R.id.chart_container);
leftT = (LinearLayout) rootView.findViewById(R.id.ly_eco_result_title);
leftB = (LinearLayout) rootView
.findViewById(R.id.ly_non_eco_result_title);
centerT = (LinearLayout) rootView.findViewById(R.id.ly_eco_result_sym);
centerB = (LinearLayout) rootView
.findViewById(R.id.ly_non_eco_result_sym);
rightT = (LinearLayout) rootView.findViewById(R.id.ly_eco_result_body);
rightB = (LinearLayout) rootView
.findViewById(R.id.ly_non_eco_result_body);
Spinner spinner = (Spinner) rootView
.findViewById(R.id.spinner_result_graph);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_dropdown_item, graphModel);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
drawChart(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
drawChart(0);
callback.setDataTrip(resultData.getEcoFuel(),
resultData.getNonEcoFuel(), resultData.getEcoDistance(),
resultData.getNonEcoDistance());
return rootView;
}
private void drawChart(int arg0) {
// TODO Auto-generated method stub
GraphicalView chartView;
XYSeries xySeries = new XYSeries("");
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer xySeriesRenderer = new XYSeriesRenderer();
xySeriesRenderer.setLineWidth(5);
xySeriesRenderer.setColor(Color.BLUE);
// Include low and max value
xySeriesRenderer.setDisplayBoundingPoints(true);
// we add point markers
xySeriesRenderer.setPointStyle(PointStyle.POINT);
xySeriesRenderer.setPointStrokeWidth(7);
xySeriesRenderer.setChartValuesTextSize(18f);
String[] tt;
switch (arg0) {
case 0:
tt = graphModel[0].split("-");
renderer.setYTitle(tt[0].trim()); // waktu
renderer.setXTitle(tt[1]); // jarak
for (int w = 0; w < resultData.getGraphDataWaktu().size(); w++) {
xySeries.add(w, resultData.getGraphDataWaktu().get(w));
}
dataset.addSeries(xySeries);
renderer.addSeriesRenderer(xySeriesRenderer);
xySeriesRenderer.setDisplayChartValues(true);
renderer.setYAxisMin(0);
renderer.setYAxisMax(200);
renderer.setYLabels(5);
break;
case 1:
tt = graphModel[1].split("-");
renderer.setYTitle(tt[0].trim()); // speed
renderer.setXTitle(tt[1]); // jarak
for (int w = 0; w < resultData.getDistanceSpeed().size(); w++) {
xySeries.add(resultData.getDistanceSpeed().get(w), resultData
.getGraphDataSpeed().get(w));
}
dataset.addSeries(xySeries);
dataset.addSeries(getMaxEcoSpeedSeries());
xySeriesRenderer.setDisplayChartValues(false);
renderer.addSeriesRenderer(xySeriesRenderer);
renderer.addSeriesRenderer(getMaxEcoSpeedSeriesRendere());
break;
default:
break;
}
renderer.setPanEnabled(true, false);
renderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00)); // transparent
renderer.setXAxisMin(0);
renderer.setXAxisMax(5);
renderer.setXLabels(6);
renderer.setXRoundedLabels(true);
renderer.setShowGrid(true);
renderer.setGridColor(Color.WHITE);
renderer.setInScroll(true);
renderer.setAxesColor(Color.BLACK);
renderer.setLabelsColor(Color.BLACK);
renderer.setXLabelsColor(Color.BLACK);
renderer.setYLabelsColor(0, Color.BLACK);
renderer.setFitLegend(true);
renderer.setLabelsTextSize(18);
renderer.setAxisTitleTextSize(24);
renderer.setLegendTextSize(24);
renderer.setMargins(new int[] { 20, 48, 16, 16 });
renderer.setYLabelsAlign(Align.LEFT);
chartView = ChartFactory.getLineChartView(getActivity(), dataset,
renderer);
try {
chartContainer.removeViewAt(0);
} catch (Exception e) {
// TODO: handle exception
}
chartContainer.addView(chartView, 0);
}
private XYSeries getMaxEcoSpeedSeries() {
// TODO Auto-generated method stub
XYSeries maxEcoXySeries = new XYSeries("Max Eco Driving Speed");
int max = resultData.getTripdata().getMotor().getMax_speed_eco();
for (double w = -Constant.SPEED_TOLERANCE; w < resultData
.getGraphDataSpeed().size() + Constant.SPEED_TOLERANCE; w += 0.2d)
maxEcoXySeries.add(w, max);
return maxEcoXySeries;
}
private XYSeriesRenderer getMaxEcoSpeedSeriesRendere() {
// TODO Auto-generated method stub
XYSeriesRenderer maxXySeriesRenderer = new XYSeriesRenderer();
maxXySeriesRenderer.setLineWidth(8);
maxXySeriesRenderer.setColor(Color.RED);
// Include low and max value
maxXySeriesRenderer.setDisplayBoundingPoints(true);
// we add point markers
maxXySeriesRenderer.setPointStyle(PointStyle.POINT);
maxXySeriesRenderer.setPointStrokeWidth(7);
return maxXySeriesRenderer;
}
private void setVisibilityLayout(int arg0) {
// TODO Auto-generated method stub
leftB.setVisibility(arg0);
leftT.setVisibility(arg0);
centerB.setVisibility(arg0);
centerT.setVisibility(arg0);
rightB.setVisibility(arg0);
rightT.setVisibility(arg0);
}
private void initDialogShare() {
// TODO Auto-generated method stub
userDialog = new UserInputDialog(USER_ACTION_SHARE_ID,
"Bagikan Perjalanan", "Bagikan dengan judul", true, this);
if (resultData.getTripdata().isNamed())
userDialog.setTextField(resultData.getTripdata().getTitle());
userDialog.setInputTypeText();
userDialog.setCustomTextButton("Batal", "Bagikan");
userDialog.show(getFragmentManager(), null);
}
private void initDialogSave() {
// TODO Auto-generated method stub
userDialog = new UserInputDialog(USER_ACTION_SAVE_ID,
"Simpan Perjalanan", "Masukkan judul", true, this);
userDialog.setInputTypeText();
if (resultData.getTripdata().isNamed())
userDialog.setTextField(resultData.getTripdata().getTitle());
userDialog.show(getFragmentManager(), null);
}
private void initDialogSaveBackPressed() {
// TODO Auto-generated method stub
userDialog = new UserInputDialog(USER_SAVE_BACKPRESSED_INPUT_ID,
"Simpan Perjalanan", "Masukkan judul", true, this);
userDialog.setInputTypeText();
userDialog.setCustomTextButton("Hapus", "Simpan");
userDialog.show(getFragmentManager(), null);
}
private void initDialogDelete() {
// TODO Auto-generated method stub
userDialog = new UserInputDialog(USER_ACTION_DELETE_ID,
"Hapus Perjalanan ?", false, this);
userDialog.show(getFragmentManager(), null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.text_jarak_tempuh_eco_result:
case R.id.text_jarak_tempuh_eco_result_title:
case R.id.text_jarak_tempuh_non_eco_result:
case R.id.text_jarak_tempuh_non_eco_result_title:
if (leftT.getVisibility() == View.VISIBLE)
setVisibilityLayout(View.GONE);
else
setVisibilityLayout(View.VISIBLE);
break;
case R.id.btn_share_result:
if (resultData.getTripdata().isSaved())
shareTrip();
else
initDialogShare();
break;
case R.id.btn_save_result:
initDialogSave();
break;
case R.id.btn_delete_result:
initDialogDelete();
break;
case R.id.back_action_bar:
callback.onBackActionPressed();
default:
break;
}
}
@Override
public void onSubmitDialog(int id, boolean action, String arg0) {
// TODO Auto-generated method stub
switch (id) {
case USER_SAVE_BACKPRESSED_INPUT_ID:
if (action) {
if (arg0 == null) {
Utils.toast(getActivity(), "Kolom masukan harus diisi !");
return;
}
if (arg0.isEmpty()) {
Utils.toast(getActivity(), "Kolom masukan harus diisi !");
return;
}
resultData.getTripdata().setTitle(arg0);
resultData.getTripdata().setSaved(true);
} else {
resultData.getTripdata().setSaved(false);
}
TripDataAdapter.updateTrip(getActivity(), resultData.getTripdata());
callback.startMainMenu();
break;
case USER_ACTION_SAVE_ID:
if (action) {
if (arg0 == null) {
Utils.toast(getActivity(), "Kolom masukan harus diisi !");
return;
}
if (arg0.isEmpty()) {
Utils.toast(getActivity(), "Kolom masukan harus diisi !");
return;
}
resultData.getTripdata().setTitle(arg0);
resultData.getTripdata().setSaved(true);
TripDataAdapter.updateTrip(getActivity(),
resultData.getTripdata());
}
break;
case USER_ACTION_SHARE_ID:
if (action) {
if (arg0 == null) {
Utils.toast(getActivity(), "Kolom masukan harus diisi !");
return;
}
if (arg0.isEmpty()) {
Utils.toast(getActivity(), "Kolom masukan harus diisi !");
return;
}
resultData.getTripdata().setTitle(arg0);
resultData.getTripdata().setSaved(true);
TripDataAdapter.updateTrip(getActivity(),
resultData.getTripdata());
shareTrip();
}
break;
case USER_ACTION_DELETE_ID:
if (action) {
resultData.getTripdata().setSaved(false);
TripDataAdapter.updateTrip(getActivity(),
resultData.getTripdata());
callback.startMainMenu();
}
break;
default:
break;
}
}
@Override
public void onSubmitSingleDialog(int id) {
// TODO Auto-generated method stub
}
private void shareTrip() {
// TODO Auto-generated method stub
if (resultData.getTripdata().getRow_id() < 0) {
Utils.toast(getActivity(),
"Tidak bisa berbagi perjalanan, tidak terdapat koneksi internet");
return;
}
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide what to do with
// it.
Api api = new Builder().title(resultData.getTripdata().getTitle())
.userName(resultData.getTripdata().getUser().getName())
.userId(resultData.getTripdata().getUser_id())
.tripId(resultData.getTripdata().getRow_id()).build();
intent.putExtra(Intent.EXTRA_SUBJECT, api.shareFormatterSubject());
intent.putExtra(Intent.EXTRA_TEXT, api.shareFormatterBody());
startActivity(Intent.createChooser(intent, "Bagikan via "));
}
@Override
public void onDismiss(int id) {
// TODO Auto-generated method stub
}
}
| 35.01773 | 81 | 0.724051 |
d24a8f2f8687671c3495658a2dd75674650ca2d1 | 490 | package com.cooltee.test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
/**
* Base abstract class of text, use to upload spring context;
* Note: No Transactional Test should extends this.
* Created by Daniel on 2017/2/14.
*/
@ContextConfiguration(locations = {"classpath:/spring/spring-*.xml"})
public abstract class NoTransSpringTestSupport extends AbstractJUnit4SpringContextTests {
}
| 35 | 89 | 0.806122 |
719b593e1920bed3aade1ff3bbcdd0003219ed79 | 5,706 | /*
* 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.shardingsphere.core.merge.dql.common;
import org.apache.shardingsphere.core.merge.dql.common.fixture.TestMemoryMergedResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.InputStream;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class MemoryMergedResultTest {
@Mock
private MemoryQueryResultRow memoryResultSetRow;
private TestMemoryMergedResult memoryMergedResult;
@Before
public void setUp() {
Map<String, Integer> labelAndIndexMap = new HashMap<>(1, 1);
labelAndIndexMap.put("label", 1);
memoryMergedResult = new TestMemoryMergedResult(labelAndIndexMap);
memoryMergedResult.setCurrentResultSetRow(memoryResultSetRow);
}
@Test
public void assertGetValueWithColumnIndex() throws SQLException {
when(memoryResultSetRow.getCell(1)).thenReturn("1");
assertThat(memoryMergedResult.getValue(1, Object.class).toString(), is("1"));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnIndexForBlob() throws SQLException {
memoryMergedResult.getValue(1, Blob.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnIndexForClob() throws SQLException {
memoryMergedResult.getValue(1, Clob.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnIndexForReader() throws SQLException {
memoryMergedResult.getValue(1, Reader.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnIndexForInputStream() throws SQLException {
memoryMergedResult.getValue(1, InputStream.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnIndexForSQLXML() throws SQLException {
memoryMergedResult.getValue(1, SQLXML.class);
}
@Test
public void assertGetValueWithColumnLabel() throws SQLException {
when(memoryResultSetRow.getCell(1)).thenReturn("1");
assertThat(memoryMergedResult.getValue("label", Object.class).toString(), is("1"));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnLabelForBlob() throws SQLException {
memoryMergedResult.getValue("label", Blob.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnLabelForClob() throws SQLException {
memoryMergedResult.getValue("label", Clob.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnLabelForReader() throws SQLException {
memoryMergedResult.getValue("label", Reader.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnLabelForInputStream() throws SQLException {
memoryMergedResult.getValue("label", InputStream.class);
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetValueWithColumnLabelForSQLXML() throws SQLException {
memoryMergedResult.getValue("label", SQLXML.class);
}
@Test
public void assertGetCalendarValueWithColumnIndex() {
when(memoryResultSetRow.getCell(1)).thenReturn(new Date(0L));
assertThat((Date) memoryMergedResult.getCalendarValue(1, Object.class, Calendar.getInstance()), is(new Date(0L)));
}
@Test
public void assertGetCalendarValueWithColumnLabel() {
when(memoryResultSetRow.getCell(1)).thenReturn(new Date(0L));
assertThat((Date) memoryMergedResult.getCalendarValue("label", Object.class, Calendar.getInstance()), is(new Date(0L)));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnIndex() throws SQLException {
memoryMergedResult.getInputStream(1, "ascii");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnLabel() throws SQLException {
memoryMergedResult.getInputStream("label", "ascii");
}
@Test
public void assertWasNull() {
assertFalse(memoryMergedResult.wasNull());
}
}
| 38.295302 | 128 | 0.74115 |
c907ebe9ef6cc54f3ede1c1cd7fd1cb1e4283a0e | 21,112 | /*
* 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.component.seda;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import org.apache.camel.AsyncEndpoint;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.Category;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.MultipleConsumersSupport;
import org.apache.camel.PollingConsumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.WaitForTaskToComplete;
import org.apache.camel.api.management.ManagedAttribute;
import org.apache.camel.api.management.ManagedOperation;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.spi.BrowsableEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.support.service.ServiceHelper;
import org.apache.camel.util.URISupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Asynchronously call another endpoint from any Camel Context in the same JVM.
*/
@ManagedResource(description = "Managed SedaEndpoint")
@UriEndpoint(firstVersion = "1.1.0", scheme = "seda", title = "SEDA", syntax = "seda:name", category = {Category.CORE, Category.ENDPOINT})
public class SedaEndpoint extends DefaultEndpoint implements AsyncEndpoint, BrowsableEndpoint, MultipleConsumersSupport {
private static final Logger LOG = LoggerFactory.getLogger(SedaEndpoint.class);
private final Set<SedaProducer> producers = new CopyOnWriteArraySet<>();
private final Set<SedaConsumer> consumers = new CopyOnWriteArraySet<>();
private volatile AsyncProcessor consumerMulticastProcessor;
private volatile boolean multicastStarted;
private volatile ExecutorService multicastExecutor;
@UriPath(description = "Name of queue") @Metadata(required = true)
private String name;
@UriParam(label = "advanced", description = "Define the queue instance which will be used by the endpoint")
private BlockingQueue queue;
@UriParam(defaultValue = "" + SedaConstants.QUEUE_SIZE)
private int size = SedaConstants.QUEUE_SIZE;
@UriParam(label = "consumer", defaultValue = "1")
private int concurrentConsumers = 1;
@UriParam(label = "consumer,advanced", defaultValue = "true")
private boolean limitConcurrentConsumers = true;
@UriParam(label = "consumer,advanced")
private boolean multipleConsumers;
@UriParam(label = "consumer,advanced")
private boolean purgeWhenStopping;
@UriParam(label = "consumer,advanced", defaultValue = "1000")
private int pollTimeout = 1000;
@UriParam(label = "producer", defaultValue = "IfReplyExpected")
private WaitForTaskToComplete waitForTaskToComplete = WaitForTaskToComplete.IfReplyExpected;
@UriParam(label = "producer", defaultValue = "30000")
private long timeout = 30000;
@UriParam(label = "producer")
private long offerTimeout;
@UriParam(label = "producer")
private boolean blockWhenFull;
@UriParam(label = "producer")
private boolean discardWhenFull;
@UriParam(label = "producer")
private boolean failIfNoConsumers;
@UriParam(label = "producer")
private boolean discardIfNoConsumers;
private BlockingQueueFactory<Exchange> queueFactory;
public SedaEndpoint() {
queueFactory = new LinkedBlockingQueueFactory<>();
}
public SedaEndpoint(String endpointUri, Component component, BlockingQueue<Exchange> queue) {
this(endpointUri, component, queue, 1);
}
public SedaEndpoint(String endpointUri, Component component, BlockingQueue<Exchange> queue, int concurrentConsumers) {
this(endpointUri, component, concurrentConsumers);
this.queue = queue;
if (queue != null) {
this.size = queue.remainingCapacity();
}
queueFactory = new LinkedBlockingQueueFactory<>();
getComponent().registerQueue(this, queue);
}
public SedaEndpoint(String endpointUri, Component component, BlockingQueueFactory<Exchange> queueFactory, int concurrentConsumers) {
this(endpointUri, component, concurrentConsumers);
this.queueFactory = queueFactory;
}
private SedaEndpoint(String endpointUri, Component component, int concurrentConsumers) {
super(endpointUri, component);
this.concurrentConsumers = concurrentConsumers;
}
@Override
public SedaComponent getComponent() {
return (SedaComponent) super.getComponent();
}
@Override
public Producer createProducer() throws Exception {
return new SedaProducer(this, getWaitForTaskToComplete(), getTimeout(),
isBlockWhenFull(), isDiscardWhenFull(), getOfferTimeout());
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
if (getComponent() != null) {
// all consumers must match having the same multipleConsumers options
String key = getComponent().getQueueKey(getEndpointUri());
QueueReference ref = getComponent().getQueueReference(key);
if (ref != null && ref.getMultipleConsumers() != isMultipleConsumers()) {
// there is already a multiple consumers, so make sure they matches
throw new IllegalArgumentException("Cannot use existing queue " + key + " as the existing queue multiple consumers "
+ ref.getMultipleConsumers() + " does not match given multiple consumers " + multipleConsumers);
}
}
Consumer answer = createNewConsumer(processor);
configureConsumer(answer);
return answer;
}
protected SedaConsumer createNewConsumer(Processor processor) {
return new SedaConsumer(this, processor);
}
@Override
public PollingConsumer createPollingConsumer() throws Exception {
SedaPollingConsumer answer = new SedaPollingConsumer(this);
configureConsumer(answer);
return answer;
}
public synchronized BlockingQueue<Exchange> getQueue() {
if (queue == null) {
// prefer to lookup queue from component, so if this endpoint is re-created or re-started
// then the existing queue from the component can be used, so new producers and consumers
// can use the already existing queue referenced from the component
if (getComponent() != null) {
// use null to indicate default size (= use what the existing queue has been configured with)
Integer size = (getSize() == Integer.MAX_VALUE || getSize() == SedaConstants.QUEUE_SIZE) ? null : getSize();
QueueReference ref = getComponent().getOrCreateQueue(this, size, isMultipleConsumers(), queueFactory);
queue = ref.getQueue();
String key = getComponent().getQueueKey(getEndpointUri());
LOG.info("Endpoint {} is using shared queue: {} with size: {}", this, key, ref.getSize() != null ? ref.getSize() : Integer.MAX_VALUE);
// and set the size we are using
if (ref.getSize() != null) {
setSize(ref.getSize());
}
} else {
// fallback and create queue (as this endpoint has no component)
queue = createQueue();
LOG.info("Endpoint {} is using queue: {} with size: {}", this, getEndpointUri(), getSize());
}
}
return queue;
}
protected BlockingQueue<Exchange> createQueue() {
if (size > 0) {
return queueFactory.create(size);
} else {
return queueFactory.create();
}
}
/**
* Get's the {@link QueueReference} for the this endpoint.
*
* @return the reference, or <tt>null</tt> if no queue reference exists.
*/
public synchronized QueueReference getQueueReference() {
String key = getComponent().getQueueKey(getEndpointUri());
QueueReference ref = getComponent().getQueueReference(key);
return ref;
}
protected synchronized AsyncProcessor getConsumerMulticastProcessor() throws Exception {
if (!multicastStarted && consumerMulticastProcessor != null) {
// only start it on-demand to avoid starting it during stopping
ServiceHelper.startService(consumerMulticastProcessor);
multicastStarted = true;
}
return consumerMulticastProcessor;
}
protected synchronized void updateMulticastProcessor() throws Exception {
// only needed if we support multiple consumers
if (!isMultipleConsumersSupported()) {
return;
}
// stop old before we create a new
if (consumerMulticastProcessor != null) {
ServiceHelper.stopService(consumerMulticastProcessor);
consumerMulticastProcessor = null;
}
int size = getConsumers().size();
if (size >= 1) {
if (multicastExecutor == null) {
// create multicast executor as we need it when we have more than 1 processor
multicastExecutor = getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, URISupport.sanitizeUri(getEndpointUri()) + "(multicast)");
}
// create list of consumers to multicast to
List<Processor> processors = new ArrayList<>(size);
for (SedaConsumer consumer : getConsumers()) {
processors.add(consumer.getProcessor());
}
// create multicast processor
multicastStarted = false;
consumerMulticastProcessor = getCamelContext().adapt(ExtendedCamelContext.class).createMulticast(processors, multicastExecutor, false);
}
}
/**
* Define the queue instance which will be used by the endpoint.
* <p/>
* This option is only for rare use-cases where you want to use a custom queue instance.
*/
public void setQueue(BlockingQueue<Exchange> queue) {
this.queue = queue;
this.size = queue.remainingCapacity();
}
@ManagedAttribute(description = "Queue max capacity")
public int getSize() {
return size;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages it can hold).
* Will by default use the defaultSize set on the SEDA component.
*/
public void setSize(int size) {
this.size = size;
}
@ManagedAttribute(description = "Current queue size")
public int getCurrentQueueSize() {
return queue.size();
}
/**
* Whether a thread that sends messages to a full SEDA queue will block until the queue's capacity is no longer exhausted.
* By default, an exception will be thrown stating that the queue is full.
* By enabling this option, the calling thread will instead block and wait until the message can be accepted.
*/
public void setBlockWhenFull(boolean blockWhenFull) {
this.blockWhenFull = blockWhenFull;
}
@ManagedAttribute(description = "Whether the caller will block sending to a full queue")
public boolean isBlockWhenFull() {
return blockWhenFull;
}
/**
* Whether a thread that sends messages to a full SEDA queue will be discarded.
* By default, an exception will be thrown stating that the queue is full.
* By enabling this option, the calling thread will give up sending and continue,
* meaning that the message was not sent to the SEDA queue.
*/
public void setDiscardWhenFull(boolean discardWhenFull) {
this.discardWhenFull = discardWhenFull;
}
@ManagedAttribute(description = "Whether the caller will discard sending to a full queue")
public boolean isDiscardWhenFull() {
return discardWhenFull;
}
/**
* Number of concurrent threads processing exchanges.
*/
public void setConcurrentConsumers(int concurrentConsumers) {
this.concurrentConsumers = concurrentConsumers;
}
@ManagedAttribute(description = "Number of concurrent consumers")
public int getConcurrentConsumers() {
return concurrentConsumers;
}
@ManagedAttribute
public boolean isLimitConcurrentConsumers() {
return limitConcurrentConsumers;
}
/**
* Whether to limit the number of concurrentConsumers to the maximum of 500.
* By default, an exception will be thrown if an endpoint is configured with a greater number. You can disable that check by turning this option off.
*/
public void setLimitConcurrentConsumers(boolean limitConcurrentConsumers) {
this.limitConcurrentConsumers = limitConcurrentConsumers;
}
public WaitForTaskToComplete getWaitForTaskToComplete() {
return waitForTaskToComplete;
}
/**
* Option to specify whether the caller should wait for the async task to complete or not before continuing.
* The following three options are supported: Always, Never or IfReplyExpected.
* The first two values are self-explanatory.
* The last value, IfReplyExpected, will only wait if the message is Request Reply based.
* The default option is IfReplyExpected.
*/
public void setWaitForTaskToComplete(WaitForTaskToComplete waitForTaskToComplete) {
this.waitForTaskToComplete = waitForTaskToComplete;
}
@ManagedAttribute
public long getTimeout() {
return timeout;
}
/**
* Timeout (in milliseconds) before a SEDA producer will stop waiting for an asynchronous task to complete.
* You can disable timeout by using 0 or a negative value.
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@ManagedAttribute
public long getOfferTimeout() {
return offerTimeout;
}
/**
* offerTimeout (in milliseconds) can be added to the block case when queue is full.
* You can disable timeout by using 0 or a negative value.
*/
public void setOfferTimeout(long offerTimeout) {
this.offerTimeout = offerTimeout;
}
@ManagedAttribute
public boolean isFailIfNoConsumers() {
return failIfNoConsumers;
}
/**
* Whether the producer should fail by throwing an exception, when sending to a queue with no active consumers.
* <p/>
* Only one of the options <tt>discardIfNoConsumers</tt> and <tt>failIfNoConsumers</tt> can be enabled at the same time.
*/
public void setFailIfNoConsumers(boolean failIfNoConsumers) {
this.failIfNoConsumers = failIfNoConsumers;
}
@ManagedAttribute
public boolean isDiscardIfNoConsumers() {
return discardIfNoConsumers;
}
/**
* Whether the producer should discard the message (do not add the message to the queue), when sending to a queue with no active consumers.
* <p/>
* Only one of the options <tt>discardIfNoConsumers</tt> and <tt>failIfNoConsumers</tt> can be enabled at the same time.
*/
public void setDiscardIfNoConsumers(boolean discardIfNoConsumers) {
this.discardIfNoConsumers = discardIfNoConsumers;
}
@ManagedAttribute
public boolean isMultipleConsumers() {
return multipleConsumers;
}
/**
* Specifies whether multiple consumers are allowed. If enabled, you can use SEDA for Publish-Subscribe messaging.
* That is, you can send a message to the SEDA queue and have each consumer receive a copy of the message.
* When enabled, this option should be specified on every consumer endpoint.
*/
public void setMultipleConsumers(boolean multipleConsumers) {
this.multipleConsumers = multipleConsumers;
}
@ManagedAttribute
public int getPollTimeout() {
return pollTimeout;
}
/**
* The timeout used when polling. When a timeout occurs, the consumer can check whether it is allowed to continue running.
* Setting a lower value allows the consumer to react more quickly upon shutdown.
*/
public void setPollTimeout(int pollTimeout) {
this.pollTimeout = pollTimeout;
}
@ManagedAttribute
public boolean isPurgeWhenStopping() {
return purgeWhenStopping;
}
/**
* Whether to purge the task queue when stopping the consumer/route.
* This allows to stop faster, as any pending messages on the queue is discarded.
*/
public void setPurgeWhenStopping(boolean purgeWhenStopping) {
this.purgeWhenStopping = purgeWhenStopping;
}
/**
* Returns the current pending exchanges
*/
@Override
public List<Exchange> getExchanges() {
return new ArrayList<>(getQueue());
}
@Override
@ManagedAttribute
public boolean isMultipleConsumersSupported() {
return isMultipleConsumers();
}
/**
* Purges the queue
*/
@ManagedOperation(description = "Purges the seda queue")
public void purgeQueue() {
LOG.debug("Purging queue with {} exchanges", queue.size());
queue.clear();
}
/**
* Returns the current active consumers on this endpoint
*/
public Set<SedaConsumer> getConsumers() {
return consumers;
}
/**
* Returns the current active producers on this endpoint
*/
public Set<SedaProducer> getProducers() {
return new HashSet<>(producers);
}
void onStarted(SedaProducer producer) {
producers.add(producer);
}
void onStopped(SedaProducer producer) {
producers.remove(producer);
}
void onStarted(SedaConsumer consumer) throws Exception {
consumers.add(consumer);
if (isMultipleConsumers()) {
updateMulticastProcessor();
}
}
void onStopped(SedaConsumer consumer) throws Exception {
consumers.remove(consumer);
if (isMultipleConsumers()) {
updateMulticastProcessor();
}
}
public boolean hasConsumers() {
return this.consumers.size() > 0;
}
@Override
protected void doStart() throws Exception {
super.doStart();
if (discardWhenFull && blockWhenFull) {
throw new IllegalArgumentException("Cannot enable both discardWhenFull=true and blockWhenFull=true."
+ " You can only either discard or block when full.");
}
// force creating queue when starting
if (queue == null) {
queue = getQueue();
}
// special for unit testing where we can set a system property to make seda poll faster
// and therefore also react faster upon shutdown, which makes overall testing faster of the Camel project
String override = System.getProperty("CamelSedaPollTimeout", "" + getPollTimeout());
setPollTimeout(Integer.valueOf(override));
}
@Override
public void stop() {
if (getConsumers().isEmpty()) {
super.stop();
} else {
LOG.debug("There is still active consumers.");
}
}
@Override
public void shutdown() {
if (isShutdown()) {
LOG.trace("Service already shut down");
return;
}
// notify component we are shutting down this endpoint
if (getComponent() != null) {
getComponent().onShutdownEndpoint(this);
}
if (getConsumers().isEmpty()) {
super.shutdown();
} else {
LOG.debug("There is still active consumers.");
}
}
@Override
protected void doShutdown() throws Exception {
// shutdown thread pool if it was in use
if (multicastExecutor != null) {
getCamelContext().getExecutorServiceManager().shutdownNow(multicastExecutor);
multicastExecutor = null;
}
// clear queue, as we are shutdown, so if re-created then the queue must be updated
queue = null;
}
}
| 37.169014 | 167 | 0.674545 |
8e21543e9e516205857bf3fff0b0266a729eca6e | 1,531 | /*
* Copyright 2006-2021 The JGUIraffe 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 net.sf.jguiraffe.gui.dlg;
/**
* <p>
* A callback interface to notify a client that the user has canceled a standard
* dialog.
* </p>
* <p>
* When working with standard dialogs client code can optionally provide an
* object implementing this interface. This single method defined here is called
* when the dialog is not closed via the OK button, but canceled. It is passed a
* client-specific data object that can contain some context information, so
* that it can react properly on the cancellation of the dialog.
* </p>
*
* @param <D> the type of the data object associated with this callback
* @since 1.4
*/
public interface DialogCanceledCallback<D>
{
/**
* Notifies this object that the associated standard dialog did not produce
* a result, but was canceled by the user.
*
* @param data client-specific data for this callback
*/
void onDialogCanceled(D data);
}
| 34.795455 | 80 | 0.72371 |
e943fc353128579e0b34821f3e3aa7cb90511523 | 1,810 | package org.innovateuk.ifs.competition.domain;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.innovateuk.ifs.category.domain.CategoryLink;
import org.innovateuk.ifs.category.domain.InnovationArea;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
@DiscriminatorValue("org.innovateuk.ifs.competition.domain.Competition#innovationArea")
public class CompetitionInnovationAreaLink extends CategoryLink<Competition, InnovationArea> {
@ManyToOne(optional = false)
@JoinColumn(name = "class_pk", referencedColumnName = "id")
private Competition competition;
protected CompetitionInnovationAreaLink() {
}
public CompetitionInnovationAreaLink(Competition competition, InnovationArea category) {
super(category);
if (competition == null) {
throw new NullPointerException("competition cannot be null");
}
this.competition = competition;
}
public Competition getEntity() {
return competition;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CompetitionInnovationAreaLink that = (CompetitionInnovationAreaLink) o;
return new EqualsBuilder()
.appendSuper(super.equals(o))
.append(competition.getId(), that.competition.getId())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.appendSuper(super.hashCode())
.append(competition.getId())
.toHashCode();
}
}
| 29.672131 | 94 | 0.688398 |
480b359c8e65d3c82738961670b9f0813c3f007b | 15,182 | /*
* 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.openmetadata.catalog.resources.databases;
import org.apache.http.client.HttpResponseException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.openmetadata.catalog.Entity;
import org.openmetadata.catalog.api.data.CreateDatabase;
import org.openmetadata.catalog.entity.data.Database;
import org.openmetadata.catalog.exception.CatalogExceptionMessage;
import org.openmetadata.catalog.jdbi3.DatabaseRepository.DatabaseEntityInterface;
import org.openmetadata.catalog.resources.EntityResourceTest;
import org.openmetadata.catalog.resources.databases.DatabaseResource.DatabaseList;
import org.openmetadata.catalog.type.EntityReference;
import org.openmetadata.catalog.util.EntityInterface;
import org.openmetadata.catalog.util.ResultList;
import org.openmetadata.catalog.util.TestUtils;
import javax.ws.rs.client.WebTarget;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.CONFLICT;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.openmetadata.catalog.exception.CatalogExceptionMessage.entityNotFound;
import static org.openmetadata.catalog.util.TestUtils.adminAuthHeaders;
import static org.openmetadata.catalog.util.TestUtils.assertResponse;
import static org.openmetadata.catalog.util.TestUtils.authHeaders;
public class DatabaseResourceTest extends EntityResourceTest<Database> {
public DatabaseResourceTest() {
super(Entity.DATABASE, Database.class, DatabaseList.class, "databases",
DatabaseResource.FIELDS, false, true, false);
}
@BeforeAll
public static void setup(TestInfo test) throws IOException, URISyntaxException {
EntityResourceTest.setup(test);
}
@Test
public void post_databaseWithLongName_400_badRequest(TestInfo test) {
// Create database with mandatory name field empty
CreateDatabase create = create(test).withName(TestUtils.LONG_ENTITY_NAME);
assertResponse(() -> createDatabase(create, adminAuthHeaders()), BAD_REQUEST,
"[name size must be between 1 and 64]");
}
@Test
public void post_databaseWithoutName_400_badRequest(TestInfo test) {
// Create database with mandatory name field empty
CreateDatabase create = create(test).withName("");
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
createDatabase(create, adminAuthHeaders()));
assertResponse(exception, BAD_REQUEST, "[name size must be between 1 and 64]");
}
@Test
public void post_databaseAlreadyExists_409_conflict(TestInfo test) throws HttpResponseException {
CreateDatabase create = create(test);
createDatabase(create, adminAuthHeaders());
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
createDatabase(create, adminAuthHeaders()));
assertResponse(exception, CONFLICT, CatalogExceptionMessage.ENTITY_ALREADY_EXISTS);
}
@Test
public void post_validDatabases_as_admin_200_OK(TestInfo test) throws IOException {
// Create team with different optional fields
CreateDatabase create = create(test);
createAndCheckEntity(create, adminAuthHeaders());
create.withName(getDatabaseName(test, 1)).withDescription("description");
createAndCheckEntity(create, adminAuthHeaders());
}
@Test
public void post_databaseFQN_as_admin_200_OK(TestInfo test) throws IOException {
// Create team with different optional fields
CreateDatabase create = create(test);
create.setService(new EntityReference().withId(SNOWFLAKE_REFERENCE.getId()).withType("databaseService"));
Database db = createAndCheckEntity(create, adminAuthHeaders());
String expectedFQN = SNOWFLAKE_REFERENCE.getName()+"."+create.getName();
assertEquals(expectedFQN, db.getFullyQualifiedName());
}
@Test
public void post_databaseWithUserOwner_200_ok(TestInfo test) throws IOException {
createAndCheckEntity(create(test).withOwner(USER_OWNER1), adminAuthHeaders());
}
@Test
public void post_databaseWithTeamOwner_200_ok(TestInfo test) throws IOException {
createAndCheckEntity(create(test).withOwner(TEAM_OWNER1), adminAuthHeaders());
}
@Test
public void post_database_as_non_admin_401(TestInfo test) {
CreateDatabase create = create(test);
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
createDatabase(create, authHeaders("[email protected]")));
assertResponse(exception, FORBIDDEN, "Principal: CatalogPrincipal{name='test'} is not admin");
}
@Test
public void post_databaseWithoutRequiredService_4xx(TestInfo test) {
CreateDatabase create = create(test).withService(null);
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
createDatabase(create, adminAuthHeaders()));
TestUtils.assertResponseContains(exception, BAD_REQUEST, "service must not be null");
}
@Test
public void post_databaseWithInvalidOwnerType_4xx(TestInfo test) {
EntityReference owner = new EntityReference().withId(TEAM1.getId()); /* No owner type is set */
CreateDatabase create = create(test).withOwner(owner);
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
createDatabase(create, adminAuthHeaders()));
TestUtils.assertResponseContains(exception, BAD_REQUEST, "type must not be null");
}
@Test
public void post_databaseWithNonExistentOwner_4xx(TestInfo test) {
EntityReference owner = new EntityReference().withId(TestUtils.NON_EXISTENT_ENTITY).withType("user");
CreateDatabase create = create(test).withOwner(owner);
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
createDatabase(create, adminAuthHeaders()));
assertResponse(exception, NOT_FOUND, entityNotFound("User", TestUtils.NON_EXISTENT_ENTITY));
}
@Test
public void post_databaseWithDifferentService_200_ok(TestInfo test) throws IOException {
EntityReference[] differentServices = {MYSQL_REFERENCE, REDSHIFT_REFERENCE, BIGQUERY_REFERENCE,
SNOWFLAKE_REFERENCE};
// Create database for each service and test APIs
for (EntityReference service : differentServices) {
createAndCheckEntity(create(test).withService(service), adminAuthHeaders());
// List databases by filtering on service name and ensure right databases are returned in the response
Map<String, String> queryParams = new HashMap<>(){{put("service", service.getName());}};
ResultList<Database> list = listEntities(queryParams, adminAuthHeaders());
for (Database db : list.getData()) {
assertEquals(service.getName(), db.getService().getName());
}
}
}
@Test
public void get_nonExistentDatabase_404_notFound() {
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
getDatabase(TestUtils.NON_EXISTENT_ENTITY, adminAuthHeaders()));
assertResponse(exception, NOT_FOUND,
entityNotFound(Entity.DATABASE, TestUtils.NON_EXISTENT_ENTITY));
}
@Test
public void get_databaseWithDifferentFields_200_OK(TestInfo test) throws IOException {
CreateDatabase create = create(test).withDescription("description").withOwner(USER_OWNER1)
.withService(SNOWFLAKE_REFERENCE);
Database database = createAndCheckEntity(create, adminAuthHeaders());
validateGetWithDifferentFields(database, false);
}
@Test
public void get_databaseByNameWithDifferentFields_200_OK(TestInfo test) throws IOException {
CreateDatabase create = create(test).withDescription("description").withOwner(USER_OWNER1)
.withService(SNOWFLAKE_REFERENCE);
Database database = createAndCheckEntity(create, adminAuthHeaders());
validateGetWithDifferentFields(database, true);
}
@Test
public void delete_emptyDatabase_200_ok(TestInfo test) throws HttpResponseException {
Database database = createDatabase(create(test), adminAuthHeaders());
deleteDatabase(database.getId(), adminAuthHeaders());
}
@Test
public void delete_nonEmptyDatabase_4xx() {
// TODO
}
@Test
public void delete_nonExistentDatabase_404() {
HttpResponseException exception = assertThrows(HttpResponseException.class, () ->
deleteDatabase(TestUtils.NON_EXISTENT_ENTITY, adminAuthHeaders()));
assertResponse(exception, NOT_FOUND, entityNotFound(Entity.DATABASE, TestUtils.NON_EXISTENT_ENTITY));
}
public static Database createAndCheckDatabase(CreateDatabase create,
Map<String, String> authHeaders) throws IOException {
return new DatabaseResourceTest().createAndCheckEntity(create, authHeaders);
}
public static Database createDatabase(CreateDatabase create,
Map<String, String> authHeaders) throws HttpResponseException {
return TestUtils.post(getResource("databases"), create, Database.class, authHeaders);
}
/** Validate returned fields GET .../databases/{id}?fields="..." or GET .../databases/name/{fqn}?fields="..." */
private void validateGetWithDifferentFields(Database database, boolean byName) throws HttpResponseException {
// .../databases?fields=owner
String fields = "owner";
database = byName ? getDatabaseByName(database.getFullyQualifiedName(), fields, adminAuthHeaders()) :
getDatabase(database.getId(), fields, adminAuthHeaders());
assertNotNull(database.getOwner());
assertNotNull(database.getService()); // We always return the service
assertNull(database.getTables());
// .../databases?fields=owner,service
fields = "owner,service";
database = byName ? getDatabaseByName(database.getFullyQualifiedName(), fields, adminAuthHeaders()) :
getDatabase(database.getId(), fields, adminAuthHeaders());
assertNotNull(database.getOwner());
assertNotNull(database.getService());
assertNull(database.getTables());
// .../databases?fields=owner,service,tables
fields = "owner,service,tables,usageSummary";
database = byName ? getDatabaseByName(database.getFullyQualifiedName(), fields, adminAuthHeaders()) :
getDatabase(database.getId(), fields, adminAuthHeaders());
assertNotNull(database.getOwner());
assertNotNull(database.getService());
assertNotNull(database.getTables());
TestUtils.validateEntityReference(database.getTables());
assertNotNull(database.getUsageSummary());
}
public static void getDatabase(UUID id, Map<String, String> authHeaders) throws HttpResponseException {
getDatabase(id, null, authHeaders);
}
public static Database getDatabase(UUID id, String fields, Map<String, String> authHeaders)
throws HttpResponseException {
WebTarget target = getResource("databases/" + id);
target = fields != null ? target.queryParam("fields", fields): target;
return TestUtils.get(target, Database.class, authHeaders);
}
public static Database getDatabaseByName(String fqn, String fields, Map<String, String> authHeaders)
throws HttpResponseException {
WebTarget target = getResource("databases/name/" + fqn);
target = fields != null ? target.queryParam("fields", fields): target;
return TestUtils.get(target, Database.class, authHeaders);
}
private void deleteDatabase(UUID id, Map<String, String> authHeaders) throws HttpResponseException {
TestUtils.delete(getResource("databases/" + id), authHeaders);
// Ensure deleted database does not exist
HttpResponseException exception = assertThrows(HttpResponseException.class, () -> getDatabase(id, authHeaders));
assertResponse(exception, NOT_FOUND, entityNotFound(Entity.DATABASE, id));
}
public static String getDatabaseName(TestInfo test) {
return String.format("database_%s", test.getDisplayName());
}
public static String getDatabaseName(TestInfo test, int index) {
return String.format("database%d_%s", index, test.getDisplayName());
}
public static CreateDatabase create(TestInfo test) {
return new CreateDatabase().withName(getDatabaseName(test)).withService(SNOWFLAKE_REFERENCE);
}
public static CreateDatabase create(TestInfo test, int index) {
return new CreateDatabase().withName(getDatabaseName(test, index)).withService(SNOWFLAKE_REFERENCE);
}
@Override
public Object createRequest(TestInfo test, int index, String description, String displayName, EntityReference owner) {
return create(test, index).withDescription(description).withOwner(owner);
}
@Override
public void validateCreatedEntity(Database createdEntity, Object request, Map<String, String> authHeaders) {
CreateDatabase createRequest = (CreateDatabase) request;
validateCommonEntityFields(getEntityInterface(createdEntity), createRequest.getDescription(),
TestUtils.getPrincipal(authHeaders), createRequest.getOwner());
// Validate service
assertService(createRequest.getService(), createdEntity.getService());
}
@Override
public void validateUpdatedEntity(Database updatedEntity, Object request, Map<String, String> authHeaders) {
validateCreatedEntity(updatedEntity, request, authHeaders);
}
@Override
public void compareEntities(Database expected, Database updated, Map<String, String> authHeaders) {
validateCommonEntityFields(getEntityInterface(updated), expected.getDescription(),
TestUtils.getPrincipal(authHeaders), expected.getOwner());
// Validate service
assertService(expected.getService(), updated.getService());
}
@Override
public EntityInterface<Database> getEntityInterface(Database entity) {
return new DatabaseEntityInterface(entity);
}
@Override
public void assertFieldChange(String fieldName, Object expected, Object actual) throws IOException {
assertCommonFieldChange(fieldName, expected, actual);
}
}
| 44.91716 | 120 | 0.758925 |
0ad1df14f2d57f3879f2301eb379f50f152cc90c | 1,882 | package com.actech.protozoan_parasite;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class OptionsPage extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options_page);
}
public void GenusLevel (View view){
Intent i = new Intent( OptionsPage.this, GenusLevel.class);
startActivity(i);
}
public void Diagnosis (View view){
Intent i = new Intent( OptionsPage.this, Diagnosis.class);
startActivity(i);
}
public void Treatment(View view){
Intent i = new Intent( OptionsPage.this, Treatment.class);
startActivity(i);
}
public void ScientificName(View view){
Intent i = new Intent( OptionsPage.this, ScientificName.class);
startActivity(i);
}
public void SpeciesLevel(View view){
Intent i = new Intent( OptionsPage.this, SpeciesLevel.class);
startActivity(i);
}
public void HostParasiteDatabase(View view){
Intent i = new Intent( OptionsPage.this, HostParasiteDatabase.class);
startActivity(i);
}
public void Acknowledgements (View view){
Intent i = new Intent( OptionsPage.this, Acknowledgements.class);
startActivity(i);
}
public void References (View view){
Intent i = new Intent( OptionsPage.this, References.class);
startActivity(i);
}
@Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),HomeScreen.class));
}
}
| 22.404762 | 85 | 0.623804 |
7541547ea99d16d116a112a63e9e90c9601dd7aa | 603 | package org.sam.server.http;
import org.junit.jupiter.api.Test;
import java.io.*;
import static org.junit.jupiter.api.Assertions.*;
class MultipartFileTest {
@Test
void writeFile() throws IOException {
InputStream fis = new FileInputStream("/Users/melchor/Downloads/download.jpeg");
int i;
File file = new File("/Users/melchor/download.jpeg");
FileOutputStream fos = new FileOutputStream(file);
while ((i = fis.read()) != -1) {
fos.write(i);
System.out.println(i);
}
fos.flush();
fos.close();
}
} | 23.192308 | 88 | 0.605307 |
aea358fe083d10b3552f3f1a1333c2a74bdbeb28 | 880 | package com.walker.concurrency.inpractice.chapter1;
/**
* @author walkerwei
* @version 2016/11/14
*/
public class SequencyDemo {
public static void main(String[] args) throws InterruptedException {
// final UnsafeSequence sequency = new UnsafeSequence();
final SafeSequency sequency = new SafeSequency();
Thread t1 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<100000;i++){
sequency.getNext();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<100000;i++){
sequency.getNext();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(sequency.getNext());
}
}
| 24.444444 | 72 | 0.498864 |
06450ee692f472cac0d437ed77d23547652322e9 | 522 | package com.onewind.android.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by bin on 2017/11/5.
*/
public class Now {
public String tmp;
public String fl;
@SerializedName("cond_code")
public String condCode;
@SerializedName("cond_txt")
public String condTxt;
@SerializedName("wind_dir")
public String windDir;
@SerializedName("wind_sc")
public String windSc;
@SerializedName("wind_spd")
public String windSpd;
public String vis;
}
| 15.352941 | 50 | 0.681992 |
56c3ea3a7a1c458f7598218990d849e69561652a | 1,867 | package net.freeapis.reactor.telnet;
import net.freeapis.reactor.IOHandler;
import java.io.File;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
/**
* Created by wuqiang on 2017/8/20.
*/
public class TelnetHandler extends IOHandler{
private static final char PACKET_DELIMITER = 0x0D0A;//数据包分隔符,默认为回车换行'\r\n'
public TelnetHandler(Selector selector, SocketChannel socketChannel) throws Exception {
super(selector, socketChannel);
}
protected void read() throws Exception{
socketChannel.read(readBuffer);
int currentPosition = readBuffer.position();
String line = null;
//使用lastpacketPosition变量记住上次读取的数据包位置,解决数据包粘包的问题
for(int i = lastPacketPosition; i < currentPosition; i++){
boolean isForceClose = (
readBuffer.getLong(i) == CLIENT_FORCE_CLOSE_UNIX
|| readBuffer.getLong(i) == CLIENT_FORCE_CLOSE_WINDOWS);
if(isForceClose) socketChannel.close();
if(readBuffer.getChar(i) == PACKET_DELIMITER){
byte[] packet = new byte[i - lastPacketPosition];
readBuffer.position(lastPacketPosition);
readBuffer.get(packet);
readBuffer.position(currentPosition);
line = new String(packet,"UTF-8");
lastPacketPosition = i + 2;
break;
}
}
if(line != null && !line.isEmpty()){
selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
writeBuffer.clear();
writeBuffer.put(CommandUtil.runShell(new File("C://"),line).getBytes());
writeBuffer.flip();
this.write();
}
//随时判断缓冲区使用情况,清理之前已经读取过的内存
clearUnusedMemory();
}
}
| 35.226415 | 91 | 0.621318 |
5a69b5fc82c9cecdc0cd2681c274a2035c79ba33 | 11,679 | package com.mindorks.test;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.FacebookSdk;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import static android.provider.ContactsContract.CommonDataKinds.Website.URL;
/**
* Created by Maddy on 21/01/17.
*/
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private ProgressDialog pDialog;
private PrefManager pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
pref = new PrefManager(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
nextActivity(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
// Progress dialog
if (pref.isLoggedIn()){
Intent main = new Intent(LoginActivity.this, ProfileActivity.class);
main.putExtra("name", pref.getName());
main.putExtra("imageUrl", pref.getUrl());
startActivity(main);
finish();
}
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
pref.setBoolean(true);
Toast.makeText(getApplicationContext(), "Logging in...", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
}
};
loginButton.setReadPermissions("user_friends");
loginButton.registerCallback(callbackManager, callback);
}
@Override
protected void onResume() {
super.onResume();
//Facebook login
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
}
@Override
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
//Facebook login
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
//Facebook login
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
private void nextActivity(Profile profile){
if(profile != null){
registerUser(profile);
}
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final Profile profile) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
params.put("emailid", profile.getLastName());
params.put("url", "google.com/");
final JSONObject jsonBody = new JSONObject(params);
user datain = new user();
datain.setName(profile.getFirstName()+" "+profile.getLastName());
datain.setId(profile.getId());
datain.setUrl(profile.getProfilePictureUri(200,200).toString());
GsonRequest<user> req = new GsonRequest<user>(
com.android.volley.Request.Method.POST,
AppConfig.URL_REGISTER,
user.class,
datain ,
new Response.Listener<user>() {
@Override
public void onResponse(user user) {
pref.setUserid(user.getId());
pref.setUrl(user.getUrl());
pref.setName(user.getName());
Intent main = new Intent(LoginActivity.this, ProfileActivity.class);
main.putExtra("name", user.getName());
// main.putExtra("surname", profile.getLastName());
main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(main);
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if(volleyError != null) Log.e("MainActivity", volleyError.getMessage());
hideDialog();
}
});
/* JsonObjectRequest req = new JsonObjectRequest(AppConfig.URL_REGISTER, jsonBody,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// handle response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handle error
if(error != null) Log.e("MainActivity", error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/x-www-form-urlencoded");
return headers;
}
};*/
/* final GsonRequest gsonRequest = new GsonRequest(AppConfig.URL_GET, user.class, null, new Response.Listener<user>() {
@Override
public void onResponse(user user) {
String textResult = "";
/* for(int i=0; i<products.getProducts().size(); i++){
Product productItem = products.getProducts().get(i);
textResult += "Name: " + productItem.getName() + "\n";
textResult += "Description: " + productItem.getDescription() + "\n";
textResult += "Price: $" + productItem.getPrice() + "\n\n";
}
tvResult.setText(textResult);*/
/* }
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if(volleyError != null) Log.e("MainActivity", volleyError.getMessage());
}
});*/
/*StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("id");
JSONObject user = jObj.getJSONObject("emailId");
String skills = user.getString("url");
// Inserting row in users table
// Launch login activity
Intent main = new Intent(LoginActivity.this, ProfileActivity.class);
main.putExtra("name", profile.getFirstName());
main.putExtra("surname", profile.getLastName());
main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(main);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("id", profile.getFirstName());
params.put("name", profile.getLastName());
params.put("url", profile.getProfilePictureUri(200,200).toString());
return params;
}
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};*/
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
| 36.611285 | 125 | 0.579245 |
8c00b973ba00c3581da32819bebac979d4360e1b | 3,545 | /*
* Artificial Intelligence for Humans
* Volume 3: Deep Learning and Neural Networks
* Java Version
* http://www.aifh.org
* http://www.jeffheaton.com
*
* Code repository:
* https://github.com/jeffheaton/aifh
*
* Copyright 2014-2015 by Jeff Heaton
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package com.heatonresearch.aifh.dbnn;
/**
* A hidden layer for a DBNN. This is based on a restricted Boltzmann machine.
*/
public class HiddenLayer extends DeepLayer {
/**
* Create a hidden layer for a DBNN.
* @param theOwner The DBNN that this layer belongs to.
* @param theInputCount The number of visible units, the input.
* @param theOutputCount The number of hidden units, the output.
*/
public HiddenLayer(DeepBeliefNetwork theOwner, int theInputCount, int theOutputCount) {
super(theOwner,theInputCount, theOutputCount);
}
/**
* Sample n times at probability p and return the count of how many samples were 1 (true).
* @param n The number of samples needed.
* @param p The probability of choosing 1 (true).
* @return The count of how many 1 (true)'s were sampled.
*/
public int binomial(int n, double p) {
if(p < 0 || p > 1) return 0;
int c = 0;
double r;
for(int i=0; i<n; i++) {
r = getOwner().getRandom().nextDouble();
if (r < p) c++;
}
return c;
}
/**
* Compute the sigmoid (logisitic) for x.
* @param x The value to compute for.
* @return The result.
*/
public static double sigmoid(double x) {
return 1.0 / (1.0 + Math.exp(-x));
}
/**
* Calculate the sigmoid output for this layer.
* @param input The input values for this layer's visable.
* @param w Thw weights for this layer.
* @param b The bias value for this layer.
* @return The hidden values for this layer, the output.
*/
public double output(double[] input, double[] w, double b) {
double linearOutput = 0.0;
// First calculate the linear output. Similar to linear regression.
for(int j=0; j<getInputCount(); j++) {
linearOutput += w[j] * input[j];
}
linearOutput += b;
// Now return the signoid of the linear sum.
return sigmoid(linearOutput);
}
/**
* Sample the hidden (h) output values, given the (v) input values. This is different than the output method
* in that we are actually sampling discrete (0 or 1) values.
* @param v The visible units.
* @param h The hidden units, the count of how many times a true (1) was sampled.
*/
public void sampleHgivenV(double[] v, double[] h) {
for(int i=0; i<getOutputCount(); i++) {
h[i] = binomial(1, output(v, getWeights()[i], this.getBias()[i]));
}
}
/**
* @return The number of input (visible) units.
*/
public int getInputCount() {
return getWeights()[0].length;
}
/**
* @return The number of output (visible) units.
*/
public int getOutputCount() {
return getWeights().length;
}
} | 29.541667 | 110 | 0.674471 |
13286d451bf42d60dc879325789586b18ea252e9 | 32,063 | package trainableSegmentation;
/**
* This class is intended for the Trainable Segmentation library. It creates and holds
* different feature images for the classification. Possible 3D filters include:
* - Gaussian blur
* - Hessian
* - High order derivative
* - Laplacian
* - Structure tensor
* - Edge detector
* - Difference of Gaussian
* - Minimum
* - Maximum
* - Mean
* - Median
* - Variance
*
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Authors: Verena Kaynig ([email protected]), Ignacio Arganda-Carreras ([email protected])
* Albert Cardona ([email protected])
*/
import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Prefs;
import ij.plugin.Filters3D;
import ij.plugin.ImageCalculator;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import imagescience.feature.Differentiator;
import imagescience.feature.Edges;
import imagescience.feature.Hessian;
import imagescience.feature.Laplacian;
import imagescience.feature.Structure;
import imagescience.image.Aspects;
import imagescience.image.FloatImage;
public class FeatureStack3D
{
/** original input image */
private ImagePlus originalImage = null;
/** list of feature images (created by filtering) */
private ArrayList<ImagePlus> wholeStack = null;
private boolean colorFeatures = false;
/** image width */
private int width = 0;
/** image height */
private int height = 0;
/** minmum sigma/radius used in the filters */
private float minimumSigma = 1;
/** maximum sigma/radius used in the filters */
private float maximumSigma = 16;
/** Gaussian filter flag index */
public static final int GAUSSIAN = 0;
/** Hessian filter flag index */
public static final int HESSIAN = 1;
/** Derivatives filter flag index */
public static final int DERIVATIVES = 2;
/** Laplacian filter flag index */
public static final int LAPLACIAN = 3;
/** structure tensor filter flag index */
public static final int STRUCTURE = 4;
/** edge filter flag index */
public static final int EDGES = 5;
/** difference of Gaussian filter flag index */
public static final int DOG = 6;
/** Minimum flag index */
public static final int MINIMUM = 7;
/** Maximum flag index */
public static final int MAXIMUM = 8;
/** Mean flag index */
public static final int MEAN = 9;
/** Median flag index */
public static final int MEDIAN = 10;
/** Variance flag index */
public static final int VARIANCE = 11;
/** names of available filters */
public static final String[] availableFeatures
= new String[]{ "Gaussian_blur", "Hessian", "Derivatives", "Laplacian",
"Structure", "Edges", "Difference_of_Gaussian", "Minimum",
"Maximum", "Mean", "Median", "Variance"};
/** flags of filters to be used */
private boolean[] enableFeatures = new boolean[]{
true, /* Gaussian_blur */
true, /* Hessian */
true, /* Derivatives */
true, /* Laplacian */
true, /* Structure */
true, /* Edges */
true, /* Difference of Gaussian */
true, /* Minimum */
true, /* Maximum */
true, /* Mean */
true, /* Median */
true /* Variance */
};
private int minDerivativeOrder = 1;
private int maxDerivativeOrder = 5;
/**
* Construct object to store stack of image features
* @param image original image
*/
public FeatureStack3D(ImagePlus image)
{
width = image.getWidth();
height = image.getHeight();
originalImage = image;
wholeStack = new ArrayList<ImagePlus>();
ImageStack is = new ImageStack ( width, height );
if( image.getType() == ImagePlus.COLOR_RGB)
{
colorFeatures = true;
for(int i=1; i<=image.getImageStackSize(); i++)
is.addSlice("original-slice-" + i, image.getImageStack().getProcessor(i) );
}
else
{
colorFeatures = false;
for(int i=1; i<=image.getImageStackSize(); i++)
is.addSlice("original-slice-" + i, image.getImageStack().getProcessor(i).convertToFloat() );
}
wholeStack.add( new ImagePlus("original", is ) );
}
/**
* Get derivatives features (to be submitted in an ExecutorService)
*
* @param originalImage input image
* @param sigma isotropic smoothing scale
* @param xOrder x-order of differentiation
* @param yOrder y-order of differentiation
* @param zOrder z-order of differentiation
* @return filter image after specific order derivatives
*/
public Callable<ArrayList<ImagePlus>> getDerivatives(
final ImagePlus originalImage,
final double sigma,
final int xOrder,
final int yOrder,
final int zOrder)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList<ImagePlus>>()
{
public ArrayList<ImagePlus> call()
{
// Get channel(s) to process
ImagePlus[] channels = extractChannels(originalImage);
ArrayList<ImagePlus>[] results = new ArrayList[ channels.length ];
for(int ch=0; ch < channels.length; ch++)
{
results[ ch ] = new ArrayList<ImagePlus>();
// pad image on the back and the front
final ImagePlus channel = channels [ ch ].duplicate();
channel.getImageStack().addSlice("pad-back", channels[ch].getImageStack().getProcessor( channels[ ch ].getImageStackSize()));
channel.getImageStack().addSlice("pad-front", channels[ch].getImageStack().getProcessor( 1 ), 1);
imagescience.image.Image img = imagescience.image.Image.wrap( channel );
Aspects aspects = img.aspects();
imagescience.image.Image newimg = new FloatImage(img);
Differentiator diff = new Differentiator();
diff.run(newimg, sigma , xOrder, yOrder, zOrder);
newimg.aspects(aspects);
final ImagePlus ip = newimg.imageplus();
if( xOrder + yOrder + zOrder == 0)
ip.setTitle( availableFeatures[GAUSSIAN] +"_" + sigma );
else
ip.setTitle( availableFeatures[DERIVATIVES] +"_" + xOrder + "_" +yOrder+"_"+zOrder+ "_"+sigma );
// remove pad
ip.getImageStack().deleteLastSlice();
ip.getImageStack().deleteSlice(1);
results[ch].add( ip );
}
return mergeResultChannels(results);
}
};
}
/**
* Get difference of Gaussian features (to be submitted in an ExecutorService)
*
* @param originalImage input image
* @param sigma1 sigma of the smaller Gausian
* @param sigma2 sigma of the larger Gausian
* @return filter image after specific order derivatives
*/
public Callable<ArrayList<ImagePlus>> getDoG(
final ImagePlus originalImage,
final double sigma1,
final double sigma2)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList<ImagePlus>>()
{
public ArrayList<ImagePlus> call()
{
// Get channel(s) to process
ImagePlus[] channels = extractChannels(originalImage);
ArrayList<ImagePlus>[] results = new ArrayList[ channels.length ];
for(int ch=0; ch < channels.length; ch++)
{
results[ ch ] = new ArrayList<ImagePlus>();
// pad image on the back and the front
final ImagePlus channel = channels [ ch ].duplicate();
channel.getImageStack().addSlice("pad-back", channels[ch].getImageStack().getProcessor( channels[ ch ].getImageStackSize()));
channel.getImageStack().addSlice("pad-front", channels[ch].getImageStack().getProcessor( 1 ), 1);
imagescience.image.Image img = imagescience.image.Image.wrap( channel );
Aspects aspects = img.aspects();
imagescience.image.Image newimg = new FloatImage(img);
imagescience.image.Image newimg2 = new FloatImage(img);
Differentiator diff = new Differentiator();
diff.run(newimg, sigma1 , 0, 0, 0);
diff.run(newimg2, sigma2 , 0, 0, 0);
newimg.aspects(aspects);
newimg2.aspects(aspects);
final ImagePlus ip = newimg.imageplus();
final ImagePlus ip2 = newimg2.imageplus();
ImageCalculator ic = new ImageCalculator();
final ImagePlus res = ic.run("Difference create stack", ip2, ip );
res.setTitle( availableFeatures[ DOG ] +"_" + sigma1 + "_" + sigma2 );
// remove pad
res.getImageStack().deleteLastSlice();
res.getImageStack().deleteSlice(1);
results[ch].add( res );
}
return mergeResultChannels(results);
}
};
}
/**
* Get Hessian features (to be submitted in an ExecutorService)
*
* @param originalImage input image
* @param sigma isotropic smoothing scale
* @return filter Hessian filter images
*/
public Callable< ArrayList<ImagePlus> >getHessian(
final ImagePlus originalImage,
final double sigma,
final boolean absolute)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable <ArrayList <ImagePlus> >()
{
public ArrayList< ImagePlus >call()
{
// Get channel(s) to process
ImagePlus[] channels = extractChannels(originalImage);
ArrayList<ImagePlus>[] results = new ArrayList[ channels.length ];
for(int ch=0; ch < channels.length; ch++)
{
results[ ch ] = new ArrayList<ImagePlus>();
// pad image on the back and the front
final ImagePlus channel = channels [ ch ].duplicate();
channel.getImageStack().addSlice("pad-back", channels[ch].getImageStack().getProcessor( channels[ ch ].getImageStackSize()));
channel.getImageStack().addSlice("pad-front", channels[ch].getImageStack().getProcessor( 1 ), 1);
imagescience.image.Image img = imagescience.image.Image.wrap( channel );
final Aspects aspects = img.aspects();
imagescience.image.Image newimg = new FloatImage( img );
final Hessian hessian = new Hessian();
final Vector<imagescience.image.Image> hessianImages = hessian.run(newimg, sigma, absolute);
final int nrimgs = hessianImages.size();
for (int i=0; i<nrimgs; ++i)
hessianImages.get(i).aspects(aspects);
final ImageStack smallest = hessianImages.get(0).imageplus().getImageStack();
final ImageStack middle = hessianImages.get(1).imageplus().getImageStack();
final ImageStack largest = hessianImages.get(2).imageplus().getImageStack();
// remove pad
smallest.deleteLastSlice();
smallest.deleteSlice(1);
middle.deleteLastSlice();
middle.deleteSlice(1);
largest.deleteLastSlice();
largest.deleteSlice(1);
results[ ch ].add( new ImagePlus( availableFeatures[HESSIAN] +"_largest_" + sigma + "_" + absolute, smallest ) );
results[ ch ].add( new ImagePlus( availableFeatures[HESSIAN] +"_middle_" + sigma + "_" + absolute, middle ) );
results[ ch ].add( new ImagePlus( availableFeatures[HESSIAN] +"_smallest_" + sigma + "_" + absolute, largest ) );
}
return mergeResultChannels(results);
}
};
}
/**
* Get Laplacian features (to be submitted in an ExecutorService)
*
* @param originalImage input image
* @param sigma isotropic smoothing scale
* @return filter Laplacian filter image
*/
public Callable<ArrayList< ImagePlus >> getLaplacian(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
// Get channel(s) to process
ImagePlus[] channels = extractChannels(originalImage);
ArrayList<ImagePlus>[] results = new ArrayList[ channels.length ];
for(int ch=0; ch < channels.length; ch++)
{
results[ ch ] = new ArrayList<ImagePlus>();
// pad image on the back and the front
final ImagePlus channel = channels [ ch ].duplicate();
channel.getImageStack().addSlice("pad-back", channels[ch].getImageStack().getProcessor( channels[ ch ].getImageStackSize()));
channel.getImageStack().addSlice("pad-front", channels[ch].getImageStack().getProcessor( 1 ), 1);
imagescience.image.Image img = imagescience.image.Image.wrap( channel );
final Aspects aspects = img.aspects();
imagescience.image.Image newimg = new FloatImage( img );
final Laplacian laplace = new Laplacian();
newimg = laplace.run(newimg, sigma);
newimg.aspects(aspects);
final ImagePlus ip = newimg.imageplus();
ip.setTitle(availableFeatures[LAPLACIAN] +"_" + sigma );
// remove pad
ip.getImageStack().deleteLastSlice();
ip.getImageStack().deleteSlice(1);
results[ch].add( ip );
}
return mergeResultChannels(results);
}
};
}
/**
* Get Edges features (to be submitted in an ExecutorService)
*
* @param originalImage input image
* @param sigma isotropic smoothing scale
* @return filter Edges filter image
*/
public Callable<ArrayList< ImagePlus >> getEdges(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
// Get channel(s) to process
ImagePlus[] channels = extractChannels(originalImage);
ArrayList<ImagePlus>[] results = new ArrayList[ channels.length ];
for(int ch=0; ch < channels.length; ch++)
{
results[ ch ] = new ArrayList<ImagePlus>();
// pad image on the back and the front
final ImagePlus channel = channels [ ch ].duplicate();
channel.getImageStack().addSlice("pad-back", channels[ch].getImageStack().getProcessor( channels[ ch ].getImageStackSize()));
channel.getImageStack().addSlice("pad-front", channels[ch].getImageStack().getProcessor( 1 ), 1);
imagescience.image.Image img = imagescience.image.Image.wrap( channel );
final Aspects aspects = img.aspects();
imagescience.image.Image newimg = new FloatImage( img );
final Edges edges = new Edges();
newimg = edges.run(newimg, sigma, false);
newimg.aspects(aspects);
final ImagePlus ip = newimg.imageplus();
ip.setTitle(availableFeatures[EDGES] +"_" + sigma );
// remove pad
ip.getImageStack().deleteLastSlice();
ip.getImageStack().deleteSlice(1);
results[ch].add( ip );
}
return mergeResultChannels(results);
}
};
}
/**
* Get Minimum features (to be submitted to an ExecutorService)
*
* @param originalImage input image
* @param sigma filter radius
* @return filter Minimum filter image
*/
public Callable<ArrayList< ImagePlus >> getMinimum(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
ImagePlus im = originalImage;
if( originalImage.getImageStack().isRGB() == false )
{
im = originalImage.duplicate();
IJ.run( im, "32-bit", "");
}
ArrayList<ImagePlus> result = new ArrayList();
final ImageStack is = Filters3D.filter(im.getImageStack(),Filters3D.MIN, (float)sigma, (float)sigma, (float)sigma);
final ImagePlus ip = new ImagePlus( availableFeatures[ MINIMUM ] +"_" + sigma, is );
result.add( ip );
return result;
}
};
}
/**
* Get Maximum features (to be submitted to an ExecutorService)
*
* @param originalImage input image
* @param sigma filter radius
* @return filter Maximum filter image
*/
public Callable<ArrayList< ImagePlus >> getMaximum(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
ImagePlus im = originalImage;
if( originalImage.getImageStack().isRGB() == false )
{
im = originalImage.duplicate();
IJ.run( im, "32-bit", "");
}
ArrayList<ImagePlus> result = new ArrayList();
final ImageStack is = Filters3D.filter(im.getImageStack(), Filters3D.MAX, (float)sigma, (float)sigma, (float)sigma);
final ImagePlus ip = new ImagePlus( availableFeatures[ MAXIMUM ] +"_" + sigma, is );
result.add( ip );
return result;
}
};
}
/**
* Get Mean features (to be submitted to an ExecutorService)
*
* @param originalImage input image
* @param sigma filter radius
* @return filter Mean filter image
*/
public Callable<ArrayList< ImagePlus >> getMean(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
ImagePlus im = originalImage;
if( originalImage.getImageStack().isRGB() == false )
{
im = originalImage.duplicate();
IJ.run( im, "32-bit", "");
}
ArrayList<ImagePlus> result = new ArrayList();
final ImageStack is = Filters3D.filter(im.getImageStack(), Filters3D.MEAN, (float)sigma, (float)sigma, (float)sigma);
final ImagePlus ip = new ImagePlus( availableFeatures[ MEAN ] +"_" + sigma, is );
result.add( ip );
return result;
}
};
}
/**
* Get Median features (to be submitted to an ExecutorService)
*
* @param originalImage input image
* @param sigma filter radius
* @return filter Median filter image
*/
public Callable<ArrayList< ImagePlus >> getMedian(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
ImagePlus im = originalImage;
if( originalImage.getImageStack().isRGB() == false )
{
im = originalImage.duplicate();
IJ.run( im, "32-bit", "");
}
ArrayList<ImagePlus> result = new ArrayList();
final ImageStack is = Filters3D.filter(im.getImageStack(), Filters3D.MEDIAN, (float)sigma, (float)sigma, (float)sigma);
final ImagePlus ip = new ImagePlus( availableFeatures[ MEDIAN ] +"_" + sigma, is );
result.add( ip );
return result;
}
};
}
/**
* Get Variance features (to be submitted to an ExecutorService)
*
* @param originalImage input image
* @param sigma filter radius
* @return filter Variance filter image
*/
public Callable<ArrayList< ImagePlus >> getVariance(
final ImagePlus originalImage,
final double sigma)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
ImagePlus im = originalImage;
if( originalImage.getImageStack().isRGB() == false )
{
im = originalImage.duplicate();
IJ.run( im, "32-bit", "");
}
ArrayList<ImagePlus> result = new ArrayList();
final ImageStack is = Filters3D.filter(im.getImageStack(), Filters3D.VAR, (float)sigma, (float)sigma, (float)sigma);
final ImagePlus ip = new ImagePlus( availableFeatures[ VARIANCE ] +"_" + sigma, is );
result.add( ip );
return result;
}
};
}
/**
* Get structure tensor features (to be submitted in an ExecutorService).
* It computes, for all pixels in the input image, the eigenvalues of the so-called structure tensor.
*
* @param originalImage input image
* @param sigma isotropic smoothing scale
* @param integrationScale integration scale (standard deviation of the Gaussian
* kernel used for smoothing the elements of the structure tensor, must be larger than zero)
* @return filter structure tensor filter image
*/
public Callable<ArrayList< ImagePlus >> getStructure(
final ImagePlus originalImage,
final double sigma,
final double integrationScale)
{
if (Thread.currentThread().isInterrupted())
return null;
return new Callable<ArrayList< ImagePlus >>()
{
public ArrayList< ImagePlus > call()
{
// Get channel(s) to process
ImagePlus[] channels = extractChannels(originalImage);
ArrayList<ImagePlus>[] results = new ArrayList[ channels.length ];
for(int ch=0; ch < channels.length; ch++)
{
results[ ch ] = new ArrayList<ImagePlus>();
// pad image on the back and the front
final ImagePlus channel = channels [ ch ].duplicate();
channel.getImageStack().addSlice("pad-back", channels[ch].getImageStack().getProcessor( channels[ ch ].getImageStackSize()));
channel.getImageStack().addSlice("pad-front", channels[ch].getImageStack().getProcessor( 1 ), 1);
imagescience.image.Image img = imagescience.image.Image.wrap( channel );
final Aspects aspects = img.aspects();
final Structure structure = new Structure();
final Vector<imagescience.image.Image> eigenimages = structure.run(new FloatImage(img), sigma, integrationScale);
final int nrimgs = eigenimages.size();
for (int i=0; i<nrimgs; ++i)
eigenimages.get(i).aspects(aspects);
final ImageStack largest = eigenimages.get(0).imageplus().getImageStack();
final ImageStack smallest = eigenimages.get(1).imageplus().getImageStack();
// remove pad
smallest.deleteLastSlice();
smallest.deleteSlice(1);
largest.deleteLastSlice();
largest.deleteSlice(1);
results[ ch ].add( new ImagePlus( availableFeatures[STRUCTURE] +"_largest_" + sigma + "_" + integrationScale, largest ) );
results[ ch ].add( new ImagePlus( availableFeatures[STRUCTURE] +"_smallest_" + sigma + "_" + integrationScale, smallest ) );
}
return mergeResultChannels(results);
}
};
}
/**
* Merge input channels if they are more than 1
* @param channels results channels
* @return result image
*/
ArrayList< ImagePlus > mergeResultChannels(final ArrayList<ImagePlus>[] channels)
{
if(channels.length > 1)
{
ArrayList< ImagePlus > mergedList = new ArrayList<ImagePlus> ();
for(int i=0; i<channels[0].size(); i++)
{
ImageStack mergedColorStack = mergeStacks(channels[0].get(i).getImageStack(), channels[1].get(i).getImageStack(), channels[2].get(i).getImageStack());
ImagePlus merged = new ImagePlus(channels[0].get(i).getTitle(), mergedColorStack);
for(int n = 1; n <= merged.getImageStackSize(); n++)
merged.getImageStack().setSliceLabel(channels[0].get(i).getImageStack().getSliceLabel(n), n);
mergedList.add( merged );
}
return mergedList;
}
else
return channels[0];
}
/**
* Merge three image stack into a color stack (no scaling)
*
* @param redChannel image stack representing the red channel
* @param greenChannel image stack representing the green channel
* @param blueChannel image stack representing the blue channel
* @return RGB merged stack
*/
ImageStack mergeStacks(ImageStack redChannel, ImageStack greenChannel, ImageStack blueChannel)
{
final ImageStack colorStack = new ImageStack( redChannel.getWidth(), redChannel.getHeight());
for(int n=1; n<=redChannel.getSize(); n++)
{
final ByteProcessor red = (ByteProcessor) redChannel.getProcessor(n).convertToByte(false);
final ByteProcessor green = (ByteProcessor) greenChannel.getProcessor(n).convertToByte(false);
final ByteProcessor blue = (ByteProcessor) blueChannel.getProcessor(n).convertToByte(false);
final ColorProcessor cp = new ColorProcessor(redChannel.getWidth(), redChannel.getHeight());
cp.setRGB((byte[]) red.getPixels(), (byte[]) green.getPixels(), (byte[]) blue.getPixels() );
colorStack.addSlice(redChannel.getSliceLabel(n), cp);
}
return colorStack;
}
/**
* Extract channels from input image if it is RGB
* @param originalImage input image
* @return array of channels
*/
ImagePlus[] extractChannels(final ImagePlus originalImage)
{
final int width = originalImage.getWidth();
final int height = originalImage.getHeight();
ImagePlus[] channels;
if( originalImage.getType() == ImagePlus.COLOR_RGB )
{
final ImageStack isRed = new ImageStack ( width, height );
final ImageStack isGreen = new ImageStack ( width, height );
final ImageStack isBlue = new ImageStack ( width, height );
for(int n = 1; n<= originalImage.getImageStackSize(); n++)
{
final ByteProcessor redBp = new ByteProcessor(width, height);
final ByteProcessor greenBp = new ByteProcessor(width, height);
final ByteProcessor blueBp = new ByteProcessor(width, height);
final byte[] redPixels = (byte[]) redBp.getPixels();
final byte[] greenPixels = (byte[]) greenBp.getPixels();
final byte[] bluePixels = (byte[]) blueBp.getPixels();
((ColorProcessor)(originalImage.getImageStack().getProcessor( n ).duplicate())).getRGB(redPixels, greenPixels, bluePixels);
isRed.addSlice( null, redBp.convertToFloat() );
isGreen.addSlice( null, greenBp.convertToFloat() );
isBlue.addSlice( null, blueBp.convertToFloat() );
}
channels = new ImagePlus[]{new ImagePlus("red", isRed),
new ImagePlus("green", isGreen),
new ImagePlus("blue", isBlue )};
}
else
{
channels = new ImagePlus[1];
final ImageStack is = new ImageStack ( width, height );
for(int i=1; i<=originalImage.getImageStackSize(); i++)
is.addSlice("original-slice-" + i, originalImage.getImageStack().getProcessor(i).convertToFloat() );
channels[0] = new ImagePlus(originalImage.getTitle(), is );
}
for(int i=0; i<channels.length; i++)
channels[i].setCalibration(originalImage.getCalibration());
return channels;
}
/**
* Update features with current list in a multi-thread fashion
*
* @return true if the features are correctly updated
*/
public boolean updateFeaturesMT()
{
if (Thread.currentThread().isInterrupted() )
return false;
ExecutorService exe = Executors.newFixedThreadPool( Prefs.getThreads() );
wholeStack = new ArrayList<ImagePlus>();
final double pixelWidth = originalImage.getCalibration().pixelWidth;
ImageStack is = new ImageStack ( width, height );
if( colorFeatures )
{
for(int i=1; i<=originalImage.getImageStackSize(); i++)
is.addSlice("original-slice-" + i, originalImage.getImageStack().getProcessor(i) );
}
else
{
for(int i=1; i<=originalImage.getImageStackSize(); i++)
is.addSlice("original-slice-" + i, originalImage.getImageStack().getProcessor(i).convertToFloat() );
}
wholeStack.add( new ImagePlus("original", is ) );
// Count the number of enabled features
int finalIndex = 0;
for(int i=0; i<enableFeatures.length; i++)
if(enableFeatures[i])
finalIndex ++;
final ArrayList< Future < ArrayList<ImagePlus> > > futures = new ArrayList< Future<ArrayList<ImagePlus>> >();
//int n=0;
int currentIndex = 0;
IJ.showStatus("Updating features...");
try{
for (float i=minimumSigma; i<= maximumSigma; i *=2)
{
double scaledSigma = i * pixelWidth;
if (Thread.currentThread().isInterrupted())
return false;
// Gaussian blur
if(enableFeatures[GAUSSIAN])
{
//IJ.log( n++ +": Calculating Gaussian filter ("+ i + ")");
futures.add(exe.submit( getDerivatives(originalImage, scaledSigma, 0, 0, 0)) );
}
// Difference of Gaussian
if(enableFeatures[ DOG ])
{
for (float j=minimumSigma; j<i; j*=2)
{
//IJ.log( n++ +": Calculating DoG filter ("+ i + ", " + j + ")");
futures.add(exe.submit( getDoG( originalImage, scaledSigma, j * pixelWidth) ) );
}
}
// Hessian
if(enableFeatures[HESSIAN])
{
//IJ.log("Calculating Hessian filter ("+ i + ")");
futures.add(exe.submit( getHessian(originalImage, scaledSigma, true)) );
}
// Derivatives
if(enableFeatures[DERIVATIVES])
{
for(int order = minDerivativeOrder; order<=maxDerivativeOrder; order++)
futures.add(exe.submit( getDerivatives(originalImage, scaledSigma, order, order, order)) );
}
// Laplacian
if(enableFeatures[LAPLACIAN])
{
futures.add(exe.submit( getLaplacian(originalImage, scaledSigma)) );
}
// Edges
if(enableFeatures[ EDGES ])
{
futures.add(exe.submit( getEdges(originalImage, scaledSigma)) );
}
// Structure tensor
if(enableFeatures[ STRUCTURE ])
{
for(int integrationScale = 1; integrationScale <= 3; integrationScale+=2)
futures.add(exe.submit( getStructure(originalImage, scaledSigma, integrationScale )) );
}
// Maximum
if(enableFeatures[ MINIMUM ])
{
futures.add(exe.submit( getMinimum(originalImage, i)) );
}
// Maxmimum
if(enableFeatures[ MAXIMUM ])
{
futures.add(exe.submit( getMaximum(originalImage, i)) );
}
// Mean
if(enableFeatures[ MEAN ])
{
futures.add(exe.submit( getMean(originalImage, i)) );
}
// Median
if(enableFeatures[ MEDIAN ])
{
futures.add(exe.submit( getMedian(originalImage, i)) );
}
// Variance
if(enableFeatures[ VARIANCE ])
{
futures.add(exe.submit( getVariance(originalImage, i)) );
}
}
// Wait for the jobs to be done
for(Future<ArrayList<ImagePlus>> f : futures)
{
final ArrayList<ImagePlus> res = f.get();
currentIndex ++;
IJ.showStatus("Updating features...");
IJ.showProgress(currentIndex, finalIndex);
for( final ImagePlus ip : res)
this.wholeStack.add( ip );
}
}
catch(InterruptedException ie)
{
IJ.log("The features udpate was interrupted by the user.");
return false;
}
catch(Exception ex)
{
IJ.log("Error when updating feature stack.");
ex.printStackTrace();
return false;
}
finally{
exe.shutdownNow();
}
IJ.showProgress(1.0);
IJ.showStatus("Features stack is updated now!");
return true;
}
/**
* Convert FeatureStack3D into a feature stack array (for 2D stacks). Experimental.
* @return
*/
public FeatureStackArray getFeatureStackArray()
{
// create empty feature stack array, with space for one stack per slice in the original image
FeatureStackArray fsa = new FeatureStackArray( originalImage.getImageStackSize(), minimumSigma, maximumSigma, false, 0, 0, null);
// Initialize each feature stack (one per slice)
for(int i=0; i<originalImage.getImageStackSize(); i++)
{
FeatureStack fs = new FeatureStack( width, height, colorFeatures );
fsa.set(fs, i);
}
// now, read current 3D features and add them to the 2D feature stacks
for( final ImagePlus ip : wholeStack)
{
//IJ.log(" Adding feature '"+ ip.getTitle() + "' from 3D stack to feature stack array... ");
for(int n=1; n<=ip.getImageStackSize(); n++)
fsa.get(n-1).getStack().addSlice(ip.getTitle(), ip.getImageStack().getProcessor(n));
}
return fsa;
}
public void setMinimumSigma( float minimumSigma )
{
this.minimumSigma = minimumSigma;
}
public void setMaximumSigma( float maximumSigma )
{
this.maximumSigma = maximumSigma;
}
}
| 30.162747 | 154 | 0.661417 |
575554f7b7c721534560ffb5b3a7c08ab2af303c | 1,280 | package com.redescooter.ses.api.common.exception;
public class BaseException extends RuntimeException {
public static final String DEFAULE_ERRORCODE = "1";
public static final String DEFAULT_ERRORMSG = "unknown error";
private String errorCode = DEFAULE_ERRORCODE;
private String errorMessage;
private boolean i18nTranslated = false;
public BaseException(String errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public BaseException(String errorCode, String errorMessage, Throwable t) {
super(errorMessage, t);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public String getErrorCode() {
return this.errorCode;
}
public String getErrorMessage() {
return this.errorMessage;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public boolean isI18nTranslated() {
return i18nTranslated;
}
public void setI18nTranslated(boolean i18nTranslated) {
this.i18nTranslated = i18nTranslated;
}
}
| 23.703704 | 78 | 0.685938 |
42e34b1a69a803a671be6b332b2e5b6735f63a9e | 352 | package com.stevecorp.teaching.spring.beans_tutorial.scenario_07.model;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@Getter
@Builder
@ToString
public class ConnectionProperties {
private final String driverClassName;
private final String url;
private final String username;
private final String password;
}
| 19.555556 | 71 | 0.789773 |
e8940ee674480e95ebddb20a0a4267132ad521e9 | 895 | package oidc.control;
import oidc.saml.DefaultServiceProviderTranslationService;
import oidc.saml.ServiceProviderTranslationService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
public class ServiceProviderTranslatorController {
private ServiceProviderTranslationService translationService = new DefaultServiceProviderTranslationService();
@RequestMapping("/translate-sp-entity-id")
public Map<String, String> translate(@RequestParam String spEntityId) {
Map<String, String> result = new LinkedHashMap<>();
result.put("spEntityId", spEntityId);
result.put("clientId", translationService.translateServiceProviderEntityId(spEntityId));
return result;
}
}
| 34.423077 | 112 | 0.818994 |
4ade3f0dc676df32fdd53d2d6fcdac79d5bbd0df | 1,795 | //
// Este archivo ha sido generado por la arquitectura JavaTM para la implantacin de la referencia de enlace (JAXB) XML v2.2.8-b130911.1802
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perdern si se vuelve a compilar el esquema de origen.
// Generado el: 2015.10.26 a las 05:59:30 PM COT
//
package generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para namedElement complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="namedElement">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "namedElement")
@XmlSeeAlso({
Feature.class,
Parent.class
})
public class NamedElement {
@XmlAttribute(name = "name")
protected String name;
/**
* Obtiene el valor de la propiedad name.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Define el valor de la propiedad name.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
| 25.28169 | 138 | 0.646797 |
8c77d38a8b8abf057ec570625480b3ae2ba31954 | 2,687 | package com.example.madinandroid;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONException;
import static com.example.madinandroid.MainActivity.books;
public class Fragment0 extends Fragment {
RecyclerView recyclerView;
EditText contactSearch;
RecyclerContactAdapter recyclerAdapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d("LifeCycleCheck", "I am in onCreateView in Fragment0");
View view = inflater.inflate(R.layout.fragment0,container,false);
recyclerView = (RecyclerView)view.findViewById(R.id.contactRecyclerView);
contactSearch = (EditText) view.findViewById(R.id.contactSearch);
try { recyclerAdapter = new RecyclerContactAdapter(getActivity(), books);
} catch (JSONException e) { e.printStackTrace(); }
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// attach swiper helper to recycler view
ContactSwiper contactswiper = new ContactSwiper();
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(contactswiper);
itemTouchHelper.attachToRecyclerView(recyclerView);
// editText
contactSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("test","change");
recyclerAdapter.getFilter().filter(charSequence);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
@Override
public void onResume() {
Log.d("LifeCycleCheck", "I am in onResume in Fragment0");
super.onResume();
recyclerAdapter.notifyDataSetChanged();
try {
recyclerAdapter.refresh(books);
} catch (JSONException e) {
e.printStackTrace();
}
}
} | 32.768293 | 132 | 0.695571 |
3d9a5a77b28f255ae0cce1b4ec0d3d41b8b756c1 | 8,193 | /*
* Copyright © 2020 Richard de Jong
*
* 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 office ;
import com4j.*;
@IID("{000C1726-0000-0000-C000-000000000046}")
public interface IMsoTickLabels extends Com4jObject {
// Methods:
/**
* <p>
* Getter method for the COM property "Parent"
* </p>
* @return Returns a value of type com4j.Com4jObject
*/
@DISPID(1610743808) //= 0x60020000. The runtime will prefer the VTID if present
@VTID(7)
@ReturnValue(type=NativeType.Dispatch)
com4j.Com4jObject getParent();
/**
* @return Returns a value of type java.lang.Object
*/
@DISPID(1610743809) //= 0x60020001. The runtime will prefer the VTID if present
@VTID(8)
@ReturnValue(type=NativeType.VARIANT)
java.lang.Object delete();
/**
* <p>
* Getter method for the COM property "Font"
* </p>
* @return Returns a value of type office.ChartFont
*/
@DISPID(1610743810) //= 0x60020002. The runtime will prefer the VTID if present
@VTID(9)
office.ChartFont getFont();
/**
* <p>
* Getter method for the COM property "Name"
* </p>
* @return Returns a value of type java.lang.String
*/
@DISPID(1610743811) //= 0x60020003. The runtime will prefer the VTID if present
@VTID(10)
java.lang.String getName();
/**
* <p>
* Getter method for the COM property "NumberFormat"
* </p>
* @return Returns a value of type java.lang.String
*/
@DISPID(1610743812) //= 0x60020004. The runtime will prefer the VTID if present
@VTID(11)
java.lang.String getNumberFormat();
/**
* <p>
* Setter method for the COM property "NumberFormat"
* </p>
* @param pval Mandatory java.lang.String parameter.
*/
@DISPID(1610743812) //= 0x60020004. The runtime will prefer the VTID if present
@VTID(12)
void setNumberFormat(
java.lang.String pval);
/**
* <p>
* Getter method for the COM property "NumberFormatLinked"
* </p>
* @return Returns a value of type boolean
*/
@DISPID(1610743814) //= 0x60020006. The runtime will prefer the VTID if present
@VTID(13)
boolean getNumberFormatLinked();
/**
* <p>
* Setter method for the COM property "NumberFormatLinked"
* </p>
* @param pval Mandatory boolean parameter.
*/
@DISPID(1610743814) //= 0x60020006. The runtime will prefer the VTID if present
@VTID(14)
void setNumberFormatLinked(
boolean pval);
/**
* <p>
* Getter method for the COM property "NumberFormatLocal"
* </p>
* @return Returns a value of type java.lang.Object
*/
@DISPID(1610743816) //= 0x60020008. The runtime will prefer the VTID if present
@VTID(15)
@ReturnValue(type=NativeType.VARIANT)
java.lang.Object getNumberFormatLocal();
/**
* <p>
* Setter method for the COM property "NumberFormatLocal"
* </p>
* @param pval Mandatory java.lang.Object parameter.
*/
@DISPID(1610743816) //= 0x60020008. The runtime will prefer the VTID if present
@VTID(16)
void setNumberFormatLocal(
@MarshalAs(NativeType.VARIANT) java.lang.Object pval);
/**
* <p>
* Getter method for the COM property "Orientation"
* </p>
* @return Returns a value of type office.XlTickLabelOrientation
*/
@DISPID(1610743818) //= 0x6002000a. The runtime will prefer the VTID if present
@VTID(17)
office.XlTickLabelOrientation getOrientation();
/**
* <p>
* Setter method for the COM property "Orientation"
* </p>
* @param pval Mandatory office.XlTickLabelOrientation parameter.
*/
@DISPID(1610743818) //= 0x6002000a. The runtime will prefer the VTID if present
@VTID(18)
void setOrientation(
office.XlTickLabelOrientation pval);
/**
* @return Returns a value of type java.lang.Object
*/
@DISPID(1610743820) //= 0x6002000c. The runtime will prefer the VTID if present
@VTID(19)
@ReturnValue(type=NativeType.VARIANT)
java.lang.Object select();
/**
* <p>
* Getter method for the COM property "ReadingOrder"
* </p>
* @return Returns a value of type int
*/
@DISPID(1610743821) //= 0x6002000d. The runtime will prefer the VTID if present
@VTID(20)
int getReadingOrder();
/**
* <p>
* Setter method for the COM property "ReadingOrder"
* </p>
* @param pval Mandatory int parameter.
*/
@DISPID(1610743821) //= 0x6002000d. The runtime will prefer the VTID if present
@VTID(21)
void setReadingOrder(
int pval);
/**
* <p>
* Getter method for the COM property "AutoScaleFont"
* </p>
* @return Returns a value of type java.lang.Object
*/
@DISPID(1610743823) //= 0x6002000f. The runtime will prefer the VTID if present
@VTID(22)
@ReturnValue(type=NativeType.VARIANT)
java.lang.Object getAutoScaleFont();
/**
* <p>
* Setter method for the COM property "AutoScaleFont"
* </p>
* @param pval Mandatory java.lang.Object parameter.
*/
@DISPID(1610743823) //= 0x6002000f. The runtime will prefer the VTID if present
@VTID(23)
void setAutoScaleFont(
@MarshalAs(NativeType.VARIANT) java.lang.Object pval);
/**
* <p>
* Getter method for the COM property "Depth"
* </p>
* @return Returns a value of type int
*/
@DISPID(1610743825) //= 0x60020011. The runtime will prefer the VTID if present
@VTID(24)
int getDepth();
/**
* <p>
* Getter method for the COM property "Offset"
* </p>
* @return Returns a value of type int
*/
@DISPID(1610743826) //= 0x60020012. The runtime will prefer the VTID if present
@VTID(25)
int getOffset();
/**
* <p>
* Setter method for the COM property "Offset"
* </p>
* @param pval Mandatory int parameter.
*/
@DISPID(1610743826) //= 0x60020012. The runtime will prefer the VTID if present
@VTID(26)
void setOffset(
int pval);
/**
* <p>
* Getter method for the COM property "Alignment"
* </p>
* @return Returns a value of type int
*/
@DISPID(1610743828) //= 0x60020014. The runtime will prefer the VTID if present
@VTID(27)
int getAlignment();
/**
* <p>
* Setter method for the COM property "Alignment"
* </p>
* @param pval Mandatory int parameter.
*/
@DISPID(1610743828) //= 0x60020014. The runtime will prefer the VTID if present
@VTID(28)
void setAlignment(
int pval);
/**
* <p>
* Getter method for the COM property "MultiLevel"
* </p>
* @return Returns a value of type boolean
*/
@DISPID(1610743830) //= 0x60020016. The runtime will prefer the VTID if present
@VTID(29)
boolean getMultiLevel();
/**
* <p>
* Setter method for the COM property "MultiLevel"
* </p>
* @param pval Mandatory boolean parameter.
*/
@DISPID(1610743830) //= 0x60020016. The runtime will prefer the VTID if present
@VTID(30)
void setMultiLevel(
boolean pval);
/**
* <p>
* Getter method for the COM property "Format"
* </p>
* @return Returns a value of type office.IMsoChartFormat
*/
@DISPID(1610743832) //= 0x60020018. The runtime will prefer the VTID if present
@VTID(31)
office.IMsoChartFormat getFormat();
/**
* <p>
* Getter method for the COM property "Application"
* </p>
* @return Returns a value of type com4j.Com4jObject
*/
@DISPID(148) //= 0x94. The runtime will prefer the VTID if present
@VTID(32)
@ReturnValue(type=NativeType.Dispatch)
com4j.Com4jObject getApplication();
/**
* <p>
* Getter method for the COM property "Creator"
* </p>
* @return Returns a value of type int
*/
@DISPID(149) //= 0x95. The runtime will prefer the VTID if present
@VTID(33)
int getCreator();
// Properties:
}
| 22.821727 | 81 | 0.655071 |
79e4fa224ab03c434394e9da473c35d07aaa3ca4 | 1,264 | package com.github.trho.reproducer;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.ext.cluster.infinispan.InfinispanClusterManager;
import org.infinispan.manager.DefaultCacheManager;
/**
* User: Tobias Rho
* Date: 10.12.20
* Time: 10:28
*/
public class Main {
public static void main(String... args) {
ClusterManager mgr = null;
try {
// Hazelcast configuration
// Config hazelcastConfig = new Config();
// hazelcastConfig.setClusterName("local-hazelcast-cluster");
// mgr = new HazelcastClusterManager(hazelcastConfig);
// vertx4
mgr = new InfinispanClusterManager(new DefaultCacheManager("infinispan-default.xml"));
// vertx3
// mgr = new InfinispanClusterManager(new DefaultCacheManager("infinispan-default-vertx-3.xml"));
} catch (Exception e) {
e.printStackTrace();
}
VertxOptions options = new VertxOptions().setClusterManager(mgr);
Vertx.clusteredVertx(options, res -> {
if (res.succeeded()) {
Vertx vertx = res.result();
for (int i = 0; i < 8; i++) {
vertx.deployVerticle(new MainVerticle());
}
} else {
// failed!
}
});
}
}
| 26.893617 | 102 | 0.65981 |
3b9a8da3fa4667123b93f42da2fba4ed1d32a7b4 | 2,935 | /*
* Copyright 2021 Vaibhav Nargwani
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.vpg.bot.commands.manager;
import net.dv8tion.jda.api.EmbedBuilder;
import net.vpg.bot.commands.BotCommandImpl;
import net.vpg.bot.core.Bot;
import net.vpg.bot.event.SlashCommandReceivedEvent;
import net.vpg.bot.event.TextCommandReceivedEvent;
import net.vpg.bot.player.PlayerManager;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class QuizCommand extends BotCommandImpl implements ManagerCommand {
Map<Long, Integer> scores = new HashMap<>();
public QuizCommand(Bot bot) {
super(bot, "quiz", "quiz");
}
@Override
public void onTextCommandRun(TextCommandReceivedEvent e) {
switch (e.getArg(0)) {
case "start":
PlayerManager.getPlayer(e).setQuizHostId(e.getUser().getIdLong());
e.send("Starting quiz with host " + e.getUser().getAsMention()).queue();
break;
case "end":
PlayerManager.getPlayer(e).setQuizHostId(0);
e.send("Starting quiz with host " + e.getUser().getAsMention()).queue();
break;
case "update":
long id = e.getMessage().getMentionedUsers().get(0).getIdLong();
Integer oldScore = scores.getOrDefault(id, 0);
scores.put(id, oldScore + 1);
e.send("Updated " + e.getJDA().getUserById(id).getName() + "'s score to " + (oldScore + 1)).queue();
case "scores":
AtomicInteger i = new AtomicInteger();
e.sendEmbeds(new EmbedBuilder()
.setDescription(scores.entrySet()
.stream()
.sorted(Comparator.comparingInt(Map.Entry::getValue))
.map(score -> i.incrementAndGet() + ". <@" + score.getKey() + "> - " + score.getValue() + " points")
.collect(Collectors.joining("\n")))
.build()).queue();
break;
case "clear":
scores.clear();
e.send("Cleared scores").queue();
break;
}
}
@Override
public void onSlashCommandRun(SlashCommandReceivedEvent e) {
e.send("Nope.").queue();
}
} | 39.133333 | 124 | 0.608518 |
dbb3ac86132d49d6e88969b0dcbf6357125c0451 | 4,508 | /*
* Copyright {2017} {Shudipto Trafder}
*
* 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.blogspot.shudiptotrafder.soilscience;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.blogspot.shudiptotrafder.soilscience.theme.ThemeUtils;
public class DeveloperActivity extends AppCompatActivity {
//to support vector drawables for lower api
static {
//complete add vector drawable support
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeUtils.initialize(this);
setContentView(R.layout.activity_developer);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView fb = findViewById(R.id.dev_fb);
TextView linkedin = findViewById(R.id.dev_linkedin);
TextView git = findViewById(R.id.dev_git);
TextView email = findViewById(R.id.dev_email);
fb.setOnClickListener(view -> customTab("https://www.facebook.com/Iamsdt"));
linkedin.setOnClickListener(view -> customTab("https://www.linkedin.com/in/shudipto-trafder-b041a97a/"));
git.setOnClickListener(view -> customTab("https://github.com/Iamsdt"));
email.setOnClickListener(view -> {
try{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("email"));
String[] s = {"[email protected]"};
intent.putExtra(Intent.EXTRA_EMAIL,s);
intent.putExtra(Intent.EXTRA_SUBJECT,"Email from soil science app");
intent.putExtra(Intent.EXTRA_TEXT,"feedback:");
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent,"Send email with..."));
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this,"No email app found",Toast.LENGTH_SHORT).show();
}
});
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
private void customTab(String url){
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setToolbarColor(R.attr.colorPrimary);
builder.setShowTitle(false);
// add share action to menu list
builder.addDefaultShareMenuItem();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//buy calling android.R.id.home
int id = item.getItemId();
if (id == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
//left in this project
// complete: 6/7/2017 add theme change option
// complete: 6/7/2017 add search view
// complete: 6/7/2017 add voice search view
// complete: 6/7/2017 add random search view
// complete: 6/7/2017 add app intro
// TODO: 6/7/2017 add item animator
//advance
//complete fill developer with animation
//database
// complete: 6/16/2017 Firebase database
// complete: 6/16/2017 user add word will be real time database
// complete: 6/16/2017 favourite swap will show a dialog
// complete: 6/16/2017 night mode move from settings to navigation drawer
// complete: 8/4/2017 if user open this app for first time then show a import dialog
// complete: 8/4/2017 Create a file import chooser dialog
}
| 34.151515 | 113 | 0.675466 |
00f043789f8752952b9c9cc87c234cc3af370bf8 | 1,880 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package sun.util.locale.provider;
import java.util.Locale;
import java.util.Set;
import sun.text.spi.JavaTimeDateTimePatternProvider;
/**
* Concrete implementation of the {@link JavaTimeDateTimePatternProvider
* } class for the JRE LocaleProviderAdapter.
*
*/
public class JavaTimeDateTimePatternImpl extends JavaTimeDateTimePatternProvider implements AvailableLanguageTags {
private final LocaleProviderAdapter.Type type;
private final Set<String> langtags;
public JavaTimeDateTimePatternImpl(LocaleProviderAdapter.Type type, Set<String> langtags) {
this.type = type;
this.langtags = langtags;
}
/**
* Returns an array of all locales for which this locale service provider
* can provide localized objects or names.
*
* @return An array of all locales for which this locale service provider
* can provide localized objects or names.
*/
@Override
public Locale[] getAvailableLocales() {
return LocaleProviderAdapter.toLocaleArray(langtags);
}
@Override
public boolean isSupportedLocale(Locale locale) {
return LocaleProviderAdapter.forType(type).isSupportedProviderLocale(locale, langtags);
}
@Override
public String getJavaTimeDateTimePattern(int timeStyle, int dateStyle, String calType, Locale locale) {
LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale);
String pattern = lr.getJavaTimeDateTimePattern(
timeStyle, dateStyle, calType);
return pattern;
}
@Override
public Set<String> getAvailableLanguageTags() {
return langtags;
}
}
| 24.415584 | 115 | 0.703723 |
9f2e16d85295226b4d5bcdf74c4be24905d03c55 | 897 | package imc.utilities;
public class TypeUtils {
/**
* returns the base type of the given type
*
* <ul>
* <li>simple types are returned without length or precission
* <li>in case of structs or dation the value is STRUCT or DATION
* </ul>
*
* @param openPearlType the type as specified in the xml input file
* @return return only the short form of the type like FIXED instead of FIXED(15)
*/
public static String shortType(String openPearlType) {
return openPearlType;
}
/**
* return the fill type info
*
* <ul>
* <li>simple types are returned with length or precission
* <li>in case of structs the value is STRUCT with all components
* </ul>
*
* @param openPearlType
* @return the complete type information with precision; STRUCTs are completely unrolled
*/
public static String longType(String openPearlType) {
return openPearlType;
}
}
| 24.916667 | 89 | 0.701226 |
d999a2e85d3d8fe90d9f98755c1bca29286edb40 | 8,627 | package org.sahagin.share.srctree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.sahagin.runlib.external.CaptureStyle;
import org.sahagin.share.srctree.code.CodeLine;
import org.sahagin.share.yaml.YamlUtils;
import org.sahagin.share.yaml.YamlConvertException;
import org.sahagin.share.yaml.YamlConvertible;
public class TestMethod extends ASTData implements YamlConvertible {
private String testClassKey;
private TestClass testClass;
private String key;
private String simpleName;
private String testDoc;
private CaptureStyle captureStyle = CaptureStyle.getDefault();
private List<String> argVariables = new ArrayList<>(4);
private int variableLengthArgIndex = -1;
private List<CodeLine> codeBody = new ArrayList<>(32);
public String getTestClassKey() {
return testClassKey;
}
public void setTestClassKey(String testClassKey) {
this.testClassKey = testClassKey;
}
public TestClass getTestClass() {
return testClass;
}
public void setTestClass(TestClass testClass) {
this.testClass = testClass;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public static String argClassQualifiedNamesToArgClassesStr(
List<String> argClassQualifiedNames) {
if (argClassQualifiedNames.size() == 0) {
return "void";
} else {
String result = "";
for (int i = 0; i < argClassQualifiedNames.size(); i++) {
String argClassQualifiedName = argClassQualifiedNames.get(i);
if (i != 0) {
result = result + ",";
}
if (StringUtils.equals(argClassQualifiedName, String.class.getCanonicalName())) {
result = result + String.class.getSimpleName();
} else if (StringUtils.equals(argClassQualifiedName, String[].class.getCanonicalName())) {
result = result + String[].class.getSimpleName();
} else if (StringUtils.equals(argClassQualifiedName, String[][].class.getCanonicalName())) {
result = result + String[][].class.getSimpleName();
} else if (StringUtils.equals(argClassQualifiedName, Object.class.getCanonicalName())) {
result = result + Object.class.getSimpleName();
} else if (StringUtils.equals(argClassQualifiedName, Object[].class.getCanonicalName())) {
result = result + Object[].class.getSimpleName();
} else if (StringUtils.equals(argClassQualifiedName, Object[][].class.getCanonicalName())) {
result = result + Object[][].class.getSimpleName();
} else {
result = result + argClassQualifiedName;
}
}
return result;
}
}
// null argClassesStr means no information,
private static String generateMethodKeySub(String classQualifiedName,
String methodSimpleName, String argClassesStr) {
if (methodSimpleName == null) {
throw new NullPointerException();
}
String result;
if (classQualifiedName != null && !classQualifiedName.equals("")) {
result = classQualifiedName + "." + methodSimpleName;
} else {
result = methodSimpleName;
}
if (argClassesStr == null) {
return result;
} else {
return result + "-" + argClassesStr;
}
}
// TODO consider more about no argClassesStr method key
// (this is generated by additional testDoc)
public static String generateMethodKey(String classQualifiedName, String methodSimpleName) {
return generateMethodKeySub(classQualifiedName, methodSimpleName, null);
}
public static String generateMethodKey(String classQualifiedName,
String methodSimpleName, List<String> argClassQualifiedNames) {
if (argClassQualifiedNames == null) {
throw new NullPointerException();
}
String argClassesStr = argClassQualifiedNamesToArgClassesStr(argClassQualifiedNames);
return generateMethodKeySub(classQualifiedName, methodSimpleName, argClassesStr);
}
public static String generateMethodKey(String classQualifiedName,
String methodSimpleName, String argClassesStr) {
if (argClassesStr == null) {
throw new NullPointerException();
}
return generateMethodKeySub(classQualifiedName, methodSimpleName, argClassesStr);
}
public String getSimpleName() {
return simpleName;
}
public void setSimpleName(String simpleName) {
this.simpleName = simpleName;
}
public String getQualifiedName() {
if (testClass == null || simpleName == null) {
return simpleName;
} else {
return testClass.getQualifiedName() + "." + simpleName;
}
}
public String getTestDoc() {
return testDoc;
}
public void setTestDoc(String testDoc) {
this.testDoc = testDoc;
}
public CaptureStyle getCaptureStyle() {
return captureStyle;
}
public void setCaptureStyle(CaptureStyle captureStyle) {
if (captureStyle == CaptureStyle.STEP_IN_ONLY) {
throw new RuntimeException("not supported yet: " + captureStyle);
}
this.captureStyle = captureStyle;
}
public List<String> getArgVariables() {
return argVariables;
}
public void addArgVariable(String argVariable) {
argVariables.add(argVariable);
}
public boolean hasVariableLengthArg() {
return variableLengthArgIndex != -1;
}
public int getVariableLengthArgIndex() {
return variableLengthArgIndex;
}
public void setVariableLengthArgIndex(int variableLengthArgIndex) {
this.variableLengthArgIndex = variableLengthArgIndex;
}
public List<CodeLine> getCodeBody() {
return codeBody;
}
public void addCodeBody(CodeLine codeLine) {
codeBody.add(codeLine);
}
public void addAllCodeBodies(List<CodeLine> codeLines) {
codeBody.addAll(codeLines);
}
@Override
public Map<String, Object> toYamlObject() {
Map<String, Object> result = new HashMap<>(8);
result.put("classKey", testClassKey);
result.put("key", key);
result.put("name", simpleName);
if (testDoc != null) {
result.put("testDoc", testDoc);
}
if (captureStyle != CaptureStyle.getDefault()) {
result.put("capture", captureStyle.getValue());
}
if (!argVariables.isEmpty()) {
result.put("argVariables", argVariables);
}
if (variableLengthArgIndex != -1) {
result.put("varLengthArgIndex", variableLengthArgIndex);
}
if (!codeBody.isEmpty()) {
result.put("codeBody", YamlUtils.toYamlObjectList(codeBody));
}
return result;
}
@Override
public void fromYamlObject(Map<String, Object> yamlObject)
throws YamlConvertException {
testClass = null;
testClassKey = YamlUtils.getStrValue(yamlObject, "classKey");
key = YamlUtils.getStrValue(yamlObject, "key");
simpleName = YamlUtils.getStrValue(yamlObject, "name");
testDoc = YamlUtils.getStrValue(yamlObject, "testDoc", true);
// captureStyle is not mandatory
captureStyle = YamlUtils.getCaptureStyleValue(yamlObject, "capture", true);
if (captureStyle == null) {
captureStyle = CaptureStyle.getDefault();
}
argVariables = YamlUtils.getStrListValue(yamlObject, "argVariables", true);
Integer variableLengthArgIndexObj = YamlUtils.getIntValue(yamlObject, "varLengthArgIndex", true);
if (variableLengthArgIndexObj == null) {
variableLengthArgIndex = -1;
} else {
variableLengthArgIndex = variableLengthArgIndexObj;
}
List<Map<String, Object>> codeBodyYamlObj
= YamlUtils.getYamlObjectListValue(yamlObject, "codeBody", true);
codeBody = new ArrayList<>(codeBodyYamlObj.size());
for (Map<String, Object> codeLineYamlObj : codeBodyYamlObj) {
CodeLine codeLine = new CodeLine();
codeLine.fromYamlObject(codeLineYamlObj);
codeBody.add(codeLine);
}
}
}
| 35.212245 | 108 | 0.632433 |
368372e0a0809816ae745b82f46fac8fc111be1c | 3,242 | package io.immutables.micro.wiring;
import io.immutables.micro.*;
import io.immutables.micro.wiring.docker.DockerRunner;
import io.immutables.regres.SqlAccessor;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.google.common.util.concurrent.ServiceManager;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.multibindings.Multibinder;
import org.junit.BeforeClass;
import org.junit.Test;
import static io.immutables.that.Assert.that;
public class DatabaseTest {
interface Repo extends SqlAccessor {}
private static final Servicelet.Name s1 = Servicelet.name("s1");
private static final Injector injector = new Launcher()
.add(new ServiceletNameModule())
.add(new ServiceManagerModule())
.add(new DatabaseModule())
.add(new JsonModule())
.add(binder -> {
binder.bind(Databases.Setup.class).toInstance(
new Databases.Setup.Builder()
.autostart(true)
.database("<random>")
.isolate(Databases.Setup.Isolate.SCHEMA)
.mode(Databases.Setup.Mode.CREATE_AND_DROP)
.connect(String.format(
"postgresql://localhost:%d/postgres", 5432/* PORT */))
//"postgresql://localhost:%d/defaultdb?user=root&password=&sslmode=disable", PORT))
.build());
})
.addServicelet(new Module() {
@Override
public void configure(Binder binder) {
ServiceletNameModule.assignName(binder, s1);
binder.bind(Manifest.class).toInstance(deriveManifestRequireDatabase());
Key<Repo> repo = Key.get(Repo.class);
binder.bind(repo).toProvider(Databases.repositoryOwnProvider(repo));
Multibinder.newSetBinder(binder, DatabaseScript.class)
.addBinding()
.toInstance(DatabaseScript.usingSql("create table roachie(id text)"));
}
private Manifest deriveManifestRequireDatabase() {
return new Manifest.Builder()
.name(s1)
.addResources(new Manifest.Resource.Builder()
.reference(References.reference(Void.class))
.kind(Manifest.Kind.DATABASE_RECORD)
.build())
.build();
}
})
.inject();
//@BeforeClass
public static void ensureListening() {
DockerRunner.assertPostgresRunning(26259);
}
@Test
public void prepareAndUseTestDatabase() throws SQLException {
ServiceManager manager = injector.getInstance(ServiceManager.class);
manager.startAsync().awaitHealthy();
Databases.RepositoryFactory factory = injector.getInstance(Databases.RepositoryFactory.class);
Repo repo = (Repo) factory.create(s1, Key.get(Repo.class));
int result = -1;
try (var h = repo.connectionHandle(); var s = h.connection.createStatement()) {
ResultSet resultSet = s.executeQuery("select count(*) from roachie");
resultSet.next();
result = resultSet.getInt(1);
}
that(result).is(0); // just 0, but we didn't failed on non existent SQL objects
manager.stopAsync().awaitStopped();
}
}
| 35.23913 | 99 | 0.659778 |
f69c221adab6fff288aefe6fdbafbd2cae030394 | 31,377 | /*
* Copyright (C) 2010 Heinrich Schuchardt
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.TreeSet;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EtchedBorder;
import org.gnu.glpk.GLPK;
import org.gnu.glpk.GLPKConstants;
import org.gnu.glpk.GlpkCallback;
import org.gnu.glpk.GlpkCallbackListener;
import org.gnu.glpk.GlpkException;
import org.gnu.glpk.GlpkTerminal;
import org.gnu.glpk.GlpkTerminalListener;
import org.gnu.glpk.SWIGTYPE_p_int;
import org.gnu.glpk.glp_iocp;
import org.gnu.glpk.glp_prob;
import org.gnu.glpk.glp_tran;
import org.gnu.glpk.glp_tree;
/**
*
* @author Heinrich Schuchardt
*/
public class GmplSwing implements Runnable, GlpkTerminalListener,
GlpkCallbackListener, ActionListener {
public enum Status {
RUN,
TERMINATE,
ABORT
}
private final static String TERMINATE = "TERMINATE";
private final static String ABORT = "ABORT";
String[] args;
private Status terminate = Status.RUN;
private String lookAndFeel = "Nimbus";
private JEditorPane jEditorPane = null;
private JFrame jFrame = null;
private JMenuBar jMenuBar = null;
private JMenu jMenuFile = null;
private JMenuItem jMenuItemEvaluate = null;
private JMenuItem jMenuItemExit = null;
private JMenuItem jMenuItemNew = null;
private JMenuItem jMenuItemOpen = null;
private JMenuItem jMenuItemSave = null;
private JMenuItem jMenuItemSaveAs = null;
private JSplitPane verticalSplitPane = null;
private JSplitPane horizontalSplitPane = null;
private JLabel statusLabel = null;
private JTextArea jTextArea = null;
private JPanel outputPane = null;
private String filename = null;
private File path = null;
private boolean running = false;
private final Object plock = new Object();
private final Object lock = new Object();
private JButton terminateButton;
private JButton abortButton;
private TreeSet<Progress> progressTree = null;
private Diagram diagram = null;
/**
* Constructor
*
* @param args command line parameters
*/
private GmplSwing(String[] args) {
this.args = args;
GLPK.glp_java_set_numeric_locale("C");
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd;
cmd = e.getActionCommand();
if (cmd.equals(TERMINATE)) {
terminate = Status.TERMINATE;
} else if (cmd.equals(ABORT)) {
terminate = Status.ABORT;
}
}
private void evaluate() {
File tmpFile;
FileWriter fw;
glp_prob lp = null;
glp_tran tran;
glp_iocp iocp;
String fname;
int skip = 0;
int ret;
synchronized (lock) {
if (running) {
return;
}
running = true;
}
synchronized (plock) {
progressTree = new TreeSet<Progress>();
}
diagram.paint();
// set the terminal hook to call GlpkTerminal
GLPK.glp_term_hook(null, null);
try {
tmpFile = File.createTempFile("glp", ".mod");
fw = new FileWriter(tmpFile);
fw.write(jEditorPane.getText());
fw.close();
fname = tmpFile.getCanonicalPath();
} catch (IOException ex) {
statusLabel.setForeground(Color.red);
statusLabel.setText(ex.getMessage());
return;
}
statusLabel.setForeground(Color.black);
statusLabel.setText("Running");
jTextArea.setText(null);
jTextArea.setLineWrap(true);
terminate = Status.RUN;
// listen to callbacks
GlpkCallback.addListener(this);
// listen to terminal output
try {
GlpkTerminal.addListener(this);
} catch (Exception ex) {
}
lp = GLPK.glp_create_prob();
try {
tran = GLPK.glp_mpl_alloc_wksp();
ret = GLPK.glp_mpl_read_model(tran, fname, skip);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
throw new RuntimeException("Model file not valid: " + fname);
}
// generate model
ret = GLPK.glp_mpl_generate(tran, null);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
throw new RuntimeException("Cannot generate model: " + fname);
}
// build model
GLPK.glp_mpl_build_prob(tran, lp);
// set solver parameters
iocp = new glp_iocp();
GLPK.glp_init_iocp(iocp);
iocp.setPresolve(GLPKConstants.GLP_ON);
// solve model
ret = GLPK.glp_intopt(lp, iocp);
// postsolve model
GLPK.glp_mpl_postsolve(tran, lp, GLPKConstants.GLP_MIP);
// free memory
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
statusLabel.setText("Model has been processed successfully.");
statusLabel.setForeground(Color.black);
} catch (RuntimeException ex) {
statusLabel.setText(ex.getMessage());
statusLabel.setForeground(Color.red);
} finally {
// do not listen for callbacks anymore
GlpkCallback.removeListener(this);
// do not listen to output anymore
GlpkTerminal.removeListener(this);
}
// free the environment as evaluate will be called again by
// a different thread
GLPK.glp_free_env();
synchronized (lock) {
running = false;
}
}
/**
* Exit application
*/
public void exit() {
// If an optimization is running, we want to abort it now.
terminate = Status.ABORT;
while (running) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
}
// Leave application
jFrame.setVisible(false);
jFrame.dispose();
System.exit(0);
}
private Diagram getDiagram() {
if (diagram == null) {
diagram = new Diagram();
}
return diagram;
}
/**
* Create horizontal splitter
*
* @return horizontal splitter
*/
private JSplitPane getHorizontalSplitPane() {
if (horizontalSplitPane == null) {
horizontalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
horizontalSplitPane.setTopComponent(
new JScrollPane(getJEditorPane()));
horizontalSplitPane.setBottomComponent(
getOutputPane());
}
return horizontalSplitPane;
}
private JEditorPane getJEditorPane() {
if (jEditorPane == null) {
jEditorPane = new JEditorPane();
jEditorPane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
}
return jEditorPane;
}
/**
* This method initializes the frame
*
* @return frame
*/
private JFrame getJFrame() {
ClassLoader loader;
JPanel jPanel;
if (jFrame == null) {
URL url;
url = GmplSwing.class.getClassLoader().getResource(
"application.png");
jFrame = new JFrame(getClass().getName());
if (url != null) {
jFrame.setIconImage(new ImageIcon(url).getImage());
}
jFrame.setSize(new Dimension(2560, 2048));
jFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
jFrame.setJMenuBar(getJMenuBar());
setTitle();
jPanel = new JPanel();
jPanel.setLayout(new BorderLayout());
jPanel.add(getVerticalSplitPane(), BorderLayout.CENTER);
jPanel.add(getStatusLabel(), BorderLayout.SOUTH);
jFrame.setContentPane(jPanel);
}
return jFrame;
}
/**
* This method initializes the menu bar
*
* @return menu bar
*/
private JMenuBar getJMenuBar() {
if (jMenuBar == null) {
jMenuBar = new JMenuBar();
jMenuBar.add(getJMenuFile());
}
return jMenuBar;
}
/**
* This method initializes jMenuFile
*
* @return javax.swing.JMenu
*/
private JMenu getJMenuFile() {
if (jMenuFile == null) {
jMenuFile = new JMenu("File");
jMenuFile.add(getJMenuItemNew());
jMenuFile.add(getJMenuItemOpen());
jMenuFile.add(getJMenuItemEvaluate());
jMenuFile.add(getJMenuItemSave());
jMenuFile.add(getJMenuItemSaveAs());
jMenuFile.addSeparator();
jMenuFile.add(getJMenuItemExit());
}
return jMenuFile;
}
/**
* This method initializes jMenuItemEvaluate
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemEvaluate() {
if (jMenuItemEvaluate == null) {
jMenuItemEvaluate = new JMenuItem("Evaluate");
jMenuItemEvaluate.addActionListener(new EvaluateAction());
}
return jMenuItemEvaluate;
}
/**
* This method initializes jMenuItemExit
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemExit() {
if (jMenuItemExit == null) {
jMenuItemExit = new JMenuItem("Exit");
jMenuItemExit.addActionListener(new ExitAction());
}
return jMenuItemExit;
}
/**
* This method initializes jMenuItemNew
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemNew() {
if (jMenuItemNew == null) {
jMenuItemNew = new JMenuItem("New");
jMenuItemNew.addActionListener(new NewAction());
}
return jMenuItemNew;
}
/**
* This method initializes jMenuItemOpen
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemOpen() {
if (jMenuItemOpen == null) {
jMenuItemOpen = new JMenuItem("Open");
jMenuItemOpen.addActionListener(new OpenAction());
}
return jMenuItemOpen;
}
/**
* This method initializes jMenuItemSave
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemSave() {
if (jMenuItemSave == null) {
jMenuItemSave = new JMenuItem("Save");
jMenuItemSave.addActionListener(new SaveAction());
}
return jMenuItemSave;
}
/**
* This method initializes jMenuItemSaveAs
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getJMenuItemSaveAs() {
if (jMenuItemSaveAs == null) {
jMenuItemSaveAs = new JMenuItem("SaveAs");
jMenuItemSaveAs.addActionListener(new SaveAsAction());
}
return jMenuItemSaveAs;
}
private JPanel getOutputPane() {
if (outputPane == null) {
JToolBar toolbar = new JToolBar();
terminateButton = new JButton("Terminate");
terminateButton.setActionCommand(TERMINATE);
terminateButton.addActionListener(this);
abortButton = new JButton("Abort");
abortButton.setActionCommand(ABORT);
abortButton.addActionListener(this);
toolbar.setFloatable(false);
toolbar.add(terminateButton);
toolbar.add(abortButton);
outputPane = new JPanel();
outputPane.setLayout(new BorderLayout());
outputPane.add(toolbar, BorderLayout.NORTH);
outputPane.add(new JScrollPane(getJTextArea()), BorderLayout.CENTER);
}
return outputPane;
}
private JLabel getStatusLabel() {
if (statusLabel == null) {
statusLabel = new JLabel();
statusLabel.setBorder(new TopEtchedBorder());
statusLabel.setPreferredSize(new Dimension(0, 24));
}
return statusLabel;
}
private JTextArea getJTextArea() {
if (jTextArea == null) {
jTextArea = new JTextArea();
jTextArea.setEditable(false);
}
return jTextArea;
}
/**
* This method initializes the vertical splitter
*
* @return
*/
private JSplitPane getVerticalSplitPane() {
if (verticalSplitPane == null) {
verticalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
verticalSplitPane.setTopComponent(getHorizontalSplitPane());
verticalSplitPane.setBottomComponent(getDiagram());
}
return verticalSplitPane;
}
private void newFile() {
filename = null;
setTitle();
jEditorPane.setText("");
}
private void open() {
File file;
JFileChooser jFileChooser;
jFileChooser = new JFileChooser();
jFileChooser.addChoosableFileFilter(new ModelFileFilter());
jFileChooser.setCurrentDirectory(path);
if (jFileChooser.showOpenDialog(getJFrame())
!= JFileChooser.APPROVE_OPTION) {
return;
}
file = jFileChooser.getSelectedFile();
if (!file.exists()
&& jFileChooser.getFileFilter() instanceof ModelFileFilter
&& !file.getName().contains(".")) {
file = new File(file.getAbsolutePath() + ".mod");
}
readFile(file);
}
/**
* Read model file
*
* @param file file
* @return model
*/
private void readFile(File file) {
String text = "";
String str;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
while ((str = bufferedReader.readLine()) != null) {
text += str + "\n";
}
filename = file.getCanonicalPath();
path = file.getParentFile();
setTitle();
statusLabel.setForeground(Color.black);
statusLabel.setText("File read");
} catch (IOException ex) {
statusLabel.setText(ex.getMessage());
statusLabel.setForeground(Color.red);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
jEditorPane.setText(text);
} catch (IOException ex) {
}
}
}
}
@Override
public void run() {
setLookAndFeel();
getJFrame().addWindowListener(new WindowClosingListener());
getJFrame().setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
getJFrame().setVisible(true);
verticalSplitPane.setDividerLocation(.75);
horizontalSplitPane.setDividerLocation(.5);
if (args.length == 1) {
readFile(new File(args[0]));
}
}
private void save() {
writeFile(new File(filename));
}
private void saveAs() {
File file;
JFileChooser jFileChooser;
jFileChooser = new JFileChooser();
jFileChooser.addChoosableFileFilter(new ModelFileFilter());
jFileChooser.setCurrentDirectory(path);
for (;;) {
if (jFileChooser.showSaveDialog(getJFrame())
!= JFileChooser.APPROVE_OPTION) {
statusLabel.setForeground(Color.black);
statusLabel.setText("File save aborted by user");
return;
}
try {
file = new File(
jFileChooser.getSelectedFile().getCanonicalPath());
if (!file.exists()
&& jFileChooser.getFileFilter() instanceof ModelFileFilter
&& !file.getName().contains(".")) {
file = new File(file.getAbsolutePath() + ".mod");
}
if (file.exists()) {
// File exists already
switch (JOptionPane.showConfirmDialog(
jFrame, "Replace existing file?")) {
case JOptionPane.NO_OPTION:
// User does not want to overwrite
continue;
case JOptionPane.CANCEL_OPTION:
statusLabel.setForeground(Color.black);
statusLabel.setText("File save aborted by user");
return;
}
}
writeFile(file);
return;
} catch (IOException ex) {
statusLabel.setForeground(Color.red);
statusLabel.setText(ex.getMessage());
}
}
}
/**
* Set look and feel
*/
private void setLookAndFeel() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if (lookAndFeel.equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
}
private void setTitle() {
String str = "untitled";
if (filename != null) {
str = filename;
}
jFrame.setTitle(this.getClass().getSimpleName()
+ " - " + str);
}
private void writeFile(File file) {
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write(getJEditorPane().getText());
filename = file.getCanonicalPath();
path = file.getParentFile();
setTitle();
statusLabel.setText("File saved.");
} catch (IOException ex) {
statusLabel.setForeground(Color.red);
statusLabel.setText(ex.getMessage());
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException ex) {
}
}
}
}
/**
* Starts the Application
*
* @param args command line parameters
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new GmplSwing(args));
}
@Override
public boolean output(final String str) {
if (terminate == Status.ABORT) {
// remove terminal listeners
GlpkTerminal.removeAllListeners();
try {
GLPK.glp_java_error("Aborting due to user request");
} catch (GlpkException ex) {
} finally {
return false;
}
}
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
jTextArea.append(str);
}
});
return false;
}
@Override
public void callback(glp_tree tree) {
glp_prob prob;
prob = GLPK.glp_ios_get_prob(tree);
int a_cnt;
int n_cnt;
int t_cnt;
int reason;
int status;
SWIGTYPE_p_int p_a = GLPK.new_intArray(1);
SWIGTYPE_p_int p_n = GLPK.new_intArray(1);
SWIGTYPE_p_int p_t = GLPK.new_intArray(1);
if (terminate != Status.RUN) {
GLPK.glp_ios_terminate(tree);
return;
}
reason = GLPK.glp_ios_reason(tree);
status = GLPK.glp_mip_status(GLPK.glp_ios_get_prob(tree));
if (reason == GLPKConstants.GLP_ISELECT
|| reason == GLPKConstants.GLP_IBINGO) {
int bestNode;
double bestBound;
double bestValue;
int lastCount;
bestNode = GLPK.glp_ios_best_node(tree);
bestBound = GLPK.glp_ios_node_bound(tree, bestNode);
bestValue = GLPK.glp_mip_obj_val(GLPK.glp_ios_get_prob(tree));
GLPK.glp_ios_tree_size(tree, p_a, p_n, p_t);
a_cnt = GLPK.intArray_getitem(p_a, 0);
n_cnt = GLPK.intArray_getitem(p_n, 0);
t_cnt = GLPK.intArray_getitem(p_t, 0);
if (progressTree.isEmpty()) {
lastCount = 0;
} else {
lastCount = progressTree.last().evaluatedNodes;
}
Progress p = new Progress();
p.evaluatedNodes = t_cnt - a_cnt;
if (p.evaluatedNodes == 0) {
return;
}
p.bestSolution = bestValue;
p.lowerBound = bestBound;
p.status = status;
synchronized (plock) {
progressTree.add(p);
}
if (lastCount < p.evaluatedNodes) {
diagram.paint();
}
}
}
/**
* Listener for menu item "Open".
*/
private class OpenAction extends AbstractAction {
private static final long serialVersionUID = 7326124121439143329L;
@Override
public void actionPerformed(ActionEvent arg0) {
open();
}
}
/**
* Listener for menu item "Save".
*/
private class SaveAction extends AbstractAction {
private static final long serialVersionUID = 7326124121439143329L;
@Override
public void actionPerformed(ActionEvent arg0) {
if (filename == null) {
saveAs();
} else {
save();
}
}
}
/**
* Listener for menu item "SaveAs".
*/
private class SaveAsAction extends AbstractAction {
private static final long serialVersionUID = 7326124121439143329L;
@Override
public void actionPerformed(ActionEvent arg0) {
saveAs();
}
}
/**
* Listener for menu item "Evaluate".
*/
private class EvaluateAction extends AbstractAction {
private static final long serialVersionUID = 7326124121439143329L;
@Override
public void actionPerformed(ActionEvent arg0) {
new EvaluateThread().start();
}
}
private class EvaluateThread extends Thread {
@Override
public void run() {
evaluate();
}
}
/**
* Listener for menu item "Exit".
*/
private class ExitAction extends AbstractAction {
private static final long serialVersionUID = 3256140765884925290L;
@Override
public void actionPerformed(ActionEvent arg0) {
exit();
}
}
/**
* Listener for menu item "Exit".
*/
private class NewAction extends AbstractAction {
private static final long serialVersionUID = -5867871767895097849L;
@Override
public void actionPerformed(ActionEvent arg0) {
newFile();
}
}
/**
* File filter for simulation model files, implements singleton pattern.
*/
private class ModelFileFilter
extends FileFilter {
@Override
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".mod")
|| f.isDirectory();
}
@Override
public String getDescription() {
return "Model File (*.mod)";
}
}
/**
* WindowListener to react upon closing of the JFrame
*/
private class WindowClosingListener implements WindowListener {
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
exit();
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowOpened(WindowEvent e) {
}
}
/**
* Border style which is etched only on the top, to be used for the status
* bar.
*/
private class TopEtchedBorder extends EtchedBorder {
@Override
public Insets getBorderInsets(Component c) {
return new Insets(2, 0, 0, 0);
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height) {
int w = width;
g.translate(x, y);
g.setColor(etchType == LOWERED ? getShadowColor(c)
: getHighlightColor(c));
g.drawLine(0, 0, w - 1, 0);
g.setColor(etchType == LOWERED ? getHighlightColor(c)
: getShadowColor(c));
g.drawLine(0, 1, w - 1, 1);
g.translate(-x, -y);
}
}
/**
* One point in the progress chart
*/
private class Progress implements Comparable<Progress> {
public Integer evaluatedNodes;
public double lowerBound;
public double bestSolution;
public int status;
@Override
public int compareTo(Progress o) {
return evaluatedNodes.compareTo(o.evaluatedNodes);
}
}
/*
* Diagram showing the progress of the MIP solution process.
* The x-axis is used for the number of evaluated nodes.
* A green line shows the development of the best MIP solution.
* A red line shows the development of the best bound.
*/
private class Diagram extends JPanel {
/**
* Repaint using the AWT event dispatching thread.
*/
public void paint() {
final Diagram diagram = this;
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
diagram.repaint();
}
});
}
@Override
public void paintComponent(Graphics g) {
Dimension size = getSize();
int height = size.height - 1;
int width = size.width - 1;
double xmax;
double ymin;
double ymax;
Progress last = null;
// paint packground in black
g.setColor(Color.BLACK);
g.fillRect(0, 0, size.width, size.height);
if (height < 2) {
return;
}
if (width < 2) {
return;
}
synchronized (plock) {
if (progressTree == null) {
return;
}
if (progressTree.isEmpty()) {
return;
}
// Determine the enclosing rectable of the graph
xmax = progressTree.last().evaluatedNodes;
if (xmax == 0) {
return;
}
ymax = -Double.MAX_VALUE;
ymin = Double.MAX_VALUE;
for (Progress p : progressTree) {
if (p.status == GLPKConstants.GLP_FEAS
|| p.status == GLPKConstants.GLP_OPT) {
if (p.bestSolution < ymin) {
ymin = p.bestSolution;
}
if (p.bestSolution > ymax) {
ymax = p.bestSolution;
}
}
if (p.lowerBound > -1e300 && p.lowerBound < 1e300) {
if (p.lowerBound < ymin) {
ymin = p.lowerBound;
}
if (p.lowerBound > ymax) {
ymax = p.lowerBound;
}
}
}
if (ymax <= ymin) {
return;
}
for (Progress p : progressTree) {
if (last != null) {
g.setColor(Color.red);
g.drawLine(
(int) (last.evaluatedNodes / xmax * width),
(int) ((ymax - last.lowerBound) / (ymax - ymin) * height),
(int) (p.evaluatedNodes / xmax * width),
(int) ((ymax - p.lowerBound) / (ymax - ymin) * height));
if (last.status == GLPKConstants.GLP_FEAS
|| last.status == GLPKConstants.GLP_OPT) {
g.setColor(Color.green);
g.drawLine(
(int) (last.evaluatedNodes / xmax * width),
(int) ((ymax - last.bestSolution) / (ymax - ymin) * height),
(int) (p.evaluatedNodes / xmax * width),
(int) ((ymax - p.bestSolution) / (ymax - ymin) * height));
}
}
last = p;
}
}
}
}
}
| 29.997132 | 96 | 0.543742 |
97f3bbf152ffec59fdf20119edc13972565df296 | 1,460 | package com.youzu.clan.main.wechatstyle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by wuyexiong on 4/25/15.
*/
public class WeChatStyleFragmentAdapter extends FragmentPagerAdapter {
//
// protected static final String[] CONTENT = new String[]{"This", "Is", "Msg", "Mine",};
// private int mCount = CONTENT.length;
private FragmentManager fm;
private ArrayList<Fragment> fragments = new ArrayList<Fragment>();
public WeChatStyleFragmentAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
super(fm);
this.fragments = fragments;
this.fm = fm;
}
@Override
public Fragment getItem(int position) {
// if(position==0){
// return HotThreadFragment.getInstance();
// }else if(position==1){
// return ForumnavFragment.getInstance();
// }else if(position ==2){
// return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
//
// }else if(position ==3){
// return MyHomePageFragment.newInstance();
//
// }
// return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
return fragments.get(position);
}
@Override
public int getCount() {
if (fragments == null)
return 0;
return fragments.size();
}
}
| 26.545455 | 91 | 0.644521 |
2410c6e4a5fb7d89e423fc6f4fb284055cbe3154 | 3,296 | package com.publiccms.logic.dao.cms;
import java.util.Date;
import org.springframework.stereotype.Repository;
import com.publiccms.common.base.BaseDao;
import com.publiccms.common.constants.CommonConstants;
import com.publiccms.common.handler.PageHandler;
import com.publiccms.common.handler.QueryHandler;
import com.publiccms.common.tools.CommonUtils;
import com.publiccms.entities.cms.CmsWord;
/**
*
* CmsWordDao
*
*/
@Repository
public class CmsWordDao extends BaseDao<CmsWord> {
/**
* @param siteId
* @param hidden
* @param startCreateDate
* @param endCreateDate
* @param name
* @param orderField
* @param orderType
* @param pageIndex
* @param pageSize
* @return results page
*/
public PageHandler getPage(Short siteId, Boolean hidden, Date startCreateDate, Date endCreateDate, String name,
String orderField, String orderType, Integer pageIndex, Integer pageSize) {
QueryHandler queryHandler = getQueryHandler("from CmsWord bean");
if (CommonUtils.notEmpty(siteId)) {
queryHandler.condition("bean.siteId = :siteId").setParameter("siteId", siteId);
}
if (null != hidden) {
queryHandler.condition("bean.hidden = :hidden").setParameter("hidden", hidden);
}
if (null != startCreateDate) {
queryHandler.condition("bean.createDate > :startCreateDate").setParameter("startCreateDate", startCreateDate);
}
if (null != endCreateDate) {
queryHandler.condition("bean.createDate <= :endCreateDate").setParameter("endCreateDate", endCreateDate);
}
if (CommonUtils.notEmpty(name)) {
queryHandler.condition("bean.name like :name").setParameter("name", like(name));
}
if (!ORDERTYPE_ASC.equalsIgnoreCase(orderType)) {
orderType = ORDERTYPE_DESC;
}
if (null == orderField) {
orderField = CommonConstants.BLANK;
}
switch (orderField) {
case "searchCount":
queryHandler.order("bean.searchCount " + orderType);
break;
case "createDate":
queryHandler.order("bean.createDate " + orderType);
break;
default:
queryHandler.order("bean.id " + orderType);
}
return getPage(queryHandler, pageIndex, pageSize);
}
/**
* @param siteId
* @param name
* @return entity
*/
public CmsWord getEntity(short siteId, String name) {
if (CommonUtils.notEmpty(name)) {
QueryHandler queryHandler = getQueryHandler("from CmsWord bean");
queryHandler.condition("bean.siteId = :siteId").setParameter("siteId", siteId);
queryHandler.condition("bean.name = :name").setParameter("name", name);
return getEntity(queryHandler);
} else {
return null;
}
}
@Override
protected CmsWord init(CmsWord entity) {
if (null == entity.getCreateDate()) {
entity.setCreateDate(CommonUtils.getDate());
}
if (CommonUtils.notEmpty(entity.getName()) && entity.getName().length() > 255) {
entity.setName(entity.getName().substring(0, 255));
}
return entity;
}
} | 33.632653 | 122 | 0.625 |
b2df1ca39a66172cd89f3e0a8eeeb82da960c99b | 924 | package net.meisen.dissertation.server.session;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import net.meisen.dissertation.server.sessions.Session;
import net.meisen.dissertation.server.sessions.Session.IDateProvider;
import org.junit.Test;
/**
* Tests the implemenation of a {@code Session}.
*
* @author pmeisen
*
*/
public class TestSession {
/**
* Tests the timeout of a session.
*/
@Test
public void testTimeout() {
Session s = new Session("philipp", new IDateProvider() {
int i = 0;
@Override
public Date now() {
if (i == 0) {
i++;
return new Date();
} else {
return new Date(new Date().getTime() + 30 * 60000);
}
}
});
assertFalse(s.isTimedOut(45));
assertFalse(s.isTimedOut(31));
assertTrue(s.isTimedOut(30));
assertTrue(s.isTimedOut(15));
assertTrue(s.isTimedOut(29));
}
}
| 19.25 | 69 | 0.669913 |
3a3b9dd6701109fbf512ca638c97d992f1e2bb9e | 2,537 | /**
* generated by Xtext 2.17.1
*/
package ck2xtext.generic.ck2;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Bool Clause Property</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link ck2xtext.generic.ck2.BoolClauseProperty#isName <em>Name</em>}</li>
* <li>{@link ck2xtext.generic.ck2.BoolClauseProperty#getValue <em>Value</em>}</li>
* <li>{@link ck2xtext.generic.ck2.BoolClauseProperty#getProperties <em>Properties</em>}</li>
* </ul>
*
* @see ck2xtext.generic.ck2.Ck2Package#getBoolClauseProperty()
* @model
* @generated
*/
public interface BoolClauseProperty extends Property
{
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(boolean)
* @see ck2xtext.generic.ck2.Ck2Package#getBoolClauseProperty_Name()
* @model
* @generated
*/
boolean isName();
/**
* Sets the value of the '{@link ck2xtext.generic.ck2.BoolClauseProperty#isName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #isName()
* @generated
*/
void setName(boolean value);
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(String)
* @see ck2xtext.generic.ck2.Ck2Package#getBoolClauseProperty_Value()
* @model
* @generated
*/
String getValue();
/**
* Sets the value of the '{@link ck2xtext.generic.ck2.BoolClauseProperty#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(String value);
/**
* Returns the value of the '<em><b>Properties</b></em>' containment reference list.
* The list contents are of type {@link ck2xtext.generic.ck2.Property}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Properties</em>' containment reference list.
* @see ck2xtext.generic.ck2.Ck2Package#getBoolClauseProperty_Properties()
* @model containment="true"
* @generated
*/
EList<Property> getProperties();
} // BoolClauseProperty
| 29.847059 | 111 | 0.632637 |
3106818dfb51eb1e179b7d9d54a3847b862f060f | 78 | package com.ze.devhelper.dto;
public enum TYPE {
COMMAND,SCRIPT,PYTHON
}
| 13 | 29 | 0.730769 |
60d00a36b986c8c8caa42bf70abfcbe5ae3f3097 | 6,255 | package org.vitrivr.cineast.standalone.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import org.vitrivr.cineast.core.features.*;
import org.vitrivr.cineast.core.features.exporter.QueryImageExporter;
import org.vitrivr.cineast.core.features.retriever.Retriever;
import org.vitrivr.cineast.core.util.ReflectionHelper;
import java.util.*;
public final class RetrievalRuntimeConfig {
private static final HashMap<String, List<RetrieverConfig>> DEFAULT_RETRIEVER_CATEGORIES = new HashMap<>();
private int threadPoolSize = 4;
private int taskQueueSize = 10;
private int maxResults = 100;
private int resultsPerModule = 50;
private HashMap<String, List<RetrieverConfig>> retrieverCategories = DEFAULT_RETRIEVER_CATEGORIES;
static{
List<RetrieverConfig> list;
list = new ArrayList<>(6);
list.add(new RetrieverConfig(AverageColor.class, 2.3));
list.add(new RetrieverConfig(DominantColors.class, 1.0));
list.add(new RetrieverConfig(MedianColor.class, 1.2));
list.add(new RetrieverConfig(QueryImageExporter.class, 0.0001));
list.add(new RetrieverConfig(AverageFuzzyHist.class, 0.7));
list.add(new RetrieverConfig(MedianFuzzyHist.class, 1.3));
DEFAULT_RETRIEVER_CATEGORIES.put("globalcolor", list);
list = new ArrayList<>(13);
list.add(new RetrieverConfig(AverageColorARP44.class, 0.5));
list.add(new RetrieverConfig(MedianColorARP44.class, 0.85));
list.add(new RetrieverConfig(SubDivAverageFuzzyColor.class, 0.5));
list.add(new RetrieverConfig(SubDivMedianFuzzyColor.class, 0.85));
list.add(new RetrieverConfig(AverageColorGrid8.class, 1.8));
list.add(new RetrieverConfig(ChromaGrid8.class, 0.95));
list.add(new RetrieverConfig(SaturationGrid8.class, 0.65));
list.add(new RetrieverConfig(AverageColorCLD.class, 1.4));
list.add(new RetrieverConfig(CLD.class, 1.3));
list.add(new RetrieverConfig(HueValueVarianceGrid8.class, 0.85));
list.add(new RetrieverConfig(MedianColorGrid8.class, 1.7));
list.add(new RetrieverConfig(AverageColorRaster.class, 1.0));
list.add(new RetrieverConfig(MedianColorRaster.class, 1.0));
DEFAULT_RETRIEVER_CATEGORIES.put("localcolor", list);
list = new ArrayList<>(7);
list.add(new RetrieverConfig(EdgeARP88.class, 0.85));
list.add(new RetrieverConfig(EdgeGrid16.class, 1.15));
list.add(new RetrieverConfig(EdgeARP88Full.class, 0.85));
list.add(new RetrieverConfig(EdgeGrid16Full.class, 0.85));
list.add(new RetrieverConfig(EHD.class, 0.7));
list.add(new RetrieverConfig(DominantEdgeGrid16.class, 1.4));
list.add(new RetrieverConfig(DominantEdgeGrid8.class, 1.4));
DEFAULT_RETRIEVER_CATEGORIES.put("edge", list);
list = new ArrayList<>(9);
list.add(new RetrieverConfig(MotionHistogram.class, 0.5));
list.add(new RetrieverConfig(SubDivMotionHistogram2.class, 1.0));
list.add(new RetrieverConfig(SubDivMotionHistogram3.class, 1.0));
list.add(new RetrieverConfig(SubDivMotionHistogram4.class, 1.0));
list.add(new RetrieverConfig(SubDivMotionHistogram5.class, 1.0));
list.add(new RetrieverConfig(SubDivMotionSum2.class, 0.5));
list.add(new RetrieverConfig(SubDivMotionSum3.class, 0.5));
list.add(new RetrieverConfig(SubDivMotionSum4.class, 0.5));
list.add(new RetrieverConfig(SubDivMotionSum5.class, 0.5));
DEFAULT_RETRIEVER_CATEGORIES.put("motion", list);
list = new ArrayList<>(3);
list.add(new RetrieverConfig(SubtitleFulltextSearch.class, 1.0));
list.add(new RetrieverConfig(DescriptionTextSearch.class, 1.0));
// list.add(new RetrieverConfig(QueryImageExporter.class, 0.001));
DEFAULT_RETRIEVER_CATEGORIES.put("meta", list);
}
@JsonCreator
public RetrievalRuntimeConfig() {
}
@JsonProperty
public int getThreadPoolSize(){
return this.threadPoolSize;
}
public void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
@JsonProperty
public int getTaskQueueSize() {
return this.taskQueueSize;
}
public void setTaskQueueSize(int taskQueueSize) {
this.taskQueueSize = taskQueueSize;
}
@JsonProperty
public int getMaxResults(){
return this.maxResults;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
@JsonProperty
public int getMaxResultsPerModule(){
return this.resultsPerModule;
}
public void setResultsPerModule(int resultsPerModule) {
this.resultsPerModule = resultsPerModule;
}
@JsonProperty("features")
public List<String> getRetrieverCategories(){
Set<String> keys = this.retrieverCategories.keySet();
ArrayList<String> _return = new ArrayList<>(keys.size());
_return.addAll(keys);
return _return;
}
public TObjectDoubleHashMap<Retriever> getRetrieversByCategory(String category){
List<RetrieverConfig> list = this.retrieverCategories.get(category);
if(list == null){
return new TObjectDoubleHashMap<>(1);
}
TObjectDoubleHashMap<Retriever> _return = new TObjectDoubleHashMap<>(list.size());
for(RetrieverConfig config : list){
Retriever rev;
if(config.getProperties() == null){
rev = ReflectionHelper.instantiate(config.getRetrieverClass());
} else {
rev = ReflectionHelper.instantiate(config.getRetrieverClass(), config.getProperties());
}
if(rev != null){
_return.put(rev, config.getWeight());
}
}
return _return;
}
public Optional<Retriever> getRetrieverByName(String retrieverName) {
for (List<RetrieverConfig> configs : this.retrieverCategories
.values()) {
for (RetrieverConfig config : configs) {
if (config.getRetrieverClass().getSimpleName().equals(retrieverName)) {
Retriever retriever;
if(config.getProperties() == null){
retriever = ReflectionHelper.instantiate(config.getRetrieverClass());
} else {
retriever = ReflectionHelper.instantiate(config.getRetrieverClass(), config.getProperties());
}
if (retriever != null) {
return Optional.of(retriever);
}
}
}
}
return Optional.empty();
}
}
| 35.742857 | 109 | 0.7255 |
a28da78702f3685d45d84d7ea62375f6be04c21c | 2,299 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.06.28 at 12:26:20 PM CEST
//
package de.uos.inf.ischedule.model.inrc;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for WeightOnly complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="WeightOnly">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>boolean">
* <attribute name="weight" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "WeightOnly", propOrder = {
"value"
})
public class InrcWeightOnly {
@XmlValue
protected boolean value;
@XmlAttribute(name = "weight")
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger weight;
/**
* Gets the value of the value property.
*
*/
public boolean isValue() {
return value;
}
/**
* Sets the value of the value property.
*
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* Gets the value of the weight property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getWeight() {
return weight;
}
/**
* Sets the value of the weight property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setWeight(BigInteger value) {
this.weight = value;
}
}
| 25.544444 | 110 | 0.61418 |
33dfc9a71afd36af30b8c4a1bf1e04da9366fa2f | 153 | package tcpassresetplugin;
public class InvalidTokenException extends RuntimeException {
public InvalidTokenException() {
super();
}
}
| 17 | 61 | 0.72549 |
d6e53dd3d45dcc6ac104dbc6e5b11d4a2c832b14 | 5,863 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office;
import com.wilutions.com.*;
/**
* _CommandBarComboBox.
*
*/
@CoInterface(guid="{000C030C-0000-0000-C000-000000000046}")
public interface _CommandBarComboBox extends IDispatch {
static boolean __typelib__loaded = __TypeLib.load();
@DeclDISPID(1610809344) public IDispatch getApplication() throws ComException;
@DeclDISPID(1610809345) public Integer getCreator() throws ComException;
@DeclDISPID(1610874880) public Boolean getBeginGroup() throws ComException;
@DeclDISPID(1610874880) public void setBeginGroup(final Boolean value) throws ComException;
@DeclDISPID(1610874882) public Boolean getBuiltIn() throws ComException;
@DeclDISPID(1610874883) public String getCaption() throws ComException;
@DeclDISPID(1610874883) public void setCaption(final String value) throws ComException;
@DeclDISPID(1610874886) public CommandBarControl Copy(final Object Bar, final Object Before) throws ComException;
@DeclDISPID(1610874887) public void Delete(final Object Temporary) throws ComException;
@DeclDISPID(1610874888) public String getDescriptionText() throws ComException;
@DeclDISPID(1610874888) public void setDescriptionText(final String value) throws ComException;
@DeclDISPID(1610874890) public Boolean getEnabled() throws ComException;
@DeclDISPID(1610874890) public void setEnabled(final Boolean value) throws ComException;
@DeclDISPID(1610874892) public void Execute() throws ComException;
@DeclDISPID(1610874893) public Integer getHeight() throws ComException;
@DeclDISPID(1610874893) public void setHeight(final Integer value) throws ComException;
@DeclDISPID(1610874895) public Integer getHelpContextId() throws ComException;
@DeclDISPID(1610874895) public void setHelpContextId(final Integer value) throws ComException;
@DeclDISPID(1610874897) public String getHelpFile() throws ComException;
@DeclDISPID(1610874897) public void setHelpFile(final String value) throws ComException;
@DeclDISPID(1610874899) public Integer getId() throws ComException;
@DeclDISPID(1610874900) public Integer getIndex() throws ComException;
@DeclDISPID(1610874902) public CommandBarControl Move(final Object Bar, final Object Before) throws ComException;
@DeclDISPID(1610874903) public Integer getLeft() throws ComException;
@DeclDISPID(1610874904) public MsoControlOLEUsage getOLEUsage() throws ComException;
@DeclDISPID(1610874904) public void setOLEUsage(final MsoControlOLEUsage value) throws ComException;
@DeclDISPID(1610874906) public String getOnAction() throws ComException;
@DeclDISPID(1610874906) public void setOnAction(final String value) throws ComException;
@DeclDISPID(1610874908) public CommandBar getParent() throws ComException;
@DeclDISPID(1610874909) public String getParameter() throws ComException;
@DeclDISPID(1610874909) public void setParameter(final String value) throws ComException;
@DeclDISPID(1610874911) public Integer getPriority() throws ComException;
@DeclDISPID(1610874911) public void setPriority(final Integer value) throws ComException;
@DeclDISPID(1610874913) public void Reset() throws ComException;
@DeclDISPID(1610874914) public void SetFocus() throws ComException;
@DeclDISPID(1610874915) public String getTag() throws ComException;
@DeclDISPID(1610874915) public void setTag(final String value) throws ComException;
@DeclDISPID(1610874917) public String getTooltipText() throws ComException;
@DeclDISPID(1610874917) public void setTooltipText(final String value) throws ComException;
@DeclDISPID(1610874919) public Integer getTop() throws ComException;
@DeclDISPID(1610874920) public MsoControlType getType() throws ComException;
@DeclDISPID(1610874921) public Boolean getVisible() throws ComException;
@DeclDISPID(1610874921) public void setVisible(final Boolean value) throws ComException;
@DeclDISPID(1610874923) public Integer getWidth() throws ComException;
@DeclDISPID(1610874923) public void setWidth(final Integer value) throws ComException;
@DeclDISPID(1610874925) public Boolean getIsPriorityDropped() throws ComException;
@DeclDISPID(1610940416) public void AddItem(final String Text, final Object Index) throws ComException;
@DeclDISPID(1610940417) public void Clear() throws ComException;
@DeclDISPID(1610940418) public Integer getDropDownLines() throws ComException;
@DeclDISPID(1610940418) public void setDropDownLines(final Integer value) throws ComException;
@DeclDISPID(1610940420) public Integer getDropDownWidth() throws ComException;
@DeclDISPID(1610940420) public void setDropDownWidth(final Integer value) throws ComException;
@DeclDISPID(1610940422) public String getList(final Integer Index) throws ComException;
@DeclDISPID(1610940422) public void setList(final Integer Index, final String value2) throws ComException;
@DeclDISPID(1610940424) public Integer getListCount() throws ComException;
@DeclDISPID(1610940425) public Integer getListHeaderCount() throws ComException;
@DeclDISPID(1610940425) public void setListHeaderCount(final Integer value) throws ComException;
@DeclDISPID(1610940427) public Integer getListIndex() throws ComException;
@DeclDISPID(1610940427) public void setListIndex(final Integer value) throws ComException;
@DeclDISPID(1610940429) public void RemoveItem(final Integer Index) throws ComException;
@DeclDISPID(1610940430) public MsoComboStyle getStyle() throws ComException;
@DeclDISPID(1610940430) public void setStyle(final MsoComboStyle value) throws ComException;
@DeclDISPID(1610940432) public String getText() throws ComException;
@DeclDISPID(1610940432) public void setText(final String value) throws ComException;
}
| 76.142857 | 117 | 0.796691 |
568976a8dfdbdcdee930fa051a302c0b11bbcf46 | 468 | package com.terraformersmc.cinderscapes.util;
public class MathHelper {
public static float map(float val, float instart, float inend, float outstart, float outend) {
return ((val - instart) / (inend - instart)) * (outend - outstart) + outstart;
}
public static float max(float ...vals) {
float max = vals[0];
for (int i = 1; i < vals.length; i++) {
max = Math.max(max, vals[i]);
}
return max;
}
}
| 29.25 | 98 | 0.58547 |
d2835e373dd8924c5af30b515c7e04ec8154a971 | 2,092 | //一只青蛙想要过河。 假定河流被等分为若干个单元格,并且在每一个单元格内都有可能放有一块石子(也有可能没有)。 青蛙可以跳上石子,但是不可以跳入水中。
//
// 给你石子的位置列表 stones(用单元格序号 升序 表示), 请判定青蛙能否成功过河(即能否在最后一步跳至最后一块石子上)。
//
// 开始时, 青蛙默认已站在第一块石子上,并可以假定它第一步只能跳跃一个单位(即只能从单元格 1 跳至单元格 2 )。
//
// 如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1、k 或 k + 1 个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。
//
//
//
//
// 示例 1:
//
//
//输入:stones = [0,1,3,5,6,8,12,17]
//输出:true
//解释:青蛙可以成功过河,按照如下方案跳跃:跳 1 个单位到第 2 块石子, 然后跳 2 个单位到第 3 块石子, 接着 跳 2 个单位到第 4 块石子, 然
//后跳 3 个单位到第 6 块石子, 跳 4 个单位到第 7 块石子, 最后,跳 5 个单位到第 8 个石子(即最后一块石子)。
//
// 示例 2:
//
//
//输入:stones = [0,1,2,3,4,8,9,11]
//输出:false
//解释:这是因为第 5 和第 6 个石子之间的间距太大,没有可选的方案供青蛙跳跃过去。
//
//
//
// 提示:
//
//
// 2 <= stones.length <= 2000
// 0 <= stones[i] <= 231 - 1
// stones[0] == 0
//
// Related Topics 动态规划
// 👍 178 👎 0
package me.bob.leetcode.editor.cn;
/**
* 403 青蛙过河
* 2021-04-29 07:08:32
* 思路:动态规划
*/
public class FrogJump {
public static void main(String[] args) {
Solution solution = new FrogJump().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean canCross(int[] stones) {
int n = stones.length;
// dp[i][k] 表示青蛙位于第 i 个石头上且上一次跳跃了 k 个距离
boolean[][] dp = new boolean[n][n];
dp[0][0] = true;
// // 当第 i - 1 个石头与第 i 个石头距离超过 i 时,无法到达终点
// for (int i = 1; i < n; i++) {
// if (stones[i] - stones[i - 1] > i) {
// return false;
// }
// }
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
int k = stones[i] - stones[j];
if (k > j + 1) {
break;
}
dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1];
if (i == n - 1 && dp[i][k]) {
return true;
}
}
}
return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 24.611765 | 80 | 0.478489 |
4c9ac64ed9333c41eeb1801442f626fb3fe0e8d1 | 1,233 | package com.leggett.upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
@ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}
}
| 31.615385 | 87 | 0.81914 |
610858d6b6edf4f5892144bc0682f990fcf87b77 | 2,114 | package com.ijinshan.sjk.dao.impl;
import java.io.Serializable;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ijinshan.sjk.dao.BaseDao;
public abstract class AbstractBaseDao<T> implements BaseDao<T> {
private static final Logger logger = LoggerFactory.getLogger(AbstractBaseDao.class);
@Resource(name = "sessionFactory")
protected SessionFactory sessions;
@Override
@SuppressWarnings("unchecked")
public T get(Serializable id) {
return (T) getSession().get(getType(), id);
}
public Session getSession() {
return sessions.getCurrentSession();
}
@Override
public Serializable save(Session sess, T t) {
return sess.save(t);
}
@Override
public Serializable save(T t) {
return getSession().save(t);
}
@Override
public void update(Session session, T t) {
session.update(t);
}
@Override
public void update(T t) {
getSession().update(t);
}
@Override
public void saveOrUpdate(Session sess, T t) {
sess.saveOrUpdate(t);
}
@Override
public void saveOrUpdate(T t) {
getSession().saveOrUpdate(t);
}
@Override
public void delete(T t) {
delete(getSession(), t);
}
@Override
public void delete(Session session, T t) {
session.delete(t);
}
public SessionFactory getSessions() {
return sessions;
}
public void setSessions(SessionFactory sessions) {
this.sessions = sessions;
}
@Override
public long count() {
return count(getSession());
}
@Override
public long count(Session session) {
String queryString = new StringBuilder("select count(id) from ").append(getType().getName()).toString();
Query query = session.createQuery(queryString);
Object o = query.uniqueResult();
return Long.valueOf(o.toString());
}
public abstract Class<T> getType();
}
| 22.252632 | 112 | 0.644749 |
7eeb27e7b006e8f9ff7e66df7bdf7ee87b679b81 | 232 | package com.yuepong.workflow.param;
import lombok.Data;
/**
* ModelAttr
* <p>
* <br/>
*
* @author apr
* @date 2021/10/25 14:54:48
**/
@Data
public class ModelAttr{
public String bpmn_xml;
public String svg_xml;
}
| 11.6 | 35 | 0.637931 |
3309a7089279ec598b2d1e0561c12049cfd0e115 | 358 | package com.sudoplay.sudoxt.classloader.asm.transform;
import org.objectweb.asm.MethodVisitor;
/**
* Created by codetaylor on 2/26/2017.
*/
public interface IMethodVisitorFactory {
MethodVisitor create(
MethodVisitor methodVisitor,
int access,
String name,
String desc,
String signature,
String[] exceptions
);
}
| 18.842105 | 54 | 0.698324 |
1c373c1506abd3a18202c704487e89c9f4358d15 | 3,444 | package lesson5.labs.prob3.control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.JFrame;
import lesson5.labs.prob3.data.Data;
import lesson5.labs.prob3.data.Logins;
import lesson5.labs.prob3.ui.*;
public enum Control {
INSTANCE;
Start start;
Grades grades;
Login login;
String username;
Remarks remarks;
private boolean isLoggedIn = false;
public boolean isLoggedIn() {
return isLoggedIn;
}
public void setLoggedIn(boolean b) {
isLoggedIn = b;
}
public void setStart(Start st) {
this.start = st;
}
public void backToStart(JFrame frame) {
frame.setVisible(false);
start.setMessage("");
start.setVisible(true);
}
class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
login = new Login();
start.setVisible(false);
login.setVisible(true);
}
}
class RemarksListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
remarks = new Remarks();
String currentUser = Control.this.username;
boolean isLogged = Control.this.isLoggedIn;
if(currentUser == null || !isLogged)
return;
HashMap<String, String> rem
= Data.dataMap.get(currentUser).getTeacherRemarks();
StringBuilder sb = new StringBuilder();
for(String key : rem.keySet()) {
sb.append(key + " : " + rem.get(key) + "\n");
}
remarks.setRemarks(sb.toString());
remarks.setTitle("Teacher Remarks for " + currentUser);
remarks.setHeading("Teacher Remarks for " + currentUser);
Control.INSTANCE.start.setMessage("");
Control.INSTANCE.start.setVisible(false);
remarks.setVisible(true);
}
}
class GradesListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String currentUser = Control.this.username;
boolean isLogged = Control.this.isLoggedIn;
if(currentUser == null || !isLogged)
return;
grades = new Grades();
HashMap<String, String> gr
= Data.dataMap.get(currentUser).getGrades();
StringBuilder sb = new StringBuilder();
for(String key : gr.keySet()) {
sb.append(key + " : " + gr.get(key) + "\n");
}
grades.setGrades(sb.toString());
grades.setTitle("Grades for " + currentUser);
grades.setHeading("Grades for " + currentUser);
Control.INSTANCE.start.setMessage("");
Control.INSTANCE.start.setVisible(false);
grades.setVisible(true);
}
}
class SubmitLoginListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String username = login.getUserName();
String password = login.getPassword();
if(!Logins.foundUserNamePwd(username, password)) {
login.setMessage("Login failed.");
} else {
Control.this.username = username;
Control.this.isLoggedIn = true;
login.setMessage("Successful login");
}
}
}
//
class LogoutListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
Control.this.setLoggedIn(false);
Control.this.username = null;
}
}
//
public SubmitLoginListener getSubmitLoginListener() {
return new SubmitLoginListener();
}
public LoginListener getLoginListener() {
return new LoginListener();
}
public RemarksListener getRemarksListener() {
return new RemarksListener();
}
public GradesListener getGradesListener() {
return new GradesListener();
}
//
public LogoutListener getLogoutListener() {
return new LogoutListener();
}
//
}
| 28 | 60 | 0.714576 |
a6feb7aea79aa764d65abb76c3207f27b624afac | 3,591 | package edu.tufts.contours.contoursGame;
import java.util.ArrayList;
public class ScoreSet {
/** Not-null value. */
private String user_id;
private String difficulty;
private int interval_size;
private int total_score;
private Long elapsed_time;
private Integer notes_hit;
private Integer notes_missed;
private Integer longest_streak;
private Integer average_streak;
private java.util.Date date;
private ArrayList<ScoreSingle> singles;
private ArrayList<SurveyResponse> surveyResponses;
public ScoreSet() {
}
public ScoreSet(String user_id, String difficulty, int interval_size, int total_score,
Long elapsed_time, Integer notes_hit, Integer notes_missed, Integer longest_streak,
Integer average_streak, java.util.Date date, ArrayList<ScoreSingle> singles) {
this.user_id = user_id;
this.difficulty = difficulty;
this.interval_size = interval_size;
this.total_score = total_score;
this.elapsed_time = elapsed_time;
this.notes_hit = notes_hit;
this.notes_missed = notes_missed;
this.longest_streak = longest_streak;
this.average_streak = average_streak;
this.date = date;
this.singles = singles;
this.surveyResponses = new ArrayList<>();
}
/** Not-null value. */
public String getUser_id() {
return user_id;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getDifficulty() {
return difficulty;
}
public void setDifficulty(String difficulty) {
this.difficulty = difficulty;
}
public int getTotal_score() {
return total_score;
}
public void setTotal_score(int total_score) {
this.total_score = total_score;
}
public Long getElapsed_time() {
return elapsed_time;
}
public void setElapsed_time(Long elapsed_time) {
this.elapsed_time = elapsed_time;
}
public Integer getNotes_hit() {
return notes_hit;
}
public void setNotes_hit(Integer notes_hit) {
this.notes_hit = notes_hit;
}
public Integer getNotes_missed() {
return notes_missed;
}
public void setNotes_missed(Integer notes_missed) {
this.notes_missed = notes_missed;
}
public Integer getLongest_streak() {
return longest_streak;
}
public void setLongest_streak(Integer longest_streak) {
this.longest_streak = longest_streak;
}
public Integer getAverage_streak() {
return average_streak;
}
public void setAverage_streak(Integer average_streak) {
this.average_streak = average_streak;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
public ArrayList<ScoreSingle> getSingles() {
return singles;
}
public void setSingles(ArrayList<ScoreSingle> singles) {
this.singles = singles;
}
public ArrayList<SurveyResponse> getSurveyResponses() {
return surveyResponses;
}
public void setSurveyResponses(ArrayList<SurveyResponse> surveyResponses) {
this.surveyResponses = surveyResponses;
}
public int getInterval_size() {
return interval_size;
}
public void setInterval_size(int interval_size) {
this.interval_size = interval_size;
}
}
| 25.468085 | 103 | 0.659983 |
af382b6e9d92d6366b7c799e2427a31e5b11c8c7 | 23,302 | package io.joyrpc.config;
/*-
* #%L
* joyrpc
* %%
* Copyright (C) 2019 joyrpc.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.
* #L%
*/
import io.joyrpc.GenericService;
import io.joyrpc.cluster.candidate.Candidature;
import io.joyrpc.cluster.distribution.*;
import io.joyrpc.cluster.event.NodeEvent;
import io.joyrpc.codec.serialization.Serialization;
import io.joyrpc.config.validator.ValidatePlugin;
import io.joyrpc.constants.Constants;
import io.joyrpc.constants.ExceptionCode;
import io.joyrpc.context.GlobalContext;
import io.joyrpc.event.EventHandler;
import io.joyrpc.exception.InitializationException;
import io.joyrpc.exception.RpcException;
import io.joyrpc.extension.MapParametric;
import io.joyrpc.extension.Parametric;
import io.joyrpc.extension.URL;
import io.joyrpc.invoker.InvokerCaller;
import io.joyrpc.transport.channel.ChannelManagerFactory;
import io.joyrpc.util.*;
import io.joyrpc.util.StateMachine.IntStateMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import static io.joyrpc.GenericService.GENERIC;
import static io.joyrpc.constants.Constants.*;
import static io.joyrpc.util.ClassUtils.forName;
import static io.joyrpc.util.ClassUtils.isReturnFuture;
/**
* 抽象消费者配置
*/
public abstract class AbstractConsumerConfig<T> extends AbstractInterfaceConfig {
private final static Logger logger = LoggerFactory.getLogger(AbstractConsumerConfig.class);
/**
* 注册中心配置,只能配置一个
*/
@Valid
protected RegistryConfig registry;
/**
* 直连调用地址
*/
protected String url;
/**
* 是否泛化调用
*/
protected Boolean generic = false;
/**
* 集群处理算法
*/
@ValidatePlugin(extensible = Router.class, name = "ROUTER", defaultValue = DEFAULT_ROUTER)
protected String cluster;
/**
* 负载均衡算法
*/
@ValidatePlugin(extensible = LoadBalance.class, name = "LOADBALANCE", defaultValue = DEFAULT_LOADBALANCE)
protected String loadbalance;
/**
* 粘连算法,尽量保持同一个目标地址
*/
protected Boolean sticky;
/**
* 是否jvm内部调用(provider和consumer配置在同一个jvm内,则走本地jvm内部,不走远程)
*/
protected Boolean injvm;
/**
* 是否强依赖(即没有服务节点就启动失败)
*/
protected Boolean check;
/**
* 默认序列化
*/
@ValidatePlugin(extensible = Serialization.class, name = "SERIALIZATION", defaultValue = DEFAULT_SERIALIZATION)
protected String serialization;
/**
* 初始化连接数
*/
protected Integer initSize;
/**
* 最小连接数
*/
protected Integer minSize;
/**
* 候选者算法插件
*/
@ValidatePlugin(extensible = Candidature.class, name = "CANDIDATURE", defaultValue = DEFAULT_CANDIDATURE)
protected String candidature;
/**
* 失败最大重试次数
*/
protected Integer retries;
/**
* 每个节点只调用一次
*/
protected Boolean retryOnlyOncePerNode;
/**
* 可以重试的逗号分隔的异常全路径类名
*/
protected String failoverWhenThrowable;
/**
* 重试异常判断接口插件
*/
@ValidatePlugin(extensible = ExceptionPredication.class, name = "EXCEPTION_PREDICATION")
protected String failoverPredication;
/**
* 异常重试目标节点选择器
*/
@ValidatePlugin(extensible = FailoverSelector.class, name = "FAILOVER_SELECTOR", defaultValue = DEFAULT_FAILOVER_SELECTOR)
protected String failoverSelector;
/**
* 并行分发数量,在采用并行分发策略有效
*/
protected Integer forks;
/**
* channel创建模式
* shared:共享(默认),unshared:独享
*/
@ValidatePlugin(extensible = ChannelManagerFactory.class, name = "CHANNEL_MANAGER_FACTORY", defaultValue = DEFAULT_CHANNEL_FACTORY)
protected String channelFactory;
/**
* 节点选择器
*/
@ValidatePlugin(extensible = NodeSelector.class, name = "NODE_SELECTOR", multiple = true)
protected String nodeSelector;
/**
* 预热权重
*/
protected Integer warmupWeight;
/**
* 预热时间
*/
protected Integer warmupDuration;
/**
* 泛化调用的类
*/
protected transient Class<?> genericClass;
/**
* 代理实现类
*/
protected transient volatile T stub;
/**
* 事件监听器
*/
protected transient List<EventHandler<NodeEvent>> eventHandlers = new CopyOnWriteArrayList<>();
/**
* 状态机
*/
protected transient volatile IntStateMachine<Void, ConsumerPilot> stateMachine = new IntStateMachine<>(() -> create());
public AbstractConsumerConfig() {
}
public AbstractConsumerConfig(AbstractConsumerConfig config) {
super(config);
this.registry = config.registry;
this.url = config.url;
this.generic = config.generic;
this.cluster = config.cluster;
this.loadbalance = config.loadbalance;
this.sticky = config.sticky;
this.injvm = config.injvm;
this.check = config.check;
this.serialization = config.serialization;
this.initSize = config.initSize;
this.minSize = config.minSize;
this.candidature = config.candidature;
this.retries = config.retries;
this.retryOnlyOncePerNode = config.retryOnlyOncePerNode;
this.failoverWhenThrowable = config.failoverWhenThrowable;
this.failoverPredication = config.failoverPredication;
this.failoverSelector = config.failoverSelector;
this.forks = config.forks;
this.channelFactory = config.channelFactory;
this.nodeSelector = config.nodeSelector;
this.warmupWeight = config.warmupWeight;
this.warmupDuration = config.warmupDuration;
}
public AbstractConsumerConfig(AbstractConsumerConfig config, String alias) {
this(config);
this.alias = alias;
}
/**
* 代理对象,用于Spring场景提前返回代理
*
* @return 代理
*/
public T proxy() {
if (stub == null) {
final Class<T> proxyClass = getProxyClass();
stub = getProxyFactory().getProxy(proxyClass, (proxy, method, args) -> {
try {
ConsumerPilot pilot = stateMachine.getController(s -> s.isOpened());
if (pilot == null) {
throw new RpcException("Consumer config is not opened. " + name());
} else {
return pilot.invoke(proxy, method, args);
}
} catch (Throwable e) {
if (isReturnFuture(proxyClass, method)) {
return Futures.completeExceptionally(e);
}
throw e;
}
});
}
return stub;
}
@Override
protected boolean isClose() {
return stateMachine.isClose(null) || super.isClose();
}
protected boolean isClose(final AbstractConsumerPilot<?, ?> controller) {
return stateMachine.isClose(controller) || super.isClose();
}
/**
* 异步引用
*
* @return CompletableFuture
*/
public CompletableFuture<T> refer() {
CompletableFuture<T> result = new CompletableFuture<>();
stateMachine.open().whenComplete((v, e) -> {
if (e == null) {
result.complete(stub);
} else {
result.completeExceptionally(e);
}
});
return result;
}
/**
* 引用一个远程服务,用于Spring场景,优先返回代理对象
*
* @param future 操作结果消费者
* @return 接口代理类
* @see AbstractConsumerConfig#refer()
* @see AbstractConsumerConfig#proxy()
*/
@Deprecated
public T refer(final CompletableFuture<Void> future) {
stateMachine.open().whenComplete((v, e) -> {
if (e == null) {
Optional.ofNullable(future).ifPresent(o -> o.complete(null));
} else {
Optional.ofNullable(future).ifPresent(o -> o.completeExceptionally(e));
}
});
return stub;
}
/**
* 创建消费控制器
*
* @return 控制器
*/
protected abstract ConsumerPilot create();
/**
* 注销
*
* @return CompletableFuture
*/
public CompletableFuture<Void> unrefer() {
Parametric parametric = new MapParametric<>(GlobalContext.getContext());
return unrefer(parametric.getBoolean(Constants.GRACEFULLY_SHUTDOWN_OPTION));
}
/**
* 注销
*
* @param gracefully 优雅标识
* @return CompletableFuture
*/
public CompletableFuture<Void> unrefer(final boolean gracefully) {
return stateMachine.close(gracefully);
}
@Override
public String name() {
if (name == null) {
name = GlobalContext.getString(PROTOCOL_KEY) + "://" + interfaceClazz + "?" + Constants.ALIAS_OPTION.getName() + "=" + alias + "&" + Constants.ROLE_OPTION.getName() + "=" + Constants.SIDE_CONSUMER;
}
return name;
}
@Override
public Class getProxyClass() {
if (Boolean.TRUE.equals(generic)) {
if (genericClass == null) {
//获取泛化类名,便于兼容历史版本
String className = GlobalContext.getString(GENERIC_CLASS);
if (className == null || className.isEmpty()) {
genericClass = GenericService.class;
} else {
try {
Class<?> clazz = forName(className);
genericClass = GENERIC.test(clazz) ? clazz : GenericService.class;
} catch (ClassNotFoundException e) {
genericClass = GenericService.class;
}
}
}
return genericClass;
}
return super.getInterfaceClass();
}
public RegistryConfig getRegistry() {
return registry;
}
public void setRegistry(RegistryConfig registry) {
this.registry = registry;
}
@Override
public boolean isSubscribe() {
return subscribe;
}
@Override
public void setSubscribe(boolean subscribe) {
this.subscribe = subscribe;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public Boolean getRetryOnlyOncePerNode() {
return retryOnlyOncePerNode;
}
public void setRetryOnlyOncePerNode(Boolean retryOnlyOncePerNode) {
this.retryOnlyOncePerNode = retryOnlyOncePerNode;
}
public String getFailoverWhenThrowable() {
return failoverWhenThrowable;
}
public void setFailoverWhenThrowable(String failoverWhenThrowable) {
this.failoverWhenThrowable = failoverWhenThrowable;
}
public String getFailoverPredication() {
return failoverPredication;
}
public void setFailoverPredication(String failoverPredication) {
this.failoverPredication = failoverPredication;
}
public String getFailoverSelector() {
return failoverSelector;
}
public void setFailoverSelector(String failoverSelector) {
this.failoverSelector = failoverSelector;
}
public Integer getForks() {
return forks;
}
public void setForks(Integer forks) {
this.forks = forks;
}
public String getLoadbalance() {
return loadbalance;
}
public void setLoadbalance(String loadbalance) {
this.loadbalance = loadbalance;
}
public Boolean getGeneric() {
return generic;
}
public void setGeneric(Boolean generic) {
this.generic = generic;
}
public Boolean getSticky() {
return sticky;
}
public void setSticky(Boolean sticky) {
this.sticky = sticky;
}
public Boolean getCheck() {
return check;
}
public void setCheck(Boolean check) {
this.check = check;
}
public String getSerialization() {
return serialization;
}
public void setSerialization(String serialization) {
this.serialization = serialization;
}
public Boolean getInjvm() {
return injvm;
}
public void setInjvm(Boolean injvm) {
this.injvm = injvm;
}
public String getNodeSelector() {
return nodeSelector;
}
public void setNodeSelector(String nodeSelector) {
this.nodeSelector = nodeSelector;
}
public Integer getInitSize() {
return initSize;
}
public void setInitSize(Integer initSize) {
this.initSize = initSize;
}
public Integer getMinSize() {
return minSize;
}
public void setMinSize(Integer minSize) {
this.minSize = minSize;
}
public String getCandidature() {
return candidature;
}
public void setCandidature(String candidature) {
this.candidature = candidature;
}
public String getChannelFactory() {
return channelFactory;
}
public void setChannelFactory(String channelFactory) {
this.channelFactory = channelFactory;
}
public T getStub() {
return stub;
}
public Integer getWarmupWeight() {
return warmupWeight;
}
public void setWarmupWeight(Integer warmupWeight) {
this.warmupWeight = warmupWeight;
}
public Integer getWarmupDuration() {
return warmupDuration;
}
public void setWarmupDuration(Integer warmupDuration) {
this.warmupDuration = warmupDuration;
}
/**
* 添加事件监听器
*
* @param handler 事件处理器
*/
public void addEventHandler(final EventHandler<NodeEvent> handler) {
if (handler != null) {
eventHandlers.add(handler);
}
}
/**
* 移除事件监听器
*
* @param handler 事件处理器
*/
public void removeEventHandler(final EventHandler<NodeEvent> handler) {
if (handler != null) {
eventHandlers.remove(handler);
}
}
@Override
protected Map<String, String> addAttribute2Map(Map<String, String> params) {
super.addAttribute2Map(params);
if (url != null) {
try {
addElement2Map(params, Constants.URL_OPTION, URL.encode(url));
} catch (UnsupportedEncodingException e) {
throw new InitializationException("Value of \"url\" value is not encode in consumer config with key " + url + " !", ExceptionCode.COMMON_URL_ENCODING);
}
}
addElement2Map(params, Constants.GENERIC_OPTION, generic);
addElement2Map(params, Constants.ROUTER_OPTION, cluster);
addElement2Map(params, Constants.RETRIES_OPTION, retries);
addElement2Map(params, Constants.RETRY_ONLY_ONCE_PER_NODE_OPTION, retryOnlyOncePerNode);
addElement2Map(params, Constants.FAILOVER_WHEN_THROWABLE_OPTION, failoverWhenThrowable);
addElement2Map(params, Constants.FAILOVER_PREDICATION_OPTION, failoverPredication);
addElement2Map(params, Constants.FAILOVER_SELECTOR_OPTION, failoverSelector);
addElement2Map(params, Constants.FORKS_OPTION, forks);
addElement2Map(params, Constants.LOADBALANCE_OPTION, loadbalance);
addElement2Map(params, Constants.IN_JVM_OPTION, injvm);
addElement2Map(params, Constants.STICKY_OPTION, sticky);
addElement2Map(params, Constants.CHECK_OPTION, check);
addElement2Map(params, Constants.SERIALIZATION_OPTION, serialization);
addElement2Map(params, Constants.NODE_SELECTOR_OPTION, nodeSelector);
addElement2Map(params, Constants.INIT_SIZE_OPTION, initSize);
addElement2Map(params, Constants.MIN_SIZE_OPTION, minSize);
addElement2Map(params, Constants.CANDIDATURE_OPTION, candidature);
addElement2Map(params, Constants.ROLE_OPTION, Constants.SIDE_CONSUMER);
addElement2Map(params, Constants.TIMESTAMP_KEY, String.valueOf(SystemClock.now()));
addElement2Map(params, Constants.CHANNEL_FACTORY_OPTION, channelFactory);
addElement2Map(params, Constants.WARMUP_ORIGIN_WEIGHT_OPTION, warmupWeight);
addElement2Map(params, Constants.WARMUP_DURATION_OPTION, warmupDuration);
return params;
}
/**
* 消费者控制器接口
*/
protected interface ConsumerPilot extends InvocationHandler, StateController<Void> {
}
/**
* 控制器
*/
protected static abstract class AbstractConsumerPilot<T, C extends AbstractConsumerConfig<T>>
extends AbstractController<C> implements ConsumerPilot, EventHandler<StateEvent> {
/**
* 注册中心配置
*/
protected RegistryConfig registry;
/**
* 注册中心地址
*/
protected URL registryUrl;
/**
* 用于注册的地址
*/
protected URL registerUrl;
/**
* 代理类
*/
protected Class<?> proxyClass;
/**
* 调用handler
*/
protected volatile InvokerCaller invocationHandler;
/**
* 等待open结束,invokeHandler初始化
*/
protected CountDownLatch latch = new CountDownLatch(1);
/**
* 构造函数
*
* @param config 配置
*/
public AbstractConsumerPilot(C config) {
super(config);
}
@Override
public void handle(final StateEvent event) {
Throwable e = event.getThrowable();
//控制器事件
switch (event.getType()) {
case StateEvent.START_OPEN:
GlobalContext.getContext();
logger.info(String.format("Start refering consumer %s with bean id %s", config.name(), config.id));
break;
case StateEvent.SUCCESS_OPEN:
logger.info(String.format("Success refering consumer %s with bean id %s", config.name(), config.id));
//触发配置更新
update();
break;
case StateEvent.FAIL_OPEN_ILLEGAL_STATE:
logger.error(String.format("Error occurs while referring %s with bean id %s,caused by state is illegal. ", config.name(), config.id));
break;
case StateEvent.FAIL_OPEN:
logger.error(String.format("Error occurs while referring %s with bean id %s,caused by %s. ", config.name(), config.id, e.getMessage()), e);
break;
case StateEvent.START_CLOSE:
logger.info(String.format("Start unrefering consumer %s with bean id %s", config.name(), config.id));
break;
case StateEvent.SUCCESS_CLOSE:
logger.info("Success unrefering consumer " + config.name());
break;
}
}
@Override
protected boolean isClose() {
return config.isClose(this);
}
@Override
protected boolean isOpened() {
return config.stateMachine.isOpened(this);
}
/**
* 打开
*
* @return CompletableFuture
*/
public CompletableFuture<Void> open() {
CompletableFuture<Void> future = new CompletableFuture<>();
try {
registry = (config.url != null && !config.url.isEmpty()) ?
new RegistryConfig(Constants.FIX_REGISTRY, config.url) :
(config.registry != null ? config.registry : RegistryConfig.DEFAULT_REGISTRY_SUPPLIER.get());
config.validate();
if (config.registry != registry) {
//做一下注册中心验证
registry.validate();
}
//代理接口
proxyClass = config.getProxyClass();
//注册中心地址
registryUrl = parse(registry);
String host = getLocalHost(registryUrl.getString(Constants.ADDRESS_OPTION));
//构造原始URL,调用远程的真实接口名称
url = new URL(GlobalContext.getString(PROTOCOL_KEY), host, 0, config.getInterfaceTarget(), config.addAttribute2Map());
//加上动态配置的服务URL
serviceUrl = configure(null);
doOpen().whenComplete((v, e) -> {
if (e == null) {
future.complete(null);
} else {
future.completeExceptionally(e);
}
});
} catch (Exception e) {
future.completeExceptionally(e);
}
return future;
}
/**
* 打开操作
*
* @return CompletableFuture
*/
protected abstract CompletableFuture<Void> doOpen();
/**
* 关闭
*
* @return CompletableFuture
*/
public CompletableFuture<Void> close() {
Parametric parametric = new MapParametric<>(GlobalContext.getContext());
return close(parametric.getBoolean(Constants.GRACEFULLY_SHUTDOWN_OPTION));
}
@Override
public CompletableFuture<Void> close(boolean gracefully) {
return CompletableFuture.completedFuture(null);
}
@Override
protected CompletableFuture<Void> update(final URL newUrl) {
return CompletableFuture.completedFuture(null);
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
InvokerCaller handler = invocationHandler;
if (handler == null) {
State state = config.stateMachine.getState();
if (state.isOpened()) {
handler = invocationHandler;
if (handler == null) {
throw new RpcException("Consumer config is opening. " + config.name());
}
} else if (state.isClosed()) {
throw new RpcException("Consumer config is closed. " + config.name());
} else if (state.isClosing()) {
throw new RpcException("Consumer config is closing. " + config.name());
} else if (state.isOpening()) {
//等待初始化
latch.await();
}
}
return handler.invoke(proxy, method, args);
}
}
}
| 30.14489 | 209 | 0.603768 |
28f42cf3eb9cb135a18c814d5aae6d14f6110aca | 7,624 | package com.manywords.softworks.tafl.test.mechanics;
import com.manywords.softworks.tafl.Log;
import com.manywords.softworks.tafl.engine.Game;
import com.manywords.softworks.tafl.engine.MoveRecord;
import com.manywords.softworks.tafl.engine.clock.TimeSpec;
import com.manywords.softworks.tafl.rules.Coord;
import com.manywords.softworks.tafl.rules.Rules;
import com.manywords.softworks.tafl.rules.Side;
import com.manywords.softworks.tafl.rules.brandub.Brandub;
import com.manywords.softworks.tafl.test.TaflTest;
import com.manywords.softworks.tafl.ui.UiCallback;
import com.manywords.softworks.tafl.command.CommandResult;
import com.manywords.softworks.tafl.command.player.ExternalEnginePlayer;
import com.manywords.softworks.tafl.command.player.Player;
import com.manywords.softworks.tafl.command.player.external.engine.ExternalEngineHost;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jay on 3/19/16.
*/
public class ExternalEngineHostTest extends TaflTest implements UiCallback {
@Override
public void run() {
PipedInputStream inFromEngine = new PipedInputStream();
PipedOutputStream outToEngine = new PipedOutputStream();
EngineOutputReader r = new EngineOutputReader(inFromEngine, outToEngine);
Rules rules = Brandub.newBrandub7();
Game g = new Game(rules, this, new TimeSpec(0, 30000, 5, 1000));
r.mGame = g;
ExternalEnginePlayer dummyPlayer = new ExternalEnginePlayer();
dummyPlayer.setGame(g);
dummyPlayer.setupTestEngine(this, r.mInputStream, r.mOutputStream);
ExternalEngineHost h = dummyPlayer.getExternalEngineHost();
r.start();
h.setGame(g);
h.move(g.getCurrentState());
h.error(1);
h.analyzePosition(5, 30, g.getCurrentState());
h.side(true);
h.position(g.getCurrentState());
h.clockUpdate();
h.playForCurrentSide(g);
List<MoveRecord> moves = new ArrayList<>();
moves.add(new MoveRecord(Coord.get(0, 0), Coord.get(0, 4)));
h.notifyMovesMade(moves);
h.finish();
h.goodbye();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.mRunning = false;
Log.println(Log.Level.VERBOSE, "Rules: " + r.mRulesResponse);
Log.println(Log.Level.VERBOSE, "Move: " + r.mMoveResponse);
Log.println(Log.Level.VERBOSE, "Error: " + r.mErrorResponse);
Log.println(Log.Level.VERBOSE, "Analyze: " + r.mAnalyzeResponse);
Log.println(Log.Level.VERBOSE, "Side: " + r.mSideResponse);
Log.println(Log.Level.VERBOSE, "Position: " + r.mPositionResponse);
Log.println(Log.Level.VERBOSE, "Clock: " + r.mClockResponse);
Log.println(Log.Level.VERBOSE, "Play: " + r.mPlayResponse);
Log.println(Log.Level.VERBOSE, "Opponent Move: " + r.mOpponentMoveResponse);
Log.println(Log.Level.VERBOSE, "Finish: " + r.mFinishResponse);
Log.println(Log.Level.VERBOSE, "Goodbye: " + r.mGoodbyeResponse);
assert r.didTestPass();
}
private class EngineOutputReader extends Thread {
public Game mGame;
public PipedInputStream mInputStream;
public PipedOutputStream mOutputStream;
public EngineOutputReader(PipedInputStream inFromEngine, PipedOutputStream outToEngine) {
mInputStream = inFromEngine;
mOutputStream = outToEngine;
}
public boolean mRunning = true;
private boolean mRulesResponse = false;
private boolean mMoveResponse = false;
private boolean mErrorResponse = false;
private boolean mAnalyzeResponse = false;
private boolean mSideResponse = false;
private boolean mPositionResponse = false;
private boolean mClockResponse = false;
private boolean mPlayResponse = false;
private boolean mOpponentMoveResponse = false;
private boolean mFinishResponse = false;
private boolean mGoodbyeResponse = false;
public boolean didTestPass() {
return mRulesResponse &&
mMoveResponse &&
mErrorResponse &&
mAnalyzeResponse &&
mSideResponse &&
mPositionResponse &&
mClockResponse &&
mPlayResponse &&
mOpponentMoveResponse &&
mFinishResponse &&
mGoodbyeResponse;
}
@Override
public void run() {
byte[] buffer = new byte[1024];
while(mRunning) {
try {
int count = mInputStream.read(buffer);
if(count == -1) {
mRunning = false;
break;
}
String string = new String(buffer);
String[] commands = string.split("\n");
for(String command : commands) {
Log.println(Log.Level.VERBOSE, "Received command: " + command);
if(command.startsWith("rules dim:7 name:Brandub surf:n atkf:y ks:w cenh: cenhe: start:/3t3/3t3/3T3/ttTKTtt/3T3/3t3/3t3/")) {
mRulesResponse = true;
}
else if(command.startsWith("move /3t3/3t3/3T3/ttTKTtt/3T3/3t3/3t3/")) {
mMoveResponse = true;
}
else if(command.startsWith("error 1")) mErrorResponse = true;
else if(command.startsWith("analyze 5 30")) mAnalyzeResponse = true;
else if(command.startsWith("side attackers")) mSideResponse = true;
else if(command.startsWith("position /3t3/3t3/3T3/ttTKTtt/3T3/3t3/3t3/")) {
mPositionResponse = true;
}
else if(command.startsWith("clock 30000* 30000* 30 5 5")) {
mClockResponse = true;
}
else if(command.startsWith("play attackers")) mPlayResponse = true;
else if(command.startsWith("opponent-move a1-a5 /3t3/3t3/3T3/ttTKTtt/3T3/3t3/3t3/")) mOpponentMoveResponse = true;
else if(command.startsWith("finish 0")) mFinishResponse = true;
else if(command.startsWith("goodbye")) mGoodbyeResponse = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void gameStarting() {
}
@Override
public void modeChanging(Mode mode, Object gameObject) {
}
@Override
public void awaitingMove(Player player, boolean isAttackingSide) {
}
@Override
public void timeUpdate(boolean currentSideAttackers) {
}
@Override
public void moveResult(CommandResult result, MoveRecord move) {
}
@Override
public void statusText(String text) {
}
@Override
public void modalStatus(String title, String text) {
}
@Override
public void gameStateAdvanced() {
}
@Override
public void victoryForSide(Side side) {
}
@Override
public void gameFinished() {
}
@Override
public MoveRecord waitForHumanMoveInput() {
return null;
}
@Override
public boolean inGame() {
return false;
}
}
| 33.292576 | 148 | 0.595357 |
cf1a29d7279946c6f9e8605311d277b4e3c72542 | 402 | package com.sunny.shop.service.user.api;
import com.sunny.base.ReturnResult;
import org.springframework.stereotype.Component;
@Component
public class UserFeignFallBack implements UserFeignApi{
@Override
public ReturnResult getByUserName(String userName) {
return null;
}
@Override
public ReturnResult loadUserByUserName(String userName) {
return null;
}
}
| 19.142857 | 61 | 0.736318 |
4e63d964bef1bbca611c29cd5a0e7d68d77506c8 | 8,034 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.ws.rx.rm;
import static com.sun.xml.ws.rx.rm.ReliableMessagingFeature.*;
/**
*
* @author Marek Potociar <marek.potociar at sun.com>
*/
public final class ReliableMessagingFeatureBuilder {
// General RM config values
private final RmVersion version;
private boolean enabled = true;
private long inactivityTimeout = DEFAULT_SEQUENCE_INACTIVITY_TIMEOUT;
private long destinationBufferQuota = DEFAULT_DESTINATION_BUFFER_QUOTA;
private boolean orderedDelivery = false;
private DeliveryAssurance deliveryAssurance = DeliveryAssurance.getDefault();
private SecurityBinding securityBinding = SecurityBinding.getDefault();
//
private long messageRetransmissionInterval = DEFAULT_MESSAGE_RETRANSMISSION_INTERVAL;
private BackoffAlgorithm retransmissionBackoffAlgorithm = BackoffAlgorithm.getDefault();
private long maxMessageRetransmissionCount = DEFAULT_MAX_MESSAGE_RETRANSMISSION_COUNT;
//
private long ackTransmittionInterval = DEFAULT_ACKNOWLEDGEMENT_TRANSMISSION_INTERVAL;
private long ackRequestTransmissionInterval = DEFAULT_ACK_REQUEST_TRANSMISSION_INTERVAL;
private long closeSequenceOperationTimeout = DEFAULT_CLOSE_SEQUENCE_OPERATION_TIMEOUT;
private boolean persistenceEnabled = false;
private long sequenceMaintenancePeriod = DEFAULT_SEQUENCE_MANAGER_MAINTENANCE_PERIOD;
private long maxConcurrentSessions = DEFAULT_MAX_CONCURRENT_SESSIONS;
public ReliableMessagingFeatureBuilder(RmVersion version) {
this.version = version;
}
public ReliableMessagingFeature build() {
return new ReliableMessagingFeature(
this.enabled,
this.version,
this.inactivityTimeout,
this.destinationBufferQuota,
this.orderedDelivery,
this.deliveryAssurance,
this.securityBinding,
this.messageRetransmissionInterval,
this.retransmissionBackoffAlgorithm,
this.maxMessageRetransmissionCount,
this.ackTransmittionInterval,
this.ackRequestTransmissionInterval,
this.closeSequenceOperationTimeout,
this.persistenceEnabled,
this.sequenceMaintenancePeriod,
this.maxConcurrentSessions);
}
/**
* @see ReliableMessagingFeature#getAcknowledgementTransmissionInterval()
*/
public ReliableMessagingFeatureBuilder acknowledgementTransmittionInterval(long value) {
this.ackTransmittionInterval = value;
return this;
}
/**
* @see ReliableMessagingFeature#getAckRequestTransmissionInterval()
*/
public ReliableMessagingFeatureBuilder ackRequestTransmissionInterval(long value) {
this.ackRequestTransmissionInterval = value;
return this;
}
/**
* @see ReliableMessagingFeature#getMessageRetransmissionInterval()
*/
public ReliableMessagingFeatureBuilder messageRetransmissionInterval(long value) {
this.messageRetransmissionInterval = value;
return this;
}
/**
* @see ReliableMessagingFeature#getRetransmissionBackoffAlgorithm()
*/
public ReliableMessagingFeatureBuilder retransmissionBackoffAlgorithm(BackoffAlgorithm value) {
this.retransmissionBackoffAlgorithm = value;
return this;
}
/**
* @see ReliableMessagingFeature#getMaxMessageRetransmissionCount()
*/
public ReliableMessagingFeatureBuilder maxMessageRetransmissionCount(long value) {
this.maxMessageRetransmissionCount = value;
return this;
}
/**
* @see ReliableMessagingFeature#getDestinationBufferQuota()
*/
public ReliableMessagingFeatureBuilder destinationBufferQuota(long value) {
this.destinationBufferQuota = value;
return this;
}
/**
* @see ReliableMessagingFeature#getCloseSequenceOperationTimeout()
*/
public ReliableMessagingFeatureBuilder closeSequenceOperationTimeout(long value) {
this.closeSequenceOperationTimeout = value;
return this;
}
/**
* @see ReliableMessagingFeature#getDeliveryAssurance()
*/
public ReliableMessagingFeatureBuilder deliveryAssurance(DeliveryAssurance value) {
this.deliveryAssurance = value;
return this;
}
/**
* @see ReliableMessagingFeature#getSequenceInactivityTimeout()
*/
public ReliableMessagingFeatureBuilder sequenceInactivityTimeout(long value) {
this.inactivityTimeout = value;
return this;
}
/**
* @see ReliableMessagingFeature#isOrderedDeliveryEnabled()
*/
public ReliableMessagingFeatureBuilder enableOrderedDelivery() {
this.orderedDelivery = true;
return this;
}
/**
* @see ReliableMessagingFeature#getVersion()
*/
public RmVersion getVersion() {
return this.version;
}
/**
* @see ReliableMessagingFeature#getSecurityBinding()
*/
public ReliableMessagingFeatureBuilder securityBinding(SecurityBinding value) {
this.securityBinding = value;
return this;
}
/**
* @see ReliableMessagingFeature#isPersistenceEnabled()
*/
public ReliableMessagingFeatureBuilder enablePersistence() {
this.persistenceEnabled = true;
return this;
}
/**
* @see ReliableMessagingFeature#isPersistenceEnabled()
*/
public ReliableMessagingFeatureBuilder disablePersistence() {
this.persistenceEnabled = false;
return this;
}
/**
* @see ReliableMessagingFeature#getSequenceManagerMaintenancePeriod()
*/
public ReliableMessagingFeatureBuilder sequenceMaintenancePeriod(long value) {
this.sequenceMaintenancePeriod = value;
return this;
}
/**
* @see ReliableMessagingFeature#getMaxConcurrentSessions()
*/
public ReliableMessagingFeatureBuilder maxConcurrentSessions(long value) {
this.maxConcurrentSessions = value;
return this;
}
}
| 36.853211 | 99 | 0.717824 |
1583a93d7c6e7bcf9cfeebfe66257ef9fe7172cc | 456 | package com.jerusalem.goods.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jerusalem.goods.entity.SpuInfoDescEntity;
/****
* 服务层接口
* spu信息介绍
* @author jerusalem
* @email [email protected]
* @date 2020-04-09 14:48:19
*/
public interface SpuInfoDescService extends IService<SpuInfoDescEntity> {
/***
* 保存SPU描述图片
* @param spuInfoDesc
*/
void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDesc);
}
| 19.826087 | 73 | 0.725877 |
1af82abb55fd08c7dd4fea98d43ef82c03b84ad4 | 7,162 | /*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.sparse.csc.misc;
import org.ejml.data.DGrowArray;
import org.ejml.data.DMatrixSparseCSC;
import org.ejml.data.IGrowArray;
import org.ejml.masks.Mask;
import org.ejml.ops.DSemiRing;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import static org.ejml.UtilEjml.adjust;
import static org.ejml.sparse.csc.mult.ImplMultiplicationWithSemiRing_DSCC.multAddColA;
/**
* based on ImplCommonOps_DSCC
*/
public class ImplCommonOpsWithSemiRing_DSCC {
/**
* Performs matrix addition:<br>
* C = A + B
*
* @param A Matrix
* @param B Matrix
* @param C Output matrix.
* @param semiRing Semi-Ring to define + and *
* @param mask (Optional) Mask for specifying which entries should be overwritten
* @param gw (Optional) Storage for internal workspace. Can be null.
* @param gx (Optional) Storage for internal workspace. Can be null.
*/
public static void add( double alpha, DMatrixSparseCSC A, double beta, DMatrixSparseCSC B, DMatrixSparseCSC C, DSemiRing semiRing,
@Nullable Mask mask, @Nullable IGrowArray gw, @Nullable DGrowArray gx ) {
double[] x = adjust(gx, A.numRows);
int[] w = adjust(gw, A.numRows, A.numRows);
C.indicesSorted = false;
C.nz_length = 0;
for (int col = 0; col < A.numCols; col++) {
C.col_idx[col] = C.nz_length;
if (mask != null) {
mask.setIndexColumn(col);
}
multAddColA(A, col, alpha, C, col + 1, semiRing, mask, x, w);
multAddColA(B, col, beta, C, col + 1, semiRing, mask, x, w);
// take the values in the dense vector 'x' and put them into 'C'
int idxC0 = C.col_idx[col];
int idxC1 = C.col_idx[col + 1];
for (int i = idxC0; i < idxC1; i++) {
C.nz_values[i] = x[C.nz_rows[i]];
}
}
C.col_idx[A.numCols] = C.nz_length;
}
/**
* Adds the results of adding a column in A and B as a new column in C.<br>
* C(:,end+1) = A(:,colA) + B(:,colB)
*
* @param A matrix
* @param colA column in A
* @param B matrix
* @param colB column in B
* @param C Column in C
* @param semiRing Semi-Ring to define + and *
* @param gw workspace
*/
public static void addColAppend( DMatrixSparseCSC A, int colA, DMatrixSparseCSC B, int colB,
DMatrixSparseCSC C, DSemiRing semiRing, @Nullable IGrowArray gw ) {
if (A.numRows != B.numRows || A.numRows != C.numRows)
throw new IllegalArgumentException("Number of rows in A, B, and C do not match");
int idxA0 = A.col_idx[colA];
int idxA1 = A.col_idx[colA + 1];
int idxB0 = B.col_idx[colB];
int idxB1 = B.col_idx[colB + 1];
C.growMaxColumns(++C.numCols, true);
C.growMaxLength(C.nz_length + idxA1 - idxA0 + idxB1 - idxB0, true);
int[] w = adjust(gw, A.numRows);
Arrays.fill(w, 0, A.numRows, -1);
for (int i = idxA0; i < idxA1; i++) {
int row = A.nz_rows[i];
C.nz_rows[C.nz_length] = row;
C.nz_values[C.nz_length] = A.nz_values[i];
w[row] = C.nz_length++;
}
for (int i = idxB0; i < idxB1; i++) {
int row = B.nz_rows[i];
if (w[row] != -1) {
C.nz_values[w[row]] = semiRing.add.func.apply(C.nz_values[w[row]], B.nz_values[i]);
} else {
C.nz_values[C.nz_length] = B.nz_values[i];
C.nz_rows[C.nz_length++] = row;
}
}
C.col_idx[C.numCols] = C.nz_length;
}
/**
* Performs element-wise multiplication:<br>
* C_ij = A_ij * B_ij
*
* @param A (Input) Matrix
* @param B (Input) Matrix
* @param C (Output) Matrix.
* @param semiRing Semi-Ring to define + and *
* @param mask (Optional) Mask for specifying which entries should be overwritten
* @param gw (Optional) Storage for internal workspace. Can be null.
* @param gx (Optional) Storage for internal workspace. Can be null.
*/
public static void elementMult( DMatrixSparseCSC A, DMatrixSparseCSC B, DMatrixSparseCSC C, DSemiRing semiRing,
@Nullable Mask mask, @Nullable IGrowArray gw, @Nullable DGrowArray gx ) {
double[] x = adjust(gx, A.numRows);
int[] w = adjust(gw, A.numRows);
Arrays.fill(w, 0, A.numRows, -1); // fill with -1. This will be a value less than column
int maxMaskEntries = Integer.MAX_VALUE;
if (mask != null) {
maxMaskEntries = mask.maxMaskedEntries();
}
C.growMaxLength(Math.min(maxMaskEntries, Math.min(A.nz_length, B.nz_length)), false);
C.indicesSorted = false; // Hmm I think if B is storted then C will be sorted...
C.nz_length = 0;
for (int col = 0; col < A.numCols; col++) {
int idxA0 = A.col_idx[col];
int idxA1 = A.col_idx[col + 1];
int idxB0 = B.col_idx[col];
int idxB1 = B.col_idx[col + 1];
// compute the maximum number of elements that there can be in this row
int maxInRow = Math.min(idxA1 - idxA0, idxB1 - idxB0);
int expectedResultSize = C.nz_length + maxInRow;
// make sure there are enough non-zero elements in C
if (expectedResultSize > C.nz_values.length) {
C.growMaxLength(Math.min(maxMaskEntries, expectedResultSize), true);
}
// update the structure of C
C.col_idx[col] = C.nz_length;
// mark the rows that appear in A and save their value
for (int i = idxA0; i < idxA1; i++) {
int row = A.nz_rows[i];
w[row] = col;
x[row] = A.nz_values[i];
}
// If a row appears in A and B, multiply and set as an element in C
for (int i = idxB0; i < idxB1; i++) {
int row = B.nz_rows[i];
if (mask == null || mask.isSet(row, col)) {
if (w[row] == col) {
C.nz_values[C.nz_length] = semiRing.mult.func.apply(x[row], B.nz_values[i]);
C.nz_rows[C.nz_length++] = row;
}
}
}
}
C.col_idx[C.numCols] = C.nz_length;
}
}
| 37.302083 | 134 | 0.572745 |
e3b4336e176a83451e4985f17783211b9bc739b4 | 4,392 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.contacts.model.account;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.IntentFilter;
import android.content.Loader;
import android.os.Bundle;
import com.android.contacts.model.AccountTypeManager;
import com.android.contacts.util.concurrent.ListenableFutureLoader;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.List;
/**
* Loads the accounts from AccountTypeManager
*/
public class AccountsLoader extends ListenableFutureLoader<List<AccountInfo>> {
private final AccountTypeManager mAccountTypeManager;
private final Predicate<AccountInfo> mFilter;
public AccountsLoader(Context context) {
this(context, Predicates.<AccountInfo>alwaysTrue());
}
public AccountsLoader(Context context, Predicate<AccountInfo> filter) {
super(context, new IntentFilter(AccountTypeManager.BROADCAST_ACCOUNTS_CHANGED));
mAccountTypeManager = AccountTypeManager.getInstance(context);
mFilter = filter;
}
@Override
protected ListenableFuture<List<AccountInfo>> loadData() {
return mAccountTypeManager.filterAccountsAsync(mFilter);
}
@Override
protected boolean isSameData(List<AccountInfo> previous, List<AccountInfo> next) {
return Objects.equal(AccountInfo.extractAccounts(previous),
AccountInfo.extractAccounts(next));
}
public interface AccountsListener {
void onAccountsLoaded(List<AccountInfo> accounts);
}
/**
* Loads the accounts into the target fragment using {@link LoaderManager}
*
* <p>This is a convenience method to reduce the
* boilerplate needed when implementing {@link android.app.LoaderManager.LoaderCallbacks}
* in the simple case that the fragment wants to just load the accounts directly</p>
* <p>Note that changing the filter between invocations in the same component will not work
* properly because the loader is cached.</p>
*/
public static <FragmentType extends Fragment & AccountsListener> void loadAccounts(
final FragmentType fragment, int loaderId, final Predicate<AccountInfo> filter) {
loadAccounts(
fragment.getActivity(), fragment.getLoaderManager(), loaderId, filter, fragment);
}
/**
* Same as {@link #loadAccounts(Fragment, int, Predicate)} for an Activity
*/
public static <ActivityType extends Activity & AccountsListener> void loadAccounts(
final ActivityType activity, int id, final Predicate<AccountInfo> filter) {
loadAccounts(activity, activity.getLoaderManager(), id, filter, activity);
}
private static void loadAccounts(final Context context, LoaderManager loaderManager, int id,
final Predicate<AccountInfo> filter, final AccountsListener listener) {
loaderManager.initLoader(id, null,
new LoaderManager.LoaderCallbacks<List<AccountInfo>>() {
@Override
public Loader<List<AccountInfo>> onCreateLoader(int id, Bundle args) {
return new AccountsLoader(context, filter);
}
@Override
public void onLoadFinished(
Loader<List<AccountInfo>> loader, List<AccountInfo> data) {
listener.onAccountsLoaded(data);
}
@Override
public void onLoaderReset(Loader<List<AccountInfo>> loader) {
}
});
}
}
| 39.214286 | 97 | 0.693078 |
8723b0070885caad21a9daef331187b9ccdf8058 | 1,478 | /**
* Copyright 2019 Jordan Zimmerman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.myco.app.request;
import com.myco.app.logging.Logging;
import com.myco.app.logging.LoggingSchema;
import io.soabase.maple.slf4j.MapleLogger;
import java.util.UUID;
import static com.myco.app.logging.LoggingEventType.CUSTOMER_REQUEST;
import static com.myco.app.logging.LoggingEventType.USER_REQUEST;
/**
* Example of a request handler
*/
public class RequestHandler {
private final MapleLogger<LoggingSchema> logger = Logging.get(getClass());
public void processCustomerRequest(UUID requestId, UUID customerId) {
logger.info(s -> s.event(CUSTOMER_REQUEST).requestId(requestId).customerId(customerId));
// etc etc handle the request
}
public void processUserRequest(UUID requestId, UUID userId) {
logger.info(s -> s.event(USER_REQUEST).requestId(requestId).userId(userId));
// etc etc handle the request
}
}
| 32.844444 | 96 | 0.743572 |
b3dac5a68ab60f3d8f0f0f3cb922c7e0d1f6d8e3 | 1,445 | /**
* Copyright 2019 SPeCS.
*
* 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. under the License.
*/
package pt.up.fe.specs.ant;
import java.io.File;
import org.junit.Test;
import pt.up.fe.specs.ant.tasks.Sftp;
import pt.up.fe.specs.util.SpecsIo;
public class TasksTest {
@Test
public void testSftp() {
// Create dummy file for transfer
File dummyFile = new File("dummmy_file.txt");
SpecsIo.write(dummyFile, "dummy");
AntTask sftpTask = new Sftp()
.set(Sftp.LOGIN, "login")
.set(Sftp.PASS, "pass")
.set(Sftp.HOST, "host")
.set(Sftp.PORT, "port")
.set(Sftp.DESTINATION_FOLDER, "destinationFolder")
.set(Sftp.NEW_FILENAME, "new_name.txt")
.set(Sftp.FILE_TO_TRANSFER, dummyFile);
System.out.println("Output:\n" + sftpTask.getScript());
SpecsIo.delete(dummyFile);
}
}
| 31.413043 | 118 | 0.649827 |
df767ed02fc8923f81def87b3ccacf0b69ed7321 | 2,107 | package com.ptong.worldcities.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
public class FileUtils {
private static final Charset CHARSET = Charset.forName("UTF-8");
private static final String RESOURCE_FOLDER = "src/test/resources";
public static String getResourcesFolder() {
File file = new File(RESOURCE_FOLDER);
String absolutePath = file.getAbsolutePath();
return absolutePath;
}
public static String getResourcesFolder(String countryCode) {
String path = RESOURCE_FOLDER + File.separator + countryCode;
File file = new File(path);
String absolutePath = file.getAbsolutePath() + File.separator;
return absolutePath;
}
public static void writeToFile(String filePath, String content) throws IOException {
OutputStreamWriter osw = null;
File file = new File(filePath);
BufferedWriter bufw = null;
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
osw = new OutputStreamWriter(new FileOutputStream(file, false), CHARSET);
bufw = new BufferedWriter(osw);
bufw.write(content);
bufw.flush();
bufw.close();
}
public static String readFile(String filePath) throws IOException {
StringBuffer sb = new StringBuffer();
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException();
}
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), CHARSET));
String str;
while ((str = in.readLine()) != null) {
sb.append(str + System.lineSeparator());
}
in.close();
return sb.toString();
}
} | 32.921875 | 106 | 0.655909 |
0917f62011ef37edbd8e30b2d5947cce756d0776 | 563 | package com.yr.net.app.base.service;
import com.yr.net.app.base.entity.TagInfo;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yr.net.app.common.exception.AppException;
import java.util.List;
/**
* @author dengbp
*/
public interface ITagInfoService extends IService<TagInfo> {
/**
* Description 性格类数据查询
* @param
* @return java.util.List<com.yr.net.app.base.entity.TagInfo>
* @throws AppException
* @Author dengbp
* @Date 2:14 AM 2/16/21
**/
List<TagInfo> character()throws AppException;
}
| 22.52 | 65 | 0.69627 |
2c9b9a50545060bd6db540bde72ecd5db960ad86 | 106 | package com.mypurecloud.sdk.v2;
public enum DetailLevel {
NONE,
MINIMAL,
HEADERS,
FULL
}
| 11.777778 | 31 | 0.650943 |
73104697712e8a3a50e8e594f3f8cbc83e29f086 | 887 | package it.unipi.di.acube.semanticview;
import java.io.Serializable;
import java.util.Comparator;
import java.util.TreeSet;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
public class Utils {
public static <K extends Comparable<? super K>> Comparator<Entry<K>> comparingEntryByCount() {
return (Comparator<Entry<K>> & Serializable) (e1, e2) -> Integer.compare(e1.getCount(), e2.getCount());
}
public static <E extends Comparable<? super E>> TreeSet<Entry<E>> getTopK(Multiset<E> s, int k) {
Comparator<Entry<E>> comp = comparingEntryByCount();
TreeSet<Entry<E>> res = new TreeSet<>(comp);
for (Entry<E> e : s.entrySet()) {
if (res.size() < k)
res.add(e);
else {
Entry<E> lowest = res.first();
if (lowest.getCount() < e.getCount()) {
res.remove(lowest);
res.add(e);
}
}
}
return res;
}
}
| 27.71875 | 105 | 0.673055 |
8eb56221d2d2afd87878e9ebc5f15e0310a19ae8 | 542 | import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import service.UserService;
/**
* @Description:
* @Author: Kevin
* @Create 2020-01-06 08:55
*/
@RestController
public class UserController {
@Reference(version = "1.0.0", url = "dubbo://127.0.0.1:12345")
private UserService userService;
@RequestMapping("/sayHello")
public String sayHello() {
return userService.sayHello();
}
}
| 24.636364 | 66 | 0.723247 |
dc7505c96559bac4c5e6503b068ced056bf258e8 | 983 | package leetcode.weekly_contests.weekly_238;
public class P_1839 {
public int longestBeautifulSubstring(String word) {
final String vowels = "aeiou";
int res = 0;
final int n = word.length();
final char[] w = word.toCharArray();
for (int i = 0; i < n; i++) {
if (w[i] == 'a') {
int j = i;
int k = 0;
boolean ok = true;
while (k < 5) {
while (j < n && w[j] == vowels.charAt(k)) {
j++;
}
if (k == 4 || j < n && w[j] == vowels.charAt(k + 1)) {
k++;
} else {
ok = false;
break;
}
}
if (ok) {
res = Math.max(res, j - i);
}
i = j - 1;
}
}
return res;
}
}
| 28.085714 | 74 | 0.318413 |
30391eaa27de444755ba3b7562ca223128dd2273 | 55,071 | package core.ast.decomposition;
import com.intellij.lang.jvm.JvmModifier;
import com.intellij.lang.jvm.types.JvmReferenceType;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import core.ast.Access;
import core.ast.AnonymousClassDeclarationObject;
import core.ast.ArrayCreationObject;
import core.ast.ClassInstanceCreationObject;
import core.ast.ConstructorInvocationObject;
import core.ast.ConstructorObject;
import core.ast.CreationObject;
import core.ast.FieldInstructionObject;
import core.ast.FieldObject;
import core.ast.LiteralObject;
import core.ast.LocalVariableDeclarationObject;
import core.ast.LocalVariableInstructionObject;
import core.ast.MethodInvocationObject;
import core.ast.MethodObject;
import core.ast.ParameterObject;
import core.ast.SuperFieldInstructionObject;
import core.ast.SuperMethodInvocationObject;
import core.ast.TypeObject;
import core.ast.decomposition.cfg.AbstractVariable;
import core.ast.decomposition.cfg.PlainVariable;
import core.ast.util.MethodDeclarationUtility;
import java.util.*;
public abstract class AbstractMethodFragment {
private final AbstractMethodFragment parent;
private final List<MethodInvocationObject> methodInvocationList;
private final List<SuperMethodInvocationObject> superMethodInvocationList;
private final List<ConstructorInvocationObject> constructorInvocationList;
private final List<FieldInstructionObject> fieldInstructionList;
private final List<SuperFieldInstructionObject> superFieldInstructionList;
private final List<LocalVariableDeclarationObject> localVariableDeclarationList;
private final List<LocalVariableInstructionObject> localVariableInstructionList;
private final List<CreationObject> creationList;
private final List<LiteralObject> literalList;
private final List<AnonymousClassDeclarationObject> anonymousClassDeclarationList;
private final Set<String> exceptionsInThrowStatements;
private final Map<AbstractVariable, ArrayList<MethodInvocationObject>> nonDistinctInvokedMethodsThroughFields;
private final Map<AbstractVariable, ArrayList<MethodInvocationObject>> nonDistinctInvokedMethodsThroughParameters;
private final Map<AbstractVariable, ArrayList<MethodInvocationObject>> nonDistinctInvokedMethodsThroughLocalVariables;
private final List<MethodInvocationObject> nonDistinctInvokedMethodsThroughThisReference;
private final List<MethodInvocationObject> nonDistinctInvokedStaticMethods;
private final List<AbstractVariable> nonDistinctDefinedFieldsThroughFields;
private final List<AbstractVariable> nonDistinctUsedFieldsThroughFields;
private final List<AbstractVariable> nonDistinctDefinedFieldsThroughParameters;
private final List<AbstractVariable> nonDistinctUsedFieldsThroughParameters;
private final List<AbstractVariable> nonDistinctDefinedFieldsThroughLocalVariables;
private final List<AbstractVariable> nonDistinctUsedFieldsThroughLocalVariables;
private final List<PlainVariable> nonDistinctDefinedFieldsThroughThisReference;
private final List<PlainVariable> nonDistinctUsedFieldsThroughThisReference;
private final Set<PlainVariable> declaredLocalVariables;
private final Set<PlainVariable> definedLocalVariables;
private final Set<PlainVariable> usedLocalVariables;
private final Map<PlainVariable, LinkedHashSet<MethodInvocationObject>> parametersPassedAsArgumentsInMethodInvocations;
private final Map<PlainVariable, LinkedHashSet<SuperMethodInvocationObject>> parametersPassedAsArgumentsInSuperMethodInvocations;
private final Map<PlainVariable, LinkedHashSet<ConstructorInvocationObject>> parametersPassedAsArgumentsInConstructorInvocations;
private final Map<PlainVariable, LinkedHashSet<ClassInstanceCreationObject>> variablesAssignedWithClassInstanceCreations;
AbstractMethodFragment(AbstractMethodFragment parent) {
this.parent = parent;
this.methodInvocationList = new ArrayList<>();
this.superMethodInvocationList = new ArrayList<>();
this.constructorInvocationList = new ArrayList<>();
this.fieldInstructionList = new ArrayList<>();
this.superFieldInstructionList = new ArrayList<>();
this.localVariableDeclarationList = new ArrayList<>();
this.localVariableInstructionList = new ArrayList<>();
this.creationList = new ArrayList<>();
this.literalList = new ArrayList<>();
this.anonymousClassDeclarationList = new ArrayList<>();
this.exceptionsInThrowStatements = new LinkedHashSet<>();
this.nonDistinctInvokedMethodsThroughFields = new LinkedHashMap<>();
this.nonDistinctInvokedMethodsThroughParameters = new LinkedHashMap<>();
this.nonDistinctInvokedMethodsThroughLocalVariables = new LinkedHashMap<>();
this.nonDistinctInvokedMethodsThroughThisReference = new ArrayList<>();
this.nonDistinctInvokedStaticMethods = new ArrayList<>();
this.nonDistinctDefinedFieldsThroughFields = new ArrayList<>();
this.nonDistinctUsedFieldsThroughFields = new ArrayList<>();
this.nonDistinctDefinedFieldsThroughParameters = new ArrayList<>();
this.nonDistinctUsedFieldsThroughParameters = new ArrayList<>();
this.nonDistinctDefinedFieldsThroughLocalVariables = new ArrayList<>();
this.nonDistinctUsedFieldsThroughLocalVariables = new ArrayList<>();
this.nonDistinctDefinedFieldsThroughThisReference = new ArrayList<>();
this.nonDistinctUsedFieldsThroughThisReference = new ArrayList<>();
this.declaredLocalVariables = new LinkedHashSet<>();
this.definedLocalVariables = new LinkedHashSet<>();
this.usedLocalVariables = new LinkedHashSet<>();
this.parametersPassedAsArgumentsInMethodInvocations = new LinkedHashMap<>();
this.parametersPassedAsArgumentsInSuperMethodInvocations = new LinkedHashMap<>();
this.parametersPassedAsArgumentsInConstructorInvocations = new LinkedHashMap<>();
this.variablesAssignedWithClassInstanceCreations = new LinkedHashMap<>();
}
public AbstractMethodFragment getParent() {
return this.parent;
}
void processVariables(List<PsiExpression> variableInstructions, List<PsiExpression> assignments,
List<PsiExpression> postfixExpressions, List<PsiExpression> prefixExpressions) {
for (PsiExpression variableInstruction : variableInstructions) {
if (variableInstruction instanceof PsiReferenceExpression) {
PsiReferenceExpression psiReference = (PsiReferenceExpression) variableInstruction;
PsiElement resolvedElement = psiReference.resolve();
if (resolvedElement instanceof PsiField) {
PsiField psiField = (PsiField) resolvedElement;
if (psiField.getContainingClass() != null) {
String originClassName = PsiUtil.getMemberQualifiedName(psiField.getContainingClass());
String fieldType = psiField.getType().getCanonicalText();
TypeObject typeObject = TypeObject.extractTypeObject(fieldType);
String fieldName = psiField.getName();
if (originClassName != null && !originClassName.equals("")) {
if (variableInstruction instanceof PsiSuperExpression) {
SuperFieldInstructionObject superFieldInstruction = new SuperFieldInstructionObject(originClassName, typeObject, fieldName);
superFieldInstruction.setSimpleName(resolvedElement);
if ((psiField.hasModifier(JvmModifier.STATIC)))
superFieldInstruction.setStatic(true);
addSuperFieldInstruction(superFieldInstruction);
} else {
FieldInstructionObject fieldInstruction = new FieldInstructionObject(originClassName, typeObject, fieldName);
fieldInstruction.setElement(resolvedElement);
if ((psiField.hasModifier(JvmModifier.STATIC)))
fieldInstruction.setStatic(true);
addFieldInstruction(fieldInstruction);
Set<PsiAssignmentExpression> fieldAssignments = getMatchingAssignments(psiField, assignments);
Set<PsiPostfixExpression> fieldPostfixAssignments = getMatchingPostfixAssignments(psiField, postfixExpressions);
Set<PsiPrefixExpression> fieldPrefixAssignments = getMatchingPrefixAssignments(psiField, prefixExpressions);
AbstractVariable variable = MethodDeclarationUtility.createVariable(psiField, null);
if (!fieldAssignments.isEmpty()) {
handleDefinedField(variable);
for (PsiAssignmentExpression assignment : fieldAssignments) {
PsiJavaToken operator = assignment.getOperationSign();
if (!JavaTokenType.EQ.equals(operator.getTokenType()))
handleUsedField(variable);
}
}
if (!fieldPostfixAssignments.isEmpty()) {
handleDefinedField(variable);
handleUsedField(variable);
}
if (!fieldPrefixAssignments.isEmpty()) {
handleDefinedField(variable);
handleUsedField(variable);
}
if (fieldAssignments.isEmpty() && fieldPostfixAssignments.isEmpty() && fieldPrefixAssignments.isEmpty()) {
handleUsedField(variable);
}
}
}
}
} else if (resolvedElement instanceof PsiLocalVariable) {
PsiLocalVariable resolvedVariable = (PsiLocalVariable) resolvedElement;
String variableName = resolvedVariable.getName();
String variableType = resolvedVariable.getType().getCanonicalText();
TypeObject localVariableType = TypeObject.extractTypeObject(variableType);
PlainVariable variable = new PlainVariable(resolvedVariable);
LocalVariableInstructionObject localVariable = new LocalVariableInstructionObject(localVariableType, variableName);
localVariable.setSimpleName(psiReference);
addLocalVariableInstruction(localVariable);
Set<PsiAssignmentExpression> localVariableAssignments = getMatchingAssignments(resolvedVariable, assignments);
Set<PsiPostfixExpression> localVariablePostfixAssignments =
getMatchingPostfixAssignments(resolvedVariable, postfixExpressions);
Set<PsiPrefixExpression> localVariablePrefixAssignments =
getMatchingPrefixAssignments(resolvedVariable, prefixExpressions);
if (!localVariableAssignments.isEmpty()) {
addDefinedLocalVariable(variable);
for (PsiAssignmentExpression assignment : localVariableAssignments) {
PsiJavaToken operator = assignment.getOperationSign();
if (!JavaTokenType.EQ.equals(operator.getTokenType()))
addUsedLocalVariable(variable);
}
}
if (!localVariablePostfixAssignments.isEmpty()) {
addDefinedLocalVariable(variable);
addUsedLocalVariable(variable);
}
if (!localVariablePrefixAssignments.isEmpty()) {
addDefinedLocalVariable(variable);
addUsedLocalVariable(variable);
}
if (localVariableAssignments.isEmpty() && localVariablePostfixAssignments.isEmpty()
&& localVariablePrefixAssignments.isEmpty()) {
addUsedLocalVariable(variable);
}
}
}
}
}
void processLocalVariableDeclaration(PsiStatement statement) {
if (statement instanceof PsiDeclarationStatement) {
PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) statement;
PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
for (PsiElement element : declaredElements) {
if (element instanceof PsiLocalVariable) {
PsiLocalVariable declaredVariable = (PsiLocalVariable) element;
String variableType = declaredVariable.getType().getCanonicalText();
TypeObject localVariableType = TypeObject.extractTypeObject(variableType);
LocalVariableDeclarationObject localVariable =
new LocalVariableDeclarationObject(localVariableType, declaredVariable.getName());
localVariable.setVariableDeclaration(declaredVariable);
addLocalVariableDeclaration(localVariable);
addDeclaredLocalVariable(new PlainVariable(declaredVariable));
}
}
}
}
private void addFieldInstruction(FieldInstructionObject fieldInstruction) {
fieldInstructionList.add(fieldInstruction);
if (parent != null) {
parent.addFieldInstruction(fieldInstruction);
}
}
private void addSuperFieldInstruction(SuperFieldInstructionObject superFieldInstruction) {
superFieldInstructionList.add(superFieldInstruction);
if (parent != null) {
parent.addSuperFieldInstruction(superFieldInstruction);
}
}
private void addLocalVariableDeclaration(LocalVariableDeclarationObject localVariable) {
localVariableDeclarationList.add(localVariable);
if (parent != null) {
parent.addLocalVariableDeclaration(localVariable);
}
}
private void addLocalVariableInstruction(LocalVariableInstructionObject localVariable) {
localVariableInstructionList.add(localVariable);
if (parent != null) {
parent.addLocalVariableInstruction(localVariable);
}
}
private void addDeclaredLocalVariable(PlainVariable variable) {
declaredLocalVariables.add(variable);
if (parent != null) {
parent.addDeclaredLocalVariable(variable);
}
}
private void addDefinedLocalVariable(PlainVariable variable) {
definedLocalVariables.add(variable);
if (parent != null) {
parent.addDefinedLocalVariable(variable);
}
}
private void addUsedLocalVariable(PlainVariable variable) {
usedLocalVariables.add(variable);
if (parent != null) {
parent.addUsedLocalVariable(variable);
}
}
void processMethodInvocations(List<PsiExpression> methodInvocations) {
for (PsiExpression expression : methodInvocations) {
if (expression instanceof PsiMethodCallExpression) {
PsiMethodCallExpression methodInvocation = (PsiMethodCallExpression) expression;
PsiMethod resolveMethod = methodInvocation.resolveMethod();
if (resolveMethod == null) continue;
String originClassName = null;
if (resolveMethod.getContainingClass() != null) {
originClassName = resolveMethod.getContainingClass().getQualifiedName();
}
TypeObject originClassTypeObject = TypeObject.extractTypeObject(originClassName);
String methodInvocationName = resolveMethod.getName();
PsiType returnTypeBinding = resolveMethod.getReturnType();
TypeObject returnType = TypeObject.extractTypeObject(returnTypeBinding == null ?
"java.lang.Object" : returnTypeBinding.getCanonicalText());
MethodInvocationObject methodInvocationObject = new MethodInvocationObject(originClassTypeObject, methodInvocationName, returnType);
methodInvocationObject.setMethodInvocation(methodInvocation);
PsiParameter[] parameters = resolveMethod.getParameterList().getParameters();
for (PsiParameter psiParameter : parameters) {
TypeObject typeObject = TypeObject.extractTypeObject(psiParameter.getType().getCanonicalText());
methodInvocationObject.addParameter(typeObject);
}
JvmReferenceType[] thrownExceptionTypes = resolveMethod.getThrowsTypes();
for (JvmReferenceType thrownExceptionType : thrownExceptionTypes) {
methodInvocationObject.addThrownException(thrownExceptionType.getName());
}
if ((resolveMethod.hasModifier(JvmModifier.STATIC)))
methodInvocationObject.setStatic(true);
addMethodInvocation(methodInvocationObject);
AbstractVariable invoker = MethodDeclarationUtility
.processMethodInvocationExpression(methodInvocation.getMethodExpression());
if (invoker != null) {
PlainVariable initialVariable = invoker.getInitialVariable();
if (initialVariable.isField()) {
addNonDistinctInvokedMethodThroughField(invoker, methodInvocationObject);
} else if (initialVariable.isParameter()) {
addNonDistinctInvokedMethodThroughParameter(invoker, methodInvocationObject);
} else {
addNonDistinctInvokedMethodThroughLocalVariable(invoker, methodInvocationObject);
}
} else {
if (methodInvocationObject.isStatic())
addStaticallyInvokedMethod(methodInvocationObject);
else {
if (methodInvocation.getFirstChild() instanceof PsiThisExpression) {
addNonDistinctInvokedMethodThroughThisReference(methodInvocationObject);
}
}
}
PsiExpression[] arguments = methodInvocation.getArgumentList().getExpressions();
for (PsiExpression argument : arguments) {
if (argument instanceof PsiReferenceExpression) {
PsiReferenceExpression argumentReference = (PsiReferenceExpression) argument;
PsiElement resolvedArgument = argumentReference.resolve();
if (resolvedArgument instanceof PsiParameter) {
PsiVariable variableBinding = (PsiVariable) resolvedArgument;
PlainVariable variable = new PlainVariable(variableBinding);
addParameterPassedAsArgumentInMethodInvocation(variable, methodInvocationObject);
}
}
}
} else if (expression instanceof PsiSuperExpression) {
PsiSuperExpression psiSuperExpression = (PsiSuperExpression) expression;
PsiElement resolvedElement = null;
if (psiSuperExpression.getReference() != null) {
resolvedElement = psiSuperExpression.getReference().resolve();
}
if (!(resolvedElement instanceof PsiMethod)) return;
PsiMethod resolvedMethod = (PsiMethod) resolvedElement;
String originClassName = Objects.requireNonNull(resolvedMethod.getContainingClass()).getQualifiedName();
TypeObject originClassTypeObject = TypeObject.extractTypeObject(originClassName);
String methodInvocationName = resolvedMethod.getName();
String returnTypeName = Objects.requireNonNull(resolvedMethod.getReturnType()).getCanonicalText();
TypeObject returnType = TypeObject.extractTypeObject(returnTypeName);
SuperMethodInvocationObject superMethodInvocationObject =
new SuperMethodInvocationObject(originClassTypeObject, methodInvocationName, returnType);
superMethodInvocationObject.setSuperMethodInvocation(psiSuperExpression);
PsiParameter[] psiParameters = resolvedMethod.getParameterList().getParameters();
for (PsiParameter parameter : psiParameters) {
String qualifiedParameterName = parameter.getType().getCanonicalText();
TypeObject typeObject = TypeObject.extractTypeObject(qualifiedParameterName);
superMethodInvocationObject.addParameter(typeObject);
}
JvmReferenceType[] thrownExceptionTypes = resolvedMethod.getThrowsTypes();
for (JvmReferenceType thrownExceptionType : thrownExceptionTypes) {
superMethodInvocationObject.addThrownException(thrownExceptionType.getName());
}
if ((resolvedMethod.hasModifier(JvmModifier.STATIC)))
superMethodInvocationObject.setStatic(true);
addSuperMethodInvocation(superMethodInvocationObject);
//TODO: handle arguments of method call
}
}
}
private void addMethodInvocation(MethodInvocationObject methodInvocationObject) {
methodInvocationList.add(methodInvocationObject);
if (parent != null) {
parent.addMethodInvocation(methodInvocationObject);
}
}
private void addSuperMethodInvocation(SuperMethodInvocationObject superMethodInvocationObject) {
superMethodInvocationList.add(superMethodInvocationObject);
if (parent != null) {
parent.addSuperMethodInvocation(superMethodInvocationObject);
}
}
private void addConstructorInvocation(ConstructorInvocationObject constructorInvocationObject) {
constructorInvocationList.add(constructorInvocationObject);
if (parent != null) {
parent.addConstructorInvocation(constructorInvocationObject);
}
}
void processClassInstanceCreations(List<PsiExpression> classInstanceCreations) {
for (PsiExpression classInstanceCreationExpression : classInstanceCreations) {
PsiNewExpression classInstanceCreation = (PsiNewExpression) classInstanceCreationExpression;
if (classInstanceCreation != null && classInstanceCreation.getClassOrAnonymousClassReference() != null) {
PsiJavaCodeReferenceElement referenceElement = classInstanceCreation.getClassOrAnonymousClassReference();
PsiClass psiClass = (PsiClass) referenceElement.resolve();
if (psiClass == null) continue;
TypeObject typeObject = null;
if (psiClass.getQualifiedName() != null) {
typeObject = TypeObject.extractTypeObject(psiClass.getQualifiedName());
}
ClassInstanceCreationObject creationObject = new ClassInstanceCreationObject(typeObject);
creationObject.setClassInstanceCreation(classInstanceCreation);
if (psiClass.getTypeParameterList() != null) {
for (PsiTypeParameter parameterType : psiClass.getTypeParameterList().getTypeParameters()) {
String qualifiedParameterName = parameterType.getQualifiedName() == null ? "java.lang.Object" : parameterType.getQualifiedName();
TypeObject parameterTypeObject = TypeObject.extractTypeObject(qualifiedParameterName);
creationObject.addParameter(parameterTypeObject);
}
}
PsiAnonymousClass anonymous = classInstanceCreation.getAnonymousClass();
if (anonymous != null) {
final AnonymousClassDeclarationObject anonymousClassObject = new AnonymousClassDeclarationObject();
if (anonymous.getName() != null) {
anonymousClassObject.setName(anonymous.getName());
}
anonymousClassObject.setAnonymousClassDeclaration(anonymous);
PsiField[] fields = anonymous.getFields();
PsiMethod[] methods = anonymous.getMethods();
for (PsiField psiField : fields) {
TypeObject fieldType = TypeObject.extractTypeObject(psiField.getType().getCanonicalText());
fieldType.setArrayDimension(fieldType.getArrayDimension());
FieldObject fieldObject = new FieldObject(fieldType, psiField.getName(), psiField);
fieldObject.setClassName(anonymousClassObject.getName());
if ((psiField.hasModifier(JvmModifier.PUBLIC)))
fieldObject.setAccess(Access.PUBLIC);
else if (psiField.hasModifier(JvmModifier.PROTECTED))
fieldObject.setAccess(Access.PROTECTED);
else if (psiField.hasModifier(JvmModifier.PRIVATE))
fieldObject.setAccess(Access.PRIVATE);
else
fieldObject.setAccess(Access.NONE);
if (psiField.hasModifier(JvmModifier.STATIC))
fieldObject.setStatic(true);
anonymousClassObject.addField(fieldObject);
}
for (PsiMethod psiMethod : methods) {
final ConstructorObject constructorObject = new ConstructorObject();
constructorObject.setMethodDeclaration(psiMethod);
constructorObject.setName(psiMethod.getName());
constructorObject.setClassName(anonymousClassObject.getName());
if ((psiMethod.hasModifier(JvmModifier.PUBLIC)))
constructorObject.setAccess(Access.PUBLIC);
else if ((psiMethod.hasModifier(JvmModifier.PROTECTED)))
constructorObject.setAccess(Access.PROTECTED);
else if ((psiMethod.hasModifier(JvmModifier.PRIVATE)))
constructorObject.setAccess(Access.PRIVATE);
else
constructorObject.setAccess(Access.NONE);
PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
for (PsiParameter parameter : parameters) {
TypeObject parameterType = TypeObject.extractTypeObject(parameter.getType().getCanonicalText());
parameterType.setArrayDimension(parameterType.getArrayDimension());
if (parameter.isVarArgs()) {
parameterType.setArrayDimension(1);
}
ParameterObject parameterObject = new ParameterObject(parameterType, parameter.getName(), parameter.isVarArgs());
parameterObject.setSingleVariableDeclaration(parameter);
constructorObject.addParameter(parameterObject);
}
PsiCodeBlock methodBody = psiMethod.getBody();
if (methodBody != null) {
MethodBodyObject methodBodyObject = new MethodBodyObject(methodBody);
constructorObject.setMethodBody(methodBodyObject);
}
MethodObject methodObject = new MethodObject(psiMethod, constructorObject);
PsiModifierList extendedModifiers = psiMethod.getModifierList();
PsiAnnotation[] annotations = extendedModifiers.getAnnotations();
for (PsiAnnotation psiAnnotation : annotations) {
if (Objects.equals(psiAnnotation.getQualifiedName(), "Test")) {
methodObject.setTestAnnotation(true);
break;
}
}
PsiType returnType = psiMethod.getReturnType();
TypeObject returnTypeObject = null;
if (returnType != null) {
returnTypeObject = TypeObject.extractTypeObject(returnType.getCanonicalText());
}
methodObject.setReturnType(returnTypeObject);
if ((psiMethod.hasModifier(JvmModifier.ABSTRACT)))
methodObject.setAbstract(true);
if ((psiMethod.hasModifier(JvmModifier.STATIC)))
methodObject.setStatic(true);
if ((psiMethod.hasModifier(JvmModifier.SYNCHRONIZED)))
methodObject.setSynchronized(true);
if ((psiMethod.hasModifier(JvmModifier.NATIVE)))
methodObject.setNative(true);
anonymousClassObject.addMethod(methodObject);
}
addAnonymousClassDeclaration(anonymousClassObject);
}
PlainVariable variable = null;
if (classInstanceCreation.getParent() instanceof PsiAssignmentExpression) {
PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) classInstanceCreation.getParent();
if (classInstanceCreation.equals(assignmentExpression.getRExpression())) {
if (assignmentExpression.getLExpression() instanceof PsiReferenceExpression) {
PsiReferenceExpression psiExpression = (PsiReferenceExpression) assignmentExpression.getLExpression();
PsiElement resolvedElement = psiExpression.resolve();
if (resolvedElement instanceof PsiVariable) {
variable = new PlainVariable((PsiVariable) resolvedElement);
}
}
}
} else if (classInstanceCreation.getParent() instanceof PsiDeclarationStatement) {
PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) classInstanceCreation.getParent();
PsiElement[] declaredElements = declarationStatement.getDeclaredElements();
for (PsiElement element : declaredElements) {
if (classInstanceCreation.equals(element)) {
if (element instanceof PsiVariable) {
variable = new PlainVariable((PsiVariable) element);
}
}
}
}
if (variable != null) {
addVariableAssignedWithClassInstanceCreation(variable, creationObject);
}
addCreation(creationObject);
}
}
}
void processArrayCreations(List<PsiExpression> arrayCreations) {
for (PsiExpression arrayCreationExpression : arrayCreations) {
if (!(arrayCreationExpression instanceof PsiNewExpression)) continue;
PsiNewExpression arrayCreation = (PsiNewExpression) arrayCreationExpression;
TypeObject typeObject = null;
if (arrayCreation.getType() != null) {
typeObject = TypeObject.extractTypeObject(arrayCreation.getType().getCanonicalText());
}
ArrayCreationObject creationObject = new ArrayCreationObject(typeObject);
creationObject.setArrayCreation(arrayCreation);
addCreation(creationObject);
}
}
private void addCreation(CreationObject creationObject) {
creationList.add(creationObject);
if (parent != null) {
parent.addCreation(creationObject);
}
}
void processLiterals(List<PsiExpression> literals) {
for (PsiExpression literal : literals) {
LiteralObject literalObject = new LiteralObject(literal);
addLiteral(literalObject);
}
}
private void addLiteral(LiteralObject literalObject) {
literalList.add(literalObject);
if (parent != null) {
parent.addLiteral(literalObject);
}
}
private void addAnonymousClassDeclaration(AnonymousClassDeclarationObject anonymousClassObject) {
anonymousClassDeclarationList.add(anonymousClassObject);
if (parent != null) {
parent.addAnonymousClassDeclaration(anonymousClassObject);
}
}
void processThrowStatement(PsiThrowStatement throwStatement) {
PsiExpression expression = throwStatement.getException();
if (expression instanceof PsiNewExpression) {
PsiNewExpression newExpression = (PsiNewExpression) expression;
if (newExpression.getArrayDimensions().length == 0) {
PsiMethod constructorCall = newExpression.resolveConstructor();
if (constructorCall != null) {
addExceptionInThrowStatement(PsiUtil.getMemberQualifiedName(constructorCall));
}
}
}
}
private void addExceptionInThrowStatement(String exception) {
exceptionsInThrowStatements.add(exception);
if (parent != null) {
parent.addExceptionInThrowStatement(exception);
}
}
private void addNonDistinctInvokedMethodThroughField(AbstractVariable field, MethodInvocationObject methodInvocation) {
if (nonDistinctInvokedMethodsThroughFields.containsKey(field)) {
ArrayList<MethodInvocationObject> methodInvocations = nonDistinctInvokedMethodsThroughFields.get(field);
methodInvocations.add(methodInvocation);
} else {
ArrayList<MethodInvocationObject> methodInvocations = new ArrayList<>();
methodInvocations.add(methodInvocation);
nonDistinctInvokedMethodsThroughFields.put(field, methodInvocations);
}
if (parent != null) {
parent.addNonDistinctInvokedMethodThroughField(field, methodInvocation);
}
}
private void addNonDistinctInvokedMethodThroughParameter(AbstractVariable parameter, MethodInvocationObject methodInvocation) {
if (nonDistinctInvokedMethodsThroughParameters.containsKey(parameter)) {
ArrayList<MethodInvocationObject> methodInvocations = nonDistinctInvokedMethodsThroughParameters.get(parameter);
methodInvocations.add(methodInvocation);
} else {
ArrayList<MethodInvocationObject> methodInvocations = new ArrayList<>();
methodInvocations.add(methodInvocation);
nonDistinctInvokedMethodsThroughParameters.put(parameter, methodInvocations);
}
if (parent != null) {
parent.addNonDistinctInvokedMethodThroughParameter(parameter, methodInvocation);
}
}
private void addNonDistinctInvokedMethodThroughLocalVariable(AbstractVariable localVariable, MethodInvocationObject methodInvocation) {
if (nonDistinctInvokedMethodsThroughLocalVariables.containsKey(localVariable)) {
ArrayList<MethodInvocationObject> methodInvocations = nonDistinctInvokedMethodsThroughLocalVariables.get(localVariable);
methodInvocations.add(methodInvocation);
} else {
ArrayList<MethodInvocationObject> methodInvocations = new ArrayList<>();
methodInvocations.add(methodInvocation);
nonDistinctInvokedMethodsThroughLocalVariables.put(localVariable, methodInvocations);
}
if (parent != null) {
parent.addNonDistinctInvokedMethodThroughLocalVariable(localVariable, methodInvocation);
}
}
private void addNonDistinctInvokedMethodThroughThisReference(MethodInvocationObject methodInvocation) {
nonDistinctInvokedMethodsThroughThisReference.add(methodInvocation);
if (parent != null) {
parent.addNonDistinctInvokedMethodThroughThisReference(methodInvocation);
}
}
private void addStaticallyInvokedMethod(MethodInvocationObject methodInvocation) {
nonDistinctInvokedStaticMethods.add(methodInvocation);
if (parent != null) {
parent.addStaticallyInvokedMethod(methodInvocation);
}
}
private void addParameterPassedAsArgumentInMethodInvocation(PlainVariable parameter, MethodInvocationObject methodInvocation) {
if (parametersPassedAsArgumentsInMethodInvocations.containsKey(parameter)) {
LinkedHashSet<MethodInvocationObject> methodInvocations = parametersPassedAsArgumentsInMethodInvocations.get(parameter);
methodInvocations.add(methodInvocation);
} else {
LinkedHashSet<MethodInvocationObject> methodInvocations = new LinkedHashSet<>();
methodInvocations.add(methodInvocation);
parametersPassedAsArgumentsInMethodInvocations.put(parameter, methodInvocations);
}
if (parent != null) {
parent.addParameterPassedAsArgumentInMethodInvocation(parameter, methodInvocation);
}
}
private void addParameterPassedAsArgumentInSuperMethodInvocation(PlainVariable parameter, SuperMethodInvocationObject methodInvocation) {
if (parametersPassedAsArgumentsInSuperMethodInvocations.containsKey(parameter)) {
LinkedHashSet<SuperMethodInvocationObject> methodInvocations = parametersPassedAsArgumentsInSuperMethodInvocations.get(parameter);
methodInvocations.add(methodInvocation);
} else {
LinkedHashSet<SuperMethodInvocationObject> methodInvocations = new LinkedHashSet<>();
methodInvocations.add(methodInvocation);
parametersPassedAsArgumentsInSuperMethodInvocations.put(parameter, methodInvocations);
}
if (parent != null) {
parent.addParameterPassedAsArgumentInSuperMethodInvocation(parameter, methodInvocation);
}
}
private void addParameterPassedAsArgumentInConstructorInvocation(PlainVariable parameter, ConstructorInvocationObject constructorInvocation) {
if (parametersPassedAsArgumentsInConstructorInvocations.containsKey(parameter)) {
LinkedHashSet<ConstructorInvocationObject> constructorInvocations = parametersPassedAsArgumentsInConstructorInvocations.get(parameter);
constructorInvocations.add(constructorInvocation);
} else {
LinkedHashSet<ConstructorInvocationObject> constructorInvocations = new LinkedHashSet<>();
constructorInvocations.add(constructorInvocation);
parametersPassedAsArgumentsInConstructorInvocations.put(parameter, constructorInvocations);
}
if (parent != null) {
parent.addParameterPassedAsArgumentInConstructorInvocation(parameter, constructorInvocation);
}
}
private void addVariableAssignedWithClassInstanceCreation(PlainVariable variable, ClassInstanceCreationObject classInstanceCreation) {
if (variablesAssignedWithClassInstanceCreations.containsKey(variable)) {
LinkedHashSet<ClassInstanceCreationObject> classInstanceCreations = variablesAssignedWithClassInstanceCreations.get(variable);
classInstanceCreations.add(classInstanceCreation);
} else {
LinkedHashSet<ClassInstanceCreationObject> classInstanceCreations = new LinkedHashSet<>();
classInstanceCreations.add(classInstanceCreation);
variablesAssignedWithClassInstanceCreations.put(variable, classInstanceCreations);
}
if (parent != null) {
parent.addVariableAssignedWithClassInstanceCreation(variable, classInstanceCreation);
}
}
private Set<PsiAssignmentExpression> getMatchingAssignments(PsiVariable variable, List<PsiExpression> assignments) {
Set<PsiAssignmentExpression> matchingAssignments = new LinkedHashSet<>();
for (PsiExpression expression : assignments) {
if (expression instanceof PsiAssignmentExpression) {
PsiAssignmentExpression assignment = (PsiAssignmentExpression) expression;
PsiExpression leftHandSide = assignment.getLExpression();
if (leftHandSide instanceof PsiReferenceExpression) {
PsiReferenceExpression referenceExpression = (PsiReferenceExpression) leftHandSide;
PsiElement resolvedElement = referenceExpression.resolve();
if (variable.equals(resolvedElement)) {
matchingAssignments.add(assignment);
}
}
}
}
return matchingAssignments;
}
private Set<PsiPostfixExpression> getMatchingPostfixAssignments(PsiVariable variable, List<PsiExpression> postfixExpressions) {
Set<PsiPostfixExpression> matchingPostfixAssignments = new LinkedHashSet<>();
for (PsiExpression expression : postfixExpressions) {
if (expression instanceof PsiPostfixExpression) {
PsiPostfixExpression postfixExpression = (PsiPostfixExpression) expression;
PsiElement element = postfixExpression.getOperand().getLastChild();
if (element != null && element.equals(variable)) {
matchingPostfixAssignments.add(postfixExpression);
}
}
}
return matchingPostfixAssignments;
}
private Set<PsiPrefixExpression> getMatchingPrefixAssignments(PsiVariable variable, List<PsiExpression> prefixExpressions) {
Set<PsiPrefixExpression> matchingPrefixAssignments = new LinkedHashSet<>();
for (PsiExpression expression : prefixExpressions) {
if (expression instanceof PsiPrefixExpression) {
PsiPrefixExpression prefixExpression = (PsiPrefixExpression) expression;
PsiExpression operand = prefixExpression.getOperand();
if (operand == null) continue;
PsiElement element = operand.getLastChild();
if (element != null && element.equals(variable) && PsiUtil.isIncrementDecrementOperation(operand)) {
matchingPrefixAssignments.add(prefixExpression);
}
}
}
return matchingPrefixAssignments;
}
private void handleDefinedField(AbstractVariable variable) {
if (variable != null) {
PlainVariable initialVariable = variable.getInitialVariable();
if (variable instanceof PlainVariable) {
nonDistinctDefinedFieldsThroughThisReference.add((PlainVariable) variable);
} else {
if (initialVariable.isField()) {
nonDistinctDefinedFieldsThroughFields.add(variable);
} else if (initialVariable.isParameter()) {
nonDistinctDefinedFieldsThroughParameters.add(variable);
} else {
nonDistinctDefinedFieldsThroughLocalVariables.add(variable);
}
}
if (parent != null) {
parent.handleDefinedField(variable);
}
}
}
private void handleUsedField(AbstractVariable variable) {
if (variable != null) {
PlainVariable initialVariable = variable.getInitialVariable();
if (variable instanceof PlainVariable) {
nonDistinctUsedFieldsThroughThisReference.add((PlainVariable) variable);
} else {
if (initialVariable.isField()) {
nonDistinctUsedFieldsThroughFields.add(variable);
} else if (initialVariable.isParameter()) {
nonDistinctUsedFieldsThroughParameters.add(variable);
} else {
nonDistinctUsedFieldsThroughLocalVariables.add(variable);
}
}
if (parent != null) {
parent.handleUsedField(variable);
}
}
}
public List<FieldInstructionObject> getFieldInstructions() {
return fieldInstructionList;
}
public List<SuperFieldInstructionObject> getSuperFieldInstructions() {
return superFieldInstructionList;
}
public List<LocalVariableDeclarationObject> getLocalVariableDeclarations() {
return localVariableDeclarationList;
}
public List<LocalVariableInstructionObject> getLocalVariableInstructions() {
return localVariableInstructionList;
}
public List<MethodInvocationObject> getMethodInvocations() {
return methodInvocationList;
}
public List<SuperMethodInvocationObject> getSuperMethodInvocations() {
return superMethodInvocationList;
}
public List<ConstructorInvocationObject> getConstructorInvocations() {
return constructorInvocationList;
}
public List<CreationObject> getCreations() {
return creationList;
}
List<ClassInstanceCreationObject> getClassInstanceCreations() {
List<ClassInstanceCreationObject> classInstanceCreations = new ArrayList<>();
for (CreationObject creation : creationList) {
if (creation instanceof ClassInstanceCreationObject) {
classInstanceCreations.add((ClassInstanceCreationObject) creation);
}
}
return classInstanceCreations;
}
List<ArrayCreationObject> getArrayCreations() {
List<ArrayCreationObject> arrayCreations = new ArrayList<>();
for (CreationObject creation : creationList) {
if (creation instanceof ArrayCreationObject) {
arrayCreations.add((ArrayCreationObject) creation);
}
}
return arrayCreations;
}
public List<LiteralObject> getLiterals() {
return literalList;
}
public List<AnonymousClassDeclarationObject> getAnonymousClassDeclarations() {
return anonymousClassDeclarationList;
}
public Set<String> getExceptionsInThrowStatements() {
return exceptionsInThrowStatements;
}
public boolean containsMethodInvocation(MethodInvocationObject methodInvocation) {
return methodInvocationList.contains(methodInvocation);
}
public boolean containsFieldInstruction(FieldInstructionObject fieldInstruction) {
return fieldInstructionList.contains(fieldInstruction);
}
public boolean containsSuperMethodInvocation(SuperMethodInvocationObject superMethodInvocation) {
return superMethodInvocationList.contains(superMethodInvocation);
}
public boolean containsLocalVariableDeclaration(LocalVariableDeclarationObject lvdo) {
return localVariableDeclarationList.contains(lvdo);
}
public Map<AbstractVariable, LinkedHashSet<MethodInvocationObject>> getInvokedMethodsThroughFields() {
Map<AbstractVariable, LinkedHashSet<MethodInvocationObject>> invokedMethodsThroughFields =
new LinkedHashMap<>();
for (AbstractVariable key : nonDistinctInvokedMethodsThroughFields.keySet()) {
invokedMethodsThroughFields.put(key, new LinkedHashSet<>(nonDistinctInvokedMethodsThroughFields.get(key)));
}
return invokedMethodsThroughFields;
}
public Map<AbstractVariable, LinkedHashSet<MethodInvocationObject>> getInvokedMethodsThroughParameters() {
Map<AbstractVariable, LinkedHashSet<MethodInvocationObject>> invokedMethodsThroughParameters =
new LinkedHashMap<>();
for (AbstractVariable key : nonDistinctInvokedMethodsThroughParameters.keySet()) {
invokedMethodsThroughParameters.put(key, new LinkedHashSet<>(nonDistinctInvokedMethodsThroughParameters.get(key)));
}
return invokedMethodsThroughParameters;
}
public Map<AbstractVariable, ArrayList<MethodInvocationObject>> getNonDistinctInvokedMethodsThroughFields() {
return nonDistinctInvokedMethodsThroughFields;
}
public Map<AbstractVariable, ArrayList<MethodInvocationObject>> getNonDistinctInvokedMethodsThroughParameters() {
return nonDistinctInvokedMethodsThroughParameters;
}
public Map<AbstractVariable, LinkedHashSet<MethodInvocationObject>> getInvokedMethodsThroughLocalVariables() {
Map<AbstractVariable, LinkedHashSet<MethodInvocationObject>> invokedMethodsThroughLocalVariables =
new LinkedHashMap<>();
for (AbstractVariable key : nonDistinctInvokedMethodsThroughLocalVariables.keySet()) {
invokedMethodsThroughLocalVariables.put(key, new LinkedHashSet<>(nonDistinctInvokedMethodsThroughLocalVariables.get(key)));
}
return invokedMethodsThroughLocalVariables;
}
public Map<AbstractVariable, ArrayList<MethodInvocationObject>> getNonDistinctInvokedMethodsThroughLocalVariables() {
return nonDistinctInvokedMethodsThroughLocalVariables;
}
public Set<MethodInvocationObject> getInvokedMethodsThroughThisReference() {
return new LinkedHashSet<>(nonDistinctInvokedMethodsThroughThisReference);
}
public List<MethodInvocationObject> getNonDistinctInvokedMethodsThroughThisReference() {
return nonDistinctInvokedMethodsThroughThisReference;
}
public Set<MethodInvocationObject> getInvokedStaticMethods() {
return new LinkedHashSet<>(nonDistinctInvokedStaticMethods);
}
List<MethodInvocationObject> getNonDistinctInvokedStaticMethods() {
return nonDistinctInvokedStaticMethods;
}
public Set<AbstractVariable> getDefinedFieldsThroughFields() {
return new LinkedHashSet<>(nonDistinctDefinedFieldsThroughFields);
}
public Set<AbstractVariable> getUsedFieldsThroughFields() {
return new LinkedHashSet<>(nonDistinctUsedFieldsThroughFields);
}
public List<AbstractVariable> getNonDistinctDefinedFieldsThroughFields() {
return nonDistinctDefinedFieldsThroughFields;
}
public List<AbstractVariable> getNonDistinctUsedFieldsThroughFields() {
return nonDistinctUsedFieldsThroughFields;
}
public Set<AbstractVariable> getDefinedFieldsThroughParameters() {
return new LinkedHashSet<>(nonDistinctDefinedFieldsThroughParameters);
}
public Set<AbstractVariable> getUsedFieldsThroughParameters() {
return new LinkedHashSet<>(nonDistinctUsedFieldsThroughParameters);
}
public List<AbstractVariable> getNonDistinctDefinedFieldsThroughParameters() {
return nonDistinctDefinedFieldsThroughParameters;
}
public List<AbstractVariable> getNonDistinctUsedFieldsThroughParameters() {
return nonDistinctUsedFieldsThroughParameters;
}
public Set<AbstractVariable> getDefinedFieldsThroughLocalVariables() {
return new LinkedHashSet<>(nonDistinctDefinedFieldsThroughLocalVariables);
}
public Set<AbstractVariable> getUsedFieldsThroughLocalVariables() {
return new LinkedHashSet<>(nonDistinctUsedFieldsThroughLocalVariables);
}
public List<AbstractVariable> getNonDistinctDefinedFieldsThroughLocalVariables() {
return nonDistinctDefinedFieldsThroughLocalVariables;
}
public List<AbstractVariable> getNonDistinctUsedFieldsThroughLocalVariables() {
return nonDistinctUsedFieldsThroughLocalVariables;
}
public Set<PlainVariable> getDefinedFieldsThroughThisReference() {
return new LinkedHashSet<>(nonDistinctDefinedFieldsThroughThisReference);
}
public List<PlainVariable> getNonDistinctDefinedFieldsThroughThisReference() {
return nonDistinctDefinedFieldsThroughThisReference;
}
public Set<PlainVariable> getUsedFieldsThroughThisReference() {
return new LinkedHashSet<>(nonDistinctUsedFieldsThroughThisReference);
}
public List<PlainVariable> getNonDistinctUsedFieldsThroughThisReference() {
return nonDistinctUsedFieldsThroughThisReference;
}
public Set<PlainVariable> getDeclaredLocalVariables() {
return declaredLocalVariables;
}
public Set<PlainVariable> getDefinedLocalVariables() {
return definedLocalVariables;
}
public Set<PlainVariable> getUsedLocalVariables() {
return usedLocalVariables;
}
public Map<PlainVariable, LinkedHashSet<MethodInvocationObject>> getParametersPassedAsArgumentsInMethodInvocations() {
return parametersPassedAsArgumentsInMethodInvocations;
}
public Map<PlainVariable, LinkedHashSet<SuperMethodInvocationObject>> getParametersPassedAsArgumentsInSuperMethodInvocations() {
return parametersPassedAsArgumentsInSuperMethodInvocations;
}
public Map<PlainVariable, LinkedHashSet<ConstructorInvocationObject>> getParametersPassedAsArgumentsInConstructorInvocations() {
return parametersPassedAsArgumentsInConstructorInvocations;
}
public Map<PlainVariable, LinkedHashSet<ClassInstanceCreationObject>> getVariablesAssignedWithClassInstanceCreations() {
return variablesAssignedWithClassInstanceCreations;
}
}
| 54.09725 | 157 | 0.654337 |
00d4a1048b5af1646f038d346036c2efa41ae350 | 9,044 | /******************************************************************
* File: TomcatTestContainerFactory.java
* Created by: Dave Reynolds
* Created on: 30 Nov 2012
*
* (c) Copyright 2012, Epimorphics Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************/
package com.epimorphics.appbase.webapi.testing;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.catalina.startup.Tomcat;
import org.apache.jena.atlas.json.JSON;
import org.apache.jena.atlas.json.JsonObject;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.util.FileManager;
import org.glassfish.jersey.client.ClientConfig;
import org.junit.After;
import org.junit.Before;
import com.epimorphics.util.NameUtils;
import com.epimorphics.util.TestUtil;
public abstract class TomcatTestBase {
protected static final String BASE_URL = "http://localhost:8070/";
protected Tomcat tomcat ;
protected Client c;
abstract public String getWebappRoot() ;
public String getWebappContext() {
return "/";
}
/**
* URL to use for liveness tests
*/
public String getTestURL() {
return NameUtils.ensureLastSlash( BASE_URL.substring(0, BASE_URL.length()-1) + getWebappContext() );
}
@Before
public void containerStart() throws Exception {
String root = getWebappRoot();
tomcat = new Tomcat();
tomcat.setPort(8070);
tomcat.setBaseDir(".");
String contextPath = getWebappContext();
File rootF = new File(root);
if (!rootF.exists()) {
rootF = new File(".");
}
if (!rootF.exists()) {
System.err.println("Can't find root app: " + root);
System.exit(1);
}
tomcat.addWebapp(contextPath, rootF.getAbsolutePath());
tomcat.start();
// Allow arbitrary HTTP methods so we can use PATCH
ClientConfig config = new ClientConfig();
// TODO Not sure this is correct or needed any more
// config.getProperties().put(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
c = ClientBuilder.newClient(config);
checkLive(200);
}
@After
public void containerStop() throws Exception {
tomcat.stop();
tomcat.destroy();
try {
checkLive(503);
} catch (Throwable e) {
// Can get net connection exceptions talking to dead tomcat, that's OK
}
}
protected int postFileStatus(String file, String uri) {
return postFileStatus(file, uri, "text/turtle");
}
protected int postFileStatus(String file, String uri, String mime) {
return postFile(file, uri, mime).getStatus();
}
protected Response postFile(String file, String uri) {
return postFile(file, uri, "text/turtle");
}
protected Response postFile(String file, String uri, String mime) {
WebTarget r = c.target(uri);
File src = new File(file);
Response response = r.request().post( Entity.entity(src, mime) );
return response;
}
protected Response postModel(Model m, String uri) {
WebTarget r = c.target(uri);
StringWriter sw = new StringWriter();
m.write(sw, "Turtle");
Response response = r.request().post(Entity.entity(sw.getBuffer().toString(), "text/turtle"));
return response;
}
protected Response invoke(String method, String file, String uri, String mime) {
WebTarget r = c.target(uri);
Response response = null;
if (file == null) {
response = r.request().header("X-HTTP-Method-Override", method).post(Entity.entity(null, mime));
} else {
File src = new File(file);
response = r.request().header("X-HTTP-Method-Override", method).post(Entity.entity(src, mime));
}
return response;
}
protected Response post(String uri, String...paramvals) {
WebTarget r = c.target(uri);
for (int i = 0; i < paramvals.length; ) {
String param = paramvals[i++];
String value = paramvals[i++];
r = r.queryParam(param, value);
}
Response response = r.request().post(null);
return response;
}
protected Response postForm(String uri, String...paramvals) {
WebTarget r = c.target(uri);
Form form = new Form();
for (int i = 0; i < paramvals.length; ) {
String param = paramvals[i++];
String value = paramvals[i++];
form.param(param, value);
}
Response response = r.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
return response;
}
protected Response invoke(String method, String file, String uri) {
return invoke(method, file, uri, "text/turtle");
}
protected Model getModelResponse(String uri, String...paramvals) {
WebTarget r = c.target( uri );
for (int i = 0; i < paramvals.length; ) {
String param = paramvals[i++];
String value = paramvals[i++];
r = r.queryParam(param, value);
}
InputStream response = r.request("text/turtle").get(InputStream.class);
Model result = ModelFactory.createDefaultModel();
result.read(response, uri, "Turtle");
return result;
}
protected Response getResponse(String uri) {
return getResponse(uri, "text/turtle");
}
protected Response getResponse(String uri, String mime) {
WebTarget r = c.target( uri );
return r.request(mime).get();
}
protected JsonObject getJSONResponse(String uri) {
Response r = getResponse(uri, MediaType.APPLICATION_JSON);
return JSON.parse( r.readEntity(InputStream.class) );
}
protected Model checkModelResponse(String fetch, String rooturi, String file, Property...omit) {
Model m = getModelResponse(fetch);
Resource actual = m.getResource(rooturi);
Resource expected = FileManager.get().loadModel(file).getResource(rooturi);
assertTrue(expected.listProperties().hasNext()); // guard against wrong rooturi in config
TestUtil.testResourcesMatch(expected, actual, omit);
return m;
}
protected Model checkModelResponse(Model m, String rooturi, String file, Property...omit) {
Resource actual = m.getResource(rooturi);
Resource expected = FileManager.get().loadModel(file).getResource(rooturi);
assertTrue(expected.listProperties().hasNext()); // guard against wrong rooturi in config
TestUtil.testResourcesMatch(expected, actual, omit);
return m;
}
protected Model checkModelResponse(Model m, String file, Property...omit) {
Model expected = FileManager.get().loadModel(file);
for (Resource root : expected.listSubjects().toList()) {
if (root.isURIResource()) {
TestUtil.testResourcesMatch(root, m.getResource(root.getURI()), omit);
}
}
return m;
}
protected void printStatus(Response response) {
String msg = "Response: " + response.getStatus();
if (response.hasEntity() && response.getStatus() != 204) {
msg += " (" + response.readEntity(String.class) + ")";
}
System.out.println(msg);
}
protected void checkLive(int targetStatus) {
boolean tomcatLive = false;
int count = 0;
while (!tomcatLive) {
int status = getResponse( getTestURL() ).getStatus();
if (status != targetStatus) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
assertTrue("Interrupted", false);
}
if (count++ > 120 ) {
assertTrue("Too many tries", false);
}
} else {
tomcatLive = true;
}
}
}
}
| 33.746269 | 110 | 0.615215 |
fc70a80b53a1e183a33ed8c48a440ddfe9447eec | 5,369 | package com.hui.DFS;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author: shenhaizhilong
* @date: 2018/11/13 21:58
*
*
* 491. Increasing Subsequences
* DescriptionHintsSubmissionsDiscussSolution
* Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .
*
* Example:
* Input: [4, 6, 7, 7]
* Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
* Note:
* The length of the given array will not exceed 15.
* The range of integer in the given array is [-100,100].
* The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
*
*
*/
public class IncreasingSubsequences {
public List<List<Integer>> findSubsequences(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
if(nums == null || nums.length <=1 )return lists;
dfs(nums, 0, lists, new ArrayList<>(), new HashSet<>());
return lists;
}
private void dfs(int[] nums, int startIdx, List<List<Integer>> lists, List<Integer> list, Set<List<Integer>> cache)
{
if(startIdx >= nums.length)return;
for (int i = startIdx; i < nums.length; i++) {
boolean isAdd = false;
if(list.isEmpty() || nums[i] >= list.get(list.size() -1))
{
list.add(nums[i]);
isAdd = true;
}
if(list.size() >1)
{
if(!cache.contains(list))
{
List<Integer> temp = new ArrayList<>(list);
cache.add(temp);
lists.add(temp);
}
}
dfs(nums, i +1, lists, list, cache);
if(isAdd)
list.remove(list.size() -1);
}
}
public List<List<Integer>> findSubsequences2(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
if(nums == null || nums.length <=1 )return lists;
dfs2(nums, 0, lists, new ArrayList<>());
return lists;
}
private void dfs2(int[] nums, int startIdx, List<List<Integer>> lists, List<Integer> list)
{
if(startIdx >= nums.length)return;
int[] used = new int[201]; // it can be replaced with HashSet
for (int i = startIdx; i < nums.length; i++) {
if(used[nums[i] + 100] ==1)continue;
if(list.isEmpty() || nums[i] >= list.get(list.size() -1))
{
list.add(nums[i]);
// used只用于每一层递归,每次只添加一次,遇到重复的就自动跳过
// 下一层会重新申请数组,所以并不会影响到下一层加新的重复的元素
used[nums[i] + 100] = 1;
if(list.size() >1)
{
lists.add(new ArrayList<>(list));
}
dfs2(nums, i +1, lists, list);
list.remove(list.size() -1);
}
}
}
public List<List<Integer>> findSubsequences3(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
if(nums == null || nums.length <=1 )return lists;
dfs3(nums, 0, lists, new ArrayList<>());
return lists;
}
private void dfs3(int[] nums, int startIdx, List<List<Integer>> lists, List<Integer> list)
{
if(startIdx >= nums.length)return;
Set<Integer> used = new HashSet<>();
for (int i = startIdx; i < nums.length; i++) {
if(used.contains(nums[i]))continue;
if(list.isEmpty() || nums[i] >= list.get(list.size() -1))
{
list.add(nums[i]);
// used只用于每一层递归,每次只添加一次,遇到重复的就自动跳过
// 下一层会重新申请数组,所以并不会影响到下一层加新的重复的元素
used.add(nums[i]);
if(list.size() >1)
{
lists.add(new ArrayList<>(list));
}
dfs3(nums, i +1, lists, list);
list.remove(list.size() -1);
}
}
}
public static void test()
{
Set<List<Integer>> set = new HashSet<>();
List<Integer> list = new ArrayList<>();
list.add(4);
list.add(7);
set.add(list);
List<Integer> list2 = new ArrayList<>();
list2.add(4);
list2.add(7);
System.out.println(set.contains(list2));
System.out.println(list.hashCode());
System.out.println(list2.hashCode());
}
public static void main(String[] args) {
// test();
IncreasingSubsequences increasingSubsequences = new IncreasingSubsequences();
List<List<Integer>> lists = increasingSubsequences.findSubsequences2(new int[]{4,6,7,7});
for (int i = 0; i < lists.size(); i++) {
System.out.println(lists.get(i));
}
List<List<Integer>> lists2 = increasingSubsequences.findSubsequences(new int[]{84,-48,-33,-34,-52,72,75,-12,72,-45});
System.out.println("*********************");
for (int i = 0; i < lists2.size(); i++) {
System.out.println(lists2.get(i));
}
}
}
| 34.416667 | 186 | 0.510151 |
411871dfb8865bf2d27e29119ca1a7afc8a8734e | 2,875 | /*
* 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.kafka.streams.state.internals;
import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsMetrics;
import org.apache.kafka.streams.kstream.Windowed;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.StateSerdes;
class MeteredWindowedKeyValueIterator<K, V> implements KeyValueIterator<Windowed<K>, V> {
private final KeyValueIterator<Windowed<Bytes>, byte[]> iter;
private final Sensor sensor;
private final StreamsMetrics metrics;
private final StateSerdes<K, V> serdes;
private final long startNs;
private final Time time;
MeteredWindowedKeyValueIterator(final KeyValueIterator<Windowed<Bytes>, byte[]> iter,
final Sensor sensor,
final StreamsMetrics metrics,
final StateSerdes<K, V> serdes,
final Time time) {
this.iter = iter;
this.sensor = sensor;
this.metrics = metrics;
this.serdes = serdes;
this.startNs = time.nanoseconds();
this.time = time;
}
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public KeyValue<Windowed<K>, V> next() {
final KeyValue<Windowed<Bytes>, byte[]> next = iter.next();
return KeyValue.pair(windowedKey(next.key), serdes.valueFrom(next.value));
}
private Windowed<K> windowedKey(final Windowed<Bytes> bytesKey) {
final K key = serdes.keyFrom(bytesKey.key().get());
return new Windowed<>(key, bytesKey.window());
}
@Override
public void close() {
try {
iter.close();
} finally {
sensor.record(time.nanoseconds() - startNs);
}
}
@Override
public Windowed<K> peekNextKey() {
return windowedKey(iter.peekNextKey());
}
}
| 35.9375 | 89 | 0.66887 |
6c5f2c69fb9e804ca5ce17baab32320ce3a93510 | 1,070 | package com.springboot.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class MyJsonInclude {
private String id;
private String name;
private String gender;
private String age;
private String zipCode;
public MyJsonInclude(String id, String name, String gender, String age, String zipCode) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.zipCode = zipCode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
| 18.77193 | 90 | 0.703738 |
f87ae389f95fdc85ab6d98ed3cd6b3464acdb6d9 | 1,971 | package zserio.runtime.array;
import java.util.ArrayList;
import java.util.List;
import zserio.runtime.ZserioError;
/**
* Packing context node.
*
* This class is used to handle a tree of contexts created by appropriate PackedArrayTraits.
* For built-in packable types only a single context is kept. However for Zserio objects, a tree
* of all packable fields is created recursively.
*
* When the context node has no children and no context, then it's so called dummy context which is used
* for unpackable fields or nested arrays.
*/
public class PackingContextNode
{
/**
* Creates a new child.
*
* @return The child which was just created.
*/
public PackingContextNode createChild()
{
final PackingContextNode child = new PackingContextNode();
children.add(child);
return child;
}
/**
* Gets list of children of the current node.
*
* @return List of children.
*/
public List<PackingContextNode> getChildren()
{
return children;
}
/**
* Creates a new packing context within the current node.
*/
public void createContext()
{
deltaContext = new DeltaContext();
}
/**
* Gets whether the current node has a packing context.
*
* @return True when the current node has assigned a context, false otherwise.
*/
public boolean hasContext()
{
return deltaContext != null;
}
/**
* Gets packing context assigned to this node.
*
* Can be called only when the context exists!
*
* @return Packing context.
*/
public DeltaContext getContext()
{
if (deltaContext == null)
throw new ZserioError("DeltaContext: PackingContextNode is not a leaf!");
return deltaContext;
}
private final ArrayList<PackingContextNode> children = new ArrayList<PackingContextNode>();
private DeltaContext deltaContext = null;
}
| 25.269231 | 104 | 0.650939 |
94a5751230a6d9e80dd8794150c37100fd13ed6c | 2,394 | package es.udc.pa.pa013.practicapa.model.orderline;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.annotations.Immutable;
import es.udc.pa.pa013.practicapa.model.order.Order;
import es.udc.pa.pa013.practicapa.model.product.Product;
@Entity
@Immutable
@Table(name = "OrderLine")
public class OrderLine {
private Long orderLineId;
private Product product;
private Order order;
private int amount;
private float price;
public OrderLine() {
}
public OrderLine(Product product, Order order, int amount, float price) {
/**
* NOTE: "orderId" *must* be left as "null" since its value is
* automatically generated.
*/
this.product = product;
this.order = order;
this.amount = amount;
this.price = price;
}
@Column(name = "orderLineId")
@SequenceGenerator( // It only takes effect for databases that use
// identifier
name = "OrderLineIdGenerator", // generators (like Oracle)
sequenceName = "OrderLineSeq")
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "OrderLineIdGenerator")
public Long getOrderLineId() {
return orderLineId;
}
public void setOrderLineId(Long orderLineId) {
this.orderLineId = orderLineId;
}
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "productId")
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "orderId")
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
@Column(name = "amount")
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Column(name = "price")
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
return "OrderLine [orderLineId=" + orderLineId + ", product=" + product
+ ", order=" + order + ", amount=" + amount + ", price="
+ price + "]";
}
}
| 22.8 | 84 | 0.722222 |
8db6daa1cf1f7fc99109e96506258acaec1e1e82 | 931 | /*
* This file is part of Linyin, Peng Wan's graduation project in Haut.
* Copyright (C) 2016 Peng Wan <[email protected]>. All Rights Reserved.
*/
package pw.phylame.linyin.service.chain.ocs;
import org.springframework.beans.factory.annotation.Autowired;
import pw.phylame.linyin.constants.ErrorCode;
import pw.phylame.linyin.service.DeviceService;
/**
* Validates the device with client ID of request.
*
* @author Peng Wan
*/
public class ValidateClientCommand extends OcsCommand {
@Autowired
private DeviceService deviceService;
@Override
public boolean execute() {
String clientId = context.getClientId();
if (!deviceService.isDeviceAvailable(clientId)) {
logger.debug("client whit ID {} is not available", clientId);
return abortChain(ErrorCode.CLIENT_NOT_AVAILABLE, "client is unavailable: " + clientId);
}
return CONTINUE_PROCESSING;
}
}
| 29.09375 | 100 | 0.709989 |
bf4b38c3c2f76f2fb10ab4854dd84cd50c0e3fbd | 6,784 | /*
* Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the
* License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "LICENSE" file accompanying this file. This file 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.amazonaws.blox.frontend.operations;
import static org.mockito.Mockito.mock;
import com.amazonaws.blox.dataservicemodel.v1.client.DataService;
import com.amazonaws.blox.dataservicemodel.v1.model.Attribute;
import com.amazonaws.blox.dataservicemodel.v1.model.DeploymentConfiguration;
import com.amazonaws.blox.dataservicemodel.v1.model.Environment;
import com.amazonaws.blox.dataservicemodel.v1.model.EnvironmentId;
import com.amazonaws.blox.dataservicemodel.v1.model.EnvironmentRevision;
import com.amazonaws.blox.dataservicemodel.v1.model.EnvironmentType;
import com.amazonaws.blox.dataservicemodel.v1.model.InstanceGroup;
import com.amazonaws.blox.frontend.MapperConfiguration;
import com.amazonaws.serverless.proxy.internal.model.ApiGatewayRequestContext;
import com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequestReader;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
// TODO: We only use the Spring runner in order to wire in the needed mappers. See the comment on
// MapperConfiguration for details.
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = EnvironmentControllerTestCase.Config.class)
@ActiveProfiles("api_test")
public abstract class EnvironmentControllerTestCase {
protected static final String ROLE = "TestRole";
protected static final String HEALTHY = "Healthy";
protected static final String STATUS = "Active";
protected static final String DEPLOYMENT_METHOD = "ReplaceAfterTerminate";
protected static final String ENVIRONMENT_REVISION_ID = "TestEnvironmentRevision";
protected static final String TASK_DEFINITION = "TestTaskDefinition";
protected static final String ENVIRONMENT_NAME = "TestEnvironment";
protected static final String TEST_CLUSTER = "TestCluster";
protected static final String ENVIRONMENT_TYPE_STRING = "Daemon";
protected static final EnvironmentType ENVIRONMENT_TYPE = EnvironmentType.Daemon;
protected static final String ATTRIBUTE_NAME = "TestAttributeName";
protected static final String ATTRIBUTE_VALUE = "TestAttributeValue";
protected static final String ACCOUNT_ID = "1234567890";
@Autowired DataService dataService;
@Autowired HttpServletRequest servletRequest;
@Configuration
@Import(MapperConfiguration.class)
@ComponentScan("com.amazonaws.blox.frontend.operations")
@Profile("api_test")
static class Config {
@Bean
public DataService dataService() {
return mock(DataService.class);
}
@Bean
public HttpServletRequest httpServletRequest() {
return new MockHttpServletRequest();
}
}
@Before
public void setupRequest() {
ApiGatewayRequestContext requestContext = new ApiGatewayRequestContext();
requestContext.setAccountId(ACCOUNT_ID);
servletRequest.setAttribute(
AwsProxyHttpServletRequestReader.API_GATEWAY_CONTEXT_PROPERTY, requestContext);
}
// TODO: Pull these helper methods out into a fixture generator class, so that we can do e.g:
// fixtures.DS.instanceGroup("key", "value");
// fixtures.FE.instanceGroup("key", "value");
protected com.amazonaws.blox.frontend.models.InstanceGroup instanceGroupWithAttributeFE(
String attributeName, String attributeValue) {
return com.amazonaws.blox.frontend.models.InstanceGroup.builder()
.attributes(
new HashSet<>(
Arrays.asList(
com.amazonaws.blox.frontend.models.Attribute.builder()
.name(attributeName)
.value(attributeValue)
.build())))
.build();
}
protected InstanceGroup instanceGroupDS() {
return instanceGroupWithAttributeDS(ATTRIBUTE_NAME, ATTRIBUTE_VALUE);
}
protected InstanceGroup instanceGroupWithAttributeDS(
String attributeName, String attributeValue) {
return InstanceGroup.builder()
.attributes(
new HashSet<>(
Arrays.asList(
Attribute.builder().name(attributeName).value(attributeValue).build())))
.build();
}
protected DeploymentConfiguration deploymentConfigurationDS() {
return DeploymentConfiguration.builder().build();
}
protected com.amazonaws.blox.frontend.models.DeploymentConfiguration deploymentConfigurationFE() {
return com.amazonaws.blox.frontend.models.DeploymentConfiguration.builder().build();
}
protected EnvironmentRevision environmentRevisionDS(
final EnvironmentId id, final InstanceGroup instanceGroup) {
return environmentRevisionDS(id, TASK_DEFINITION, instanceGroup);
}
protected EnvironmentRevision environmentRevisionDS(
final EnvironmentId id, final String taskDefinition, final InstanceGroup instanceGroup) {
return EnvironmentRevision.builder()
.environmentId(id)
.environmentRevisionId(ENVIRONMENT_REVISION_ID)
.instanceGroup(instanceGroup)
.taskDefinition(taskDefinition)
.createdTime(Instant.now())
.build();
}
protected Environment environmentDS(
final EnvironmentId id, final DeploymentConfiguration deploymentConfiguration) {
return Environment.builder()
.environmentId(id)
.role(ROLE)
.environmentType(ENVIRONMENT_TYPE)
.environmentHealth(HEALTHY)
.environmentStatus(STATUS)
.deploymentMethod(DEPLOYMENT_METHOD)
.deploymentConfiguration(deploymentConfiguration)
.createdTime(Instant.now())
.lastUpdatedTime(Instant.now())
.build();
}
}
| 41.365854 | 100 | 0.762235 |
f53a2c2bbdae7579fbd50197469047caa9291fc6 | 229 | package Taxi.controler;
public class DriverController {
// priemane na zaqven kurs i opredelqne ma cena
// end kurs
// pregled na all zavyrsheni kursove
// pregled na ocenkite ot kursovete i obshta ocenka
// more?
}
| 17.615385 | 52 | 0.720524 |
5fae7986648a934dddfd82076359652682591f90 | 5,640 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.component.lumberjack
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|lumberjack
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Exchange
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Processor
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|mock
operator|.
name|MockEndpoint
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|test
operator|.
name|AvailablePortFinder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|test
operator|.
name|junit4
operator|.
name|CamelTestSupport
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|BeforeClass
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_class
DECL|class|LumberjackDisconnectionTest
specifier|public
class|class
name|LumberjackDisconnectionTest
extends|extends
name|CamelTestSupport
block|{
DECL|field|port
specifier|private
specifier|static
name|int
name|port
decl_stmt|;
annotation|@
name|BeforeClass
DECL|method|beforeClass ()
specifier|public
specifier|static
name|void
name|beforeClass
parameter_list|()
block|{
name|port
operator|=
name|AvailablePortFinder
operator|.
name|getNextAvailable
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
specifier|public
name|void
name|configure
parameter_list|()
block|{
comment|// Lumberjack configured with something that throws an exception
name|from
argument_list|(
literal|"lumberjack:0.0.0.0:"
operator|+
name|port
argument_list|)
operator|.
name|process
argument_list|(
operator|new
name|ErrorProcessor
argument_list|()
argument_list|)
operator|.
name|to
argument_list|(
literal|"mock:output"
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
annotation|@
name|Test
DECL|method|shouldDisconnectUponError ()
specifier|public
name|void
name|shouldDisconnectUponError
parameter_list|()
throws|throws
name|Exception
block|{
comment|// We're expecting 3 messages with Maps
comment|// The fourth one crashed and we didn't received the next ones
name|MockEndpoint
name|mock
init|=
name|getMockEndpoint
argument_list|(
literal|"mock:output"
argument_list|)
decl_stmt|;
name|mock
operator|.
name|expectedMessageCount
argument_list|(
literal|3
argument_list|)
expr_stmt|;
name|mock
operator|.
name|allMessages
argument_list|()
operator|.
name|body
argument_list|()
operator|.
name|isInstanceOf
argument_list|(
name|Map
operator|.
name|class
argument_list|)
expr_stmt|;
comment|// When sending messages
name|List
argument_list|<
name|Integer
argument_list|>
name|responses
init|=
name|LumberjackUtil
operator|.
name|sendMessages
argument_list|(
name|port
argument_list|,
literal|null
argument_list|)
decl_stmt|;
comment|// Then we should have the messages we're expecting
name|mock
operator|.
name|assertIsSatisfied
argument_list|()
expr_stmt|;
comment|// And no acknowledgment is received
name|assertCollectionSize
argument_list|(
name|responses
argument_list|,
literal|0
argument_list|)
expr_stmt|;
block|}
comment|/** * This processor throws an exception as the fourth message received. */
DECL|class|ErrorProcessor
specifier|private
specifier|static
specifier|final
class|class
name|ErrorProcessor
implements|implements
name|Processor
block|{
DECL|field|count
name|int
name|count
decl_stmt|;
annotation|@
name|Override
DECL|method|process (Exchange exchange)
specifier|public
name|void
name|process
parameter_list|(
name|Exchange
name|exchange
parameter_list|)
throws|throws
name|Exception
block|{
name|count
operator|++
expr_stmt|;
if|if
condition|(
name|count
operator|==
literal|4
condition|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
literal|"Ooops"
argument_list|)
throw|;
block|}
block|}
block|}
block|}
end_class
end_unit
| 16.443149 | 810 | 0.801418 |
0e3d571ef32da00b62d179eafef3e7ddc7d7d88e | 1,579 | /**
* FileInfo.java
*
* For hold some information of a file's features
*/
package com.sciome.bmdexpress2.util.annotation;
import java.io.File;
public class FileInfo {
private String httpURL = null, fName = null;
private File file = null;
private int fSize = 0;
private long lastModified = 0;
private boolean accessible = false;
private Exception fException = null;
public FileInfo() {
}
public FileInfo(String url, File f) {
httpURL = url;
file = f;
}
public FileInfo(String name) {
fName = name;
}
public FileInfo(File f) {
file = f;
}
public void setName(String name) {
fName = name;
}
public void setLastModified(long date) {
lastModified = date;
}
public void setSize(int size) {
fSize = size;
}
public void setAccessible(boolean bool) {
accessible = bool;
}
public void setException(Exception e) {
fException = e;
}
/**
* return info
*/
public String getName() {
return fName;
}
public String getHttpURL() {
return httpURL;
}
public File getFile() {
return file;
}
public long getLastModified() {
return lastModified;
}
public int getSize() {
return fSize;
}
public boolean isAccessible() {
return accessible;
}
public Exception getException() {
return fException;
}
}
| 18.360465 | 51 | 0.542115 |
5561f6f66924b1895162504027686c5bb34728cd | 449 | package pw.dotdash.mukkit.impl.command;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.SimpleCommandMap;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
public class MukkitCommandMap extends SimpleCommandMap {
public MukkitCommandMap(@NotNull Server server) {
super(server);
}
public Map<String, Command> getKnownCommands() {
return this.knownCommands;
}
} | 23.631579 | 56 | 0.750557 |
71d9718ea4ab557c16296f58c6257e2f8a5b5fe8 | 2,251 | /*
* Copyright (c) 2008-2016, GigaSpaces Technologies, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openspaces.events.notify;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Controls which type of notifications will be sent.
*
* @author kimchy
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotifyType {
/**
* Should this listener be notified when write occurs and it matches the given template.
*/
boolean write() default false;
/**
* Should this listener be notified when take occurs and it matches the given template.
*/
boolean take() default false;
/**
* Should this listener be notified when update occurs and it matches the given template.
*/
boolean update() default false;
/**
* Should this listener be notified when lease expiration occurs and it matches the given
* template.
*/
boolean leaseExpire() default false;
/**
* Should this listener be notified when entries that no longer match the provided template be
* notified.
*/
boolean unmatched() default false;
/**
* Should this listener be notified when entries that weren't match to a provided template
* become match after an update occurs.
*
* @since 9.1
*/
boolean matchedUpdate() default false;
/**
* Should this listener be notified when entries that were already match to a provided template
* stays match after an update occurs.
*
* @since 9.1
*/
boolean rematchedUpdate() default false;
}
| 29.233766 | 99 | 0.699689 |
c2bda9e4c22d4c87249eaa21735a573d1dee4f85 | 13,423 | package io.hashimati.microcli.config;
import io.micronaut.context.annotation.Factory;
import javax.inject.Singleton;
import java.util.HashMap;
@Factory
public class FeaturesFactory {
@Singleton
public static HashMap<String, Feature> features(){
HashMap<String, Feature> features = new HashMap<>();
features.putIfAbsent("flyway", new Feature(){{
setName("flyway");
setGradle(" implementation(\"io.micronaut.flyway:micronaut-flyway\")");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.flyway</groupId>\n" +
"\t\t<artifactId>micronaut-flyway</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>");
}});
features.put("jdbc-hikari", new Feature(){{
setName("jdbc-hikari");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.sql</groupId>\n" +
"\t\t<artifactId>micronaut-jdbc-hikari</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>\n");
setGradle(" implementation(\"io.micronaut.sql:micronaut-jdbc-hikari\")");
}});
features.put("data-jdbc", new Feature(){{
setName("data-jdbc");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.data</groupId>\n" +
"\t\t<artifactId>micronaut-data-jdbc</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>");
setGradle(" implementation(\"io.micronaut.data:micronaut-data-jdbc\")");
setAnnotationGradle(" annotationProcessor(\"io.micronaut.data:micronaut-data-processor\")");
setAnnotationMaven(
" <path>\n" +
" <groupId>io.micronaut.data</groupId>\n" +
" <artifactId>micronaut-data-processor</artifactId>\n" +
" <version>${micronaut.data.version}</version>\n" +
" </path>");
setVersionProperties("<micronaut.data.version>1.1.3</micronaut.data.version>");
}});
features.put("mongo-reactive", new Feature(){{
setName("mongo-reactive");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.mongodb</groupId>\n" +
"\t\t<artifactId>micronaut-mongo-reactive</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>\n");
setGradle(" implementation(\"io.micronaut.mongodb:micronaut-mongo-reactive\")");
}});
features.put("data-jpa", new Feature(){{
setName("data-jpa");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.data</groupId>\n" +
"\t\t<artifactId>micronaut-data-hibernate-jpa</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>\n");
setGradle(" implementation(\"io.micronaut.data:micronaut-data-hibernate-jpa\")");
setAnnotationGradle(" annotationProcessor(\"io.micronaut.data:micronaut-data-processor\")");
setAnnotationMaven(" <path>\n" +
" <groupId>io.micronaut.data</groupId>\n" +
" <artifactId>micronaut-data-processor</artifactId>\n" +
" <version>${micronaut.data.version}</version>\n" +
" </path>");
setVersionProperties("<micronaut.data.version>1.1.3</micronaut.data.version>");
}});
features.put("mongo-sync", new Feature(){{
setName("mongo-sync");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.mongodb</groupId>\n" +
"\t\t<artifactId>micronaut-mongo-sync</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>\n");
setGradle(" implementation(\"io.micronaut.mongodb:micronaut-mongo-sync\")");
}});
features.put("liquibase", new Feature(){{
setName("liquibase");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.liquibase</groupId>\n" +
"\t\t<artifactId>micronaut-liquibase</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>\n");
setGradle(" implementation(\"io.micronaut.liquibase:micronaut-liquibase\")");
}});
features.put("embed.mongo", new Feature(){{
setName("embed.mongo");
setMaven("\t<dependency>\n" +
"\t\t<groupId>de.flapdoodle.embed</groupId>\n" +
"\t\t<artifactId>de.flapdoodle.embed.mongo</artifactId>\n" +
"\t\t<version>2.0.1</version>\n" +
"\t\t<scope>test</scope>\n" +
"\t</dependency>\n");
setGradle(" testImplementation(\"de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.0.1\")");
}});
features.put("h2", new Feature(){{
setName("h2");
setMaven("\t<dependency>\n" +
"\t\t<groupId>com.h2database</groupId>\n" +
"\t\t<artifactId>h2</artifactId>\n" +
"\t\t<scope>runtime</scope>\n" +
"\t</dependency>\n");
setTestMaven("\t<dependency>\n" +
"\t\t<groupId>com.h2database</groupId>\n" +
"\t\t<artifactId>h2</artifactId>\n" +
"\t\t<scope>test</scope>\n" +
"\t\t<scope>test</scope>\n" +
"\t</dependency>\n");
setGradle(" runtimeOnly(\"com.h2database:h2\")");
setTestGradle(" testRuntimeOnly(\"com.h2database:h2\")");
}});
features.put("mysql", new Feature(){{
setName("mysql");
setMaven(" <dependency>\n" +
" <groupId>mysql</groupId>\n" +
" <artifactId>mysql-connector-java</artifactId>\n" +
" <scope>runtime</scope>\n" +
" </dependency>\n");
setGradle(" runtimeOnly(\"mysql:mysql-connector-java\")");
setTestGradle(" testRuntimeOnly(\"org.testcontainers:mysql\")");
setTestMaven(" <dependency>\n" +
" <groupId>org.testcontainers</groupId>\n" +
" <artifactId>mysql</artifactId>\n" +
" <scope>test</scope>\n" +
" </dependency>");
}});
features.put("testcontainers", new Feature(){{
setName("testcontainers");
setDepndencyManagement("<dependency>\n" +
" <groupId>org.testcontainers</groupId>\n" +
" <artifactId>testcontainers-bom</artifactId>\n" +
" <version>1.14.3</version>\n" +
" <type>pom</type>\n" +
" <scope>import</scope>\n" +
" </dependency>");
setTestContainerGradle(" testImplementation(platform(\"org.testcontainers:testcontainers-bom:1.14.3\"))");
}});
features.put("postgres", new Feature(){{
setName("postgres");
setMaven(" <dependency>\n" +
" <groupId>org.postgresql</groupId>\n" +
" <artifactId>postgresql</artifactId>\n" +
" <scope>runtime</scope>\n" +
" </dependency>\n");
setMaven(" <dependency>\n" +
" <groupId>org.testcontainers</groupId>\n" +
" <artifactId>postgresql</artifactId>\n" +
" <scope>test</scope>\n" +
" </dependency>");
setGradle(" runtimeOnly(\"org.postgresql:postgresql\")\n");
setTestGradle(" testRuntimeOnly(\"org.testcontainers:postgresql\")");
}});
features.put("mariadb", new Feature(){{
setName("mariadb");
setMaven(" <dependency>\n" +
" <groupId>org.mariadb.jdbc</groupId>\n" +
" <artifactId>mariadb-java-client</artifactId>\n" +
" <scope>runtime</scope>\n" +
" </dependency>\n");
setTestMaven("<dependency>\n" +
" <groupId>org.testcontainers</groupId>\n" +
" <artifactId>mariadb</artifactId>\n" +
" <scope>test</scope>\n" +
" </dependency>");
setGradle(" runtimeOnly(\"org.mariadb.jdbc:mariadb-java-client\")\n");
setTestGradle(" testRuntimeOnly(\"org.testcontainers:mariadb\")\n");
}});
features.put("oracle", new Feature(){{
setName("oracle");
setMaven("<dependency>\n" +
" <groupId>com.oracle.ojdbc</groupId>\n" +
" <artifactId>ojdbc8</artifactId>\n" +
" <scope>runtime</scope>\n" +
" </dependency>\n");
setTestMaven(" <dependency>\n" +
" <groupId>org.testcontainers</groupId>\n" +
" <artifactId>oracle-xe</artifactId>\n" +
" <scope>test</scope>\n" +
" </dependency>");
setGradle(" runtimeOnly(\"com.oracle.ojdbc:ojdbc8\")\n");
setTestGradle(" testRuntimeOnly(\"org.testcontainers:oracle-xe\")\n");
}});
features.put("sqlserver", new Feature(){{
setName("sqlserver");
setMaven(" <dependency>\n" +
" <groupId>com.microsoft.sqlserver</groupId>\n" +
" <artifactId>mssql-jdbc</artifactId>\n" +
" <scope>runtime</scope>\n" +
" </dependency>\n");
setGradle(" runtimeOnly(\"com.microsoft.sqlserver:mssql-jdbc\")\n");
setTestGradle(" testRuntimeOnly(\"org.testcontainers:mssqlserver\")");
setTestMaven(" <dependency>\n" +
" <groupId>org.testcontainers</groupId>\n" +
" <artifactId>mssqlserver</artifactId>\n" +
" <scope>test</scope>\n" +
" </dependency>");
}});
features.put("graphql", new Feature(){{
setName("graphql");
setMaven("\t<dependency>\n" +
"\t\t<groupId>io.micronaut.graphql</groupId>\n" +
"\t\t<artifactId>micronaut-graphql</artifactId>\n" +
"\t\t<scope>compile</scope>\n" +
"\t</dependency>");
setGradle(" implementation(\"io.micronaut.graphql:micronaut-graphql\")\n");
}});
features.put("openapi", new Feature(){{
setName("openapi");
setMaven(" <dependency>\n" +
" <groupId>io.swagger.core.v3</groupId>\n" +
" <artifactId>swagger-annotations</artifactId>\n" +
" <scope>compile</scope>\n" +
" </dependency>");
setGradle(" implementation(\"io.swagger.core.v3:swagger-annotations\")");
setAnnotationGradle(" annotationProcessor(\"io.micronaut.configuration:micronaut-openapi\")");
setAnnotationMaven(
" <path>\n" +
" <groupId>io.micronaut.configuration</groupId>\n" +
" <artifactId>micronaut-openapi</artifactId>\n" +
" <version>${micronaut.openapi.version}</version>\n" +
" </path>");
}});
features.put("lombok", new Feature(){{
setName("lombok");
setMaven("\t<dependency>\n" +
"\t\t<groupId>org.projectlombok</groupId>\n" +
"\t\t<artifactId>lombok</artifactId>\n" +
"\t\t<version>1.18.12</version>\n" +
"\t\t<scope>provided</scope>\n" +
"\t</dependency>");
setAnnotationMaven(
" <path>\n" +
" <groupId>org.projectlombok</groupId>\n" +
" <artifactId>lombok</artifactId>\n" +
" <version>1.18.12</version>\n" +
" </path>");
setGradle(" compileOnly 'org.projectlombok:lombok:1.18.12'\n");
setAnnotationGradle("\n annotationProcessor 'org.projectlombok:lombok:1.18.12'");
setTestGradleAnnotation(" testAnnotationProcessor 'org.projectlombok:lombok:1.18.12'");
setTestGradle(" testCompileOnly 'org.projectlombok:lombok:1.18.12'\n");
}});
return features;
}
}
| 47.098246 | 121 | 0.471057 |
71a98f66f0e4ba31b51eacf49d91f6b5404796bc | 1,701 | package freeseawind.lf.basic.button;
import java.awt.Color;
import java.io.Serializable;
/**
* Button color attribute class
*
* @author freeseawind@github
* @version 1.0
*/
public class LuckButtonColorInfo implements Serializable
{
private static final long serialVersionUID = -6352677081768535770L;
// Initial state color
private Color normalColor;
// The color of the mouse over time
private Color rollverColor;
// The color of the mouse click
private Color pressedColor;
// The Button font color
private Color fontColor;
/**
*
* @param normal Initial state color
*
* @param rollver The color of the mouse over time
*
* @param pressed The color of the mouse click
*
* @param font The Button font color
*
*/
public LuckButtonColorInfo(Color normal,
Color rollver,
Color pressed,
Color font)
{
this.normalColor = normal;
this.rollverColor = rollver;
this.pressedColor = pressed;
this.fontColor = font;
}
/**
*
* @return <code>Color</code>
*/
public Color getNormalColor()
{
return normalColor;
}
/**
*
* @return <code>Color</code>
*/
public Color getRollverColor()
{
return rollverColor;
}
/**
*
* @return <code>Color</code>
*/
public Color getPressedColor()
{
return pressedColor;
}
/**
*
* @return <code>Color</code>
*/
public Color getFontColor()
{
return fontColor;
}
}
| 19.77907 | 72 | 0.553204 |
b4c9185d781f6373889597eb84df7234c056c0fa | 3,257 | package com.olacabs.dp.utils;
import com.olacabs.dp.exceptions.HttpFailureException;
import com.olacabs.dp.foster.models.metastore.Schema;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
public class HttpPostClient {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpPostClient.class);
public String post(String url , String contentType, Object content) throws HttpFailureException {
DefaultHttpClient httpClient = null;
StringBuilder responseStr = null;
try {
httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
HttpPost postRequest = new HttpPost(url);
StringEntity input = new StringEntity(content.toString());
input.setContentType(contentType);
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode != 200 && responseCode != 201 && responseCode != 202) {
throw new HttpFailureException("Failed : HTTP error code : "
+ responseCode);
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
responseStr = new StringBuilder();
while ((output = br.readLine()) != null) {
LOGGER.debug("Response Received : {} ", output);
responseStr.append(output);
}
} catch (MalformedURLException e) {
LOGGER.error("",e);
} catch (IOException e) {
LOGGER.error("", e);
}finally {
if(httpClient != null)
httpClient.getConnectionManager().shutdown();
}
return responseStr != null ? responseStr.toString() : null;
}
public static void main(String[] args) throws Exception {
HttpPostClient httpPostClient = new HttpPostClient();
Schema entitySchema = new Schema();
entitySchema.setNamespace("DP");
entitySchema.setObjectName("Test");
entitySchema.setColumns("");
String content = "{\"org\":\"ola\",\"tenant\":\"localhost\",\"namespace\":\"ola\",\"objectName\":\"test11\",\"schema_type\":\"table\",\"columns\":\"{\\\"id\\\":\\\"int\\\"}\",\"entityId\":null,\"status\":1,\"id\":null,\"createdAt\":\"1466589182862\",\"updatedAt\":\"1466589182862\",\"createdBy\":\"maxwell\",\"updatedBy\":\"maxwell\",\"primaryKey\":\"[\\\"id\\\"]\",\"schemaVersion\":\"0\"}";
httpPostClient.post("http://metastore-server.mlbstg.corp.olacabs.com/v1/schema/", "application/json", content);
}
}
| 41.227848 | 400 | 0.642616 |
60b6ccb85f347bd3e0a64ec4b255889f9d203eaf | 14,886 | /*
* 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.
*
* Copyright 2012-2020 the original author or authors.
*/
package org.assertj.core.api.recursive.comparison;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.api.recursive.comparison.Color.BLUE;
import static org.assertj.core.api.recursive.comparison.Color.GREEN;
import static org.assertj.core.api.recursive.comparison.ColorWithCode.RED;
import static org.assertj.core.api.recursive.comparison.RecursiveComparisonAssert_isEqualTo_Test.EmployeeDTO.JobTitle.QA_ENGINEER;
import static org.assertj.core.error.ShouldBeEqual.shouldBeEqual;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
import static org.assertj.core.test.AlwaysEqualComparator.ALWAY_EQUALS_STRING;
import static org.assertj.core.util.Lists.list;
import static org.junit.jupiter.api.condition.OS.WINDOWS;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.Mockito.verify;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
import java.util.stream.Stream;
import org.assertj.core.api.RecursiveComparisonAssert_isEqualTo_BaseTest;
import org.assertj.core.internal.objects.data.AlwaysEqualPerson;
import org.assertj.core.internal.objects.data.FriendlyPerson;
import org.assertj.core.internal.objects.data.Giant;
import org.assertj.core.internal.objects.data.Human;
import org.assertj.core.internal.objects.data.Person;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@DisplayName("RecursiveComparisonAssert isEqualTo")
class RecursiveComparisonAssert_isEqualTo_Test extends RecursiveComparisonAssert_isEqualTo_BaseTest {
@Test
void should_pass_when_actual_and_expected_are_null() {
// GIVEN
Person actual = null;
Person expected = null;
// THEN
assertThat(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
@Test
void should_fail_when_actual_is_null_and_expected_is_not() {
// GIVEN
Person actual = null;
Person expected = new Person();
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
verify(failures).failure(info, shouldNotBeNull());
}
@Test
void should_fail_when_actual_is_not_null_and_expected_is() {
// GIVEN
Person actual = new Person();
Person expected = null;
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
verify(failures).failure(info, shouldBeEqual(actual, null, objects.getComparisonStrategy(), info.representation()));
}
@Test
void should_propagate_comparators_by_type() {
// GIVEN
Person actual = new Person("John");
// WHEN
RecursiveComparisonConfiguration assertion = assertThat(actual).usingComparatorForType(ALWAY_EQUALS_STRING, String.class)
.usingRecursiveComparison()
.getRecursiveComparisonConfiguration();
// THEN
assertThat(assertion.comparatorByTypes()).contains(entry(String.class, ALWAY_EQUALS_STRING));
}
@Test
void should_not_use_equal_implementation_of_root_objects_to_compare() {
// GIVEN
AlwaysEqualPerson actual = new AlwaysEqualPerson();
actual.name = "John";
actual.home.address.number = 1;
AlwaysEqualPerson expected = new AlwaysEqualPerson();
expected.name = "John";
expected.home.address.number = 2;
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference numberDifference = diff("home.address.number", actual.home.address.number, expected.home.address.number);
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, numberDifference);
}
@Test
void should_treat_date_as_equal_to_timestamp() {
// GIVEN
Person actual = new Person("Fred");
actual.dateOfBirth = new Date(1000L);
Person expected = new Person("Fred");
expected.dateOfBirth = new Timestamp(1000L);
// THEN
assertThat(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
@Test
void should_be_able_to_compare_objects_with_percentages() {
// GIVEN
Person actual = new Person("foo");
Person expected = new Person("%foo");
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference nameDifference = diff("name", actual.name, expected.name);
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, nameDifference);
}
@Test
void should_fail_when_fields_of_different_nesting_levels_differ() {
// GIVEN
Person actual = new Person("John");
actual.home.address.number = 1;
Person expected = new Person("Jack");
expected.home.address.number = 2;
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference nameDifference = diff("name", actual.name, expected.name);
ComparisonDifference numberDifference = diff("home.address.number", actual.home.address.number, expected.home.address.number);
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, numberDifference, nameDifference);
}
@SuppressWarnings("unused")
@ParameterizedTest(name = "{2}: actual={0} / expected={1}")
@MethodSource("recursivelyEqualObjects")
void should_pass_for_objects_with_the_same_data_when_using_the_default_recursive_comparison(Object actual,
Object expected,
String testDescription) {
assertThat(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
private static Stream<Arguments> recursivelyEqualObjects() {
Person person1 = new Person("John");
person1.home.address.number = 1;
Person person2 = new Person("John");
person2.home.address.number = 1;
Person person3 = new Person("John");
person3.home.address.number = 1;
Human person4 = new Human();
person4.name = "John";
person4.home.address.number = 1;
return Stream.of(arguments(person1, person2, "same data, same type"),
arguments(person2, person1, "same data, same type reversed"),
arguments(person3, person4, "same data, different type"),
arguments(new Theme(RED), new Theme(RED), "same data with enum overriding methods - covers #1866"),
arguments(person4, person3, "same data, different type"));
}
@Test
void should_be_able_to_compare_objects_with_direct_cycles() {
// GIVEN
Person actual = new Person("John");
actual.home.address.number = 1;
Person expected = new Person("John");
expected.home.address.number = 1;
// neighbour
expected.neighbour = actual;
actual.neighbour = expected;
// THEN
assertThat(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
@Test
void should_be_able_to_compare_objects_with_cycles_in_ordered_collection() {
// GIVEN
FriendlyPerson actual = new FriendlyPerson();
actual.name = "John";
actual.home.address.number = 1;
FriendlyPerson expected = new FriendlyPerson();
expected.name = "John";
expected.home.address.number = 1;
// neighbour
expected.neighbour = actual;
actual.neighbour = expected;
// friends
FriendlyPerson sherlock = new FriendlyPerson();
sherlock.name = "Sherlock";
sherlock.home.address.number = 221;
actual.friends.add(sherlock);
actual.friends.add(expected);
expected.friends.add(sherlock);
expected.friends.add(actual);
// THEN
assertThat(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
@Test
void should_be_able_to_compare_objects_with_cycles_in_ordered_and_unordered_collection() {
// GIVEN
FriendlyPerson actual = new FriendlyPerson();
actual.name = "John";
actual.home.address.number = 1;
FriendlyPerson expected = new FriendlyPerson();
expected.name = "John";
expected.home.address.number = 1;
// neighbour - direct cycle
expected.neighbour = actual;
actual.neighbour = expected;
// friends cycle with intermediate collection
FriendlyPerson sherlock = new FriendlyPerson();
sherlock.name = "Sherlock";
sherlock.home.address.number = 221;
// ordered collections
actual.friends.add(sherlock);
actual.friends.add(expected);
expected.friends.add(sherlock);
expected.friends.add(actual);
// unordered collections
// this could cause an infinite recursion if we don't track correctly the visited objects
actual.otherFriends.add(actual);
actual.otherFriends.add(expected);
actual.otherFriends.add(sherlock);
expected.otherFriends.add(sherlock);
expected.otherFriends.add(expected);
expected.otherFriends.add(actual);
// THEN
assertThat(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
@Test
void should_report_difference_in_collection() {
// GIVEN
FriendlyPerson actual = new FriendlyPerson();
FriendlyPerson actualFriend = new FriendlyPerson();
actualFriend.home.address.number = 99;
actual.friends = list(actualFriend);
FriendlyPerson expected = new FriendlyPerson();
FriendlyPerson expectedFriend = new FriendlyPerson();
expectedFriend.home.address.number = 10;
expected.friends = list(expectedFriend);
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference friendNumberDifference = diff("friends.home.address.number", 99, 10);
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, friendNumberDifference);
}
@Test
void should_report_missing_property() {
// GIVEN
Giant actual = new Giant();
actual.name = "joe";
actual.height = 3.0;
Human expected = new Human();
expected.name = "joe";
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference missingFieldDifference = diff("", actual, expected,
"org.assertj.core.internal.objects.data.Giant can't be compared to org.assertj.core.internal.objects.data.Human as Human does not declare all Giant fields, it lacks these: [height]");
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, missingFieldDifference);
}
@Test
void should_not_compare_enum_recursively() {
// GIVEN
Light actual = new Light(GREEN);
Light expected = new Light(BLUE);
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference difference = diff("color", actual.color, expected.color);
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, difference);
}
@Test
void should_compare_enum_by_value_only_when_strictTypeChecking_mode_is_disabled() {
// GIVEN
Light actual = new Light(GREEN);
LightDto expected = new LightDto(ColorDto.GREEN);
// WHEN-THEN
then(actual).usingRecursiveComparison()
.isEqualTo(expected);
}
@Test
void should_fail_when_expected_is_an_enum_and_actual_is_not() {
// GIVEN
LightString actual = new LightString("GREEN");
Light expected = new Light(GREEN);
// WHEN
compareRecursivelyFailsAsExpected(actual, expected);
// THEN
ComparisonDifference difference = diff("color", "GREEN", GREEN,
"expected field is an enum but actual field is not (java.lang.String)");
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(actual, expected, difference);
}
@Test
void should_fail_when_actual_is_an_enum_and_expected_is_not() {
// GIVEN
Employee devPerson = new Employee("Example Name", "SOFTWARE_DEVELOPER");
BlogPost devBlogPost = new BlogPost(devPerson);
EmployeeDTO qaPersonDTO = new EmployeeDTO("Example Name", QA_ENGINEER);
BlogPostDTO qaBlogPostDTO = new BlogPostDTO(qaPersonDTO);
// WHEN
compareRecursivelyFailsAsExpected(qaBlogPostDTO, devBlogPost);
// THEN
ComparisonDifference difference = diff("author.jobTitle", QA_ENGINEER, "SOFTWARE_DEVELOPER");
verifyShouldBeEqualByComparingFieldByFieldRecursivelyCall(qaBlogPostDTO, devBlogPost, difference);
}
static class LightString {
public String color;
public LightString(String value) {
this.color = value;
}
}
@Test
@DisabledOnOs(WINDOWS)
void should_not_treat_Path_as_Iterable_to_avoid_infinite_recursion() {
final Container container1 = new Container("/tmp/example");
final Container container2 = new Container("/tmp/example");
assertThat(container1).usingRecursiveComparison()
.isEqualTo(container2)
.ignoringAllOverriddenEquals()
.isEqualTo(container2);
}
public static class Container {
private Path path;
public Container(String path) {
this.path = Paths.get(path);
}
public Path getPath() {
return path;
}
}
public static class BlogPost {
Employee author;
public BlogPost(Employee author) {
this.author = author;
}
}
public static class BlogPostDTO {
EmployeeDTO author;
public BlogPostDTO(EmployeeDTO author) {
this.author = author;
}
}
public static class Employee {
String name;
String jobTitle;
public Employee(String name, String jobTitle) {
this.name = name;
this.jobTitle = jobTitle;
}
}
public static class EmployeeDTO {
String name;
JobTitle jobTitle;
public EmployeeDTO(String name, JobTitle jobTitle) {
this.name = name;
this.jobTitle = jobTitle;
}
public enum JobTitle {
SOFTWARE_DEVELOPER, QA_ENGINEER
}
}
}
| 34.943662 | 238 | 0.703883 |
753f34cf9b710c3cc08ed366de0711af2fec083b | 2,728 | package com.billow.system.api;
import com.billow.base.workflow.component.WorkFlowExecute;
import com.billow.base.workflow.component.WorkFlowQuery;
import com.billow.base.workflow.vo.CustomPage;
import com.billow.base.workflow.vo.ProcessDefinitionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
/**
* 流程定义API
*
* @author liuyongtao
* @create 2019-08-29 16:31
*/
@Slf4j
@RestController
@RequestMapping("/actProcDefApi")
@Api(value = "工作流部署API")
public class ActProcDefApi {
@Autowired
private WorkFlowExecute workFlowExecute;
@Autowired
private WorkFlowQuery workFlowQuery;
@ApiOperation(value = "查询流程定义列表")
@PostMapping("/findProcDefList")
public CustomPage<ProcessDefinitionVo> findProcDefList(@RequestBody ProcessDefinitionVo vo) {
CustomPage<ProcessDefinitionVo> definitionPage = workFlowQuery.queryProcessDefinition(vo, vo.getOffset(), vo.getPageSize());
return definitionPage;
}
@ApiOperation(value = "挂起流程定义")
@PutMapping("/suspendProcess/{processDefinitionId}/{cascade}")
public void suspendProcess(@PathVariable String processDefinitionId, @PathVariable(required = false) boolean cascade) throws Exception {
if (cascade) {
workFlowExecute.suspendProcessCascade(processDefinitionId);
} else {
workFlowExecute.suspendProcess(processDefinitionId);
}
}
@ApiOperation(value = "激活流程定义")
@PutMapping("/activateProcess/{processDefinitionId}/{cascade}")
public void activateProcess(@PathVariable String processDefinitionId, @PathVariable(required = false) boolean cascade) throws Exception {
if (cascade) {
workFlowExecute.activateProcessCascade(processDefinitionId);
} else {
workFlowExecute.activateProcess(processDefinitionId);
}
}
@ApiOperation(value = "通过 key 查询到最新的一个流程定义")
@GetMapping("/findDefByKey/{key}")
public ProcessDefinitionVo findDefByKey(@PathVariable String key) {
ProcessDefinitionVo processDefinitionVo = workFlowQuery.queryProcessDefinitionByKey(key);
return processDefinitionVo;
}
}
| 37.888889 | 141 | 0.762097 |
69b0d1c736ca1f57e359f41e06159395b26ce7c6 | 1,056 | package test2;
import javax.xml.bind.annotation.*;
import java.util.List;
@XmlRootElement(name = "question")
@XmlAccessorType(XmlAccessType.FIELD)
public class Question {
private int id;
private String questionname;
@XmlElementWrapper(name = "answersC")
@XmlElement(name = "answer")
private List<Answer> answers;
public Question() {}
public Question(int id, String questionname, List<Answer> answers) {
super();
this.id = id;
this.questionname = questionname;
this.answers = answers;
}
//@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//@XmlElement
public String getQuestionname() {
return questionname;
}
public void setQuestionname(String questionname) {
this.questionname = questionname;
}
//@XmlElement
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
| 23.466667 | 72 | 0.629735 |
f4c10e494300e0a8eb536d021200d5ecb23527d8 | 7,650 | /**
* MIT License
*
* Copyright (c) 2018 - 2020 FormKiQ
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.formkiq.stacks.api.handler;
import static com.formkiq.lambda.apigateway.ApiResponseStatus.SC_OK;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.formkiq.lambda.apigateway.ApiAuthorizer;
import com.formkiq.lambda.apigateway.ApiGatewayRequestEvent;
import com.formkiq.lambda.apigateway.ApiGatewayRequestEventUtil;
import com.formkiq.lambda.apigateway.ApiGatewayRequestHandler;
import com.formkiq.lambda.apigateway.ApiRequestHandlerResponse;
import com.formkiq.lambda.apigateway.AwsServiceCache;
import com.formkiq.lambda.apigateway.exception.BadException;
import com.formkiq.stacks.api.ApiUrlResponse;
import com.formkiq.stacks.dynamodb.DocumentItem;
import com.formkiq.stacks.dynamodb.DocumentItemDynamoDb;
import com.formkiq.stacks.dynamodb.DocumentService;
import com.formkiq.stacks.dynamodb.DocumentTag;
import com.formkiq.stacks.dynamodb.DocumentTagType;
/** {@link ApiGatewayRequestHandler} for GET "/documents/upload". */
public class DocumentsUploadRequestHandler
implements ApiGatewayRequestHandler, ApiGatewayRequestEventUtil {
/** Default Duration Hours. */
private static final int DEFAULT_DURATION_HOURS = 48;
/** {@link DocumentsRestrictionsMaxDocuments}. */
private DocumentsRestrictionsMaxDocuments restrictionMaxDocuments =
new DocumentsRestrictionsMaxDocuments();
/** {@link DocumentsRestrictionsMaxContentLength}. */
private DocumentsRestrictionsMaxContentLength restrictionMaxContentLength =
new DocumentsRestrictionsMaxContentLength();
/**
* constructor.
*
*/
public DocumentsUploadRequestHandler() {}
@Override
public ApiRequestHandlerResponse get(final LambdaLogger logger,
final ApiGatewayRequestEvent event, final ApiAuthorizer authorizer,
final AwsServiceCache awsservice) throws Exception {
boolean documentExists = false;
Date date = new Date();
String documentId = UUID.randomUUID().toString();
String username = getCallingCognitoUsername(event);
DocumentItem item = new DocumentItemDynamoDb(documentId, date, username);
List<DocumentTag> tags = new ArrayList<>();
Map<String, String> query = event.getQueryStringParameters();
String siteId = authorizer.getSiteId();
DocumentService service = awsservice.documentService();
if (query != null && query.containsKey("path")) {
String path = query.get("path");
path = URLDecoder.decode(path, StandardCharsets.UTF_8.toString());
item.setPath(path);
tags.add(
new DocumentTag(documentId, "path", path, date, username, DocumentTagType.SYSTEMDEFINED));
}
String urlstring = generatePresignedUrl(awsservice, logger, siteId, documentId, query);
logger.log("generated presign url: " + urlstring + " for document " + documentId);
if (!documentExists) {
tags.add(new DocumentTag(documentId, "untagged", "true", date, username,
DocumentTagType.SYSTEMDEFINED));
String value = this.restrictionMaxDocuments.getValue(awsservice, siteId);
if (!this.restrictionMaxDocuments.enforced(awsservice, siteId, value)) {
logger.log("saving document: " + item.getDocumentId() + " on path " + item.getPath());
service.saveDocument(siteId, item, tags);
if (value != null) {
awsservice.documentCountService().incrementDocumentCount(siteId);
}
} else {
throw new BadException("Max Number of Documents reached");
}
}
return new ApiRequestHandlerResponse(SC_OK, new ApiUrlResponse(urlstring, documentId));
}
/**
* Generate Presigned URL.
*
* @param awsservice {@link AwsServiceCache}
* @param logger {@link LambdaLogger}
* @param siteId {@link String}
* @param documentId {@link String}
* @param query {@link Map}
* @return {@link String}
* @throws BadException BadException
*/
private String generatePresignedUrl(final AwsServiceCache awsservice, final LambdaLogger logger,
final String siteId, final String documentId, final Map<String, String> query)
throws BadException {
String key = siteId != null ? siteId + "/" + documentId : documentId;
Duration duration = caculateDuration(query);
Optional<Long> contentLength = calculateContentLength(awsservice, logger, query, siteId);
URL url = awsservice.s3Service().presignPostUrl(awsservice.documents3bucket(), key, duration,
contentLength);
String urlstring = url.toString();
return urlstring;
}
/**
* Calculate Content Length.
*
* @param awsservice {@link AwsServiceCache}
* @param logger {@link LambdaLogger}
* @param query {@link Map}
* @param siteId {@link String}
* @return {@link Optional} {@link Long}
* @throws BadException BadException
*/
private Optional<Long> calculateContentLength(final AwsServiceCache awsservice,
final LambdaLogger logger, final Map<String, String> query, final String siteId)
throws BadException {
Long contentLength = query != null && query.containsKey("contentLength")
? Long.valueOf(query.get("contentLength"))
: null;
String value = this.restrictionMaxContentLength.getValue(awsservice, siteId);
if (value != null
&& this.restrictionMaxContentLength.enforced(awsservice, siteId, value, contentLength)) {
if (contentLength == null) {
throw new BadException("'contentLength' is required");
}
String maxContentLengthBytes =
this.restrictionMaxContentLength.getValue(awsservice, siteId);
throw new BadException("'contentLength' cannot exceed " + maxContentLengthBytes + " bytes");
}
return contentLength != null ? Optional.of(contentLength) : Optional.empty();
}
/**
* Calculate Duration.
*
* @param query {@link Map}
* @return {@link Duration}
*/
private Duration caculateDuration(final Map<String, String> query) {
Integer durationHours =
query != null && query.containsKey("duration") ? Integer.valueOf(query.get("duration"))
: Integer.valueOf(DEFAULT_DURATION_HOURS);
Duration duration = Duration.ofHours(durationHours.intValue());
return duration;
}
@Override
public String getRequestUrl() {
return "/documents/upload";
}
}
| 36.956522 | 100 | 0.729412 |
2be11c38ccdefb3e5d07e75e7a1038fcda81ecd1 | 3,014 | package com.ppdai.das.core.client;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.tomcat.jdbc.pool.PooledConnection;
import com.ppdai.das.client.Hints;
import com.ppdai.das.core.HintEnum;
import com.ppdai.das.core.DasConfigureFactory;
import com.ppdai.das.core.DasException;
import com.ppdai.das.core.DasLogger;
public class DalConnection {
private Integer oldIsolationLevel;
private Integer newIsolationLevel;
private Connection conn;
private boolean master;
private String shardId;
private DbMeta meta;
private DasLogger logger;
private boolean needDiscard;;
public DalConnection(Connection conn, boolean master, String shardId, DbMeta meta) throws SQLException {
this.oldIsolationLevel = conn.getTransactionIsolation();
this.conn = conn;
this.master = master;
this.shardId = shardId;
this.meta = meta;
this.logger = DasConfigureFactory.getLogger();
}
public Connection getConn() {
return conn;
}
public boolean isMaster() {
return master;
}
public DbMeta getMeta() {
return meta;
}
public String getShardId() {
return shardId;
}
public String getDatabaseName() throws SQLException {
return meta.getDatabaseName();
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
if(conn.getAutoCommit() != autoCommit) {
conn.setAutoCommit(autoCommit);
}
}
public void applyHints(Hints hints) throws SQLException {
Integer level = hints.getInt(HintEnum.isolationLevel);
if(level == null || oldIsolationLevel.equals(level)) {
return;
}
newIsolationLevel = level;
conn.setTransactionIsolation(level);
}
public void error(Throwable e) {
needDiscard |= isDisconnectionException(e);
}
public void close() {
try {
if(conn == null || conn.isClosed()) {
return;
}
} catch (Throwable e) {
logger.error("Restore connection isolation level failed!", e);
}
try {
if(newIsolationLevel != null) {
conn.setTransactionIsolation(oldIsolationLevel);
}
} catch (Throwable e) {
logger.error("Restore connection isolation level failed!", e);
}
try {
if(needDiscard) {
markDiscard(conn);
}
conn.close();
} catch (Throwable e) {
logger.error("Close connection failed!", e);
}
conn = null;
}
private boolean isDisconnectionException(Throwable e) {
//Filter wrapping exception
while(e!= null && e instanceof DasException) {
e = e.getCause();
}
while(e!= null && !(e instanceof SQLException)) {
e = e.getCause();
}
if(e == null) {
return false;
}
SQLException se = (SQLException)e;
if(meta.getDatabaseCategory().isDisconnectionError(se.getSQLState())) {
return true;
}
return isDisconnectionException(se.getNextException());
}
private void markDiscard(Connection conn) throws SQLException {
PooledConnection pConn = (PooledConnection)conn.unwrap(PooledConnection.class);
pConn.setDiscarded(true);
}
}
| 23.184615 | 105 | 0.693762 |
4c6e8aa35f2b0b449129feb31e0f5f17d05ce61c | 517 | package org.example;
import java.util.HashMap;
import java.util.Map;
import org.gradle.api.tasks.Input;
public class TemplateData {
private String name;
private Map<String, String> variables;
public TemplateData(String name, Map<String, String> variables) {
this.name = name;
this.variables = new HashMap<>(variables);
}
@Input
public String getName() { return this.name; }
@Input
public Map<String, String> getVariables() {
return this.variables;
}
}
| 21.541667 | 69 | 0.667311 |
76892a4f80c86193392fddc211d3d48ef31a80aa | 4,973 | /*
* 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.iotdb.tsfile.encoding.decoder;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import org.apache.iotdb.tsfile.encoding.common.EndianType;
import org.apache.iotdb.tsfile.exception.encoding.TsFileDecodingException;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
import org.apache.iotdb.tsfile.utils.Binary;
public abstract class Decoder {
private static final String ERROR_MSG = "Decoder not found: %s , DataType is : %s";
private TSEncoding type;
public Decoder(TSEncoding type) {
this.type = type;
}
public void setType(TSEncoding type) {
this.type = type;
}
public TSEncoding getType() {
return type;
}
/**
* get Decoder object by type.
*
* @param type TSEncoding type
* @param dataType TSDataType
* @return Decoder object
*/
public static Decoder getDecoderByType(TSEncoding type, TSDataType dataType) {
// PLA and DFT encoding are not supported in current version
if (type == TSEncoding.PLAIN) {
return new PlainDecoder(EndianType.BIG_ENDIAN);
} else if (type == TSEncoding.RLE) {
switch (dataType) {
case BOOLEAN:
case INT32:
return new IntRleDecoder(EndianType.BIG_ENDIAN);
case INT64:
return new LongRleDecoder(EndianType.BIG_ENDIAN);
case FLOAT:
case DOUBLE:
return new FloatDecoder(TSEncoding.valueOf(type.toString()), dataType);
default:
throw new TsFileDecodingException(String.format(ERROR_MSG, type, dataType));
}
} else if (type == TSEncoding.TS_2DIFF) {
switch (dataType) {
case INT32:
return new DeltaBinaryDecoder.IntDeltaDecoder();
case INT64:
return new DeltaBinaryDecoder.LongDeltaDecoder();
case FLOAT:
case DOUBLE:
return new FloatDecoder(TSEncoding.valueOf(type.toString()), dataType);
default:
throw new TsFileDecodingException(
String.format(ERROR_MSG, type, dataType));
}
} else if (type == TSEncoding.GORILLA) {
switch (dataType) {
case FLOAT:
return new SinglePrecisionDecoder();
case DOUBLE:
return new DoublePrecisionDecoder();
default:
throw new TsFileDecodingException(
String.format(ERROR_MSG, type, dataType));
}
} else if (type == TSEncoding.REGULAR) {
switch (dataType) {
case INT32:
return new RegularDataDecoder.IntRegularDecoder();
case INT64:
return new RegularDataDecoder.LongRegularDecoder();
default:
throw new TsFileDecodingException(
String.format(ERROR_MSG, type, dataType));
}
} else {
throw new TsFileDecodingException(
String.format(ERROR_MSG, type, dataType));
}
}
public int readInt(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readInt is not supproted by Decoder");
}
public boolean readBoolean(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readBoolean is not supproted by Decoder");
}
public short readShort(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readShort is not supproted by Decoder");
}
public long readLong(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readLong is not supproted by Decoder");
}
public float readFloat(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readFloat is not supproted by Decoder");
}
public double readDouble(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readDouble is not supproted by Decoder");
}
public Binary readBinary(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readBinary is not supproted by Decoder");
}
public BigDecimal readBigDecimal(ByteBuffer buffer) {
throw new TsFileDecodingException("Method readBigDecimal is not supproted by Decoder");
}
public abstract boolean hasNext(ByteBuffer buffer) throws IOException;
public abstract void reset();
}
| 33.153333 | 91 | 0.699377 |
41c8e224af3bb7c20390c267595605e1501e5e58 | 2,990 | package com.ankhrom.base.networking;
import android.content.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
@Deprecated
public class HttpCache {
public class HttpCacheItem {
private final Context context;
private final HttpCache httpCache;
private final String fileName;
public HttpCacheItem(Context context, HttpCache httpCache, String fileName) {
this.context = context;
this.httpCache = httpCache;
this.fileName = fileName;
}
public long getLastModifiedTime() {
File f = new File(httpCache.getCacheDir(), fileName);
if (f.exists()) {
return f.lastModified();
}
return 0;
}
public void setLastModifiedTime(long time) {
File f = new File(httpCache.getCacheDir(), fileName);
if (f.exists()) {
f.setLastModified(time);
}
}
public InputStream createInputStream() throws FileNotFoundException {
File f = new File(httpCache.getCacheDir(), fileName);
if (f.exists()) {
return new FileInputStream(f);
}
return null;
}
public OutputStream createOutputStream() throws IOException {
File f = new File(httpCache.getCacheDir(), fileName);
if (!f.exists()) {
f.createNewFile();
}
return new FileOutputStream(f);
}
}
final Context context;
public HttpCache(Context context) {
this.context = context;
}
public HttpCacheItem get(String url) {
return new HttpCacheItem(context, this, urlToFileName(url));
}
private File getCacheDir() {
File cacheDir = new File(context.getCacheDir(), "httpcache");
if (!cacheDir.exists()) {
cacheDir.mkdir();
}
return cacheDir;
}
String urlToFileName(String url) {
String hash = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] bytes = url.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
hash = byteArrayToHex(bytes);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return hash;
}
public static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format(Locale.US, "%02x", b & 0xff));
return sb.toString();
}
}
| 28.47619 | 85 | 0.597324 |
8d5d043e48fcd42c22f4933ad66eb9fa00cb7fff | 55,912 | /*
* 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.logging.log4j.spi;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.message.ParameterizedMessageFactory;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.status.StatusLogger;
/**
* Base implementation of a Logger. It is highly recommended that any Logger implementation extend this class.
*
*/
public abstract class AbstractLogger implements Logger {
/**
* Marker for flow tracing.
*/
public static final Marker FLOW_MARKER = MarkerManager.getMarker("FLOW");
/**
* Marker for method entry tracing.
*/
public static final Marker ENTRY_MARKER = MarkerManager.getMarker("ENTRY", FLOW_MARKER);
/**
* Marker for method exit tracing.
*/
public static final Marker EXIT_MARKER = MarkerManager.getMarker("EXIT", FLOW_MARKER);
/**
* Marker for exception tracing.
*/
public static final Marker EXCEPTION_MARKER = MarkerManager.getMarker("EXCEPTION");
/**
* Marker for throwing exceptions.
*/
public static final Marker THROWING_MARKER = MarkerManager.getMarker("THROWING", EXCEPTION_MARKER);
/**
* Marker for catching exceptions.
*/
public static final Marker CATCHING_MARKER = MarkerManager.getMarker("CATCHING", EXCEPTION_MARKER);
/**
* The default MessageFactory class.
*/
public static final Class<? extends MessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS =
ParameterizedMessageFactory.class;
private static final String FQCN = AbstractLogger.class.getName();
private static final String THROWING = "throwing";
private static final String CATCHING = "catching";
private final String name;
private final MessageFactory messageFactory;
/**
* Creates a new logger named after the class (or subclass).
*/
public AbstractLogger() {
this.name = getClass().getName();
this.messageFactory = createDefaultMessageFactory();
}
/**
* Creates a new named logger.
*
* @param name the logger name
*/
public AbstractLogger(final String name) {
this.name = name;
this.messageFactory = createDefaultMessageFactory();
}
/**
* Creates a new named logger.
*
* @param name the logger name
* @param messageFactory the message factory, if null then use the default message factory.
*/
public AbstractLogger(final String name, final MessageFactory messageFactory) {
this.name = name;
this.messageFactory = messageFactory == null ? createDefaultMessageFactory() : messageFactory;
}
/**
* Checks that the message factory a logger was created with is the same as the given messageFactory. If they are
* different log a warning to the {@linkplain StatusLogger}. A null MessageFactory translates to the default
* MessageFactory {@link #DEFAULT_MESSAGE_FACTORY_CLASS}.
*
* @param logger
* The logger to check
* @param messageFactory
* The message factory to check.
*/
public static void checkMessageFactory(final Logger logger, final MessageFactory messageFactory) {
final String name = logger.getName();
final MessageFactory loggerMessageFactory = logger.getMessageFactory();
if (messageFactory != null && !loggerMessageFactory.equals(messageFactory)) {
StatusLogger
.getLogger()
.warn("The Logger {} was created with the message factory {} and is now requested with the " +
"message factory {}, which may create log events with unexpected formatting.",
name, loggerMessageFactory, messageFactory);
} else if (messageFactory == null
&& !loggerMessageFactory.getClass().equals(DEFAULT_MESSAGE_FACTORY_CLASS)) {
StatusLogger
.getLogger()
.warn("The Logger {} was created with the message factory {} and is now requested with a null " +
"message factory (defaults to {}), which may create log events with unexpected formatting.",
name, loggerMessageFactory, DEFAULT_MESSAGE_FACTORY_CLASS.getName());
}
}
private MessageFactory createDefaultMessageFactory() {
try {
return DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
} catch (final InstantiationException e) {
throw new IllegalStateException(e);
} catch (final IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Logs entry to a method.
*/
public void entry() {
if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) {
log(ENTRY_MARKER, FQCN, Level.TRACE, messageFactory.newMessage(" entry"), null);
}
}
/**
* Logs entry to a method.
*
* @param params The parameters to the method.
*/
public void entry(final Object... params) {
if (isEnabled(Level.TRACE, ENTRY_MARKER, (Object) null, null)) {
log(ENTRY_MARKER, FQCN, Level.TRACE, entryMsg(params.length, params), null);
}
}
/**
* Logs exit from a method.
*/
public void exit() {
if (isEnabled(Level.TRACE, EXIT_MARKER, (Object) null, null)) {
log(EXIT_MARKER, FQCN, Level.TRACE, toExitMsg(null), null);
}
}
/**
* Logs exiting from a method with the result.
*
* @param <R> The type of the parameter and object being returned.
* @param result The result being returned from the method call.
* @return the Throwable.
*/
public <R> R exit(final R result) {
if (isEnabled(Level.TRACE, EXIT_MARKER, (Object) null, null)) {
log(EXIT_MARKER, FQCN, Level.TRACE, toExitMsg(result), null);
}
return result;
}
/**
* Logs a Throwable to be thrown.
*
* @param <T> the type of the Throwable.
* @param t The Throwable.
* @return the Throwable.
*/
public <T extends Throwable> T throwing(final T t) {
if (isEnabled(Level.ERROR, THROWING_MARKER, (Object) null, null)) {
log(THROWING_MARKER, FQCN, Level.ERROR, messageFactory.newMessage(THROWING), t);
}
return t;
}
/**
* Logs a Throwable to be thrown.
*
* @param <T> the type of the Throwable.
* @param level The logging Level.
* @param t The Throwable.
* @return the Throwable.
*/
public <T extends Throwable> T throwing(final Level level, final T t) {
if (isEnabled(level, THROWING_MARKER, (Object) null, null)) {
log(THROWING_MARKER, FQCN, level, messageFactory.newMessage(THROWING), t);
}
return t;
}
/**
* Logs a Throwable at the {@link Level#ERROR ERROR} level..
*
* @param t The Throwable.
*/
public void catching(final Throwable t) {
if (isEnabled(Level.ERROR, CATCHING_MARKER, (Object) null, null)) {
log(CATCHING_MARKER, FQCN, Level.ERROR, messageFactory.newMessage(CATCHING), t);
}
}
/**
* Logs a Throwable that has been caught.
*
* @param level The logging Level.
* @param t The Throwable.
*/
public void catching(final Level level, final Throwable t) {
if (isEnabled(level, CATCHING_MARKER, (Object) null, null)) {
log(CATCHING_MARKER, FQCN, level, messageFactory.newMessage(CATCHING), t);
}
}
/**
* Logs a message object with the {@link Level#TRACE TRACE} level.
*
* @param message the message object to log.
*/
public void trace(final String message) {
if (isEnabled(Level.TRACE, null, message)) {
log(null, FQCN, Level.TRACE, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#TRACE TRACE} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void trace(final Marker marker, final String message) {
if (isEnabled(Level.TRACE, marker, message)) {
log(marker, FQCN, Level.TRACE, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#TRACE TRACE} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
* <p/>
* <p>
* See {@link #debug(String)} form for more detailed information.
* </p>
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void trace(final String message, final Throwable t) {
if (isEnabled(Level.TRACE, null, message, t)) {
log(null, FQCN, Level.TRACE, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#TRACE TRACE} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
* <p/>
* <p>
* See {@link #debug(String)} form for more detailed information.
* </p>
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void trace(final Marker marker, final String message, final Throwable t) {
if (isEnabled(Level.TRACE, marker, message, t)) {
log(marker, FQCN, Level.TRACE, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message object with the {@link Level#TRACE TRACE} level.
*
* @param message the message object to log.
*/
public void trace(final Object message) {
if (isEnabled(Level.TRACE, null, message, null)) {
log(null, FQCN, Level.TRACE, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#TRACE TRACE} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void trace(final Marker marker, final Object message) {
if (isEnabled(Level.TRACE, marker, message, null)) {
log(marker, FQCN, Level.TRACE, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#TRACE TRACE} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
* <p/>
* <p>
* See {@link #debug(String)} form for more detailed information.
* </p>
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void trace(final Object message, final Throwable t) {
if (isEnabled(Level.TRACE, null, message, t)) {
log(null, FQCN, Level.TRACE, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#TRACE TRACE} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
* <p/>
* <p>
* See {@link #debug(String)} form for more detailed information.
* </p>
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void trace(final Marker marker, final Object message, final Throwable t) {
if (isEnabled(Level.TRACE, marker, message, t)) {
log(marker, FQCN, Level.TRACE, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message with parameters at the {@link Level#TRACE TRACE} level.
*
* @param message the message to log.
* @param params parameters to the message.
*/
public void trace(final String message, final Object... params) {
if (isEnabled(Level.TRACE, null, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(null, FQCN, Level.TRACE, msg, msg.getThrowable());
}
}
/**
* Logs a message with parameters at the {@link Level#TRACE TRACE} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param params parameters to the message.
*/
public void trace(final Marker marker, final String message, final Object... params) {
if (isEnabled(Level.TRACE, marker, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(marker, FQCN, Level.TRACE, msg, msg.getThrowable());
}
}
/**
* Checks whether this Logger is enabled for the TRACE Level.
*
* @return boolean - {@code true} if this Logger is enabled for level
* TRACE, {@code false} otherwise.
*/
public boolean isTraceEnabled() {
return isEnabled(Level.TRACE, null, (Object) null, null);
}
/**
* Checks whether this Logger is enabled for the TRACE Level.
*
* @param marker The marker data.
* @return boolean - {@code true} if this Logger is enabled for level
* TRACE, {@code false} otherwise.
*/
public boolean isTraceEnabled(final Marker marker) {
return isEnabled(Level.TRACE, marker, (Object) null, null);
}
/**
* Logs a message with the specific Marker at the TRACE level.
*
* @param msg the message string to be logged
*/
public void trace(final Message msg) {
if (isEnabled(Level.TRACE, null, msg, null)) {
log(null, FQCN, Level.TRACE, msg, null);
}
}
/**
* Logs a message with the specific Marker at the TRACE level.
*
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void trace(final Message msg, final Throwable t) {
if (isEnabled(Level.TRACE, null, msg, t)) {
log(null, FQCN, Level.TRACE, msg, t);
}
}
/**
* Logs a message with the specific Marker at the TRACE level.
*
* @param marker the marker data specific to this log statement.
* @param msg the message string to be logged
*/
public void trace(final Marker marker, final Message msg) {
if (isEnabled(Level.TRACE, marker, msg, null)) {
log(marker, FQCN, Level.TRACE, msg, null);
}
}
/**
* Logs a message with the specific Marker at the TRACE level.
*
* @param marker the marker data specific to this log statement.
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void trace(final Marker marker, final Message msg, final Throwable t) {
if (isEnabled(Level.TRACE, marker, msg, t)) {
log(marker, FQCN, Level.TRACE, msg, t);
}
}
/**
* Logs a message object with the {@link Level#DEBUG DEBUG} level.
*
* @param message the message object to log.
*/
public void debug(final String message) {
if (isEnabled(Level.DEBUG, null, message)) {
log(null, FQCN, Level.DEBUG, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#DEBUG DEBUG} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void debug(final Marker marker, final String message) {
if (isEnabled(Level.DEBUG, marker, message)) {
log(marker, FQCN, Level.DEBUG, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#DEBUG DEBUG} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message to log.
* @param t the exception to log, including its stack trace.
*/
public void debug(final String message, final Throwable t) {
if (isEnabled(Level.DEBUG, null, message, t)) {
log(null, FQCN, Level.DEBUG, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#DEBUG DEBUG} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param t the exception to log, including its stack trace.
*/
public void debug(final Marker marker, final String message, final Throwable t) {
if (isEnabled(Level.DEBUG, marker, message, t)) {
log(marker, FQCN, Level.DEBUG, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message object with the {@link Level#DEBUG DEBUG} level.
*
* @param message the message object to log.
*/
public void debug(final Object message) {
if (isEnabled(Level.DEBUG, null, message, null)) {
log(null, FQCN, Level.DEBUG, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#DEBUG DEBUG} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void debug(final Marker marker, final Object message) {
if (isEnabled(Level.DEBUG, marker, message, null)) {
log(marker, FQCN, Level.DEBUG, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#DEBUG DEBUG} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message to log.
* @param t the exception to log, including its stack trace.
*/
public void debug(final Object message, final Throwable t) {
if (isEnabled(Level.DEBUG, null, message, t)) {
log(null, FQCN, Level.DEBUG, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#DEBUG DEBUG} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param t the exception to log, including its stack trace.
*/
public void debug(final Marker marker, final Object message, final Throwable t) {
if (isEnabled(Level.DEBUG, marker, message, t)) {
log(marker, FQCN, Level.DEBUG, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message with parameters at the {@link Level#DEBUG DEBUG} level.
*
* @param message the message to log.
* @param params parameters to the message.
*/
public void debug(final String message, final Object... params) {
if (isEnabled(Level.DEBUG, null, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(null, FQCN, Level.DEBUG, msg, msg.getThrowable());
}
}
/**
* Logs a message with parameters at the {@link Level#DEBUG DEBUG} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param params parameters to the message.
*/
public void debug(final Marker marker, final String message, final Object... params) {
if (isEnabled(Level.DEBUG, marker, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(marker, FQCN, Level.DEBUG, msg, msg.getThrowable());
}
}
/**
* Checks whether this Logger is enabled for the DEBUG Level.
*
* @return boolean - {@code true} if this Logger is enabled for level
* DEBUG, {@code false} otherwise.
*/
public boolean isDebugEnabled() {
return isEnabled(Level.DEBUG, null, null);
}
/**
* Checks whether this Logger is enabled for the DEBUG Level.
*
* @param marker The marker data.
* @return boolean - {@code true} if this Logger is enabled for level
* DEBUG, {@code false} otherwise.
*/
public boolean isDebugEnabled(final Marker marker) {
return isEnabled(Level.DEBUG, marker, (Object) null, null);
}
/**
* Logs a message with the specific Marker at the DEBUG level.
*
* @param msg the message string to be logged
*/
public void debug(final Message msg) {
if (isEnabled(Level.DEBUG, null, msg, null)) {
log(null, FQCN, Level.DEBUG, msg, null);
}
}
/**
* Logs a message with the specific Marker at the DEBUG level.
*
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void debug(final Message msg, final Throwable t) {
if (isEnabled(Level.DEBUG, null, msg, t)) {
log(null, FQCN, Level.DEBUG, msg, t);
}
}
/**
* Logs a message with the specific Marker at the DEBUG level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
*/
public void debug(final Marker marker, final Message msg) {
if (isEnabled(Level.DEBUG, marker, msg, null)) {
log(marker, FQCN, Level.DEBUG, msg, null);
}
}
/**
* Logs a message with the specific Marker at the DEBUG level.
*
* @param marker the marker data specific to this log statement.
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void debug(final Marker marker, final Message msg, final Throwable t) {
if (isEnabled(Level.DEBUG, marker, msg, t)) {
log(marker, FQCN, Level.DEBUG, msg, t);
}
}
/**
* Logs a message object with the {@link Level#INFO INFO} level.
*
* @param message the message object to log.
*/
public void info(final String message) {
if (isEnabled(Level.INFO, null, message)) {
log(null, FQCN, Level.INFO, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#INFO INFO} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void info(final Marker marker, final String message) {
if (isEnabled(Level.INFO, marker, message)) {
log(marker, FQCN, Level.INFO, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#INFO INFO} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void info(final String message, final Throwable t) {
if (isEnabled(Level.INFO, null, message, t)) {
log(null, FQCN, Level.INFO, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#INFO INFO} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void info(final Marker marker, final String message, final Throwable t) {
if (isEnabled(Level.INFO, marker, message, t)) {
log(marker, FQCN, Level.INFO, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message object with the {@link Level#INFO INFO} level.
*
* @param message the message object to log.
*/
public void info(final Object message) {
if (isEnabled(Level.INFO, null, message, null)) {
log(null, FQCN, Level.INFO, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#INFO INFO} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void info(final Marker marker, final Object message) {
if (isEnabled(Level.INFO, marker, message, null)) {
log(marker, FQCN, Level.INFO, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#INFO INFO} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void info(final Object message, final Throwable t) {
if (isEnabled(Level.INFO, null, message, t)) {
log(null, FQCN, Level.INFO, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#INFO INFO} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void info(final Marker marker, final Object message, final Throwable t) {
if (isEnabled(Level.INFO, marker, message, t)) {
log(marker, FQCN, Level.INFO, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message with parameters at the {@link Level#INFO INFO} level.
*
* @param message the message to log.
* @param params parameters to the message.
*/
public void info(final String message, final Object... params) {
if (isEnabled(Level.INFO, null, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(null, FQCN, Level.INFO, msg, msg.getThrowable());
}
}
/**
* Logs a message with parameters at the {@link Level#INFO INFO} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param params parameters to the message.
*/
public void info(final Marker marker, final String message, final Object... params) {
if (isEnabled(Level.INFO, marker, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(marker, FQCN, Level.INFO, msg, msg.getThrowable());
}
}
/**
* Checks whether this Logger is enabled for the INFO Level.
*
* @return boolean - {@code true} if this Logger is enabled for level
* INFO, {@code false} otherwise.
*/
public boolean isInfoEnabled() {
return isEnabled(Level.INFO, null, (Object) null, null);
}
/**
* Checks whether this Logger is enabled for the INFO Level.
* @param marker The marker data.
* @return boolean - {@code true} if this Logger is enabled for level
* INFO, {@code false} otherwise.
*/
public boolean isInfoEnabled(final Marker marker) {
return isEnabled(Level.INFO, marker, (Object) null, null);
}
/**
* Logs a message with the specific Marker at the TRACE level.
*
* @param msg the message string to be logged
*/
public void info(final Message msg) {
if (isEnabled(Level.INFO, null, msg, null)) {
log(null, FQCN, Level.INFO, msg, null);
}
}
/**
* Logs a message with the specific Marker at the INFO level.
*
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void info(final Message msg, final Throwable t) {
if (isEnabled(Level.INFO, null, msg, t)) {
log(null, FQCN, Level.INFO, msg, t);
}
}
/**
* Logs a message with the specific Marker at the INFO level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
*/
public void info(final Marker marker, final Message msg) {
if (isEnabled(Level.INFO, marker, msg, null)) {
log(marker, FQCN, Level.INFO, msg, null);
}
}
/**
* Logs a message with the specific Marker at the INFO level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void info(final Marker marker, final Message msg, final Throwable t) {
if (isEnabled(Level.INFO, marker, msg, t)) {
log(marker, FQCN, Level.INFO, msg, t);
}
}
/**
* Logs a message object with the {@link Level#WARN WARN} level.
*
* @param message the message object to log.
*/
public void warn(final String message) {
if (isEnabled(Level.WARN, null, message)) {
log(null, FQCN, Level.WARN, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#WARN WARN} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void warn(final Marker marker, final String message) {
if (isEnabled(Level.WARN, marker, message)) {
log(marker, FQCN, Level.WARN, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#WARN WARN} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void warn(final String message, final Throwable t) {
if (isEnabled(Level.WARN, null, message, t)) {
log(null, FQCN, Level.WARN, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#WARN WARN} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void warn(final Marker marker, final String message, final Throwable t) {
if (isEnabled(Level.WARN, marker, message, t)) {
log(marker, FQCN, Level.WARN, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message object with the {@link Level#WARN WARN} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void warn(final Marker marker, final Object message) {
if (isEnabled(Level.WARN, marker, message, null)) {
log(marker, FQCN, Level.WARN, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#WARN WARN} level.
*
* @param message the message object to log.
*/
public void warn(final Object message) {
if (isEnabled(Level.WARN, null, message, null)) {
log(null, FQCN, Level.WARN, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#WARN WARN} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void warn(final Object message, final Throwable t) {
if (isEnabled(Level.WARN, null, message, t)) {
log(null, FQCN, Level.WARN, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#WARN WARN} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void warn(final Marker marker, final Object message, final Throwable t) {
if (isEnabled(Level.WARN, marker, message, t)) {
log(marker, FQCN, Level.WARN, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message with parameters at the {@link Level#WARN WARN} level.
*
* @param message the message to log.
* @param params parameters to the message.
*/
public void warn(final String message, final Object... params) {
if (isEnabled(Level.WARN, null, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(null, FQCN, Level.WARN, msg, msg.getThrowable());
}
}
/**
* Logs a message with parameters at the {@link Level#WARN WARN} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param params parameters to the message.
*/
public void warn(final Marker marker, final String message, final Object... params) {
if (isEnabled(Level.WARN, marker, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(marker, FQCN, Level.WARN, msg, msg.getThrowable());
}
}
/**
* Checks whether this Logger is enabled for the WARN Level.
*
* @return boolean - {@code true} if this Logger is enabled for level
* WARN, {@code false} otherwise.
*/
public boolean isWarnEnabled() {
return isEnabled(Level.WARN, null, (Object) null, null);
}
/**
* Checks whether this Logger is enabled for the WARN Level.
*
* @param marker The marker data.
* @return boolean - {@code true} if this Logger is enabled for level
* WARN, {@code false} otherwise.
*/
public boolean isWarnEnabled(final Marker marker) {
return isEnabled(Level.WARN, marker, (Object) null, null);
}
/**
* Logs a message with the specific Marker at the WARN level.
*
* @param msg the message string to be logged
*/
public void warn(final Message msg) {
if (isEnabled(Level.WARN, null, msg, null)) {
log(null, FQCN, Level.WARN, msg, null);
}
}
/**
* Logs a message with the specific Marker at the WARN level.
*
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void warn(final Message msg, final Throwable t) {
if (isEnabled(Level.WARN, null, msg, t)) {
log(null, FQCN, Level.WARN, msg, t);
}
}
/**
* Logs a message with the specific Marker at the WARN level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
*/
public void warn(final Marker marker, final Message msg) {
if (isEnabled(Level.WARN, marker, msg, null)) {
log(marker, FQCN, Level.WARN, msg, null);
}
}
/**
* Logs a message with the specific Marker at the WARN level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void warn(final Marker marker, final Message msg, final Throwable t) {
if (isEnabled(Level.WARN, marker, msg, t)) {
log(marker, FQCN, Level.WARN, msg, t);
}
}
/**
* Logs a message object with the {@link Level#ERROR ERROR} level.
*
* @param message the message object to log.
*/
public void error(final String message) {
if (isEnabled(Level.ERROR, null, message)) {
log(null, FQCN, Level.ERROR, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#ERROR ERROR} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void error(final Marker marker, final String message) {
if (isEnabled(Level.ERROR, marker, message)) {
log(marker, FQCN, Level.ERROR, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#ERROR ERROR} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void error(final String message, final Throwable t) {
if (isEnabled(Level.ERROR, null, message, t)) {
log(null, FQCN, Level.ERROR, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#ERROR ERROR} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void error(final Marker marker, final String message, final Throwable t) {
if (isEnabled(Level.ERROR, marker, message, t)) {
log(marker, FQCN, Level.ERROR, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message object with the {@link Level#ERROR ERROR} level.
*
* @param message the message object to log.
*/
public void error(final Object message) {
if (isEnabled(Level.ERROR, null, message, null)) {
log(null, FQCN, Level.ERROR, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#ERROR ERROR} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void error(final Marker marker, final Object message) {
if (isEnabled(Level.ERROR, marker, message, null)) {
log(marker, FQCN, Level.ERROR, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#ERROR ERROR} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void error(final Object message, final Throwable t) {
if (isEnabled(Level.ERROR, null, message, t)) {
log(null, FQCN, Level.ERROR, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#ERROR ERROR} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void error(final Marker marker, final Object message, final Throwable t) {
if (isEnabled(Level.ERROR, marker, message, t)) {
log(marker, FQCN, Level.ERROR, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message with parameters at the {@link Level#ERROR ERROR} level.
*
* @param message the message to log.
* @param params parameters to the message.
*/
public void error(final String message, final Object... params) {
if (isEnabled(Level.ERROR, null, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(null, FQCN, Level.ERROR, msg, msg.getThrowable());
}
}
/**
* Logs a message with parameters at the {@link Level#ERROR ERROR} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param params parameters to the message.
*/
public void error(final Marker marker, final String message, final Object... params) {
if (isEnabled(Level.ERROR, marker, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(marker, FQCN, Level.ERROR, msg, msg.getThrowable());
}
}
/**
* Checks whether this Logger is enabled for the {@link Level#ERROR ERROR} Level.
*
* @return boolean - {@code true} if this Logger is enabled for level
* {@link Level#ERROR ERROR}, {@code false} otherwise.
*/
public boolean isErrorEnabled() {
return isEnabled(Level.ERROR, null, (Object) null, null);
}
/**
* Checks whether this Logger is enabled for the {@link Level#ERROR ERROR} Level.
*
* @param marker The marker data.
* @return boolean - {@code true} if this Logger is enabled for level
* {@link Level#ERROR ERROR}, {@code false} otherwise.
*/
public boolean isErrorEnabled(final Marker marker) {
return isEnabled(Level.ERROR, marker, (Object) null, null);
}
/**
* Logs a message with the specific Marker at the {@link Level#ERROR ERROR} level.
*
* @param msg the message string to be logged
*/
public void error(final Message msg) {
if (isEnabled(Level.ERROR, null, msg, null)) {
log(null, FQCN, Level.ERROR, msg, null);
}
}
/**
* Logs a message with the specific Marker at the {@link Level#ERROR ERROR} level.
*
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void error(final Message msg, final Throwable t) {
if (isEnabled(Level.ERROR, null, msg, t)) {
log(null, FQCN, Level.ERROR, msg, t);
}
}
/**
* Logs a message with the specific Marker at the {@link Level#ERROR ERROR} level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
*/
public void error(final Marker marker, final Message msg) {
if (isEnabled(Level.ERROR, marker, msg, null)) {
log(marker, FQCN, Level.ERROR, msg, null);
}
}
/**
* Logs a message with the specific Marker at the {@link Level#ERROR ERROR} level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void error(final Marker marker, final Message msg, final Throwable t) {
if (isEnabled(Level.ERROR, marker, msg, t)) {
log(marker, FQCN, Level.ERROR, msg, t);
}
}
/**
* Logs a message object with the {@link Level#FATAL FATAL} level.
*
* @param message the message object to log.
*/
public void fatal(final String message) {
if (isEnabled(Level.FATAL, null, message)) {
log(null, FQCN, Level.FATAL, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#FATAL FATAL} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void fatal(final Marker marker, final String message) {
if (isEnabled(Level.FATAL, marker, message)) {
log(marker, FQCN, Level.FATAL, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#FATAL FATAL} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void fatal(final String message, final Throwable t) {
if (isEnabled(Level.FATAL, null, message, t)) {
log(null, FQCN, Level.FATAL, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#FATAL FATAL} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void fatal(final Marker marker, final String message, final Throwable t) {
if (isEnabled(Level.FATAL, marker, message, t)) {
log(marker, FQCN, Level.FATAL, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message object with the {@link Level#FATAL FATAL} level.
*
* @param message the message object to log.
*/
public void fatal(final Object message) {
if (isEnabled(Level.FATAL, null, message, null)) {
log(null, FQCN, Level.FATAL, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message object with the {@link Level#FATAL FATAL} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
*/
public void fatal(final Marker marker, final Object message) {
if (isEnabled(Level.FATAL, marker, message, null)) {
log(marker, FQCN, Level.FATAL, messageFactory.newMessage(message), null);
}
}
/**
* Logs a message at the {@link Level#FATAL FATAL} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void fatal(final Object message, final Throwable t) {
if (isEnabled(Level.FATAL, null, message, t)) {
log(null, FQCN, Level.FATAL, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message at the {@link Level#FATAL FATAL} level including the
* stack trace of the {@link Throwable} <code>t</code> passed as parameter.
*
* @param marker the marker data specific to this log statement.
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
*/
public void fatal(final Marker marker, final Object message, final Throwable t) {
if (isEnabled(Level.FATAL, marker, message, t)) {
log(marker, FQCN, Level.FATAL, messageFactory.newMessage(message), t);
}
}
/**
* Logs a message with parameters at the {@link Level#FATAL FATAL} level.
*
* @param message the message to log.
* @param params parameters to the message.
*/
public void fatal(final String message, final Object... params) {
if (isEnabled(Level.FATAL, null, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(null, FQCN, Level.FATAL, msg, msg.getThrowable());
}
}
/**
* Logs a message with parameters at the {@link Level#FATAL FATAL} level.
*
* @param marker the marker data specific to this log statement.
* @param message the message to log.
* @param params parameters to the message.
*/
public void fatal(final Marker marker, final String message, final Object... params) {
if (isEnabled(Level.FATAL, marker, message, params)) {
final Message msg = messageFactory.newMessage(message, params);
log(marker, FQCN, Level.FATAL, msg, msg.getThrowable());
}
}
/**
* Checks whether this Logger is enabled for the FATAL Level.
*
* @return boolean - {@code true} if this Logger is enabled for level
* FATAL, {@code false} otherwise.
*/
public boolean isFatalEnabled() {
return isEnabled(Level.FATAL, null, (Object) null, null);
}
/**
* Checks whether this Logger is enabled for the FATAL Level.
*
* @param marker The marker data.
* @return boolean - {@code true} if this Logger is enabled for level
* FATAL, {@code false} otherwise.
*/
public boolean isFatalEnabled(final Marker marker) {
return isEnabled(Level.FATAL, marker, (Object) null, null);
}
/**
* Logs a message with the specific Marker at the FATAL level.
*
* @param msg the message string to be logged
*/
public void fatal(final Message msg) {
if (isEnabled(Level.FATAL, null, msg, null)) {
log(null, FQCN, Level.FATAL, msg, null);
}
}
/**
* Logs a message with the specific Marker at the FATAL level.
*
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void fatal(final Message msg, final Throwable t) {
if (isEnabled(Level.FATAL, null, msg, t)) {
log(null, FQCN, Level.FATAL, msg, t);
}
}
/**
* Logs a message with the specific Marker at the FATAL level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
*/
public void fatal(final Marker marker, final Message msg) {
if (isEnabled(Level.FATAL, marker, msg, null)) {
log(marker, FQCN, Level.FATAL, msg, null);
}
}
/**
* Logs a message with the specific Marker at the FATAL level.
*
* @param marker the marker data specific to this log statement
* @param msg the message string to be logged
* @param t A Throwable or null.
*/
public void fatal(final Marker marker, final Message msg, final Throwable t) {
if (isEnabled(Level.FATAL, marker, msg, t)) {
log(marker, FQCN, Level.FATAL, msg, t);
}
}
/**
* Logs a message with location information.
*
* @param marker The Marker
* @param fqcn The fully qualified class name of the <b>caller</b>
* @param level The logging level
* @param data The Message.
* @param t A Throwable or null.
*/
protected abstract void log(Marker marker, String fqcn, Level level, Message data, Throwable t);
/*
* Instead of one single method with Object... declared the following methods explicitly specify
* parameters because they perform dramatically better than having the JVM convert them to an
* array.
*/
/**
* Determine if logging is enabled.
* @param level The logging Level to check.
* @param marker A Marker or null.
* @param data The message.
* @return True if logging is enabled, false otherwise.
*/
protected abstract boolean isEnabled(Level level, Marker marker, String data);
/**
* Determine if logging is enabled.
* @param level The logging Level to check.
* @param marker A Marker or null.
* @param data The message.
* @param t A Throwable.
* @return True if logging is enabled, false otherwise.
*/
protected abstract boolean isEnabled(Level level, Marker marker, String data, Throwable t);
/**
* Determine if logging is enabled.
* @param level The logging Level to check.
* @param marker A Marker or null.
* @param data The message.
* @param p1 The parameters.
* @return True if logging is enabled, false otherwise.
*/
protected abstract boolean isEnabled(Level level, Marker marker, String data, Object... p1);
/**
* Determine if logging is enabled.
* @param level The logging Level to check.
* @param marker A Marker or null.
* @param data The message.
* @param t A Throwable.
* @return True if logging is enabled, false otherwise.
*/
protected abstract boolean isEnabled(Level level, Marker marker, Object data, Throwable t);
/**
* Checks whether this Logger is enabled for the the given Level.
* <p>
* Note that passing in {@link Level#OFF OFF} always returns {@code true}.
* </p>
* @param level the level to check
* @return boolean - {@code true} if this Logger is enabled for level, {@code false} otherwise.
*/
public boolean isEnabled(final Level level) {
return isEnabled(level, null, (Object) null, null);
}
/**
* Determine if logging is enabled.
* @param level The logging Level to check.
* @param marker A Marker or null.
* @param data The Message.
* @param t A Throwable.
* @return True if logging is enabled, false otherwise.
*/
protected abstract boolean isEnabled(Level level, Marker marker, Message data, Throwable t);
private Message entryMsg(final int count, final Object... params) {
if (count == 0) {
return messageFactory.newMessage(" entry");
}
final StringBuilder sb = new StringBuilder(" entry parms(");
int i = 0;
for (final Object parm : params) {
if (parm != null) {
sb.append(parm.toString());
} else {
sb.append("null");
}
if (++i < params.length) {
sb.append(", ");
}
}
sb.append(")");
return messageFactory.newMessage(sb.toString());
}
private Message toExitMsg(final Object result) {
if (result == null) {
return messageFactory.newMessage(" exit");
}
return messageFactory.newMessage(" exit with (" + result + ")");
}
/* (non-Javadoc)
* @see org.apache.logging.log4j.Logger#getName()
*/
public String getName() {
return name;
}
/**
* Returns a String representation of this instance in the form {@code "name"}.
* @return A String describing this Logger instance.
*/
@Override
public String toString() {
return name;
}
/**
* Gets the message factory.
*
* @return the message factory.
*/
public MessageFactory getMessageFactory() {
return messageFactory;
}
}
| 35.658163 | 117 | 0.614537 |
680bd43ee79d0738957358d859e0db9896654401 | 1,035 | /**
*
*/
package mx.com.extend.example;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* @author alexander
*
*/
public class UtilProperties {
/**
* Path del archivo properties
*/
private static final String AVRO_PROPERTIES = "C:\\ws\\avro\\avro-example\\src\\main\\resources\\avro.properties";
/**
*
*/
public UtilProperties() {
}
public static String getProperty(String nameProperty) {
/**Creamos un Objeto de tipo Properties*/
Properties propiedades = new Properties();
/**Cargamos el archivo desde la ruta especificada*/
try {
propiedades.load(new FileInputStream(AVRO_PROPERTIES));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/**Obtenemos los parametros definidos en el archivo*/
String property = propiedades.getProperty(nameProperty);
return property;
}
}
| 20.7 | 116 | 0.662802 |
bab56b84a45ff8118fc3e18d55a5195f0a8f9555 | 218 | import java.util.*;
class Test<K,V> {
private final Map<? extends K, ? extends V> m = null;
{
f(m.entrySet());
}
private static <A, B> void f(Set<? extends Map.Entry<? extends A, ? extends B>> s) {}
}
| 15.571429 | 87 | 0.577982 |
bd26d48ef672686f6745a88bb320631092c1b2e3 | 13,314 | /*
* Copyright (c) 2002-2019 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.javascript.host.dom;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.gargoylesoftware.htmlunit.BrowserRunner;
import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts;
import com.gargoylesoftware.htmlunit.util.MimeType;
import com.gargoylesoftware.htmlunit.WebDriverTestCase;
/**
* Tests for {@link Attr}.
*
* @author Marc Guillemot
* @author Ahmed Ashour
* @author Daniel Gredler
* @author Ronald Brill
* @author Frank Danek
*/
@RunWith(BrowserRunner.class)
public class AttrTest extends WebDriverTestCase {
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"true", "exception thrown"})
public void specified() throws Exception {
final String html
= "<html><head><title>foo</title><script>\n"
+ "function doTest() {\n"
+ " try {\n"
+ " var s = document.getElementById('testSelect');\n"
+ " var o1 = s.options[0];\n"
+ " alert(o1.getAttributeNode('value').specified);\n"
+ " var o2 = s.options[1];\n"
+ " alert(o2.getAttributeNode('value').specified);\n"
+ " } catch(e) {\n"
+ " alert('exception thrown');\n"
+ " }\n"
+ "}\n"
+ "</script></head><body onload='doTest()'>\n"
+ "<form name='form1'>\n"
+ " <select name='select1' id='testSelect'>\n"
+ " <option name='option1' value='foo'>One</option>\n"
+ " <option>Two</option>\n"
+ " </select>\n"
+ "</form>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* Trimming of "class" attributes during Firefox emulation was having the unintended side effect
* of setting the attribute's "specified" attribute to "false".
* @throws Exception if the test fails
*/
@Test
@Alerts({"true", "true"})
public void specified2() throws Exception {
final String html
= "<html><body onload='test()'><div id='div' class='test'></div>\n"
+ "<script>\n"
+ " function test() {\n"
+ " var div = document.getElementById('div');\n"
+ " alert(div.attributes.id.specified);\n"
+ " alert(div.attributes.class.specified);\n"
+ " }\n"
+ "</script>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("[object HTMLOptionElement]")
public void ownerElement() throws Exception {
final String html
= "<html><head><title>foo</title><script>\n"
+ "function doTest() {\n"
+ " var s = document.getElementById('testSelect');\n"
+ " var o1 = s.options[0];\n"
+ " alert(o1.getAttributeNode('value').ownerElement);\n"
+ "}\n"
+ "</script></head><body onload='doTest()'>\n"
+ "<form name='form1'>\n"
+ " <select name='select1' id='testSelect'>\n"
+ " <option name='option1' value='foo'>One</option>\n"
+ " <option>Two</option>\n"
+ " </select>\n"
+ "</form>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"undefined", "undefined", "undefined"})
public void isId() throws Exception {
final String html
= "<html><head><script>\n"
+ "function test() {\n"
+ " var d = document.getElementById('d');\n"
+ " alert(d.getAttributeNode('id').isId);\n"
+ " alert(d.getAttributeNode('name').isId);\n"
+ " alert(d.getAttributeNode('width').isId);\n"
+ "}\n"
+ "</script></head>\n"
+ "<body onload='test()'>\n"
+ "<div iD='d' name='d' width='40'></div>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = {"undefined", "undefined", "undefined", "undefined", "undefined"},
IE = {"false", "true", "false", "true", "true"})
public void expando() throws Exception {
final String html
= "<html><head><script>\n"
+ "function test() {\n"
+ " var d = document.getElementById('d');\n"
+ " alert(d.attributes['id'].expando);\n"
+ " alert(d.attributes['name'].expando);\n"
+ " alert(d.attributes['style'].expando);\n"
+ " alert(d.attributes['custom'].expando);\n"
+ " alert(d.attributes['other'].expando);\n"
+ "}\n"
+ "</script></head>\n"
+ "<body onload='test()'>\n"
+ " <div id='d' name='d' style='display: block' custom='value' other></div>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* Testcase for issue http://sourceforge.net/p/htmlunit/bugs/1493/.
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = "undefined",
IE = "false")
public void expandoEvent() throws Exception {
final String html
= "<html><head><script>\n"
+ "function test() {\n"
+ " var d = document.getElementById('d');\n"
+ " d.setAttribute('onfocusin', 't');\n"
+ " alert(d.attributes['onfocusin'].expando);\n"
+ "}\n"
+ "</script></head>\n"
+ "<body onload='test()'>\n"
+ " <div id='d'></div>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts("test()")
public void textContent() throws Exception {
final String html
= "<html><head><script>\n"
+ "function test() {\n"
+ " var a = document.body.getAttributeNode('onload');\n"
+ " alert(a.textContent);\n"
+ "}\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"null", "null", "null", "null"})
public void getAttributeNodeUndefinedAttribute() throws Exception {
final String html
= "<html><head><script>\n"
+ "function test() {\n"
+ " var elem = document.getElementById('myDiv');\n"
+ " alert(elem.getAttributeNode('class'));\n"
+ " alert(elem.getAttributeNode('style'));\n"
+ " alert(elem.getAttributeNode('unknown'));\n"
+ " alert(elem.getAttributeNode('name'));\n"
+ "}\n"
+ "</script></head><body onload='test()'>\n"
+ "<div id='myDiv'></div>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"null", "null", "null", "null"})
public void getAttributesUndefinedAttribute() throws Exception {
final String html
= "<html><head><script>\n"
+ "function test() {\n"
+ " var elem = document.getElementById('myDiv');\n"
+ " alert(elem.attributes.getNamedItem('class'));\n"
+ " alert(elem.attributes.getNamedItem('style'));\n"
+ " alert(elem.attributes.getNamedItem('unknown'));\n"
+ " alert(elem.attributes.getNamedItem('name'));\n"
+ "}\n"
+ "</script></head><body onload='test()'>\n"
+ "<div id='myDiv'></div>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "", "[object Attr]", ""})
public void value() throws Exception {
final String html = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " var attr = document.createAttribute('hi');\n"
+ " alert(attr);\n"
+ " alert(attr.value);\n"
+ " attr = document.implementation.createDocument('', '', null).createAttribute('hi');\n"
+ " alert(attr);\n"
+ " alert(attr.value);\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "undefined"})
public void html_baseName() throws Exception {
html("baseName");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = {"[object Attr]", "§§URL§§"},
IE = {"[object Attr]", "undefined"})
public void html_baseURI() throws Exception {
html("baseURI");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "null"})
public void html_namespaceURI() throws Exception {
html("namespaceURI");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = {"[object Attr]", "testattr"},
IE = {"[object Attr]", "testAttr"})
public void html_localName() throws Exception {
html("localName");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "null"})
public void html_prefix() throws Exception {
html("prefix");
}
private void html(final String methodName) throws Exception {
final String html
= "<html>\n"
+ "<script>\n"
+ " function test() {\n"
+ " debug(document.getElementById('tester').attributes.getNamedItem('testAttr'));\n"
+ " }\n"
+ " function debug(e) {\n"
+ " alert(e);\n"
+ " alert(e." + methodName + ");\n"
+ " }\n"
+ "</script>\n"
+ "</head>\n"
+ "<body onload='test()'>\n"
+ "<div id='tester' testAttr='test'></div>\n"
+ "</body></html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "undefined"})
public void xml_baseName() throws Exception {
xml("baseName");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = {"[object Attr]", "§§URL§§foo.xml"},
IE = {"[object Attr]", "undefined"})
public void xml_baseURI() throws Exception {
xml("baseURI");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "null"})
public void xml_namespaceURI() throws Exception {
xml("namespaceURI");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "testAttr"})
public void xml_localName() throws Exception {
xml("localName");
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts({"[object Attr]", "null"})
public void xml_prefix() throws Exception {
xml("prefix");
}
private void xml(final String methodName) throws Exception {
final String html =
"<html>\n"
+ " <head>\n"
+ " <script>\n"
+ " function test() {\n"
+ " var request;\n"
+ " request = new XMLHttpRequest();\n"
+ " request.open('GET', 'foo.xml', false);\n"
+ " request.send('');\n"
+ " var doc = request.responseXML;\n"
+ " debug(doc.documentElement.childNodes[0].attributes.item(0));\n"
+ " }\n"
+ " function debug(e) {\n"
+ " try {\n"
+ " alert(e);\n"
+ " } catch(ex) {alert(ex)}\n"
+ " alert(e." + methodName + ");\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='test()'>\n"
+ " </body>\n"
+ "</html>";
final String xml =
"<xml>"
+ "<div testAttr='test'></div>"
+ "</xml>";
getMockWebConnection().setDefaultResponse(xml, MimeType.TEXT_XML);
loadPageWithAlerts2(html);
}
}
| 32.15942 | 104 | 0.498723 |
45869721c2844e0e38b0ef45f305eb3c0ce73e8f | 3,290 | package net.emuman.commandbuilder;
import net.emuman.commandbuilder.exceptions.CommandStructureException;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import java.util.*;
import java.util.stream.Collectors;
public class SingleStringNode extends NodeBase {
private List<String> options;
/**
* A node for parsing an integer out of an argument
*
* @param name the name of the node
* @param options the list of words that can be passed
*/
public SingleStringNode(String name, List<String> options) {
super(name);
this.options = options;
}
/**
* A node for parsing an integer out of an argument
*
* @param name the name of the node
*/
public SingleStringNode(String name) {
super(name);
this.options = null;
}
@Override
public void onExecute(String[] args, Map<String, Object> values, CommandTraceLog traceLog)
throws CommandStructureException {
if (args.length == 0) {
addTraceLogData(traceLog, CommandTraceLog.ReturnCode.MISSING_ARGUMENT, null);
return;
}
String choice = args[0].toLowerCase();
// if there are specific options for this string
if (options != null && options.size() != 0) {
// make sure variable is in the list of options
if (!options.contains(choice)) {
addTraceLogData(traceLog, CommandTraceLog.ReturnCode.INVALID_ARGUMENT, null);
return;
}
}
addTraceLogData(traceLog, CommandTraceLog.ReturnCode.SUCCESS, choice);
values.put(getName(), choice);
if (getNodes().size() == 0) {
throw new CommandStructureException("SingleStringNode must point towards one other node");
}
getNodes().get(0).onExecute(Arrays.copyOfRange(args, 1, args.length), values, traceLog);
}
@Override
public NodeBase createCopy(String name) {
return new SingleStringNode(name, options);
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 1) {
if (options != null && options.size() != 0) {
return options.stream().filter(s -> s.toLowerCase().startsWith(args[0])).collect(Collectors.toList());
} else {
return new ArrayList<>(Collections.singletonList("<" + getName() + ">"));
}
} else {
return getNodes().get(0).onTabComplete(sender, cmd, label, Arrays.copyOfRange(args, 1, args.length));
}
}
private void addTraceLogData(CommandTraceLog traceLog, CommandTraceLog.ReturnCode code, String choice) {
if (code == CommandTraceLog.ReturnCode.SUCCESS) {
traceLog.addTrace(choice);
} else {
if (options == null || options.size() == 0) {
// there are no options, display name of node
traceLog.addTrace("<" + getName() + ">");
} else {
// there are options to choose from, display that
traceLog.addTrace("[" + String.join("|", options) + "]");
}
traceLog.setReturnCode(code);
}
}
}
| 35.376344 | 118 | 0.602736 |
b9a8ab69bbbd4e4ca187a8508ebbae53a203ffa7 | 5,737 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.scxml2;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.scxml2.env.SimpleContext;
import org.apache.commons.scxml2.env.jexl.JexlEvaluator;
import org.apache.commons.scxml2.model.EnterableState;
import org.apache.commons.scxml2.model.History;
import org.apache.commons.scxml2.model.State;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SCInstanceTest {
private SCXMLExecutor executor;
private SCInstance instance;
@Before
public void setUp() {
executor = new SCXMLExecutor();
instance = executor.getSCInstance();
}
@Test
public void testGetRootContextNull() {
Assert.assertNull(instance.getRootContext());
}
@Test
public void testGetRootContext() {
Context context = new SimpleContext();
context.set("name", "value");
instance.setRootContext(context);
Assert.assertEquals("value", instance.getRootContext().get("name"));
}
@Test
public void testGetRootContextEvaluator() throws Exception {
Evaluator evaluator = new JexlEvaluator();
executor.setEvaluator(evaluator);
Assert.assertTrue(instance.getRootContext() instanceof JexlContext);
}
@Test
public void testGetContext() {
State target = new State();
target.setId("1");
Context context = new SimpleContext();
context.set("name", "value");
instance.setContext(target, context);
Assert.assertEquals("value", instance.getContext(target).get("name"));
}
@Test
public void testGetContextNullParent() throws Exception {
State target = new State();
target.setId("1");
Context context = new SimpleContext();
context.set("name", "value");
instance.setRootContext(context);
Evaluator evaluator = new JexlEvaluator();
executor.setEvaluator(evaluator);
Assert.assertEquals("value", instance.getContext(target).get("name"));
Assert.assertEquals("value", instance.lookupContext(target).get("name"));
}
@Test
public void testGetContextParent() throws Exception {
State target = new State();
target.setId("1");
State parent = new State();
parent.setId("parent");
target.setParent(parent);
Context context = new SimpleContext();
context.set("name", "value");
instance.setRootContext(context);
Evaluator evaluator = new JexlEvaluator();
executor.setEvaluator(evaluator);
Assert.assertEquals("value", instance.getContext(target).get("name"));
Assert.assertEquals("value", instance.lookupContext(target).get("name"));
}
@Test
public void testGetLastConfigurationNull() {
History history = new History();
Set<EnterableState> returnConfiguration = instance.getLastConfiguration(history);
Assert.assertEquals(0, returnConfiguration.size());
}
@Test
public void testGetLastConfiguration() {
History history = new History();
history.setId("1");
Set<EnterableState> configuration = new HashSet<EnterableState>();
EnterableState tt1 = new State();
EnterableState tt2 = new State();
configuration.add(tt1);
configuration.add(tt2);
instance.setLastConfiguration(history, configuration);
Set<EnterableState> returnConfiguration = instance.getLastConfiguration(history);
Assert.assertEquals(2, returnConfiguration.size());
Assert.assertTrue(returnConfiguration.contains(tt1));
Assert.assertTrue(returnConfiguration.contains(tt2));
}
@Test
public void testIsEmpty() {
Assert.assertTrue(instance.getLastConfiguration(new History()).isEmpty());
}
@Test
public void testIsEmptyFalse() {
History history = new History();
history.setId("1");
Set<EnterableState> configuration = new HashSet<EnterableState>();
EnterableState tt1 = new State();
configuration.add(tt1);
instance.setLastConfiguration(history, configuration);
Assert.assertFalse(instance.getLastConfiguration(history).isEmpty());
}
@Test
public void testReset() {
History history = new History();
history.setId("1");
Set<EnterableState> configuration = new HashSet<EnterableState>();
EnterableState tt1 = new State();
configuration.add(tt1);
instance.setLastConfiguration(history, configuration);
instance.resetConfiguration(history);
Assert.assertTrue(instance.getLastConfiguration(history).isEmpty());
}
}
| 31.696133 | 89 | 0.658009 |
86d587b1b47a40197f11ede5416adedd716d724d | 27,784 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.pubsub.model;
/**
* A subscription resource.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Pub/Sub API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Subscription extends com.google.api.client.json.GenericJson {
/**
* The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to
* acknowledge receipt before resending the message. In the interval after the message is
* delivered and before it is acknowledged, it is considered to be *outstanding*. During that time
* period, the message will not be redelivered (on a best-effort basis). For pull subscriptions,
* this value is used as the initial value for the ack deadline. To override this value for a
* given message, call `ModifyAckDeadline` with the corresponding `ack_id` if using non-streaming
* pull or send the `ack_id` in a `StreamingModifyAckDeadlineRequest` if using streaming pull. The
* minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can
* specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is
* used. For push delivery, this value is also used to set the request timeout for the call to the
* push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will
* eventually redeliver the message.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer ackDeadlineSeconds;
/**
* A policy that specifies the conditions for dead lettering messages in this subscription. If
* dead_letter_policy is not set, dead lettering is disabled. The Cloud Pub/Sub service account
* associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-
* pubsub.iam.gserviceaccount.com) must have permission to Acknowledge() messages on this
* subscription.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeadLetterPolicy deadLetterPolicy;
/**
* Indicates whether the subscription is detached from its topic. Detached subscriptions don't
* receive messages from their topic and don't retain any backlog. `Pull` and `StreamingPull`
* requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to
* the endpoint will not be made.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean detached;
/**
* If true, Pub/Sub provides the following guarantees for the delivery of a message with a given
* value of `message_id` on this subscription: * The message sent to a subscriber is guaranteed
* not to be resent before the message's acknowledgement deadline expires. * An acknowledged
* message will not be resent to a subscriber. Note that subscribers may still receive multiple
* copies of a message when `enable_exactly_once_delivery` is true if the message was published
* multiple times by a publisher client. These copies are considered distinct by Pub/Sub and have
* distinct `message_id` values.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableExactlyOnceDelivery;
/**
* If true, messages published with the same `ordering_key` in `PubsubMessage` will be delivered
* to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise,
* they may be delivered in any order.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableMessageOrdering;
/**
* A policy that specifies the conditions for this subscription's expiration. A subscription is
* considered active as long as any connected subscriber is successfully consuming messages from
* the subscription or is issuing operations on the subscription. If `expiration_policy` is not
* set, a *default policy* with `ttl` of 31 days will be used. The minimum allowed value for
* `expiration_policy.ttl` is 1 day. If `expiration_policy` is set, but `expiration_policy.ttl` is
* not set, the subscription never expires.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ExpirationPolicy expirationPolicy;
/**
* An expression written in the Pub/Sub [filter
* language](https://cloud.google.com/pubsub/docs/filtering). If non-empty, then only
* `PubsubMessage`s whose `attributes` field matches the filter are delivered on this
* subscription. If empty, then no messages are filtered out.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String filter;
/**
* See Creating and managing labels.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* How long to retain unacknowledged messages in the subscription's backlog, from the moment a
* message is published. If `retain_acked_messages` is true, then this also configures the
* retention of acknowledged messages, and thus configures how far back in time a `Seek` can be
* done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String messageRetentionDuration;
/**
* Required. The name of the subscription. It must have the format
* `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter,
* and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`),
* periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255
* characters in length, and it must not start with `"goog"`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* If push delivery is used with this subscription, this field is used to configure it. At most
* one of `pushConfig` and `bigQueryConfig` can be set. If both are empty, then the subscriber
* will pull and ack messages using API methods.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PushConfig pushConfig;
/**
* Indicates whether to retain acknowledged messages. If true, then messages are not expunged from
* the subscription's backlog, even if they are acknowledged, until they fall out of the
* `message_retention_duration` window. This must be true if you would like to [`Seek` to a
* timestamp] (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time) in the past to
* replay previously-acknowledged messages.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean retainAckedMessages;
/**
* A policy that specifies how Pub/Sub retries message delivery for this subscription. If not set,
* the default retry policy is applied. This generally implies that messages will be retried as
* soon as possible for healthy subscribers. RetryPolicy will be triggered on NACKs or
* acknowledgement deadline exceeded events for a given message.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RetryPolicy retryPolicy;
/**
* Output only. An output-only field indicating whether or not the subscription can receive
* messages.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String state;
/**
* Required. The name of the topic from which this subscription is receiving messages. Format is
* `projects/{project}/topics/{topic}`. The value of this field will be `_deleted-topic_` if the
* topic has been deleted.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String topic;
/**
* Output only. Indicates the minimum duration for which a message is retained after it is
* published to the subscription's topic. If this field is set, messages published to the
* subscription's topic in the last `topic_message_retention_duration` are always available to
* subscribers. See the `message_retention_duration` field in `Topic`. This field is set only in
* responses from the server; it is ignored if it is set in any requests.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String topicMessageRetentionDuration;
/**
* The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to
* acknowledge receipt before resending the message. In the interval after the message is
* delivered and before it is acknowledged, it is considered to be *outstanding*. During that time
* period, the message will not be redelivered (on a best-effort basis). For pull subscriptions,
* this value is used as the initial value for the ack deadline. To override this value for a
* given message, call `ModifyAckDeadline` with the corresponding `ack_id` if using non-streaming
* pull or send the `ack_id` in a `StreamingModifyAckDeadlineRequest` if using streaming pull. The
* minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can
* specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is
* used. For push delivery, this value is also used to set the request timeout for the call to the
* push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will
* eventually redeliver the message.
* @return value or {@code null} for none
*/
public java.lang.Integer getAckDeadlineSeconds() {
return ackDeadlineSeconds;
}
/**
* The approximate amount of time (on a best-effort basis) Pub/Sub waits for the subscriber to
* acknowledge receipt before resending the message. In the interval after the message is
* delivered and before it is acknowledged, it is considered to be *outstanding*. During that time
* period, the message will not be redelivered (on a best-effort basis). For pull subscriptions,
* this value is used as the initial value for the ack deadline. To override this value for a
* given message, call `ModifyAckDeadline` with the corresponding `ack_id` if using non-streaming
* pull or send the `ack_id` in a `StreamingModifyAckDeadlineRequest` if using streaming pull. The
* minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can
* specify is 600 seconds (10 minutes). If this parameter is 0, a default value of 10 seconds is
* used. For push delivery, this value is also used to set the request timeout for the call to the
* push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will
* eventually redeliver the message.
* @param ackDeadlineSeconds ackDeadlineSeconds or {@code null} for none
*/
public Subscription setAckDeadlineSeconds(java.lang.Integer ackDeadlineSeconds) {
this.ackDeadlineSeconds = ackDeadlineSeconds;
return this;
}
/**
* A policy that specifies the conditions for dead lettering messages in this subscription. If
* dead_letter_policy is not set, dead lettering is disabled. The Cloud Pub/Sub service account
* associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-
* pubsub.iam.gserviceaccount.com) must have permission to Acknowledge() messages on this
* subscription.
* @return value or {@code null} for none
*/
public DeadLetterPolicy getDeadLetterPolicy() {
return deadLetterPolicy;
}
/**
* A policy that specifies the conditions for dead lettering messages in this subscription. If
* dead_letter_policy is not set, dead lettering is disabled. The Cloud Pub/Sub service account
* associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-
* pubsub.iam.gserviceaccount.com) must have permission to Acknowledge() messages on this
* subscription.
* @param deadLetterPolicy deadLetterPolicy or {@code null} for none
*/
public Subscription setDeadLetterPolicy(DeadLetterPolicy deadLetterPolicy) {
this.deadLetterPolicy = deadLetterPolicy;
return this;
}
/**
* Indicates whether the subscription is detached from its topic. Detached subscriptions don't
* receive messages from their topic and don't retain any backlog. `Pull` and `StreamingPull`
* requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to
* the endpoint will not be made.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDetached() {
return detached;
}
/**
* Indicates whether the subscription is detached from its topic. Detached subscriptions don't
* receive messages from their topic and don't retain any backlog. `Pull` and `StreamingPull`
* requests will return FAILED_PRECONDITION. If the subscription is a push subscription, pushes to
* the endpoint will not be made.
* @param detached detached or {@code null} for none
*/
public Subscription setDetached(java.lang.Boolean detached) {
this.detached = detached;
return this;
}
/**
* If true, Pub/Sub provides the following guarantees for the delivery of a message with a given
* value of `message_id` on this subscription: * The message sent to a subscriber is guaranteed
* not to be resent before the message's acknowledgement deadline expires. * An acknowledged
* message will not be resent to a subscriber. Note that subscribers may still receive multiple
* copies of a message when `enable_exactly_once_delivery` is true if the message was published
* multiple times by a publisher client. These copies are considered distinct by Pub/Sub and have
* distinct `message_id` values.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableExactlyOnceDelivery() {
return enableExactlyOnceDelivery;
}
/**
* If true, Pub/Sub provides the following guarantees for the delivery of a message with a given
* value of `message_id` on this subscription: * The message sent to a subscriber is guaranteed
* not to be resent before the message's acknowledgement deadline expires. * An acknowledged
* message will not be resent to a subscriber. Note that subscribers may still receive multiple
* copies of a message when `enable_exactly_once_delivery` is true if the message was published
* multiple times by a publisher client. These copies are considered distinct by Pub/Sub and have
* distinct `message_id` values.
* @param enableExactlyOnceDelivery enableExactlyOnceDelivery or {@code null} for none
*/
public Subscription setEnableExactlyOnceDelivery(java.lang.Boolean enableExactlyOnceDelivery) {
this.enableExactlyOnceDelivery = enableExactlyOnceDelivery;
return this;
}
/**
* If true, messages published with the same `ordering_key` in `PubsubMessage` will be delivered
* to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise,
* they may be delivered in any order.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableMessageOrdering() {
return enableMessageOrdering;
}
/**
* If true, messages published with the same `ordering_key` in `PubsubMessage` will be delivered
* to the subscribers in the order in which they are received by the Pub/Sub system. Otherwise,
* they may be delivered in any order.
* @param enableMessageOrdering enableMessageOrdering or {@code null} for none
*/
public Subscription setEnableMessageOrdering(java.lang.Boolean enableMessageOrdering) {
this.enableMessageOrdering = enableMessageOrdering;
return this;
}
/**
* A policy that specifies the conditions for this subscription's expiration. A subscription is
* considered active as long as any connected subscriber is successfully consuming messages from
* the subscription or is issuing operations on the subscription. If `expiration_policy` is not
* set, a *default policy* with `ttl` of 31 days will be used. The minimum allowed value for
* `expiration_policy.ttl` is 1 day. If `expiration_policy` is set, but `expiration_policy.ttl` is
* not set, the subscription never expires.
* @return value or {@code null} for none
*/
public ExpirationPolicy getExpirationPolicy() {
return expirationPolicy;
}
/**
* A policy that specifies the conditions for this subscription's expiration. A subscription is
* considered active as long as any connected subscriber is successfully consuming messages from
* the subscription or is issuing operations on the subscription. If `expiration_policy` is not
* set, a *default policy* with `ttl` of 31 days will be used. The minimum allowed value for
* `expiration_policy.ttl` is 1 day. If `expiration_policy` is set, but `expiration_policy.ttl` is
* not set, the subscription never expires.
* @param expirationPolicy expirationPolicy or {@code null} for none
*/
public Subscription setExpirationPolicy(ExpirationPolicy expirationPolicy) {
this.expirationPolicy = expirationPolicy;
return this;
}
/**
* An expression written in the Pub/Sub [filter
* language](https://cloud.google.com/pubsub/docs/filtering). If non-empty, then only
* `PubsubMessage`s whose `attributes` field matches the filter are delivered on this
* subscription. If empty, then no messages are filtered out.
* @return value or {@code null} for none
*/
public java.lang.String getFilter() {
return filter;
}
/**
* An expression written in the Pub/Sub [filter
* language](https://cloud.google.com/pubsub/docs/filtering). If non-empty, then only
* `PubsubMessage`s whose `attributes` field matches the filter are delivered on this
* subscription. If empty, then no messages are filtered out.
* @param filter filter or {@code null} for none
*/
public Subscription setFilter(java.lang.String filter) {
this.filter = filter;
return this;
}
/**
* See Creating and managing labels.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* See Creating and managing labels.
* @param labels labels or {@code null} for none
*/
public Subscription setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* How long to retain unacknowledged messages in the subscription's backlog, from the moment a
* message is published. If `retain_acked_messages` is true, then this also configures the
* retention of acknowledged messages, and thus configures how far back in time a `Seek` can be
* done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes.
* @return value or {@code null} for none
*/
public String getMessageRetentionDuration() {
return messageRetentionDuration;
}
/**
* How long to retain unacknowledged messages in the subscription's backlog, from the moment a
* message is published. If `retain_acked_messages` is true, then this also configures the
* retention of acknowledged messages, and thus configures how far back in time a `Seek` can be
* done. Defaults to 7 days. Cannot be more than 7 days or less than 10 minutes.
* @param messageRetentionDuration messageRetentionDuration or {@code null} for none
*/
public Subscription setMessageRetentionDuration(String messageRetentionDuration) {
this.messageRetentionDuration = messageRetentionDuration;
return this;
}
/**
* Required. The name of the subscription. It must have the format
* `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter,
* and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`),
* periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255
* characters in length, and it must not start with `"goog"`.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Required. The name of the subscription. It must have the format
* `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter,
* and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`),
* periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255
* characters in length, and it must not start with `"goog"`.
* @param name name or {@code null} for none
*/
public Subscription setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* If push delivery is used with this subscription, this field is used to configure it. At most
* one of `pushConfig` and `bigQueryConfig` can be set. If both are empty, then the subscriber
* will pull and ack messages using API methods.
* @return value or {@code null} for none
*/
public PushConfig getPushConfig() {
return pushConfig;
}
/**
* If push delivery is used with this subscription, this field is used to configure it. At most
* one of `pushConfig` and `bigQueryConfig` can be set. If both are empty, then the subscriber
* will pull and ack messages using API methods.
* @param pushConfig pushConfig or {@code null} for none
*/
public Subscription setPushConfig(PushConfig pushConfig) {
this.pushConfig = pushConfig;
return this;
}
/**
* Indicates whether to retain acknowledged messages. If true, then messages are not expunged from
* the subscription's backlog, even if they are acknowledged, until they fall out of the
* `message_retention_duration` window. This must be true if you would like to [`Seek` to a
* timestamp] (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time) in the past to
* replay previously-acknowledged messages.
* @return value or {@code null} for none
*/
public java.lang.Boolean getRetainAckedMessages() {
return retainAckedMessages;
}
/**
* Indicates whether to retain acknowledged messages. If true, then messages are not expunged from
* the subscription's backlog, even if they are acknowledged, until they fall out of the
* `message_retention_duration` window. This must be true if you would like to [`Seek` to a
* timestamp] (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time) in the past to
* replay previously-acknowledged messages.
* @param retainAckedMessages retainAckedMessages or {@code null} for none
*/
public Subscription setRetainAckedMessages(java.lang.Boolean retainAckedMessages) {
this.retainAckedMessages = retainAckedMessages;
return this;
}
/**
* A policy that specifies how Pub/Sub retries message delivery for this subscription. If not set,
* the default retry policy is applied. This generally implies that messages will be retried as
* soon as possible for healthy subscribers. RetryPolicy will be triggered on NACKs or
* acknowledgement deadline exceeded events for a given message.
* @return value or {@code null} for none
*/
public RetryPolicy getRetryPolicy() {
return retryPolicy;
}
/**
* A policy that specifies how Pub/Sub retries message delivery for this subscription. If not set,
* the default retry policy is applied. This generally implies that messages will be retried as
* soon as possible for healthy subscribers. RetryPolicy will be triggered on NACKs or
* acknowledgement deadline exceeded events for a given message.
* @param retryPolicy retryPolicy or {@code null} for none
*/
public Subscription setRetryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Output only. An output-only field indicating whether or not the subscription can receive
* messages.
* @return value or {@code null} for none
*/
public java.lang.String getState() {
return state;
}
/**
* Output only. An output-only field indicating whether or not the subscription can receive
* messages.
* @param state state or {@code null} for none
*/
public Subscription setState(java.lang.String state) {
this.state = state;
return this;
}
/**
* Required. The name of the topic from which this subscription is receiving messages. Format is
* `projects/{project}/topics/{topic}`. The value of this field will be `_deleted-topic_` if the
* topic has been deleted.
* @return value or {@code null} for none
*/
public java.lang.String getTopic() {
return topic;
}
/**
* Required. The name of the topic from which this subscription is receiving messages. Format is
* `projects/{project}/topics/{topic}`. The value of this field will be `_deleted-topic_` if the
* topic has been deleted.
* @param topic topic or {@code null} for none
*/
public Subscription setTopic(java.lang.String topic) {
this.topic = topic;
return this;
}
/**
* Output only. Indicates the minimum duration for which a message is retained after it is
* published to the subscription's topic. If this field is set, messages published to the
* subscription's topic in the last `topic_message_retention_duration` are always available to
* subscribers. See the `message_retention_duration` field in `Topic`. This field is set only in
* responses from the server; it is ignored if it is set in any requests.
* @return value or {@code null} for none
*/
public String getTopicMessageRetentionDuration() {
return topicMessageRetentionDuration;
}
/**
* Output only. Indicates the minimum duration for which a message is retained after it is
* published to the subscription's topic. If this field is set, messages published to the
* subscription's topic in the last `topic_message_retention_duration` are always available to
* subscribers. See the `message_retention_duration` field in `Topic`. This field is set only in
* responses from the server; it is ignored if it is set in any requests.
* @param topicMessageRetentionDuration topicMessageRetentionDuration or {@code null} for none
*/
public Subscription setTopicMessageRetentionDuration(String topicMessageRetentionDuration) {
this.topicMessageRetentionDuration = topicMessageRetentionDuration;
return this;
}
@Override
public Subscription set(String fieldName, Object value) {
return (Subscription) super.set(fieldName, value);
}
@Override
public Subscription clone() {
return (Subscription) super.clone();
}
}
| 46.461538 | 182 | 0.729557 |
b40870a3b1fef572798b731dc2ca931c23c27d95 | 4,087 | package synergynet3.web.earlyyears.server;
import synergynet3.web.earlyyears.client.EarlyYearsUI;
import synergynet3.web.earlyyears.client.service.EarlyYearsService;
import synergynet3.web.earlyyears.core.EarlyYearsControlComms;
import synergynet3.web.earlyyears.shared.EarlyYearsActivity;
import synergynet3.web.shared.messages.PerformActionMessage;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The Class EarlyYearsServiceImpl.
*/
public class EarlyYearsServiceImpl extends RemoteServiceServlet implements EarlyYearsService
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 888142181330339335L;
/*
* (non-Javadoc)
* @see
* synergynet3.web.earlyyears.client.service.EarlyYearsService#setActivity
* (synergynet3.web.earlyyears.shared.EarlyYearsActivity,
* java.lang.String[])
*/
@Override
public void setActivity(EarlyYearsActivity scenario, String[] tables)
{
if (tables.length < 1)
{
return;
}
for (String table : tables)
{
if (table.equals(EarlyYearsUI.ALL_TABLES_ID))
{
EarlyYearsControlComms.get().setAllTablesScenario(scenario);
break;
}
else
{
EarlyYearsControlComms.get().setSpecificTablesScenario(scenario, table);
}
}
}
/*
* (non-Javadoc)
* @see synergynet3.web.earlyyears.client.service.EarlyYearsService#
* setRailwayCornerNum(int, java.lang.String[])
*/
@Override
public void setRailwayCornerNum(int newNum, String[] tables)
{
if (tables.length < 1)
{
return;
}
for (String table : tables)
{
if (table.equals(EarlyYearsUI.ALL_TABLES_ID))
{
EarlyYearsControlComms.get().setAllTablesRailwayCorners(newNum);
}
else
{
EarlyYearsControlComms.get().setSpecificTablesRailwayCorners(newNum, table);
}
}
}
/*
* (non-Javadoc)
* @see synergynet3.web.earlyyears.client.service.EarlyYearsService#
* setRailwayCrossNum(int, java.lang.String[])
*/
@Override
public void setRailwayCrossNum(int newNum, String[] tables)
{
if (tables.length < 1)
{
return;
}
for (String table : tables)
{
if (table.equals(EarlyYearsUI.ALL_TABLES_ID))
{
EarlyYearsControlComms.get().setAllTablesRailwayCrosses(newNum);
}
else
{
EarlyYearsControlComms.get().setSpecificTablesRailwayCrosses(newNum, table);
}
}
}
/*
* (non-Javadoc)
* @see synergynet3.web.earlyyears.client.service.EarlyYearsService#
* setRailwayStraightNum(int, java.lang.String[])
*/
@Override
public void setRailwayStraightNum(int newNum, String[] tables)
{
if (tables.length < 1)
{
return;
}
for (String table : tables)
{
if (table.equals(EarlyYearsUI.ALL_TABLES_ID))
{
EarlyYearsControlComms.get().setAllTablesRailwayStraights(newNum);
}
else
{
EarlyYearsControlComms.get().setSpecificTablesRailwayStraights(newNum, table);
}
}
}
/*
* (non-Javadoc)
* @see
* synergynet3.web.earlyyears.client.service.EarlyYearsService#setRoadMode
* (synergynet3.web.shared.messages.PerformActionMessage,
* java.lang.String[])
*/
@Override
public void setRoadMode(PerformActionMessage roadMode, String[] tables)
{
if (tables.length < 1)
{
return;
}
for (String table : tables)
{
if (table.equals(EarlyYearsUI.ALL_TABLES_ID))
{
EarlyYearsControlComms.get().setAllRoadMode(roadMode);
}
else
{
EarlyYearsControlComms.get().setSpecificRoadMode(roadMode, table);
}
}
}
/*
* (non-Javadoc)
* @see synergynet3.web.earlyyears.client.service.EarlyYearsService#
* showExplorerTeacherConsole
* (synergynet3.web.shared.messages.PerformActionMessage,
* java.lang.String[])
*/
@Override
public void showExplorerTeacherConsole(PerformActionMessage show, String[] tables)
{
if (tables.length < 1)
{
return;
}
for (String table : tables)
{
if (table.equals(EarlyYearsUI.ALL_TABLES_ID))
{
EarlyYearsControlComms.get().setAllTablesExplorerShowTeacherControl(show);
}
else
{
EarlyYearsControlComms.get().setSpecificTablesExplorerShowTeacherControl(show, table);
}
}
}
}
| 22.960674 | 92 | 0.718865 |
c43509ae2b90cd1dc313feb40e95ab169636657d | 4,007 | package org.kasource.spring.nats.integration;
import java.io.File;
import org.springframework.util.SocketUtils;
import org.kasource.spring.nats.integration.avro.NatsAvroJavaIntegration;
import org.kasource.spring.nats.integration.avro.NatsAvroXmlIntegration;
import org.kasource.spring.nats.integration.custom.NatsCustomJavaIntegration;
import org.kasource.spring.nats.integration.custom.NatsCustomXmlIntegration;
import org.kasource.spring.nats.integration.java.NatsJavaSerDeJavaIntegration;
import org.kasource.spring.nats.integration.java.NatsJavaSerDeXmlIntegration;
import org.kasource.spring.nats.integration.json.NatsGsonJavaIntegration;
import org.kasource.spring.nats.integration.json.NatsGsonXmlIntegration;
import org.kasource.spring.nats.integration.json.NatsJacksonJavaIntegration;
import org.kasource.spring.nats.integration.json.NatsJacksonXmlIntegration;
import org.kasource.spring.nats.integration.kryo.NatsKryoJavaIntegration;
import org.kasource.spring.nats.integration.kryo.NatsKryoXmlIntegration;
import org.kasource.spring.nats.integration.proto.NatsProtoJavaIntegration;
import org.kasource.spring.nats.integration.proto.NatsProtoXmlIntegration;
import org.kasource.spring.nats.integration.thrift.NatsThriftJavaIntegration;
import org.kasource.spring.nats.integration.thrift.NatsThriftXmlIntegration;
import org.kasource.spring.nats.integration.xml.NatsJaxbJavaIntegration;
import org.kasource.spring.nats.integration.xml.NatsJaxbXmlIntegration;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.containers.wait.strategy.Wait;
@RunWith(Suite.class)
@Suite.SuiteClasses({
NatsJacksonJavaIntegration.class,
NatsJacksonXmlIntegration.class,
NatsGsonXmlIntegration.class,
NatsGsonJavaIntegration.class,
NatsKryoJavaIntegration.class,
NatsKryoXmlIntegration.class,
NatsJavaSerDeJavaIntegration.class,
NatsJavaSerDeXmlIntegration.class,
NatsAvroXmlIntegration.class,
NatsAvroJavaIntegration.class,
NatsProtoXmlIntegration.class,
NatsProtoJavaIntegration.class,
NatsThriftJavaIntegration.class,
NatsThriftXmlIntegration.class,
NatsJaxbXmlIntegration.class,
NatsJaxbJavaIntegration.class,
NatsCustomXmlIntegration.class,
NatsCustomJavaIntegration.class
})
public class SpringNatsIT {
public static final Integer NATS_PORT = SocketUtils.findAvailableTcpPort(10000);
public static final Integer NATS_MONITOR_PORT = SocketUtils.findAvailableTcpPort(10000);
@ClassRule
public static DockerComposeContainer dockerComposeContainer =
new DockerComposeContainer(new File("src/test/resources/docker/docker-compose.yml"))
.withEnv("NATS_PORT", NATS_PORT.toString())
.withEnv("NATS_MONITOR_PORT", NATS_MONITOR_PORT.toString())
.waitingFor("nats", Wait.forListeningPort())
.waitingFor("nats", Wait.forLogMessage(".*Server is ready.*\\n", 1));
@BeforeClass
public static void setupPorts() {
System.setProperty("NATS_PORT", NATS_PORT.toString());
System.setProperty("NATS_MONITOR_PORT", NATS_MONITOR_PORT.toString());
System.out.println("\n\n##################################");
System.out.println("Starting NATS with port " + NATS_PORT + " and monitoring port " + NATS_MONITOR_PORT);
System.out.println("##################################\n\n");
}
}
| 51.371795 | 113 | 0.691041 |
f489bd1972ec2b004e267f1add763cc54488022e | 2,101 | package codejam2010;
import java.io.*;
import java.util.*;
public class Solution {
final String f = "A-large-practice.in.txt";
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
void solve() throws IOException {
int D = nextInt();
int I = nextInt();
int m = nextInt();
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
int[] d = new int[256];
for (int i = 0; i < n; ++i) {
int[] t = new int[256];
Arrays.fill(t, Integer.MAX_VALUE);
for (int u = 0; u < 256; ++u) {
t[u] = Math.min(t[u], d[u] + D);
for (int v = 0; v < 256; ++v) {
if (Math.abs(u - v) <= m) {
t[v] = Math.min(t[v], d[u] + Math.abs(v - a[i]));
}
}
}
if (m != 0) {
for (int u = 0; u < 256; ++u) {
for (int v = 0; v < 256; ++v) {
t[v] = Math.min(t[v], t[u] + ((Math.abs(u - v) + m - 1) / m) * I);
}
}
}
d = t;
}
int ans = Integer.MAX_VALUE;
for (int u = 0; u < 256; ++u) {
ans = Math.min(ans, d[u]);
}
out.println(ans);
}
Solution() throws IOException {
in = new BufferedReader(new FileReader(f ));
out = new PrintWriter(f + ".out");
eat("");
int tests = nextInt();
for (int test = 0; test < tests; ++test) {
System.out.println("Test #" + (test + 1));
out.print("Case #" + (test + 1) + ": ");
solve();
}
in.close();
out.close();
}
private void eat(String str) {
st = new StringTokenizer(str);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
new Solution();
}
}
| 21.222222 | 73 | 0.516421 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.