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
|
---|---|---|---|---|---|
18c9ed1a950e7d0d533c95c2b5954880a3222845 | 470 | package ru.frostdelta.authserver;
import java.util.HashMap;
public class UserSession {
public static HashMap<String, Boolean> session = new HashMap<String, Boolean>();
public UserSession(String username) {
UserSession.session.put(username, true);
}
public UserSession() {
}
public boolean usersession(String username){
if(session.containsKey(username)){
return true;
}else return false;
}
}
| 15.16129 | 84 | 0.651064 |
4bf8bf09eeff29c7347f8bc05a69daa08cf3f358 | 1,717 | package edu.uta.futureye.lib.element;
import edu.uta.futureye.core.Element;
import edu.uta.futureye.core.Line1DCoord;
import edu.uta.futureye.core.Mesh;
import edu.uta.futureye.core.intf.CoordTrans;
import edu.uta.futureye.core.intf.FiniteElement;
import edu.uta.futureye.function.basic.FX;
import edu.uta.futureye.function.intf.MathFunc;
import edu.uta.futureye.util.container.VertexList;
/**
* Linear line element in a 1D space
*
* shape functions
*
* 1-----2 -->r
* -1 0 1
*
* N1 = (1-r)/2
* N2 = (1+r)/2
*
*/
public class FELinearLine1D implements FiniteElement {
Line1DCoord coord;
//Construct a function with the coordinate of points in an element as parameters
String[] argsOrder;
public int nDOFs = 2;
MathFunc[] shapeFuncs = new MathFunc[nDOFs];
public FELinearLine1D() {
FX x1 = new FX("x1");
FX x2 = new FX("x2");
this.coord = new Line1DCoord(x1, x2);
MathFunc r = coord.getCoordR();
argsOrder = new String[]{x1,x2,r};
shapeFuncs[0] = 0.5*(1-r);
shapeFuncs[1] = 0.5*(1+r);
}
@Override
public MathFunc[] getShapeFunctions() {
return this.shapeFuncs;
}
@Override
public int getNumberOfDOFs() {
return this.nDOFs;
}
@Override
public String[] getArgsOrder() {
return this.argsOrder;
}
@Override
public FiniteElement getBoundaryFE() {
throw new UnsupportedOperationException();
}
@Override
public int getGlobalIndex(Mesh mesh, Element e, int localIndex) {
VertexList vertices = e.vertices();
return vertices.at(localIndex).globalNode().globalIndex;
}
@Override
public int getTotalNumberOfDOFs(Mesh mesh) {
return mesh.getNodeList().size();
}
@Override
public CoordTrans getCoordTrans() {
return this.coord;
}
}
| 20.939024 | 81 | 0.703553 |
fea5a04d5cfbfca58d862c2643aa84be5577a9af | 18,402 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
import net.runelite.rs.ScriptOpcodes;
@ObfuscatedName("ci")
@Implements("Players")
public class Players {
@ObfuscatedName("s")
static byte[] field1276;
@ObfuscatedName("e")
@ObfuscatedSignature(
descriptor = "[Lgl;"
)
static class185[] field1277;
@ObfuscatedName("r")
@ObfuscatedSignature(
descriptor = "[Lpi;"
)
static Buffer[] field1278;
@ObfuscatedName("o")
@ObfuscatedGetter(
intValue = -997920691
)
@Export("Players_count")
static int Players_count;
@ObfuscatedName("i")
@Export("Players_indices")
static int[] Players_indices;
@ObfuscatedName("w")
@ObfuscatedGetter(
intValue = 295337231
)
@Export("Players_emptyIdxCount")
static int Players_emptyIdxCount;
@ObfuscatedName("v")
@Export("Players_emptyIndices")
static int[] Players_emptyIndices;
@ObfuscatedName("a")
@Export("Players_regions")
static int[] Players_regions;
@ObfuscatedName("y")
@Export("Players_orientations")
static int[] Players_orientations;
@ObfuscatedName("u")
@Export("Players_targetIndices")
static int[] Players_targetIndices;
@ObfuscatedName("h")
@ObfuscatedGetter(
intValue = 221870495
)
@Export("Players_pendingUpdateCount")
static int Players_pendingUpdateCount;
@ObfuscatedName("q")
@Export("Players_pendingUpdateIndices")
static int[] Players_pendingUpdateIndices;
@ObfuscatedName("x")
@ObfuscatedSignature(
descriptor = "Lpi;"
)
static Buffer field1275;
@ObfuscatedName("gv")
@ObfuscatedSignature(
descriptor = "Llv;"
)
@Export("fontPlain12")
static Font fontPlain12;
static {
field1276 = new byte[2048];
field1277 = new class185[2048];
field1278 = new Buffer[2048];
Players_count = 0;
Players_indices = new int[2048];
Players_emptyIdxCount = 0;
Players_emptyIndices = new int[2048];
Players_regions = new int[2048];
Players_orientations = new int[2048];
Players_targetIndices = new int[2048];
Players_pendingUpdateCount = 0;
Players_pendingUpdateIndices = new int[2048];
field1275 = new Buffer(new byte[5000]);
}
@ObfuscatedName("c")
@ObfuscatedSignature(
descriptor = "(II)Lbl;",
garbageValue = "-502833726"
)
@Export("getScript")
static Script getScript(int var0) {
Script var1 = (Script)Script.Script_cached.get((long)var0);
if (var1 != null) {
return var1;
} else {
byte[] var2 = class148.archive12.takeFile(var0, 0);
if (var2 == null) {
return null;
} else {
var1 = ScriptFrame.newScript(var2);
Script.Script_cached.put(var1, (long)var0);
return var1;
}
}
}
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "(CLlu;I)C",
garbageValue = "1415681673"
)
@Export("standardizeChar")
static char standardizeChar(char var0, Language var1) {
if (var0 >= 192 && var0 <= 255) {
if (var0 >= 192 && var0 <= 198) {
return 'A';
}
if (var0 == 199) {
return 'C';
}
if (var0 >= 200 && var0 <= 203) {
return 'E';
}
if (var0 >= 204 && var0 <= 207) {
return 'I';
}
if (var0 == 209 && var1 != Language.Language_ES) {
return 'N';
}
if (var0 >= 210 && var0 <= 214) {
return 'O';
}
if (var0 >= 217 && var0 <= 220) {
return 'U';
}
if (var0 == 221) {
return 'Y';
}
if (var0 == 223) {
return 's';
}
if (var0 >= 224 && var0 <= 230) {
return 'a';
}
if (var0 == 231) {
return 'c';
}
if (var0 >= 232 && var0 <= 235) {
return 'e';
}
if (var0 >= 236 && var0 <= 239) {
return 'i';
}
if (var0 == 241 && var1 != Language.Language_ES) {
return 'n';
}
if (var0 >= 242 && var0 <= 246) {
return 'o';
}
if (var0 >= 249 && var0 <= 252) {
return 'u';
}
if (var0 == 253 || var0 == 255) {
return 'y';
}
}
if (var0 == 338) {
return 'O';
} else if (var0 == 339) {
return 'o';
} else if (var0 == 376) {
return 'Y';
} else {
return var0;
}
}
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "([Lbi;II[I[IB)V",
garbageValue = "16"
)
@Export("sortWorlds")
static void sortWorlds(World[] var0, int var1, int var2, int[] var3, int[] var4) {
if (var1 < var2) {
int var5 = var1 - 1;
int var6 = var2 + 1;
int var7 = (var2 + var1) / 2;
World var8 = var0[var7];
var0[var7] = var0[var1];
var0[var1] = var8;
while (var5 < var6) {
boolean var9 = true;
int var10;
int var11;
int var12;
do {
--var6;
for (var10 = 0; var10 < 4; ++var10) {
if (var3[var10] == 2) {
var11 = var0[var6].index;
var12 = var8.index;
} else if (var3[var10] == 1) {
var11 = var0[var6].population;
var12 = var8.population;
if (var11 == -1 && var4[var10] == 1) {
var11 = 2001;
}
if (var12 == -1 && var4[var10] == 1) {
var12 = 2001;
}
} else if (var3[var10] == 3) {
var11 = var0[var6].isMembersOnly() ? 1 : 0;
var12 = var8.isMembersOnly() ? 1 : 0;
} else {
var11 = var0[var6].id;
var12 = var8.id;
}
if (var12 != var11) {
if ((var4[var10] != 1 || var11 <= var12) && (var4[var10] != 0 || var11 >= var12)) {
var9 = false;
}
break;
}
if (var10 == 3) {
var9 = false;
}
}
} while(var9);
var9 = true;
do {
++var5;
for (var10 = 0; var10 < 4; ++var10) {
if (var3[var10] == 2) {
var11 = var0[var5].index;
var12 = var8.index;
} else if (var3[var10] == 1) {
var11 = var0[var5].population;
var12 = var8.population;
if (var11 == -1 && var4[var10] == 1) {
var11 = 2001;
}
if (var12 == -1 && var4[var10] == 1) {
var12 = 2001;
}
} else if (var3[var10] == 3) {
var11 = var0[var5].isMembersOnly() ? 1 : 0;
var12 = var8.isMembersOnly() ? 1 : 0;
} else {
var11 = var0[var5].id;
var12 = var8.id;
}
if (var12 != var11) {
if ((var4[var10] != 1 || var11 >= var12) && (var4[var10] != 0 || var11 <= var12)) {
var9 = false;
}
break;
}
if (var10 == 3) {
var9 = false;
}
}
} while(var9);
if (var5 < var6) {
World var13 = var0[var5];
var0[var5] = var0[var6];
var0[var6] = var13;
}
}
sortWorlds(var0, var1, var6, var3, var4);
sortWorlds(var0, var6 + 1, var2, var3, var4);
}
}
@ObfuscatedName("y")
@ObfuscatedSignature(
descriptor = "(CI)Z",
garbageValue = "187224492"
)
static boolean method2308(char var0) {
for (int var1 = 0; var1 < "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"�$%^&*()-_=+[{]};:'@#~,<.>/?\\| ".length(); ++var1) {
if (var0 == "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"�$%^&*()-_=+[{]};:'@#~,<.>/?\\| ".charAt(var1)) {
return true;
}
}
return false;
}
@ObfuscatedName("az")
@ObfuscatedSignature(
descriptor = "(ILbl;ZB)I",
garbageValue = "97"
)
static int method2305(int var0, Script var1, boolean var2) {
if (var0 == ScriptOpcodes.WORLDLIST_FETCH) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = class6.loadWorlds() ? 1 : 0;
return 1;
} else {
World var9;
if (var0 == ScriptOpcodes.WORLDLIST_START) {
var9 = MusicPatch.worldListStart();
if (var9 != null) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.id;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.properties;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var9.activity;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.location;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.population;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var9.host;
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = -1;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
}
return 1;
} else if (var0 == ScriptOpcodes.WORLDLIST_NEXT) {
var9 = class114.getNextWorldListWorld();
if (var9 != null) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.id;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.properties;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var9.activity;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.location;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var9.population;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var9.host;
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = -1;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
}
return 1;
} else {
int var3;
World var7;
int var8;
if (var0 == ScriptOpcodes.WORLDLIST_SPECIFIC) {
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize];
var7 = null;
for (var8 = 0; var8 < World.World_count; ++var8) {
if (var3 == class33.World_worlds[var8].id) {
var7 = class33.World_worlds[var8];
break;
}
}
if (var7 != null) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.id;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.properties;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var7.activity;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.location;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.population;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var7.host;
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = -1;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
}
return 1;
} else if (var0 == ScriptOpcodes.WORLDLIST_SORT) {
Interpreter.Interpreter_intStackSize -= 4;
var3 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
boolean var10 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1] == 1;
var8 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 2];
boolean var6 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 3] == 1;
class126.sortWorldList(var3, var10, var8, var6);
return 1;
} else if (var0 != 6511) {
if (var0 == ScriptOpcodes.SETFOLLOWEROPSLOWPRIORITY) {
Client.followerOpsLowPriority = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize] == 1;
return 1;
} else {
int var4;
ParamComposition var5;
if (var0 == ScriptOpcodes.NC_PARAM) {
Interpreter.Interpreter_intStackSize -= 2;
var3 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
var4 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1];
var5 = HealthBarUpdate.getParamDefinition(var4);
if (var5.isString()) {
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = UserComparator10.getNpcDefinition(var3).getStringParam(var4, var5.defaultStr);
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = UserComparator10.getNpcDefinition(var3).getIntParam(var4, var5.defaultInt);
}
return 1;
} else if (var0 == ScriptOpcodes.LC_PARAM) {
Interpreter.Interpreter_intStackSize -= 2;
var3 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
var4 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1];
var5 = HealthBarUpdate.getParamDefinition(var4);
if (var5.isString()) {
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = ParamComposition.getObjectDefinition(var3).getStringParam(var4, var5.defaultStr);
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = ParamComposition.getObjectDefinition(var3).getIntParam(var4, var5.defaultInt);
}
return 1;
} else if (var0 == ScriptOpcodes.OC_PARAM) {
Interpreter.Interpreter_intStackSize -= 2;
var3 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
var4 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1];
var5 = HealthBarUpdate.getParamDefinition(var4);
if (var5.isString()) {
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = Client.ItemDefinition_get(var3).getStringParam(var4, var5.defaultStr);
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.ItemDefinition_get(var3).getIntParam(var4, var5.defaultInt);
}
return 1;
} else if (var0 == ScriptOpcodes.STRUCT_PARAM) {
Interpreter.Interpreter_intStackSize -= 2;
var3 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
var4 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1];
var5 = HealthBarUpdate.getParamDefinition(var4);
if (var5.isString()) {
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = class136.StructDefinition_getStructDefinition(var3).getStringParam(var4, var5.defaultStr);
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = class136.StructDefinition_getStructDefinition(var3).getIntParam(var4, var5.defaultInt);
}
return 1;
} else if (var0 == ScriptOpcodes.ON_MOBILE) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.onMobile ? 1 : 0;
return 1;
} else if (var0 == ScriptOpcodes.CLIENTTYPE) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.clientType;
return 1;
} else if (var0 == 6520) {
return 1;
} else if (var0 == ScriptOpcodes.MOBILE_KEYBOARDHIDE) {
return 1;
} else if (var0 == 6522) {
--BufferedNetSocket.Interpreter_stringStackSize;
--Interpreter.Interpreter_intStackSize;
return 1;
} else if (var0 == 6523) {
--BufferedNetSocket.Interpreter_stringStackSize;
--Interpreter.Interpreter_intStackSize;
return 1;
} else if (var0 == ScriptOpcodes.MOBILE_BATTERYLEVEL) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = -1;
return 1;
} else if (var0 == ScriptOpcodes.MOBILE_BATTERYCHARGING) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 1;
return 1;
} else if (var0 == ScriptOpcodes.MOBILE_WIFIAVAILABLE) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 1;
return 1;
} else if (var0 == 6527) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = Client.field502;
return 1;
} else {
return 2;
}
}
} else {
var3 = Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize];
if (var3 >= 0 && var3 < World.World_count) {
var7 = class33.World_worlds[var3];
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.id;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.properties;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var7.activity;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.location;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = var7.population;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = var7.host;
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = -1;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
Interpreter.Interpreter_stringStack[++BufferedNetSocket.Interpreter_stringStackSize - 1] = "";
}
return 1;
}
}
}
}
}
| 34.918406 | 189 | 0.672807 |
e8c1559e47b2964e9e66c4e8818b416669d99411 | 3,092 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.costmanagement.implementation;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.costmanagement.CostManagementManager;
import com.azure.resourcemanager.costmanagement.fluent.DimensionsClient;
import com.azure.resourcemanager.costmanagement.fluent.models.DimensionInner;
import com.azure.resourcemanager.costmanagement.models.Dimension;
import com.azure.resourcemanager.costmanagement.models.Dimensions;
import com.azure.resourcemanager.costmanagement.models.ExternalCloudProviderType;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class DimensionsImpl implements Dimensions {
@JsonIgnore private final ClientLogger logger = new ClientLogger(DimensionsImpl.class);
private final DimensionsClient innerClient;
private final CostManagementManager serviceManager;
public DimensionsImpl(DimensionsClient innerClient, CostManagementManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public PagedIterable<Dimension> list(String scope) {
PagedIterable<DimensionInner> inner = this.serviceClient().list(scope);
return inner.mapPage(inner1 -> new DimensionImpl(inner1, this.manager()));
}
public PagedIterable<Dimension> list(
String scope, String filter, String expand, String skiptoken, Integer top, Context context) {
PagedIterable<DimensionInner> inner = this.serviceClient().list(scope, filter, expand, skiptoken, top, context);
return inner.mapPage(inner1 -> new DimensionImpl(inner1, this.manager()));
}
public PagedIterable<Dimension> byExternalCloudProviderType(
ExternalCloudProviderType externalCloudProviderType, String externalCloudProviderId) {
PagedIterable<DimensionInner> inner =
this.serviceClient().byExternalCloudProviderType(externalCloudProviderType, externalCloudProviderId);
return inner.mapPage(inner1 -> new DimensionImpl(inner1, this.manager()));
}
public PagedIterable<Dimension> byExternalCloudProviderType(
ExternalCloudProviderType externalCloudProviderType,
String externalCloudProviderId,
String filter,
String expand,
String skiptoken,
Integer top,
Context context) {
PagedIterable<DimensionInner> inner =
this
.serviceClient()
.byExternalCloudProviderType(
externalCloudProviderType, externalCloudProviderId, filter, expand, skiptoken, top, context);
return inner.mapPage(inner1 -> new DimensionImpl(inner1, this.manager()));
}
private DimensionsClient serviceClient() {
return this.innerClient;
}
private CostManagementManager manager() {
return this.serviceManager;
}
}
| 42.944444 | 120 | 0.750323 |
69e4b8ebec2f1909763a85aca93ead4fc634a742 | 1,114 | /*
* 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.skywalking.apm.testcase.baidu.brpc.interfaces;
import com.baidu.brpc.protocol.BrpcMeta;
/**
* Copy from brpc-java-example
*/
public interface EchoService {
@BrpcMeta(serviceName = "example.EchoService", methodName = "Echo")
Echo.EchoResponse echo(Echo.EchoRequest request);
}
| 35.935484 | 75 | 0.753142 |
14452bce94ffa6544064b847ade2ce9deb898c30 | 4,164 | /*
* Copyright (C) 2014 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.example.android_environment_tv;
import android.graphics.drawable.Drawable;
import androidx.leanback.widget.ImageCardView;
import androidx.leanback.widget.Presenter;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
/*
* A CardPresenter is used to generate Views and bind Objects to them on demand.
* It contains an Image CardView
*/
public class CardPresenter extends Presenter {
private static final String TAG = "CardPresenter";
private static final int CARD_WIDTH = 313;
private static final int CARD_HEIGHT = 176;
private static int sSelectedBackgroundColor;
private static int sDefaultBackgroundColor;
private Drawable mDefaultCardImage;
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent) {
Log.d(TAG, "onCreateViewHolder");
sDefaultBackgroundColor =
ContextCompat.getColor(parent.getContext(), R.color.default_background);
sSelectedBackgroundColor =
ContextCompat.getColor(parent.getContext(), R.color.selected_background);
/*
* This template uses a default image in res/drawable, but the general case for Android TV
* will require your resources in xhdpi. For more information, see
* https://developer.android.com/training/tv/start/layouts.html#density-resources
*/
mDefaultCardImage = ContextCompat.getDrawable(parent.getContext(), R.drawable.movie);
ImageCardView cardView =
new ImageCardView(parent.getContext()) {
@Override
public void setSelected(boolean selected) {
updateCardBackgroundColor(this, selected);
super.setSelected(selected);
}
};
cardView.setFocusable(true);
cardView.setFocusableInTouchMode(true);
updateCardBackgroundColor(cardView, false);
return new ViewHolder(cardView);
}
private static void updateCardBackgroundColor(ImageCardView view, boolean selected) {
int color = selected ? sSelectedBackgroundColor : sDefaultBackgroundColor;
// Both background colors should be set because the view's background is temporarily visible
// during animations.
view.setBackgroundColor(color);
view.findViewById(R.id.info_field).setBackgroundColor(color);
}
@Override
public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
Movie movie = (Movie) item;
ImageCardView cardView = (ImageCardView) viewHolder.view;
Log.d(TAG, "onBindViewHolder");
if (movie.getCardImageUrl() != null) {
cardView.setTitleText(movie.getTitle());
cardView.setContentText(movie.getStudio());
cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT);
Glide.with(viewHolder.view.getContext())
.load(movie.getCardImageUrl())
.centerCrop()
.error(mDefaultCardImage)
.into(cardView.getMainImageView());
}
}
@Override
public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) {
Log.d(TAG, "onUnbindViewHolder");
ImageCardView cardView = (ImageCardView) viewHolder.view;
// Remove references to images so that the garbage collector can free up memory
cardView.setBadgeImage(null);
cardView.setMainImage(null);
}
}
| 40.038462 | 100 | 0.684198 |
481e2598194dc941d7f3a45beefb561cc296090f | 1,009 | package com.victor.sample.controller;
import com.victor.sample.service.ISampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("sample")
public class SampleController {
@Autowired
ISampleService sampleService;
@PostMapping
public ResponseEntity<Object> readRedis(@RequestParam String method,@RequestParam String key,@RequestParam String value) throws Exception {
switch (method){
case "get":
return ResponseEntity.ok(sampleService.readRedis(key));
case "post":
case "put":
return ResponseEntity.ok(sampleService.writeRedis(key,value));
case "delete":
return ResponseEntity.ok(sampleService.deleteRedis(key));
default:
throw new IllegalArgumentException("Method is not valid");
}
}
}
| 28.828571 | 144 | 0.679881 |
2ad54e577f07ce3812269bda0871db716e4a6f68 | 2,892 | package com.boydti.fawe.jnbt.anvil;
import com.boydti.fawe.beta.IChunkGet;
import com.boydti.fawe.beta.implementation.packet.ChunkPacket;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.world.AbstractWorld;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import java.io.File;
import java.util.Set;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class MCAWorld extends AbstractWorld {
private final File path;
public MCAWorld(File path) {
checkArgument(path.isDirectory());
this.path = path;
}
@Override
public String getName() {
return path.getName();
}
@Override
public <B extends BlockStateHolder<B>> boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException {
return false;
}
@Override
public boolean setTile(int x, int y, int z, CompoundTag tile) throws WorldEditException {
return false;
}
@Override
public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException {
return false;
}
@Override
public Set<SideEffect> applySideEffects(BlockVector3 position, BlockState previousType, SideEffectSet sideEffectSet) throws WorldEditException {
return SideEffectSet.none().getSideEffectsToApply();
}
@Override
public boolean clearContainerBlockContents(BlockVector3 position) {
return false;
}
@Override
public void dropItem(Vector3 position, BaseItemStack item) {
}
@Override
public void simulateBlockMine(BlockVector3 position) {
}
@Override
public boolean regenerate(Region region, EditSession editSession) {
return false;
}
@Override
public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException {
return false;
}
@Override
public BlockVector3 getSpawnPosition() {
return null;
}
@Override
public void refreshChunk(int chunkX, int chunkZ) {
}
@Override
public IChunkGet get(int x, int z) {
return null;
}
@Override
public void sendFakeChunk(@Nullable Player player, ChunkPacket packet) {
}
}
| 27.283019 | 148 | 0.737898 |
8a36571ba7da9758af428262f7c07123ff8f0fc0 | 8,173 | package basearch.dao.impl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
import basearch.model.PersistentObject;
import basearch.model.PersistentObject_;
public abstract class BaseDao {
@PersistenceContext
private EntityManager em;
public void setEm(EntityManager em) {
this.em = em;
}
/*
* fluent accessors
*/
/**
* Fluent accessor for a single entity, by id or with property restrictions
*/
protected final <E extends PersistentObject> EntityAccessor<E> entity(Class<E> type) {
return new EntityAccessorImpl<E>(type);
}
protected interface EntityAccessor<E extends PersistentObject> {
public E by(Long id);
public <T> PropertyBoundEntityAccessor<E> with(SingularAttribute<E, T> propertyName, T propertyValue);
}
protected interface PropertyBoundEntityAccessor<E extends PersistentObject> {
public <T> PropertyBoundEntityAccessor<E> and(SingularAttribute<E, T> propertyName, T propertyValue);
public E find();
}
private class EntityAccessorImpl<E extends PersistentObject> implements EntityAccessor<E>,PropertyBoundEntityAccessor<E> {
private final Class<E> type;
private CriteriaBuilder builder;
private CriteriaQuery<E> q;
private Root<E> r;
private Map<Path<?>,Object> parameters;
public EntityAccessorImpl(Class<E> type) { this.type = type; }
@Override public E by(Long id) {
assert(id != null);
return em.find(type, id);
}
@Override public <T> PropertyBoundEntityAccessor<E> with(SingularAttribute<E, T> propertyName, T propertyValue) {
assert(propertyName != null && propertyValue != null);
builder = em.getCriteriaBuilder();
q = builder.createQuery(type);
r = q.from(type);
parameters = new HashMap<Path<?>,Object>();
parameters.put(r.get(propertyName), propertyValue);
return this;
}
@Override public <T> PropertyBoundEntityAccessor<E> and(SingularAttribute<E, T> propertyName, T propertyValue) {
assert(propertyName != null && propertyValue != null);
parameters.put(r.get(propertyName), propertyValue);
return this;
}
@Override public E find() throws NonUniqueResultException {
Iterator<Entry<Path<?>,Object>> eit = parameters.entrySet().iterator();
Entry<Path<?>,Object> entry = eit.next();
Predicate conditions = builder.equal(entry.getKey(), entry.getValue());
while (eit.hasNext()) {
entry = eit.next();
conditions = builder.and(conditions,builder.equal(entry.getKey(), entry.getValue()));
}
q.where(conditions);
try { return em.createQuery(q).getSingleResult(); } catch(NoResultException nre) { return null; }
}
}
/**
* Fluent accessor for querying a single entity, by named query or by jpql
*/
protected final <E extends PersistentObject> EntityQuerier<E> query(Class<E> type) {
return new EntityQuerierImpl<E>(type);
}
protected interface EntityQuerier<E extends PersistentObject> {
public EntityNamedQuerier<E> named(String queryName);
}
protected interface EntityNamedQuerier<E extends PersistentObject> {
public List<E> list();
}
private class EntityQuerierImpl<E extends PersistentObject> implements EntityQuerier<E>, EntityNamedQuerier<E> {
private final Class<E> type;
private TypedQuery<E> query;
public EntityQuerierImpl(Class<E> type) { this.type = type; }
@Override public EntityNamedQuerier<E> named(String queryName) {
assert(queryName != null && queryName.length() > 0);
this.query = em.createNamedQuery(queryName, type);
return this;
}
@Override public List<E> list() { return this.query.getResultList(); }
}
/*
* persistence-forwarded methods
*/
/**
* Gets an entity. Doesn't return proxys. May return null if non-existent object.
*/
protected final <T extends PersistentObject> T entityFor(Class<T> type, Long id) {
assert(type != null && id != null);
return em.find(type, id);
}
/**
* Gets an entity. May return a proxy. Never returns null, but proxy may throw an exception if object
* is non-existent. Best used when object is known to exist.
*
* @throws EntityNotFoundException
*/
protected final <T extends PersistentObject> T referenceFor(Class<T> type, Long id) throws EntityNotFoundException {
assert(type != null && id != null);
return em.getReference(type, id);
}
/**
* Refresh object with new data from db, if any
*/
protected final <T extends PersistentObject> T refresh(T entity) {
assert(entity != null);
em.refresh(entity);
return entity;
}
/**
* Persists the object
*/
protected final <T extends PersistentObject> void persist(T entity) {
assert(entity != null);
em.persist(entity);
}
/**
* Checks if an entity is persistent in this persistence context
*/
protected final boolean isPersistent(PersistentObject entity) {
assert(entity != null);
return em.contains(entity);
}
/**
* Deletes the object
*/
protected final <T extends PersistentObject> void remove(T entity) {
assert(entity != null);
em.remove(entity);
}
/*
* utility methods
*/
/**
* Lists all objects of type
*/
protected final <T extends PersistentObject> List<T> allOf(Class<T> type) {
TypedQuery<T> q = em.createQuery(em.getCriteriaBuilder().createQuery(type));
return q.getResultList();
}
/**
* Gets the first object of type, the one with the lowest id
*/
protected final <T extends PersistentObject> T first(Class<T> type) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery(type);
Root<T> r = criteria.from(type);
criteria.orderBy(builder.asc(r.get(PersistentObject_.id)));
TypedQuery<T> q = em.createQuery(criteria);
q.setMaxResults(1);
return q.getSingleResult();
}
/*
* query methods
*/
/**
* Lists entities of type T having it's properties matched with values from params. Params can't be null.
* Property names and values arrays must be of the same size and have the same internal order.
*/
protected final <T extends PersistentObject> List<T> entitiesWith(Class<T> type, String[] properties, Object[] values) {
assert(type != null && properties != null && values != null);
assert(properties.length == values.length);
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<T> q = builder.createQuery(type);
Root<T> r = q.from(type);
for (int i = 0; i < properties.length; i++) {
//q.where(builder.)
}
List<T> results = em.createQuery(q).getResultList();
return results;
}
/*
* hardmodes
*/
protected final <T extends PersistentObject> EntityGraph<T> entityGraphFor(Class<T> type) {
return em.createEntityGraph(type);
}
protected final <T extends PersistentObject> TypedQuery<T> jpqlQueryFor(Class<T> type, String query) {
return em.createQuery(query, type);
}
protected final Query nativeQueryFor(String query) {
return em.createNativeQuery(query);
}
protected final CriteriaBuilder criteriaBuilder() {
return em.getCriteriaBuilder();
}
protected final <T> List<T> query(CriteriaQuery<T> q) {
assert(q != null);
return em.createQuery(q).getResultList();
}
/**
* @throws NoResultException
* @throws NonUniqueResultException
*/
protected final <T> T singleResult(CriteriaQuery<T> q) {
assert(q != null);
return em.createQuery(q).getSingleResult();
}
}
| 32.177165 | 124 | 0.703903 |
7281ebc9f01a86ef1024cd40a616c018e91da77c | 76 | package org.hidetake.stubyaml.service;
public interface ObjectCompiler {
}
| 15.2 | 38 | 0.815789 |
141618b8a47b94fb2fda74798d7e70740b5d2342 | 8,408 | /*
* Copyright 2015-2020 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.services.amplify.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Structure with Production Branch information.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ProductionBranch" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProductionBranch implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Last Deploy Time of Production Branch.
* </p>
*/
private java.util.Date lastDeployTime;
/**
* <p>
* Status of Production Branch.
* </p>
*/
private String status;
/**
* <p>
* Thumbnail URL for Production Branch.
* </p>
*/
private String thumbnailUrl;
/**
* <p>
* Branch Name for Production Branch.
* </p>
*/
private String branchName;
/**
* <p>
* Last Deploy Time of Production Branch.
* </p>
*
* @param lastDeployTime
* Last Deploy Time of Production Branch.
*/
public void setLastDeployTime(java.util.Date lastDeployTime) {
this.lastDeployTime = lastDeployTime;
}
/**
* <p>
* Last Deploy Time of Production Branch.
* </p>
*
* @return Last Deploy Time of Production Branch.
*/
public java.util.Date getLastDeployTime() {
return this.lastDeployTime;
}
/**
* <p>
* Last Deploy Time of Production Branch.
* </p>
*
* @param lastDeployTime
* Last Deploy Time of Production Branch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProductionBranch withLastDeployTime(java.util.Date lastDeployTime) {
setLastDeployTime(lastDeployTime);
return this;
}
/**
* <p>
* Status of Production Branch.
* </p>
*
* @param status
* Status of Production Branch.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* Status of Production Branch.
* </p>
*
* @return Status of Production Branch.
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* Status of Production Branch.
* </p>
*
* @param status
* Status of Production Branch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProductionBranch withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* Thumbnail URL for Production Branch.
* </p>
*
* @param thumbnailUrl
* Thumbnail URL for Production Branch.
*/
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
/**
* <p>
* Thumbnail URL for Production Branch.
* </p>
*
* @return Thumbnail URL for Production Branch.
*/
public String getThumbnailUrl() {
return this.thumbnailUrl;
}
/**
* <p>
* Thumbnail URL for Production Branch.
* </p>
*
* @param thumbnailUrl
* Thumbnail URL for Production Branch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProductionBranch withThumbnailUrl(String thumbnailUrl) {
setThumbnailUrl(thumbnailUrl);
return this;
}
/**
* <p>
* Branch Name for Production Branch.
* </p>
*
* @param branchName
* Branch Name for Production Branch.
*/
public void setBranchName(String branchName) {
this.branchName = branchName;
}
/**
* <p>
* Branch Name for Production Branch.
* </p>
*
* @return Branch Name for Production Branch.
*/
public String getBranchName() {
return this.branchName;
}
/**
* <p>
* Branch Name for Production Branch.
* </p>
*
* @param branchName
* Branch Name for Production Branch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProductionBranch withBranchName(String branchName) {
setBranchName(branchName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getLastDeployTime() != null)
sb.append("LastDeployTime: ").append(getLastDeployTime()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus()).append(",");
if (getThumbnailUrl() != null)
sb.append("ThumbnailUrl: ").append(getThumbnailUrl()).append(",");
if (getBranchName() != null)
sb.append("BranchName: ").append(getBranchName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ProductionBranch == false)
return false;
ProductionBranch other = (ProductionBranch) obj;
if (other.getLastDeployTime() == null ^ this.getLastDeployTime() == null)
return false;
if (other.getLastDeployTime() != null && other.getLastDeployTime().equals(this.getLastDeployTime()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
if (other.getThumbnailUrl() == null ^ this.getThumbnailUrl() == null)
return false;
if (other.getThumbnailUrl() != null && other.getThumbnailUrl().equals(this.getThumbnailUrl()) == false)
return false;
if (other.getBranchName() == null ^ this.getBranchName() == null)
return false;
if (other.getBranchName() != null && other.getBranchName().equals(this.getBranchName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getLastDeployTime() == null) ? 0 : getLastDeployTime().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
hashCode = prime * hashCode + ((getThumbnailUrl() == null) ? 0 : getThumbnailUrl().hashCode());
hashCode = prime * hashCode + ((getBranchName() == null) ? 0 : getBranchName().hashCode());
return hashCode;
}
@Override
public ProductionBranch clone() {
try {
return (ProductionBranch) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.amplify.model.transform.ProductionBranchMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| 28.405405 | 137 | 0.59931 |
6bd6f96825943624c37ce535bcb89363cf5cf966 | 3,383 | package org.jasig.cas.authentication;
import org.jasig.cas.util.http.HttpClient;
import org.jasig.cas.util.http.SimpleHttpClientFactoryBean;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import static org.junit.Assert.*;
/**
* Tests for the {@code FileTrustStoreSslSocketFactory} class, checking for self-signed
* and missing certificates via a local truststore.
* @author Misagh Moayyed
* @since 4.1.0
*/
public class FileTrustStoreSslSocketFactoryTests {
@Test
public void verifyTrustStoreLoadingSuccessfullyWithCertAvailable() throws Exception {
final ClassPathResource resource = new ClassPathResource("truststore.jks");
final FileTrustStoreSslSocketFactory factory = new FileTrustStoreSslSocketFactory(resource.getFile(), "changeit");
final SimpleHttpClientFactoryBean clientFactory = new SimpleHttpClientFactoryBean();
clientFactory.setSslSocketFactory(factory);
final HttpClient client = clientFactory.getObject();
assertTrue(client.isValidEndPoint("https://www.cacert.org"));
}
@Test
public void verifyTrustStoreLoadingSuccessfullyWithCertAvailable2() throws Exception {
final ClassPathResource resource = new ClassPathResource("truststore.jks");
final FileTrustStoreSslSocketFactory factory = new FileTrustStoreSslSocketFactory(resource.getFile(), "changeit");
final SimpleHttpClientFactoryBean clientFactory = new SimpleHttpClientFactoryBean();
clientFactory.setSslSocketFactory(factory);
final HttpClient client = clientFactory.getObject();
assertTrue(client.isValidEndPoint("https://test.scaldingspoon.org/idp/shibboleth"));
}
@Test(expected = RuntimeException.class)
public void verifyTrustStoreNotFound() throws Exception {
new FileTrustStoreSslSocketFactory(new File("test.jks"), "changeit");
}
@Test(expected = RuntimeException.class)
public void verifyTrustStoreBadPassword() throws Exception {
final ClassPathResource resource = new ClassPathResource("truststore.jks");
new FileTrustStoreSslSocketFactory(resource.getFile(), "invalid");
}
@Test
public void verifyTrustStoreLoadingSuccessfullyForValidEndpointWithNoCert() throws Exception {
final ClassPathResource resource = new ClassPathResource("truststore.jks");
final FileTrustStoreSslSocketFactory factory = new FileTrustStoreSslSocketFactory(resource.getFile(), "changeit");
final SimpleHttpClientFactoryBean clientFactory = new SimpleHttpClientFactoryBean();
clientFactory.setSslSocketFactory(factory);
final HttpClient client = clientFactory.getObject();
assertTrue(client.isValidEndPoint("https://www.google.com"));
}
@Test
public void verifyTrustStoreLoadingSuccessfullyWihInsecureEndpoint() throws Exception {
final ClassPathResource resource = new ClassPathResource("truststore.jks");
final FileTrustStoreSslSocketFactory factory = new FileTrustStoreSslSocketFactory(resource.getFile(), "changeit");
final SimpleHttpClientFactoryBean clientFactory = new SimpleHttpClientFactoryBean();
clientFactory.setSslSocketFactory(factory);
final HttpClient client = clientFactory.getObject();
assertTrue(client.isValidEndPoint("http://wikipedia.org"));
}
}
| 47.647887 | 122 | 0.759976 |
e2e35705b3a75e4e42a649f0ba6c1830e8586ffc | 2,974 | /*
* Copyright (c) 2016 DreamLiner Studio
* 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.dreamliner.lib.dropdownmenu.listener;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* @author chenzj
* @Title: OnRecyclerItemClickListener
* @Description: 类的描述 - 简易的recyclerview的itemClick实现
* @date
* @email [email protected]
*/
public abstract class OnRecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private GestureDetectorCompat mGestureDetector;
private RecyclerView recyclerView;
public OnRecyclerItemClickListener(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
mGestureDetector = new GestureDetectorCompat(recyclerView.getContext(), new ItemTouchHelperGestureListener());
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
private class ItemTouchHelperGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null) {
RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
int position = recyclerView.getChildAdapterPosition(child);
onItemClick(vh, child, position);
}
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null) {
RecyclerView.ViewHolder vh = recyclerView.getChildViewHolder(child);
int position = recyclerView.getChildAdapterPosition(child);
onLongClick(vh, child, position);
}
}
}
public abstract void onItemClick(RecyclerView.ViewHolder vh, View view, int position);
public void onLongClick(RecyclerView.ViewHolder vh, View view, int position) {
}
}
| 34.581395 | 118 | 0.704775 |
3232523961f707b04d5fd28d8bdb3f5d3eb99c30 | 201 | package com.shieldui.wicket.dropdown;
public abstract class SelectEventListener extends com.shieldui.wicket.combobox.SelectEventListener
{
private static final long serialVersionUID = 1L;
}
| 28.714286 | 99 | 0.800995 |
28e2a71cf3fe9e5b24fe9264878eda760dd0b366 | 133 | package com.atlassian.maven.plugin.clover.samples.testsources;
/**
* Simulate a base class for tests.
*/
public class WebTest {
}
| 16.625 | 62 | 0.736842 |
ff808148d0c4a162499c282d27de40fa7038b26b | 13,522 | /*
* 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.linkis.metadatamanager.server.loader;
import org.apache.linkis.common.conf.CommonVars;
import org.apache.linkis.common.conf.Configuration;
import org.apache.linkis.common.exception.ErrorException;
import org.apache.linkis.metadatamanager.common.exception.MetaRuntimeException;
import org.apache.linkis.metadatamanager.common.service.AbstractMetaService;
import org.apache.linkis.metadatamanager.common.service.MetadataService;
import org.apache.linkis.metadatamanager.server.utils.MetadataUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
/** Class Loader for metaClass // TODO used interface class */
public class MetaClassLoaderManager {
private final Map<String, ClassLoader> classLoaders = new ConcurrentHashMap<>();
private final Map<String, MetaServiceInstance> metaServiceInstances = new ConcurrentHashMap<>();
public static CommonVars<String> LIB_DIR =
CommonVars.apply(
"wds.linkis.server.mdm.service.lib.dir",
Configuration.getLinkisHome()
+ "/lib/linkis-public-enhancements/linkis-ps-metadatamanager/service");
public static CommonVars<Integer> INSTANCE_EXPIRE_TIME =
CommonVars.apply("wds.linkis.server.mdm.service.instance.expire-in-seconds", 60);
private static final String META_CLASS_NAME =
"org.apache.linkis.metadatamanager.service.%sMetaService";
private static final Logger LOG = LoggerFactory.getLogger(MetaClassLoaderManager.class);
public BiFunction<String, Object[], Object> getInvoker(String dsType) throws ErrorException {
boolean needToLoad = true;
MetaServiceInstance serviceInstance = metaServiceInstances.get(dsType);
if (Objects.nonNull(serviceInstance)) {
Integer expireTimeInSec = INSTANCE_EXPIRE_TIME.getValue();
// Lazy load
needToLoad =
Objects.nonNull(expireTimeInSec)
&& expireTimeInSec > 0
&& (serviceInstance.initTimeStamp
+ TimeUnit.MILLISECONDS.convert(
expireTimeInSec, TimeUnit.SECONDS))
< System.currentTimeMillis();
}
if (needToLoad) {
MetaServiceInstance finalServiceInstance1 = serviceInstance;
serviceInstance =
metaServiceInstances.compute(
dsType,
(key, instance) -> {
if (null != instance
&& !Objects.equals(finalServiceInstance1, instance)) {
return instance;
}
String lib = LIB_DIR.getValue();
String stdLib = lib.endsWith("/") ? lib.replaceAll(".$", "") : lib;
String componentLib = stdLib + "/" + dsType;
LOG.info(
"Start to load/reload meta instance of data source type: ["
+ dsType
+ "] from library dir:"
+ componentLib);
ClassLoader parentClassLoader =
MetaClassLoaderManager.class.getClassLoader();
ClassLoader metaClassLoader =
classLoaders.compute(
dsType,
(type, classLoader) -> {
try {
return new URLClassLoader(
getJarsUrlsOfPath(componentLib)
.toArray(new URL[0]),
parentClassLoader);
} catch (Exception e) {
LOG.error(
"Cannot init the classloader of type: ["
+ dsType
+ "] in library path: ["
+ componentLib
+ "]",
e);
return null;
}
});
if (Objects.isNull(metaClassLoader)) {
throw new MetaRuntimeException(
"Error in creating classloader of type: ["
+ dsType
+ "]",
null);
}
String expectClassName = null;
if (dsType.length() > 0) {
String prefix =
dsType.substring(0, 1).toUpperCase()
+ dsType.substring(1);
expectClassName = String.format(META_CLASS_NAME, prefix);
}
Class<? extends MetadataService> metaServiceClass =
searchForLoadMetaServiceClass(
metaClassLoader, expectClassName, true);
if (Objects.isNull(metaServiceClass)) {
throw new MetaRuntimeException(
"Fail to init and load meta service class for type: ["
+ dsType
+ "]",
null);
}
MetadataService metadataService =
MetadataUtils.loadMetaService(
metaServiceClass, metaClassLoader);
if (metadataService instanceof AbstractMetaService) {
LOG.info(
"Invoke the init() method in meta service for type: ["
+ dsType
+ "]");
((AbstractMetaService<?>) metadataService).init();
}
return new MetaServiceInstance(metadataService, metaClassLoader);
});
}
Method[] childMethods = serviceInstance.methods;
MetaServiceInstance finalServiceInstance = serviceInstance;
return (String m, Object... args) -> {
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(finalServiceInstance.metaClassLoader);
Method method =
Arrays.stream(childMethods)
.filter(eachMethod -> eachMethod.getName().equals(m))
.collect(Collectors.toList())
.get(0);
return method.invoke(finalServiceInstance.serviceInstance, args);
} catch (Exception e) {
Throwable t = e;
// UnWrap the Invocation target exception
while (t instanceof InvocationTargetException) {
t = t.getCause();
}
String message =
"Fail to invoke method: ["
+ m
+ "] in meta service instance: ["
+ finalServiceInstance.serviceInstance.toString()
+ "]";
LOG.warn(message, t);
throw new MetaRuntimeException(message, t);
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
};
}
private Class<? extends MetadataService> searchForLoadMetaServiceClass(
ClassLoader classLoader, String expectClassName, boolean initialize) {
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
Class<? extends MetadataService> metaClass = null;
if (StringUtils.isNotBlank(expectClassName)) {
metaClass =
MetadataUtils.loadMetaServiceClass(
classLoader,
expectClassName,
initialize,
"Cannot find class in using expect class name: ["
+ expectClassName
+ "]");
}
if (Objects.isNull(metaClass)) {
if (classLoader instanceof URLClassLoader) {
String[] metaServiceClassNames =
MetadataUtils.searchMetaServiceClassInLoader(
(URLClassLoader) classLoader);
if (metaServiceClassNames.length > 0) {
String metaServiceClassName = metaServiceClassNames[0];
metaClass =
MetadataUtils.loadMetaServiceClass(
classLoader,
metaServiceClassName,
initialize,
"Cannot load class in canonical name: ["
+ metaServiceClassName
+ "], please check the compiled jar/file");
}
}
}
return metaClass;
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
private List<URL> getJarsUrlsOfPath(String path) throws MalformedURLException {
File file = new File(path);
List<URL> jars = new ArrayList<>();
if (file.listFiles() != null) {
for (File f : Objects.requireNonNull(file.listFiles())) {
if (!f.isDirectory() && f.getName().endsWith(".jar")) {
jars.add(f.toURI().toURL());
} else if (f.isDirectory()) {
jars.addAll(getJarsUrlsOfPath(f.getPath()));
}
}
}
return jars;
}
/** ServiceInstance Holder */
public static class MetaServiceInstance {
private MetadataService serviceInstance;
private Method[] methods;
private ClassLoader metaClassLoader;
private long initTimeStamp = 0L;
public MetaServiceInstance(MetadataService serviceInstance, ClassLoader metaClassLoader) {
this.serviceInstance = serviceInstance;
this.metaClassLoader = metaClassLoader;
this.methods = serviceInstance.getClass().getMethods();
this.initTimeStamp = System.currentTimeMillis();
}
public MetadataService getServiceInstance() {
return serviceInstance;
}
}
}
| 51.026415 | 104 | 0.472415 |
f7ce4d4d8ef2ec81ea573d8d5c15346b64457806 | 3,829 | /*
* Copyright 2020 Netflix, Inc.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.netflix.conductor.contribs.queue.sqs.config;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.netflix.conductor.common.metadata.tasks.Task.Status;
import com.netflix.conductor.contribs.queue.sqs.SQSObservableQueue.Builder;
import com.netflix.conductor.core.config.ConductorProperties;
import com.netflix.conductor.core.events.EventQueueProvider;
import com.netflix.conductor.core.events.queue.ObservableQueue;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import rx.Scheduler;
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Configuration
@EnableConfigurationProperties(SQSEventQueueProperties.class)
@ConditionalOnProperty(name = "conductor.event-queues.sqs.enabled", havingValue = "true")
public class SQSEventQueueConfiguration {
@ConditionalOnMissingBean
@Bean
public AmazonSQSClient getSQSClient(AWSCredentialsProvider credentialsProvider) {
return new AmazonSQSClient(credentialsProvider);
}
@Bean
public EventQueueProvider sqsEventQueueProvider(AmazonSQSClient sqsClient, SQSEventQueueProperties properties,
Scheduler scheduler) {
return new SQSEventQueueProvider(sqsClient, properties, scheduler);
}
@ConditionalOnProperty(name = "conductor.default-event-queue.type", havingValue = "sqs", matchIfMissing = true)
@Bean
public Map<Status, ObservableQueue> getQueues(ConductorProperties conductorProperties,
SQSEventQueueProperties properties, AmazonSQSClient sqsClient) {
String stack = "";
if (conductorProperties.getStack() != null && conductorProperties.getStack().length() > 0) {
stack = conductorProperties.getStack() + "_";
}
Status[] statuses = new Status[]{Status.COMPLETED, Status.FAILED};
Map<Status, ObservableQueue> queues = new HashMap<>();
for (Status status : statuses) {
String queuePrefix = StringUtils.isBlank(properties.getListenerQueuePrefix())
? conductorProperties.getAppId() + "_sqs_notify_" + stack
: properties.getListenerQueuePrefix();
String queueName = queuePrefix + status.name();
Builder builder = new Builder().withClient(sqsClient).withQueueName(queueName);
String auth = properties.getAuthorizedAccounts();
String[] accounts = auth.split(",");
for (String accountToAuthorize : accounts) {
accountToAuthorize = accountToAuthorize.trim();
if (accountToAuthorize.length() > 0) {
builder.addAccountToAuthorize(accountToAuthorize.trim());
}
}
ObservableQueue queue = builder.build();
queues.put(status, queue);
}
return queues;
}
}
| 45.583333 | 118 | 0.733612 |
c7f735780fe4ac1a175a5c941e48aaa13451fea2 | 1,354 | class Intersect
{
int intersectPoint(Node headA, Node headB)
{
// code here
Node temp1 = headA;
Node temp2 = headB;
int countA = 0;
int countB = 0;
while(temp1 != null){
countA++;
temp1 = temp1.next;
}
while(temp2 != null){
countB++;
temp2 = temp2.next;
}
temp1 = headA;
temp2 = headB;
int diff = 0;
if(countA>countB){
diff = countA - countB;
for(int i = 0; i < diff; i++ ){
temp1 = temp1.next;
}
while(temp1 != null && temp2 != null){
if(temp1.data == temp2.data)
return temp1.data;
else
{
temp1 = temp1.next;
temp2 = temp2.next;
}
}
return -1;
}
else{
diff = countB - countA;
for(int i = 0; i < diff; i++ ){
temp2 = temp2.next;
}
while(temp1 != null && temp2 != null){
if(temp1.data == temp2.data)
return temp1.data;
else{
temp1 = temp1.next;
temp2 = temp2.next;
}
}
return -1;
}
}
}
| 22.566667 | 50 | 0.370015 |
84ad290a0af124564bbca234e52d318bdc7326c3 | 1,928 | package com.telerik.app.tasks;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.Scopes;
import com.telerik.app.activities.LoginActivity;
import java.io.IOException;
import com.telerik.app.model.BaseViewModel;
public class GoogleLoginTask extends AsyncTask {
private String token;
private String accountName;
private Activity activity;
private ProgressDialog progressDialog;
public GoogleLoginTask(Activity activity, String accountName, ProgressDialog progressDialog) {
this.activity = activity;
this.accountName = accountName;
this.progressDialog = progressDialog;
}
@Override
protected Object doInBackground(Object... params) {
String scope = "oauth2: " + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_PROFILE;
try {
this.token = GoogleAuthUtil.getToken(this.activity, accountName, "oauth2:" + Scopes.PLUS_LOGIN + " " +
"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email");
BaseViewModel.EverliveAPP.workWith().
authentication().
loginWithGoogle(this.token).
execute(new LoginRequestResultCallbackAction(this.activity, "Google", this.progressDialog));
} catch (UserRecoverableAuthException e) {
Intent recover = e.getIntent();
activity.startActivityForResult(recover, LoginActivity.REQUEST_CODE_RESOLVE_ERR);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return null;
}
}
| 37.803922 | 119 | 0.693983 |
e841ed3dab5b8b4578f0d4b2b8e12fcb64619b92 | 183 | package github.ryuunoakaihitomi.poweract.test;
import org.junit.Rule;
public class BaseTest implements Log {
@Rule
public BorderLogger borderLogger = new BorderLogger();
}
| 18.3 | 58 | 0.765027 |
4df3222e60893b94b8fbdf46e86fcae49e78220d | 1,590 | package com.example.webtestclient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration;
@SpringBootTest
@ExtendWith({SpringExtension.class, RestDocumentationExtension.class})
public class SampleWebTestClientApplicationTests {
@Autowired
ApplicationContext context;
private WebTestClient webTestClient;
@BeforeEach
public void setUp(RestDocumentationContextProvider restDocumentation) {
this.webTestClient = WebTestClient.bindToApplicationContext(context)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
@Test
public void sample() throws Exception {
this.webTestClient.get().uri("/").exchange()
.expectStatus().isOk().expectBody()
.consumeWith(document("sample", resource("sample description")));
}
}
| 36.976744 | 115 | 0.835849 |
6291300ba4857952bb41f5a9a1a33945f8afc2e0 | 2,721 | package com.nmittal.maze.solve;
import org.junit.Assert;
import org.junit.Test;
import com.nmittal.maze.domain.Aisle;
import com.nmittal.maze.domain.Block;
import com.nmittal.maze.domain.Maze;
import com.nmittal.maze.domain.Wall;
import com.nmittal.maze.util.MazeBuilder;
/**
* JUnit to test the Maze
*
* @author Narain Mittal
*
*/
public class MazeDfsTest {
private IMazeSolver dfs;
@Test(expected = IllegalArgumentException.class)
public void testInsufficientMazeDataException() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0 } };
Maze maze = MazeBuilder.buildMaze(data, 0, 1, 3, 1);
dfs = new MazeSolverBfs(maze);
dfs.solve();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidMazeDataException() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 2 } };
Maze maze = MazeBuilder.buildMaze(data, 0, 1, 3, 1);
dfs = new MazeSolverBfs(maze);
dfs.solve();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidMazeDataException2() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1, 1 } };
Maze maze = MazeBuilder.buildMaze(data, 0, 1, 3, 1);
dfs = new MazeSolverBfs(maze);
dfs.solve();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidMazeStartException() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 } };
Maze maze = MazeBuilder.buildMaze(data, 5, 5, 3, 1);
dfs = new MazeSolverBfs(maze);
dfs.solve();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidMazeEndException() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 } };
Maze maze = MazeBuilder.buildMaze(data, 0, 1, 5, 5);
dfs = new MazeSolverBfs(maze);
dfs.solve();
}
@Test
public void testMazeSolution() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 } };
Maze maze = MazeBuilder.buildMaze(data, 0, 1, 3, 1);
dfs = new MazeSolverBfs(maze);
Assert.assertTrue(dfs.solve());
Block[][] blocks = maze.getBlocks();
for (Block[] bl : blocks) {
for (Block b : bl) {
if (b instanceof Wall) {
Assert.assertFalse(dfs.isBlockVisited(b));
Assert.assertFalse(dfs.isBlockInSolution(b));
} else if (b instanceof Aisle) {
Assert.assertTrue(dfs.isBlockVisited(b));
Assert.assertTrue(dfs.isBlockInSolution(b));
}
}
}
}
@Test
public void testMazeNoSolution() {
int[][] data = new int[][] { { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 }, { 1, 0, 1 } };
Maze maze = MazeBuilder.buildMaze(data, 0, 1, 3, 2);
dfs = new MazeSolverBfs(maze);
Assert.assertFalse(dfs.solve());
}
}
| 30.233333 | 87 | 0.615215 |
a4d9fc93765b7dd93fdd62e93a24e860a9026ac6 | 530 | package org.vinci.commons.orm.mybatis.scurd;
public class UpdateDepict extends CurdAbstractDepict<UpdateDepict> {
public UpdateDepict(String fieldName, String columnName) {
super.setFieldName(fieldName);
super.setColumnName(columnName);
}
public UpdateDepict(String fieldName, String columnName, CurdAbstractDepictMap<UpdateDepict> curdAbstractDepictMap) {
super.setFieldName(fieldName);
super.setColumnName(columnName);
super.setOwnerDepictMap(curdAbstractDepictMap);
}
} | 37.857143 | 121 | 0.754717 |
729e95d5f281a3545623782f61dab648a89411f9 | 2,231 | /*******************************************************************************
* <copyright>
*
* Copyright (c) 2005, 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SAP AG - initial API, implementation and documentation
*
* </copyright>
*
*******************************************************************************/
package org.activiti.designer.eclipse.outline.tree;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;
import org.eclipse.graphiti.mm.algorithms.GraphicsAlgorithm;
import org.eclipse.graphiti.mm.algorithms.styles.Color;
import org.eclipse.graphiti.mm.algorithms.styles.Point;
import org.eclipse.graphiti.mm.algorithms.styles.Style;
import org.eclipse.graphiti.mm.pictograms.ConnectionDecorator;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
/**
* A concrete implementation of the interface IEditPartFactory for Trees, which
* works on a pictogram model.
*/
public class PictogramsTreeEditPartFactory implements EditPartFactory {
/**
* Creates a new PictogramsEditPartFactory.
*/
public PictogramsTreeEditPartFactory() {
super();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.gef.EditPartFactory#createEditPart(org.eclipse.gef.EditPart,
* java.lang.Object)
*/
@Override
public EditPart createEditPart(EditPart context, Object model) {
EditPart ret = null;
if (model instanceof PictogramElement) {
ret = new PictogramElementTreeEditPart((PictogramElement) model);
} else if (model instanceof GraphicsAlgorithm) {
ret = new GraphicsAlgorithmTreeEditPart((GraphicsAlgorithm) model);
} else if (model instanceof ConnectionDecorator) {
ret = new ConnectionDecoratorTreeEditPart((ConnectionDecorator) model);
} else if (model instanceof Point) {
ret = new PointTreeEditPart((Point) model);
} else if (model instanceof Color) {
ret = new ColorTreeEditPart((Color) model);
} else if (model instanceof Style) {
ret = new StyleTreeEditPart((Style) model);
}
return ret;
}
} | 34.323077 | 81 | 0.700134 |
d8bf4e4cdaacab725c5ceab21c84d992c9b8c338 | 55,038 | /* This thread does all the work. It communicates with the client through Envelopes.
*
*/
import java.lang.Thread;
import java.net.Socket;
import java.io.*;
import java.util.*;
// include crypto librarys needed
import javax.crypto.*;
import javax.crypto.KeyGenerator;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
// add pemobject and pemreader for parsing public/private keys
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class GroupThread extends Thread {
DataLogger gLog = new DataLogger("Group");
StringWriter stackTraceString = new StringWriter();
PrintWriter stackTrace = new PrintWriter(stackTraceString);
private final Socket socket;
private GroupServer my_gs;
private SecretKey sessionConfidentialityAESKey;
private SecretKey sessionIntegrityAESKey;
private byte[] authenticationHash;
private SecureRandom sr = null;
private int counter;
public GroupThread(Socket _socket, GroupServer _gs) {
socket = _socket;
my_gs = _gs;
}
public void run() {
Security.addProvider(new BouncyCastleProvider());
boolean proceed = true;
try {
//Announces connection and opens object streams
System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***");
final ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
do {
if (sr == null) {
Envelope message = (Envelope) input.readObject();
System.out.println("Request received: " + message.getMessage());
Envelope response;
if (message.getMessage().equals("AUTH1")) {
// open the users public key from the UserPubKeys folder
String username = (String) message.getObjContents().get(0); //Get the username
// if the user isnt in the system dont even try
if (username != null && my_gs.userList.checkUser(username)) {
try {
// their username exist
// try to open their public key for encrypting session key
PemReader userPubPemReader = new PemReader(new InputStreamReader(new FileInputStream("UserPubKeys/user-" + username + "-pubK.pem")));
PemObject userPubPemObj = userPubPemReader.readPemObject();
byte[] publicBytes = userPubPemObj.getContent();
X509EncodedKeySpec pubEncoded = new X509EncodedKeySpec(publicBytes);
KeyFactory daFactory = KeyFactory.getInstance("RSA");
PublicKey userPubK = daFactory.generatePublic(pubEncoded);
userPubPemReader.close();
// create the shared key to be used in that session
KeyGenerator theGenerator = KeyGenerator.getInstance("AES", "BC");
theGenerator.init(256, new SecureRandom());
sessionConfidentialityAESKey = theGenerator.generateKey();
theGenerator.init(256, new SecureRandom());
sessionIntegrityAESKey = theGenerator.generateKey();
// generate a fresh random challenge
SecureRandom rand = new SecureRandom();
byte[] challenge = new byte[20];//160 bit random challenge.
rand.nextBytes(challenge);
// generate the hash of the session key bytes and challenge byte to temporarily remember
byte[] concat = new byte[84];
byte[] encodedSesAes = sessionConfidentialityAESKey.getEncoded();
byte[] encodedIntegrity = sessionIntegrityAESKey.getEncoded();
System.arraycopy(encodedSesAes, 0, concat, 0, encodedSesAes.length);//copying the encoded key, and the challenge into a concat byte array
System.arraycopy(encodedIntegrity, 0, concat, encodedSesAes.length, encodedIntegrity.length);
System.arraycopy(challenge, 0, concat, (encodedSesAes.length + encodedIntegrity.length), challenge.length);
MessageDigest theDigester = MessageDigest.getInstance("SHA-256", "BC");
theDigester.update(concat);
authenticationHash = theDigester.digest();
// encrypt the key and send over the bytes
Cipher cipher = Cipher.getInstance("RSA", "BC");
cipher.init(Cipher.ENCRYPT_MODE, userPubK);
byte[] encryptedConf = cipher.doFinal(encodedSesAes);
encryptedConf = Base64.getEncoder().encode(encryptedConf);
byte[] encryptedInteg = cipher.doFinal(encodedIntegrity);
encryptedInteg = Base64.getEncoder().encode(encryptedInteg);
// everything went fine, send challenge and encrypted session key
response = new Envelope("1");
response.addBytes1(Base64.getEncoder().encode(challenge));
response.addBytes2(encryptedConf);
response.addBytes3(encryptedInteg);
output.writeObject(response);
} catch (Exception ex) {
// if their public key file is not on the server, fail
response = new Envelope("NOKEY");
response.addBytes1(null);
output.writeObject(response);
System.out.println(ex.getMessage());
ex.printStackTrace();
}
} else {
response = new Envelope("FAIL");
response.addBytes1(null);
output.writeObject(response);
}
} else if (message.getMessage().equals("AUTH2")) {
byte[] hashToCheck = Base64.getDecoder().decode(message.getBytes1());
byte[] encryptedChallenge = Base64.getDecoder().decode(message.getBytes2());
// if hashes are the same, then we know its them
//System.out.println("H: "+new String(hashToCheck));
//System.out.println("A: "+new String(authenticationHash));
if (Arrays.equals(authenticationHash, hashToCheck)) {
try {
// hashes were the same, decrypt the challenge and send it back to them
PemReader sysPrivPemReader = new PemReader(new InputStreamReader(new FileInputStream("SystemKeys/gs-privK.pem")));
PemObject sysPrivPemObj = sysPrivPemReader.readPemObject();
byte[] privateBytes = sysPrivPemObj.getContent();
PKCS8EncodedKeySpec privEncoded = new PKCS8EncodedKeySpec(privateBytes);
KeyFactory daFactory = KeyFactory.getInstance("RSA");
PrivateKey privK = daFactory.generatePrivate(privEncoded);
sysPrivPemReader.close();
Cipher cipher = Cipher.getInstance("RSA", "BC");
cipher.init(Cipher.DECRYPT_MODE, privK);
// set-up space for the decrypted bytes to go
byte[] decryptedChallenge = cipher.doFinal(encryptedChallenge);
//decryptedChallenge = new byte[cipher.getOutputSize(encryptedChallenge.length)];
//int decryptedLength = cipher.update(encryptedChallenge, 0, encryptedChallenge.length, decryptedChallenge, 0);
//decryptedLength += cipher.doFinal(decryptedChallenge, decryptedLength);
// now we have the decryptedChallenge bytes, send them back
System.out.println("Mutual authentication successful.");
message = new Envelope("2");
message.addBytes1(Base64.getEncoder().encode(decryptedChallenge));
output.writeObject(message);
sr = new SecureRandom();
counter = 0;
} catch (Exception ex) {
response = new Envelope("FAIL");
response.addBytes1(null);
output.writeObject(response);
}
} else {
response = new Envelope("FAIL");
response.addBytes1(null);
output.writeObject(response);
}
}
} else {
Envelope message = null;
Envelope response;
try {
message = (Envelope) decrypt(input);
System.out.println(message.getMessage());
} catch (Exception e) {
}
if (message.getMessage().equals("GET"))//Client wants a token
{
String username = (String) message.getObjContents().get(0); //Get the username
String wantedIP = (String) message.getObjContents().get(1); //Get the wantedIP
String wantedPort = (String) message.getObjContents().get(2); //Get the wantedPort
if (username == null || wantedIP == null || wantedPort == null) {
response = new Envelope("FAIL");
response.addObject(null);
encrypt(response, output);
} else {
UserToken yourToken = createToken(username, wantedIP, wantedPort); //Create a token
System.out.println("Token issued to: " + username);
//Respond to the client. On error, the client will receive a null token
response = new Envelope("OK");
response.addObject(yourToken);
encrypt(response, output);
}
} else if (message.getMessage().equals("KCHAIN")) {
if (message.getObjContents().size() < 2) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
String username = (String) message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken) message.getObjContents().get(1); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
// username and token are valid, create their keychain and send it back
Hashtable<String, ArrayList<String>> encKeyChainTable = createKeyChainTable(username, yourToken, "e");
Hashtable<String, ArrayList<String>> intKeyChainTable = createKeyChainTable(username, yourToken, "i");
System.out.println("encr kchain's size is: " + encKeyChainTable.size());
System.out.println("int kchain's size is: " + encKeyChainTable.size());
if (encKeyChainTable != null && intKeyChainTable != null) {
System.out.println("Valid encryption keychain and integrity keychain made");
response = new Envelope("OK"); //Success
response.addObject(encKeyChainTable);
response.addObject(intKeyChainTable);
System.out.println(yourToken.getSubject() + " was successfully given their keychains");
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("CUSER")) //Client wants to create a user
{
if (message.getObjContents().size() < 2) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
String username = (String) message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken) message.getObjContents().get(1); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
if (createUser(username, yourToken)) {
response = new Envelope("OK"); //Success
System.out.println("Admin " + yourToken.getSubject() + " successfully created User: " + username);
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("DUSER")) //Client wants to delete a user
{
if (message.getObjContents().size() < 2) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
String username = (String) message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken) message.getObjContents().get(1); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
if (deleteUser(username, yourToken)) {
response = new Envelope("OK"); //Success
System.out.println("Admin " + yourToken.getSubject() + " successfully deleted User: " + username);
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("CGROUP")) //Client wants to create a group
{
// first should be the group second should be the token
if (message.getObjContents().size() < 2) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
String daGroupName = (String) message.getObjContents().get(0); //Extract the group to be created
UserToken yourToken = (UserToken) message.getObjContents().get(1); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
// method implemented found below
if (createGroup(daGroupName, yourToken)) {
response = new Envelope("OK"); //Success
System.out.println("User " + yourToken.getSubject() + " successfully created Group: " + daGroupName);
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("DGROUP")) //Client wants to delete a group
{
// first should be group second should be token
if (message.getObjContents().size() < 2) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
String daGroupName = (String) message.getObjContents().get(0); //Extract group to be deleted
UserToken yourToken = (UserToken) message.getObjContents().get(1); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
// method implementation found below
if (deleteGroup(daGroupName, yourToken)) {
response = new Envelope("OK"); //Success
System.out.println("User " + yourToken.getSubject() + " successfully deleted Group: " + daGroupName);
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("LMEMBERS")) //Client wants a list of members in a group
{
// first should be group second should be token
if (message.getObjContents().size() < 2) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
String daGroupName = (String) message.getObjContents().get(0); //Extract group whose members we list
UserToken yourToken = (UserToken) message.getObjContents().get(1); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
ArrayList<String> listOfMembers = listMembersOfGroup(daGroupName, yourToken);
if (listOfMembers != null) // we built a list
{
response = new Envelope("OK"); //Success
response.addObject(listOfMembers);
}
} else {
response = new Envelope("MODIFIED");
}
encrypt(response, output);
}
}
}
} else if (message.getMessage().equals("AUSERTOGROUP")) //Client wants to add user to a group
{
// first should be username, second should be group third should be token
if (message.getObjContents().size() < 3) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
if (message.getObjContents().get(2) != null) {
String daUserName = (String) message.getObjContents().get(0); //Extract the username
String daGroupName = (String) message.getObjContents().get(1); //Extract the group
UserToken yourToken = (UserToken) message.getObjContents().get(2); //Extract the token
/* method found below */
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
if (addUserToGroup(daUserName, daGroupName, yourToken)) {
response = new Envelope("OK"); //Success
System.out.println("User " + yourToken.getSubject() + " successfully added User: " + daUserName + " to Group: " + daGroupName);
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("RUSERFROMGROUP")) //Client wants to remove user from a group
{
// same as adding users to groups, we need the same info
if (message.getObjContents().size() < 3) {
response = new Envelope("FAIL");
} else {
response = new Envelope("FAIL");
if (message.getObjContents().get(0) != null) {
if (message.getObjContents().get(1) != null) {
if (message.getObjContents().get(2) != null) {
String daUserName = (String) message.getObjContents().get(0); //Extract the username
String daGroupName = (String) message.getObjContents().get(1); //Extract the group
UserToken yourToken = (UserToken) message.getObjContents().get(2); //Extract the token
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
System.out.println(yourToken.getSubject() + "'s token was successfully verified.");
if (deleteUserFromGroup(daUserName, daGroupName, yourToken)) {
// they were successfully removed, generate a new group key
int currentBlock = my_gs.keyList.getCurBlockNum(daGroupName);
my_gs.keyList.addKeysToGroup(daGroupName);
my_gs.userList.addUserEndBlock(daUserName, daGroupName, currentBlock);
response = new Envelope("OK"); //Success
System.out.println("User " + yourToken.getSubject() + " successfully removed User: " + daUserName + " from Group: " + daGroupName);
}
} else {
response = new Envelope("MODIFIED");
}
}
}
}
}
encrypt(response, output);
} else if (message.getMessage().equals("DISCONNECT")) //Client wants to disconnect
{
sr = null;
socket.close(); //Close the socket
proceed = false; //End this communication loop
} else {
response = new Envelope("FAIL"); //Server does not understand client request
encrypt(response, output);
}
}
} while (proceed);
} catch (Exception e) {
e.printStackTrace(stackTrace);
gLog.write("err", e.getMessage(), stackTraceString.toString());
}
}
//Method to create tokens
private UserToken createToken(String username, String wantedIP, String wantedPort) {
//Check that user exists
if (my_gs.userList.checkUser(username)) {
// using BouncyCastleProvider
Security.addProvider(new BouncyCastleProvider());
try {
// load the server's private key file to be used in signature process
PemReader daPrivPemReader = new PemReader(new InputStreamReader(new FileInputStream("SystemKeys/gs-privK.pem")));
PemObject daPrivPemObj = daPrivPemReader.readPemObject();
byte[] privateBytes = daPrivPemObj.getContent();
PKCS8EncodedKeySpec privEncoded = new PKCS8EncodedKeySpec(privateBytes);
KeyFactory daFactory = KeyFactory.getInstance("RSA");
PrivateKey privK = daFactory.generatePrivate(privEncoded);
// create the concatenated string, add sentinel value for separation
String toBeHashed = my_gs.name + "\0" + username + "\0" + wantedIP + "\0" + wantedPort + "\0";
ArrayList<String> userGroups = my_gs.userList.getUserGroups(username);
// sort the groups so they are hashed in a consistent manner
Collections.sort(userGroups);
for (int i = 0; i < userGroups.size(); i++) {
toBeHashed = toBeHashed + userGroups.get(i) + "\0";
}
// create the SHA256 hash of the concatenated string, sign it with privK
MessageDigest theDigester = MessageDigest.getInstance("SHA-256", new BouncyCastleProvider());
theDigester.update(toBeHashed.getBytes());
byte[] hashedToken = theDigester.digest();
Signature signature = Signature.getInstance("SHA256withRSA", "BC");
signature.initSign(privK, new SecureRandom());
signature.update(hashedToken);
byte[] signedHash = signature.sign();
//Issue a new token with server's name, user's name, and user's groups
UserToken yourToken = new Token(my_gs.name, username, my_gs.userList.getUserGroups(username), wantedIP, wantedPort, signedHash);
//log that the server issued a token
gLog.write("data", "Server issued token to user " + username + ".", "");
return yourToken;
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
// if we never returned the actual token, this will return null
return null;
}
//Method to create the keychain table for all blocks from all groups a user can have access too
private Hashtable createKeyChainTable(String username, UserToken yourToken, String type) {
int usersStartBlock, usersEndBlock;
Hashtable<String, ArrayList<String>> keyChainTable = null;
String requester = yourToken.getSubject();
//Check if requester exists
if (my_gs.userList.checkUser(requester)) {
ArrayList<String> userGroups = my_gs.userList.getUserGroups(requester);
if (userGroups.size() > 0) {
keyChainTable = new Hashtable<String, ArrayList<String>>();
System.out.println("user group's size is: " + userGroups.size());
for (int i = 0; i < userGroups.size(); i++) {
System.out.println("loop iter: " + i);
// for each of the groups, get its name
String groupName = userGroups.get(i);
// get its full key chains
ArrayList<SecretKey> fullKeyList = null;
if(type.equals("e")) {
fullKeyList = my_gs.keyList.getGroupsKeyEncChain(groupName);
System.out.println("fullkeylist size is: " + fullKeyList.size());
} else {
fullKeyList = my_gs.keyList.getGroupsKeyIntChain(groupName);
System.out.println("fullkeylist size is: " + fullKeyList.size());
}
// get the users start and end blocks
usersStartBlock = my_gs.userList.getUserStartBlock(requester, groupName);
if (!(my_gs.userList.isUserCurrentlyActive(requester, groupName))) {
usersEndBlock = my_gs.userList.getUserEndBlock(requester, groupName);
} else {
usersEndBlock = fullKeyList.size() - 1;
}
// now make the new partialKeyList for what they have access too
ArrayList<String> partialKeyList = new ArrayList<String>();
System.out.println("userEndBlock is: " + usersEndBlock);
System.out.println("userstartBlock is: " + usersStartBlock);
for (int j = 0; j < fullKeyList.size(); j++) {
if (j < usersStartBlock || j > usersEndBlock) {
partialKeyList.add("-1");
} else {
String stringifiedKey = new String(Base64.getEncoder().encode(fullKeyList.get(j).getEncoded()));
System.out.println("stringkey is: " + stringifiedKey);
partialKeyList.add(stringifiedKey);
}
}
// add that partial arraylist into the retun hashtable using the group name as the index
keyChainTable.put(groupName, partialKeyList);
System.out.println("put was successful");
}
return keyChainTable;
}
}
return null;
}
//Method to create a user
private boolean createUser(String username, UserToken yourToken) {
String requester = yourToken.getSubject();
//Check if requester exists
if (my_gs.userList.checkUser(requester)) {
//Get the user's groups
ArrayList<String> temp = my_gs.userList.getUserGroups(requester);
//requester needs to be an administrator
if (temp.contains("ADMIN")) {
//Does user already exist?
if (!my_gs.userList.checkUser(username)) {
my_gs.userList.addUser(username);
// log the server created the user
gLog.write("data", "User \"" + username + "\" was successfully created by " + requester + ".", "");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
//Method to delete a user
private boolean deleteUser(String username, UserToken yourToken) {
String requester = yourToken.getSubject();
//Does requester exist?
if (my_gs.userList.checkUser(requester)) {
ArrayList<String> temp = my_gs.userList.getUserGroups(requester);
//requester needs to be an administer
if (temp.contains("ADMIN")) {
//Does user exist?
if (my_gs.userList.checkUser(username)) {
//User needs deleted from the groups they belong
ArrayList<String> deleteFromGroups = new ArrayList<String>();
//This will produce a hard copy of the list of groups this user belongs
for (int index = 0; index < my_gs.userList.getUserGroups(username).size(); index++) {
deleteFromGroups.add(my_gs.userList.getUserGroups(username).get(index));
}
for (int i = 0; i < deleteFromGroups.size(); i++) {
my_gs.groupList.removeUser(deleteFromGroups.get(i), username);
}
//If groups are owned, they must be deleted
ArrayList<String> deleteOwnedGroup = new ArrayList<String>();
//Make a hard copy of the user's ownership list
for (int index = 0; index < my_gs.userList.getUserOwnership(username).size(); index++) {
deleteOwnedGroup.add(my_gs.userList.getUserOwnership(username).get(index));
}
//Delete owned groups
for (int index = 0; index < deleteOwnedGroup.size(); index++) {
//Use the delete group method. Token must be created for this action
deleteGroup(deleteOwnedGroup.get(index), new Token(my_gs.name, username, deleteOwnedGroup, "-1", "-1", null));
}
//Delete the user from the user list
my_gs.userList.deleteUser(username);
gLog.write("data", "User \"" + username + "\" was successfully deleted by " + requester + ".", "");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
//Method to create a group
private boolean createGroup(String groupToCreate, UserToken yourToken) {
byte[] newHashedToken = computeTokenHash(yourToken.getIssuer(), yourToken.getSubject(), yourToken.getGroups(), yourToken.getIPAddress(), yourToken.getPortNumber());
if (verifySignature(newHashedToken, yourToken.getSignedHash())) {
String requester = yourToken.getSubject();
//Check if requester exists
if (my_gs.userList.checkUser(requester)) {
if (!my_gs.groupList.checkGroup(groupToCreate)) {
// no one is in that group, add requester to group and make them owner
my_gs.userList.addGroup(requester, groupToCreate);
my_gs.userList.addOwnership(requester, groupToCreate);
my_gs.groupList.addGroup(groupToCreate);
my_gs.groupList.addUser(groupToCreate, requester);
my_gs.groupList.addOwnership(groupToCreate, requester);
my_gs.keyList.newGroupKeyChain(groupToCreate);
my_gs.userList.addUserStartBlock(requester, groupToCreate, 0);
// log that the group was created
gLog.write("data", "Group \"" + groupToCreate + "\" was successfully created by " + requester + ".", "");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
//Method to delete a group
private boolean deleteGroup(String groupToDelete, UserToken yourToken) {
String requester = yourToken.getSubject();
//Check if requester exists
if (my_gs.userList.checkUser(requester)) {
// check that they own the group or are an admin in order to delete it
if (my_gs.userList.getUserOwnership(requester).contains(groupToDelete) || my_gs.userList.getUserGroups(requester).contains("ADMIN")) {
// check if group exists
if (my_gs.groupList.checkGroup(groupToDelete)) {
ArrayList<String> allToRemove = my_gs.groupList.getGroupsUsers(groupToDelete);
// make sure the userlist shows that each user in that group is removed
for (int i = 0; i < allToRemove.size(); i++) {
// remove them from the group, will check if it contains if it doesnt wont affect output, refer to UserList.java
my_gs.userList.removeGroup(allToRemove.get(i), groupToDelete);
}
my_gs.groupList.deleteGroup(groupToDelete);
// all users have been removed from the group
// log no more users in group!
gLog.write("data", "Group \"" + groupToDelete + "\" was successfully deleted by " + requester + ".", "");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
//Method to list all of the memebers of a group
private ArrayList<String> listMembersOfGroup(String groupToList, UserToken yourToken) {
String requester = yourToken.getSubject();
// wholelist will either be null or contain list of members
ArrayList<String> daWholeList = null;
// if requester doesnt exist, dont show anything
if (my_gs.userList.checkUser(requester)) {
// they must either own the group or be an admin to see the members
if (my_gs.userList.getUserOwnership(requester).contains(groupToList) || my_gs.userList.getUserGroups(requester).contains("ADMIN")) {
// check if the group exist
if (my_gs.groupList.checkGroup(groupToList)) {
ArrayList<String> daMemberList = new ArrayList<String>();
for (int index = 0; index < my_gs.groupList.getGroupsUsers(groupToList).size(); index++) {
daMemberList.add(my_gs.groupList.getGroupsUsers(groupToList).get(index));
}
System.out.println("User " + yourToken.getSubject() + " listed members of Group:" + groupToList + ". Results:");
for (int i = 0; i < daMemberList.size(); i++) {
System.out.println("User: " + daMemberList.get(i).toString());
}
if (daMemberList.size() != 0) {
// log someone viewed a group's member list
gLog.write("data", "User \"" + requester + "\" requested to view group \"" + groupToList + "\"'s member list.", "");
return daMemberList;
} else {
System.out.println("The group is currently empty.");
return null;
}
} else {
return null;
}
} else {
return null;
}
} else {
return null;
}
}
private boolean addUserToGroup(String username, String groupAddingTo, UserToken yourToken) {
String requester = yourToken.getSubject();
// check that requester is user and the user they want to delete is valid
if (my_gs.userList.checkUser(requester)) {
// either admin or owner of group needed to add a user to the group
if (my_gs.userList.getUserOwnership(requester).contains(groupAddingTo) || my_gs.userList.getUserGroups(requester).contains("ADMIN")) {
// check if user exist
if (my_gs.userList.checkUser(username)) {
// check if the group exist
if (my_gs.groupList.checkGroup(groupAddingTo)) {
// check if that user isnt already in the group
if (!my_gs.groupList.getGroupsUsers(groupAddingTo).contains(username)) {
my_gs.userList.addGroup(username, groupAddingTo);
my_gs.groupList.addUser(groupAddingTo, username);
my_gs.keyList.addKeysToGroup(groupAddingTo);
System.out.println("new key was added!");
int currentBlock = my_gs.keyList.getCurBlockNum(groupAddingTo);
System.out.println("current block num is: " + currentBlock);
my_gs.userList.addUserStartBlock(username, groupAddingTo, currentBlock);
System.out.println("added user start block!");
// log here
gLog.write("data", "User \"" + username + "\" was successfully added to the group \"" + groupAddingTo + "\" by " + requester + ".", "");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private boolean deleteUserFromGroup(String username, String groupDeletingFrom, UserToken yourToken) {
String requester = yourToken.getSubject();
// check that requester is user and the user they want to delete is valid
if (my_gs.userList.checkUser(requester)) {
// either admin or owner of group needed to delete a user from the group
if (my_gs.userList.getUserOwnership(requester).contains(groupDeletingFrom) || my_gs.userList.getUserGroups(requester).contains("ADMIN")) {
// check if the user exist
if (my_gs.userList.checkUser(username)) {
if (my_gs.groupList.checkGroup(groupDeletingFrom)) {
// check if that user is in the group they are being deleted from
if (my_gs.groupList.getGroupsUsers(groupDeletingFrom).contains(username)) {
my_gs.userList.removeGroup(username, groupDeletingFrom);
my_gs.groupList.removeUser(groupDeletingFrom, username);
// check if user was owner of group, if so remove ownership, make admin the owner
if (my_gs.groupList.getGroupOwnership(groupDeletingFrom).equals(username)) {
my_gs.groupList.removeOwnership(username, groupDeletingFrom);
my_gs.groupList.addOwnership(yourToken.getSubject(), groupDeletingFrom);
my_gs.groupList.removeOwnership(groupDeletingFrom, username);
my_gs.groupList.addOwnership(groupDeletingFrom, yourToken.getSubject());
}
// log that the server was successfully ran
gLog.write("data", "User \"" + username + "\" was successfully deleted from the group \"" + groupDeletingFrom + "\" by " + requester + ".", "");
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private void encrypt(Envelope Object, ObjectOutputStream output) {
try {
ByteArrayOutputStream boutput = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream(boutput);
Object.addCounter(counter);
counter++;
oStream.writeObject(Object);
byte[] byteValue = boutput.toByteArray();
oStream.close();
byte[] IV = new byte[16];
sr.nextBytes(IV);
IvParameterSpec spec = new IvParameterSpec(IV);
Cipher aes = Cipher.getInstance("AES/CBC/PKCS7PADDING", new BouncyCastleProvider());
aes.init(Cipher.ENCRYPT_MODE, sessionConfidentialityAESKey, spec);
Envelope temp = new Envelope("Encrypted");
Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
mac.init(sessionIntegrityAESKey);
mac.update(byteValue);
temp.addObject(new String(Base64.getEncoder().encode(IV)));
temp.addBytes1(Base64.getEncoder().encode(mac.doFinal()));//put the HMAC here.
temp.addBytes2(Base64.getEncoder().encode(aes.doFinal(byteValue)));
output.writeObject(temp);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private Object decrypt(ObjectInputStream input) {
try {
Envelope env = (Envelope) input.readObject();
IvParameterSpec spec = new IvParameterSpec(Base64.getDecoder().decode(((String) env.getObjContents().get(0)).getBytes()));
Cipher aes = Cipher.getInstance("AES/CBC/PKCS7PADDING", new BouncyCastleProvider());
aes.init(Cipher.DECRYPT_MODE, sessionConfidentialityAESKey, spec);
byte[] temp = aes.doFinal(Base64.getDecoder().decode(env.getBytes2()));
byte[] passedHMAC = Base64.getDecoder().decode(env.getBytes1());
ByteArrayInputStream in = new ByteArrayInputStream(temp);
ObjectInputStream is = new ObjectInputStream(in);
env = (Envelope) is.readObject();
int counter1 = env.getCounter();
if (counter1 != counter) {
System.out.println("Error: detected tampering in the message received, counter didn't match.");
socket.close();
System.exit(0);
}
counter++;
Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
mac.init(sessionIntegrityAESKey);
//calculate the string to be used to calculate this HMAC, then compare.
mac.update(temp);
byte[] calculatedHMAC = mac.doFinal();
if (!Arrays.equals(passedHMAC, calculatedHMAC)) {
System.out.println("Error: detected tampering in the message received, HMAC didn't match.");
socket.close();
System.exit(0);
}
return env;
} catch (IOException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(GroupClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(GroupClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(GroupClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(GroupClient.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
private boolean verifySignature(byte[] computedHash, byte[] signedHash) {
byte[] returnHash = null;
try {
Security.addProvider(new BouncyCastleProvider());
PemReader daPubPemReader = new PemReader(new InputStreamReader(new FileInputStream("SystemKeys/gs-pubK.pem")));
PemObject daPubPemObj = daPubPemReader.readPemObject();
byte[] publicBytes = daPubPemObj.getContent();
X509EncodedKeySpec pubEncoded = new X509EncodedKeySpec(publicBytes);
KeyFactory daFactory = KeyFactory.getInstance("RSA");
PublicKey pubK = daFactory.generatePublic(pubEncoded);
Signature signature = Signature.getInstance("SHA256withRSA", "BC");
signature.initVerify(pubK);
signature.update(computedHash);
if (signature.verify(signedHash)) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
private byte[] computeTokenHash(String server, String username, List<String> groups, String ipFound, String portFound) {
try {
byte[] hashedToken = null;
ArrayList<String> userGroups = (ArrayList<String>) groups;
Collections.sort(userGroups);
String toBeHashed = server + "\0" + username + "\0" + ipFound + "\0" + portFound + "\0";
for (int i = 0; i < userGroups.size(); i++) {
toBeHashed = toBeHashed + userGroups.get(i) + "\0";
}
MessageDigest theDigester = MessageDigest.getInstance("SHA-256");
theDigester.update(toBeHashed.getBytes());
hashedToken = theDigester.digest();
return hashedToken;
} catch (Exception e) {
return null;
}
}
}
| 57.813025 | 204 | 0.509194 |
b920b6c009c2aaa808795e9eefb2a61cb2bd6666 | 1,571 | package seedu.address.logic.parser;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG_NAME;
import java.util.List;
import seedu.address.logic.commands.FilterCommand;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.pdf.TagContainsKeywordsPredicate;
/**
* Parses input arguments and creates a new FilterCommand object.
* Filter command is actually a modified version of find command,
* albeit using tag as the find 'keyword'.
*/
public class FilterCommandParser implements Parser<FilterCommand> {
/**
* Parses the given {@code String} of arguments in the context of the FilterCommand
* and returns an FilterCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public FilterCommand parse(String args) throws ParseException {
requireNonNull(args);
String trimmedArgs = args.trim();
ArgumentMultimap argMultiMap = ArgumentTokenizer.tokenize(args, PREFIX_TAG_NAME);
if (trimmedArgs.isEmpty() || argMultiMap.getAllValues(PREFIX_TAG_NAME).isEmpty()) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, FilterCommand.MESSAGE_USAGE));
}
List<String> tagKeywords = argMultiMap.getAllValues(PREFIX_TAG_NAME);
return new FilterCommand(new TagContainsKeywordsPredicate(tagKeywords));
}
}
| 38.317073 | 96 | 0.754297 |
f80482b157de6dcc8b8f8ca3d80137f7c5d19d3e | 2,869 | package admob.plugin;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.RequestConfiguration;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import admob.plugin.ads.AdBase;
public class ExecuteContext {
public final AdMob plugin;
public final String actionKey;
public final JSONArray args;
public final CallbackContext callbackContext;
public final JSONObject opts;
ExecuteContext(AdMob plugin, String actionKey, JSONArray args, CallbackContext callbackContext) {
this.plugin = plugin;
this.actionKey = actionKey;
this.args = args;
this.callbackContext = callbackContext;
this.opts = args.optJSONObject(0);
}
public int optId() {
return opts.optInt("id");
}
public String optPosition() {
return opts.optString("position");
}
@Nullable
public AdBase getAd() {
return AdBase.getAd(optId());
}
@Nullable
public String getAdUnitID() {
return this.opts.optString("adUnitId");
}
public RequestConfiguration getRequestConfiguration() {
RequestConfiguration.Builder builder = new RequestConfiguration.Builder();
if (this.opts.has("maxAdContentRating")) {
builder.setMaxAdContentRating(this.opts.optString("maxAdContentRating"));
}
if (this.opts.has("tagForChildDirectedTreatment")) {
builder.setTagForChildDirectedTreatment(this.opts.optInt("tagForChildDirectedTreatment"));
}
if (this.opts.has("tagForUnderAgeOfConsent")) {
builder.setTagForUnderAgeOfConsent(this.opts.optInt("tagForUnderAgeOfConsent"));
}
if (this.opts.has("testDeviceIds")) {
List<String> testDeviceIds = new ArrayList<String>();
JSONArray ids = this.opts.optJSONArray("testDeviceIds");
for (int i = 0; i < ids.length(); i++) {
String testDeviceId = ids.optString(i);
if (testDeviceId != null) {
testDeviceIds.add(testDeviceId);
}
}
builder.setTestDeviceIds(testDeviceIds);
}
return builder.build();
}
public AdRequest buildAdRequest() {
Bundle extras = new Bundle();
AdRequest.Builder builder = new AdRequest.Builder();
if (this.opts.has("npa")) {
extras.putString("npa", opts.optString("npa"));
}
return builder.addNetworkExtrasBundle(AdMobAdapter.class, extras).build();
}
public Activity getActivity() {
return plugin.cordova.getActivity();
}
}
| 31.184783 | 102 | 0.653886 |
582f211dd18b453875fbd6a8e1c7678a357646cf | 704 | package jasonftw.CustomDifficulty.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import jasonftw.CustomDifficulty.hooks.Permissions;
import jasonftw.CustomDifficulty.util.Manager;
public abstract class Reload {
public static void onCommand(CommandSender commandSender, String[] args) {
if (!Permissions.has(commandSender, "CustomDifficulty.reload")) {
commandSender.sendMessage(Permissions.noPermission);
return;
}
Manager.reload();
if (commandSender instanceof Player) {
commandSender.sendMessage((Object)ChatColor.GREEN + "Reloading done.");
}
}
}
| 30.608696 | 83 | 0.714489 |
08847119266e19ba69057b71ba5b7628654b8b36 | 564 | package fun.epoch.learn.design.pattern.structural.facade;
public class Test {
public static void main(String[] args) {
PointsGift pointsGift = new PointsGift("《Java 从入门到放弃》");
System.out.println("使用积分兑换礼物:" + pointsGift.getName());
String shippingOrderNo = "";
// 使用外观模式简化一系列子系统的调用 (外部程序无需深入了解各个子系统是如何协调工作的)
GiftExchangeService giftExchangeService = new GiftExchangeService();
shippingOrderNo = giftExchangeService.exchangeGift(pointsGift);
System.out.println("礼物的物流订单号:" + shippingOrderNo);
}
}
| 33.176471 | 76 | 0.698582 |
524d73720757b6085691256cea7b8a3a817ac2df | 1,943 | package fr.inra.urgi.datadiscovery.pillar;
import java.util.List;
import java.util.Objects;
import fr.inra.urgi.datadiscovery.util.Utils;
/**
* A pillar, with its list of database sources
* @author JB Nizet
*/
public final class PillarDTO {
/**
* The name of the pillar
*/
private final String name;
/**
* The database sources of this pillar
*/
private final List<DatabaseSourceDTO> databaseSources;
public PillarDTO(String name, List<DatabaseSourceDTO> databaseSources) {
this.name = name;
this.databaseSources = Utils.nullSafeUnmodifiableCopy(databaseSources);
}
public String getName() {
return name;
}
public List<DatabaseSourceDTO> getDatabaseSources() {
return databaseSources;
}
/**
* Returns the number of documents in this pillar. We could use the docCount retrieved by Elasticsearch,
* but since these counts are approximate, just summing the counts from database resources avoids
* wondering why the sum of the database sources document count is not equal to the pillar document count.
*/
public long getDocumentCount() {
return this.databaseSources.stream().mapToLong(DatabaseSourceDTO::getDocumentCount).sum();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PillarDTO pillarDTO = (PillarDTO) o;
return Objects.equals(name, pillarDTO.name) &&
Objects.equals(databaseSources, pillarDTO.databaseSources);
}
@Override
public int hashCode() {
return Objects.hash(name, databaseSources);
}
@Override
public String toString() {
return "PillarDTO{" +
"name='" + name + '\'' +
", databaseSources=" + databaseSources +
'}';
}
}
| 27.366197 | 110 | 0.633042 |
761ef5d03b40a1756aa18bf38b275f7fbe9a1500 | 401 | package filemanager.harshapp.hm.fileexplorer.directory;
import filemanager.harshapp.hm.fileexplorer.directory.DocumentsAdapter.Environment;
public class AvMessageFooter extends Footer {
public AvMessageFooter(Environment environment, int itemViewType, int icon, String message) {
super(itemViewType);
mIcon = icon;
mMessage = message;
mEnv = environment;
}
} | 30.846154 | 97 | 0.740648 |
36b6a093ecb6935e47dd09778d430ea6a752791f | 1,482 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.wildfly.security.util;
import java.security.SecureRandom;
public class PasswordUtil {
private static final SecureRandom RANDOM = new SecureRandom();
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
/**
* Generate a random string of given size.
*
* @param stringSize the size of the string
* @return a random string
*/
public static String generateSecureRandomString(int stringSize) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < stringSize; i++) {
int index = (int) (RANDOM.nextDouble() * CHARS.length());
builder.append(CHARS, index, index + 1);
}
return builder.toString();
}
} | 36.146341 | 105 | 0.695682 |
a0f488eeb3d401844f2fefc13ba6dd710ef79f2e | 916 | package learnings.sriram.enums;
/**
* Enum representing a Month of a calendar year.
* @author tansr02
*
*/
public enum Month implements Comparable<Month>{
FEB(28, "February"), MAR(31, "March"), APR(30, "April"), MAY(31, "May"), JUN(30, "June"), JAN(31, "January"),
JUL(31, "July"), AUG(31, "August"), SEP(30, "September"), OCT(31, "October"), NOV(30, "November"), DEC(31, "December");
int days;
String name;
// default constructor
Month(){}
// constructor with days as input
Month(int days, String name){ this.days = days; this.name = name; }
public int getDays() { return days; }
public String getName() { return name; }
@Override
public String toString() { return String.join("-", name, ""+days); }
public boolean has30Days() { return days == 30; }
public boolean has31Days() { return days == 31; }
public boolean hasMorethanOrEqualTo30Days() { return days >= 30; }
}
| 23.487179 | 120 | 0.643013 |
4a0c3db9bf0f5823d48fb49181dc235ac46fc6a7 | 4,450 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.actions;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.impl.RunDialog;
import com.intellij.execution.impl.RunManagerImpl;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.ApplicationManager;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class CreateAction extends BaseRunConfigurationAction {
public CreateAction() {
super(ExecutionBundle.lazyMessage("create.run.configuration.action.name"), Presentation.NULL_STRING, null);
}
@Override
protected void perform(final ConfigurationContext context) {
choosePolicy(context).perform(context);
}
@Override
protected void updatePresentation(final Presentation presentation, @NotNull final String actionText, final ConfigurationContext context) {
choosePolicy(context).update(presentation, context, actionText);
}
private static BaseCreatePolicy choosePolicy(final ConfigurationContext context) {
final RunnerAndConfigurationSettings configuration = context.findExisting();
return configuration == null ? Holder.CREATE_AND_EDIT : Holder.EDIT;
}
private static abstract class BaseCreatePolicy {
public void update(final Presentation presentation, final ConfigurationContext context, @NotNull final String actionText) {
updateText(presentation, actionText);
updateIcon(presentation, context);
}
protected void updateIcon(final Presentation presentation, final ConfigurationContext context) {
final List<ConfigurationFromContext> fromContext = context.getConfigurationsFromContext();
if (fromContext != null && fromContext.size() == 1) {
//hide fuzzy icon when multiple run configurations are possible
presentation.setIcon(fromContext.iterator().next().getConfiguration().getIcon());
}
}
protected abstract void updateText(final Presentation presentation, final String actionText);
public abstract void perform(ConfigurationContext context);
}
private static class CreateAndEditPolicy extends BaseCreatePolicy {
@Override
protected void updateText(final Presentation presentation, final String actionText) {
presentation.setText(actionText.length() > 0 ? ExecutionBundle.message("create.run.configuration.for.item.action.name", actionText) + "..."
: ExecutionBundle.message("create.run.configuration.action.name"), false);
}
@Override
public void perform(final ConfigurationContext context) {
final RunnerAndConfigurationSettings configuration = context.getConfiguration();
if (ApplicationManager.getApplication().isUnitTestMode() ||
RunDialog.editConfiguration(context.getProject(), configuration,
ExecutionBundle.message("create.run.configuration.for.item.dialog.title", configuration.getName()))) {
final RunManagerImpl runManager = (RunManagerImpl)context.getRunManager();
runManager.addConfiguration(configuration);
runManager.setSelectedConfiguration(configuration);
}
}
}
private static class EditPolicy extends CreateAndEditPolicy {
@Override
protected void updateText(final Presentation presentation, final String actionText) {
presentation.setText(actionText.length() > 0 ? ExecutionBundle.message("edit.run.configuration.for.item.action.name", actionText) + "..."
: ExecutionBundle.message("edit.run.configuration.action.name"), false);
}
@Override
public void perform(final ConfigurationContext context) {
final RunnerAndConfigurationSettings configuration = context.getConfiguration();
if (!ApplicationManager.getApplication().isUnitTestMode()) {
RunDialog.editConfiguration(context.getProject(), configuration,
ExecutionBundle.message("edit.run.configuration.for.item.dialog.title", configuration.getName()));
}
}
}
private static class Holder {
private static final BaseCreatePolicy CREATE_AND_EDIT = new CreateAndEditPolicy();
private static final BaseCreatePolicy EDIT = new EditPolicy();
}
}
| 46.354167 | 145 | 0.739326 |
c4d82b49e96445b7c25286b3966cfec2a3e42a7f | 2,519 | /*
This file is part of AvatarMod.
AvatarMod 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.
AvatarMod 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 AvatarMod. If not, see <http://www.gnu.org/licenses/>.
*/
package com.crowsofwar.avatar.common.bending.air;
import com.crowsofwar.avatar.common.bending.Ability;
import com.crowsofwar.avatar.common.bending.BendingAi;
import com.crowsofwar.avatar.common.data.Bender;
import com.crowsofwar.avatar.common.data.ctx.AbilityContext;
import com.crowsofwar.avatar.common.entity.EntityAirGust;
import com.crowsofwar.gorecore.util.Vector;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.world.World;
import static com.crowsofwar.avatar.common.config.ConfigStats.STATS_CONFIG;
import static com.crowsofwar.avatar.common.data.AbilityData.AbilityTreePath.FIRST;
import static com.crowsofwar.avatar.common.data.AbilityData.AbilityTreePath.SECOND;
/**
* @author CrowsOfWar
*/
public class AbilityAirGust extends Ability {
public AbilityAirGust() {
super(Airbending.ID, "air_gust");
}
@Override
public void execute(AbilityContext ctx) {
EntityLivingBase entity = ctx.getBenderEntity();
Bender bender = ctx.getBender();
World world = ctx.getWorld();
if (!bender.consumeChi(STATS_CONFIG.chiAirGust)) return;
Vector look = Vector.toRectangular(Math.toRadians(entity.rotationYaw),
Math.toRadians(entity.rotationPitch));
Vector pos = Vector.getEyePos(entity);
EntityAirGust gust = new EntityAirGust(world);
gust.setVelocity(look.times(25));
gust.setPosition(pos.x(), pos.y(), pos.z());
gust.setOwner(entity);
gust.setDestroyProjectiles(ctx.isMasterLevel(FIRST));
gust.setAirGrab(ctx.isMasterLevel(SECOND));
System.out.println("PR : " + ctx.getPowerRating());
world.spawnEntity(gust);
}
@Override
public int getCooldown(AbilityContext ctx) {
return ctx.getLevel() >= 1 ? 30 : 60;
}
@Override
public BendingAi getAi(EntityLiving entity, Bender bender) {
return new AiAirGust(this, entity, bender);
}
}
| 31.886076 | 83 | 0.767368 |
959b7c561288692721f7002ae4732b258bf40fde | 7,771 | /*
* #!
* Ontopia Rest
* #-
* Copyright (C) 2001 - 2017 The Ontopia 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 net.ontopia.topicmaps.rest.v1.role;
import net.ontopia.infoset.impl.basic.URILocator;
import net.ontopia.topicmaps.rest.exceptions.OntopiaRestErrors;
import net.ontopia.topicmaps.rest.model.Association;
import net.ontopia.topicmaps.rest.model.AssociationRole;
import net.ontopia.topicmaps.rest.model.Topic;
import net.ontopia.topicmaps.rest.v1.AbstractV1ResourceTest;
import org.junit.Assert;
import org.junit.Test;
public class AssociationRoleResourcePUTTest extends AbstractV1ResourceTest {
public AssociationRoleResourcePUTTest() {
super(ROLES_LTM, "roles");
}
/* -- Successfull requests -- */
private AssociationRole createAssociationRole() {
AssociationRole role = new AssociationRole();
role.setAssociation(new Association("2"));
role.setPlayer(new Topic("1"));
role.setType(new Topic("4"));
return role;
}
@Test
public void testPUT() {
AssociationRole added = put(createAssociationRole(), AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getObjectId());
Assert.assertNotNull(added.getPlayer());
Assert.assertEquals("1", added.getPlayer().getObjectId());
Assert.assertNotNull(added.getType());
Assert.assertEquals("4", added.getType().getObjectId());
Assert.assertNotNull(added.getAssociation());
Assert.assertEquals("2", added.getAssociation().getObjectId());
}
@Test
public void testWithPlayerByItemIdentifier() {
AssociationRole role = createAssociationRole();
Topic topic = new Topic();
topic.getItemIdentifiers().add(URILocator.create("foo:#topic1"));
role.setPlayer(topic);
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getObjectId());
Assert.assertNotNull(added.getPlayer());
Assert.assertEquals("1", added.getPlayer().getObjectId());
}
@Test
public void testWithTypeByItemIdentifier() {
AssociationRole role = createAssociationRole();
Topic topic = new Topic();
topic.getItemIdentifiers().add(URILocator.create("foo:#topic2"));
role.setType(topic);
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getObjectId());
Assert.assertNotNull(added.getType());
Assert.assertEquals("4", added.getType().getObjectId());
}
@Test
public void testWithItemIdentifier() {
AssociationRole role = createAssociationRole();
role.getItemIdentifiers().add(URILocator.create("foo:bar30"));
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getItemIdentifiers());
Assert.assertFalse(added.getItemIdentifiers().isEmpty());
Assert.assertEquals("foo:bar30", added.getItemIdentifiers().iterator().next().getAddress());
}
@Test
public void testWithItemIdentifiers() {
AssociationRole role = createAssociationRole();
role.getItemIdentifiers().add(URILocator.create("bar:foo31"));
role.getItemIdentifiers().add(URILocator.create("bar:bar32"));
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getItemIdentifiers());
Assert.assertFalse(added.getItemIdentifiers().isEmpty());
Assert.assertEquals(2, added.getItemIdentifiers().size());
Assert.assertTrue(added.getItemIdentifiers().contains(URILocator.create("bar:foo31")));
Assert.assertTrue(added.getItemIdentifiers().contains(URILocator.create("bar:bar32")));
}
@Test
public void testWithEmptyIdentifiers() {
AssociationRole role = createAssociationRole();
role.getItemIdentifiers().clear();
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getItemIdentifiers());
Assert.assertTrue(added.getItemIdentifiers().isEmpty());
}
@Test
public void testWithReification() {
AssociationRole role = createAssociationRole();
role.setReifier(new Topic("1"));
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getReifier());
Assert.assertEquals("1", added.getReifier().getObjectId());
}
@Test
public void testWithReificationByItemIdentifier() {
AssociationRole role = createAssociationRole();
Topic topic = new Topic();
topic.getItemIdentifiers().add(URILocator.create("foo:#topic1"));
role.setReifier(topic);
AssociationRole added = put(role, AssociationRole.class);
Assert.assertNotNull(added);
Assert.assertNotNull(added.getReifier());
Assert.assertEquals("1", added.getReifier().getObjectId());
}
/* -- Failing requests -- */
@Test
public void testEmptyBody() {
assertPutFails(null, OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
@Test
public void testWrongObjectType() {
assertPutFails(new Topic("foobar"), OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
@Test
public void testMissingAssociation() {
AssociationRole role = createAssociationRole();
role.setAssociation(null);
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
@Test
public void testInvalidAssociation() {
AssociationRole role = createAssociationRole();
role.setAssociation(new Association("1"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_WRONG_TYPE);
}
@Test
public void testUnexistingAssociation() {
AssociationRole role = createAssociationRole();
role.setAssociation(new Association("unexisting_association_id"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
@Test
public void testMissingPlayer() {
AssociationRole role = createAssociationRole();
role.setPlayer(null);
assertPutFails(role, OntopiaRestErrors.MANDATORY_FIELD_IS_NULL);
}
@Test
public void testInvalidPlayer() {
AssociationRole role = createAssociationRole();
role.setPlayer(new Topic("2"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_WRONG_TYPE);
}
@Test
public void testUnexistingPlayer() {
AssociationRole role = createAssociationRole();
role.setPlayer(new Topic("unexisting_topic_id"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
@Test
public void testMissingType() {
AssociationRole role = createAssociationRole();
role.setType(null);
assertPutFails(role, OntopiaRestErrors.MANDATORY_FIELD_IS_NULL);
}
@Test
public void testInvalidType() {
AssociationRole role = createAssociationRole();
role.setType(new Topic("2"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_WRONG_TYPE);
}
@Test
public void testUnexistingType() {
AssociationRole role = createAssociationRole();
role.setType(new Topic("unexisting_topic_id"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
@Test
public void testInvalidReification() {
AssociationRole role = createAssociationRole();
role.setReifier(new Topic("2"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_WRONG_TYPE);
}
@Test
public void testUnexistingReification() {
AssociationRole role = createAssociationRole();
role.setReifier(new Topic("unexisting_topic_id"));
assertPutFails(role, OntopiaRestErrors.MANDATORY_OBJECT_IS_NULL);
}
}
| 32.244813 | 94 | 0.76438 |
9f7c6748ba5911a2e991ca715ecadb171ce9fee3 | 4,687 | package com.akhh.aungkhanthtoo.androidforall;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.akhh.aungkhanthtoo.androidforall.data.Vocab;
import com.squareup.picasso.Picasso;
import java.util.List;
import java.util.Random;
/**
* Created by Lenovo on 1/27/2018.
*/
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
private Context mContext;
private static final String TAG = "MyListAdapter";
static final String EXTRA_COLOR_HEX= "MyListAdapter.EXTRA_COLOR_ID";
static final String EXTRA_TITLE = "MyListAdapter.EXTRA_TITLE";
static final String EXTRA_DESCRIPTION = "MyListAdapter.EXTRA_DESCRIPTION";
static final String EXTRA_SAMPLE = "MyListAdapter.EXTRA_SAMPLE";
static final String EXTRA_IMAGES = "MyListAdapter.EXTRA_IMAGES";
static final String EXTRA_ID = "MyListAdapter.EXTRA_ID";
private List<Vocab> mList;
MyListAdapter(List<Vocab> mList, Context context) {
this.mList = mList;
mContext = context;
}
@Override
public MyListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(view, mContext);
}
@Override
public void onBindViewHolder(final MyListAdapter.MyViewHolder holder, final int position) {
final Vocab current = mList.get(position);
holder.mTextView.setText(current.getTitle());
Picasso.with(mContext)
.load(DetailActivity.BASE_URL + current.getThumb() )
.noFade()
.into(holder.mImageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: holder.getAdapterPosition() " + holder.getAdapterPosition());
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra(EXTRA_COLOR_HEX, current.getColor());
intent.putExtra(EXTRA_IMAGES, current.getImages());
intent.putExtra(EXTRA_DESCRIPTION, current.getDescription());
intent.putExtra(EXTRA_SAMPLE, current.getSample());
intent.putExtra(EXTRA_TITLE, current.getTitle());
intent.putExtra(EXTRA_ID, String.valueOf(holder.getAdapterPosition()+1));
ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(((Activity) mContext),
new Pair<View, String>(holder.mTextView, DetailActivity.VIEW_NAME_HEADER_TITLE),
new Pair<View, String>(holder.mImageView, DetailActivity.VIEW_NAME_IMAGE));
mContext.startActivity(intent, activityOptions.toBundle());
}
});
}
/**
* Returns the total number of items in the data set held by the mAdapter.
*
* @return The total number of items in this mAdapter.
*/
@Override
public int getItemCount() {
return mList.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
private ImageView mImageView;
Typeface mTypeface;
MyViewHolder(View itemView, Context context) {
super(itemView);
mTextView = itemView.findViewById(R.id.textView_list_title);
mImageView = itemView.findViewById(R.id.list_image);
mTypeface = Typeface.createFromAsset(context.getAssets(), "roboto_black.ttf");
mTextView.setTypeface(mTypeface);
}
}
private int getIntInRange(int max, int min) {
Random random = new Random();
return random.nextInt(max + min + 1) + min;
}
private int getRandomHSVColor() {
// Generate a random hue value between 0 and 360
int hue = new Random().nextInt(361);
// Make the color depth full
float saturation = 1.0f;
// Make a full bright color
float value = 1.0f;
// Avoid the transparency
int alpha = 255;
//Finally generate the color
return Color.HSVToColor(alpha, new float[]{hue, saturation, value});
}
}
| 36.053846 | 129 | 0.676979 |
ae0d27203f82130dbfb47ed92e78c6b3766c26d8 | 1,974 | package foodev.jsondiff.jsonwrap.jackson2;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import foodev.jsondiff.jsonwrap.JzonArray;
import foodev.jsondiff.jsonwrap.JzonElement;
import foodev.jsondiff.jsonwrap.JzonObject;
import foodev.jsondiff.jsonwrap.Wrapper;
import java.io.IOException;
public class Jackson2Wrapper implements Wrapper {
private final static ObjectMapper JSON = new ObjectMapper();
public static JzonElement wrap(JsonNode el) {
if (el == null || el.isNull()) {
return Jackson2JsonNull.INSTANCE;
} else if (el.isArray()) {
return new Jackson2JsonArray((ArrayNode) el);
} else if (el.isObject()) {
return new Jackson2JsonObject((ObjectNode) el);
} else if (el.isValueNode()) {
return new Jackson2JsonPrimitive((ValueNode) el);
} else {
throw new IllegalStateException();
}
}
@Override
public JzonElement parse(String json) {
try {
JsonParser parser = JSON.getJsonFactory().createJsonParser(json);
parser.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
parser.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
return wrap(parser.readValueAsTree());
} catch (JsonProcessingException e) {
throw new Jackson2WrapperException("Failed to parse JSON", e);
} catch (IOException e) {
throw new Jackson2WrapperException("IOException parsing a String?", e);
}
}
@Override
public JzonElement wrap(Object o) {
return wrap((JsonNode) o);
}
@Override
public JzonObject createJsonObject() {
return (JzonObject) wrap(JSON.createObjectNode());
}
@Override
public JzonArray createJsonArray() {
return (JzonArray) wrap(JSON.createArrayNode());
}
}
| 30.369231 | 74 | 0.764944 |
1bd0aa4849d4cdad8234d7ba30e9c9c00276a41c | 878 | // 전화번호부 클래스 필드
public class PhoneInfo {
// 필드
String name; // 이름
int age; // 나이
String phoneNum; // 전화번호
String email; // 이메일
int group; // 그룹
// 생성자
public PhoneInfo(String name, int age, String phoneNum, String email, int group) {
this.name = name;
this.age = age;
this.phoneNum = phoneNum;
this.email = email;
this.group = group;
}
// 메소드
public void showPhoneInfo() {
System.out.println("이름: " + name);
System.out.println("나이: " + age);
System.out.println("전화번호: " + phoneNum);
System.out.println("이메일: " + email);
switch(group) {
case 1:
System.out.println("그룹: 가족");
case 2:
System.out.println("그룹: 친구");
case 3:
System.out.println("그룹: 동료");
}
}
}
| 25.085714 | 86 | 0.498861 |
b756afd9f8dce4151fce49c127e9abd1035c7d52 | 1,374 | public class QuickSort {
private long count;
private long exchange;
protected String fileName;
public void resetCount() {
count = 0;
exchange = 0;
}
public void sort(int[] input,int beginning,int end) {
int index;
increaseCount();
if (beginning>end){
return;
}
index=partition(input,beginning,end);
sort(input,beginning,index-1);
sort(input,index+1,end);
}
private int partition(int[] input, int beginning, int end) {
int pivot = input[beginning];
int i = beginning;
int j=end;
while(i<j){
while (input[i]<pivot){
i++;
}
while (input[j]>pivot){
j--;
}
if (i < j){
if(input[i] == input[j]){
i++;
}
swap(input,i,j);
}
increaseCount();
}
// swap(input,beginning,j);
return j;
}
private void increaseCount() {
count++;
}
private void swap(int[] list, int i, int j) {
int temp = list[i];
list[i] = list[j];
list[j] = temp;
increaseCount();
}
public long getCount() {
count = count + exchange;
exchange = 0;
return count;
}
} | 22.16129 | 64 | 0.453421 |
675427eb53f40ecce2670f989183620934a2ce09 | 2,857 | package org.fourbit.stuffeverywhere.model;
public class StuffTag {
CharSequence mLabel;
CharSequence mValue;
private StuffTag(CharSequence label, CharSequence value) {
// FIXME java.lang.NoClassDefFoundError: android.test.MoreAsserts on device!?
// MoreAsserts.assertNotEqual(label.toString(), "#");
// Assert.assertEquals(label.toString(), label.toString().trim());
// Assert.assertEquals(value.toString(), value.toString().trim());
// MoreAsserts.assertNotContainsRegex("\\s+", label.toString());
mLabel = label;
mValue = value;
}
public static StuffTag fromText(CharSequence rawInput) throws MalformedStuffTagException {
return fromText(rawInput, '#');
}
/**
* Creates a tag with first occurrence of splitter treated as tag/value separator. Malformed
* input fails with {@link MalformedStuffTagException}.
*
* @param rawInput
* @return the tag
* @throws MalformedStuffTagException occurs when rawInput:<br>
* <li>splitter is the first char in rawInput</li><br>
* <li>tag or value are trimable</li><br>
* <li>tag is empty</li><br>
* <li>tag contains whitespaces</li><br>
*/
public static StuffTag fromText(CharSequence rawInput, char splitter) throws MalformedStuffTagException {
// split into label and value
CharSequence label = "", value = "";
int firstSplit = rawInput.toString().indexOf(splitter);
if (firstSplit == 0)
throw new MalformedStuffTagException("" + splitter + " is not allowed as beginning of a tag");
if (firstSplit < 0) {
label = rawInput;
} else {
label = rawInput.subSequence(0, firstSplit);
value = rawInput.subSequence(firstSplit + 1, rawInput.length());
}
if (!label.toString().equals(label.toString().trim()))
throw new MalformedStuffTagException("The tag is not allowed to be trimable");
if (!value.toString().equals(value.toString().trim()))
throw new MalformedStuffTagException("The value is not allowed to be trimable");
if ("".equals(label))
throw new MalformedStuffTagException("The tag is not allowed to be empty");
if (java.util.regex.Pattern.matches("\\s+", label))
throw new MalformedStuffTagException("The tag is not allowed to have whitespaces");
// COMMENT for the reason of visually separating tags
// TODO normalize UTF before storing and exchanging
// label = Normalizer.normalize(rawInput, Normalizer.Form.NFC);
return new StuffTag(label, value);
}
@Override
public String toString() {
return "" + mLabel + (!mValue.equals("") ? "#" + mValue : "");
}
} | 40.239437 | 109 | 0.628281 |
e8123b449911a9eeaa15f7fdaef0c68a3b50360b | 1,846 | package com.rationaleemotions.pojo;
import com.jcraft.jsch.UserInfo;
/**
* Represents a user for whom it's assumed that passwordless setup has already been completed.
* Passwordless setup refers to the process wherein a user is allowed login to a remote host via ssh
* without being prompted for their password.
* The setup is fairly simple. Please refer <a href='http://www.linuxproblem.org/art_9.html'>here</a> for more details
* on how to setup passwordless access
* to a remote host.
*/
public class InteractiveUser implements UserInfo {
private String passphrase;
private String password;
private InteractiveUser() {
//We have factory methods. Defeat instantiation
}
private void setPassphrase(String passphrase) {
this.passphrase = passphrase;
}
private void setPassword(String password) {
this.password = password;
}
@Override
public String getPassphrase() {
return passphrase;
}
@Override
public String getPassword() {
return password;
}
@Override
public boolean promptPassword(String message) {
return password != null;
}
@Override
public boolean promptPassphrase(String message) {
return passphrase != null;
}
@Override
public boolean promptYesNo(String message) {
return false;
}
@Override
public void showMessage(String message) {
//No Op implementation
}
public static UserInfo createPasswordlessUser(String passphrase) {
InteractiveUser user = new InteractiveUser();
user.setPassphrase(passphrase);
return user;
}
public static UserInfo createPasswordDrivenUser(String password) {
InteractiveUser user = new InteractiveUser();
user.setPassword(password);
return user;
}
}
| 26 | 118 | 0.68039 |
04e14d27af02c0a093ba35bd15e5ebb6d73686d2 | 530 | package com.kenshine.nutz.utils;
import org.apache.shiro.crypto.hash.SimpleHash;
/**
* @Author kenshine
*/
public class PasswordUtils {
private PasswordUtils(){}
/**
*
* @param salt 盐
* @param password 明文密码
* @return String 加密后的数据
*/
public static String getPassword(String salt,String password){
//加密类型
String hashAlgorithmName = "md5";
//迭代次数
int iteration = 2;
return new SimpleHash(hashAlgorithmName,password,salt,iteration).toHex();
}
}
| 19.62963 | 81 | 0.626415 |
34d3f511188f20ca7d60bb0bb59497558b9a8b52 | 109 | package org.synyx.urlaubsverwaltung.absence;
public enum AbsenceMappingType {
VACATION,
SICKNOTE
}
| 13.625 | 44 | 0.761468 |
00a857afe0017ec0281e30d3ae03bb93a56ce58f | 9,833 | package binarytreedemo;
import java.util.*;
/** program to demonstrate implementation of a traditional binary search tree **/
public class BinaryTreeDemo {
public static void main(String[] args) {
// Declare new binary search tree.
BinarySearchTree myTree = new BinarySearchTree();
myTree.rootNode = new Node(10);
for (int i = 1; i < 20; i++)
{
if (i != 10)
{
myTree.addNode(myTree.rootNode, new Node(i));
}
}
// Traverse tree.
System.out.print("\nIn-order traversal example:\n\n");
myTree.traverse(myTree.rootNode, "in-order");
System.out.print("\nPost-order traversal example:\n\n");
myTree.traverse(myTree.rootNode, "post-order");
System.out.print("\nPre-order traversal example:\n\n");
myTree.traverse(myTree.rootNode, "pre-order");
// Remove an element from the tree.
System.out.print("\nNode with value 5 removed from the tree.\n\n");
myTree.removeNode(myTree.rootNode, new Node(5));
// Traverse tree.
System.out.print("\nBreadth first tree traversal example:\n\n");
myTree.traverse(myTree.rootNode, "breadth-first");
System.out.print("\nDepth first tree traversal example:\n\n");
myTree.traverse(myTree.rootNode, "depth-first");
// Search the tree.
boolean valueLocated = ((myTree.search(myTree.rootNode, new Node(10)).value) != -1);
System.out.print("\nDoes the tree contain a 17? " + valueLocated + ".\n\n");
// Is the tree empty?
System.out.print("Is the tree empty? " + myTree.isEmpty() + ".\n\n");
// How many nodes inside the tree?
System.out.print("How many nodes are in the tree? " + myTree.nodeCount() + ".\n\n");
// What's the sum of all Node data in the tree?
System.out.print("What is the sum of all node data in the tree? " + myTree.sum() + ".\n\n");
}
}
/** binary search tree data structure **/
class BinarySearchTree
{
/** node at the top of the tree **/
Node rootNode;
/** determine if the tree contains any nodes **/
public boolean isEmpty()
{
return (rootNode == null);
}
/** add a new node to the tree **/
public void addNode(Node root, Node newNode)
{
if (isEmpty())
{
rootNode = newNode;
}
else
{
if (newNode.value > root.value)
{
if (root.right == null)
{
root.right = newNode;
}
else
{
addNode(root.right, newNode);
}
}
if (newNode.value < root.value)
{
if (root.left == null)
{
root.left = newNode;
}
else
{
addNode(root.left, newNode);
}
}
if (newNode.value == root.value)
{
System.out.print("\n\nThe tree already contains the value that you wish to add.\n\n");
}
}
}
/** remove a specific node from the tree **/
/** method uses a binary search (of course) to locate the element **/
public void removeNode(Node root, Node removeMe)
{
if (isEmpty())
{
System.out.print("\n\nElements cannot be removed because the tree is empty.\n\n");
}
else
{
if (removeMe.value == root.value)
{
if (removeMe.left == null & removeMe.right == null)
{
}
else if (removeMe.left == null)
{
}
else if (removeMe.right == null)
{
}
else if (removeMe.right != null && removeMe.left != null)
{
}
}
if (removeMe.value > root.value && root.right != null)
{
removeNode(root.right, removeMe);
}
if (removeMe.value < root.value && root.left != null)
{
removeNode(root.left, removeMe);
}
}
}
/** traverse the tree and print node data **/
public void traverse(Node root, String order)
{
if (order.equals("in-order"))
{
if (root != null)
{
traverse(root.left, "in-order");
System.out.print(root.value + "\n");
traverse(root.right, "in-order");
}
}
else if (order.equals("post-order"))
{
if (root != null)
{
traverse(root.right, "post-order");
traverse(root.left, "post-order");
System.out.print(root.value + "\n");
}
}
else if (order.equals("pre-order"))
{
if (root != null)
{
System.out.print(root.value + "\n");
traverse(root.left, "pre-order");
traverse(root.right, "pre-order");
}
}
else if (order.equals("depth-first"))
{
Stack<Node> nodeStack = new Stack<>();
nodeStack.add(rootNode);
while (!nodeStack.isEmpty())
{
Node current = nodeStack.pop();
if (current.right != null)
{
nodeStack.add(current.right);
}
if (current.left != null)
{
nodeStack.add(current.left);
}
System.out.print(current.value + "\n");
}
}
else if (order.equals("breadth-first"))
{
Queue<Node> nodeQueue = new LinkedList<>();
nodeQueue.add(rootNode);
while (!nodeQueue.isEmpty())
{
Node current = nodeQueue.remove();
System.out.print(current.value + "\n");
if (current.left != null)
{
nodeQueue.add(current.left);
}
if (current.right != null)
{
nodeQueue.add(current.right);
}
}
}
}
/** method to locate a value in the tree, if no value is located, return -1 **/
/** this method (of course) implements a binary search **/
public Node search(Node root, Node findMe)
{
if (!isEmpty())
{
int valueToFind = findMe.value;
if (valueToFind == root.value)
{
return root;
}
if (valueToFind < root.value)
{
return search(root.left, findMe);
}
if (valueToFind > root.value)
{
return search(root.right, findMe);
}
}
return new Node(-1);
}
/** return the amount of nodes currently in the tree **/
/** this method uses a depth first search to traverse the tree **/
public int nodeCount()
{
if (!isEmpty())
{
int nodeCounter = 0;
Stack<Node> nodeStack = new Stack<>();
nodeStack.add(rootNode);
while (!nodeStack.isEmpty())
{
nodeCounter++;
Node current = nodeStack.pop();
if (current.right != null)
{
nodeStack.add(current.right);
}
if (current.left != null)
{
nodeStack.add(current.left);
}
}
return nodeCounter;
}
return -1;
}
/** return the sum of all node data **/
/** this method uses a depth first search to traverse the tree **/
public int sum()
{
if (!isEmpty())
{
int sum = 0;
Stack<Node> nodeStack = new Stack<>();
nodeStack.add(rootNode);
while (!nodeStack.isEmpty())
{
Node current = nodeStack.pop();
sum += current.value;
if (current.right != null)
{
nodeStack.add(current.right);
}
if (current.left != null)
{
nodeStack.add(current.left);
}
}
return sum;
}
return 0;
}
}
/** node to be placed into binary tree (holds an integer value & links to child nodes) **/
class Node
{
/** data held by the node **/
int value;
/** link to left child of 'this' (child on the left has a smaller value than 'this') **/
Node left;
/** link to right child of 'this' (child on the right has a greater value than 'this') **/
Node right;
/** constructor function **/
public Node(int nodeVal)
{
value = nodeVal;
left = null;
right = null;
}
}
| 27.776836 | 102 | 0.430998 |
0140916724c4ba200c5282f4d18c5dc422b00d6a | 1,786 | /*
* Copyright (c) 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.volumecontroller.impl.plugins;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.emc.storageos.networkcontroller.exceptions.NetworkDeviceControllerException;
import com.emc.storageos.networkcontroller.impl.NetworkDiscoveryWorker;
import com.emc.storageos.networkcontroller.impl.NetworkSystemDevice;
import com.emc.storageos.plugins.AccessProfile;
import com.emc.storageos.plugins.BaseCollectionException;
public class NetworkCommunicationInterface extends ExtendedCommunicationInterfaceImpl {
private NetworkSystemDevice _device;
private static final Logger _log = LoggerFactory
.getLogger(NetworkCommunicationInterface.class);
public void setDevice(NetworkSystemDevice _device) {
this._device = _device;
}
@Override
public void collectStatisticsInformation(AccessProfile accessProfile)
throws BaseCollectionException {
// do nothing
}
@Override
public void scan(AccessProfile accessProfile)
throws BaseCollectionException {
// do nothing
}
@Override
public void discover(AccessProfile accessProfile)
throws BaseCollectionException {
try {
_log.info("Access Profile Details :" + accessProfile.toString());
NetworkDiscoveryWorker worker = new NetworkDiscoveryWorker(_device, _dbClient);
worker.setCoordinator(_coordinator);
worker.verifyVersion(accessProfile.getSystemId());
worker.updatePhysicalInventory(accessProfile.getSystemId());
} catch (Exception e) {
throw NetworkDeviceControllerException.exceptions.discoverNetworkSystemFailed(e);
}
}
}
| 35.019608 | 93 | 0.736282 |
35fb141c977ad49c72a0ed1ebf977b89197a56c7 | 2,374 | package com.veezean.idea.plugin.codereviewer.common;
import java.io.*;
/**
* 序列化反序列化工具类
*
* @author Wang Weiren
* @since 2021/4/26
*/
public final class SerializeUtils {
/**
* 生成文件序列化地址
*
* @param parentDirName 父目录名称(非绝对路径,仅仅是父级目录名称,最终会放在user.home下面)
* @param fileName 具体文件名称
* @return 存储的文件File对象
*/
private static File prepareAndGetCacheDataPath(String parentDirName, String fileName) {
String usrHome = System.getProperty("user.home");
File userDir = new File(usrHome);
File cacheDir = new File(userDir, parentDirName);
if (!cacheDir.exists() || !cacheDir.isDirectory()) {
boolean mkdirs = cacheDir.mkdirs();
if (!mkdirs) {
System.out.println("create cache path failed...");
}
}
return new File(cacheDir, fileName);
}
/**
* 序列化评审信息
*
* @param data 待序列化的数据
* @param parentDirName 父目录名称(非绝对路径,仅仅是父级目录名称,最终会放在user.home下面)
* @param fileName 文件名
*/
synchronized static <T extends Serializable> void serialize(T data, String parentDirName,
String fileName) {
File file = prepareAndGetCacheDataPath(parentDirName, fileName);
ObjectOutputStream oout = null;
try {
oout = new ObjectOutputStream(new FileOutputStream(file));
oout.writeObject(data);
} catch (Exception e) {
throw new CodeReviewException("序列化本地缓存数据异常", e);
} finally {
CommonUtil.closeQuitely(oout);
}
}
/**
* 反序列化评审数据
*
* @param parentDirName 父目录名称(非绝对路径,仅仅是父级目录名称,最终会放在user.home下面)
* @param fileName 文件名
* @param <T> 反序列化的实体类型
* @return 反序列化后的评审数据
*/
synchronized static <T extends Serializable> T deserialize(String parentDirName, String fileName) {
File file = prepareAndGetCacheDataPath(parentDirName, fileName);
ObjectInputStream oin = null;
T cache;
try {
oin = new ObjectInputStream(new FileInputStream(file));
cache = (T) oin.readObject(); // 强制转换到Person类型
} catch (Exception e) {
throw new CodeReviewException("反序列化本地缓存数据异常", e);
} finally {
CommonUtil.closeQuitely(oin);
}
return cache;
}
}
| 30.435897 | 103 | 0.592671 |
88cdd1c0ac17ddd73e2f18901720a907cd117c1a | 137 | package net.sourceforge.greenvine.model.api;
public interface MutableComponentField extends ComponentField, MutableFieldCollection {
}
| 22.833333 | 87 | 0.854015 |
a52f0ef210b4052c147213c9d2555d590c1aa0bf | 1,041 | package com.yang.young.common.sso.rest.controller;
import org.springframework.hateoas.VndErrors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.yang.young.common.sso.rest.controller.exception.UserNotFoundException;
@ControllerAdvice
public class GlobalControllerAdvice {
@ResponseBody
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public VndErrors nullPointerExceptionHandler(NullPointerException e) {
return new VndErrors("error", "this a internal server error. We will fix ASAP");
}
@ResponseBody
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
VndErrors userNotFoundExceptionHandler(UserNotFoundException ex) {
return new VndErrors("error", ex.getMessage());
}
}
| 32.53125 | 82 | 0.830932 |
bcbf35e7fd1f1aca98b8aabc6f85c8479747d85a | 255 | package Factory_Design.Concrete_Creator;
public class Client {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape_1 = shapeFactory.get_shape("Circle");
shape_1.draw();
}
}
| 25.5 | 57 | 0.678431 |
35ef0e205703ff8c5b5fd5479fea6ad63368e4a4 | 80 | package complex_numbers;
public enum StatusComplex {
ONLY_REAL,
ONLY_IMAG;
}
| 11.428571 | 27 | 0.7875 |
426daad1cb40f32e5faa20b8c725d1e889a9eb3a | 4,549 | /**
* Copyright (C) 2011-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.test;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.ClassicConfiguration;
import org.flywaydb.core.api.configuration.Configuration;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Helper factory for Flyway creation and support for setting the flyway.properties and configure
* flyway with {@link Flyway#configure(java.util.Properties)}.
*
* @author Florian
*
* @version 2013-04-01
* @version 2.1
*/
public class FlywayHelperFactory {
/**
* Used for logging inside test executions.
*/
// @@ Construction
private final Log logger = LogFactory.getLog(getClass());
private Flyway flyway;
private Properties flywayProperties;
private ClassicConfiguration flywayConfiguration;
public FlywayHelperFactory() {
logger.info("Create flyway helper factory.");
}
/**
* Create a new flyway instance and call {@link Flyway#configure(java.util.Properties)} with
* content of file <i>flyway.properties</i>.
*
* @return the flyway instance
*/
public synchronized Flyway createFlyway() {
if (flyway == null) {
logger.info("Create a new flyway instance.");
// now use the flyway properties
Properties configuredProperties = getFlywayProperties();
if (configuredProperties == null) {
// try to search flyway.properties in classpath
configuredProperties = new Properties();
setFlywayProperties(configuredProperties);
ClassPathResource classPathResource = new ClassPathResource("flyway.properties");
InputStream inputStream = null;
try {
inputStream = classPathResource.getInputStream();
configuredProperties.load(inputStream);
inputStream.close();
} catch (IOException e) {
logger.error("Can not load flyway.properties.", e);
}
setFlywayProperties(configuredProperties);
logger.info(String.format("Load flyway.properties with %d entries.", configuredProperties.size()));
} else {
logger.info(String.format("Used preconfigured flyway.properties with %d entries.", configuredProperties.size()));
}
if ( flywayConfiguration == null) {
ClassicConfiguration classicConfiguration = new ClassicConfiguration();
classicConfiguration.configure(getFlywayProperties());
setFlywayConfiguration(classicConfiguration);
} else {
ClassicConfiguration classicConfiguration = getFlywayConfiguration();
classicConfiguration.configure(getFlywayProperties());
setFlywayConfiguration(classicConfiguration);
}
Flyway toReturn = Flyway.configure()
.configuration(getFlywayConfiguration())
.load();
setFlyway(toReturn);
}
return flyway;
}
public Properties getFlywayProperties() {
return flywayProperties;
}
public void setFlywayProperties(Properties flywayProperties) {
this.flywayProperties = flywayProperties;
}
@SuppressWarnings("unused")
public Flyway getFlyway() {
return flyway;
}
private void setFlyway(Flyway flyway) {
this.flyway = flyway;
}
public ClassicConfiguration getFlywayConfiguration() {
return flywayConfiguration;
}
public void setFlywayConfiguration(ClassicConfiguration flywayConfiguration) {
this.flywayConfiguration = flywayConfiguration;
}
} | 32.492857 | 129 | 0.657947 |
ee20426c8c34ec5e3e97956facd6fa09a5490e11 | 1,003 | /* ************************************************************************
#
# DivConq
#
# http://divconq.com/
#
# Copyright:
# Copyright 2014 eTimeline, LLC. All rights reserved.
#
# License:
# See the license.txt file in the project's top-level directory for details.
#
# Authors:
# * Andy White
#
************************************************************************ */
package divconq.service.plugin;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Operation {
String description() default "";
String descriptionCode() default "";
String[] tags() default "User";
Request request() default @Request;
Response response() default @Response;
}
| 27.108108 | 80 | 0.613161 |
116bb8a60d875b410164fe0ebebb6f405b07e52e | 516 | package com.nobr.android.questr;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.nobr.android.questr.util.InjectionUtils;
public abstract class BaseFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
setupInjection();
}
private void setupInjection() {
InjectionUtils.inject(getActivity(), this);
}
} | 23.454545 | 53 | 0.713178 |
ab3c456e394193855be5ad572ca06fa165f69b1c | 14,490 | package com.vackosar.gitflowincrementalbuild.boundary;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.util.Arrays;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.MavenProject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.google.common.collect.ImmutableMap;
import com.vackosar.gitflowincrementalbuild.SystemPropertiesResetExtension;
import com.vackosar.gitflowincrementalbuild.boundary.Configuration.BuildUpstreamMode;
import com.vackosar.gitflowincrementalbuild.control.Property;
/**
* Tests the system properties parsing logic in {@link Configuration}.
*
* @author famod
*
*/
@ExtendWith({SystemPropertiesResetExtension.class, MockitoExtension.class})
public class ConfigurationTest {
@Mock
private MavenExecutionRequest mavenExecutionRequestMock;
@Mock(lenient = true)
private MavenSession mavenSessionMock;
private final Properties projectProperties = new Properties();
@BeforeEach
void before() {
when(mavenSessionMock.getRequest()).thenReturn(mavenExecutionRequestMock);
MavenProject mockTLProject = mock(MavenProject.class, withSettings().lenient());
when(mockTLProject.getProperties()).thenReturn(projectProperties);
when(mavenSessionMock.getTopLevelProject()).thenReturn(mockTLProject);
}
@Test
public void invalidProperty() {
String invalidProperty = Property.PREFIX + "invalid";
System.setProperty(invalidProperty, "invalid");
assertThatIllegalArgumentException().isThrownBy(() -> new Configuration.Provider(mavenSessionMock).get())
.withMessageContaining(invalidProperty)
.withMessageContaining(Property.disableBranchComparison.fullName());
}
@Test
public void enabled() {
System.setProperty(Property.enabled.fullName(), "false");
assertFalse(Configuration.isEnabled(mavenSessionMock));
}
@Test
public void enabled_projectProperties() {
projectProperties.put(Property.enabled.fullName(), "false");
assertFalse(Configuration.isEnabled(mavenSessionMock));
}
@Test
public void enabled_projectProperties_overriddenBySystemProperty() {
projectProperties.put(Property.enabled.fullName(), "true");
System.setProperty(Property.enabled.fullName(), "false");
assertFalse(Configuration.isEnabled(mavenSessionMock));
}
@Test
public void argsForUpstreamModules() {
System.setProperty(Property.argsForUpstreamModules.fullName(), "x=true a=false");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertEquals(ImmutableMap.of("x", "true", "a", "false"), configuration.argsForUpstreamModules);
}
@Test
public void excludeDownstreamModulesPackagedAs() {
System.setProperty(Property.excludeDownstreamModulesPackagedAs.fullName(), "ear,war");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertEquals(Arrays.asList("ear", "war"), configuration.excludeDownstreamModulesPackagedAs);
}
// deprecated old name of excludeDownstreamModulesPackagedAs
@Test
public void excludeTransitiveModulesPackagedAs() {
System.setProperty(Property.excludeDownstreamModulesPackagedAs.deprecatedFullName(), "ear,war");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertEquals(Arrays.asList("ear", "war"), configuration.excludeDownstreamModulesPackagedAs);
}
@Test
public void forceBuildModules_pattern() {
String expectedPatternString = ".*-some-artifact";
System.setProperty(Property.forceBuildModules.fullName(), expectedPatternString);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertNotNull(configuration.forceBuildModules,"Field forceBuildModules is null");
assertEquals( 1, configuration.forceBuildModules.size(), "Unexpected number of Patterns in forceBuildModules");
Pattern pattern = configuration.forceBuildModules.get(0);
assertNotNull(pattern, "Pattern form forceBuildModules is null");
assertEquals(expectedPatternString, pattern.pattern(), "Unexpected pattern string of Pattern from forceBuildModules");
}
@Test
public void forceBuildModules_patternInvalid() {
System.setProperty(Property.forceBuildModules.fullName(), "*-some-artifact"); // pattern is missing the dot
assertThatIllegalArgumentException().isThrownBy(() -> new Configuration.Provider(mavenSessionMock).get())
.withMessageContaining(Property.forceBuildModules.fullName())
.withCauseExactlyInstanceOf(PatternSyntaxException.class);
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// tests for configuration.buildUpstreamMode (which is calculated from two(!) properties: buildUpstream and buildUpstreamMode)
@Test
public void buildUpstreamMode_never() {
System.setProperty(Property.buildUpstream.fullName(), "never");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.NONE, configuration.buildUpstreamMode);
verify(mavenExecutionRequestMock, never()).getMakeBehavior();
}
@Test
public void buildUpstreamMode_false() {
System.setProperty(Property.buildUpstream.fullName(), "false");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.NONE, configuration.buildUpstreamMode);
verify(mavenExecutionRequestMock, never()).getMakeBehavior();
}
@Test
public void buildUpstreamMode_always() {
System.setProperty(Property.buildUpstream.fullName(), "always");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.CHANGED, configuration.buildUpstreamMode);
verify(mavenExecutionRequestMock, never()).getMakeBehavior();
}
@Test
public void buildUpstreamMode_true() {
System.setProperty(Property.buildUpstream.fullName(), "true");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.CHANGED, configuration.buildUpstreamMode);
verify(mavenExecutionRequestMock, never()).getMakeBehavior();
}
@Test
public void buildUpstreamMode_unknown() {
System.setProperty(Property.buildUpstream.fullName(), "foo");
assertThatIllegalArgumentException().isThrownBy(() -> new Configuration.Provider(mavenSessionMock).get())
.withMessageContaining(Property.buildUpstream.fullName());
}
// tests for mode value 'derived' (default value)
@Test
public void buildUpstreamMode_derived_noMake() {
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.NONE, configuration.buildUpstreamMode);
}
@Test
public void buildUpstreamMode_derived_makeUpstream() {
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.CHANGED, configuration.buildUpstreamMode);
}
@Test
public void buildUpstreamMode_derived_makeBoth() {
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_BOTH);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.CHANGED, configuration.buildUpstreamMode);
}
@Test
public void buildUpstreamMode_derived_makeDownstream() {
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.NONE, configuration.buildUpstreamMode);
}
@Test
public void buildUpstreamMode_derived_makeUpstream_impacted() {
System.setProperty(Property.buildUpstreamMode.fullName(), "impacted");
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.IMPACTED, configuration.buildUpstreamMode);
}
@Test
public void buildUpstreamMode_derived_makeUpstream_unknown() {
System.setProperty(Property.buildUpstreamMode.fullName(), "foo");
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
assertThatIllegalArgumentException().isThrownBy(() -> new Configuration.Provider(mavenSessionMock).get())
.withMessageContaining(Property.buildUpstreamMode.fullName())
.withCauseExactlyInstanceOf(IllegalArgumentException.class);
}
// just an example to show 'derived' can also be set explicitely
@Test
public void buildUpstreamMode_derivedExplicit_makeUpstream() {
System.setProperty(Property.buildUpstream.fullName(), "derived");
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertSame(BuildUpstreamMode.CHANGED, configuration.buildUpstreamMode);
}
// ///////////////////////////////////////
// tests for configuration.buildDownstream
// 'always' is default
@Test
public void buildDownstream() {
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertTrue(configuration.buildDownstream);
verify(mavenExecutionRequestMock, times(1)).getMakeBehavior(); // called once for buildDownstreamMode
}
@Test
public void buildDownstream_never() {
System.setProperty(Property.buildDownstream.fullName(), "never");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertFalse(configuration.buildDownstream);
verify(mavenExecutionRequestMock, times(1)).getMakeBehavior(); // called once for buildDownstreamMode
}
@Test
public void buildDownstream_false() {
System.setProperty(Property.buildDownstream.fullName(), "false");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertFalse(configuration.buildDownstream);
verify(mavenExecutionRequestMock, times(1)).getMakeBehavior(); // called once for buildDownstreamMode
}
@Test
public void buildDownstream_always() {
System.setProperty(Property.buildDownstream.fullName(), "always");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertTrue(configuration.buildDownstream);
verify(mavenExecutionRequestMock, times(1)).getMakeBehavior(); // called once for buildDownstreamMode
}
@Test
public void buildDownstream_true() {
System.setProperty(Property.buildDownstream.fullName(), "true");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertTrue(configuration.buildDownstream);
verify(mavenExecutionRequestMock, times(1)).getMakeBehavior(); // called once for buildDownstreamMode
}
@Test
public void buildDownstream_unknown() {
System.setProperty(Property.buildDownstream.fullName(), "foo");
assertThatIllegalArgumentException().isThrownBy(() -> new Configuration.Provider(mavenSessionMock).get())
.withMessageContaining(Property.buildDownstream.fullName());
}
@Test
public void buildDownstream_derived_noMake() {
System.setProperty(Property.buildDownstream.fullName(), "derived");
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertFalse(configuration.buildDownstream);
}
@Test
public void buildDownstream_derived_makeDownstream() {
System.setProperty(Property.buildDownstream.fullName(), "derived");
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertTrue(configuration.buildDownstream);
}
@Test
public void buildDownstream_derived_makeBoth() {
System.setProperty(Property.buildDownstream.fullName(), "derived");
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_BOTH);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertTrue(configuration.buildDownstream);
}
@Test
public void buildDownstream_derived_makeUpstream() {
System.setProperty(Property.buildDownstream.fullName(), "derived");
when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
Configuration configuration = new Configuration.Provider(mavenSessionMock).get();
assertFalse(configuration.buildDownstream);
}
}
| 40.027624 | 130 | 0.736715 |
2a1e030b5e0ac3ceaedb0d6132faf416640e01f3 | 2,222 | /**
* Copyright 2011-2015 John Ericksen
*
* 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.parceler.internal;
import org.androidtransfuse.adapter.ASTAnnotation;
import org.androidtransfuse.adapter.ASTType;
import org.androidtransfuse.transaction.AbstractCompletionTransactionWorker;
import org.parceler.ParcelClass;
import org.parceler.ParcelClasses;
import javax.inject.Inject;
import javax.inject.Provider;
/**
* Executes the analysis and generation of an annotated @Parcel class.
*
* @author John Ericksen
*/
public class ExternalParcelRepositoryTransactionWorker extends AbstractCompletionTransactionWorker<Provider<ASTType>, Provider<ASTType>> {
private final ExternalParcelRepository repository;
@Inject
public ExternalParcelRepositoryTransactionWorker(ExternalParcelRepository repository) {
this.repository = repository;
}
@Override
public Provider<ASTType> innerRun(Provider<ASTType> valueProvider) {
ASTType value = valueProvider.get();
ASTAnnotation parcelClassesAnnotation = value.getASTAnnotation(ParcelClasses.class);
if(parcelClassesAnnotation != null){
ASTAnnotation[] parcelTypes = parcelClassesAnnotation.getProperty("value", ASTAnnotation[].class);
for(ASTAnnotation annotation : parcelTypes){
repository.add(annotation.getProperty("value", ASTType.class));
}
}
ASTAnnotation astAnnotation = value.getASTAnnotation(ParcelClass.class);
if(astAnnotation != null){
ASTType parcelType = astAnnotation.getProperty("value", ASTType.class);
repository.add(parcelType);
}
return valueProvider;
}
}
| 34.71875 | 138 | 0.735824 |
be3664d1a2fbfe930d17f9a350b969897566f7f2 | 2,866 | package org.dragon.zhang.annotator.annotator.impl;
import net.bytebuddy.asm.MemberAttributeExtension;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.matcher.ElementMatchers;
import org.codehaus.plexus.logging.Logger;
import org.dragon.zhang.annotator.annotator.AbstractAnnotator;
import org.dragon.zhang.annotator.annotator.Annotator;
import org.dragon.zhang.annotator.model.JavadocMapping;
import org.jboss.forge.roaster.model.JavaDocTag;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.JavaDocSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import java.lang.annotation.ElementType;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author zhangzicheng
* @date 2021/03/10
*/
public class MethodAnnotator extends AbstractAnnotator {
public MethodAnnotator(Logger log) {
super(log);
}
@Override
protected Map<String, Set<JavadocMapping>> needToTag(Set<JavadocMapping> needToTag, JavaClassSource source) {
Map<String, Set<JavadocMapping>> result = new HashMap<>();
List<MethodSource<JavaClassSource>> methods = source.getMethods();
for (MethodSource<JavaClassSource> method : methods) {
result.put(method.getName(), AbstractAnnotator.buildNeedToTag(method, needToTag));
}
return result;
}
@Override
protected Map<String, Map<String, Object>> initComment(JavaClassSource source) {
Map<String, Map<String, Object>> comment = new HashMap<>();
List<MethodSource<JavaClassSource>> methods = source.getMethods();
for (MethodSource<JavaClassSource> method : methods) {
Map<String, Object> map = new HashMap<>();
JavaDocSource<?> methodDoc = method.getJavaDoc();
map.put(Annotator.DESCRIPTION_KEY, methodDoc.getText());
List<JavaDocTag> methodTags = methodDoc.getTags();
for (JavaDocTag tag : methodTags) {
String tagName = tag.getName();
if (Annotator.PARAM_TAG.equals(tagName)) {
continue;
}
map.put(tagName, tag.getValue());
}
comment.put(method.getName(), map);
}
return comment;
}
@Override
protected DynamicType.Builder<?> tagAnnotations(DynamicType.Builder<?> builder, Collection<AnnotationDescription> descriptions, String name, int index) {
return builder.visit(new MemberAttributeExtension.ForMethod()
.annotateMethod(descriptions)
.on(ElementMatchers.named(name)));
}
@Override
public ElementType annotateType() {
return ElementType.METHOD;
}
}
| 37.710526 | 157 | 0.693301 |
3cae1e4dc290836f52c66d044d9e7dfae76f137b | 1,278 | package demo.model.user;
import javax.enterprise.context.RequestScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@RequestScoped
public class PersonDao {
@PersistenceContext(name = "jpa-unit")
private EntityManager em;
public void createPerson(Person person){
em.persist(person);
}
public Person readPerson(int persId){
return em.find(Person.class, persId);
}
public void updatePerson(Person person){
em.merge(person);
}
public void deletePerson(Person person){
em.remove(person);
}
public List<Person> readAllPersons(){
return em.createQuery("Person.findAll", Person.class).getResultList();
}
public List<Person> findPerson(String username, String email) {
return em.createNamedQuery("Person.findPerson", Person.class)
.setParameter("username", username)
.setParameter("email", email).getResultList();
}
public Person findUsername(String username) {
return em.createNamedQuery("Person.findPersonUsername", Person.class)
.setParameter("username", username).getSingleResult();
}
public EntityManager getEm() {
return em;
}
}
| 25.56 | 78 | 0.676839 |
86a7837780275c6f748ce7672f46f18d2e6f822c | 819 | public static int findProfit(List[] inventory, int order){
HashMap<Integer, Integer> hm = new HashMap<>();
int res = 0;
int max = 0;
for(int i = 0; i < inventory.size();i++){
if(hm.containsKey(inventory.get(i))){
hm.put(inventory.get(i),hm.getOrDefault(inventory.get(i), 0) + 1);
}else{
hm.put(inventory.get(i), 1);
}
max = Math.max(max, inventory.get(i));
}
while (order > 0) {
int tempOrder = Math.min(hm.get(max), order);
res += tempOrder * max;
order -= tempOrder;
hm.remove(max);
if (hm.containsKey(max - 1)) {
hm.put(max - 1,hm.getOrDefault(max - 1, 0) + tempOrder);
} else {
hm.put(max - 1, tempOrder);
}
max = max - 1;
}
return res;
} | 31.5 | 78 | 0.509158 |
275d71f6a7f9707b9f0b765879e4e3c357eba31f | 137 | package p;
public @interface A {
Class<?> val();
String constant();
}
class B {}
class C {
public static final String FOO = "";
} | 12.454545 | 38 | 0.613139 |
862cf638cf230d07c9a056f6d90dd9dbc334a6a1 | 14,650 | package cucumber.runtime;
import cucumber.api.Pending;
import cucumber.api.StepDefinitionReporter;
import cucumber.api.SummaryPrinter;
import cucumber.runtime.io.ResourceLoader;
import cucumber.runtime.model.CucumberFeature;
import cucumber.runtime.model.RunResult;
import cucumber.runtime.snippets.FunctionNameGenerator;
import cucumber.runtime.xstream.LocalizedXStreams;
import gherkin.I18n;
import gherkin.formatter.Argument;
import gherkin.formatter.Formatter;
import gherkin.formatter.Reporter;
import gherkin.formatter.model.Comment;
import gherkin.formatter.model.DataTableRow;
import gherkin.formatter.model.DocString;
import gherkin.formatter.model.Match;
import gherkin.formatter.model.Result;
import gherkin.formatter.model.Step;
import gherkin.formatter.model.Tag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* This is the main entry point for running Cucumber features.
*/
public class Runtime implements UnreportedStepExecutor {
private static final String[] PENDING_EXCEPTIONS = {
"org.junit.AssumptionViolatedException",
"org.junit.internal.AssumptionViolatedException"
};
static {
Arrays.sort(PENDING_EXCEPTIONS);
}
private static final Object DUMMY_ARG = new Object();
private static final byte ERRORS = 0x1;
private final Glue glue;
private final Collection<? extends Backend> backends;
private final ResourceLoader resourceLoader;
private final ClassLoader classLoader;
private final StopWatch.StopWatchFactory stopWatchFactory;
private final boolean isDryRun;
public Runtime(ResourceLoader resourceLoader, ClassFinder classFinder, ClassLoader classLoader, boolean isDryRun, List<String> glue) {
this(resourceLoader, classLoader, isDryRun, glue, loadBackends(resourceLoader, classFinder));
}
public Runtime(ResourceLoader resourceLoader, ClassLoader classLoader, boolean isDryRun, List<String> glue, Collection<? extends Backend> backends) {
this(resourceLoader, classLoader, isDryRun, glue, backends, StopWatch.SIMPLE_FACTORY, null);
}
public Runtime(ResourceLoader resourceLoader, ClassLoader classLoader, boolean isDryRun, List<String> glue, Collection<? extends Backend> backends, RuntimeGlue optionalGlue) {
this(resourceLoader, classLoader, isDryRun, glue, backends, StopWatch.SIMPLE_FACTORY, optionalGlue);
}
public Runtime(ResourceLoader resourceLoader, ClassLoader classLoader,
boolean isDryRun, List<String> glue,
Collection<? extends Backend> backends, StopWatch.StopWatchFactory stopWatchFactory, RuntimeGlue optionalGlue) {
if (backends.isEmpty()) {
throw new CucumberException("No backends were found. Please make sure you have a backend module on your CLASSPATH.");
}
this.resourceLoader = resourceLoader;
this.classLoader = classLoader;
this.backends = backends;
this.stopWatchFactory = stopWatchFactory;
this.glue = optionalGlue != null ? optionalGlue : new RuntimeGlue(new LocalizedXStreams(classLoader));
this.isDryRun = isDryRun;
for (Backend backend : backends) {
backend.loadGlue(this.glue, glue);
backend.setUnreportedStepExecutor(this);
}
}
private static Collection<? extends Backend> loadBackends(ResourceLoader resourceLoader, ClassFinder classFinder) {
Reflections reflections = new Reflections(classFinder);
return reflections.instantiateSubclasses(Backend.class, "cucumber.runtime", new Class[]{ResourceLoader.class}, new Object[]{resourceLoader});
}
public static final class RuntimeRunResult {
public final byte exitStatus;
public final List<Throwable> errors;
public RuntimeRunResult(byte exitCode, List<Throwable> errors) {
this.exitStatus = exitCode;
this.errors = errors;
}
}
/**
* This is the main entry point. Used from CLI, but not from JUnit.
*/
public RuntimeRunResult run(RuntimeOptions runtimeOptions) throws IOException {
// Make sure all features parse before initialising any reporters/formatters
List<CucumberFeature> features = runtimeOptions.cucumberFeatures(resourceLoader);
RunResult runResult = RunResult.IDENTITY;
List<Throwable> errors = new ArrayList<Throwable>();
UndefinedStepsTracker tracker = new UndefinedStepsTracker();
final Stats.StatsFormatOptions statsFormatOptions = new Stats.StatsFormatOptions(runtimeOptions.isMonochrome());
// TODO: This is duplicated in cucumber.api.android.CucumberInstrumentationCore - refactor or keep uptodate
Formatter formatter = runtimeOptions.formatter(classLoader);
Reporter reporter = runtimeOptions.reporter(classLoader);
StepDefinitionReporter stepDefinitionReporter = runtimeOptions.stepDefinitionReporter(classLoader);
glue.reportStepDefinitions(stepDefinitionReporter);
for (CucumberFeature cucumberFeature : features) {
final RunResult runFeatureResult = cucumberFeature.run(formatter, reporter, this, tracker);
runResult = RunResult.append(runResult, runFeatureResult);
}
formatter.done();
formatter.close();
SummaryPrinter summaryPrinter = runtimeOptions.summaryPrinter(classLoader);
summaryPrinter.print(statsFormatOptions, runResult.stats, runResult.errors, getSnippets(tracker, runtimeOptions.getSnippetType().getFunctionNameGenerator()), runtimeOptions.isStrict());
final byte exitStatus = Runtime.exitStatus(errors, tracker, runtimeOptions.isStrict());
return new RuntimeRunResult(exitStatus, errors);
}
public ScenarioImpl buildBackendWorlds(Reporter reporter, Set<Tag> tags, gherkin.formatter.model.Scenario gherkinScenario) {
for (Backend backend : backends) {
backend.buildWorld();
}
//TODO: this is the initial state of the state machine, it should not go here, but into something else
return new ScenarioImpl(reporter, tags, gherkinScenario);
}
public void disposeBackendWorlds() {
for (Backend backend : backends) {
backend.disposeWorld();
}
}
public static byte exitStatus(List<Throwable> errors, UndefinedStepsTracker undefinedStepsTracker, boolean isStrict) {
byte result = 0x0;
if (hasErrors(errors) || hasUndefinedOrPendingStepsAndIsStrict(errors, undefinedStepsTracker, isStrict)) {
result |= ERRORS;
}
return result;
}
private static boolean hasUndefinedOrPendingStepsAndIsStrict(List<Throwable> errors, UndefinedStepsTracker undefinedStepsTracker, boolean isStrict) {
return isStrict && hasUndefinedOrPendingSteps(errors, undefinedStepsTracker);
}
private static boolean hasUndefinedOrPendingSteps(List<Throwable> throwables, UndefinedStepsTracker undefinedStepsTracker) {
return undefinedStepsTracker.hasUndefinedSteps() || hasPendingSteps(throwables);
}
private static boolean hasPendingSteps(List<Throwable> errors) {
return !errors.isEmpty() && !hasErrors(errors);
}
private static boolean hasErrors(List<Throwable> errors) {
for (Throwable error : errors) {
if (!isPending(error)) {
return true;
}
}
return false;
}
public List<String> getSnippets(UndefinedStepsTracker undefinedStepsTracker, FunctionNameGenerator functionNameGenerator) {
return undefinedStepsTracker.getSnippets(backends, functionNameGenerator);
}
public Glue getGlue() {
return glue;
}
public RunStepResult runBeforeHooks(ScenarioImpl scenarioResult, Reporter reporter, Set<Tag> tags) {
return runHooks(scenarioResult, glue.getBeforeHooks(), reporter, tags, true, isDryRun);
}
public RunStepResult runAfterHooks(ScenarioImpl scenarioResult, Reporter reporter, Set<Tag> tags) {
return runHooks(scenarioResult, glue.getAfterHooks(), reporter, tags, false, isDryRun);
}
private RunStepResult runHooks(ScenarioImpl scenarioResult, List<HookDefinition> hooks, Reporter reporter, Set<Tag> tags, boolean isBefore, boolean isDryRun) {
boolean skipNextStep = false;
Stats stats = Stats.IDENTITY;
List<Throwable> errors = Collections.emptyList();
if (!isDryRun) {
for (HookDefinition hook : hooks) {
final RunStepResult runHookResult = runHookIfTagsMatch(scenarioResult, hook, reporter, tags, isBefore);
stats = Stats.append(stats, runHookResult.runResult.stats);
errors = Utils.append(errors, runHookResult.runResult.errors);
if (runHookResult.skipNext) {
skipNextStep = true;
}
}
}
return new RunStepResult(skipNextStep, new RunResult(stats, errors));
}
private RunStepResult runHookIfTagsMatch(ScenarioImpl scenarioResult, HookDefinition hook, Reporter reporter, Set<Tag> tags, boolean isBefore) {
Stats stats = new Stats();
boolean skipNextStep = false;
final List<Throwable> errors = new ArrayList<Throwable>(1);
if (hook.matches(tags)) {
String status = Result.PASSED;
Throwable error = null;
Match match = new Match(Collections.<Argument>emptyList(), hook.getLocation(false));
final StopWatch stopWatch = stopWatchFactory.create();
stopWatch.start();
try {
hook.execute(scenarioResult);
} catch (Throwable t) {
error = t;
status = isPending(t) ? "pending" : Result.FAILED;
errors.add(t);
skipNextStep = true;
} finally {
long duration = stopWatch.stop();
Result result = new Result(status, duration, error, DUMMY_ARG);
scenarioResult.add(result);
stats.addHookTime(result.getDuration());
if (isBefore) {
reporter.before(match, result);
} else {
reporter.after(match, result);
}
}
}
return new RunStepResult(skipNextStep, new RunResult(stats, errors));
}
//TODO: Maybe this should go into the cucumber step execution model and it should return the result of that execution!
@Override
public void runUnreportedStep(String featurePath, I18n i18n, String stepKeyword, String stepName, int line, List<DataTableRow> dataTableRows, DocString docString, UndefinedStepsTracker undefinedStepsTracker) throws Throwable {
Step step = new Step(Collections.<Comment>emptyList(), stepKeyword, stepName, line, dataTableRows, docString);
StepDefinitionMatch match = glue.stepDefinitionMatch(featurePath, step, i18n, undefinedStepsTracker);
if (match == null) {
UndefinedStepException error = new UndefinedStepException(step);
StackTraceElement[] originalTrace = error.getStackTrace();
StackTraceElement[] newTrace = new StackTraceElement[originalTrace.length + 1];
newTrace[0] = new StackTraceElement("✽", "StepDefinition", featurePath, line);
System.arraycopy(originalTrace, 0, newTrace, 1, originalTrace.length);
error.setStackTrace(newTrace);
throw error;
}
match.runStep(i18n);
}
public static final class RunStepResult {
public final boolean skipNext;
public final RunResult runResult;
public RunStepResult(boolean skipNext, RunResult runResult) {
this.skipNext = skipNext;
this.runResult = runResult;
}
}
/** returns {@code true} if the next step should be skipped */
public RunStepResult runStep(ScenarioImpl scenarioResult, UndefinedStepsTracker tracker, String featurePath, Step step, Reporter reporter, I18n i18n, boolean skip) {
final StepDefinitionMatch match;
final Stats stats = new Stats();
try {
match = glue.stepDefinitionMatch(featurePath, step, i18n, tracker);
} catch (AmbiguousStepDefinitionsException e) {
reporter.match(e.getMatches().get(0));
Result result = new Result(Result.FAILED, 0L, e, DUMMY_ARG);
reporter.result(result);
scenarioResult.add(result);
stats.addStep(result);
return new RunStepResult(true, new RunResult(stats, Collections.<Throwable>singletonList(e)));
}
if (match == null) {
reporter.match(Match.UNDEFINED);
reporter.result(Result.UNDEFINED);
scenarioResult.add(Result.UNDEFINED);
stats.addStep(Result.UNDEFINED);
return new RunStepResult(true, new RunResult(stats, Collections.<Throwable>emptyList()));
}
reporter.match(match);
if (skip || isDryRun) {
scenarioResult.add(Result.SKIPPED);
stats.addStep(Result.SKIPPED);
reporter.result(Result.SKIPPED);
return new RunStepResult(true, new RunResult(stats, Collections.<Throwable>emptyList()));
} else {
String status = Result.PASSED;
Throwable error = null;
final StopWatch stopWatch = stopWatchFactory.create();
stopWatch.start();
boolean skipNextStep = false;
final List<Throwable> errors = new ArrayList<Throwable>(1);
try {
match.runStep(i18n);
} catch (Throwable t) {
error = t;
status = isPending(t) ? "pending" : Result.FAILED;
errors.add(t);
skipNextStep = true;
} finally {
long duration = stopWatch.stop();
Result result = new Result(status, duration, error, DUMMY_ARG);
scenarioResult.add(result);
stats.addStep(result);
reporter.result(result);
}
return new RunStepResult(skipNextStep, new RunResult(stats, errors));
}
}
public static boolean isPending(Throwable t) {
if (t == null) {
return false;
}
return t.getClass().isAnnotationPresent(Pending.class) || Arrays.binarySearch(PENDING_EXCEPTIONS, t.getClass().getName()) >= 0;
}
}
| 42.961877 | 230 | 0.675222 |
26d79d4d481b5ddf407d8d9a0407f0ad99965a61 | 680 | package com.labs64.utils.swid.builder;
import com.labs64.utils.swid.exception.SwidException;
import org.iso.standards.iso._19770.__2._2014_dis.schema.Process;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ProcessBuilderTest {
@Test(expected = SwidException.class)
public void testBuilderIncomplete() {
ProcessBuilder builder = new ProcessBuilder();
builder.lang("lang").build();
}
@Test
public void testBuilder() {
ProcessBuilder builder = new ProcessBuilder();
Process process = builder.name("FileName").lang("lang").build();
assertEquals("FileName", process.getName());
}
}
| 28.333333 | 72 | 0.705882 |
a6a04d918126dc0c6e31f5a8568bd7c4031b68b1 | 182 | package io.cdap.plugin.json.parser;
import java.util.List;
public class DQRules {
private List<Rule> rules;
public List<Rule> getRules() {
return rules;
}
}
| 13 | 35 | 0.648352 |
eca7d563f60f8fe80eae9fb736faa6295311abf9 | 5,945 | /*
* Copyright 2018 Azilet B.
*
* 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 kg.net.bazi.gsb4j;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.io.IOException;
import kg.net.bazi.gsb4j.properties.Gsb4jProperties;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provider of HTTP client to be used for making requests to Safe Browsing API.
*
* @author azilet
*/
class HttpClientProvider implements Provider<CloseableHttpClient> {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientProvider.class);
@Inject
Gsb4jProperties properties;
@Override
public CloseableHttpClient get() {
PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
pcm.setMaxTotal(50);
pcm.setDefaultMaxPerRoute(5);
pcm.setValidateAfterInactivity(10_000);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(15_000)
.build();
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.disableCookieManagement()
.addInterceptorFirst(new GzipCompressionRequestInterceptor())
.addInterceptorFirst(new GzipCompressionResponseInterceptor())
.setConnectionManager(pcm);
String referer = properties.getApiHttpReferrer();
if (referer != null && !referer.isEmpty()) {
httpClientBuilder.addInterceptorLast(makeRequestRefererInterceptor(referer));
}
if (LOGGER.isDebugEnabled()) {
httpClientBuilder.addInterceptorFirst(makeRequestPayloadLogger());
httpClientBuilder.addInterceptorFirst(makeResponsePayloadLogger());
}
return httpClientBuilder.build();
}
private HttpRequestInterceptor makeRequestRefererInterceptor(String referer) {
return new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
request.addHeader(HttpHeaders.REFERER, referer);
}
};
}
private HttpRequestInterceptor makeRequestPayloadLogger() {
return new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
LOGGER.debug("===> {}", request.getRequestLine());
}
};
}
private HttpResponseInterceptor makeResponsePayloadLogger() {
return new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
LOGGER.debug("<=== {}", response.getStatusLine());
}
};
}
/**
* HTTP request interceptor that adds headers to requests indicating responses can be compressed using gzip.
*
* @author azilet
*/
static class GzipCompressionRequestInterceptor implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
if (!request.containsHeader(HttpHeaders.ACCEPT_ENCODING)) {
request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip,deflate");
}
}
}
/**
* HTTP response interceptor that makes possible to read compressed responses in gzip, deflate, etc.
*
* @author azilet
*/
static class GzipCompressionResponseInterceptor implements HttpResponseInterceptor {
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
// immediately return for responses that have no body, e.g. response to HEAD requests
if (entity == null) {
return;
}
Header header = entity.getContentEncoding();
if (header != null) {
for (HeaderElement he : header.getElements()) {
if (he.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(entity));
return;
}
if (he.getName().equalsIgnoreCase("deflate")) {
response.setEntity(new DeflateDecompressingEntity(entity));
return;
}
}
}
}
}
}
| 37.15625 | 112 | 0.677544 |
e3257fa5511a1de21b2f9f2bc7d86406ae4049e6 | 2,170 | package com.github.onblog.snowjenaticketserver.rule;
import com.github.onblog.commoon.entity.RateLimiterRule;
import com.github.onblog.commoon.entity.RateLimiterRuleBuilder;
import com.github.onblog.snowjenaticketserver.exception.ResultEnum;
import com.github.onblog.snowjenaticketserver.exception.ResultException;
import com.github.onblog.snowjenaticketserver.rule.entity.Result;
import com.github.onblog.snowjenaticketserver.rule.service.RuleService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RuleController {
@Autowired
private RuleService ruleService;
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 心跳包
* @param rule 规则字符串
* @return 最新规则字符串
*/
@RequestMapping(value = "/heart", method = RequestMethod.POST)
public String heartbeat(@RequestParam("data") String rule) {
logger.debug("heart:" + rule);
RateLimiterRule rateLimiterRule = JSON.parseObject(rule, RateLimiterRule.class);
return JSON.toJSONString(ruleService.heartbeat(rateLimiterRule));
}
/**
* @return 所有规则
*/
@RequestMapping(value = "/rule", method = RequestMethod.GET)
@ResultException
public Result<RateLimiterRule> getAllRule(String app, String id, int page, int limit) {
return ruleService.getAllRule(app, id, page, limit);
}
/**
* 修改限流规则
* @return true/false
*/
@RequestMapping(value = "/rule", method = RequestMethod.PUT)
@ResultException
public Result update(@RequestParam("data") String rule) {
RateLimiterRule rateLimiterRule = JSON.parseObject(rule, RateLimiterRule.class);
RateLimiterRuleBuilder.check(rateLimiterRule);
ruleService.update(rateLimiterRule);
return new Result(ResultEnum.SUCCESS);
}
}
| 36.166667 | 91 | 0.746083 |
76a9375ed07ebe0e0eb050ba116939292d422760 | 151 | package objet.typestat;
public interface Deplacements extends TypeStat {
public static Class<?> getTypeStat() {
return Deplacements.class;
}
}
| 15.1 | 48 | 0.748344 |
3c8969cff9a3395bcda479526626454c23b422b7 | 864 | package com.company.cab.routeplan;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.cab.cabs.Cab;
import com.company.cab.cabs.CabRepository;
import com.company.cab.droppoint.DropPoint;
import com.company.cab.droppoint.DropPointNotFoundException;
import com.company.cab.droppoint.DroppointDistance;
import com.company.cab.droppoint.DroppointDistanceRepository;
import com.company.cab.droppoint.DroppointRel;
@RestController
public class RoutePlanController {
@Autowired
RoutePlanService routePlanService;
@GetMapping("/route_plan")
public RoutePlan getRoutePlan() {
return routePlanService.getRoutePlan();
}
}
| 26.181818 | 62 | 0.824074 |
fd334cbb3d4c88ff895afb527db9bcb68cebb345 | 1,130 |
package xyz.keksdose.spoon.code_solver.history;
import spoon.reflect.declaration.CtType;
import xyz.keksdose.spoon.code_solver.transformations.BadSmell;
public class Change {
private MarkdownString text;
private String issue;
private CtType<?> affectedType;
private BadSmell badsmell = BadSmell.emptyRule();
public Change(String text, String issue, CtType<?> affectedType) {
this.text = MarkdownString.fromRaw(text);
this.issue = issue;
this.affectedType = affectedType;
}
public Change(MarkdownString text, String issue, CtType<?> affectedType) {
this.text = text;
this.issue = issue;
this.affectedType = affectedType;
}
public Change(BadSmell badSmell, MarkdownString text, CtType<?> affectedType) {
this.text = text;
this.issue = badSmell.getName().asText();
this.badsmell = badSmell;
this.affectedType = affectedType;
}
public MarkdownString getChangeText() {
return text;
}
/**
* @return the affectedType
*/
public CtType<?> getAffectedType() {
return affectedType;
}
public String getIssue() {
return issue;
}
public BadSmell getBadSmell() {
return badsmell;
}
}
| 22.156863 | 80 | 0.733628 |
93903f1df89d59eb996016613b93351f4c310f28 | 2,504 | /*
* Copyright 2017, Backblaze Inc. All Rights Reserved.
* License https://www.backblaze.com/using_b2_code.html
*/
package com.backblaze.b2.util;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.backblaze.b2.util.B2StringUtil.toHexString;
public interface B2Sha1 {
int SHA1_SIZE = 20;
int HEX_SHA1_SIZE = 2 * SHA1_SIZE;
/**
* Returns a SHA-1 MessageDigest, which we expect to always be available.
*/
static MessageDigest createSha1MessageDigest() {
try {
return MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException("No SHA-1 installed!", e);
}
}
/**
* Returns the SHA-1 of the given bytes, as binary data.
*/
static byte [] binarySha1OfBytes(byte [] data) {
MessageDigest digest = createSha1MessageDigest();
digest.update(data);
return digest.digest();
}
/**
* Returns the SHA-1 of the given bytes, as a hex string.
*/
static String hexSha1OfBytes(byte [] data) {
return toHexString(binarySha1OfBytes(data));
}
/**
* Returns the SHA-1 of the given input stream, as a hex string.
*/
static String hexSha1OfInputStream(InputStream in) throws IOException {
return toHexString(binarySha1OfInputStream(in));
}
/**
* Returns the SHA-1 of the given InputStream, as binary data.
*/
static byte [] binarySha1OfInputStream(InputStream in) throws IOException {
MessageDigest digest = createSha1MessageDigest();
byte[] bytesBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(bytesBuffer)) != -1) {
digest.update(bytesBuffer, 0, bytesRead);
}
return digest.digest();
}
/**
* This canonicalizes sha1s before comparing them.
*
* @param sha1a the first sha1 to compare. must be non-null.
* @param sha1b the second sha1 to compare. must be non-null.
* @return true iff these represent the same sha1.
*/
static boolean equalHexSha1s(String sha1a, String sha1b) {
B2Preconditions.checkArgument(sha1a != null);
B2Preconditions.checkArgument(sha1b != null);
final String lowerA = sha1a.toLowerCase();
final String lowerB = sha1b.toLowerCase();
return lowerA.equals(lowerB);
}
}
| 29.809524 | 79 | 0.646565 |
66b622817a6777a7f58d173606182b6945008263 | 821 | package com.qmetric.spark.metrics;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import spark.Request;
import spark.Response;
import spark.Route;
import static com.codahale.metrics.MetricRegistry.name;
public class RouteTimerWrapper implements Route
{
private final Route route;
private final Timer timer;
public RouteTimerWrapper(final MetricRegistry metricRegistry, final Route route)
{
this.route = route;
timer = metricRegistry.timer(name(route.getClass(), "timer"));
}
@Override public Object handle(final Request request, final Response response)
{
final Timer.Context context = timer.time();
try {
return route.handle(request, response);
}finally {
context.stop();
}
}
}
| 24.878788 | 84 | 0.690621 |
fb94995d02ada3e99118c2885993b13f68574dcf | 1,602 | package com.messolution.openmes.entitys.baseInfo.factoryModel;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import com.messolution.opemmes.hibernate.common.IEntity;
/**
*
* @declaration:
* @project : openmes-plugin-baseInfomation
* @package : com.messolution.openmes.entitys.baseInfo.factoryModel
* @create_time :2014年10月30日 下午11:55:29
* @author : panzhichun
* @mail : [email protected]
*/
@Entity
@Table(name="bi_fm_processCell")
public class ProcessCell extends IEntity {
private static final long serialVersionUID = 1480274115258767557L;
private String name;
private String description;
private Set<Unit> units;
private Area area;
@Column(name="processCellName",length=16)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(length=64)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@OneToMany(mappedBy="processCell")
@Cascade({CascadeType.SAVE_UPDATE})
public Set<Unit> getUnits() {
return units;
}
public void setUnits(Set<Unit> units) {
this.units = units;
}
@ManyToOne
@JoinColumn(name="area_Id")
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
| 19.301205 | 67 | 0.747815 |
311a4f706baecfde5da98e58ae890d3c4ffe600f | 553 | package com.tqmars.requisition.presentation.dto.share;
/**
* 分页查询模型,提供起始页,页码int值
* @author jjh
*
*/
public class PageModel {
public int pageIndex;
public int pageSize;
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@Override
public String toString() {
return "PageModel [pageIndex=" + pageIndex + ", pageSize=" + pageSize
+ "]";
}
}
| 19.068966 | 71 | 0.692586 |
0ca9bd0f88fdfed37bdfcb7716024aa06d78615b | 690 | package com.glisco.victus.item;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public abstract class EdibleItem extends Item {
public EdibleItem(Settings settings) {
super(settings);
}
@Override
public ItemStack finishUsing(ItemStack stack, World world, LivingEntity user) {
if (!world.isClient && user instanceof PlayerEntity player) onEaten(stack, world, player);
return super.finishUsing(stack, world, user);
}
abstract void onEaten(ItemStack stack, World world, PlayerEntity eater);
}
| 28.75 | 98 | 0.744928 |
0bfa332a84f84b0cb3bc6dd24f0d787c203513bc | 9,702 | package tk.sciwhiz12.basedefense;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.SimpleRecipeSerializer;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.crafting.IIngredientSerializer;
import net.minecraftforge.registries.ObjectHolder;
import tk.sciwhiz12.basedefense.api.capablities.ICodeHolder;
import tk.sciwhiz12.basedefense.api.capablities.IContainsCode;
import tk.sciwhiz12.basedefense.api.capablities.IKey;
import tk.sciwhiz12.basedefense.api.capablities.ILock;
import tk.sciwhiz12.basedefense.block.KeysmithBlock;
import tk.sciwhiz12.basedefense.block.LockedDoorBlock;
import tk.sciwhiz12.basedefense.block.LocksmithBlock;
import tk.sciwhiz12.basedefense.block.PadlockedDoorBlock;
import tk.sciwhiz12.basedefense.block.PortableSafeBlock;
import tk.sciwhiz12.basedefense.container.KeyringContainer;
import tk.sciwhiz12.basedefense.container.KeysmithContainer;
import tk.sciwhiz12.basedefense.container.LocksmithContainer;
import tk.sciwhiz12.basedefense.container.PortableSafeContainer;
import tk.sciwhiz12.basedefense.item.BrokenLockPiecesItem;
import tk.sciwhiz12.basedefense.item.LockedBlockItem;
import tk.sciwhiz12.basedefense.item.key.AdminKeyItem;
import tk.sciwhiz12.basedefense.item.key.KeyItem;
import tk.sciwhiz12.basedefense.item.key.KeyringItem;
import tk.sciwhiz12.basedefense.item.lock.AdminLockCoreItem;
import tk.sciwhiz12.basedefense.item.lock.AdminPadlockItem;
import tk.sciwhiz12.basedefense.item.lock.CodedLockCoreItem;
import tk.sciwhiz12.basedefense.item.lock.CodedPadlockItem;
import tk.sciwhiz12.basedefense.recipe.CodedLockRecipe;
import tk.sciwhiz12.basedefense.recipe.ColoringRecipe;
import tk.sciwhiz12.basedefense.recipe.LockedItemIngredient;
import tk.sciwhiz12.basedefense.recipe.LockedItemRecipe;
import tk.sciwhiz12.basedefense.tileentity.LockableTile;
import tk.sciwhiz12.basedefense.tileentity.LockedDoorTile;
import tk.sciwhiz12.basedefense.tileentity.PadlockedDoorTile;
import tk.sciwhiz12.basedefense.tileentity.PortableSafeTileEntity;
import tk.sciwhiz12.basedefense.util.RecipeHelper;
import tk.sciwhiz12.basedefense.util.Util;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Holds references to constants and objects created and registered by this mod.
*
* @author SciWhiz12
*/
public final class Reference {
public static final String MODID = "basedefense";
@ObjectHolder(MODID)
public static final class Blocks {
public static final KeysmithBlock KEYSMITH_TABLE = Util.Null();
public static final LocksmithBlock LOCKSMITH_TABLE = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_IRON_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_OAK_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_BIRCH_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_SPRUCE_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_JUNGLE_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_ACACIA_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_DARK_OAK_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_CRIMSON_DOOR = Util.Null();
public static final PadlockedDoorBlock PADLOCKED_WARPED_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_IRON_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_OAK_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_BIRCH_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_SPRUCE_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_JUNGLE_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_ACACIA_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_DARK_OAK_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_CRIMSON_DOOR = Util.Null();
public static final LockedDoorBlock LOCKED_WARPED_DOOR = Util.Null();
public static final PortableSafeBlock PORTABLE_SAFE = Util.Null();
// Prevent instantiation
private Blocks() {
}
}
public static final class Capabilities {
public static final Capability<ILock> LOCK = CapabilityManager.get(new CapabilityToken<>() {
});
public static final Capability<IKey> KEY = CapabilityManager.get(new CapabilityToken<>() {
});
public static final Capability<IContainsCode> CONTAINS_CODE = CapabilityManager.get(new CapabilityToken<>() {
});
public static final Capability<ICodeHolder> CODE_HOLDER = CapabilityManager.get(new CapabilityToken<>() {
});
// Prevent instantiation
private Capabilities() {
}
}
public static final CreativeModeTab ITEM_GROUP = new CreativeModeTab(MODID) {
@Override
public ItemStack makeIcon() {
return new ItemStack(Items.LOCK_CORE);
}
};
@ObjectHolder(MODID)
public static final class Items {
public static final Item BLANK_KEY = Util.Null();
public static final KeyItem KEY = Util.Null();
public static final CodedLockCoreItem LOCK_CORE = Util.Null();
public static final CodedPadlockItem PADLOCK = Util.Null();
public static final KeyringItem KEYRING = Util.Null();
public static final BrokenLockPiecesItem BROKEN_LOCK_PIECES = Util.Null();
public static final AdminKeyItem ADMIN_KEY = Util.Null();
public static final AdminLockCoreItem ADMIN_LOCK_CORE = Util.Null();
public static final AdminPadlockItem ADMIN_PADLOCK = Util.Null();
public static final BlockItem KEYSMITH_TABLE = Util.Null();
public static final BlockItem LOCKSMITH_TABLE = Util.Null();
public static final LockedBlockItem LOCKED_IRON_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_OAK_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_BIRCH_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_SPRUCE_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_JUNGLE_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_ACACIA_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_CRIMSON_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_WARPED_DOOR = Util.Null();
public static final LockedBlockItem LOCKED_DARK_OAK_DOOR = Util.Null();
public static final LockedBlockItem PORTABLE_SAFE = Util.Null();
// Prevent instantiation
private Items() {
}
}
@ObjectHolder(MODID)
public static final class Containers {
public static final MenuType<KeysmithContainer> KEYSMITH_TABLE = Util.Null();
public static final MenuType<LocksmithContainer> LOCKSMITH_TABLE = Util.Null();
public static final MenuType<KeyringContainer> KEYRING = Util.Null();
public static final MenuType<PortableSafeContainer> PORTABLE_SAFE = Util.Null();
// Prevent instantiation
private Containers() {
}
}
@ObjectHolder(MODID)
public static final class RecipeSerializers {
public static final RecipeHelper.ShapedSerializer<LockedItemRecipe> LOCKED_ITEM = Util.Null();
public static final RecipeHelper.ShapedSerializer<CodedLockRecipe> CODED_LOCK = Util.Null();
public static final SimpleRecipeSerializer<ColoringRecipe> COLORING = Util.Null();
// Prevent instantiation
private RecipeSerializers() {
}
}
public static final class IngredientSerializers {
public static IIngredientSerializer<LockedItemIngredient> LOCKED_ITEM = Util.Null();
// Prevent instantiation
private IngredientSerializers() {
}
}
@ObjectHolder(MODID)
public static final class Sounds {
public static final SoundEvent LOCKED_DOOR_ATTEMPT = Util.Null();
public static final SoundEvent LOCKED_DOOR_RELOCK = Util.Null();
public static final SoundEvent LOCKED_DOOR_UNLOCK = Util.Null();
// Prevent instantiation
private Sounds() {
}
}
@ObjectHolder(MODID)
public static final class TileEntities {
public static final BlockEntityType<LockableTile> LOCKABLE_TILE = Util.Null();
public static final BlockEntityType<PadlockedDoorTile> PADLOCKED_DOOR = Util.Null();
public static final BlockEntityType<LockedDoorTile> LOCKED_DOOR = Util.Null();
public static final BlockEntityType<PortableSafeTileEntity> PORTABLE_SAFE = Util.Null();
// Prevent instantiation
private TileEntities() {
}
}
// Prevent instantiation
private Reference() {
}
/**
* Creates a {@link ResourceLocation} with the namespace as
* {@link Reference#MODID} and the specified path.
*
* @param path The specified path
* @return A {@code ResourceLocation} with {@link Reference#MODID} and path
*/
public static ResourceLocation modLoc(String path) {
return new ResourceLocation(MODID, checkNotNull(path));
}
}
| 45.125581 | 117 | 0.745619 |
1f1331a802b6f1ba9cd930a2ba424e968de93cf0 | 2,836 | package org.flowant.website.rest;
import java.util.UUID;
import java.util.function.BiFunction;
import javax.validation.Valid;
import org.flowant.website.model.Relation;
import org.flowant.website.repository.RelationRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RestController;
import reactor.core.publisher.Mono;
@RestController
public class RelationRest extends RepositoryRest<Relation, UUID, RelationRepository> {
public final static String PATH_RELATION = "/relation";
public final static String PATH_SEG_METHOD = "/{method}";
public final static String PATH_SEG_FOLLOWEE = "/{followee}";
public final static String METHOD = "method";
public final static String FOLLOW = "follow";
public final static String UNFOLLOW = "unfollow";
public final static String FOLLOWEE = "followee";
@PostMapping(value = PATH_RELATION)
public Mono<ResponseEntity<Relation>> post(@Valid @RequestBody Relation relation) {
return super.post(relation);
}
@PostMapping(value = PATH_RELATION + PATH_SEG_METHOD + PATH_SEG_ID + PATH_SEG_FOLLOWEE)
public Mono<ResponseEntity<Relation>> put(
@PathVariable(value = METHOD) String method,
@PathVariable(value = ID) String id,
@PathVariable(value = FOLLOWEE) String followee) {
BiFunction<UUID, UUID, Mono<UUID>> m;
switch (method.toLowerCase()) {
case FOLLOW:
m = repo::follow;
break;
case UNFOLLOW:
m = repo::unfollow;
break;
default:
return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
UUID follower = UUID.fromString(id);
return m.apply(follower, UUID.fromString(followee))
.then(super.getById(follower));
}
@PutMapping(value = PATH_RELATION)
public Mono<ResponseEntity<Relation>> put(@Valid @RequestBody Relation relation) {
return super.put(relation);
}
@GetMapping(value = PATH_RELATION + PATH_SEG_ID)
public Mono<ResponseEntity<Relation>> getById(@PathVariable(value = ID) String id) {
return super.getById(UUID.fromString(id));
}
@DeleteMapping(value = PATH_RELATION + PATH_SEG_ID)
public Mono<ResponseEntity<Void>> deleteById(@PathVariable(value = ID) String id) {
return super.deleteById(UUID.fromString(id));
}
}
| 35.898734 | 91 | 0.714386 |
b9192b58fe9c154981be84c77341eb4359b3944d | 7,903 | package com.bellotapps.the_messenger.consumer;
import com.bellotapps.the_messenger.commons.Message;
import com.bellotapps.the_messenger.commons.headers.MessageType;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* An adapter of a {@link TypedMessageHandler.Builder} to be used in the context of a parent builder.
*
* @param <P> The concrete type of parent builder.
*/
public final class TypedMessageHandlerBuilderWrapper<P> {
/**
* A builder of type {@code P} that creates this builder.
*/
private final P parentBuilder;
/**
* The {@link TypedMessageHandler.Builder} being wrapped (the building process is delegated to it).
*/
private final TypedMessageHandler.Builder typedMessageHandlerBuilder;
/**
* A {@link BiConsumer} that takes the parent and a {@link MessageHandler} that will be built with the wrapped
* {@link TypedMessageHandler.Builder} and sets the latter in the former.
*/
private final BiConsumer<P, TypedMessageHandler> typedMessageHandlerSetter;
/**
* Private Constructor. To get an instance of this wrapper us {@link #createForParent(Object, BiConsumer)}.
*
* @param parentBuilder A builder of type {@code P} that creates this builder.
* @param typedMessageHandlerSetter A {@link BiConsumer} that takes the parent and a {@link MessageHandler}
* that will be built with the wrapped
* * {@link TypedMessageHandler.Builder} and sets the latter in the former.
*/
private TypedMessageHandlerBuilderWrapper(
final P parentBuilder,
final BiConsumer<P, TypedMessageHandler> typedMessageHandlerSetter) {
this.parentBuilder = parentBuilder;
this.typedMessageHandlerSetter = typedMessageHandlerSetter;
this.typedMessageHandlerBuilder = TypedMessageHandler.Builder.create();
}
/**
* Builds the configured {@link TypedMessageHandler}.
*
* @return The created {@link TypedMessageHandler}.
*/
private TypedMessageHandler build() {
return typedMessageHandlerBuilder.build();
}
/**
* Configures a {@link MessageHandler} for the given {@code type}.
*
* @param type The type to be handled by the given {@code handler}.
* @param handler The {@link MessageHandler} that will handle {@link Message}s of the given {@code type}.
* @return {@code this} for method chaining.
*/
public TypedMessageHandlerBuilderWrapper<P> handleTypeWith(final String type, final MessageHandler handler) {
typedMessageHandlerBuilder.handleTypeWith(type, handler);
return this;
}
/**
* Sets a {@link MessageHandler} for simple {@link Message}s.
*
* @param messageHandler A {@link MessageHandler} for simple {@link Message}s.
* @return {@code this} for method chaining.
* @see MessageType#SIMPLE
*/
public TypedMessageHandlerBuilderWrapper<P> handleSimpleMessageWith(final MessageHandler messageHandler) {
typedMessageHandlerBuilder.handleSimpleMessageWith(messageHandler);
return this;
}
/**
* Sets a {@link MessageHandler} for reply {@link Message}s.
*
* @param messageHandler A {@link MessageHandler} for reply {@link Message}s.
* @return {@code this} for method chaining.
* @see MessageType#REPLY
*/
public TypedMessageHandlerBuilderWrapper<P> handleReplyMessageWith(final MessageHandler messageHandler) {
typedMessageHandlerBuilder.handleReplyMessageWith(messageHandler);
return this;
}
/**
* Sets a {@link MessageHandler} for command {@link Message}s.
*
* @param messageHandler A {@link MessageHandler} for reply {@link Message}s.
* @return {@code this} for method chaining.
* @see MessageType#COMMAND
*/
public TypedMessageHandlerBuilderWrapper<P> handleCommandMessageWith(final MessageHandler messageHandler) {
typedMessageHandlerBuilder.handleCommandMessageWith(messageHandler);
return this;
}
/**
* Replaces all the configured {@link MessageHandler}s with the given {@code messageHandlers}.
*
* @param messageHandlers The new {@link MessageHandler}s.
* @return {@code this} for method chaining.
*/
public TypedMessageHandlerBuilderWrapper<P> replaceHandlers(final Map<String, MessageHandler> messageHandlers) {
typedMessageHandlerBuilder.replaceHandlers(messageHandlers);
return this;
}
/**
* Configures all the given {@code messageHandlers}.
*
* @param messageHandlers The {@link MessageHandler}s to be configured.
* @return {@code this} for method chaining.
*/
public TypedMessageHandlerBuilderWrapper<P> addHandlers(final Map<String, MessageHandler> messageHandlers) {
typedMessageHandlerBuilder.addHandlers(messageHandlers);
return this;
}
/**
* Configures the default {@link MessageHandler}
* (will handle typed {@link Message}s whose type has no {@link MessageHandler} configured).
*
* @param defaultMessageHandler The default {@link MessageHandler}.
* @return {@code this} for method chaining.
*/
public TypedMessageHandlerBuilderWrapper<P> defaultHandler(final MessageHandler defaultMessageHandler) {
typedMessageHandlerBuilder.defaultHandler(defaultMessageHandler);
return this;
}
/**
* Creates a {@link CommandMessageHandlerBuilderWrapper} to configure a {@link CommandMessageHandler}.
*
* @return A {@link CommandMessageHandlerBuilderWrapper} that uses this builder as a parent.
* @apiNote Calling {@link CommandMessageHandlerBuilderWrapper#continueWithParentBuilder()}
* will replace the {@link MessageHandler} set with the {@link #handleCommandMessageWith(MessageHandler)}
* method.
* @see CommandMessageHandler
* @see CommandMessageHandler.Builder
* @see CommandMessageHandlerBuilderWrapper
*/
public CommandMessageHandlerBuilderWrapper<TypedMessageHandlerBuilderWrapper<P>> configureCommandMessageHandlers() {
return CommandMessageHandlerBuilderWrapper
.createForParent(this, TypedMessageHandlerBuilderWrapper::handleCommandMessageWith);
}
/**
* Clears this builder.
*
* @return {@code this} for method chaining.
*/
public TypedMessageHandlerBuilderWrapper<P> clear() {
typedMessageHandlerBuilder.clear();
return this;
}
/**
* Continues with the builder of type {@code P}, calling the {@link #typedMessageHandlerBuilder} with
* the parent builder and the {@link TypedMessageHandler} that is created by this builder wrapper.
*
* @return The parent builder this builder wrapper.
*/
public P continueWithParentBuilder() {
this.typedMessageHandlerSetter.accept(parentBuilder, build());
return parentBuilder;
}
/**
* Creates a {@link TypedMessageHandlerBuilderWrapper} of type {@code T}.
*
* @param parentBuilder A builder of type {@code T} that creates this builder.
* @param typedHandlerSetter A {@link BiConsumer} that takes the parent and a {@link MessageHandler}
* that will be built with the wrapped
* {@link CommandMessageHandler.Builder}, and sets the latter in the former.
* @param <T> The concrete type of parent builder.
* @return The created {@link CommandMessageHandlerBuilderWrapper}.
*/
public static <T> TypedMessageHandlerBuilderWrapper<T> createForParent(
final T parentBuilder,
final BiConsumer<T, TypedMessageHandler> typedHandlerSetter) {
return new TypedMessageHandlerBuilderWrapper<>(parentBuilder, typedHandlerSetter);
}
}
| 40.116751 | 120 | 0.687967 |
b855807f41549eb6538a49496f8c943e30406526 | 1,609 | package com.tobiascode.marvelclient.rest.model;
import java.security.NoSuchAlgorithmException;
import java.time.LocalTime;
import java.util.Optional;
import javax.el.PropertyNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tobiascode.marvelclient.rest.util.Md5Creator;
import com.tobiascode.marvelclient.service.constants.Property;
import com.tobiascode.marvelclient.util.Configuration;
public final class MarvelAuthorisationKey {
private final Logger logger = LoggerFactory.getLogger(MarvelAuthorisationKey.class);
private final String ts;
private final String privateKey;
private final String publicKey;
public MarvelAuthorisationKey() {
privateKey = Configuration.getProperty(Property.PRIVATE_KEY).orElseThrow(() -> new PropertyNotFoundException(Property.PRIVATE_KEY));
publicKey = Configuration.getProperty(Property.PUBLIC_KEY).orElseThrow(() -> new PropertyNotFoundException(Property.PUBLIC_KEY));
ts = LocalTime.now().toString().replace(":", "").replace(".", "");
}
public MarvelAuthorisationKey(String ts, String privateKey, String publicKey) {
this.ts = ts;
this.privateKey = privateKey;
this.publicKey = publicKey;
}
public Optional<String> getTs() {
return Optional.ofNullable(ts);
}
public Optional<String> getHash() {
try {
return new Md5Creator(ts + privateKey + publicKey).getHash();
} catch (NoSuchAlgorithmException e) {
logger.error(e.getMessage(), e);
}
return Optional.empty();
}
}
| 33.520833 | 140 | 0.717837 |
8503eabc665ee13185f5f3e17b74e6d9940b585b | 2,601 | package com.ucar.zkdoctor.service.machine.impl;
import com.ucar.zkdoctor.dao.mysql.MachineStateDao;
import com.ucar.zkdoctor.dao.mysql.MachineStateLogDao;
import com.ucar.zkdoctor.pojo.po.MachineState;
import com.ucar.zkdoctor.pojo.po.MachineStateLog;
import com.ucar.zkdoctor.service.machine.MachineStateService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
* Description: 机器状态服务接口实现类
* Created on 2018/1/11 15:15
*
* @author 吕小玲([email protected])
*/
@Service
public class MachineStateServiceImpl implements MachineStateService {
@Resource
private MachineStateDao machineStateDao;
@Resource
private MachineStateLogDao machineStateLogDao;
@Override
public boolean mergeMachineState(MachineState machineState) {
if (machineState == null) {
return false;
}
return machineStateDao.insertMachineState(machineState);
}
@Override
public MachineState getMachineStateByMachineId(int machineId) {
return machineStateDao.getMachineStateByMachineId(machineId);
}
@Override
public boolean deleteMachineStateByMachineId(int machineId) {
return machineStateDao.deleteMachineStateByMachineId(machineId);
}
@Override
public boolean batchInsertMachineStateLogs(List<MachineStateLog> machineStateLogList) {
if (CollectionUtils.isEmpty(machineStateLogList)) {
return false;
}
return machineStateLogDao.batchInsertMachineStateLogs(machineStateLogList);
}
@Override
public boolean insertMachineStateLogs(MachineStateLog machineStateLog) {
if (machineStateLog == null) {
return false;
}
return machineStateLogDao.insertMachineStateLogs(machineStateLog);
}
@Override
public List<MachineStateLog> getMachineStateLogByMachine(int machineId, Date startDate, Date endDate) {
return machineStateLogDao.getMachineStateLogByMachine(machineId, startDate, endDate);
}
@Override
public boolean cleanMachineStateLogData(Date endDate) {
return machineStateLogDao.cleanMachineStateLogData(endDate);
}
@Override
public Long cleanMachineStateLogCount(Date endDate) {
return machineStateLogDao.cleanMachineStateLogCount(endDate);
}
@Override
public MachineStateLog getMachineStateLogByTime(String host, Date dateTime) {
return machineStateLogDao.getMachineStateLogByTime(host, dateTime);
}
}
| 30.964286 | 107 | 0.747789 |
027462b93a659a8d6b6b64e7ec4c88b010dea025 | 3,063 | package uk.co.codelity.event.sourcing.core.utils.reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
public class ReflectionUtility {
static Logger logger = LoggerFactory.getLogger(ReflectionUtility.class);
private ReflectionUtility(){
}
public static Set<Method> getMethodsWithAnnotation(String packageName, Class<? extends Annotation> annotation)
throws IOException, URISyntaxException, ClassNotFoundException {
requireNonNull(packageName);
requireNonNull(annotation);
Set<Class<?>> classes = getClasses(packageName);
return classes.stream()
.flatMap(c -> Arrays.stream(c.getMethods()))
.filter(method -> nonNull(method.getAnnotation(annotation)))
.collect(Collectors.toSet());
}
public static Set<Class<?>> getClassesWithAnnotation(String packageName, Class<? extends Annotation> annotation)
throws IOException, URISyntaxException, ClassNotFoundException {
requireNonNull(packageName);
requireNonNull(annotation);
Set<Class<?>> classes = getClasses(packageName);
return classes.stream().filter(c -> nonNull(c.getAnnotation(annotation)))
.collect(Collectors.toSet());
}
public static Optional<Class<?>> getAnyClassWithAnnotation(String packageName, Class<? extends Annotation> annotation)
throws IOException, URISyntaxException, ClassNotFoundException {
requireNonNull(packageName);
requireNonNull(annotation);
Set<Class<?>> classes = getClasses(packageName);
return classes.stream().filter(c -> nonNull(c.getAnnotation(annotation)))
.findAny();
}
public static Set<Class<?>> getClasses(String packageName)
throws IOException, URISyntaxException, ClassNotFoundException {
requireNonNull(packageName);
Enumeration<URL> urls = getResources(packageName);
Set<Class<?>> result = new HashSet<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
ResourceLookup resourceLookup = ResourceLookupFactory.create(url, packageName);
if (nonNull(resourceLookup)) {
Set<Class<?>> list = resourceLookup.getClasses();
result.addAll(list);
}
}
return result;
}
private static Enumeration<URL> getResources(String packageName) throws IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return classLoader.getResources(packageName.replaceAll("[.]", "/"));
}
}
| 35.206897 | 122 | 0.688214 |
99bfe91ca1da7a4201fd467308d18d02eb8cedc7 | 2,724 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.util.collections;
import org.broad.igv.util.collections.IntArrayList;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author jrobinso
*/
public class IntArrayListTest {
private static final int NUM_POINTS = 10000000;
public IntArrayListTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void test() {
IntArrayList al = new IntArrayList(10);
long t0 = System.currentTimeMillis();
for (int i = 0; i < NUM_POINTS; i++) {
al.add(i);
}
int[] values = al.toArray();
assertEquals(NUM_POINTS, values.length);
assertEquals(2, values[2]);
System.out.println("IntArrayList time: " + (System.currentTimeMillis() - t0));
}
@Test
public void testAddAll() {
IntArrayList aList = new IntArrayList(40);
for(int i=0; i<30; i++) {
aList.add(i);
}
IntArrayList aList2 = new IntArrayList(20);
for(int i=0; i<20; i++) {
aList2.add(i);
}
aList.addAll(aList2);
for(int i=0; i<30; i++) {
assertEquals(i, aList.get(i));
}
for(int i=30; i<50; i++) {
assertEquals(i-30, aList.get(i));
}
}
} | 28.673684 | 86 | 0.657122 |
f3ec41988e883139b28c009a0da2acc094767154 | 426 | /**
*
* Copyright (c) 2016
* All rights reserved.
*
* @Title PCHandler.java
* @Package com.probestar.pc.pipeline
* @author ProbeStar
* @Email [email protected]
* @QQ 344137375
* @date 2016年6月14日 下午4:52:25
* @version V1.0
* @Description
*
*/
package com.probestar.pc.pipeline;
public abstract class PCHandler {
public abstract void handle(PCContext context);
public void caughtException(Throwable t) {
}
}
| 16.384615 | 48 | 0.697183 |
d2ce2a8d4ddb07328f6e20b225c1c2bebe4413ea | 1,418 | package ru.i_novus.ms.rdm.api.async;
import org.springframework.data.domain.Sort;
import ru.i_novus.ms.rdm.api.model.AbstractCriteria;
import javax.ws.rs.QueryParam;
import java.util.List;
import java.util.UUID;
/**
* Асинхронная операция: Критерий поиска.
*/
public class AsyncOperationLogEntryCriteria extends AbstractCriteria {
public static final Sort.Order DEFAULT_ORDER = Sort.Order.desc("tsStart");
@QueryParam("id")
private UUID id;
@QueryParam("operationType")
private AsyncOperationTypeEnum operationType;
@QueryParam("code")
private String code;
@QueryParam("status")
private AsyncOperationStatusEnum status;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public AsyncOperationTypeEnum getOperationType() {
return operationType;
}
public void setOperationType(AsyncOperationTypeEnum operationType) {
this.operationType = operationType;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public AsyncOperationStatusEnum getStatus() {
return status;
}
public void setStatus(AsyncOperationStatusEnum status) {
this.status = status;
}
@Override
protected List<Sort.Order> getDefaultOrders() {
return List.of(DEFAULT_ORDER);
}
}
| 21.484848 | 78 | 0.679126 |
84848d211d6f279657f13d1783783e77fd4ab354 | 24,143 | package de.jmonitoring.DBOperations;
import java.sql.PreparedStatement;
import de.jmonitoring.base.buildings.BuildingInformation;
import de.jmonitoring.base.buildings.BuildingProperties;
import de.jmonitoring.base.Messages;
import de.jmonitoring.base.MoniSoftConstants;
import de.jmonitoring.base.sensors.SensorProperties;
import de.jmonitoring.utils.UnitCalulation.UnitInformation;
import de.jmonitoring.Cluster.Cluster;
import java.sql.Connection;
import de.jmonitoring.References.ReferenceDescription;
import de.jmonitoring.References.ReferenceValue;
import de.jmonitoring.base.MoniSoft;
import de.jmonitoring.utils.UnitCalulation.Unit;
import de.jmonitoring.utils.swing.EDT;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
/**
* This class is responsible for querying the database entries and fill all the
* lists necessary for operation:<p> SensorList<br> BuildingList<br>
* UnitList<br>Reference values<br>Sensor collections
*
* @author togro
*/
public class ListFiller {
private ch.qos.logback.classic.Logger logger = MoniSoft.getInstance().getLogger();
/**
* Reads from T_Buildings, creates {@link BuildingProperties} for each
* building and fills the global list of buildings
*
* @return A List of {@link BuildingProperties}
*/
public ArrayList<BuildingProperties> readBuildingList() {
EDT.never("readBuildingList");
Connection myConn = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList<BuildingProperties> buildingList = new ArrayList<BuildingProperties>(100);
Messages.showMessage(java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.LESE GEBÄUDELISTE"), true);
BuildingProperties props;
ArrayList<Integer> idList;
String sensorCollectionIDs;
try {
myConn = DBConnector.openConnection();
stmt = myConn.createStatement();
// get list of all columns in sensor table
stmt = myConn.createStatement();
Set<String> columnNames = new HashSet<String>();
stmt.executeQuery("show columns from " + MoniSoftConstants.BUILDING_TABLE);
rs = stmt.getResultSet();
while (rs.next()) {
columnNames.add(rs.getString(1));
}
rs = stmt.executeQuery("select * from " + MoniSoftConstants.BUILDING_TABLE);
while (rs.next()) {
props = new BuildingProperties();
if (columnNames.contains(MoniSoftConstants.BUILDING_NAME)) {
props.setBuildingName(rs.getString(MoniSoftConstants.BUILDING_NAME));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_ID)) {
props.setBuildingID(returnInteger(rs, MoniSoftConstants.BUILDING_ID));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_STREET)) {
props.setStreet(rs.getString(MoniSoftConstants.BUILDING_STREET));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_CONTACT)) {
props.setPlz(rs.getInt(MoniSoftConstants.BUILDING_PLZ));
props.setContact(rs.getString(MoniSoftConstants.BUILDING_CONTACT));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_CITY)) {
props.setCity(rs.getString(MoniSoftConstants.BUILDING_CITY));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_PHONE)) {
props.setPhone(returnLong(rs, MoniSoftConstants.BUILDING_PHONE));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_NETWORKING)) {
props.setNetworking(rs.getString(MoniSoftConstants.BUILDING_NETWORKING));
}
if (columnNames.contains(MoniSoftConstants.BUILDING_DESCRIPTION)) {
props.setBuildingDescription(rs.getString(MoniSoftConstants.BUILDING_DESCRIPTION));
}
// Die SensorCollections des Gebäudes holen und numerisch Umwandeln
idList = new ArrayList<Integer>(36);
sensorCollectionIDs = rs.getString(MoniSoftConstants.BUILDING_COLLECTIONIDS);
if (sensorCollectionIDs != null) {
for (String entry : Arrays.asList(sensorCollectionIDs.split(","))) {
if (!entry.isEmpty() && Integer.valueOf(entry) != null) {
idList.add(Integer.valueOf(entry));
}
}
}
// props.setSensorCollecions(idList);
// props.setObjectID(rs.getInt(MoniSoftConstants.BUILDING_OBJECT));
buildingList.add(props);
}
Messages.showMessage(" " + (buildingList.size()) + " " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.BUILDINGSREAD") + "\n", true);
} catch (SQLException e) {
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.ERROR") + " " + e.getMessage() + "\n", true);
logger.error(e.getMessage());
Messages.showException(e);
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
DBConnector.closeConnection(myConn, stmt, rs);
return buildingList;
}
}
/**
* Reads from T_Sensors, creates {@link SensorProperties} for each sensor
* and fills the global list of sensors
*
* @return A List of {@link SensorProperties}
*/
public ArrayList<SensorProperties> readSensorList() {
EDT.never("readSensorList");
Connection myConn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<SensorProperties> sensorList = new ArrayList<SensorProperties>(1024);
int id;
Messages.showMessage(java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.LESE MESSPUNKTLISTE"), true);
SensorProperties props;
try {
myConn = DBConnector.openConnection();
// get list of all columns in sensor table
Statement s = myConn.createStatement();
Set<String> columnNames = new HashSet<String>();
s.executeQuery("show columns from " + MoniSoftConstants.SENSOR_TABLE);
rs = s.getResultSet();
while (rs.next()) {
columnNames.add(rs.getString(1));
}
pstmt = myConn.prepareStatement(PreparedStatements.SELECT_ALL_FROM_SENSORTABLE);
rs = pstmt.executeQuery();
while (rs.next()) {
id = rs.getInt(MoniSoftConstants.SENSOR_ID);
props = new SensorProperties(id);
if (columnNames.contains(MoniSoftConstants.SENSOR_NAME)) {
props.setSensorName(rs.getString(MoniSoftConstants.SENSOR_NAME));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_DESCRIPTION)) {
props.setSensorDescription(rs.getString(MoniSoftConstants.SENSOR_DESCRIPTION));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_UNIT_ID)) {
props.setSensorUnit(UnitInformation.getUnitFormID(rs.getInt(MoniSoftConstants.SENSOR_UNIT_ID)));
}
if (columnNames.contains(MoniSoftConstants.IS_MANUAL)) {
props.setManual(rs.getBoolean(MoniSoftConstants.IS_MANUAL));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_FACTOR)) {
props.setFactor(returnDouble(rs, MoniSoftConstants.SENSOR_FACTOR));
}
if (columnNames.contains(MoniSoftConstants.IS_COUNTER)) {
props.setCounter(rs.getBoolean(MoniSoftConstants.IS_COUNTER));
}
if (columnNames.contains(MoniSoftConstants.MIN_WORKDAY)) {
props.setWTLimits(returnInteger(rs, MoniSoftConstants.MIN_WORKDAY), MoniSoftConstants.MINIMUM);
}
if (columnNames.contains(MoniSoftConstants.MAX_WORKDAY)) {
props.setWTLimits(returnInteger(rs, MoniSoftConstants.MAX_WORKDAY), MoniSoftConstants.MAXIMUM);
}
if (columnNames.contains(MoniSoftConstants.MIN_WEEKEND)) {
props.setWELimits(returnInteger(rs, MoniSoftConstants.MIN_WEEKEND), MoniSoftConstants.MINIMUM);
}
if (columnNames.contains(MoniSoftConstants.MAX_WEEKEND)) {
props.setWELimits(returnInteger(rs, MoniSoftConstants.MAX_WEEKEND), MoniSoftConstants.MAXIMUM);
}
if (columnNames.contains(MoniSoftConstants.MAX_WORKDAY_CHANGETIME)) {
props.setMaxChangeTimes(returnLong(rs, MoniSoftConstants.MAX_WORKDAY_CHANGETIME), MoniSoftConstants.WORKDAY);
}
if (columnNames.contains(MoniSoftConstants.MAX_WEEKEND_CHANGETIME)) {
props.setMaxChangeTimes(returnLong(rs, MoniSoftConstants.MAX_WEEKEND_CHANGETIME), MoniSoftConstants.WEEKEND);
}
if (columnNames.contains(MoniSoftConstants.SENSOR_INTERVAL)) {
props.setInterval(returnInteger(rs, MoniSoftConstants.SENSOR_INTERVAL));
}
if (columnNames.contains(MoniSoftConstants.IS_EVENT)) {
props.setEvent(rs.getBoolean(MoniSoftConstants.IS_EVENT));
}
if (columnNames.contains(MoniSoftConstants.VIRT_DEF)) {
props.setVirtualDefinition(rs.getString(MoniSoftConstants.VIRT_DEF));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_KEY)) {
props.setKeyName(rs.getString(MoniSoftConstants.SENSOR_KEY));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_BUILDING_ID)) {
props.setBuildingID(returnInteger(rs, MoniSoftConstants.SENSOR_BUILDING_ID)); //(rs.getObject(MoniSoftConstants.SENSOR_BUILDING_ID)));
}
if (columnNames.contains(MoniSoftConstants.IS_RESETCOUNTER)) {
props.setResetCounter(rs.getBoolean(MoniSoftConstants.IS_RESETCOUNTER));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_MEDIUM)) {
props.setMedium(rs.getString(MoniSoftConstants.SENSOR_MEDIUM));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_CONSTANT)) {
props.setConstant(returnDouble(rs, MoniSoftConstants.SENSOR_CONSTANT));
}
if (columnNames.contains(MoniSoftConstants.IS_USAGE)) {
props.setUsage(rs.getBoolean(MoniSoftConstants.IS_USAGE));
}
// AZ: MONISOFT-22: Zeitzonen
if (columnNames.contains(MoniSoftConstants.SENSOR_UTC_PLUX_X)) {
props.setUtcPlusX(returnLong(rs, MoniSoftConstants.SENSOR_UTC_PLUX_X));
}
if (columnNames.contains(MoniSoftConstants.SENSOR_SUMMERTIME)) {
props.setSummerTime(rs.getBoolean(MoniSoftConstants.SENSOR_SUMMERTIME));
}
sensorList.add(props);
}
Messages.showMessage(" " + sensorList.size() + " " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.SENSORSREAD") + "\n", true);
} catch (Exception e) {
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.ERROR") + " " + e.getMessage() + "\n", true);
logger.error(e.getMessage());
Messages.showException(e);
} finally {
DBConnector.closeConnection(myConn, pstmt, rs);
return sensorList;
}
}
/**
* Reads reference value from the database and puts them into a map with
* the<br> buildingID as key and an ArrayList of all {@link ReferenceValue}
* as content
*
* @return A map of reference values for all buildings
*/
public HashMap<Integer, ArrayList<ReferenceValue>> readBuildingReferencesMap() {
EDT.never("readBuildingReferencesMap");
HashMap<Integer, ArrayList<ReferenceValue>> map = new HashMap<Integer, ArrayList<ReferenceValue>>();
ArrayList<BuildingProperties> buildings = BuildingInformation.getBuildingList();
Integer buildingID;
Connection myConn = null;
Statement stmt = null;
ResultSet rs = null;
String name;
Double value;
// fill map for all buildings with empty lists
for (BuildingProperties building : buildings) {
map.put(building.getBuildingID(), new ArrayList<ReferenceValue>(20));
}
try {
myConn = DBConnector.openConnection();
stmt = myConn.createStatement();
rs = stmt.executeQuery("select " + MoniSoftConstants.REFERENCEMAP_NAME + "," + MoniSoftConstants.REFERENCEMAP_VALUE + "," + MoniSoftConstants.REFERENCEMAP_BUILDING_ID + " from " + MoniSoftConstants.REFERENCEMAP_TABLE);
while (rs.next()) {
name = rs.getString(1);
value = rs.getDouble(2);
buildingID = rs.getInt(3);
if (name != null && !name.isEmpty() && value != null && value != 0 && buildingID != null) {
map.get(buildingID).add(new ReferenceValue(name, value, null, null));
}
}
} catch (Exception e) {
Messages.showMessage(java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.ERROR") + " " + e.getMessage() + "\n", true);
logger.error(e.getMessage());
} finally {
DBConnector.closeConnection(myConn, stmt, rs);
}
return map;
}
/**
* Reads units from T_Units table and puts them into a map with the<br>
* unitID as key and the name of the unit as content
*
* @return A map of {@link Unit}s
*/
public HashMap<Integer, Unit> readUnitList() {
EDT.never("readUnitList");
HashMap<Integer, Unit> unitMap = new HashMap<Integer, Unit>(100);
Connection myConn = null;
Statement stmt = null;
ResultSet rs = null;
Messages.showMessage(java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.LESE EINHEITENLISTE"), true);
try {
myConn = DBConnector.openConnection();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + MoniSoftConstants.UNIT + "," + MoniSoftConstants.UNIT_ID + " from " + MoniSoftConstants.UNIT_TABLE);
while (rs.next()) {
unitMap.put(rs.getInt(2), new Unit(rs.getString(1)));
}
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.OK") + "\n", true);
} catch (Exception e) {
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.ERROR") + " " + e.getMessage() + "\n", true);
logger.error(e.getMessage());
Messages.showException(e);
} finally {
DBConnector.closeConnection(myConn, stmt, rs);
return unitMap;
}
}
/**
* Reads the refernce descriptions from the database
*
* @return A set of all {@link ReferenceDescription}s
*/
public TreeSet<ReferenceDescription> readReferenceList() {
EDT.never("readReferenceList");
Connection myConn = null;
Statement stmt = null;
ResultSet rs = null;
TreeSet<ReferenceDescription> referenceList = new TreeSet<ReferenceDescription>();
Messages.showMessage(java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.LESE LISTE DER BEZUGSGRÖSSEN"), true);
try {
myConn = DBConnector.openConnection();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + MoniSoftConstants.REFERENCENAME_NAME + "," + MoniSoftConstants.REFERENCENAME_UNIT_ID + "," + MoniSoftConstants.REFERENCENAME_DESCRIPTION + " from " + MoniSoftConstants.REFERENCES_TABLE);
while (rs.next()) {
referenceList.add(new ReferenceDescription(rs.getString(1), rs.getString(3), rs.getInt(2)));
}
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.OK") + "\n", true);
} catch (Exception e) {
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.ERROR") + " " + e.getMessage() + "\n", true);
logger.error(e.getMessage());
Messages.showException(e);
} finally {
DBConnector.closeConnection(myConn, stmt, rs);
return referenceList;
}
}
/**
* Reads a list of clusters from the database.
*
* @return A map of all {@link Cluster}s with their name as key
*/
public TreeMap<String, Cluster> readClusterList() {
EDT.never("readClusterList");
Connection myConn = null;
Statement stmt = null;
ResultSet rs = null;
TreeMap<String, Cluster> list = new TreeMap<String, Cluster>();
Messages.showMessage(java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.LESE LISTE DER CLUSTER"), true);
try {
myConn = DBConnector.openConnection();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + MoniSoftConstants.CLUSTER_NAME + "," + MoniSoftConstants.CLUSTER_KAT + "," + MoniSoftConstants.CLUSTER_BUILDINGS + " from " + MoniSoftConstants.CLUSTER_TABLE);
String name;
Integer group;
Cluster cluster;
String buildingString;
while (rs.next()) {
name = rs.getString(1);
group = rs.getInt(2);
buildingString = rs.getString(3);
// Wenn Cluster schon aufgenommen diesen holen, sonst neu erstellen
if (list.containsKey(name)) {
cluster = list.get(name);
} else {
cluster = new Cluster(name);
list.put(name, cluster);
}
// Die Gruppe der aktuellen Zeile hinzufügen (jede Zeile ist quasi eine Gruppe
cluster.setGroup(group);
// Set aus Gebäudestring generieren
TreeSet<Integer> buildingSet = buildingIDSet(buildingString);
// Alle Gebäude durchlaufen und eintragen
for (Integer building : buildingSet) {
cluster.addBuilding(group, building);
}
}
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.OK") + "\n", true);
} catch (Exception e) {
Messages.showMessage(" " + java.util.ResourceBundle.getBundle("de/jmonitoring/DBOperations/Bundle").getString("ListFiller.ERROR") + " " + e.getMessage() + "\n", true);
logger.error(e.getMessage());
Messages.showException(e);
} finally {
DBConnector.closeConnection(myConn, stmt, rs);
return list;
}
}
/**
* Reads a list of sensor collections from the database.
*
* @return A map of all sensor collections with their id as key and a
* {@link HashSet} of the assigned sensorIDs
*/
public HashMap<Integer, HashSet<Integer>> readCollectionSensors() {
EDT.never("readCollectionSensors");
Connection myConn = null;
Statement stmt = null;
ResultSet rs = null;
String[] list;
Integer collectionID;
HashMap<Integer, HashSet<Integer>> collectionSensors = new HashMap<Integer, HashSet<Integer>>();
try {
myConn = DBConnector.openConnection();
stmt = myConn.createStatement();
rs = stmt.executeQuery("select " + MoniSoftConstants.SENSORCOLLECTION_ID + "," + MoniSoftConstants.SENSORCOLLECTION_LIST + " from " + MoniSoftConstants.SENSORCOLLECTION_TABLE);
while (rs.next()) {
HashSet<Integer> idList = new HashSet<Integer>(32);
collectionID = rs.getInt(1);
list = rs.getString(2).split(",");
for (String entry : list) {
if (!entry.isEmpty()) { // Leere Strings ausfischen
idList.add(Integer.valueOf(entry));
}
}
collectionSensors.put(collectionID, idList);
}
} catch (SQLException ex) {
logger.error(ex.getMessage());
Messages.showException(ex);
} finally {
DBConnector.closeConnection(myConn, stmt, rs);
}
return collectionSensors;
}
/**
* Builds a list of {@link Integer} buildingIDs from the given
* {@link String} of comma seperated buildingIDs
*
* @param buildingString The list of buildingIDs as {@link String}
* @return A set of buildingIDs
*/
private TreeSet<Integer> buildingIDSet(String buildingString) {
TreeSet<Integer> set = new TreeSet<Integer>();
String[] s = buildingString.split(",");
for (int i = 0; i < s.length; i++) {
if (!s[i].equals("")) {
set.add(Integer.valueOf(s[i]));
}
}
return set;
}
/**
* Returns the {@link Integer} value of a column of the given
* {@link ResultSet} or
* <code>null</code> if the database field is empty.<br> The builtin
* getInt() method of {@link ResultSet} would return 0 instead.
*
* @param rs The {@link ResultSet}
* @param columName The cname of the column in question
* @return The {@link Integer} value
* @throws SQLException
*/
private Integer returnInteger(ResultSet rs, String columName) throws SQLException {
Integer i = new Integer(rs.getInt(columName));
if (rs.wasNull()) {
i = null;
}
return i;
}
/**
* Returns the {@link Long} value of a column of the given {@link ResultSet}
* or
* <code>null</code> if the database field is empty.<br> The builtin
* getLong() method of {@link ResultSet} would return 0 instead.
*
* @param rs The {@link ResultSet}
* @param columName The cname of the column in question
* @return The {@link Long} value
* @throws SQLException
*/
private Long returnLong(ResultSet rs, String columName) throws SQLException {
Long l = new Long(rs.getLong(columName));
if (rs.wasNull()) {
l = null;
}
return l;
}
/**
* Returns the {@link Double} value of a column of the given
* {@link ResultSet} or
* <code>null</code> if the database field is empty.<br> The builtin
* getLong() method of {@link ResultSet} would return 0.0 instead.
*
* @param rs The {@link ResultSet}
* @param columName The cname of the column in question
* @return The {@link Double} value
* @throws SQLException
*/
private Double returnDouble(ResultSet rs, String columName) throws SQLException {
Double d = new Double(rs.getDouble(columName));
if (rs.wasNull()) {
d = null;
}
return d;
}
}
| 47.062378 | 233 | 0.611357 |
2279e23f0c420256843fb97ab17f5c7a63fda129 | 2,015 | package com.dry3.concurrentProgramming.example.unsafe;
import com.dry3.concurrentProgramming.annotations.NotThreadSafe;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* ArrayList 是线程不安全的, 而且在ArrayList的add中代码是这样的
* public boolean add(E e) {
* ensureCapacityInternal(size + 1); // Increments modCount!!
* elementData[size++] = e;
* return true;
* }
* size++操作不是原子性的, 这样操作数组会导致数组越界问题出现
* @author Administrator
* @email [email protected]
* @date 2018/11/21
* @time 15:35
*/
@Slf4j
@NotThreadSafe
public class ArrayListTest {
private static int threadTotal = 200;
private static int clientTotal = 5000;
private static List<Integer> list = Lists.newArrayList();
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
Semaphore semaphore = new Semaphore(threadTotal);
CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
Long start = System.currentTimeMillis();
for (int i = 0; i < clientTotal; i++) {
final int count = i;
executorService.execute(() -> {
try {
semaphore.acquire();
add(count);
semaphore.release();
} catch (InterruptedException e) {
log.error("exception", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("size: {},time : {}秒", list.size(), (System.currentTimeMillis() - start) / 1000f);
}
private static void add(int i) {
list.add(i);
}
}
| 31.484375 | 100 | 0.608933 |
125cda7007c61f23f634fa911fde49dda49b18aa | 1,017 | /*
* Copyright 2016-present Open Networking Foundation
*
* 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.onosproject.rabbitmq.api;
/**
* Interface for declaring a start, publish and stop api's for mq transactions.
*/
public interface Manageable {
/**
* Establishes connection with MQ server.
*/
void start();
/**
* Publishes onos events on to MQ server.
*/
void publish();
/**
* Releases connection and channels.
*/
void stop();
}
| 26.076923 | 79 | 0.688299 |
8d65bb06add51fb07ad945353e4715362ca3bdc0 | 1,688 | package rosipetkova.cmdtester;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.reflections.Reflections;
import rosipetkova.cmdtester.interfaces.ApiTest;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.*;
class AppTest {
@Test
public void objectMapperError() throws IOException {
ObjectMapper m = mock(ObjectMapper.class);
when(m.readValue(ArgumentMatchers.<File>any(), ArgumentMatchers.<Class<Object>>any())).thenThrow(new IOException());
Reflections r = mock(Reflections.class);
App app = new App(m, r);
assertEquals(101, app.call());
}
@Test
public void testsFailError() {
ObjectMapper m = mock(ObjectMapper.class);
Reflections r = mock(Reflections.class);
class TmpTest implements ApiTest {
@Override
public boolean execute(Map<?, ?> config) {
return false;
}
}
Set<Class<? extends ApiTest>> classes = new HashSet<>();
classes.add(TmpTest.class);
when(r.getSubTypesOf(ApiTest.class)).thenReturn(classes);
App app = new App(m, r);
assertEquals(102, app.call());
}
@Test
public void success() {
ObjectMapper m = mock(ObjectMapper.class);
Reflections r = mock(Reflections.class);
App app = new App(m, r);
assertNull(app.call());
}
} | 28.610169 | 124 | 0.661137 |
d658728c953e9f707b05d05d6553f2a2bb6363f4 | 673 | package com.enioka.jqm.api;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebListener
public class Ctx implements ServletContextListener
{
static Logger log = LoggerFactory.getLogger(Ctx.class);
@Override
public void contextInitialized(ServletContextEvent sce)
{
// nothing for now
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
log.debug("Cleaning after Hibernate during WS application shutdown");
JqmClientFactory.getClient().dispose();
}
}
| 24.035714 | 77 | 0.7474 |
66c88b16a49950778a06bfee28c32557bb4a9bba | 147 | /**
* Strategy interfaces and classes for extracting URI fragment tokens and query parameters.
*/
package org.roklib.urifragmentrouting.strategy; | 36.75 | 91 | 0.802721 |
a1d5b77198a3ba978176e9d78bea6b30ea62f0fc | 899 | package com.example.gstokengame;
public class Token {
private String Id;
private String Content;
private String Created;
private String Consumed;
private String ConsumedA;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getCreated() {
return Created;
}
public void setCreated(String created) {
Created = created;
}
public String getConsumed() {
return Consumed;
}
public void setConsumed(String consumed) {
Consumed = consumed;
}
public String getConsumedA() {
return ConsumedA;
}
public void setConsumedA(String consumedA) {
ConsumedA = consumedA;
}
}
| 17.627451 | 48 | 0.600667 |
4efd811dc6cb508d7e1973d9c300a562525dc05d | 2,327 | package at.fh.ima.swengs.bartendrV2.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Entity
public class Drink {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String drinkName;
private String bar;
private double price;
@Version
@JsonIgnore
private long version;
public Drink() {
}
public Drink(String drinkName, String bar, double price, long version) {
this.drinkName = drinkName;
this.bar = bar;
this.price = price;
this.version = version;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDrinkName() {
return drinkName;
}
public void setDrinkName(String drinkName) {
this.drinkName = drinkName;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Drink)) return false;
Drink drink = (Drink) o;
return getId() == drink.getId() &&
Double.compare(drink.getPrice(), getPrice()) == 0 &&
getVersion() == drink.getVersion() &&
Objects.equals(getDrinkName(), drink.getDrinkName()) &&
Objects.equals(getBar(), drink.getBar());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getDrinkName(), getBar(), getPrice(), getVersion());
}
@Override
public String toString() {
return "Drink{" +
"id=" + id +
", drinkName='" + drinkName + '\'' +
", bar='" + bar + '\'' +
", price=" + price +
", version=" + version +
'}';
}
}
| 22.161905 | 89 | 0.558229 |
fc2621b1eab7b8fd4a537f5bc02f8ff6a39979f7 | 144 | @javax.xml.bind.annotation.XmlSchema(namespace = "http://soap.chapter4.webservices.koitoer.com/")
package webservices.chapter4.client.wsimport;
| 48 | 97 | 0.8125 |
86397c40292fdc66efe3f6cdcb30812cd4ce2267 | 43,483 | /**
* 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.falcon.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.TrustManagerUtils;
import org.apache.falcon.LifeCycle;
import org.apache.falcon.cli.FalconMetadataCLI;
import org.apache.falcon.entity.v0.Entity;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.recipe.RecipeTool;
import org.apache.falcon.recipe.RecipeToolArgs;
import org.apache.falcon.resource.APIResult;
import org.apache.falcon.resource.EntityList;
import org.apache.falcon.resource.EntitySummaryResult;
import org.apache.falcon.resource.FeedInstanceResult;
import org.apache.falcon.resource.InstancesResult;
import org.apache.falcon.resource.InstancesSummaryResult;
import org.apache.falcon.resource.LineageGraphResult;
import org.apache.hadoop.security.authentication.client.AuthenticatedURL;
import org.apache.hadoop.security.authentication.client.KerberosAuthenticator;
import org.apache.hadoop.security.authentication.client.PseudoAuthenticator;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.SecureRandom;
import java.util.List;
import java.util.Properties;
/**
* Client API to submit and manage Falcon Entities (Cluster, Feed, Process) jobs
* against an Falcon instance.
*/
public class FalconClient {
public static final String WS_HEADER_PREFIX = "header:";
public static final String USER = System.getProperty("user.name");
public static final String AUTH_URL = "api/options?" + PseudoAuthenticator.USER_NAME + "=" + USER;
private static final String FALCON_INSTANCE_ACTION_CLUSTERS = "falcon.instance.action.clusters";
private static final String FALCON_INSTANCE_SOURCE_CLUSTERS = "falcon.instance.source.clusters";
/**
* Name of the HTTP cookie used for the authentication token between the client and the server.
*/
public static final String AUTH_COOKIE = "hadoop.auth";
private static final String AUTH_COOKIE_EQ = AUTH_COOKIE + "=";
private static final KerberosAuthenticator AUTHENTICATOR = new KerberosAuthenticator();
private static final String TEMPLATE_SUFFIX = "-template.xml";
private static final String PROPERTIES_SUFFIX = ".properties";
public static final int DEFAULT_NUM_RESULTS = 10;
public static final HostnameVerifier ALL_TRUSTING_HOSTNAME_VERIFIER = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
};
private final WebResource service;
private final AuthenticatedURL.Token authenticationToken;
private final Properties clientProperties;
/**
* Create a Falcon client instance.
*
* @param falconUrl of the server to which client interacts
* @throws FalconCLIException - If unable to initialize SSL Props
*/
public FalconClient(String falconUrl) throws FalconCLIException {
this(falconUrl, new Properties());
}
/**
* Create a Falcon client instance.
*
* @param falconUrl of the server to which client interacts
* @param properties client properties
* @throws FalconCLIException - If unable to initialize SSL Props
*/
public FalconClient(String falconUrl, Properties properties) throws FalconCLIException {
try {
String baseUrl = notEmpty(falconUrl, "FalconUrl");
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
this.clientProperties = properties;
SSLContext sslContext = getSslContext();
DefaultClientConfig config = new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties(ALL_TRUSTING_HOSTNAME_VERIFIER, sslContext)
);
Client client = Client.create(config);
client.setConnectTimeout(Integer.parseInt(clientProperties.getProperty("falcon.connect.timeout",
"180000")));
client.setReadTimeout(Integer.parseInt(clientProperties.getProperty("falcon.read.timeout", "180000")));
service = client.resource(UriBuilder.fromUri(baseUrl).build());
client.resource(UriBuilder.fromUri(baseUrl).build());
authenticationToken = getToken(baseUrl);
} catch (Exception e) {
throw new FalconCLIException("Unable to initialize Falcon Client object", e);
}
}
private static SSLContext getSslContext() throws Exception {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(
null,
new TrustManager[]{TrustManagerUtils.getValidateServerCertificateTrustManager()},
new SecureRandom());
return sslContext;
}
public Properties getClientProperties() {
return clientProperties;
}
public static AuthenticatedURL.Token getToken(String baseUrl) throws FalconCLIException {
AuthenticatedURL.Token currentToken = new AuthenticatedURL.Token();
try {
URL url = new URL(baseUrl + AUTH_URL);
// using KerberosAuthenticator which falls back to PsuedoAuthenticator
// instead of passing authentication type from the command line - bad factory
HttpsURLConnection.setDefaultSSLSocketFactory(getSslContext().getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
new AuthenticatedURL(AUTHENTICATOR).openConnection(url, currentToken);
} catch (Exception ex) {
throw new FalconCLIException("Could not authenticate, " + ex.getMessage(), ex);
}
return currentToken;
}
/**
* Methods allowed on Entity Resources.
*/
protected static enum Entities {
VALIDATE("api/entities/validate/", HttpMethod.POST, MediaType.TEXT_XML),
SUBMIT("api/entities/submit/", HttpMethod.POST, MediaType.TEXT_XML),
UPDATE("api/entities/update/", HttpMethod.POST, MediaType.TEXT_XML),
SUBMITandSCHEDULE("api/entities/submitAndSchedule/", HttpMethod.POST, MediaType.TEXT_XML),
SCHEDULE("api/entities/schedule/", HttpMethod.POST, MediaType.TEXT_XML),
SUSPEND("api/entities/suspend/", HttpMethod.POST, MediaType.TEXT_XML),
RESUME("api/entities/resume/", HttpMethod.POST, MediaType.TEXT_XML),
DELETE("api/entities/delete/", HttpMethod.DELETE, MediaType.TEXT_XML),
STATUS("api/entities/status/", HttpMethod.GET, MediaType.TEXT_XML),
DEFINITION("api/entities/definition/", HttpMethod.GET, MediaType.TEXT_XML),
LIST("api/entities/list/", HttpMethod.GET, MediaType.TEXT_XML),
SUMMARY("api/entities/summary", HttpMethod.GET, MediaType.APPLICATION_JSON),
DEPENDENCY("api/entities/dependencies/", HttpMethod.GET, MediaType.TEXT_XML),
TOUCH("api/entities/touch", HttpMethod.POST, MediaType.TEXT_XML);
private String path;
private String method;
private String mimeType;
Entities(String path, String method, String mimeType) {
this.path = path;
this.method = method;
this.mimeType = mimeType;
}
}
/**
* Methods allowed on Metadata Discovery Resources.
*/
protected static enum MetadataOperations {
LIST("api/metadata/discovery/", HttpMethod.GET, MediaType.APPLICATION_JSON),
RELATIONS("api/metadata/discovery/", HttpMethod.GET, MediaType.APPLICATION_JSON),
VERTICES("api/metadata/lineage/vertices", HttpMethod.GET, MediaType.APPLICATION_JSON),
EDGES("api/metadata/lineage/edges", HttpMethod.GET, MediaType.APPLICATION_JSON),
LINEAGE("api/metadata/lineage/entities", HttpMethod.GET, MediaType.APPLICATION_JSON);
private String path;
private String method;
private String mimeType;
MetadataOperations(String path, String method, String mimeType) {
this.path = path;
this.method = method;
this.mimeType = mimeType;
}
}
/**
* Methods allowed on Process Instance Resources.
*/
protected static enum Instances {
RUNNING("api/instance/running/", HttpMethod.GET, MediaType.APPLICATION_JSON),
STATUS("api/instance/status/", HttpMethod.GET, MediaType.APPLICATION_JSON),
LIST("api/instance/list", HttpMethod.GET, MediaType.APPLICATION_JSON),
KILL("api/instance/kill/", HttpMethod.POST, MediaType.APPLICATION_JSON),
SUSPEND("api/instance/suspend/", HttpMethod.POST, MediaType.APPLICATION_JSON),
RESUME("api/instance/resume/", HttpMethod.POST, MediaType.APPLICATION_JSON),
RERUN("api/instance/rerun/", HttpMethod.POST, MediaType.APPLICATION_JSON),
LOG("api/instance/logs/", HttpMethod.GET, MediaType.APPLICATION_JSON),
SUMMARY("api/instance/summary/", HttpMethod.GET, MediaType.APPLICATION_JSON),
PARAMS("api/instance/params/", HttpMethod.GET, MediaType.APPLICATION_JSON),
LISTING("api/instance/listing/", HttpMethod.GET, MediaType.APPLICATION_JSON);
private String path;
private String method;
private String mimeType;
Instances(String path, String method, String mimeType) {
this.path = path;
this.method = method;
this.mimeType = mimeType;
}
}
protected static enum AdminOperations {
STACK("api/admin/stack", HttpMethod.GET, MediaType.TEXT_PLAIN),
VERSION("api/admin/version", HttpMethod.GET, MediaType.APPLICATION_JSON);
private String path;
private String method;
private String mimeType;
AdminOperations(String path, String method, String mimeType) {
this.path = path;
this.method = method;
this.mimeType = mimeType;
}
}
public String notEmpty(String str, String name) {
if (str == null) {
throw new IllegalArgumentException(name + " cannot be null");
}
if (str.length() == 0) {
throw new IllegalArgumentException(name + " cannot be empty");
}
return str;
}
public APIResult schedule(EntityType entityType, String entityName, String colo)
throws FalconCLIException {
return sendEntityRequest(Entities.SCHEDULE, entityType, entityName,
colo);
}
public APIResult suspend(EntityType entityType, String entityName, String colo)
throws FalconCLIException {
return sendEntityRequest(Entities.SUSPEND, entityType, entityName, colo);
}
public APIResult resume(EntityType entityType, String entityName, String colo)
throws FalconCLIException {
return sendEntityRequest(Entities.RESUME, entityType, entityName, colo);
}
public APIResult delete(EntityType entityType, String entityName)
throws FalconCLIException {
return sendEntityRequest(Entities.DELETE, entityType, entityName, null);
}
public APIResult validate(String entityType, String filePath)
throws FalconCLIException {
InputStream entityStream = getServletInputStream(filePath);
return sendEntityRequestWithObject(Entities.VALIDATE, entityType,
entityStream, null);
}
public APIResult submit(String entityType, String filePath)
throws FalconCLIException {
InputStream entityStream = getServletInputStream(filePath);
return sendEntityRequestWithObject(Entities.SUBMIT, entityType,
entityStream, null);
}
public APIResult update(String entityType, String entityName, String filePath)
throws FalconCLIException {
InputStream entityStream = getServletInputStream(filePath);
Entities operation = Entities.UPDATE;
WebResource resource = service.path(operation.path).path(entityType).path(entityName);
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(operation.mimeType).type(MediaType.TEXT_XML)
.method(operation.method, ClientResponse.class, entityStream);
checkIfSuccessful(clientResponse);
return parseAPIResult(clientResponse);
}
public APIResult submitAndSchedule(String entityType, String filePath)
throws FalconCLIException {
InputStream entityStream = getServletInputStream(filePath);
return sendEntityRequestWithObject(Entities.SUBMITandSCHEDULE,
entityType, entityStream, null);
}
public APIResult getStatus(EntityType entityType, String entityName, String colo)
throws FalconCLIException {
return sendEntityRequest(Entities.STATUS, entityType, entityName, colo);
}
public Entity getDefinition(String entityType, String entityName)
throws FalconCLIException {
return sendDefinitionRequest(Entities.DEFINITION, entityType,
entityName);
}
public EntityList getDependency(String entityType, String entityName)
throws FalconCLIException {
return sendDependencyRequest(Entities.DEPENDENCY, entityType, entityName);
}
//SUSPEND CHECKSTYLE CHECK ParameterNumberCheck
public EntityList getEntityList(String entityType, String fields, String filterBy, String filterTags,
String orderBy, String sortOrder, Integer offset,
Integer numResults, String searchPattern) throws FalconCLIException {
return sendListRequest(Entities.LIST, entityType, fields, filterBy,
filterTags, orderBy, sortOrder, offset, numResults, searchPattern);
}
public EntitySummaryResult getEntitySummary(String entityType, String cluster, String start, String end,
String fields, String filterBy, String filterTags,
String orderBy, String sortOrder,
Integer offset, Integer numResults, Integer numInstances)
throws FalconCLIException {
return sendEntitySummaryRequest(Entities.SUMMARY, entityType, cluster, start, end, fields, filterBy, filterTags,
orderBy, sortOrder, offset, numResults, numInstances);
}
public APIResult touch(String entityType, String entityName, String colo) throws FalconCLIException {
Entities operation = Entities.TOUCH;
WebResource resource = service.path(operation.path).path(entityType).path(entityName);
if (colo != null) {
resource = resource.queryParam("colo", colo);
}
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(operation.mimeType).type(MediaType.TEXT_XML)
.method(operation.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
return parseAPIResult(clientResponse);
}
public InstancesResult getRunningInstances(String type, String entity, String colo, List<LifeCycle> lifeCycles,
String filterBy, String orderBy, String sortOrder,
Integer offset, Integer numResults) throws FalconCLIException {
return sendInstanceRequest(Instances.RUNNING, type, entity, null, null,
null, null, colo, lifeCycles, filterBy, orderBy, sortOrder, offset, numResults)
.getEntity(InstancesResult.class);
}
public InstancesResult getStatusOfInstances(String type, String entity,
String start, String end,
String colo, List<LifeCycle> lifeCycles, String filterBy,
String orderBy, String sortOrder,
Integer offset, Integer numResults) throws FalconCLIException {
return sendInstanceRequest(Instances.STATUS, type, entity, start, end,
null, null, colo, lifeCycles, filterBy, orderBy, sortOrder, offset, numResults)
.getEntity(InstancesResult.class);
}
public InstancesSummaryResult getSummaryOfInstances(String type, String entity,
String start, String end,
String colo, List<LifeCycle> lifeCycles) throws FalconCLIException {
return sendInstanceRequest(Instances.SUMMARY, type, entity, start, end, null,
null, colo, lifeCycles, "", "", "", 0, DEFAULT_NUM_RESULTS).getEntity(InstancesSummaryResult.class);
}
public FeedInstanceResult getFeedListing(String type, String entity, String start,
String end, String colo)
throws FalconCLIException {
return sendInstanceRequest(Instances.LISTING, type, entity, start, end, null,
null, colo, null, "", "", "", 0, DEFAULT_NUM_RESULTS).getEntity(FeedInstanceResult.class);
}
public InstancesResult killInstances(String type, String entity, String start,
String end, String colo, String clusters,
String sourceClusters, List<LifeCycle> lifeCycles)
throws FalconCLIException, UnsupportedEncodingException {
return sendInstanceRequest(Instances.KILL, type, entity, start, end,
getServletInputStream(clusters, sourceClusters, null), null, colo, lifeCycles);
}
public InstancesResult suspendInstances(String type, String entity, String start,
String end, String colo, String clusters,
String sourceClusters, List<LifeCycle> lifeCycles)
throws FalconCLIException, UnsupportedEncodingException {
return sendInstanceRequest(Instances.SUSPEND, type, entity, start, end,
getServletInputStream(clusters, sourceClusters, null), null, colo, lifeCycles);
}
public InstancesResult resumeInstances(String type, String entity, String start,
String end, String colo, String clusters,
String sourceClusters, List<LifeCycle> lifeCycles)
throws FalconCLIException, UnsupportedEncodingException {
return sendInstanceRequest(Instances.RESUME, type, entity, start, end,
getServletInputStream(clusters, sourceClusters, null), null, colo, lifeCycles);
}
public InstancesResult rerunInstances(String type, String entity, String start,
String end, String filePath, String colo,
String clusters, String sourceClusters, List<LifeCycle> lifeCycles)
throws FalconCLIException, IOException {
StringBuilder buffer = new StringBuilder();
if (filePath != null) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filePath));
String str;
while ((str = in.readLine()) != null) {
buffer.append(str).append("\n");
}
} finally {
IOUtils.closeQuietly(in);
}
}
String temp = (buffer.length() == 0) ? null : buffer.toString();
return sendInstanceRequest(Instances.RERUN, type, entity, start, end,
getServletInputStream(clusters, sourceClusters, temp), null, colo, lifeCycles);
}
public InstancesResult getLogsOfInstances(String type, String entity, String start,
String end, String colo, String runId,
List<LifeCycle> lifeCycles, String filterBy,
String orderBy, String sortOrder, Integer offset, Integer numResults)
throws FalconCLIException {
return sendInstanceRequest(Instances.LOG, type, entity, start, end,
null, runId, colo, lifeCycles, filterBy, orderBy, sortOrder, offset, numResults)
.getEntity(InstancesResult.class);
}
public InstancesResult getParamsOfInstance(String type, String entity,
String start, String colo,
List<LifeCycle> lifeCycles)
throws FalconCLIException, UnsupportedEncodingException {
return sendInstanceRequest(Instances.PARAMS, type, entity,
start, null, null, null, colo, lifeCycles);
}
public String getThreadDump() throws FalconCLIException {
return sendAdminRequest(AdminOperations.STACK);
}
public String getVersion() throws FalconCLIException {
return sendAdminRequest(AdminOperations.VERSION);
}
public int getStatus() throws FalconCLIException {
AdminOperations job = AdminOperations.VERSION;
ClientResponse clientResponse = service.path(job.path)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(job.mimeType).type(MediaType.TEXT_PLAIN)
.method(job.method, ClientResponse.class);
return clientResponse.getStatus();
}
public String getDimensionList(String dimensionType, String cluster) throws FalconCLIException {
return sendMetadataDiscoveryRequest(MetadataOperations.LIST, dimensionType, null, cluster);
}
public LineageGraphResult getEntityLineageGraph(String pipelineName) throws FalconCLIException {
MetadataOperations operation = MetadataOperations.LINEAGE;
WebResource resource = service.path(operation.path)
.queryParam(FalconMetadataCLI.PIPELINE_OPT, pipelineName);
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(operation.mimeType).type(operation.mimeType)
.method(operation.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
return clientResponse.getEntity(LineageGraphResult.class);
}
public String getDimensionRelations(String dimensionType, String dimensionName) throws FalconCLIException {
return sendMetadataDiscoveryRequest(MetadataOperations.RELATIONS, dimensionType, dimensionName, null);
}
/**
* Converts a InputStream into ServletInputStream.
*
* @param filePath - Path of file to stream
* @return ServletInputStream
* @throws FalconCLIException
*/
private InputStream getServletInputStream(String filePath)
throws FalconCLIException {
if (filePath == null) {
return null;
}
InputStream stream;
try {
stream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
throw new FalconCLIException("File not found:", e);
}
return stream;
}
private InputStream getServletInputStream(String clusters,
String sourceClusters, String properties)
throws FalconCLIException, UnsupportedEncodingException {
InputStream stream;
StringBuilder buffer = new StringBuilder();
if (clusters != null) {
buffer.append(FALCON_INSTANCE_ACTION_CLUSTERS).append('=').append(clusters).append('\n');
}
if (sourceClusters != null) {
buffer.append(FALCON_INSTANCE_SOURCE_CLUSTERS).append('=').append(sourceClusters).append('\n');
}
if (properties != null) {
buffer.append(properties);
}
stream = new ByteArrayInputStream(buffer.toString().getBytes());
return (buffer.length() == 0) ? null : stream;
}
private APIResult sendEntityRequest(Entities entities, EntityType entityType,
String entityName, String colo) throws FalconCLIException {
WebResource resource = service.path(entities.path)
.path(entityType.toString().toLowerCase()).path(entityName);
if (colo != null) {
resource = resource.queryParam("colo", colo);
}
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(entities.mimeType).type(MediaType.TEXT_XML)
.method(entities.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
// should be removed return parseAPIResult(clientResponse);
return clientResponse.getEntity(APIResult.class);
}
private WebResource addParamsToResource(WebResource resource,
String start, String end, String runId, String colo,
String fields, String filterBy, String tags,
String orderBy, String sortOrder, Integer offset,
Integer numResults, Integer numInstances, String searchPattern) {
if (!StringUtils.isEmpty(fields)) {
resource = resource.queryParam("fields", fields);
}
if (!StringUtils.isEmpty(tags)) {
resource = resource.queryParam("tags", tags);
}
if (!StringUtils.isEmpty(filterBy)) {
resource = resource.queryParam("filterBy", filterBy);
}
if (!StringUtils.isEmpty(orderBy)) {
resource = resource.queryParam("orderBy", orderBy);
}
if (!StringUtils.isEmpty(sortOrder)) {
resource = resource.queryParam("sortOrder", sortOrder);
}
if (!StringUtils.isEmpty(start)) {
resource = resource.queryParam("start", start);
}
if (!StringUtils.isEmpty(end)) {
resource = resource.queryParam("end", end);
}
if (runId != null) {
resource = resource.queryParam("runid", runId);
}
if (colo != null) {
resource = resource.queryParam("colo", colo);
}
if (offset != null) {
resource = resource.queryParam("offset", offset.toString());
}
if (numResults != null) {
resource = resource.queryParam("numResults", numResults.toString());
}
if (numInstances != null) {
resource = resource.queryParam("numInstances", numInstances.toString());
}
if (!StringUtils.isEmpty(searchPattern)) {
resource = resource.queryParam("pattern", searchPattern);
}
return resource;
}
private EntitySummaryResult sendEntitySummaryRequest(Entities entities, String entityType, String cluster,
String start, String end,
String fields, String filterBy, String filterTags,
String orderBy, String sortOrder, Integer offset, Integer numResults,
Integer numInstances) throws FalconCLIException {
WebResource resource = service.path(entities.path).path(entityType);
if (!StringUtils.isEmpty(cluster)) {
resource = resource.queryParam("cluster", cluster);
}
resource = addParamsToResource(resource, start, end, null, null,
fields, filterBy, filterTags,
orderBy, sortOrder,
offset, numResults, numInstances, null);
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(entities.mimeType).type(MediaType.TEXT_XML)
.method(entities.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
return clientResponse.getEntity(EntitySummaryResult.class);
}
//RESUME CHECKSTYLE CHECK ParameterNumberCheck
private Entity sendDefinitionRequest(Entities entities, String entityType,
String entityName) throws FalconCLIException {
ClientResponse clientResponse = service
.path(entities.path).path(entityType).path(entityName)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(entities.mimeType).type(MediaType.TEXT_XML)
.method(entities.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
String entity = clientResponse.getEntity(String.class);
return Entity.fromString(EntityType.getEnum(entityType), entity);
}
private EntityList sendDependencyRequest(Entities entities, String entityType,
String entityName) throws FalconCLIException {
ClientResponse clientResponse = service
.path(entities.path).path(entityType).path(entityName)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(entities.mimeType).type(MediaType.TEXT_XML)
.method(entities.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
return parseEntityList(clientResponse);
}
private APIResult sendEntityRequestWithObject(Entities entities, String entityType,
Object requestObject, String colo) throws FalconCLIException {
WebResource resource = service.path(entities.path)
.path(entityType);
if (colo != null) {
resource = resource.queryParam("colo", colo);
}
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(entities.mimeType).type(MediaType.TEXT_XML)
.method(entities.method, ClientResponse.class, requestObject);
checkIfSuccessful(clientResponse);
//remove this return parseAPIResult(clientResponse);
return clientResponse.getEntity(APIResult.class);
}
//SUSPEND CHECKSTYLE CHECK VisibilityModifierCheck
private InstancesResult sendInstanceRequest(Instances instances, String type,
String entity, String start, String end, InputStream props,
String runid, String colo,
List<LifeCycle> lifeCycles) throws FalconCLIException {
return sendInstanceRequest(instances, type, entity, start, end, props,
runid, colo, lifeCycles, "", "", "", 0, DEFAULT_NUM_RESULTS)
.getEntity(InstancesResult.class);
}
private ClientResponse sendInstanceRequest(Instances instances, String type, String entity,
String start, String end, InputStream props, String runid, String colo,
List<LifeCycle> lifeCycles, String filterBy, String orderBy, String sortOrder,
Integer offset, Integer numResults) throws FalconCLIException {
checkType(type);
WebResource resource = service.path(instances.path).path(type)
.path(entity);
resource = addParamsToResource(resource, start, end, runid, colo,
null, filterBy, null, orderBy, sortOrder, offset, numResults, null, null);
if (lifeCycles != null) {
checkLifeCycleOption(lifeCycles, type);
for (LifeCycle lifeCycle : lifeCycles) {
resource = resource.queryParam("lifecycle", lifeCycle.toString());
}
}
ClientResponse clientResponse;
if (props == null) {
clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(instances.mimeType)
.method(instances.method, ClientResponse.class);
} else {
clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(instances.mimeType)
.method(instances.method, ClientResponse.class, props);
}
checkIfSuccessful(clientResponse);
return clientResponse;
}
//RESUME CHECKSTYLE CHECK VisibilityModifierCheck
private void checkLifeCycleOption(List<LifeCycle> lifeCycles, String type) throws FalconCLIException {
if (lifeCycles != null && !lifeCycles.isEmpty()) {
EntityType entityType = EntityType.getEnum(type);
for (LifeCycle lifeCycle : lifeCycles) {
if (entityType != lifeCycle.getTag().getType()) {
throw new FalconCLIException("Incorrect lifecycle: " + lifeCycle + "for given type: " + type);
}
}
}
}
protected void checkType(String type) throws FalconCLIException {
if (type == null || type.isEmpty()) {
throw new FalconCLIException("entity type is empty");
} else {
EntityType entityType = EntityType.getEnum(type);
if (entityType == EntityType.CLUSTER) {
throw new FalconCLIException(
"Instance management functions don't apply to Cluster entities");
}
}
}
//SUSPEND CHECKSTYLE CHECK ParameterNumberCheck
private EntityList sendListRequest(Entities entities, String entityType, String fields, String filterBy,
String filterTags, String orderBy, String sortOrder, Integer offset,
Integer numResults, String searchPattern) throws FalconCLIException {
WebResource resource = service.path(entities.path)
.path(entityType);
resource = addParamsToResource(resource, null, null, null, null, fields, filterBy, filterTags,
orderBy, sortOrder, offset, numResults, null, searchPattern);
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(entities.mimeType).type(MediaType.TEXT_XML)
.method(entities.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
return parseEntityList(clientResponse);
}
// RESUME CHECKSTYLE CHECK ParameterNumberCheck
private String sendAdminRequest(AdminOperations job) throws FalconCLIException {
ClientResponse clientResponse = service.path(job.path)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(job.mimeType)
.type(job.mimeType)
.method(job.method, ClientResponse.class);
return clientResponse.getEntity(String.class);
}
private String sendMetadataDiscoveryRequest(final MetadataOperations operation,
final String dimensionType,
final String dimensionName,
final String cluster) throws FalconCLIException {
WebResource resource;
switch (operation) {
case LIST:
resource = service.path(operation.path)
.path(dimensionType)
.path(FalconMetadataCLI.LIST_OPT);
break;
case RELATIONS:
resource = service.path(operation.path)
.path(dimensionType)
.path(dimensionName)
.path(FalconMetadataCLI.RELATIONS_OPT);
break;
default:
throw new FalconCLIException("Invalid Metadata client Operation " + operation.toString());
}
if (!StringUtils.isEmpty(cluster)) {
resource = resource.queryParam(FalconMetadataCLI.CLUSTER_OPT, cluster);
}
ClientResponse clientResponse = resource
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(operation.mimeType).type(operation.mimeType)
.method(operation.method, ClientResponse.class);
checkIfSuccessful(clientResponse);
return clientResponse.getEntity(String.class);
}
private APIResult parseAPIResult(ClientResponse clientResponse)
throws FalconCLIException {
return clientResponse.getEntity(APIResult.class);
}
private EntityList parseEntityList(ClientResponse clientResponse)
throws FalconCLIException {
EntityList result = clientResponse.getEntity(EntityList.class);
if (result == null || result.getElements() == null) {
return null;
}
return result;
}
public String getVertex(String id) throws FalconCLIException {
return sendMetadataLineageRequest(MetadataOperations.VERTICES, id);
}
public String getVertices(String key, String value) throws FalconCLIException {
return sendMetadataLineageRequest(MetadataOperations.VERTICES, key, value);
}
public String getVertexEdges(String id, String direction) throws FalconCLIException {
return sendMetadataLineageRequestForEdges(MetadataOperations.VERTICES, id, direction);
}
public String getEdge(String id) throws FalconCLIException {
return sendMetadataLineageRequest(MetadataOperations.EDGES, id);
}
public APIResult submitRecipe(String recipeName,
String recipeToolClassName) throws FalconCLIException {
String recipePath = clientProperties.getProperty("falcon.recipe.path");
if (StringUtils.isEmpty(recipePath)) {
throw new FalconCLIException("falcon.recipe.path is not set in client.properties");
}
String recipeFilePath = recipePath + File.separator + recipeName + TEMPLATE_SUFFIX;
File file = new File(recipeFilePath);
if (!file.exists()) {
throw new FalconCLIException("Recipe template file does not exist : " + recipeFilePath);
}
String propertiesFilePath = recipePath + File.separator + recipeName + PROPERTIES_SUFFIX;
file = new File(propertiesFilePath);
if (!file.exists()) {
throw new FalconCLIException("Recipe properties file does not exist : " + propertiesFilePath);
}
String processFile;
try {
String prefix = "falcon-recipe" + "-" + System.currentTimeMillis();
File tmpPath = new File("/tmp");
if (!tmpPath.exists()) {
if (!tmpPath.mkdir()) {
throw new FalconCLIException("Creating directory failed: " + tmpPath.getAbsolutePath());
}
}
File f = File.createTempFile(prefix, ".xml", tmpPath);
f.deleteOnExit();
processFile = f.getAbsolutePath();
String[] args = {
"-" + RecipeToolArgs.RECIPE_FILE_ARG.getName(), recipeFilePath,
"-" + RecipeToolArgs.RECIPE_PROPERTIES_FILE_ARG.getName(), propertiesFilePath,
"-" + RecipeToolArgs.RECIPE_PROCESS_XML_FILE_PATH_ARG.getName(), processFile,
};
if (recipeToolClassName != null) {
Class<?> clz = Class.forName(recipeToolClassName);
Method method = clz.getMethod("main", String[].class);
method.invoke(null, args);
} else {
RecipeTool.main(args);
}
validate(EntityType.PROCESS.toString(), processFile);
return submitAndSchedule(EntityType.PROCESS.toString(), processFile);
} catch (Exception e) {
throw new FalconCLIException(e.getMessage(), e);
}
}
private String sendMetadataLineageRequest(MetadataOperations job, String id) throws FalconCLIException {
ClientResponse clientResponse = service.path(job.path)
.path(id)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(job.mimeType)
.type(job.mimeType)
.method(job.method, ClientResponse.class);
return clientResponse.getEntity(String.class);
}
private String sendMetadataLineageRequest(MetadataOperations job, String key,
String value) throws FalconCLIException {
ClientResponse clientResponse = service.path(job.path)
.queryParam("key", key)
.queryParam("value", value)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(job.mimeType)
.type(job.mimeType)
.method(job.method, ClientResponse.class);
return clientResponse.getEntity(String.class);
}
private String sendMetadataLineageRequestForEdges(MetadataOperations job, String id,
String direction) throws FalconCLIException {
ClientResponse clientResponse = service.path(job.path)
.path(id)
.path(direction)
.header("Cookie", AUTH_COOKIE_EQ + authenticationToken)
.accept(job.mimeType)
.type(job.mimeType)
.method(job.method, ClientResponse.class);
return clientResponse.getEntity(String.class);
}
private void checkIfSuccessful(ClientResponse clientResponse) throws FalconCLIException {
Response.Status.Family statusFamily = clientResponse.getClientResponseStatus().getFamily();
if (statusFamily != Response.Status.Family.SUCCESSFUL
&& statusFamily != Response.Status.Family.INFORMATIONAL) {
throw FalconCLIException.fromReponse(clientResponse);
}
}
}
| 43.966633 | 120 | 0.64554 |
3a574e8c00ebff8c8312dede9dc08279bf61e22b | 5,400 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.core.amqp;
import java.time.Duration;
import java.util.Objects;
/**
* A set of options that can be specified to influence how retry attempts are made.
*/
public class RetryOptions implements Cloneable {
private int maxRetries;
private Duration delay;
private Duration maxDelay;
private Duration tryTimeout;
private RetryMode retryMode;
/**
* Creates an instance with the default retry options set.
*/
public RetryOptions() {
maxRetries = 3;
delay = Duration.ofMillis(800);
maxDelay = Duration.ofMinutes(1);
tryTimeout = Duration.ofMinutes(1);
retryMode = RetryMode.EXPONENTIAL;
}
/**
* Sets the approach to use for calculating retry delays.
*
* @param retryMode The retry approach to use for calculating delays.
* @return The updated {@link RetryOptions} object.
*/
public RetryOptions setRetryMode(RetryMode retryMode) {
this.retryMode = retryMode;
return this;
}
/**
* Sets the maximum number of retry attempts before considering the associated operation to have failed.
*
* @param numberOfRetries The maximum number of retry attempts.
* @return The updated {@link RetryOptions} object.
*/
public RetryOptions setMaxRetries(int numberOfRetries) {
this.maxRetries = numberOfRetries;
return this;
}
/**
* Gets the delay between retry attempts for a fixed approach or the delay on which to base calculations for a
* backoff-approach.
*
* @param delay The delay between retry attempts.
* @return The updated {@link RetryOptions} object.
*/
public RetryOptions setDelay(Duration delay) {
this.delay = delay;
return this;
}
/**
* Sets the maximum permissible delay between retry attempts.
*
* @param maximumDelay The maximum permissible delay between retry attempts.
* @return The updated {@link RetryOptions} object.
*/
public RetryOptions setMaxDelay(Duration maximumDelay) {
this.maxDelay = maximumDelay;
return this;
}
/**
* Sets the maximum duration to wait for completion of a single attempt, whether the initial attempt or a retry.
*
* @param tryTimeout The maximum duration to wait for completion.
* @return The updated {@link RetryOptions} object.
*/
public RetryOptions setTryTimeout(Duration tryTimeout) {
this.tryTimeout = tryTimeout;
return this;
}
/**
* Gets the approach to use for calculating retry delays.
*
* @return The approach to use for calculating retry delays.
*/
public RetryMode getRetryMode() {
return retryMode;
}
/**
* The maximum number of retry attempts before considering the associated operation to have failed.
*
* @return The maximum number of retry attempts before considering the associated operation to have failed.
*/
public int getMaxRetries() {
return maxRetries;
}
/**
* Gets the delay between retry attempts for a fixed approach or the delay on which to base calculations for a
* backoff-approach.
*
* @return The delay between retry attempts.
*/
public Duration getDelay() {
return delay;
}
/**
* Gets the maximum permissible delay between retry attempts.
*
* @return The maximum permissible delay between retry attempts.
*/
public Duration getMaxDelay() {
return maxDelay;
}
/**
* Gets the maximum duration to wait for completion of a single attempt, whether the initial attempt or a retry.
*
* @return The maximum duration to wait for completion of a single attempt, whether the initial attempt or a retry.
*/
public Duration getTryTimeout() {
return tryTimeout;
}
/**
* Creates a new copy of the current instance, cloning its attributes into a new instance.
*
* @return A new copy of {@link RetryOptions}.
*/
@Override
public RetryOptions clone() {
RetryOptions clone;
try {
clone = (RetryOptions) super.clone();
} catch (CloneNotSupportedException e) {
clone = new RetryOptions();
}
return clone.setDelay(delay)
.setMaxDelay(maxDelay)
.setMaxRetries(maxRetries)
.setTryTimeout(tryTimeout)
.setRetryMode(retryMode);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RetryOptions)) {
return false;
}
final RetryOptions other = (RetryOptions) obj;
return this.getMaxRetries() == other.getMaxRetries()
&& this.getRetryMode() == other.getRetryMode()
&& Objects.equals(this.getMaxDelay(), other.getMaxDelay())
&& Objects.equals(this.getDelay(), other.getDelay())
&& Objects.equals(this.getTryTimeout(), other.getTryTimeout());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(maxRetries, retryMode, maxDelay, delay, tryTimeout);
}
}
| 29.347826 | 119 | 0.632778 |
bf385095bf97bcf39eb5d8b413fbf33e826772db | 6,867 | package xyz.sleekstats.softball.dialogs;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import xyz.sleekstats.softball.R;
import xyz.sleekstats.softball.adapters.AddPlayersRecyclerViewAdapter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class AddNewPlayersDialog extends DialogFragment {
private AddPlayersRecyclerViewAdapter mAdapter;
private RecyclerView mRecyclerView;
private OnListFragmentInteractionListener mListener;
private static final String KEY_NAMES = "names";
private static final String KEY_GENDERS = "genders";
private static final String KEY_EDITS = "edits";
private static final String KEY_TEAM_NAME = "team_name";
private static final String KEY_TEAM_ID = "team_id";
private String mTeamName;
private String mTeamID;
public AddNewPlayersDialog() {
}
public static AddNewPlayersDialog newInstance(String teamName, String teamID) {
AddNewPlayersDialog fragment = new AddNewPlayersDialog();
Bundle args = new Bundle();
args.putString(KEY_TEAM_NAME, teamName);
args.putString(KEY_TEAM_ID, teamID);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if(bundle == null) {
return;
}
mTeamName = bundle.getString(KEY_TEAM_NAME);
mTeamID = bundle.getString(KEY_TEAM_ID);
if (savedInstanceState != null) {
List<Integer> edits = savedInstanceState.getIntegerArrayList(KEY_EDITS);
List<Integer> genderEntries = savedInstanceState.getIntegerArrayList(KEY_GENDERS);
List<String> nameEntries = savedInstanceState.getStringArrayList(KEY_NAMES);
mAdapter = new AddPlayersRecyclerViewAdapter(nameEntries, genderEntries, edits);
} else {
mAdapter = new AddPlayersRecyclerViewAdapter();
}
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
@SuppressLint("InflateParams") View view = LayoutInflater.from(getActivity()).inflate(R.layout.rv_list, null);
Context context = view.getContext();
mRecyclerView = (RecyclerView) view;
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(mAdapter);
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.setView(mRecyclerView)
.setTitle("Add new players to " + mTeamName)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
onButtonPressed();
disableViewHolderEditTexts();
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
disableViewHolderEditTexts();
dialog.dismiss();
}
}
})
.setCancelable(false)
.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return alertDialog;
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
disableViewHolderEditTexts();
}
private void onButtonPressed() {
if (mListener != null) {
ArrayList<String> names = new ArrayList<>(mAdapter.getNameEntries());
ArrayList<Integer> genders = new ArrayList<>(mAdapter.getGenderEntries());
mListener.onSubmitPlayersListener(names, genders, mTeamName, mTeamID);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
ArrayList<String> names = new ArrayList<>(mAdapter.getNameEntries());
ArrayList<Integer> genders = new ArrayList<>(mAdapter.getGenderEntries());
HashSet<Integer> edits = mAdapter.getEdits();
outState.putStringArrayList(KEY_NAMES, names);
outState.putIntegerArrayList(KEY_GENDERS, new ArrayList<>(genders));
outState.putIntegerArrayList(KEY_EDITS, new ArrayList<>(edits));
super.onSaveInstanceState(outState);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
if(mRecyclerView != null) {
mRecyclerView.setAdapter(null);
mAdapter = null;
mRecyclerView = null;
}
}
private void disableViewHolderEditTexts(){
for (int childCount = mRecyclerView.getChildCount(), i = 0; i < childCount; ++i) {
final RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(mRecyclerView.getChildAt(i));
mAdapter.disableEditTextCursor(holder);
}
}
public interface OnListFragmentInteractionListener {
void onSubmitPlayersListener(List<String> names, List<Integer> genders, String team, String teamID);
}
}
| 39.465517 | 139 | 0.653124 |
41336637331a62ebae699e4bba69463e80e7d27d | 6,161 | package com.happybudui.venuesystem.service;
import com.happybudui.venuesystem.bean.AreaBean;
import com.happybudui.venuesystem.entity.OrderEntity;
import com.happybudui.venuesystem.entity.VenueEntity;
import com.happybudui.venuesystem.entity.VenueExternEntity;
import com.happybudui.venuesystem.mapper.OrderMapper;
import com.happybudui.venuesystem.mapper.VenueExternMapper;
import com.happybudui.venuesystem.mapper.VenueMapper;
import com.happybudui.venuesystem.wrapper.ResponseResult;
import com.happybudui.venuesystem.wrapper.ResultGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import static com.happybudui.venuesystem.wrapper.ResultGenerator.success;
//CopyRight © 2018-2018 Happybudui All Rights Reserved.
//Written by Happybudui
@Service
public class OrderService {
private final OrderMapper orderMapper;
private final VenueMapper venueMapper;
private final VenueExternMapper venueExternMapper;
private Map<Integer,AreaBean> venueAreaMap;
public OrderService(OrderMapper orderMapper, VenueMapper venueMapper, VenueExternMapper venueExternMapper) {
this.orderMapper = orderMapper;
this.venueMapper = venueMapper;
this.venueExternMapper = venueExternMapper;
venueAreaMap=VenueService.venueAreaMap;
}
// 用户创建订单
@Transactional
public ResponseResult<Integer> addOrder(String orderDate, String orderStatus, String orderPrice,
String venueId, String dayOfWeek, String timeSlot, HttpSession session) {
if (venueMapper.getVenueById(Integer.valueOf(venueId)).isVenueStatus()) {
if(venueExternMapper.getVenueAreaRemain(Integer.valueOf(venueId), Integer.valueOf(dayOfWeek), Integer.valueOf(timeSlot))==null) {
venueExternMapper.insertVenueExternInfo(new VenueExternEntity(Integer.valueOf(venueId),Integer.valueOf(dayOfWeek),Integer.valueOf(timeSlot),venueMapper.getVenueById(Integer.valueOf(venueId)).getVenueAreaNum()));
}
if (venueExternMapper.getVenueAreaRemain(Integer.valueOf(venueId), Integer.valueOf(dayOfWeek), Integer.valueOf(timeSlot)) != 0) {
String thisUserId = (String) session.getAttribute("userId");
int currentAreaRemain = venueExternMapper.getVenueAreaRemain(Integer.valueOf(venueId), Integer.valueOf(dayOfWeek), Integer.valueOf(timeSlot));
orderMapper.insertOrder(new OrderEntity(Double.valueOf(orderPrice), thisUserId, Integer.valueOf(venueId),
Integer.valueOf(dayOfWeek), Integer.valueOf(timeSlot)));
venueExternMapper.updateVenueAreaRemain(Integer.valueOf(venueId), Integer.valueOf(dayOfWeek), Integer.valueOf(timeSlot), currentAreaRemain - 1);
((AreaBean)venueAreaMap.get(venueId)).refreshData();
return success("Insert Order successfully!");
} else {
return ResultGenerator.error("No idle area!");
}
} else {
return ResultGenerator.error("Venue is unopened!");
}
}
//获取用户所有订单
@Transactional
public ResponseResult<List<OrderEntity>> getUserAllOrders(HttpSession session) {
String userId = (String) session.getAttribute("userId");
if (userId != null) {
List<OrderEntity> allUserOrders = orderMapper.getOrderByUserId(userId);
return success(allUserOrders);
}
return ResultGenerator.error("Inner Error!");
}
//根据订单状态获取所有订单
@Transactional
public ResponseResult<List<OrderEntity>> getUserOrdersByStatus(HttpSession session, String orderStatus) {
String userId = (String) session.getAttribute("userId");
if (userId != null) {
List<OrderEntity> allUserOrders = orderMapper.getUserOrderByStatus(userId, Integer.valueOf(orderStatus));
return success(allUserOrders);
}
return ResultGenerator.error("Inner Error!");
}
//取消订单
@Transactional
public ResponseResult<Integer> cancelOrder(String orderId){
orderMapper.changeOrderStatus(orderId,3);
OrderEntity orderEntity=orderMapper.getOrderByOrderId(orderId);
int currentAreaRemain = venueExternMapper.getVenueAreaRemain(orderEntity.getVenueId(),orderEntity.getDayOfWeek(),orderEntity.getTimeSlot());
venueExternMapper.updateVenueAreaRemain(orderEntity.getVenueId(),orderEntity.getDayOfWeek(),orderEntity.getTimeSlot(),currentAreaRemain+1);
((AreaBean)venueAreaMap.get(orderEntity.getVenueId())).refreshData();
return ResultGenerator.success("order has canceled!");
}
//管理员接口
//获取所有订单
@Transactional
public ResponseResult<List<OrderEntity>> getAllOrders() {
List<OrderEntity> allOrders = orderMapper.getAllOrders();
return ResultGenerator.success(allOrders);
}
//根据订单状态获取所有订单
@Transactional
public ResponseResult<List<OrderEntity>> getOrdersByStatus(String orderStatus) {
List<OrderEntity> allOrders = orderMapper.getOrderByOrderStatus(Integer.valueOf(orderStatus));
return ResultGenerator.success(allOrders);
}
//审核并通过订单
@Transactional
public ResponseResult<Integer> approveOrder(String orderId){
orderMapper.changeOrderStatus(orderId,1);
return ResultGenerator.success("approved!");
}
//审核并拒绝订单
@Transactional
public ResponseResult<Integer> disApproveOrder(String orderId){
orderMapper.changeOrderStatus(orderId,2);
OrderEntity orderEntity=orderMapper.getOrderByOrderId(orderId);
int currentAreaRemain = venueExternMapper.getVenueAreaRemain(orderEntity.getVenueId(),orderEntity.getDayOfWeek(),orderEntity.getTimeSlot());
venueExternMapper.updateVenueAreaRemain(orderEntity.getVenueId(),orderEntity.getDayOfWeek(),orderEntity.getTimeSlot(),currentAreaRemain+1);
((AreaBean)venueAreaMap.get(orderEntity.getVenueId())).refreshData();
return ResultGenerator.success("disapproved!");
}
}
| 44.644928 | 231 | 0.728291 |
ad15d688a155da52efe6cb7293789c6d70b92f18 | 1,995 | package net.clgd.ccemux.init;
import static java.lang.System.getProperty;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.common.base.MoreObjects;
import com.google.common.base.Throwables;
import net.clgd.ccemux.emulation.CCEmuX;
/**
* Used to collect system information when an uncaught exception causes CCEmuX
* to crash
*
* @author apemanzilla
*/
public final class CrashReport {
private final Throwable throwable;
public CrashReport(Throwable throwable) {
this.throwable = throwable;
}
public Throwable getThrowable() {
return throwable;
}
public static Map<String, String> collectInfo() {
Map<String, String> info = new LinkedHashMap<>();
try {
info.put("CCEmuX version", MoreObjects.firstNonNull(CCEmuX.getVersion(), "unknown"));
} catch (Throwable t) {
info.put("CCEmuX version", t.toString());
}
info.put("OS name", getProperty("os.name", "unknown"));
info.put("OS version", getProperty("os.version", "unknown"));
info.put("OS architecture", getProperty("os.arch", "unknown"));
info.put("JRE vendor", getProperty("java.vendor", "unknown"));
info.put("JRE version", getProperty("java.version", "unknown"));
info.put("JRE architecture", getProperty("sun.arch.data.model", "unknown"));
return info;
}
@Override
public String toString() {
return collectInfo().entrySet().stream().map(e -> e.getKey() + ": " + e.getValue() + "\n").reduce("",
(a, b) -> a + b) + "\n" + Throwables.getStackTraceAsString(getThrowable());
}
public void createIssue() throws URISyntaxException, IOException {
Desktop.getDesktop()
.browse(new URI(String.format("https://github.com/Lignumm/CCEmuX/issues/new?title=%s&body=%s",
URLEncoder.encode("Unexpected " + getThrowable().getClass().toString(), "UTF-8"),
URLEncoder.encode("```\n" + toString() + "```", "UTF-8"))));
}
}
| 29.776119 | 103 | 0.701754 |
fe3dcefd9b885817a81fd72b5a37f2f2dcb5478e | 400 | package com.blue_unicorn.android_auth_lib.android;
import android.os.Binder;
public class FidoAuthServiceBinder extends Binder {
private FidoAuthService fidoAuthService;
public FidoAuthServiceBinder(FidoAuthService fidoAuthService) {
super();
this.fidoAuthService = fidoAuthService;
}
public FidoAuthService getService() {
return fidoAuthService;
}
}
| 22.222222 | 67 | 0.74 |
2c02bdf6d72a643a085fb0ddc641bb3a4611847d | 815 | package com.bazl.dna.lims.model.po;
import java.io.Serializable;
/**
* @Author: lzn
* @Date: 2020/3/31 14:10
* @Version: 1.0
*/
public class DnaNoSeq implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String code;
private String currentVal;
private String numIncrement;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getCurrentVal() {
return currentVal;
}
public void setCurrentVal(String currentVal) {
this.currentVal = currentVal;
}
public String getNumIncrement() {
return numIncrement;
}
public void setNumIncrement(String numIncrement) {
this.numIncrement = numIncrement;
}
}
| 17.717391 | 54 | 0.63681 |
d7f6fb4f9286a1c64f9da5db36cbd656e2efc550 | 1,936 | package com.janiwanow.flatmap.realty.provider.n1;
import com.janiwanow.flatmap.internal.http.HttpConnection;
import com.janiwanow.flatmap.realty.PropertyDetailsExtractor;
import com.janiwanow.flatmap.realty.RelevanceCheckResult;
import com.janiwanow.flatmap.realty.RelevanceChecker;
import java.net.URI;
import java.util.Objects;
import java.util.regex.Pattern;
public final class N1RelevanceChecker implements RelevanceChecker {
private static final Pattern PATTERN = Pattern.compile("https://.*\\.n1\\.ru");
private final HttpConnection connection;
private final PropertyDetailsExtractor extractor;
public N1RelevanceChecker(
HttpConnection connection,
PropertyDetailsExtractor extractor
) {
Objects.requireNonNull(connection, "Connection must not be null.");
Objects.requireNonNull(extractor, "Extractor must not be null.");
this.connection = connection;
this.extractor = extractor;
}
public static N1RelevanceChecker getDefault(HttpConnection connection) {
Objects.requireNonNull(connection, "Connection must not be null.");
return new N1RelevanceChecker(connection, new PropertyDetailsExtractor(
new AddressExtractor(),
new AreaExtractor(),
new PriceExtractor()
));
}
@Override
public RelevanceCheckResult check(URI url) {
Objects.requireNonNull(url, "URL must not be null.");
var document = connection.fetch(url);
var isObsolete = (
document.isEmpty() ||
extractor.extract(document.get()).isEmpty()
);
return isObsolete
? RelevanceCheckResult.obsolete(url)
: RelevanceCheckResult.relevant(url);
}
@Override
public boolean supports(URI url) {
Objects.requireNonNull(url, "URL must not be null.");
return PATTERN.matcher(url.toString()).lookingAt();
}
}
| 33.37931 | 83 | 0.692665 |
4b08d6b3d6c99d02d33184b489657d4f888e91de | 118 | /**
* This package holds all the events used within the JDS library
*/
package io.github.subiyacryolite.jds.context; | 29.5 | 64 | 0.762712 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.