hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequence | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequence | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequence | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9243cc2320dba1b2dc397071f6c9b9d58d4a25d3 | 21,681 | java | Java | src/edu/syr/pcpratts/rootbeer/generate/opencl/OpenCLMethod.java | michael-mathieu/rootbeer1 | b5984b04e2e0fe9eae3ec02bb7d869ec1f75ab67 | [
"MIT"
] | null | null | null | src/edu/syr/pcpratts/rootbeer/generate/opencl/OpenCLMethod.java | michael-mathieu/rootbeer1 | b5984b04e2e0fe9eae3ec02bb7d869ec1f75ab67 | [
"MIT"
] | null | null | null | src/edu/syr/pcpratts/rootbeer/generate/opencl/OpenCLMethod.java | michael-mathieu/rootbeer1 | b5984b04e2e0fe9eae3ec02bb7d869ec1f75ab67 | [
"MIT"
] | null | null | null | 38.373451 | 118 | 0.653937 | 1,002,779 | /*
* Copyright 2012 Phil Pratt-Szeliga and other contributors
* http://chirrup.org/
*
* See the file LICENSE for copying permission.
*/
package edu.syr.pcpratts.rootbeer.generate.opencl;
import edu.syr.pcpratts.rootbeer.generate.bytecode.StaticOffsets;
import edu.syr.pcpratts.rootbeer.generate.opencl.body.MethodJimpleValueSwitch;
import edu.syr.pcpratts.rootbeer.generate.opencl.body.OpenCLBody;
import edu.syr.pcpratts.rootbeer.generate.opencl.tweaks.Tweaks;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import soot.*;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.options.Options;
import soot.rbclassload.MethodSignatureUtil;
import soot.rbclassload.RootbeerClassLoader;
/**
* Represents an OpenCL function.
* @author pcpratts
*/
public class OpenCLMethod {
private final SootMethod m_sootMethod;
private SootClass m_sootClass;
private Set<String> m_dontMangleMethods;
private Set<String> m_emitUnmangled;
public OpenCLMethod(SootMethod soot_method, SootClass soot_class){
m_sootMethod = soot_method;
m_sootClass = soot_class;
createDontMangleMethods();
}
public String getReturnString(){
StringBuilder ret = new StringBuilder();
if(isConstructor()){
ret.append("int");
} else {
OpenCLType return_type = new OpenCLType(m_sootMethod.getReturnType());
ret.append(return_type.getCudaTypeString());
}
return ret.toString();
}
private String getRestOfArgumentListStringInternal(){
StringBuilder ret = new StringBuilder();
List args = m_sootMethod.getParameterTypes();
if(args.size() != 0)
ret.append(", ");
for(int i = 0; i < args.size(); ++i){
Type curr_arg = (Type) args.get(i);
OpenCLType parameter_type = new OpenCLType(curr_arg);
ret.append(parameter_type.getCudaTypeString());
ret.append(" parameter" + Integer.toString(i));
if(i < args.size()-1)
ret.append(", ");
}
ret.append(", int * exception");
ret.append(")");
return ret.toString();
}
private String getArgumentListStringInternal(boolean override_ctor){
StringBuilder ret = new StringBuilder();
ret.append("(");
String address_space_qual = Tweaks.v().getGlobalAddressSpaceQualifier();
if(isConstructor() == true){
ret.append(address_space_qual+" char * gc_info");
} else if((isConstructor() == false || override_ctor == true) && m_sootMethod.isStatic() == false){
ret.append(address_space_qual+" char * gc_info, int thisref");
} else {
ret.append(address_space_qual+" char * gc_info");
}
ret.append(getRestOfArgumentListStringInternal());
return ret.toString();
}
public String getArgumentListString(boolean ctor_body){
if(ctor_body){
String address_space_qual = Tweaks.v().getGlobalAddressSpaceQualifier();
String ret = "("+address_space_qual+" char * gc_info, int thisref";
ret += getRestOfArgumentListStringInternal();
return ret;
} else {
return getArgumentListStringInternal(false);
}
}
public String getArgumentListStringPolymorphic(){
return getArgumentListStringInternal(true);
}
private String getMethodDecl(boolean ctor_body){
StringBuilder ret = new StringBuilder();
ret.append(Tweaks.v().getDeviceFunctionQualifier()+" ");
if(ctor_body){
ret.append("void");
} else {
ret.append(getReturnString());
}
ret.append(" ");
ret.append(getPolymorphicNameInternal(ctor_body));
ret.append(getArgumentListString(ctor_body));
return ret.toString();
}
public String getMethodPrototype(){
String ret = getMethodDecl(false)+";\n";
if(isConstructor()){
ret += getMethodDecl(true)+";\n";
}
return ret;
}
private boolean isLinux(){
String s = File.separator;
if(s.equals("/")){
return true;
}
return false;
}
private String synchronizedEnter(){
String prefix = Options.v().rbcl_remap_prefix();
if(Options.v().rbcl_remap_all() == false){
prefix = "";
}
String ret = "";
ret += "int id;\n";
ret += "char * mem;\n";
ret += "char * trash;\n";
ret += "char * mystery;\n";
ret += "int count;\n";
ret += "int old;\n";
ret += "char * thisref_synch_deref;\n";
if(m_sootMethod.isStatic() == false){
ret += "if(thisref == -1){\n";
SootClass null_ptr = Scene.v().getSootClass(prefix+"java.lang.NullPointerException");
ret += " *exception = "+RootbeerClassLoader.v().getDfsInfo().getClassNumber(null_ptr)+";\n";
if(returnsAValue()){
ret += " return 0;\n";
} else {
ret += " return;\n";
}
ret += "}\n";
}
ret += "id = getThreadId();\n";
StaticOffsets static_offsets = new StaticOffsets();
int junk_index = static_offsets.getEndIndex() - 4;
int mystery_index = junk_index - 4;
if(m_sootMethod.isStatic()){
int offset = static_offsets.getIndex(m_sootClass);
ret += "mem = edu_syr_pcpratts_gc_deref(gc_info, 0);\n";
ret += "trash = mem + "+junk_index+";\n";
ret += "mystery = mem + "+mystery_index+";\n";
ret += "mem += "+offset+";\n";
} else {
ret += "mem = edu_syr_pcpratts_gc_deref(gc_info, thisref);\n";
ret += "trash = edu_syr_pcpratts_gc_deref(gc_info, 0) + "+junk_index+";\n";
ret += "mystery = trash - 8;\n";
ret += "mem += 12;\n";
}
ret += "count = 0;\n";
ret += "while(count < 100){\n";
ret += " old = atomicCAS((int *) mem, -1 , id);\n";
ret += " *((int *) trash) = old;\n";
if(isLinux()){
ret += " if(old == -1 || old == id){\n";
} else {
ret += " if(old != -1 && old != id){\n";
ret += " count++;\n";
ret += " if(count > 50 || (*((int *) mystery)) == 0){\n";
ret += " count = 0;\n";
ret += " }\n";
ret += " } else {\n";
}
//adding this in makes the WhileTrueTest pass.
//for some reason the first write to memory doesn't work well inside a sync block.
if(m_sootMethod.isStatic() == false){
ret += " if ( thisref ==-1 ) { \n";
ret += " * exception = 11;\n";
ret += " }\n";
ret += " if ( * exception != 0 ) {\n";
ret += " edu_syr_pcpratts_exitMonitorMem ( gc_info , mem , old ) ;\n";
if(returnsAValue()){
ret += " return 0;\n";
} else {
ret += " return;\n";
}
ret += " }\n";
ret += " thisref_synch_deref = edu_syr_pcpratts_gc_deref ( gc_info , thisref );\n";
ret += " * ( ( int * ) & thisref_synch_deref [ 16 ] ) = 20 ;\n";
}
return ret;
}
public String getMethodBody(){
StringBuilder ret = new StringBuilder();
if(shouldEmitBody()){
ret.append(getMethodDecl(false)+"{\n");
try {
if(methodIsRuntimeBasicBlockRun() == false){
OpenCLBody ocl_body = new OpenCLBody(m_sootMethod, isConstructor());
ret.append(ocl_body.getLocals());
if(isSynchronized()){
ret.append(synchronizedEnter());
}
ret.append(ocl_body.getBodyNoLocals());
if(isSynchronized()){
if(isLinux()){
ret.append(" } else {");
ret.append(" count++;\n");
ret.append(" if(count > 50 || (*((int *) mystery)) == 0){\n");
ret.append(" count = 0;\n");
ret.append(" }\n");
ret.append(" }\n");
ret.append("}\n");
} else {
ret.append(" }\n");
ret.append("}\n");
}
}
if(returnsAValue()){
ret.append("return 0;");
}
}
} catch(RuntimeException ex){
ex.printStackTrace(System.out);
System.out.println("error creating method body: "+m_sootMethod.getSignature());
OpenCLMethod ocl_method = new OpenCLMethod(m_sootMethod, m_sootClass);
if(ocl_method.returnsAValue())
ret.append("return 0;\n");
else
ret.append("\n");
}
ret.append("}\n");
if(isConstructor()){
ret.append(getMethodDecl(true)+"{\n");
OpenCLBody ocl_body = new OpenCLBody(m_sootMethod.retrieveActiveBody());
ret.append(ocl_body.getBody());
ret.append("}\n");
}
}
return ret.toString();
}
public String getConstructorBodyInvokeString(SpecialInvokeExpr arg0){
StringBuilder ret = new StringBuilder();
ret.append(getPolymorphicNameInternal(true) +"(");
List args = arg0.getArgs();
List<String> args_list = new ArrayList<String>();
args_list.add("gc_info");
args_list.add("thisref");
for(int i = 0; i < args_list.size() - 1; ++i){
ret.append(args_list.get(i));
ret.append(",\n ");
}
if(args_list.size() > 0){
ret.append(args_list.get(args_list.size()-1));
if(args.size() > 0)
ret.append(",\n ");
}
MethodJimpleValueSwitch quick_value_switch = new MethodJimpleValueSwitch(ret);
for(int i = 0; i < args.size(); ++i){
Value arg = (Value) args.get(i);
arg.apply(quick_value_switch);
if(i < args.size() - 1)
ret.append(",\n ");
}
ret.append(", exception");
ret.append(")");
return ret.toString();
}
public String getInstanceInvokeString(InstanceInvokeExpr arg0){
Value base = arg0.getBase();
Type base_type = base.getType();
List<Type> hierarchy;
if(base_type instanceof ArrayType){
hierarchy = new ArrayList<Type>();
SootClass obj = Scene.v().getSootClass("java.lang.Object");
hierarchy.add(obj.getType());
} else if (base_type instanceof RefType){
RefType ref_type = (RefType) base_type;
hierarchy = RootbeerClassLoader.v().getDfsInfo().getHierarchy(ref_type.getSootClass());
} else {
throw new UnsupportedOperationException("how do we handle this case?");
}
IsPolyMorphic poly_checker = new IsPolyMorphic();
if(poly_checker.isPoly(m_sootMethod, hierarchy) == false || isConstructor() || arg0 instanceof SpecialInvokeExpr){
return writeInstanceInvoke(arg0, "", m_sootClass.getType());
} else if(hierarchy.size() == 0){
System.out.println("size = 0");
return null;
} else {
return writeInstanceInvoke(arg0, "invoke_", hierarchy.get(0));
}
}
public String getStaticInvokeString(StaticInvokeExpr expr){
StringBuilder ret = new StringBuilder();
ret.append(getPolymorphicName()+"(");
List args = expr.getArgs();
List<String> args_list = new ArrayList<String>();
args_list.add("gc_info");
for(int i = 0; i < args_list.size() - 1; ++i){
ret.append(args_list.get(i));
ret.append(", ");
}
if(args_list.size() > 0){
ret.append(args_list.get(args_list.size()-1));
if(args.size() > 0)
ret.append(", ");
}
MethodJimpleValueSwitch quick_value_switch = new MethodJimpleValueSwitch(ret);
for(int i = 0; i < args.size(); ++i){
Value arg = (Value) args.get(i);
arg.apply(quick_value_switch);
if(i < args.size() - 1)
ret.append(", ");
}
ret.append(", exception");
ret.append(")");
return ret.toString();
}
private String writeInstanceInvoke(InstanceInvokeExpr arg0, String method_prefix, Type type){
if(type instanceof RefType == false){
throw new RuntimeException("please report bug in OpenCLMethod.writeInstanceInvoke");
}
RefType ref_type = (RefType) type;
OpenCLMethod corrected_this = new OpenCLMethod(m_sootMethod, ref_type.getSootClass());
StringBuilder ret = new StringBuilder();
Value base = arg0.getBase();
if(base instanceof Local == false)
throw new UnsupportedOperationException("How do we handle an invoke on a non loca?");
Local local = (Local) base;
if(isConstructor()){
ret.append("edu_syr_pcpratts_gc_assign (gc_info, \n&"+local.getName()+", ");
}
String function_name = method_prefix+corrected_this.getPolymorphicName();
ret.append(function_name+"(");
List args = arg0.getArgs();
List<String> args_list = new ArrayList<String>();
args_list.add("gc_info");
//write the thisref
if(isConstructor() == false)
args_list.add(local.getName());
for(int i = 0; i < args_list.size() - 1; ++i){
ret.append(args_list.get(i));
ret.append(",\n ");
}
if(args_list.size() > 0){
ret.append(args_list.get(args_list.size()-1));
if(args.size() > 0)
ret.append(",\n ");
}
MethodJimpleValueSwitch quick_value_switch = new MethodJimpleValueSwitch(ret);
for(int i = 0; i < args.size(); ++i){
Value arg = (Value) args.get(i);
arg.apply(quick_value_switch);
if(i < args.size() - 1)
ret.append(",\n ");
}
ret.append(", exception");
ret.append(")");
if(isConstructor()){
ret.append(")");
}
return ret.toString();
}
public boolean isConstructor(){
String method_name = m_sootMethod.getName();
if(method_name.equals("<init>"))
return true;
return false;
}
public String getPolymorphicName(){
return getPolymorphicNameInternal(false);
}
private String getPolymorphicNameInternal(boolean ctor_body){
String ret = getBaseMethodName();
if(ctor_body){
ret += "_body";
}
String signature = m_sootMethod.getSignature();
if(m_dontMangleMethods.contains(signature) == false)
ret += NameMangling.v().mangleArgs(m_sootMethod);
return ret;
}
private String getBaseMethodName(){
//if we are here and a method is not concrete, it is the case where a
//invoke expresion is to an interface pointer and the method is not polymorphic
if(m_sootMethod.isConcrete() == false){
Set<String> virtual_signatures = RootbeerClassLoader.v().getVirtualSignaturesDown(m_sootMethod);
//double check that we are safe to do the interface remapping
if(virtual_signatures.size() != 1){
//not safe, go back to normal method
return getBaseMethodName(m_sootClass, m_sootMethod);
} else {
String signature = virtual_signatures.iterator().next();
MethodSignatureUtil util = new MethodSignatureUtil();
util.parse(signature);
SootMethod soot_method = util.getSootMethod();
SootClass soot_class = soot_method.getDeclaringClass();
return getBaseMethodName(soot_class, soot_method);
}
} else {
return getBaseMethodName(m_sootClass, m_sootMethod);
}
}
private String getBaseMethodName(SootClass soot_class, SootMethod soot_method){
OpenCLClass ocl_class = new OpenCLClass(soot_class);
String method_name = soot_method.getName();
//here I use a certain uuid for init so there is low chance of collisions
method_name = method_name.replace("<init>", "init"+OpenCLScene.v().getUuid());
String ret = ocl_class.getName()+"_"+method_name;
return ret;
}
private boolean shouldEmitBody(){
String signature = m_sootMethod.getSignature();
if(m_emitUnmangled.contains(signature)){
return true;
}
if(m_dontMangleMethods.contains(signature)){
return false;
}
return true;
}
@Override
public String toString(){
return getPolymorphicName();
}
private boolean methodIsRuntimeBasicBlockRun() {
if(m_sootClass.getName().equals("edu.syr.pcpratts.javaautogpu.runtime.RuntimeBasicBlock") == false)
return false;
if(m_sootMethod.getName().equals("run") == false)
return false;
return true;
}
public boolean returnsAValue() {
if(isConstructor())
return true;
Type t = m_sootMethod.getReturnType();
if(t instanceof VoidType)
return false;
return true;
}
public boolean isSynchronized() {
return m_sootMethod.isSynchronized();
}
private void createDontMangleMethods() {
m_dontMangleMethods = new HashSet<String>();
m_emitUnmangled = new HashSet<String>();
m_dontMangleMethods.add("<java.lang.StrictMath: double exp(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double log(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double log10(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double log(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double sqrt(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double cbrt(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double IEEEremainder(double,double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double ceil(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double floor(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double sin(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double cos(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double tan(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double asin(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double acos(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double atan(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double atan2(double,double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double pow(double,double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double sinh(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double cosh(double)>");
m_dontMangleMethods.add("<java.lang.StrictMath: double tanh(double)>");
m_dontMangleMethods.add("<java.lang.Double: long doubleToLongBits(double)>");
m_dontMangleMethods.add("<java.lang.Double: double longBitsToDouble(long)>");
m_dontMangleMethods.add("<java.lang.Float: int floatToIntBits(float)>");
m_dontMangleMethods.add("<java.lang.Float: float intBitsToFloat(int)>");
m_dontMangleMethods.add("<java.lang.System: void arraycopy(java.lang.Object,int,java.lang.Object,int,int)>");
m_dontMangleMethods.add("<java.lang.Throwable: java.lang.Throwable fillInStackTrace()>");
m_dontMangleMethods.add("<java.lang.Throwable: int getStackTraceDepth()>");
m_dontMangleMethods.add("<java.lang.Throwable: java.lang.StackTraceElement getStackTraceElement(int)>");
m_dontMangleMethods.add("<java.lang.Object: java.lang.Object clone()>");
m_dontMangleMethods.add("<java.lang.Object: int hashCode()>");
m_dontMangleMethods.add("<java.lang.OutOfMemoryError: void <init>()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: boolean isOnGpu()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: int getThreadId()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: int getThreadIdxx()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: int getBlockIdxx()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: int getBlockDimx()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: long getRef(java.lang.Object)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void synchthreads()>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: byte getSharedByte(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedByte(int,byte)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: char getSharedChar(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedChar(int,char)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: boolean getSharedBoolean(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedBoolean(int,boolean)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: short getSharedShort(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedShort(int,short)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: int getSharedInteger(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedInteger(int,int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: long getSharedLong(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedLong(int,long)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: float getSharedFloat(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedFloat(int,float)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: double getSharedDouble(int)>");
m_dontMangleMethods.add("<edu.syr.pcpratts.rootbeer.runtime.RootbeerGpu: void setSharedDouble(int,double)>");
m_dontMangleMethods.add("<java.lang.System: long nanoTime()>");
m_dontMangleMethods.add("<java.lang.Class: java.lang.String getName()>");
m_dontMangleMethods.add("<java.lang.Object: java.lang.Class getClass()>");
m_dontMangleMethods.add("<java.lang.StringValue: char[] from(char[])");
m_dontMangleMethods.add("<java.lang.String: void <init>(char[])>");
m_emitUnmangled.add("<java.lang.String: void <init>(char[])>");
}
public String getSignature() {
return m_sootMethod.getSignature();
}
}
|
9243cc85bb7fdf3323994d2c05df8c65442388e0 | 7,059 | java | Java | archive/phase2/src/GraphPanel.java | Isinlor/DKE-Project | a25847acab9a79102977de08c389598f800c0579 | [
"MIT"
] | null | null | null | archive/phase2/src/GraphPanel.java | Isinlor/DKE-Project | a25847acab9a79102977de08c389598f800c0579 | [
"MIT"
] | 25 | 2018-10-05T19:36:48.000Z | 2019-01-16T04:31:35.000Z | archive/phase2/src/GraphPanel.java | Isinlor/DKE-Project | a25847acab9a79102977de08c389598f800c0579 | [
"MIT"
] | 2 | 2018-11-26T13:05:40.000Z | 2018-12-13T11:51:42.000Z | 26.04797 | 114 | 0.560703 | 1,002,780 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* The panel responsible for displaying a graph.
*
* It can generate visual representation of a graph. The arrangement is optimized.
*
* It can also indicate invalid edges as a hint.
*
* Original idea: Anna (see: sketchpad/anna/DrawingBoard.java)
* Implementation with graph arrangement optimization: Tomek
* Integration: Tomek
*/
public class GraphPanel extends JPanel {
protected Graph graph;
protected int panelWidth = 800;
protected int panelHeight = 600;
protected int vertexSize = 25;
protected Color defaultColor = Color.black;
protected boolean showEdgesValidation = false;
/**
* @param gameState
*/
public GraphPanel(GameState gameState) {
this.graph = gameState.getGraph();
vertexSize = vertexSize - Math.min(graph.getNumberOfVertices() / 5, 15); // allows to handle bigger graphs
initializeCoordinates();
setPreferredSize(new Dimension(
panelWidth, panelHeight
));
setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(new VertexClickListener(gameState, this, vertexSize));
}
/**
* A hint function. Allows to start displaying edge validation.
*/
public void showEdgesValidation() {
showEdgesValidation = true;
}
/**
* Initialize coordinates of vertices.
*/
private void initializeCoordinates() {
Vertex[] vertices = new Vertex[graph.getNumberOfVertices() + 1];
int coordinatesToSet = graph.getNumberOfVertices();
while(coordinatesToSet > 0) {
int x = (int)(Math.random()*(panelWidth - vertexSize*2));
int y = (int)(Math.random()*(panelHeight - vertexSize*2));
// creates spacing from the frame of graph panel
if(x < vertexSize || y < vertexSize) {
continue;
}
int index = (graph.getNumberOfVertices() - coordinatesToSet) + 1;
boolean hasOverlap = false;
for(int i = 1; i < index; i++) {
if(vertices[i].hasOverlap(x, y, vertexSize*3)) {
hasOverlap = true;
break;
}
}
if(hasOverlap) {
continue;
}
vertices[index] = new Vertex(x, y);
coordinatesToSet--;
}
graph.setVertices(vertices);
optimizeStrategyA(100000);
optimizeStrategyB(100000);
}
/**
* @param g
*/
public void paintComponent(Graphics g) {
// See: https://stackoverflow.com/a/13281121/893222
// without it panel get visual artifacts after repaint
super.paintComponent(g);
turnAntialiasingOn(g);
drawEdges(g);
drawVertices(g);
}
/**
* @param g
*/
protected void turnAntialiasingOn(Graphics g) {
((Graphics2D)g).setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
}
/**
* @param g
*/
protected void drawVertices(Graphics g) {
for(Vertex vertex: graph.getVertices()) {
//noinspection ConstantConditions
if(!(vertex instanceof Vertex)) { continue; }
if(vertex.hasColor()) {
// colored vertex
g.setColor(vertex.getColor());
g.fillOval(vertex.x, vertex.y, vertexSize, vertexSize);
} else {
// white space vertex
g.setColor(Color.white);
g.fillOval(vertex.x, vertex.y, vertexSize, vertexSize);
g.setColor(defaultColor);
g.drawOval(vertex.x, vertex.y, vertexSize, vertexSize);
}
}
}
/**
* @param g
*/
protected void drawEdges(Graphics g) {
graph.validateEdges();
Vertex[] vertices = graph.getVertices();
for(Edge edge: graph.getEdges()) {
g.setColor(showEdgesValidation ? edge.getColor() : defaultColor);
Vertex from = vertices[edge.from];
Vertex to = vertices[edge.to];
g.drawLine(from.x+vertexSize/2, from.y+vertexSize/2, to.x+vertexSize/2, to.y+vertexSize/2);
}
g.setColor(defaultColor); // reset color to default
}
/**
* Optimizes vertices location based on swaping each vertex position.
*
* @param limitOfIterations Allows to limit number of swaps for big graphs.
*/
protected void optimizeStrategyA(int limitOfIterations) {
int counter = 0;
int minDistance = Integer.MAX_VALUE;
for(int swapA = 1; swapA <= graph.getNumberOfVertices(); swapA++) {
for(int swapB = 1; swapB <= graph.getNumberOfVertices(); swapB++) {
if(counter > limitOfIterations) {
return;
}
swapCoordinates(swapA, swapB);
int distance = computeTotalDistance();
if(minDistance > distance) {
minDistance = distance;
} else {
swapCoordinates(swapA, swapB);
}
counter++;
}
}
}
/**
* Optimizes vertices location based on random swaps.
*
* @param iterations Number of random swaps to test.
*/
protected void optimizeStrategyB(int iterations) {
int minDistance = Integer.MAX_VALUE;
for(int i = 0; i < iterations; i++) {
int swapA = (int)(Math.random()*graph.getNumberOfVertices())+1;
int swapB = (int)(Math.random()*graph.getNumberOfVertices())+1;
swapCoordinates(swapA, swapB);
int distance = computeTotalDistance();
if(minDistance > distance) {
minDistance = distance;
} else {
swapCoordinates(swapA, swapB);
}
}
}
/**
* @param swapA
* @param swapB
*/
protected void swapCoordinates(int swapA, int swapB) {
Vertex[] vertices = graph.getVertices();
Vertex a = vertices[swapA];
Vertex b = vertices[swapB];
vertices[swapA] = b;
vertices[swapB] = a;
}
/**
* Computes total length of all edges based on vertices coordinates.
*
* Notice! The length is not euclidean. It's manhattan distance.
*
* @return Total length of edges.
*/
protected int computeTotalDistance() {
int distance = 0;
Vertex[] vertices = graph.getVertices();
for(int j = 0; j < graph.getEdges().length; j++) {
Edge edge = graph.getEdges()[j];
int vertexFrom = edge.from;
int vertexTo = edge.to;
Vertex from = vertices[vertexFrom];
Vertex to = vertices[vertexTo];
distance += Math.abs(from.x-to.x) + Math.abs(from.y-to.y);
}
return distance;
}
}
|
9243ccd77c5a0b0bf75d025e49b90e34cde8875e | 1,149 | java | Java | src/main/java/nextstep/subway/member/domain/Member.java | charllossdev/atdd-subway-service | f42aeb4cebb3bcea1cc336d5e4f4b967fa0aed23 | [
"MIT"
] | null | null | null | src/main/java/nextstep/subway/member/domain/Member.java | charllossdev/atdd-subway-service | f42aeb4cebb3bcea1cc336d5e4f4b967fa0aed23 | [
"MIT"
] | null | null | null | src/main/java/nextstep/subway/member/domain/Member.java | charllossdev/atdd-subway-service | f42aeb4cebb3bcea1cc336d5e4f4b967fa0aed23 | [
"MIT"
] | null | null | null | 24.446809 | 63 | 0.78416 | 1,002,781 | package nextstep.subway.member.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.apache.commons.lang3.StringUtils;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import nextstep.subway.BaseEntity;
import nextstep.subway.auth.application.AuthorizationException;
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
public class Member extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String password;
private Integer age;
public Member(String email, String password, Integer age) {
this.email = email;
this.password = password;
this.age = age;
}
public void update(Member member) {
this.email = member.email;
this.password = member.password;
this.age = member.age;
}
public void checkPassword(String password) {
if (!StringUtils.equals(this.password, password)) {
throw new AuthorizationException("비밀번호가 틀렸습니다.");
}
}
}
|
9243cd64bcd1b6330027c9114bf5a3db19731b92 | 4,335 | java | Java | src/main/java/io/ebean/docker/commands/SqlServerContainer.java | FOCONIS/ebean-test-docker | ee2a1708b76edd1edd91e013ffde24563231b022 | [
"Apache-2.0"
] | 4 | 2018-11-29T02:13:59.000Z | 2019-08-28T10:44:50.000Z | src/main/java/io/ebean/docker/commands/SqlServerContainer.java | FOCONIS/ebean-test-docker | ee2a1708b76edd1edd91e013ffde24563231b022 | [
"Apache-2.0"
] | 43 | 2018-03-27T03:39:19.000Z | 2022-02-28T05:12:14.000Z | src/main/java/io/ebean/docker/commands/SqlServerContainer.java | FOCONIS/ebean-test-docker | ee2a1708b76edd1edd91e013ffde24563231b022 | [
"Apache-2.0"
] | 2 | 2018-10-08T07:35:21.000Z | 2021-11-22T14:28:23.000Z | 30.528169 | 108 | 0.700115 | 1,002,782 | package io.ebean.docker.commands;
import io.ebean.docker.container.Container;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
/**
* Commands for controlling a SqlServer docker container.
*/
public class SqlServerContainer extends JdbcBaseDbContainer implements Container {
public static SqlServerContainer create(String version, Properties properties) {
return new SqlServerContainer(new SqlServerConfig(version, properties));
}
public SqlServerContainer(SqlServerConfig config) {
super(config);
}
@Override
void createDatabase() {
createRoleAndDatabase(false);
}
@Override
void dropCreateDatabase() {
createRoleAndDatabase(true);
}
private void createRoleAndDatabase(boolean withDrop) {
try (Connection connection = config.createAdminConnection()) {
if (withDrop) {
dropDatabaseIfExists(connection);
}
createDatabase(connection);
createLogin(connection);
createUser();
} catch (SQLException e) {
throw new RuntimeException("Error when creating database and role", e);
}
}
private void createUser() {
try (Connection dbConnection = dbConfig.createAdminConnection(dbConfig.jdbcUrl())) {
createUser(dbConnection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void createLogin(Connection connection) {
if (!loginExists(connection, dbConfig.getUsername())) {
createLogin(connection, dbConfig.getUsername(), dbConfig.getPassword());
}
}
private void createUser(Connection dbConnection) {
if (!userExists(dbConnection, dbConfig.getUsername())) {
createUser(dbConnection, dbConfig.getUsername(), dbConfig.getUsername());
grantOwner(dbConnection, dbConfig.getUsername());
}
}
private void createDatabase(Connection connection) {
if (!databaseExists(connection, dbConfig.getDbName())) {
createDatabase(connection, dbConfig.getDbName());
}
}
private void dropDatabaseIfExists(Connection connection) {
if (databaseExists(connection, dbConfig.getDbName())) {
dropDatabase(connection, dbConfig.getDbName());
}
}
private void dropDatabase(Connection connection, String dbName) {
sqlRun(connection, "drop database " + dbName);
}
// private void dropLogin(Connection connection) {
// if (loginExists(connection, dbConfig.username)) {
// sqlRun(connection, "drop login " + dbConfig.username);
// }
// }
private void createDatabase(Connection connection, String dbName) {
sqlRun(connection, "create database " + dbName);
}
private void createLogin(Connection connection, String login, String pass) {
sqlRun(connection, "create login " + login + " with password = '" + pass + "'");
}
private void createUser(Connection dbConnection, String roleName, String login) {
sqlRun(dbConnection, "create user " + roleName + " for login " + login);
}
private void grantOwner(Connection dbConnection, String roleName) {
sqlRun(dbConnection, "exec sp_addrolemember 'db_owner', " + roleName);
}
private boolean userExists(Connection dbConnection, String userName) {
return sqlHasRow(dbConnection, "select 1 from sys.database_principals where name = '" + userName + "'");
}
private boolean loginExists(Connection connection, String roleName) {
return sqlHasRow(connection, "select 1 from master.dbo.syslogins where loginname = '" + roleName + "'");
}
private boolean databaseExists(Connection connection, String dbName) {
return sqlHasRow(connection, "select 1 from sys.databases where name='" + dbName + "'");
}
@Override
protected ProcessBuilder runProcess() {
List<String> args = dockerRun();
args.add("-e");
args.add("ACCEPT_EULA=Y");
args.add("-e");
args.add("SA_PASSWORD=" + dbConfig.getAdminPassword());
if (config.isDefaultCollation()) {
// do nothing, use server default
} else if (config.isExplicitCollation()) {
args.add("-e");
args.add("MSSQL_COLLATION=" + dbConfig.getCollation());
} else {
// use case sensitive collation by default
args.add("-e");
args.add("MSSQL_COLLATION=Latin1_General_100_BIN2");
}
args.add(config.getImage());
return createProcessBuilder(args);
}
}
|
9243cd819eecb932be81de86f4e5e5cf310d6c4c | 1,653 | java | Java | rule-engine-web/src/main/java/cn/ruleengine/web/service/impl/RuleEngineConditionGroupServiceImpl.java | zhaojc/rule-engine | 499c3f74a329109c235432e1a5f06d6e334d4ea8 | [
"Apache-2.0"
] | 3 | 2021-12-09T15:38:37.000Z | 2022-02-24T03:21:40.000Z | rule-engine-web/src/main/java/cn/ruleengine/web/service/impl/RuleEngineConditionGroupServiceImpl.java | lihjchain/rule-engine | cfacd6f9437f42195e8217f3029957641df5dd6d | [
"Apache-2.0"
] | null | null | null | rule-engine-web/src/main/java/cn/ruleengine/web/service/impl/RuleEngineConditionGroupServiceImpl.java | lihjchain/rule-engine | cfacd6f9437f42195e8217f3029957641df5dd6d | [
"Apache-2.0"
] | 2 | 2021-04-15T02:27:09.000Z | 2022-01-27T07:16:29.000Z | 29 | 102 | 0.753176 | 1,002,783 | package cn.ruleengine.web.service.impl;
import cn.ruleengine.web.service.RuleEngineConditionGroupService;
import cn.ruleengine.web.store.entity.RuleEngineConditionGroup;
import cn.ruleengine.web.store.manager.RuleEngineConditionGroupManager;
import cn.ruleengine.web.vo.condition.group.SaveOrUpdateConditionGroup;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 〈一句话功能简述〉<br>
* 〈〉
*
* @author dingqianwen
* @date 2020/8/28
* @since 1.0.0
*/
@Service
public class RuleEngineConditionGroupServiceImpl implements RuleEngineConditionGroupService {
@Resource
private RuleEngineConditionGroupManager ruleEngineConditionGroupManager;
/**
* 保存或者更新条件组
*
* @param saveOrUpdateConditionGroup 条件组信息
* @return int
*/
@Override
public Integer saveOrUpdateConditionGroup(SaveOrUpdateConditionGroup saveOrUpdateConditionGroup) {
RuleEngineConditionGroup engineConditionGroup = new RuleEngineConditionGroup();
engineConditionGroup.setId(saveOrUpdateConditionGroup.getId());
engineConditionGroup.setName(saveOrUpdateConditionGroup.getName());
engineConditionGroup.setRuleId(saveOrUpdateConditionGroup.getRuleId());
engineConditionGroup.setOrderNo(saveOrUpdateConditionGroup.getOrderNo());
this.ruleEngineConditionGroupManager.saveOrUpdate(engineConditionGroup);
return engineConditionGroup.getId();
}
/**
* 删除条件组
*
* @param id 条件组id
* @return true
*/
@Override
public Boolean delete(Integer id) {
return this.ruleEngineConditionGroupManager.removeById(id);
}
}
|
9243ceacf42f464edfa488395ac59085214c4d06 | 1,261 | java | Java | src/main/java/de/tum/flexsmc/smc/config/BgwSuite.java | grandcat/flexsmc-fresco | 57cfed7a7ccfa4ce751f979919d6f8fe64c4982a | [
"Apache-2.0"
] | null | null | null | src/main/java/de/tum/flexsmc/smc/config/BgwSuite.java | grandcat/flexsmc-fresco | 57cfed7a7ccfa4ce751f979919d6f8fe64c4982a | [
"Apache-2.0"
] | null | null | null | src/main/java/de/tum/flexsmc/smc/config/BgwSuite.java | grandcat/flexsmc-fresco | 57cfed7a7ccfa4ce751f979919d6f8fe64c4982a | [
"Apache-2.0"
] | null | null | null | 25.734694 | 91 | 0.748612 | 1,002,784 | package de.tum.flexsmc.smc.config;
import java.math.BigInteger;
import java.util.logging.Logger;
import dk.alexandra.fresco.framework.sce.configuration.SCEConfiguration;
import dk.alexandra.fresco.suite.bgw.configuration.BgwConfiguration;
public class BgwSuite implements BgwConfiguration {
private static final Logger l = Logger.getLogger(BgwSuite.class.getName());
private static BigInteger DEFAULT_MODULUS = new BigInteger("618970019642690137449562111");
private int threshold;
private BigInteger modulus;
public BgwSuite(SCEConfiguration sceConf) {
modulus = DEFAULT_MODULUS;
// Allow < n/2 parties to be corrupt
threshold = ((int) Math.ceil((double) sceConf.getParties().size() / 2.0)) - 1;
if (threshold < 0) {
threshold = 0;
l.severe("BGW: not enough parties to provide any protection for corruption");
}
}
public BgwSuite(int threshold) {
this.threshold = threshold;
modulus = DEFAULT_MODULUS;
}
public BgwSuite(int threshold, BigInteger modulus) {
this.threshold = threshold;
this.modulus = modulus;
}
@Override
public int getThreshold() {
// TODO Auto-generated method stub
return threshold;
}
@Override
public BigInteger getModulus() {
// TODO Auto-generated method stub
return modulus;
}
}
|
9243cf693cdb390f649a26bd6c7b835f8ecd43ff | 1,534 | java | Java | src/main/java/com/bmtc/task/domain/ExecutePlanScriptDO.java | caizhenxing/mobileAutoTest | b738c64ac871ac30f8d7ec8df59809fc322397be | [
"Apache-2.0"
] | 1 | 2021-04-10T15:09:27.000Z | 2021-04-10T15:09:27.000Z | src/main/java/com/bmtc/task/domain/ExecutePlanScriptDO.java | caizhenxing/mobileAutoTest | b738c64ac871ac30f8d7ec8df59809fc322397be | [
"Apache-2.0"
] | null | null | null | src/main/java/com/bmtc/task/domain/ExecutePlanScriptDO.java | caizhenxing/mobileAutoTest | b738c64ac871ac30f8d7ec8df59809fc322397be | [
"Apache-2.0"
] | null | null | null | 20.453333 | 63 | 0.664928 | 1,002,785 | package com.bmtc.task.domain;
import java.io.Serializable;
/**
* 执行计划和脚本关联的实体类
* @author Administrator
*
*/
public class ExecutePlanScriptDO implements Serializable{
/**
* 属性
*/
private static final long serialVersionUID = 1L;
// 主键id
private String id;
// 测试任务id
private Long executePlanId;
// 脚本id
private Long scriptId;
// 选中的caseName
private String checkedCaseName;
/**
* 构造
*/
public ExecutePlanScriptDO() {
super();
}
public ExecutePlanScriptDO(Long executePlanId, Long scriptId,
String checkedCaseName) {
super();
this.executePlanId = executePlanId;
this.scriptId = scriptId;
this.checkedCaseName = checkedCaseName;
}
/**
* set&get
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getExecutePlanId() {
return executePlanId;
}
public void setExecutePlanId(Long executePlanId) {
this.executePlanId = executePlanId;
}
public Long getScriptId() {
return scriptId;
}
public void setScriptId(Long scriptId) {
this.scriptId = scriptId;
}
public String getCheckedCaseName() {
return checkedCaseName;
}
public void setCheckedCaseName(String checkedCaseName) {
this.checkedCaseName = checkedCaseName;
}
/**
* toString
*/
@Override
public String toString() {
return "ExecutePlanScriptDO [id=" + id + ", executePlanId="
+ executePlanId + ", scriptId=" + scriptId
+ ", checkedCaseName=" + checkedCaseName + "]";
}
}
|
9243cfa26ec1024335e40ea4a8afafd4e895004d | 373 | java | Java | collections/src/main/java/com/wildbeeslabs/jentle/collections/graph2/Edge.java | AlexRogalskiy/jentle | 5d6f9feee02902cb0a330c7359c0c268feed2015 | [
"MIT"
] | null | null | null | collections/src/main/java/com/wildbeeslabs/jentle/collections/graph2/Edge.java | AlexRogalskiy/jentle | 5d6f9feee02902cb0a330c7359c0c268feed2015 | [
"MIT"
] | 12 | 2019-11-13T09:35:37.000Z | 2021-12-09T20:59:29.000Z | collections/src/main/java/com/wildbeeslabs/jentle/collections/graph2/Edge.java | AlexRogalskiy/jentle | 5d6f9feee02902cb0a330c7359c0c268feed2015 | [
"MIT"
] | null | null | null | 16.954545 | 51 | 0.573727 | 1,002,786 | package com.wildbeeslabs.jentle.collections.graph2;
public class Edge {
private final String id1;
private final String id2;
public Edge(final String id1,
final String id2) {
this.id1 = id1;
this.id2 = id2;
}
public String getId1() {
return id1;
}
public String getId2() {
return id2;
}
}
|
9243d012c4b157af2a1e9e7b7d2f1458aab5ba1f | 2,264 | java | Java | src/main/java/com/gmail/mediusecho/livecraft_spigot_essentials/modules/sleepvote/SleepvoteEssentialsHook.java | Livecraft-Server/livecraft-spigot-essentials | 5942f720a49eae37ab77f602256ca577b3b8b17b | [
"MIT"
] | null | null | null | src/main/java/com/gmail/mediusecho/livecraft_spigot_essentials/modules/sleepvote/SleepvoteEssentialsHook.java | Livecraft-Server/livecraft-spigot-essentials | 5942f720a49eae37ab77f602256ca577b3b8b17b | [
"MIT"
] | null | null | null | src/main/java/com/gmail/mediusecho/livecraft_spigot_essentials/modules/sleepvote/SleepvoteEssentialsHook.java | Livecraft-Server/livecraft-spigot-essentials | 5942f720a49eae37ab77f602256ca577b3b8b17b | [
"MIT"
] | null | null | null | 39.034483 | 97 | 0.749117 | 1,002,787 | /*
* Copyright (c) 2020 Jacob (MediusEcho)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the “Software”), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.gmail.mediusecho.livecraft_spigot_essentials.modules.sleepvote;
import com.earth2me.essentials.Essentials;
import net.ess3.api.events.AfkStatusChangeEvent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
public class SleepvoteEssentialsHook implements Listener {
private final SleepvoteModule sleepvoteModule;
private Essentials essentials;
public SleepvoteEssentialsHook (final SleepvoteModule sleepvoteModule)
{
this.sleepvoteModule = sleepvoteModule;
essentials = (Essentials) Essentials.getProvidingPlugin(Essentials.class);
}
/**
* Checks to see if this player is AFK
*
* @param player
* The player to check
* @return
* Boolean
*/
public boolean isPlayerAfk (Player player) {
return essentials.getUser(player).isAfk();
}
@EventHandler
public void onPlayerAfkStatusChange (@NotNull AfkStatusChangeEvent event) {
sleepvoteModule.onPlayerAfkStatusToggle(event.getAffected().getBase(), event.getValue());
}
}
|
9243d14f18e18d651bf40e8dc1644a367d244cc8 | 1,555 | java | Java | src/test/java/io/stoks/SampleServiceTests.java | salvitas/springboot-eureka-service | f4825d04cdc3773874160a633ba60551d4a50daf | [
"Apache-2.0"
] | null | null | null | src/test/java/io/stoks/SampleServiceTests.java | salvitas/springboot-eureka-service | f4825d04cdc3773874160a633ba60551d4a50daf | [
"Apache-2.0"
] | null | null | null | src/test/java/io/stoks/SampleServiceTests.java | salvitas/springboot-eureka-service | f4825d04cdc3773874160a633ba60551d4a50daf | [
"Apache-2.0"
] | null | null | null | 27.280702 | 86 | 0.654019 | 1,002,788 | package io.stoks;
import io.generated.stoks.model.Sampleres;
import io.stoks.mappers.SampleMapper;
import io.stoks.repositories.SampleDTO;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest()
public class SampleServiceTests {
@Autowired
private SampleMapper sampleMapper;
@Test
public void contextLoads() {
assertNotNull(sampleMapper);
}
@Test
public void testFormat() {
String f = new DecimalFormat("#0.##").format(new BigDecimal("-2.9900000000"));
System.out.println(f);
}
@Test
public void givenDestinationToSource_whenMaps_thenCorrect() {
SampleDTO sampleDTO = SampleDTO.builder()
.name("name")
.externalId("externalid-1")
.alias("salva")
.balance(new BigDecimal("090.00"))
.currency("USD")
.customerId("475142622")
.number("12345678909")
.status("ACTIVE")
.type("CURRENT_ACCOUNT")
.build();
Sampleres source = sampleMapper.convertToModel(sampleDTO);
Assertions.assertEquals(sampleDTO.getName(), source.getName());
Assertions.assertEquals(sampleDTO.getBalance(), source.getBalance());
}
}
|
9243d203c4c5d27b569f1d8b86fb2250e6b3b2dd | 981 | java | Java | src/main/java/com/maxmind/geoip2/GeoIp2Provider.java | 6si/GeoIP2-java | dd70ac38cf63ea4c35fd60c56a2b7f98878bf06c | [
"Apache-2.0"
] | 606 | 2015-01-22T17:12:27.000Z | 2022-03-31T03:18:29.000Z | src/main/java/com/maxmind/geoip2/GeoIp2Provider.java | 6si/GeoIP2-java | dd70ac38cf63ea4c35fd60c56a2b7f98878bf06c | [
"Apache-2.0"
] | 183 | 2015-02-25T08:14:02.000Z | 2022-03-30T19:15:02.000Z | src/main/java/com/maxmind/geoip2/GeoIp2Provider.java | 6si/GeoIP2-java | dd70ac38cf63ea4c35fd60c56a2b7f98878bf06c | [
"Apache-2.0"
] | 192 | 2015-01-21T10:08:20.000Z | 2022-03-25T10:32:54.000Z | 32.7 | 70 | 0.714577 | 1,002,789 | package com.maxmind.geoip2;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import java.io.IOException;
import java.net.InetAddress;
public interface GeoIp2Provider {
/**
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return A Country model for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
CountryResponse country(InetAddress ipAddress) throws IOException,
GeoIp2Exception;
/**
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return A City model for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
CityResponse city(InetAddress ipAddress) throws IOException,
GeoIp2Exception;
}
|
9243d23adf206dbecbd3512365f47ef4db4ed21b | 5,486 | java | Java | src/test/java/org/openwms/core/uaa/auth/LoginControllerDocumentation.java | lslog/org.openwms.core.uaa_fork | db7dc5d8011342a549251ae4de6be99db9c88e31 | [
"Apache-2.0"
] | 4 | 2018-12-29T07:40:05.000Z | 2021-11-28T14:29:18.000Z | src/test/java/org/openwms/core/uaa/auth/LoginControllerDocumentation.java | lslog/org.openwms.core.uaa_fork | db7dc5d8011342a549251ae4de6be99db9c88e31 | [
"Apache-2.0"
] | 18 | 2017-03-22T17:52:49.000Z | 2021-09-21T21:39:53.000Z | src/test/java/org/openwms/core/uaa/auth/LoginControllerDocumentation.java | lslog/org.openwms.core.uaa_fork | db7dc5d8011342a549251ae4de6be99db9c88e31 | [
"Apache-2.0"
] | 7 | 2019-04-15T04:28:47.000Z | 2021-05-27T06:48:07.000Z | 47.293103 | 103 | 0.670069 | 1,002,790 | /*
* Copyright 2005-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.openwms.core.uaa.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openwms.core.UAAApplicationTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.Filter;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* A LoginControllerDocumentation.
*
* @author Heiko Scherrer
*/
@Sql({"classpath:test.sql"})
@UAAApplicationTest
class LoginControllerDocumentation {
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@Qualifier(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
@Autowired
private Filter springSecurityFilterChain;
@Autowired
private OAuthHelper helper;
/**
* Do something before each test method.
*/
@BeforeEach
void setUp(RestDocumentationContextProvider restDocumentation, WebApplicationContext context) {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilter(springSecurityFilterChain)
.apply(documentationConfiguration(restDocumentation))
.build();
}
@Test
void shall_find_user() throws Exception {
RequestPostProcessor bearerToken = helper.bearerToken("gateway");
mockMvc.perform(
get("/oauth/userinfo").with(bearerToken))
.andDo(document("oauth-findUserInfo",
preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("sub").description("Subject is the logged in end-user"),
fieldWithPath("gender").description("The end-users gender"),
fieldWithPath("name").description("Name of the end-user"),
fieldWithPath("phone_number").description("Her phone number"),
fieldWithPath("given_name").description("The given name"),
fieldWithPath("family_name").description("Her family name"),
fieldWithPath("email").description("Her primary email address"),
fieldWithPath("picture").description("A link to a profile picture")
)
))
.andExpect(status().isOk())
;
}
// @Test
void shall_not_find_user() throws Exception {
RequestPostProcessor bearerToken = helper.bearerToken("UNKNOWN");
mockMvc.perform(
get("/oauth/userinfo").with(bearerToken))
.andDo(document("oauth-findUserInfo",
preprocessResponse(prettyPrint()),
responseFields(
fieldWithPath("sub").description("Subject is the logged in end-user"),
fieldWithPath("gender").description("The end-users gender"),
fieldWithPath("name").description("Name of the end-user"),
fieldWithPath("phone_number").description("Her phone number"),
fieldWithPath("given_name").description("The given name"),
fieldWithPath("family_name").description("Her family name"),
fieldWithPath("email").description("Her primary email address"),
fieldWithPath("picture").description("A link to a profile picture")
)
))
.andExpect(status().isOk())
;
}
}
|
9243d3a3c213ebc87269473ee7fb83345716e413 | 17,690 | java | Java | modules/gui/src/com/haulmont/reports/gui/report/wizard/RegionsStepFrame.java | klaus7/reports | b1ae74dcc8048a494f268c3c219fc6bee4e31d5b | [
"Apache-2.0"
] | 10 | 2018-07-05T13:35:03.000Z | 2021-02-08T11:45:33.000Z | modules/gui/src/com/haulmont/reports/gui/report/wizard/RegionsStepFrame.java | klaus7/reports | b1ae74dcc8048a494f268c3c219fc6bee4e31d5b | [
"Apache-2.0"
] | 239 | 2018-04-06T08:56:02.000Z | 2022-01-12T06:50:58.000Z | modules/gui/src/com/haulmont/reports/gui/report/wizard/RegionsStepFrame.java | klaus7/reports | b1ae74dcc8048a494f268c3c219fc6bee4e31d5b | [
"Apache-2.0"
] | 6 | 2019-10-03T04:31:46.000Z | 2022-02-22T15:31:35.000Z | 46.675462 | 162 | 0.65082 | 1,002,791 | /*
* Copyright (c) 2008-2019 Haulmont.
*
* 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.haulmont.reports.gui.report.wizard;
import com.haulmont.cuba.gui.WindowManager.OpenType;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.DialogAction.Type;
import com.haulmont.reports.entity.wizard.EntityTreeNode;
import com.haulmont.reports.entity.wizard.RegionProperty;
import com.haulmont.reports.entity.wizard.ReportData.ReportType;
import com.haulmont.reports.entity.wizard.ReportRegion;
import com.haulmont.reports.gui.components.actions.OrderableItemMoveAction;
import com.haulmont.reports.gui.components.actions.OrderableItemMoveAction.Direction;
import com.haulmont.reports.gui.report.wizard.step.StepFrame;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RegionsStepFrame extends StepFrame {
protected static final String ADD_TABULATED_REGION_ACTION_ID = "tabulatedRegion";
protected static final String ADD_SIMPLE_REGION_ACTION_ID = "simpleRegion";
protected AddSimpleRegionAction addSimpleRegionAction;
protected AddTabulatedRegionAction addTabulatedRegionAction;
protected EditRegionAction editRegionAction;
protected RemoveRegionAction removeRegionAction;
public RegionsStepFrame(ReportWizardCreator wizard) {
super(wizard, wizard.getMessage("reportRegions"), "regionsStep");
initFrameHandler = new InitRegionsStepFrameHandler();
beforeShowFrameHandler = new BeforeShowRegionsStepFrameHandler();
beforeHideFrameHandler = new BeforeHideRegionsStepFrameHandler();
}
protected abstract class AddRegionAction extends AbstractAction {
protected AddRegionAction(String id) {
super(id);
}
protected ReportRegion createReportRegion(boolean tabulated) {
ReportRegion reportRegion = wizard.metadata.create(ReportRegion.class);
reportRegion.setReportData(wizard.getItem());
reportRegion.setIsTabulatedRegion(tabulated);
reportRegion.setOrderNum((long) wizard.getItem().getReportRegions().size() + 1L);
return reportRegion;
}
protected void openTabulatedRegionEditor(final ReportRegion item) {
if (ReportType.SINGLE_ENTITY == wizard.reportTypeOptionGroup.getValue()) {
openRegionEditorOnlyWithNestedCollections(item);
} else {
openRegionEditor(item);
}
}
private void openRegionEditorOnlyWithNestedCollections(final ReportRegion item) {//show lookup for choosing parent collection for tabulated region
final Map<String, Object> lookupParams = new HashMap<>();
lookupParams.put("rootEntity", wizard.getItem().getEntityTreeRootNode());
lookupParams.put("collectionsOnly", Boolean.TRUE);
lookupParams.put("persistentOnly", ReportType.LIST_OF_ENTITIES_WITH_QUERY == wizard.reportTypeOptionGroup.getValue());
wizard.openLookup("report$ReportEntityTree.lookup", items -> {
if (items.size() == 1) {
EntityTreeNode regionPropertiesRootNode = (EntityTreeNode) CollectionUtils.get(items, 0);
Map<String, Object> editorParams = new HashMap<>();
editorParams.put("scalarOnly", Boolean.TRUE);
editorParams.put("persistentOnly", ReportType.LIST_OF_ENTITIES_WITH_QUERY == wizard.reportTypeOptionGroup.getValue());
editorParams.put("rootEntity", regionPropertiesRootNode);
item.setRegionPropertiesRootNode(regionPropertiesRootNode);
Window.Editor regionEditor = wizard.openEditor("report$Report.regionEditor", item,
OpenType.DIALOG, editorParams, wizard.reportRegionsDs);
regionEditor.addCloseListener(new RegionEditorCloseListener());
}
}, OpenType.DIALOG, lookupParams);
}
protected void openRegionEditor(ReportRegion item) {
item.setRegionPropertiesRootNode(wizard.getItem().getEntityTreeRootNode());
Map<String, Object> editorParams = new HashMap<>();
editorParams.put("rootEntity", wizard.getItem().getEntityTreeRootNode());
editorParams.put("scalarOnly", Boolean.TRUE);
editorParams.put("persistentOnly", ReportType.LIST_OF_ENTITIES_WITH_QUERY == wizard.reportTypeOptionGroup.getValue());
Window.Editor regionEditor = wizard.openEditor("report$Report.regionEditor", item,
OpenType.DIALOG, editorParams, wizard.reportRegionsDs);
regionEditor.addCloseListener(new AddRegionAction.RegionEditorCloseListener());
}
protected class RegionEditorCloseListener implements Window.CloseListener {
@Override
public void windowClosed(String actionId) {
if (Window.COMMIT_ACTION_ID.equals(actionId)) {
wizard.regionsTable.refresh();
wizard.setupButtonsVisibility();
}
}
}
}
protected class AddSimpleRegionAction extends AddRegionAction {
public AddSimpleRegionAction() {
super(ADD_SIMPLE_REGION_ACTION_ID);
}
@Override
public void actionPerform(Component component) {
openRegionEditor(createReportRegion(false));
}
}
protected class AddTabulatedRegionAction extends AddRegionAction {
public AddTabulatedRegionAction() {
super(ADD_TABULATED_REGION_ACTION_ID);
}
@Override
public void actionPerform(Component component) {
openTabulatedRegionEditor(createReportRegion(true));
}
}
protected class ReportRegionTableColumnGenerator implements Table.ColumnGenerator<ReportRegion> {
protected static final String WIDTH_PERCENT_100 = "100%";
protected static final int MAX_ATTRS_BTN_CAPTION_WIDTH = 95;
protected static final String BOLD_LABEL_STYLE = "semi-bold-label";
private ReportRegion currentReportRegionGeneratedColumn;
@Override
public Component generateCell(ReportRegion entity) {
currentReportRegionGeneratedColumn = entity;
BoxLayout mainLayout = wizard.componentsFactory.createComponent(VBoxLayout.class);
mainLayout.setWidth(WIDTH_PERCENT_100);
mainLayout.add(createFirstTwoRowsLayout());
mainLayout.add(createThirdRowAttrsLayout());
return mainLayout;
}
private BoxLayout createFirstTwoRowsLayout() {
BoxLayout firstTwoRowsLayout = wizard.componentsFactory.createComponent(HBoxLayout.class);
BoxLayout expandedAttrsLayout = createExpandedAttrsLayout();
firstTwoRowsLayout.setWidth(WIDTH_PERCENT_100);
firstTwoRowsLayout.add(expandedAttrsLayout);
firstTwoRowsLayout.add(createBtnsLayout());
firstTwoRowsLayout.expand(expandedAttrsLayout);
return firstTwoRowsLayout;
}
private BoxLayout createExpandedAttrsLayout() {
BoxLayout expandedAttrsLayout = wizard.componentsFactory.createComponent(HBoxLayout.class);
expandedAttrsLayout.setWidth(WIDTH_PERCENT_100);
expandedAttrsLayout.add(createFirstRowAttrsLayout());
expandedAttrsLayout.add(createSecondRowAttrsLayout());
return expandedAttrsLayout;
}
private BoxLayout createFirstRowAttrsLayout() {
BoxLayout firstRowAttrsLayout = wizard.componentsFactory.createComponent(HBoxLayout.class);
firstRowAttrsLayout.setSpacing(true);
Label regionLbl = wizard.componentsFactory.createComponent(Label.class);
regionLbl.setStyleName(BOLD_LABEL_STYLE);
regionLbl.setValue(wizard.getMessage("region"));
Label regionValueLbl = wizard.componentsFactory.createComponent(Label.class);
regionValueLbl.setValue(currentReportRegionGeneratedColumn.getName());
regionValueLbl.setWidth(WIDTH_PERCENT_100);
firstRowAttrsLayout.add(regionLbl);
firstRowAttrsLayout.add(regionValueLbl);
return firstRowAttrsLayout;
}
private BoxLayout createSecondRowAttrsLayout() {
BoxLayout secondRowAttrsLayout = wizard.componentsFactory.createComponent(HBoxLayout.class);
secondRowAttrsLayout.setSpacing(true);
Label entityLbl = wizard.componentsFactory.createComponent(Label.class);
entityLbl.setStyleName(BOLD_LABEL_STYLE);
entityLbl.setValue(wizard.getMessage("entity"));
Label entityValueLbl = wizard.componentsFactory.createComponent(Label.class);
entityValueLbl.setValue(wizard.messageTools.getEntityCaption(currentReportRegionGeneratedColumn.getRegionPropertiesRootNode().getWrappedMetaClass()));
entityValueLbl.setWidth(WIDTH_PERCENT_100);
secondRowAttrsLayout.add(entityLbl);
secondRowAttrsLayout.add(entityValueLbl);
return secondRowAttrsLayout;
}
private BoxLayout createBtnsLayout() {
BoxLayout btnsLayout = wizard.componentsFactory.createComponent(HBoxLayout.class);
btnsLayout.setSpacing(true);
btnsLayout.setStyleName("on-hover-visible-layout");
return btnsLayout;
}
private BoxLayout createThirdRowAttrsLayout() {
BoxLayout thirdRowAttrsLayout = wizard.componentsFactory.createComponent(HBoxLayout.class);
thirdRowAttrsLayout.setSpacing(true);
Label entityLbl = wizard.componentsFactory.createComponent(Label.class);
entityLbl.setStyleName(BOLD_LABEL_STYLE);
entityLbl.setValue(wizard.getMessage("attributes"));
Button editBtn = wizard.componentsFactory.createComponent(Button.class);
editBtn.setCaption(generateAttrsBtnCaption());
editBtn.setStyleName("link");
editBtn.setWidth(WIDTH_PERCENT_100);
editBtn.setAction(editRegionAction);
thirdRowAttrsLayout.add(entityLbl);
thirdRowAttrsLayout.add(editBtn);
return thirdRowAttrsLayout;
}
private String generateAttrsBtnCaption() {
return StringUtils.abbreviate(StringUtils.join(
CollectionUtils.collect(currentReportRegionGeneratedColumn.getRegionProperties(),
RegionProperty::getHierarchicalLocalizedNameExceptRoot), ", "
), MAX_ATTRS_BTN_CAPTION_WIDTH
);
}
}
protected class RemoveRegionAction extends AbstractAction {
public RemoveRegionAction() {
super("removeRegion");
}
@Override
public void actionPerform(Component component) {
if (wizard.regionsTable.getSingleSelected() != null) {
wizard.showOptionDialog(
wizard.getMessage("dialogs.Confirmation"),
wizard.formatMessage("deleteRegion", wizard.regionsTable.getSingleSelected().getName()),
Frame.MessageType.CONFIRMATION, new Action[]{
new DialogAction(Type.YES) {
@Override
public void actionPerform(Component component) {
wizard.reportRegionsDs.removeItem(wizard.regionsTable.getSingleSelected());
normalizeRegionPropertiesOrderNum();
wizard.regionsTable.refresh();
wizard.setupButtonsVisibility();
}
},
new DialogAction(Type.NO, Status.PRIMARY)
});
}
}
@Override
public String getCaption() {
return "";
}
protected void normalizeRegionPropertiesOrderNum() {
long normalizedIdx = 0;
List<ReportRegion> allItems = new ArrayList<>(wizard.reportRegionsDs.getItems());
for (ReportRegion item : allItems) {
item.setOrderNum(++normalizedIdx); //first must to be 1
}
}
}
protected class EditRegionAction extends AddRegionAction {
public EditRegionAction() {
super("removeRegion");
}
@Override
public void actionPerform(Component component) {
if (wizard.regionsTable.getSingleSelected() != null) {
Map<String, Object> editorParams = new HashMap<>();
editorParams.put("rootEntity", wizard.regionsTable.getSingleSelected().getRegionPropertiesRootNode());
editorParams.put("scalarOnly", Boolean.TRUE);
editorParams.put("persistentOnly", ReportType.LIST_OF_ENTITIES_WITH_QUERY == wizard.reportTypeOptionGroup.getValue());
Window.Editor regionEditor = wizard.openEditor("report$Report.regionEditor",
wizard.regionsTable.getSingleSelected(),
OpenType.DIALOG,
editorParams,
wizard.reportRegionsDs);
regionEditor.addCloseListener(new RegionEditorCloseListener());
}
}
@Override
public String getCaption() {
return "";
}
}
protected class InitRegionsStepFrameHandler implements InitStepFrameHandler {
@Override
public void initFrame() {
addSimpleRegionAction = new AddSimpleRegionAction();
addTabulatedRegionAction = new AddTabulatedRegionAction();
wizard.addSimpleRegionBtn.setAction(addSimpleRegionAction);
wizard.addTabulatedRegionBtn.setAction(addTabulatedRegionAction);
wizard.addRegionPopupBtn.addAction(addSimpleRegionAction);
wizard.addRegionPopupBtn.addAction(addTabulatedRegionAction);
wizard.regionsTable.addGeneratedColumn("regionsGeneratedColumn", new ReportRegionTableColumnGenerator());
editRegionAction = new EditRegionAction();
removeRegionAction = new RemoveRegionAction();
wizard.moveDownBtn.setAction(new OrderableItemMoveAction<>("downItem", Direction.DOWN, wizard.regionsTable));
wizard.moveUpBtn.setAction(new OrderableItemMoveAction<>("upItem", Direction.UP, wizard.regionsTable));
wizard.removeBtn.setAction(removeRegionAction);
}
}
protected class BeforeShowRegionsStepFrameHandler implements BeforeShowStepFrameHandler {
@Override
public void beforeShowFrame() {
wizard.setupButtonsVisibility();
wizard.runBtn.setAction(new AbstractAction("runReport") {
@Override
public void actionPerform(Component component) {
if (wizard.getItem().getReportRegions().isEmpty()) {
wizard.showNotification(wizard.getMessage("addRegionsWarn"), Frame.NotificationType.TRAY);
return;
}
wizard.lastGeneratedTmpReport = wizard.buildReport(true);
if (wizard.lastGeneratedTmpReport != null) {
wizard.reportGuiManager.runReport(
wizard.lastGeneratedTmpReport,
wizard);
}
}
});
showAddRegion();
wizard.setCorrectReportOutputType();
wizard.getWindow().setHeightAuto();
wizard.getDialogOptions().center();
}
private void showAddRegion() {
if (wizard.reportRegionsDs.getItems().isEmpty()) {
if (((ReportType) wizard.reportTypeOptionGroup.getValue()).isList()) {
if (wizard.entityTreeHasSimpleAttrs) {
addTabulatedRegionAction.actionPerform(wizard.regionsStepFrame.getFrame());
}
} else {
if (wizard.entityTreeHasSimpleAttrs && wizard.entityTreeHasCollections) {
addSimpleRegionAction.actionPerform(wizard.regionsStepFrame.getFrame());
} else if (wizard.entityTreeHasSimpleAttrs) {
addSimpleRegionAction.actionPerform(wizard.regionsStepFrame.getFrame());
} else if (wizard.entityTreeHasCollections) {
addTabulatedRegionAction.actionPerform(wizard.regionsStepFrame.getFrame());
}
}
}
}
}
protected class BeforeHideRegionsStepFrameHandler implements BeforeHideStepFrameHandler {
@Override
public void beforeHideFrame() {
}
}
} |
9243d3d1df1415e3a183d5c175d28390e0e5cf88 | 1,318 | java | Java | Ds/src/DAAAssessment/StringOfTwo.java | gsrsagar/Java-Ds-Algo-Practice | 92abc05347c2e468d67b650c460babf68bb8b6ac | [
"Apache-2.0"
] | null | null | null | Ds/src/DAAAssessment/StringOfTwo.java | gsrsagar/Java-Ds-Algo-Practice | 92abc05347c2e468d67b650c460babf68bb8b6ac | [
"Apache-2.0"
] | null | null | null | Ds/src/DAAAssessment/StringOfTwo.java | gsrsagar/Java-Ds-Algo-Practice | 92abc05347c2e468d67b650c460babf68bb8b6ac | [
"Apache-2.0"
] | null | null | null | 27.458333 | 84 | 0.515175 | 1,002,792 | package Ds.src.DAAAssessment;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class StringOfTwo {
static String stringWithTwo(String input){
String inputarray[]=input.split(" ");
String result="";
HashMap<String,Integer> hmap= new HashMap<>();
for(int i=0;i<inputarray.length;i++){
if(!hmap.isEmpty() && hmap.containsKey(inputarray[i])){
hmap.put(inputarray[i], Integer.valueOf(hmap.get(inputarray[i])+1));
}
else hmap.put(inputarray[i],1);
}
for(String key:hmap.keySet()){
if(hmap.get(key)==2){
result=key;
break;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String resultArray[]=new String[n];
int index=0;
while(n>0){
int length=sc.nextInt();
String input="";
for(int i=0;i<length;i++){
input+=sc.next();
input+=" ";
}
resultArray[index]=stringWithTwo(input);
index++;
n--;
}
System.out.println(Arrays.toString(resultArray));
sc.close();
}
}
|
9243d47e343c1b400674e7e6c5f1cfbd107a11ae | 2,802 | java | Java | Vguard_Automation/src/test/java/com/test/utility/TestUtilFillthebriefdetailsaboutCompany.java | Gauravkumarsinha007/AutomationProject_Guard | e81e3f698c3f3c437fa8097d864423e59fd107fe | [
"Apache-2.0"
] | 1 | 2020-05-06T07:39:54.000Z | 2020-05-06T07:39:54.000Z | Vguard_Automation/src/test/java/com/test/utility/TestUtilFillthebriefdetailsaboutCompany.java | gaurav150792/AutomationProject_Guard | e81e3f698c3f3c437fa8097d864423e59fd107fe | [
"Apache-2.0"
] | 5 | 2021-12-10T01:38:52.000Z | 2021-12-14T21:52:53.000Z | Vguard_Automation/src/test/java/com/test/utility/TestUtilFillthebriefdetailsaboutCompany.java | Gauravkumarsinha007/AutomationProject_Guard | e81e3f698c3f3c437fa8097d864423e59fd107fe | [
"Apache-2.0"
] | null | null | null | 36.38961 | 157 | 0.723412 | 1,002,793 | package com.test.utility;
import java.util.ArrayList;
import com.excel.utility.Xls_Reader;
public class TestUtilFillthebriefdetailsaboutCompany {
static Xls_Reader reader;
public static ArrayList<Object[]> GetDataFromExcel()
{
ArrayList<Object[]> myData= new ArrayList<Object[]>();
try {
reader = new Xls_Reader("C:\\Users\\AJN\\eclipse-workspace\\MavenEMP\\src\\test\\java\\com\\textdata\\EmployeeFeedbackDataDrivenTestingExcelSheet.xlsx");
}catch(Exception e)
{
e.printStackTrace();
}
for(int rowNum=2; rowNum <= reader.getRowCount("FillthebriefdetailsaboutCompany"); rowNum++)
{
String CIN = reader.getCellData("FillthebriefdetailsaboutCompany", "CIN", rowNum);
String foundername = reader.getCellData("FillthebriefdetailsaboutCompany", "foundername", rowNum);
String GST = reader.getCellData("FillthebriefdetailsaboutCompany", "GST", rowNum);
String PAN = reader.getCellData("FillthebriefdetailsaboutCompany", "PAN", rowNum);
String Directorname = reader.getCellData("FillthebriefdetailsaboutCompany", "Directorname", rowNum);
String DIN = reader.getCellData("FillthebriefdetailsaboutCompany", "DIN", rowNum);
String website = reader.getCellData("FillthebriefdetailsaboutCompany", "website", rowNum);
String companysize = reader.getCellData("FillthebriefdetailsaboutCompany", "companysize", rowNum);
String Turnover = reader.getCellData("FillthebriefdetailsaboutCompany", "Turnover", rowNum);
String officehour = reader.getCellData("FillthebriefdetailsaboutCompany", "officehour", rowNum);
String workingdays = reader.getCellData("FillthebriefdetailsaboutCompany", "workingdays", rowNum);
String leavespermonths = reader.getCellData("FillthebriefdetailsaboutCompany", "leavespermonths", rowNum);
String country = reader.getCellData("FillthebriefdetailsaboutCompany", "country", rowNum);
String state = reader.getCellData("FillthebriefdetailsaboutCompany", "state", rowNum);
String city = reader.getCellData("FillthebriefdetailsaboutCompany", "city", rowNum);
String pincode = reader.getCellData("FillthebriefdetailsaboutCompany", "pincode", rowNum);
String streetaddress = reader.getCellData("FillthebriefdetailsaboutCompany", "streetaddress", rowNum);
String copyverificationlink = reader.getCellData("FillthebriefdetailsaboutCompany", "copyverificationlink", rowNum);
Object ob[]= { CIN, foundername, GST, PAN, Directorname, DIN, website,
companysize, Turnover, officehour, workingdays, leavespermonths, country, state, city, pincode, streetaddress, copyverificationlink};
myData.add(ob);
}
return myData;
}
}
|
9243d4909634cf69cef71c2fd9daef97c214c456 | 2,272 | java | Java | webauthn4j-core/src/main/java/com/webauthn4j/data/PublicKeyCredentialParameters.java | bedrin/webauthn4j | 3fca0530ddd1760a665f0617a2d6ca44db9f4612 | [
"Apache-2.0"
] | null | null | null | webauthn4j-core/src/main/java/com/webauthn4j/data/PublicKeyCredentialParameters.java | bedrin/webauthn4j | 3fca0530ddd1760a665f0617a2d6ca44db9f4612 | [
"Apache-2.0"
] | null | null | null | webauthn4j-core/src/main/java/com/webauthn4j/data/PublicKeyCredentialParameters.java | bedrin/webauthn4j | 3fca0530ddd1760a665f0617a2d6ca44db9f4612 | [
"Apache-2.0"
] | null | null | null | 32 | 112 | 0.673856 | 1,002,794 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webauthn4j.data;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.webauthn4j.data.attestation.statement.COSEAlgorithmIdentifier;
import java.io.Serializable;
import java.util.Objects;
/**
* {@link PublicKeyCredentialParameters} is used to supply additional parameters when creating a new credential.
*
* @see <a href="https://www.w3.org/TR/webauthn-1/#dictdef-publickeycredentialparameters">
* §5.3. Parameters for Credential Generation (dictionary PublicKeyCredentialParameters)</a>
*/
public class PublicKeyCredentialParameters implements Serializable {
// ~ Instance fields
// ================================================================================================
private PublicKeyCredentialType type;
private COSEAlgorithmIdentifier alg;
@JsonCreator
public PublicKeyCredentialParameters(
@JsonProperty("type") PublicKeyCredentialType type,
@JsonProperty("alg") COSEAlgorithmIdentifier alg) {
this.type = type;
this.alg = alg;
}
public PublicKeyCredentialType getType() {
return type;
}
public COSEAlgorithmIdentifier getAlg() {
return alg;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PublicKeyCredentialParameters that = (PublicKeyCredentialParameters) o;
return type == that.type &&
alg == that.alg;
}
@Override
public int hashCode() {
return Objects.hash(type, alg);
}
}
|
9243d668db0e58ea01d2fb403a0bfd34c0b23314 | 8,321 | java | Java | main/plugins/org.talend.designer.components.libs/libs_src/mdm_services/src/main/java/org/talend/mdm/webservice/WSRunQuery.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 114 | 2015-03-05T15:34:59.000Z | 2022-02-22T03:48:44.000Z | main/plugins/org.talend.designer.components.libs/libs_src/mdm_services/src/main/java/org/talend/mdm/webservice/WSRunQuery.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 1,137 | 2015-03-04T01:35:42.000Z | 2022-03-29T06:03:17.000Z | main/plugins/org.talend.designer.components.libs/libs_src/mdm_services/src/main/java/org/talend/mdm/webservice/WSRunQuery.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 219 | 2015-01-21T10:42:18.000Z | 2022-02-17T07:57:20.000Z | 32.759843 | 117 | 0.589713 | 1,002,795 | /**
* WSRunQuery.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.talend.mdm.webservice;
/**
* Runs an xQuery on the XML DB in the revision ID, the Query is run
* from the DataCluster at the head
* The Data Cluster can be null to run cross-cluster queries
* ** !!! Use of this is fast but dangerous and makes !!!
* ** !!! code non portable accross xml servers !!!
*/
public class WSRunQuery implements java.io.Serializable {
private java.lang.String revisionID;
private org.talend.mdm.webservice.WSDataClusterPK wsDataClusterPK;
private java.lang.String query;
private java.lang.String[] parameters;
public WSRunQuery() {
}
public WSRunQuery(
java.lang.String revisionID,
org.talend.mdm.webservice.WSDataClusterPK wsDataClusterPK,
java.lang.String query,
java.lang.String[] parameters) {
this.revisionID = revisionID;
this.wsDataClusterPK = wsDataClusterPK;
this.query = query;
this.parameters = parameters;
}
/**
* Gets the revisionID value for this WSRunQuery.
*
* @return revisionID
*/
public java.lang.String getRevisionID() {
return revisionID;
}
/**
* Sets the revisionID value for this WSRunQuery.
*
* @param revisionID
*/
public void setRevisionID(java.lang.String revisionID) {
this.revisionID = revisionID;
}
/**
* Gets the wsDataClusterPK value for this WSRunQuery.
*
* @return wsDataClusterPK
*/
public org.talend.mdm.webservice.WSDataClusterPK getWsDataClusterPK() {
return wsDataClusterPK;
}
/**
* Sets the wsDataClusterPK value for this WSRunQuery.
*
* @param wsDataClusterPK
*/
public void setWsDataClusterPK(org.talend.mdm.webservice.WSDataClusterPK wsDataClusterPK) {
this.wsDataClusterPK = wsDataClusterPK;
}
/**
* Gets the query value for this WSRunQuery.
*
* @return query
*/
public java.lang.String getQuery() {
return query;
}
/**
* Sets the query value for this WSRunQuery.
*
* @param query
*/
public void setQuery(java.lang.String query) {
this.query = query;
}
/**
* Gets the parameters value for this WSRunQuery.
*
* @return parameters
*/
public java.lang.String[] getParameters() {
return parameters;
}
/**
* Sets the parameters value for this WSRunQuery.
*
* @param parameters
*/
public void setParameters(java.lang.String[] parameters) {
this.parameters = parameters;
}
public java.lang.String getParameters(int i) {
return this.parameters[i];
}
public void setParameters(int i, java.lang.String _value) {
this.parameters[i] = _value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof WSRunQuery)) return false;
WSRunQuery other = (WSRunQuery) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.revisionID==null && other.getRevisionID()==null) ||
(this.revisionID!=null &&
this.revisionID.equals(other.getRevisionID()))) &&
((this.wsDataClusterPK==null && other.getWsDataClusterPK()==null) ||
(this.wsDataClusterPK!=null &&
this.wsDataClusterPK.equals(other.getWsDataClusterPK()))) &&
((this.query==null && other.getQuery()==null) ||
(this.query!=null &&
this.query.equals(other.getQuery()))) &&
((this.parameters==null && other.getParameters()==null) ||
(this.parameters!=null &&
java.util.Arrays.equals(this.parameters, other.getParameters())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getRevisionID() != null) {
_hashCode += getRevisionID().hashCode();
}
if (getWsDataClusterPK() != null) {
_hashCode += getWsDataClusterPK().hashCode();
}
if (getQuery() != null) {
_hashCode += getQuery().hashCode();
}
if (getParameters() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getParameters());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getParameters(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(WSRunQuery.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("urn-com-amalto-xtentis-webservice", "WSRunQuery"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("revisionID");
elemField.setXmlName(new javax.xml.namespace.QName("", "revisionID"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("wsDataClusterPK");
elemField.setXmlName(new javax.xml.namespace.QName("", "wsDataClusterPK"));
elemField.setXmlType(new javax.xml.namespace.QName("urn-com-amalto-xtentis-webservice", "WSDataClusterPK"));
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("query");
elemField.setXmlName(new javax.xml.namespace.QName("", "query"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("parameters");
elemField.setXmlName(new javax.xml.namespace.QName("", "parameters"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
9243d74e9c6e9b207969f946b434476aba36f0f7 | 2,990 | java | Java | plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/AbstractDimensionProperty.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/AbstractDimensionProperty.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | null | null | null | plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/properties/AbstractDimensionProperty.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 1 | 2019-07-18T16:50:52.000Z | 2019-07-18T16:50:52.000Z | 36.024096 | 104 | 0.772575 | 1,002,796 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.uiDesigner.propertyInspector.properties;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.propertyInspector.Property;
import com.intellij.uiDesigner.propertyInspector.PropertyEditor;
import com.intellij.uiDesigner.propertyInspector.PropertyRenderer;
import com.intellij.uiDesigner.propertyInspector.editors.IntRegexEditor;
import com.intellij.uiDesigner.propertyInspector.renderers.DimensionRenderer;
import com.intellij.uiDesigner.radComponents.RadComponent;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* This class is a base for implementing such properties
* as "minimum size", "preferred size" and "maximum size".
*
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public abstract class AbstractDimensionProperty<T extends RadComponent> extends Property<T, Dimension> {
private final Property[] myChildren;
private final DimensionRenderer myRenderer;
private final IntRegexEditor<Dimension> myEditor;
public AbstractDimensionProperty(@NonNls final String name){
super(null, name);
myChildren=new Property[]{
new IntFieldProperty(this, "width", -1, JBUI.emptySize()),
new IntFieldProperty(this, "height", -1, JBUI.emptySize()),
};
myRenderer = new DimensionRenderer();
myEditor = new IntRegexEditor<>(Dimension.class, myRenderer, new int[]{-1, -1});
}
@NotNull
public final Property[] getChildren(final RadComponent component){
return myChildren;
}
@NotNull
public final PropertyRenderer<Dimension> getRenderer() {
return myRenderer;
}
public final PropertyEditor<Dimension> getEditor() {
return myEditor;
}
public Dimension getValue(T component) {
return getValueImpl(component.getConstraints());
}
protected abstract Dimension getValueImpl(final GridConstraints constraints);
@Override public boolean isModified(final T component) {
final Dimension defaultValue = getValueImpl(FormEditingUtil.getDefaultConstraints(component));
return !getValueImpl(component.getConstraints()).equals(defaultValue);
}
@Override public void resetValue(T component) throws Exception {
setValueImpl(component, getValueImpl(FormEditingUtil.getDefaultConstraints(component)));
}
}
|
9243d88936af8c845e13a36293b7b64c18543a08 | 37,925 | java | Java | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/job/ExecutionHandler.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 347 | 2015-01-20T14:13:21.000Z | 2022-03-31T17:53:11.000Z | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/job/ExecutionHandler.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 128 | 2015-05-22T19:14:32.000Z | 2022-03-31T08:11:18.000Z | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/job/ExecutionHandler.java | emesika/ovirt-engine | db6458e688eeb385b683a0c9c5530917cd6dfe5f | [
"Apache-2.0"
] | 202 | 2015-01-04T06:20:49.000Z | 2022-03-08T15:30:08.000Z | 41 | 135 | 0.587132 | 1,002,797 | package org.ovirt.engine.core.bll.job;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.context.EngineContext;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.HasCorrelationId;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.ActionParametersBase;
import org.ovirt.engine.core.common.action.ActionReturnValue;
import org.ovirt.engine.core.common.action.ActionType;
import org.ovirt.engine.core.common.job.ExternalSystemType;
import org.ovirt.engine.core.common.job.Job;
import org.ovirt.engine.core.common.job.JobExecutionStatus;
import org.ovirt.engine.core.common.job.Step;
import org.ovirt.engine.core.common.job.StepEnum;
import org.ovirt.engine.core.common.job.StepSubjectEntity;
import org.ovirt.engine.core.common.utils.ExecutionMethod;
import org.ovirt.engine.core.common.utils.ValidationUtils;
import org.ovirt.engine.core.common.validation.group.PreRun;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.job.ExecutionMessageDirector;
import org.ovirt.engine.core.dao.JobDao;
import org.ovirt.engine.core.dao.StepDao;
import org.ovirt.engine.core.utils.CorrelationIdTracker;
import org.ovirt.engine.core.utils.lock.EngineLock;
import org.ovirt.engine.core.utils.log.LoggedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides methods for managing the flow objects the of the command, by the given execution context o the command.
* <ul>
* <li>Creates an {@code ExecutionContext} instance for {@code CommandBase}.</li>
* <li>Creates {@code Job} entities.</li>
* <li>Add {@code Step} to a {@code Job}.</li>
* <li>Add {@code Step} to a {@code Step} as a sub step.</li>
* <li>End step.</li>
* <li>End job.</li>
* </ul>
*/
@Singleton
public class ExecutionHandler {
private final Logger log = LoggerFactory.getLogger(ExecutionHandler.class);
private static final List<Class<?>> validationGroups = Arrays.asList(new Class<?>[] { PreRun.class });
private static ExecutionHandler instance;
@Deprecated
public static ExecutionHandler getInstance() {
return instance;
}
@Inject
private JobRepository jobRepository;
@Inject
private JobDao jobDao;
@Inject
private StepDao stepDao;
@PostConstruct
private void init() {
instance = this;
}
/**
* Creates and returns an instance of {@link Job} entity.
*
* @param actionType
* The action type the job entity represents.
* @param command
* The {@code CommandBase} instance which the job entity describes.
* @return An initialized {@code Job} instance.
*/
public static Job createJob(ActionType actionType, CommandBase<?> command) {
Job job = new Job();
job.setId(Guid.newGuid());
job.setActionType(actionType);
job.setDescription(ExecutionMessageDirector.resolveJobMessage(actionType, command.getJobMessageProperties()));
job.setJobSubjectEntities(getSubjectEntities(command.getPermissionCheckSubjects()));
job.setOwnerId(command.getUserId());
job.setEngineSessionSeqId(command.getSessionSeqId());
job.setStatus(JobExecutionStatus.STARTED);
job.setStartTime(new Date());
job.setCorrelationId(command.getCorrelationId());
return job;
}
private static Map<Guid, VdcObjectType> getSubjectEntities(List<PermissionSubject> permSubjectList) {
Map<Guid, VdcObjectType> entities = new HashMap<>();
for (PermissionSubject permSubj : permSubjectList) {
if (permSubj.getObjectId() != null && permSubj.getObjectType() != null) {
entities.put(permSubj.getObjectId(), permSubj.getObjectType());
}
}
return entities;
}
/**
* Finalizes a {@code Step} execution by a given context in which the step was performed and by the exit status of
* the step.
*
* @param context
* The context in which the {@code Step} was executed.
* @param step
* The step to finalize.
* @param exitStatus
* Indicates if the execution described by the step ended successfully or not.
*/
public void endStep(ExecutionContext context, Step step,
boolean exitStatus) {
if (context == null) {
return;
}
if (context.isMonitored()) {
Job job = context.getJob();
try {
if (step != null) {
step.markStepEnded(exitStatus);
jobRepository.updateStep(step);
}
if (context.getExecutionMethod() == ExecutionMethod.AsJob
&& job != null && !exitStatus) {
// step failure will cause the job to be marked as failed
context.setCompleted(true);
job.markJobEnded(false);
jobRepository.updateCompletedJobAndSteps(job);
} else {
Step parentStep = context.getStep();
if (context.getExecutionMethod() == ExecutionMethod.AsStep
&& parentStep != null) {
context.setCompleted(true);
if (job != null && !exitStatus) {
job.markJobEnded(false);
jobRepository.updateCompletedJobAndSteps(job);
}
}
}
} catch (Exception e) {
log.error("Exception", e);
}
}
}
/**
* Finalizes a {@code Step} execution which represents a VDSM task. In case of a failure status, the job will not be
* marked as failed at this stage, but via executing the {@code CommandBase.endAction} with the proper status by
* {@code the AsyncTaskManager}.
*
* @param stepId
* A unique identifier of the step to finalize.
* @param exitStatus
* The status which the step should be ended with.
*/
public void endTaskStep(Guid stepId, JobExecutionStatus exitStatus) {
try {
if (stepId != null) {
Step step = jobRepository.getStep(stepId, false);
if (step != null) {
step.markStepEnded(exitStatus);
jobRepository.updateStep(step);
}
}
} catch (Exception e) {
log.error("Failed to terminate step '{}' with status '{}': {}",
stepId,
exitStatus,
e.getMessage());
log.debug("Exception", e);
}
}
/**
* Prepares the monitoring objects for the command by the default behavior:
* <ul>
* <li> {@link ExecutionContext} determines how the command should be monitored. By default, non-internal commands
* will be associated with {@code Job} to represent the command execution. Internal commands will not be monitored
* by default, therefore the {@code ExecutionContext} is created as non-monitored context.
* <li> {@link Job} is created for monitored actions
* </ul>
*
* @param command
* The created instance of the command (can't be <code>null</code>).
* @param actionType
* The action type of the command
* @param runAsInternal
* Indicates if the command should be run as internal action or not
*/
public void prepareCommandForMonitoring(CommandBase<?> command,
ActionType actionType,
boolean runAsInternal) {
ExecutionContext context = command.getExecutionContext();
if (context == null) {
context = new ExecutionContext();
}
try {
boolean isMonitored = shouldMonitorCommand(actionType, runAsInternal);
// A monitored job is created for monitored external flows
if (isMonitored || context.isJobRequired()) {
Job job = getJob(command, actionType);
context.setExecutionMethod(ExecutionMethod.AsJob);
context.setJob(job);
command.setExecutionContext(context);
command.setJobId(job.getId());
context.setMonitored(true);
}
} catch (Exception e) {
log.error("Failed to prepare command of type '{}' for monitoring due to error '{}'",
actionType.name(),
e.getMessage());
log.debug("Exception", e);
}
}
private Job getJob(CommandBase<?> command, ActionType actionType) {
ActionParametersBase params = command.getParameters();
Job job;
// if Job is external, we had already created the Job by AddExternalJobCommand, so just get it from DB
if (params.getJobId() != null) {
job = jobDao.get(params.getJobId());
} else {
job = createJob(actionType, command);
jobRepository.saveJob(job);
}
return job;
}
/**
* Determines if a specific action should be monitored by the following criteria:
* <ul>
* <li>{@code ActionType.isMonitored} - defined for a specific action type</li>
* <li>{@code isInternal} - By default, only non-internal commands are monitored</li>
* </ul>
*
* @param actionType
* The action type
* @param isInternal
* Indicator of action invocation method
* @return true if the command should be monitored, else false.
*/
private static boolean shouldMonitorCommand(ActionType actionType, boolean isInternal) {
return actionType.isActionMonitored() && !isInternal;
}
/**
* Adds a {@link Step} entity by the provided context. A {@link Step} will not be created if
* {@code ExecutionContext.isMonitored()} returns false.
*
* @param context
* The context of the execution which defines visibility and execution method.
* @param stepName
* The name of the step.
* @param description
* A presentation name for the step. If not provided, the presentation name is resolved by the
* {@code stepName}.
* @return The created instance of the step or {@code null}.
*/
public Step addStep(ExecutionContext context, StepEnum stepName, String description) {
return addStep(context, stepName, description, false);
}
/**
* Adds a {@link Step} entity by the provided context. A {@link Step} will not be created if
* {@code ExecutionContext.isMonitored()} returns false.
*
* @param context
* The context of the execution which defines visibility and execution method.
* @param stepName
* The name of the step.
* @param description
* A presentation name for the step. If not provided, the presentation name is resolved by the
* {@code stepName}.
* @param isExternal
* Indicates if the step is invoked by a plug-in
*/
public Step addStep(ExecutionContext context, StepEnum stepName, String description, boolean isExternal) {
if (context == null) {
return null;
}
Step step = null;
if (context.isMonitored()) {
if (description == null) {
description = ExecutionMessageDirector.getInstance().getStepMessage(stepName);
}
try {
Job job = context.getJob();
if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
step = job.addStep(stepName, description);
try {
step.setExternal(isExternal);
jobRepository.saveStep(step);
} catch (Exception e) {
log.error("Failed to save new step '{}' for job '{}', '{}': {}",
stepName.name(),
job.getId(),
job.getActionType().name(),
e.getMessage());
log.debug("Exception", e);
job.getSteps().remove(step);
step = null;
}
} else {
Step contextStep = context.getStep();
if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) {
step = addSubStep(contextStep, stepName, description, Collections.emptyList());
step.setExternal(isExternal);
}
}
} catch (Exception e) {
log.error("Exception", e);
}
}
return step;
}
/**
* Adds a {@link Step} entity which describes a VDSM task by the provided context. A {@link Step} will not be
* created if {@code ExecutionContext.isTasksMonitored()} returns false.
*
* @param context
* The context of the execution which defines visibility of tasks.
* @param stepName
* The name of the step.
* @param description
* A presentation name for the step. If not provided, the presentation name is resolved by the
* {@code stepName}.
* @return The created instance of the step or {@code null}.
*/
public Step addTaskStep(ExecutionContext context, StepEnum stepName,
String description,
Collection<StepSubjectEntity> stepSubjectEntities) {
if (context == null) {
return null;
}
Step step = null;
if (context.isTasksMonitored()) {
Step parentTaskStep = context.getParentTasksStep();
if (parentTaskStep != null) {
step = addSubStep(parentTaskStep, stepName, description, stepSubjectEntities);
}
}
return step;
}
private Step addSubStep(Step parentStep,
StepEnum stepName,
String description,
Collection<StepSubjectEntity> stepSubjectEntities) {
Step step = null;
if (parentStep != null) {
if (description == null) {
description = ExecutionMessageDirector.getInstance().getStepMessage(stepName);
}
step = parentStep.addStep(stepName, description);
try {
jobRepository.saveStep(step, stepSubjectEntities);
} catch (Exception e) {
log.error("Failed to save new step '{}' for step '{}', '{}': {}",
stepName.name(),
parentStep.getId(),
parentStep.getStepType().name(),
e.getMessage());
log.debug("Exception", e);
parentStep.getSteps().remove(step);
step = null;
}
}
return step;
}
/**
* Adds a {@link Step} entity by the provided context as a child step of a given parent step. A {@link Step} will
* not be created if {@code ExecutionContext.isMonitored()} returns false.
*
* @param context
* The context of the execution which defines visibility and execution method.
* @param parentStep
* The parent step which the new step will be added as its child.
* @param newStepName
* The name of the step.
* @param description
* A presentation name for the step. If not provided, the presentation name is resolved by the
* {@code stepName}.
* @return The created instance of the step or {@code null}.
*/
public Step addSubStep(ExecutionContext context, Step parentStep, StepEnum newStepName, String description) {
return addSubStep(context, parentStep, newStepName, description, false);
}
/**
* Adds a {@link Step} entity by the provided context as a child step of a given parent step. A {@link Step} will
* not be created if {@code ExecutionContext.isMonitored()} returns false.
*
* @param context
* The context of the execution which defines visibility and execution method.
* @param parentStep
* The parent step which the new step will be added as its child.
* @param newStepName
* The name of the step.
* @param description
* A presentation name for the step. If not provided, the presentation name is resolved by the
* {@code stepName}.
* @param isExternal
* Indicates if the step is invoked by a plug-in
*/
public Step addSubStep(ExecutionContext context, Step parentStep, StepEnum newStepName, String description, boolean isExternal) {
Step step = null;
if (context == null || parentStep == null) {
return null;
}
try {
if (context.isMonitored()) {
if (description == null) {
description = ExecutionMessageDirector.getInstance().getStepMessage(newStepName);
}
if (context.getExecutionMethod() == ExecutionMethod.AsJob) {
if (stepDao.exists(parentStep.getId())) {
if (parentStep.getJobId().equals(context.getJob().getId())) {
step = parentStep.addStep(newStepName, description);
}
}
} else if (context.getExecutionMethod() == ExecutionMethod.AsStep) {
step = parentStep.addStep(newStepName, description);
}
}
if (step != null) {
step.setExternal(isExternal);
jobRepository.saveStep(step);
}
} catch (Exception e) {
log.error("Exception", e);
}
return step;
}
/**
* Finalizes a {@code Job} execution by a given context in which the job was performed and by the exit status of
* the step. If the {@code Job} execution continues beyond the scope of the command, the {@code Job.isAsyncJob()}
* should be set to {@code true}. If {@code ExecutionMethod.AsStep} is defined, the current active step can end the
* running {@code Job} by setting the {@link ExecutionContext#shouldEndJob()} to
* {@code true}.
*
* @param context
* The context of the execution which defines how the job should be ended
* @param exitStatus
* Indicates if the execution described by the job ended successfully or not.
*/
public void endJob(ExecutionContext context, boolean exitStatus) {
if (context == null) {
return;
}
Job job = context.getJob();
try {
if (context.isMonitored()) {
if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
if (context.shouldEndJob() || !(job.isAsyncJob() && exitStatus)) {
context.setCompleted(true);
endJob(exitStatus, job);
}
} else {
Step step = context.getStep();
if (context.getExecutionMethod() == ExecutionMethod.AsStep && step != null) {
if (context.shouldEndJob()) {
if (job == null) {
job = jobRepository.getJob(step.getJobId());
}
if (job != null) {
context.setCompleted(true);
endJob(exitStatus, job);
}
}
}
}
}
} catch (Exception e) {
log.error("Exception", e);
}
}
private void endJob(boolean exitStatus, Job job) {
job.markJobEnded(exitStatus);
try {
jobRepository.updateCompletedJobAndSteps(job);
} catch (Exception e) {
log.error("Failed to end Job '{}', '{}': {}",
job.getId(),
job.getActionType().name(),
e.getMessage());
log.debug("Exception", e);
}
}
/**
* Creates a context for execution of internal command as a monitored Job
*
* @return an execution context as a Job
*/
public static CommandContext createInternalJobContext() {
return createInternalJobContext((EngineLock) null);
}
public static CommandContext createInternalJobContext(CommandContext commandContext) {
return createInternalJobContext(commandContext, null);
}
/**
* Creates a context for execution of internal command as a monitored Job,
* the command will release the given lock when it is finished.
*
* @param lock
* The lock which should be released at child command (can be null)
* @return an execution context as a Job
*/
public static CommandContext createInternalJobContext(EngineLock lock) {
return modifyContextForInternalJob(new CommandContext(new EngineContext()), lock);
}
public static CommandContext createInternalJobContext(CommandContext commandContext, EngineLock lock) {
return modifyContextForInternalJob(commandContext.clone(), lock);
}
private static CommandContext modifyContextForInternalJob(CommandContext returnedContext, EngineLock lock) {
return returnedContext
.withExecutionContext(createMonitoredExecutionContext())
.withLock(lock)
.withoutCompensationContext();
}
private static ExecutionContext createMonitoredExecutionContext() {
ExecutionContext executionContext = new ExecutionContext();
executionContext.setJobRequired(true);
executionContext.setMonitored(true);
return executionContext;
}
/**
* Creates a default execution context for an inner command which creates VDSM tasks so the tasks will be monitored
* under the parent {@code StepEnum.EXECUTING} step. If the parent command is an internal command, its parent task
* step is passed to its internal command.
*
* @param parentContext
* The context of the parent command
* @return A context by which the internal command should be monitored.
*/
public static CommandContext createDefaultContextForTasks(CommandContext parentContext) {
return createDefaultContextForTasks(parentContext, null);
}
/**
* Creates a default execution context for an inner command which creates VDSM tasks so the tasks will be monitored
* under the parent {@code StepEnum.EXECUTING} step. If the parent command is an internal command, its parent task
* step is passed to its internal command.
*
* @param commandContext
* The context of the parent command
* @param lock
* The lock which should be released at child command
* @return A context by which the internal command should be monitored.
*/
public static CommandContext createDefaultContextForTasks(CommandContext commandContext, EngineLock lock) {
CommandContext result = commandContext.clone().withLock(lock).withoutCompensationContext();
return result.withExecutionContext(createDefaultContextForTasksImpl(result.getExecutionContext()));
}
public static void setExecutionContextForTasks(CommandContext commandContext, ExecutionContext executionContext, EngineLock lock) {
commandContext.withExecutionContext(createDefaultContextForTasksImpl(executionContext))
.withLock(lock);
}
private static ExecutionContext createDefaultContextForTasksImpl(ExecutionContext parentExecutionContext) {
ExecutionContext executionContext = new ExecutionContext();
if (parentExecutionContext != null) {
if (parentExecutionContext.getJob() != null) {
Step parentStep = parentExecutionContext.getParentTasksStep();
if (parentStep != null) {
executionContext.setParentTasksStep(parentStep);
}
} else {
executionContext.setParentTasksStep(parentExecutionContext.getParentTasksStep());
}
executionContext.setStep(parentExecutionContext.getStep());
executionContext.setStepsList(parentExecutionContext.getStepsList());
executionContext.setJob(parentExecutionContext.getJob());
}
return executionContext;
}
/**
* Creates {@code ExecutionContext} which defines the context for executing the finalizing step of the job. If the
* step exists, it must be part of a job, therefore the {@code Job} entity is being set as part of the context.
*
* @param stepId
* The unique identifier of the step. Must not be {@code null}.
* @return The context for monitoring the finalizing step of the job, or {@code null} if no such step.
*/
public ExecutionContext createFinalizingContext(Guid stepId) {
ExecutionContext context = null;
try {
Step step = jobRepository.getStep(stepId, false);
if (step != null && step.getParentStepId() != null) {
context = new ExecutionContext();
Step executionStep = jobRepository.getStep(step.getParentStepId(), false);
// indicates if a step is monitored at Job level or as an inner step
Guid parentStepId = executionStep.getParentStepId();
if (parentStepId == null) {
context.setExecutionMethod(ExecutionMethod.AsJob);
context.setJob(jobRepository.getJobWithSteps(step.getJobId()));
} else {
context.setExecutionMethod(ExecutionMethod.AsStep);
Step parentStep = jobRepository.getStep(parentStepId, false);
parentStep.setSteps(stepDao.getStepsByParentStepId(parentStep.getId()));
context.setStep(parentStep);
}
context.setMonitored(true);
}
} catch (Exception e) {
log.error("Exception", e);
}
return context;
}
/**
* Method should be called when finalizing the command. The execution step is being ended with success and the
* finalization step is started.
*
* @param executionContext
* The context of the job
* @return A created instance of the Finalizing step
*/
public Step startFinalizingStep(ExecutionContext executionContext) {
if (executionContext == null) {
return null;
}
Step step = null;
try {
if (executionContext.getExecutionMethod() == ExecutionMethod.AsJob) {
Job job = executionContext.getJob();
if (job != null) {
Step executingStep = job.getStep(StepEnum.EXECUTING);
Step finalizingStep =
job.addStep(StepEnum.FINALIZING,
ExecutionMessageDirector.getInstance().getStepMessage(StepEnum.FINALIZING));
if (executingStep != null) {
executingStep.markStepEnded(true);
jobRepository.updateExistingStepAndSaveNewStep(executingStep,
finalizingStep);
} else {
jobRepository.saveStep(finalizingStep);
}
}
} else if (executionContext.getExecutionMethod() == ExecutionMethod.AsStep) {
Step parentStep = executionContext.getStep();
if (parentStep != null) {
Step executingStep = parentStep.getStep(StepEnum.EXECUTING);
Step finalizingStep =
parentStep.addStep(StepEnum.FINALIZING, ExecutionMessageDirector.getInstance()
.getStepMessage(StepEnum.FINALIZING));
if (executingStep != null) {
executingStep.markStepEnded(true);
jobRepository.updateExistingStepAndSaveNewStep(executingStep,
finalizingStep);
} else {
jobRepository.saveStep(finalizingStep);
}
}
}
} catch (Exception e) {
log.error("Exception", e);
}
return step;
}
/**
* Updates the step with the id in the external system in which the describe task runs.
*
* @param step
* The step which represents the external task
* @param externalId
* The id of the task in the external system
* @param systemType
* The type of the system
*/
public void updateStepExternalId(Step step, Guid externalId, ExternalSystemType systemType) {
if (step != null) {
step.getExternalSystem().setId(externalId);
step.getExternalSystem().setType(systemType);
try {
jobRepository.updateStep(step);
} catch (Exception e) {
log.error("Failed to save step '{}', '{}' for system-type '{}' with id '{}': {}",
step.getId(),
step.getStepType().name(),
systemType.name(),
externalId,
e.getMessage());
log.debug("Exception", e);
}
}
}
/**
* Mark the Job as an Async Job which should be terminated by external process to the current command scope.
*
* @param executionContext
* The context which describe the running job.
* @param isAsync
* indicates if the job should be ended by current action
*/
public static void setAsyncJob(ExecutionContext executionContext, boolean isAsync) {
if (executionContext == null) {
return;
}
Job job = executionContext.getJob();
if (executionContext.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
job.setIsAsyncJob(isAsync);
}
}
/**
* Evaluates if a given correlation-ID as part of the parameters is set correctly. If the correlation-ID is null or
* empty, a valid correlation-ID will be set. If the correlation-ID exceeds its permitted length, an error return
* value will be created and returned.
*
* @param parameters
* The parameters input of the command
* @return A {@code null} object emphasis correlation-ID is valid or {@code ActionReturnValue} contains the
* correlation-ID violation message
*/
public static ActionReturnValue evaluateCorrelationId(HasCorrelationId parameters) {
ActionReturnValue returnValue = null;
String correlationId = parameters.getCorrelationId();
if (StringUtils.isEmpty(correlationId)) {
correlationId = CorrelationIdTracker.getCorrelationId();
if (StringUtils.isEmpty(correlationId)) {
correlationId = LoggedUtils.getObjectId(parameters);
}
parameters.setCorrelationId(correlationId);
} else {
List<String> messages = ValidationUtils.validateInputs(validationGroups, parameters);
if (!messages.isEmpty()) {
ActionReturnValue returnErrorValue = new ActionReturnValue();
returnErrorValue.setValid(false);
returnErrorValue.getValidationMessages().addAll(messages);
return returnErrorValue;
}
}
return returnValue;
}
/**
* If the provided {@link ExecutionContext} execution method is as Step the current step will
* be ended with the appropriate exitStatus and so is the FINALIZING {@link Step} if present.
*
* @param context
* The context of the execution
* @param exitStatus
* Indicates if the execution ended successfully or not.
*/
public void endFinalizingStepAndCurrentStep(ExecutionContext context, boolean exitStatus) {
if (context == null) {
return;
}
try {
Step parentStep = context.getStep();
if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) {
Step finalizingStep = parentStep.getStep(StepEnum.FINALIZING);
if (finalizingStep != null) {
finalizingStep.markStepEnded(exitStatus);
jobRepository.updateStep(finalizingStep);
}
parentStep.markStepEnded(exitStatus);
jobRepository.updateStep(parentStep);
}
} catch (RuntimeException e) {
log.error("Exception", e);
}
}
/**
* Finalizes Job with VDSM tasks, as this case requires verification that no other steps are running in order to
* close the entire Job
*
* @param context
* The context of the execution which defines how the job should be ended
* @param exitStatus
* Indicates if the execution described by the job ended successfully or not.
*/
public void endTaskJobIfNeeded(ExecutionContext context, boolean exitStatus) {
if (context == null) {
return;
}
if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) {
endJob(context, exitStatus);
} else {
Step parentStep = context.getStep();
if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) {
List<Step> steps = stepDao.getStepsByJobId(parentStep.getJobId());
boolean hasChildStepsRunning = false;
for (Step step : steps) {
if (step.getStatus() == JobExecutionStatus.STARTED && step.getParentStepId() != null) {
hasChildStepsRunning = true;
break;
}
}
if (!hasChildStepsRunning) {
endJob(exitStatus, jobRepository.getJob(parentStep.getJobId()));
}
}
}
}
/**
* If the provided {@link ExecutionContext} execution method is as Step the current step will
* be ended with the appropriate exitStatus and so is the FINALIZING {@link Step} if present.
* If needed the job will be ended as well.
*
* @param context
* The context of the execution which defines how the job should be ended
* @param exitStatus
* Indicates if the execution described by the job ended successfully or not.
*/
public void endTaskStepAndJob(ExecutionContext context, boolean exitStatus) {
endFinalizingStepAndCurrentStep(context, exitStatus);
endTaskJobIfNeeded(context, exitStatus);
}
/**
* Checks if a Job has any Step associated with VDSM task
*
* @param context
* The context of the execution stores the Job
* @return true if Job has any Step for VDSM Task, else false.
*/
public boolean checkIfJobHasTasks(ExecutionContext context) {
if (context == null || !context.isMonitored()) {
return false;
}
try {
Guid jobId = null;
if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) {
jobId = context.getJob().getId();
} else if (context.getExecutionMethod() == ExecutionMethod.AsStep && context.getStep() != null) {
jobId = context.getStep().getId();
}
if (jobId != null) {
return jobDao.checkIfJobHasTasks(jobId);
}
} catch (RuntimeException e) {
log.error("Exception", e);
}
return false;
}
/**
* Updates Job for the same entity for a specific action as completed with a given exit status.
*
* @param entityId
* The entity to search for its jobs
* @param actionType
* The action type to search for
* @param status
* The exist status to be set for the job
*/
public void updateSpecificActionJobCompleted(Guid entityId, ActionType actionType, boolean status) {
try {
List<Job> jobs = jobRepository.getJobsByEntityAndAction(entityId, actionType);
for (Job job : jobs) {
if (job.getStatus() == JobExecutionStatus.STARTED) {
job.markJobEnded(status);
}
jobRepository.updateCompletedJobAndSteps(job);
}
} catch (RuntimeException e) {
log.error("Exception", e);
}
}
}
|
9243d8de9cfcc508d657f155c4de2097cb7c4380 | 2,702 | java | Java | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/eclipse/emulation/java/lang/Class/S_getDeclaringClass/S_getDeclaringClass.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/eclipse/emulation/java/lang/Class/S_getDeclaringClass/S_getDeclaringClass.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | null | null | null | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/eclipse/emulation/java/lang/Class/S_getDeclaringClass/S_getDeclaringClass.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | 32.95122 | 93 | 0.69171 | 1,002,798 | /*
* 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.
*/
/**
* @author Elena V. Sayapina
* @version $Revision: 1.3 $
*/
package org.apache.harmony.test.stress.eclipse.emulation.java.lang.Class.S_getDeclaringClass;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.harmony.test.stress.eclipse.emulation.java.lang.share.UsefulMethods;
import org.apache.harmony.share.Test;
public class S_getDeclaringClass extends Test {
public int test() {
String auxilaryDir = testArgs[0];
String eclipsePath = testArgs[1];
int getDeclaringClass = 0;
int nullCount = 0;
File auxilaryFile = new File(auxilaryDir + File.separator
+ "getDeclaringClass_parameters.txt");
URL[] eclipsePlugins = UsefulMethods.get_plugin_path(eclipsePath);
if (eclipsePlugins != null ) {
URLClassLoader urlClassLoader = new URLClassLoader(eclipsePlugins);
Class[] classes = UsefulMethods.getClassesArray(auxilaryFile,
urlClassLoader);
if (classes == null) return fail("Test failed: " +
"unable to get class list");
log.info("Number of classes to test: " + classes.length);
String info = "";
try {
Class[] clazz = new Class[classes.length];
for (int i=0; i<classes.length; i++) {
info = classes[i].getName();
clazz[i] = classes[i].getDeclaringClass();
getDeclaringClass++;
if (clazz[i] == null) nullCount++;
}
log.info("getDeclaringClass() call count: "
+ String.valueOf(getDeclaringClass));
//log.info("Null value count:" + String.valueOf(nullCount));
return pass();
} catch (Throwable e) {
log.add(e);
log.add("Error on class: " + info);
return fail("Test failed: " + e.toString());
}
} else {
return fail("Test failed: Unable to get eclipse plugins list");
}
}
public static void main(String[] args) {
System.exit(new S_getDeclaringClass().test(args));
}
}
|
9243d9fd0170362d2374d241cb687e34cc7cb36b | 5,322 | java | Java | MyTextApplication/app/src/main/java/com/example/dell/mytextapplication/share/VideoImage.java | YiNPNG/test | 1f6b73600e7a5e5312c5555e5b36b01be6f26722 | [
"Apache-2.0"
] | null | null | null | MyTextApplication/app/src/main/java/com/example/dell/mytextapplication/share/VideoImage.java | YiNPNG/test | 1f6b73600e7a5e5312c5555e5b36b01be6f26722 | [
"Apache-2.0"
] | null | null | null | MyTextApplication/app/src/main/java/com/example/dell/mytextapplication/share/VideoImage.java | YiNPNG/test | 1f6b73600e7a5e5312c5555e5b36b01be6f26722 | [
"Apache-2.0"
] | null | null | null | 28.459893 | 104 | 0.680571 | 1,002,799 | package com.example.dell.mytextapplication.share;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.example.dell.mytextapplication.R;
import com.example.dell.mytextapplication.component.AppActivityClose;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class VideoImage extends Activity{
public List<String> video_path;
public String path;
public static ImageAdapterVideo imageAdapterV;
private GridView video_gridview;
public static VideoImage instance;
Bitmap bitmapV = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videoimage);
instance = this;
AppActivityClose.getInstance().addActivity(this); //tianjia
path = "/mnt/sdcard";//AppInforToCustom.getAppInforToCustomInstance().getCameraShootingPath();
imageAdapterV = new ImageAdapterVideo(getApplicationContext());
video_gridview = (GridView)findViewById(R.id.videoGallery);
video_gridview.setAdapter(imageAdapterV);
video_gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try
{
File file = new File(video_path.get(position).toString());
if (file.exists())
{
ShareActivity.isBackground = true;
Intent v = new Intent();
v.setClass(VideoImage.this, VideoGalleryActivity.class);
v.putExtra("videoPath", video_path.get(position).toString());
v.putExtra("position", position);
startActivity(v);
}else {
//如果用户在后台删除视频,这里则重新加载所有的视频
video_path = getInSDVideo();
imageAdapterV.notifyDataSetChanged();
showMessage("文件已经删除");
}
file = null;
} catch (IndexOutOfBoundsException e)
{
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
video_path = getInSDVideo();
if (video_path.size() >= 100)
{
showMessage("视频大于100个以后的不显示");
}
getAsyncTaskVideo();
}
/**
* 异步加载视频缩略图
*/
public void getAsyncTaskVideo() {
@SuppressWarnings("deprecation")
final Object data = getLastNonConfigurationInstance();
if (data == null) {
new AsyncTaskLoadVideo(VideoImage.this, video_path).execute();
} else {
final Bitmap[] videos = (Bitmap[]) data;
if (videos.length == 0) {
new AsyncTaskLoadVideo(VideoImage.this,video_path).execute();
}
for (Bitmap photo : videos) {
imageAdapterV.addPhoto(photo);
imageAdapterV.notifyDataSetChanged();
}
}
}
/**
* 视频异步类
* @author zhangjie
*/
class AsyncTaskLoadVideo extends AsyncTask<Object, Bitmap, Object> {
private List<String> video_lis;
public AsyncTaskLoadVideo(Context mContext,
List<String> path) {
video_lis = path;
}
/*
* 获取视频的缩图
* 先通过ThumbnailUtils来创建一个视频的图,然后再利用ThumbnailUtils来生成指定大小的图
* MICRO_KIND
*/
@Override
protected Object doInBackground(Object... params) {
Bitmap bitmapV = null;
int size = video_lis.size();
for(int i = 0 ; i < size; i++){
bitmapV = getVideoThumbnail(video_lis.get(i).toString(), 190,82, Thumbnails.MICRO_KIND);
if (bitmapV != null) {
publishProgress(bitmapV);
}else{
Bitmap bitmapP1 = BitmapFactory.decodeResource(getResources(), R.drawable.zhangjie);
if(bitmapP1 !=null){
bitmapV = Bitmap.createScaledBitmap(bitmapP1,190,82,true);
publishProgress(bitmapV);
}
}
}
return null;
}
@Override
protected void onPostExecute(Object result) {
}
@Override
protected void onProgressUpdate(Bitmap... values) {
for (Bitmap bitmap : values) {
imageAdapterV.addPhoto(bitmap);
imageAdapterV.notifyDataSetChanged();
}
}
}
/**
* 获取视频缩略图
* @param videoPath
* @param width
* @param height
* @param kind
* @return
*/
private Bitmap getVideoThumbnail(String videoPath, int width , int height, int kind){
Bitmap bitmap = null;
bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
/*
* 获取SD卡指定目录的视频列表
*/
public List<String> getInSDVideo() {
List<String> it_p = new ArrayList<String>();
File f = new File(path);
if (!f.exists()){
f.mkdirs();
}else {
File[] files = f.listFiles();
for(File file : files){
if (file.isFile()) {
String fileName = file.getName();
if (fileName.endsWith(".mp4")) {
it_p.add(file.getPath());
}
if (it_p.size() >= 100)
{
showMessage("视频文件大于100以后不显示");
break;
}
}
}
}
return it_p;
}
public void showMessage(String msg){
Toast toast = Toast.makeText(instance, msg, Toast.LENGTH_LONG);
toast.show();
}
}
|
9243daa5450ed82a468efebf49b3529c115dfca0 | 496 | java | Java | app/src/main/java/com/liuguangqiang/idaily/di/components/AppComponent.java | sunkiha/Idaily-master | c185b2e8fb407b950932e57bfc4885e46b4a9afe | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/liuguangqiang/idaily/di/components/AppComponent.java | sunkiha/Idaily-master | c185b2e8fb407b950932e57bfc4885e46b4a9afe | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/liuguangqiang/idaily/di/components/AppComponent.java | sunkiha/Idaily-master | c185b2e8fb407b950932e57bfc4885e46b4a9afe | [
"Apache-2.0"
] | null | null | null | 23.619048 | 58 | 0.804435 | 1,002,800 | package com.liuguangqiang.idaily.di.components;
import com.liuguangqiang.idaily.app.DailyApplication;
import com.liuguangqiang.idaily.di.modules.AppModule;
import com.liuguangqiang.idaily.di.modules.MainModule;
import com.liuguangqiang.idaily.ui.act.MainActivity;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by Eric on 16/3/22.
*/
@Component(modules = AppModule.class)
public interface AppComponent {
DailyApplication inject(DailyApplication application);
}
|
9243db555665bb4b6c220f9996ef0e85277620e6 | 1,651 | java | Java | compiler/extensions/cpp98/src/zserio/emit/cpp98/ConstEmitterTemplateData.java | Klebert-Engineering/zserio-1 | fbb4fc42d9ab6f3afa6c040a36267357399180f4 | [
"BSD-3-Clause"
] | 2 | 2019-02-06T17:50:24.000Z | 2019-11-20T16:51:34.000Z | compiler/extensions/cpp98/src/zserio/emit/cpp98/ConstEmitterTemplateData.java | Klebert-Engineering/zserio-1 | fbb4fc42d9ab6f3afa6c040a36267357399180f4 | [
"BSD-3-Clause"
] | 1 | 2019-11-25T16:25:51.000Z | 2019-11-25T18:09:39.000Z | compiler/extensions/cpp98/src/zserio/emit/cpp98/ConstEmitterTemplateData.java | Klebert-Engineering/zserio-1 | fbb4fc42d9ab6f3afa6c040a36267357399180f4 | [
"BSD-3-Clause"
] | null | null | null | 30.018182 | 110 | 0.736523 | 1,002,801 | package zserio.emit.cpp98;
import zserio.ast.Constant;
import zserio.emit.common.ExpressionFormatter;
import zserio.emit.common.ZserioEmitException;
import zserio.emit.cpp98.symbols.CppNativeSymbol;
import zserio.emit.cpp98.types.CppNativeType;
public class ConstEmitterTemplateData extends CppTemplateData
{
public ConstEmitterTemplateData(TemplateDataContext context, Constant constant) throws ZserioEmitException
{
super(context);
final CppNativeMapper cppNativeMapper = context.getCppNativeMapper();
final ExpressionFormatter cppExpressionFormatter = context.getExpressionFormatter(
new HeaderIncludeCollectorAdapter(this));
final CppNativeSymbol constantNativeSymbol = cppNativeMapper.getCppSymbol(constant);
packageData = new PackageTemplateData(constantNativeSymbol.getPackageName());
name = constantNativeSymbol.getName();
final CppNativeType nativeTargetType = cppNativeMapper.getCppType(constant.getTypeReference());
addHeaderIncludesForType(nativeTargetType);
cppTypeName = nativeTargetType.getFullName();
value = cppExpressionFormatter.formatGetter(constant.getValueExpression());
}
public PackageTemplateData getPackage()
{
return packageData;
}
public String getName()
{
return name;
}
public String getCppTypeName()
{
return cppTypeName;
}
public String getValue()
{
return value;
}
private final PackageTemplateData packageData;
private final String name;
private final String cppTypeName;
private final String value;
}
|
9243dc0835d5553512b011774e380e5b4ad73e7a | 2,636 | java | Java | src/mock/java/com/jcabi/urn/URNMocker.java | jcabi/jcabi-urn | fe0c774a5a42edf20e5474d52c9ac8255e7462c7 | [
"BSD-3-Clause"
] | 13 | 2015-05-12T07:15:36.000Z | 2022-03-31T04:07:16.000Z | src/mock/java/com/jcabi/urn/URNMocker.java | jcabi/jcabi-urn | fe0c774a5a42edf20e5474d52c9ac8255e7462c7 | [
"BSD-3-Clause"
] | 15 | 2015-01-08T16:40:31.000Z | 2021-01-31T07:19:40.000Z | src/mock/java/com/jcabi/urn/URNMocker.java | jcabi/jcabi-urn | fe0c774a5a42edf20e5474d52c9ac8255e7462c7 | [
"BSD-3-Clause"
] | 9 | 2015-01-21T15:02:34.000Z | 2021-08-23T23:31:15.000Z | 29.629213 | 73 | 0.681077 | 1,002,802 | /**
* Copyright (c) 2012-2017, jcabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcabi.urn;
import java.util.UUID;
/**
* Mocker of {@link URN}.
* @author Yegor Bugayenko ([email protected])
* @version $Id: 9243dc0835d5553512b011774e380e5b4ad73e7a $
* @since 0.6
*/
public final class URNMocker {
/**
* Namespace ID.
*/
private transient String nid;
/**
* Nammespace specific string.
*/
private transient String nss;
/**
* Public ctor.
*/
public URNMocker() {
this.nid = "test";
this.nss = UUID.randomUUID().toString();
}
/**
* With this namespace.
* @param name The namespace
* @return This object
*/
public URNMocker withNid(final String name) {
this.nid = name;
return this;
}
/**
* With this nss.
* @param text The nss
* @return This object
*/
public URNMocker withNss(final String text) {
this.nss = text;
return this;
}
/**
* Mock it.
* @return Mocked URN
*/
public URN mock() {
return new URN(this.nid, this.nss);
}
}
|
9243dd9681d7e0d5ee581ea5851c224fcbfa5a4d | 3,533 | java | Java | src/main/java/istc/bigdawg/query/ConnectionInfo.java | fnukrishnaramesh/bigdawg-1 | 13622acbcd08f0762dae9afa59a2e705c4f2b4d6 | [
"BSD-3-Clause"
] | 33 | 2017-03-27T12:40:31.000Z | 2022-03-18T03:17:31.000Z | src/main/java/istc/bigdawg/query/ConnectionInfo.java | fnukrishnaramesh/bigdawg-1 | 13622acbcd08f0762dae9afa59a2e705c4f2b4d6 | [
"BSD-3-Clause"
] | 10 | 2017-05-11T00:39:43.000Z | 2022-02-21T06:35:22.000Z | src/main/java/istc/bigdawg/query/ConnectionInfo.java | fnukrishnaramesh/bigdawg-1 | 13622acbcd08f0762dae9afa59a2e705c4f2b4d6 | [
"BSD-3-Clause"
] | 19 | 2017-06-25T22:39:30.000Z | 2022-03-25T01:43:18.000Z | 24.880282 | 75 | 0.681574 | 1,002,803 | /**
*
*/
package istc.bigdawg.query;
import java.io.Serializable;
import java.text.ParseException;
import java.util.Collection;
import istc.bigdawg.executor.ExecutorEngine;
import org.apache.commons.lang3.tuple.Pair;
/**
* This class represents a connection information to a given database.
*
* @author Adam Dziedzic
*/
public interface ConnectionInfo extends Serializable {
/**
*
* @return name of the URL where the instance is running from which the
* connection will be obtained
*/
public String getUrl();
/**
*
* @return name of the host where the instance is running from which the
* connection will be obtained
*/
public String getHost();
/**
*
* @return port number of the running instance from which the connection
* will be obtained
*/
public String getPort();
/**
*
* @return user name who can can get the connection
*/
public String getUser();
/**
*
* @return password for the user
*/
public String getPassword();
/**
*
* @return databases/binpath, etc
*/
public String getDatabase();
/**
* @param objects
* a Collection of objects to be removed
* @return a collection of queries that when run on the instance, removes
* all of the given objects.
*/
public Collection<String> getCleanupQuery(Collection<String> objects);
/**
* Used for executing shuffle joins.
* @param object
* the table for which the histogram should be computed
* @param attribute
* the attribute of the table for which the histogram should be
* computed
* @param start
* the minimum value contained in the histogram
* @param end
* the maximum value contained in the histogram
* @param numBuckets
* the number of buckets in the histogram
* @return an array such that the ith value is equal to the number of
* elements stored in the ith bucket of the histogram
*/
public long[] computeHistogram(String object, String attribute,
double start, double end, int numBuckets)
throws ExecutorEngine.LocalQueryExecutionException;
/**
* Used for executing shuffle joins.
* @param object
* @param attribute
* @return
* @throws ExecutorEngine.LocalQueryExecutionException
* @throws ParseException
*/
public Pair<Number, Number> getMinMax(String object, String attribute)
throws ExecutorEngine.LocalQueryExecutionException, ParseException;
public ExecutorEngine getLocalQueryExecutor()
throws LocalQueryExecutorLookupException;
class LocalQueryExecutorLookupException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public LocalQueryExecutorLookupException() {
super();
}
public LocalQueryExecutorLookupException(String message) {
super(message);
}
public LocalQueryExecutorLookupException(Throwable cause) {
super(cause);
}
public LocalQueryExecutorLookupException(String message,
Throwable cause) {
super(message, cause);
}
}
/**
* @return
*/
public default String toSimpleString() {
StringBuilder result = new StringBuilder();
result.append(this.getClass().getName() + " Object {");
result.append(" Host: " + this.getHost());
result.append(" Port: " + this.getPort());
result.append(" Database: " + this.getDatabase());
result.append(" User: " + this.getUser());
result.append(" Password: This is a secret!");
result.append("}");
return result.toString();
}
}
|
9243dda2d5ce85d185b6663413d27bbaec9970a1 | 667 | java | Java | multiapps-common/src/main/java/org/cloudfoundry/multiapps/common/ContentException.java | Boris-ILIEV/multiapps | e504d1d96c862fcfb1985928a598990224a6ac79 | [
"Apache-2.0"
] | 15 | 2018-06-10T06:17:51.000Z | 2022-01-01T21:24:43.000Z | multiapps-common/src/main/java/org/cloudfoundry/multiapps/common/ContentException.java | Boris-ILIEV/multiapps | e504d1d96c862fcfb1985928a598990224a6ac79 | [
"Apache-2.0"
] | 96 | 2018-06-19T12:03:49.000Z | 2021-09-29T13:03:17.000Z | multiapps-common/src/main/java/org/cloudfoundry/multiapps/common/ContentException.java | Boris-ILIEV/multiapps | e504d1d96c862fcfb1985928a598990224a6ac79 | [
"Apache-2.0"
] | 12 | 2018-06-06T16:51:29.000Z | 2021-07-20T10:05:20.000Z | 23.821429 | 83 | 0.689655 | 1,002,804 | package org.cloudfoundry.multiapps.common;
public class ContentException extends SLException {
private static final long serialVersionUID = 4471159624548251863L;
public ContentException(String message, Object... arguments) {
super(message, arguments);
}
public ContentException(String message) {
super(message);
}
public ContentException(Throwable cause, String message, Object... arguments) {
super(cause, message, arguments);
}
public ContentException(Throwable cause, String message) {
super(cause, message);
}
public ContentException(Throwable cause) {
super(cause);
}
}
|
9243de1d3d84b90bbb541dd8e6cbb6d2a0230a22 | 709 | java | Java | src/main/java/io/khasang/freefly/service/CatService.java | SamLRR/freefly | f1a689f5d3e890ba47abeaf26a380599f6c17e38 | [
"MIT"
] | null | null | null | src/main/java/io/khasang/freefly/service/CatService.java | SamLRR/freefly | f1a689f5d3e890ba47abeaf26a380599f6c17e38 | [
"MIT"
] | 1 | 2018-08-21T10:19:22.000Z | 2018-08-21T10:19:49.000Z | src/main/java/io/khasang/freefly/service/CatService.java | SamLRR/freefly | f1a689f5d3e890ba47abeaf26a380599f6c17e38 | [
"MIT"
] | null | null | null | 17.725 | 44 | 0.564175 | 1,002,805 | package io.khasang.freefly.service;
import io.khasang.freefly.entity.Cat;
import java.util.List;
public interface CatService {
/**
* method for add cat
*
* @param cat - new cat for creation
* @return created cat
*/
Cat addCat(Cat cat);
/**
* method for getting cat by specific id
*
* @param id - cat's id
* @return cat by id
*/
Cat getCatById(long id);
/**
* method for getting all cats
* @return cats's list
*/
List<Cat> getAllCats();
/**
* method for update cat
*
* @param cat - cat for update
* @return update cat
*/
Cat updateCat(Cat cat);
void removeCatById(Cat cat);
}
|
9243de4fb4b93907b7f00d42c5cc53672d8288d0 | 3,229 | java | Java | anfodis-waterfall/src/main/java/net/mcparkour/anfodis/command/handler/WaterfallCommandHandler.java | mcparkournet/anfodis | 2ef1104b09ed3da05366c11d8d09308aff310da7 | [
"MIT"
] | 2 | 2020-09-06T13:00:34.000Z | 2021-07-31T07:37:55.000Z | anfodis-waterfall/src/main/java/net/mcparkour/anfodis/command/handler/WaterfallCommandHandler.java | mcparkournet/anfodis | 2ef1104b09ed3da05366c11d8d09308aff310da7 | [
"MIT"
] | null | null | null | anfodis-waterfall/src/main/java/net/mcparkour/anfodis/command/handler/WaterfallCommandHandler.java | mcparkournet/anfodis | 2ef1104b09ed3da05366c11d8d09308aff310da7 | [
"MIT"
] | null | null | null | 48.19403 | 152 | 0.771446 | 1,002,806 | /*
* MIT License
*
* Copyright (c) 2020 MCParkour
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.mcparkour.anfodis.command.handler;
import java.util.Map;
import net.mcparkour.anfodis.command.WaterfallMessenger;
import net.mcparkour.anfodis.command.context.Sender;
import net.mcparkour.anfodis.command.context.WaterfallCommandContext;
import net.mcparkour.anfodis.command.context.WaterfallCommandContextBuilder;
import net.mcparkour.anfodis.command.mapper.WaterfallCommand;
import net.mcparkour.anfodis.command.mapper.properties.WaterfallCommandProperties;
import net.mcparkour.anfodis.handler.ContextHandler;
import net.md_5.bungee.api.CommandSender;
import org.jetbrains.annotations.Nullable;
public class WaterfallCommandHandler
extends CommandHandler<WaterfallCommand, WaterfallCommandContext, WaterfallCommandContextBuilder, CommandSender, WaterfallMessenger> {
public WaterfallCommandHandler(
final WaterfallCommand command,
final Map<WaterfallCommand, ? extends CommandContextBuilderHandler<WaterfallCommandContextBuilder, WaterfallCommandContext>> subCommandHandlers,
final @Nullable ContextHandler<? super WaterfallCommandContext> executorHandler,
final CommandContextCreator<WaterfallCommand, WaterfallCommandContext, CommandSender> contextSupplier,
final WaterfallMessenger messenger
) {
super(command, subCommandHandlers, executorHandler, contextSupplier, messenger);
}
@Override
public void handle(final WaterfallCommandContextBuilder contextBuilder) {
WaterfallCommand command = getCommand();
WaterfallCommandProperties properties = command.getProperties();
Sender<CommandSender> sender = contextBuilder.getSender();
if (!properties.isValidSender(sender)) {
WaterfallMessenger messenger = getMessenger();
var contextCreator = getContextCreator();
WaterfallCommandContext context = contextBuilder.build(contextCreator);
var senderTypes = properties.getSenderTypes();
messenger.sendInvalidSenderMessage(context, senderTypes);
return;
}
super.handle(contextBuilder);
}
}
|
9243df87e11a544bbd4ce4c71a25732349d86e8b | 23,448 | java | Java | modules/andes-core/broker/src/main/java/org/wso2/andes/kernel/router/TopicRoutingMatcher.java | Vathsan/andes | 292855fda3d4d047e8f2d2ca230fba166e7414b1 | [
"Apache-2.0"
] | 3 | 2017-08-01T04:41:47.000Z | 2018-04-20T10:12:21.000Z | modules/andes-core/broker/src/main/java/org/wso2/andes/kernel/router/TopicRoutingMatcher.java | a5anka/andes | 7b4a8cd5d16777b920a0c6ca208aa07ea6426c49 | [
"Apache-2.0"
] | 183 | 2015-01-12T03:58:20.000Z | 2021-03-05T11:45:20.000Z | modules/andes-core/broker/src/main/java/org/wso2/andes/kernel/router/TopicRoutingMatcher.java | a5anka/andes | 7b4a8cd5d16777b920a0c6ca208aa07ea6426c49 | [
"Apache-2.0"
] | 114 | 2015-01-22T05:06:07.000Z | 2022-03-30T03:18:29.000Z | 41.574468 | 119 | 0.626621 | 1,002,807 | /*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.andes.kernel.router;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.amqp.AMQPUtils;
import org.wso2.andes.kernel.AndesException;
import org.wso2.andes.kernel.ProtocolType;
import org.wso2.andes.kernel.subscription.StorageQueue;
import org.wso2.andes.mqtt.utils.MQTTUtils;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Bitmap based topic matcher
*/
public class TopicRoutingMatcher {
private Log log = LogFactory.getLog(TopicRoutingMatcher.class);
/**
* The topic delimiter to differentiate each constituent according to the current protocol type.
*/
private String constituentsDelimiter;
/**
* The multi level matching wildcard according to the current protocol type.
*/
private String multiLevelWildCard;
/**
* The single level matching wildcard according to the current protocol type.
*/
private String singleLevelWildCard;
private ProtocolType protocolType;
// 'Null' and 'Other' constituents are picked from restricted topic characters
/**
* Constituent name to represent that a constituent is not available at this location.
*/
private static final String NULL_CONSTITUENT = "%null%";
/**
* Constituent name to represent any constituent except a wildcard.
*/
private static final String OTHER_CONSTITUENT = "%other%";
/**
* Keeps all the storage queues.
*/
private List<StorageQueue> storageQueueList = new ArrayList<>();
/**
* Keeps all the binding keys of storage queues broken into their constituents.
*/
private Map<Integer, String[]> queueConstituents = new HashMap<>();
/**
* Keeps all the constituent tables as ListOfConstituentTables <ConstituentPart, BitSet>.
*/
private List<Map<String, BitSet>> constituentTables = new ArrayList<>();
/**
* Initialize BitMapHandler with the protocol type.
*
* @param protocolType The protocol type to handle
*/
public TopicRoutingMatcher(ProtocolType protocolType) {
if (ProtocolType.AMQP == protocolType) {
constituentsDelimiter = ".";
// AMQPUtils keep wildcard concatenated with constituent delimiter, hence removing them get wildcard only
multiLevelWildCard = AMQPUtils.TOPIC_AND_CHILDREN_WILDCARD.replace(constituentsDelimiter, "");
singleLevelWildCard = AMQPUtils.IMMEDIATE_CHILDREN_WILDCARD.replace(constituentsDelimiter, "");
} else if (ProtocolType.MQTT == protocolType) {
constituentsDelimiter = "/";
multiLevelWildCard = MQTTUtils.MULTI_LEVEL_WILDCARD;
singleLevelWildCard = MQTTUtils.SINGLE_LEVEL_WILDCARD;
} else {
throw new RuntimeException("Protocol type " + protocolType + " is not recognized.");
}
this.protocolType = protocolType;
}
public void addStorageQueue(StorageQueue storageQueue) throws AndesException {
String bindingKey = storageQueue.getMessageRouterBindingKey();
if (StringUtils.isNotEmpty(bindingKey)) {
if (!isStorageQueueAvailable(storageQueue)) {
int newQueueIndex = storageQueueList.size();
// The index is added to make it clear to which index this is being inserted
storageQueueList.add(newQueueIndex, storageQueue);
String constituents[] = bindingKey.split(Pattern.quote(constituentsDelimiter));
queueConstituents.put(newQueueIndex, constituents);
for (int constituentIndex = 0; constituentIndex < constituents.length; constituentIndex++) {
String constituent = constituents[constituentIndex];
Map<String, BitSet> constituentTable;
if ((constituentIndex + 1) > constituentTables.size()) {
// No tables exist for this constituent index need to create
constituentTable = addConstituentTable(constituentIndex);
} else {
constituentTable = constituentTables.get(constituentIndex);
}
if (!constituentTable.keySet().contains(constituent)) {
// This constituent is not available in this table. Need to add a new row
addConstituentRow(constituent, constituentIndex);
}
}
addStorageQueueColumn(bindingKey, newQueueIndex);
} else {
updateStorageQueue(storageQueue);
}
} else {
throw new AndesException("Error adding a new storageQueue. Subscribed bindingKey is empty.");
}
}
public void updateStorageQueue(StorageQueue storageQueue) {
if (isStorageQueueAvailable(storageQueue)) {
// Need to add the new entry to the same index since bitmap logic is dependent on this index
int index = storageQueueList.indexOf(storageQueue);
// Should not allow to modify this list until the update is complete
// Otherwise the storageQueue indexes will be invalid
synchronized (storageQueueList) {
storageQueueList.remove(index);
storageQueueList.add(index, storageQueue);
}
}
}
/**
* @param constituentIndex The index to create the constituent for
* @return The created constituent table
*/
private Map<String, BitSet> addConstituentTable(int constituentIndex) {
Map<String, BitSet> constituentTable = new HashMap<>();
BitSet nullBitSet = new BitSet(storageQueueList.size());
BitSet otherBitSet = new BitSet(storageQueueList.size());
// Fill null and other constituent values for all available queues
for (int queueIndex = 0; queueIndex < storageQueueList.size(); queueIndex++) {
String[] constituentsOfQueue = queueConstituents.get(queueIndex);
if (constituentsOfQueue.length < constituentIndex + 1) {
// There is no constituent in this queue for this constituent index
nullBitSet.set(queueIndex);
// If last constituent of the queue is multiLevelWildCard, then any other is a match
if (multiLevelWildCard.equals(constituentsOfQueue[constituentsOfQueue.length - 1])) {
otherBitSet.set(queueIndex);
}
} else {
String queueConstituent = constituentsOfQueue[constituentIndex];
// Check if this is a wildcard
if (multiLevelWildCard.equals(queueConstituent) ||
singleLevelWildCard.equals(queueConstituent)) {
otherBitSet.set(queueIndex);
}
}
}
// Add 'null' and 'other' constituent
constituentTable.put(NULL_CONSTITUENT, nullBitSet);
constituentTable.put(OTHER_CONSTITUENT, otherBitSet);
constituentTables.add(constituentIndex, constituentTable);
return constituentTable;
}
/**
* Run through each constituentTable and insert a new column for a new storage queue filling it's values
* by comparing constituents.
* <p/>
* This will only fill values for the already available constituents. Will not add new constituents.
*
* @param bindingKey The newly subscribed destination
*/
private void addStorageQueueColumn(String bindingKey, int queueIndex) throws AndesException {
String[] bindingKeyConstituents = queueConstituents.get(queueIndex);
// Create a mock destination with two constituents for 'other' wildcard matching
String matchDestinationForOther = OTHER_CONSTITUENT + constituentsDelimiter + OTHER_CONSTITUENT;
// Create a mock destination with three constituents for 'null' wildcard matching
String matchDestinationForNull = NULL_CONSTITUENT + constituentsDelimiter + NULL_CONSTITUENT +
constituentsDelimiter + NULL_CONSTITUENT;
// Loop through each constituent table for the new constituents
for (int constituentIndex = 0; constituentIndex < bindingKeyConstituents.length;
constituentIndex++) {
String currentConstituent = bindingKeyConstituents[constituentIndex];
Map<String, BitSet> constituentTable = constituentTables.get(constituentIndex);
// Loop through each constituent row in the table and fill values
for (Map.Entry<String, BitSet> constituentRow : constituentTable.entrySet()) {
String constituentOfCurrentRow = constituentRow.getKey();
BitSet bitSet = constituentRow.getValue();
if (constituentOfCurrentRow.equals(currentConstituent)) {
bitSet.set(queueIndex);
} else if (NULL_CONSTITUENT.equals(constituentOfCurrentRow)) {
// Check if this constituent being null matches the destination if we match it with
// a null constituent
String wildcardDestination = NULL_CONSTITUENT + constituentsDelimiter +
currentConstituent;
bitSet.set(queueIndex, isMatchForProtocolType(wildcardDestination,
matchDestinationForNull));
// }
} else if (OTHER_CONSTITUENT.equals(constituentOfCurrentRow)) {
// Check if other is matched by comparing wildcard through specific wildcard matching
// Create a mock destinations with current constituent added last and check if it match with a
// non-wildcard destination match with the corresponding matching method
String wildCardDestination = OTHER_CONSTITUENT + constituentsDelimiter + currentConstituent;
bitSet.set(queueIndex, isMatchForProtocolType(wildCardDestination,
matchDestinationForOther));
} else if (singleLevelWildCard.equals(currentConstituent) ||
multiLevelWildCard.equals(currentConstituent)) {
// If there is any wildcard at this position, then this should match.
bitSet.set(queueIndex);
} else {
bitSet.set(queueIndex, false);
}
}
}
int noOfMaxConstituents = constituentTables.size();
if (noOfMaxConstituents > bindingKeyConstituents.length) {
// There are more constituent tables to be filled. Wildcard matching is essential here.
boolean matchingOthers = true;
// The OTHER_CONSTITUENT is added here to represent any constituent
if (!multiLevelWildCard.equals(bindingKeyConstituents[bindingKeyConstituents.length
- 1])) {
String otherConstituentComparer = bindingKey + constituentsDelimiter + OTHER_CONSTITUENT;
matchingOthers = isMatchForProtocolType(bindingKey, otherConstituentComparer);
} // Else matchingOthers will be true
for (int constituentIndex = bindingKeyConstituents.length; constituentIndex <
noOfMaxConstituents; constituentIndex++) {
Map<String, BitSet> constituentTable = constituentTables.get(constituentIndex);
// Loop through each constituent row in the table and fill values
for (Map.Entry<String, BitSet> constituentRow : constituentTable.entrySet()) {
String constituentOfCurrentRow = constituentRow.getKey();
BitSet bitSet = constituentRow.getValue();
if (NULL_CONSTITUENT.equals(constituentOfCurrentRow)) {
// Null constituent is always true here
bitSet.set(queueIndex);
} else {
bitSet.set(queueIndex, matchingOthers);
}
}
}
}
}
/**
* Add a new constituent row for the given constituent index table and fill values for already available
* queues.
*
* @param constituent The constituent to add
* @param constituentIndex The index of the constituent
*/
private void addConstituentRow(String constituent, int constituentIndex) {
Map<String, BitSet> constituentTable = constituentTables.get(constituentIndex);
BitSet bitSet = new BitSet();
for (int i = 0; i < queueConstituents.size(); i++) {
String[] constituentsOfQueue = queueConstituents.get(i);
if (constituentIndex < constituentsOfQueue.length) {
// Get the i'th queue's [constituentIndex]'th constituent
String queueConstituent = constituentsOfQueue[constituentIndex];
if (queueConstituent.equals(constituent) || multiLevelWildCard.equals(queueConstituent)
|| singleLevelWildCard.equals(queueConstituent)) {
// The new constituent matches the queues i'th constituent
bitSet.set(i);
} else {
// The new constituent does not match the i'th queues [constituentIndex] constituent
bitSet.set(i, false);
}
} else {
// The queue does not have a constituent for this index
// If the last constituent of the queue is multiLevelWildCard we match else false
if (multiLevelWildCard.equals(constituentsOfQueue[constituentsOfQueue.length - 1])) {
bitSet.set(i);
} else {
bitSet.set(i, false);
}
}
}
constituentTable.put(constituent, bitSet);
}
/**
* Return the match between the given two parameters with respect to the protocol.
*
* @param wildCardDestination The destination with/without wildcard
* @param nonWildCardDestination The direct destination without wildcards
* @return Match status
* @throws AndesException
*/
private boolean isMatchForProtocolType(String wildCardDestination, String nonWildCardDestination) throws
AndesException {
boolean matching = false;
if (ProtocolType.AMQP == protocolType) {
matching = AMQPUtils.isTargetQueueBoundByMatchingToRoutingKey(wildCardDestination, nonWildCardDestination);
} else if (ProtocolType.MQTT == protocolType) {
matching = MQTTUtils.isTargetQueueBoundByMatchingToRoutingKey(wildCardDestination, nonWildCardDestination);
} else {
throw new AndesException("Protocol type " + protocolType + " is not recognized.");
}
return matching;
}
/**
* This methods adds a constituent table with only null and other constituents.
* This is required when a message comes with more than the available number of constituents. If wildcard
* queues are available for those, they should match. Hence need to create these empty constituent tables.
*/
private void addEmptyConstituentTable() {
int noOfqueues = storageQueueList.size();
Map<String, BitSet> constituentTable = new HashMap<>();
BitSet nullBitSet = new BitSet(noOfqueues);
BitSet otherBitSet = new BitSet(noOfqueues);
if (noOfqueues > 0) {
// Null constituent will always be true for empty constituents, hence need to flip
nullBitSet.flip(0, noOfqueues - 1);
for (int queueIndex = 0; queueIndex < noOfqueues; queueIndex++) {
// For 'other', if subscribers last constituent is multi level wild card then matching
String[] allConstituent = queueConstituents.get(queueIndex);
String lastConstituent = allConstituent[allConstituent.length - 1];
if (multiLevelWildCard.equals(lastConstituent)) {
otherBitSet.set(queueIndex);
} else {
otherBitSet.set(queueIndex, false);
}
}
}
constituentTable.put(NULL_CONSTITUENT, nullBitSet);
constituentTable.put(OTHER_CONSTITUENT, otherBitSet);
constituentTables.add(constituentTable);
}
/**
* Removing a storageQueue from the structure.
*
* @param storageQueue The storageQueue to remove
*/
public void removeStorageQueue(StorageQueue storageQueue) {
int queueIndex = storageQueueList.indexOf(storageQueue);
if (queueIndex > -1) {
for (Map<String, BitSet> constituentTable : constituentTables) {
for (Map.Entry<String, BitSet> constituentRow : constituentTable.entrySet()) {
// For every row create a new BitSet with the values for the removed storageQueue removed
String constituent = constituentRow.getKey();
BitSet bitSet = constituentRow.getValue();
BitSet newBitSet = new BitSet();
int bitIndex = 0;
for (int i = 0; i < bitSet.size(); i++) {
if (bitIndex == queueIndex) {
// If the this is the index to remove then skip this round
bitIndex++;
}
newBitSet.set(i, bitSet.get(bitIndex));
bitIndex++;
}
constituentTable.put(constituent, newBitSet);
}
}
// Remove the storageQueue from storageQueue list
storageQueueList.remove(queueIndex);
} else {
log.warn("Storage queue for with name : " + storageQueue.getName() + " is not found to " +
"remove");
}
}
public boolean isStorageQueueAvailable(StorageQueue storageQueue) {
return storageQueueList.contains(storageQueue);
}
/**
* Get storage queues matching to routing key
* @param routingKey routing key to match queues
* @return set of storage queues
*/
public Set<StorageQueue> getMatchingStorageQueues(String routingKey) {
Set<StorageQueue> matchingQueues = new HashSet<>();
if (StringUtils.isNotEmpty(routingKey)) {
// constituentDelimiter is quoted to avoid making the delimiter a regex symbol
String[] constituents = routingKey.split(Pattern.quote(constituentsDelimiter),-1);
int noOfCurrentMaxConstituents = constituentTables.size();
// If given routingKey has more constituents than any subscriber has, then create constituent tables
// for those before collecting matching subscribers
if (constituents.length > noOfCurrentMaxConstituents) {
for (int i = noOfCurrentMaxConstituents; i < constituents.length; i++) {
addEmptyConstituentTable();
}
}
// Keeps the results of 'AND' operations between each bit sets
BitSet andBitSet = new BitSet(storageQueueList.size());
// Since BitSet is initialized with false for each element we need to flip
andBitSet.flip(0, storageQueueList.size());
// Get corresponding bit set for each constituent in the routingKey and operate bitwise AND operation
for (int constituentIndex = 0; constituentIndex < constituents.length; constituentIndex++) {
String constituent = constituents[constituentIndex];
Map<String, BitSet> constituentTable = constituentTables.get(constituentIndex);
BitSet bitSetForAnd = constituentTable.get(constituent);
if (null == bitSetForAnd) {
// The constituent is not found in the table, hence matching with 'other' constituent
bitSetForAnd = constituentTable.get(OTHER_CONSTITUENT);
}
andBitSet.and(bitSetForAnd);
}
// If there are more constituent tables, get the null constituent in each of them and operate bitwise AND
for (int constituentIndex = constituents.length; constituentIndex < constituentTables.size();
constituentIndex++) {
Map<String, BitSet> constituentTable = constituentTables.get(constituentIndex);
andBitSet.and(constituentTable.get(NULL_CONSTITUENT));
}
// Valid queues are filtered, need to pick from queue pool
int nextSetBitIndex = andBitSet.nextSetBit(0);
while (nextSetBitIndex > -1) {
matchingQueues.add(storageQueueList.get(nextSetBitIndex));
nextSetBitIndex = andBitSet.nextSetBit(nextSetBitIndex + 1);
}
} else {
log.warn("Cannot retrieve storage queues via bitmap handler since routingKey to match is empty");
}
return matchingQueues;
}
/**
* Get all the storage queues currently saved.
*
* @return List of all storage queues
*/
public List<StorageQueue> getAllStorageQueues() {
return storageQueueList;
}
/**
* Get all binding keys saved
*
* @return set of different binding keys
*/
public Set<String> getAllBindingKeys() {
Set<String> topics = new HashSet<>();
for (Map.Entry<Integer, String[]> subcriberConstituent : queueConstituents.entrySet()) {
StringBuilder topic = new StringBuilder();
String[] constituents = subcriberConstituent.getValue();
for (int i = 0; i < constituents.length; i++) {
String constituent = constituents[i];
// if this is a wildcard constituent, we provide it as 'ANY' in it's place for readability
if (multiLevelWildCard.equals(constituent) || singleLevelWildCard.equals(constituent)) {
topic.append("ANY");
} else {
topic.append(constituent);
}
// append the delimiter if there are more constituents to come
if ((constituents.length - 1) > i) {
topic.append(constituentsDelimiter);
}
}
topics.add(topic.toString());
}
return topics;
}
}
|
9243e07ab2f9aaacc9306429b0aa076ccfeb0124 | 919 | java | Java | src/main/java/com/alipay/api/domain/AlipayPcreditLoanLoanUnclearQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 333 | 2018-08-28T09:26:55.000Z | 2022-03-31T07:26:42.000Z | src/main/java/com/alipay/api/domain/AlipayPcreditLoanLoanUnclearQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 46 | 2018-09-27T03:52:42.000Z | 2021-08-10T07:54:57.000Z | src/main/java/com/alipay/api/domain/AlipayPcreditLoanLoanUnclearQueryModel.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 158 | 2018-12-07T17:03:43.000Z | 2022-03-17T09:32:43.000Z | 21.372093 | 75 | 0.712731 | 1,002,808 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 查询待还账单
*
* @author auto create
* @since 1.0, 2018-11-14 14:27:40
*/
public class AlipayPcreditLoanLoanUnclearQueryModel extends AlipayObject {
private static final long serialVersionUID = 4246612525392728319L;
/**
* 预算类型,取值{CLEAR, OVD_AND_CURRENT}:CLEAR-结清预算, OVD_AND_CURRENT-逾期和当期预算
*/
@ApiField("budget_type")
private String budgetType;
/**
* 代表了一次请求,作为业务幂等性控制
*/
@ApiField("out_request_no")
private String outRequestNo;
public String getBudgetType() {
return this.budgetType;
}
public void setBudgetType(String budgetType) {
this.budgetType = budgetType;
}
public String getOutRequestNo() {
return this.outRequestNo;
}
public void setOutRequestNo(String outRequestNo) {
this.outRequestNo = outRequestNo;
}
}
|
9243e2102b95503f7ac299cbb818db0ba57d65e3 | 714 | java | Java | app/src/main/java/hk/hku/cs/buttonnavigationtest/Admission/Stu_Lee.java | wmsheng/HKUMSCCS | a137ba510f50c9bb11ac278e15992c8d48bceb81 | [
"Apache-2.0"
] | 1 | 2018-12-15T08:02:41.000Z | 2018-12-15T08:02:41.000Z | app/src/main/java/hk/hku/cs/buttonnavigationtest/Admission/Stu_Lee.java | wmsheng/HKUMSCCS | a137ba510f50c9bb11ac278e15992c8d48bceb81 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/hk/hku/cs/buttonnavigationtest/Admission/Stu_Lee.java | wmsheng/HKUMSCCS | a137ba510f50c9bb11ac278e15992c8d48bceb81 | [
"Apache-2.0"
] | 1 | 2019-12-27T07:45:26.000Z | 2019-12-27T07:45:26.000Z | 28.56 | 66 | 0.726891 | 1,002,809 | package hk.hku.cs.buttonnavigationtest.Admission;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import hk.hku.cs.buttonnavigationtest.R;
/*
* 项目名: ButtonNavigationTest
* 包名: hk.hku.cs.buttonnavigationtest.Admission
* 文件名: Stu_cuiyitong
* 创建者: BENNETT
* 创建时间: 2018/10/21 19:46
* 描述: TODO
*/public class Stu_Lee extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admission_stuindivi_leeliptong);
View view = findViewById(R.id.lee);
}
}
|
9243e22769b80cc9b9a09932dbd4e2fbb94b19ad | 2,536 | java | Java | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloudTest.java | hugh-barclay/kubernetes-plugin | ec8031d03fa3197a1c1c680f4e4e91a41dc71b24 | [
"Apache-2.0"
] | 2 | 2017-01-06T09:42:11.000Z | 2017-06-10T12:46:24.000Z | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloudTest.java | hugh-barclay/kubernetes-plugin | ec8031d03fa3197a1c1c680f4e4e91a41dc71b24 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloudTest.java | hugh-barclay/kubernetes-plugin | ec8031d03fa3197a1c1c680f4e4e91a41dc71b24 | [
"Apache-2.0"
] | 2 | 2019-06-06T21:04:02.000Z | 2021-05-05T13:00:42.000Z | 39.625 | 201 | 0.68336 | 1,002,810 | package org.csanchez.jenkins.plugins.kubernetes;
import static org.junit.Assert.*;
import org.csanchez.jenkins.plugins.kubernetes.volumes.EmptyDirVolume;
import org.csanchez.jenkins.plugins.kubernetes.volumes.PodVolume;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
public class KubernetesCloudTest {
private KubernetesCloud cloud = new KubernetesCloud("test", null, "http://localhost:8080", "default", null, "", 0,
0, /* retentionTimeoutMinutes= */ 5);
@Test
public void testInheritance() {
ContainerTemplate jnlp = new ContainerTemplate("jnlp", "jnlp:1");
ContainerTemplate maven = new ContainerTemplate("maven", "maven:1");
maven.setTtyEnabled(true);
maven.setCommand("cat");
PodVolume podVolume = new EmptyDirVolume("/some/path", true);
PodTemplate parent = new PodTemplate();
parent.setName("parent");
parent.setLabel("parent");
parent.setContainers(Arrays.asList(jnlp));
parent.setVolumes(Arrays.asList(podVolume));
ContainerTemplate maven2 = new ContainerTemplate("maven", "maven:2");
PodTemplate withNewMavenVersion = new PodTemplate();
withNewMavenVersion.setContainers(Arrays.asList(maven2));
PodTemplate result = PodTemplateUtils.combine(parent, withNewMavenVersion);
}
@Test
public void testParseDockerCommand() {
assertNull(cloud.parseDockerCommand(""));
assertNull(cloud.parseDockerCommand(null));
assertEquals(ImmutableList.of("bash"), cloud.parseDockerCommand("bash"));
assertEquals(ImmutableList.of("bash", "-c", "x y"), cloud.parseDockerCommand("bash -c \"x y\""));
assertEquals(ImmutableList.of("a", "b", "c", "d"), cloud.parseDockerCommand("a b c d"));
}
@Test
public void testParseLivenessProbe() {
assertNull(cloud.parseLivenessProbe(""));
assertNull(cloud.parseLivenessProbe(null));
assertEquals(ImmutableList.of("docker","info"), cloud.parseLivenessProbe("docker info"));
assertEquals(ImmutableList.of("echo","I said: 'I am alive'"), cloud.parseLivenessProbe("echo \"I said: 'I am alive'\""));
assertEquals(ImmutableList.of("docker","--version"), cloud.parseLivenessProbe("docker --version"));
assertEquals(ImmutableList.of("curl","-k","--silent","--output=/dev/null","https://localhost:8080"), cloud.parseLivenessProbe("curl -k --silent --output=/dev/null \"https://localhost:8080\""));
}
}
|
9243e2c897a10fb0d8c4a1b234e9bcd360ab7cac | 3,016 | java | Java | addressbook-web-tests/src/test/java/ua/qa/training/addressbook/appmanager/ApplicationManager.java | olenasblv/java_training | ff78f98a905c09b0fab7e511e6f4a7a5e68858ce | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ua/qa/training/addressbook/appmanager/ApplicationManager.java | olenasblv/java_training | ff78f98a905c09b0fab7e511e6f4a7a5e68858ce | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ua/qa/training/addressbook/appmanager/ApplicationManager.java | olenasblv/java_training | ff78f98a905c09b0fab7e511e6f4a7a5e68858ce | [
"Apache-2.0"
] | null | null | null | 31.092784 | 115 | 0.680371 | 1,002,811 | package ua.qa.training.addressbook.appmanager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.BrowserType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* Created by osoboleva on 9/18/2016.
*/
public class ApplicationManager {
private final Properties properties;
WebDriver wd;
private SessionHelper sessionHelper;
private NavigationHelper navigationHelper;
private ContactHelper contactHelper;
private GroupHelper groupHelper;
private String browser;
private DBHelper dbHelper;
public ApplicationManager(String browser) {
this.browser = browser;
properties = new Properties();
}
public void init() throws IOException {
String target = System.getProperty("target", "local");
properties.load(new FileReader(new File(String.format("src/test/resources/%s.properties", target))));
dbHelper = new DBHelper();
if ("".equals(properties.getProperty("selenium.server"))) {
if (Objects.equals(browser, BrowserType.FIREFOX)) {
wd = new FirefoxDriver();
} else if (Objects.equals(browser, BrowserType.CHROME)) {
wd = new ChromeDriver();
} else if (Objects.equals(browser, BrowserType.IE)) {
wd = new InternetExplorerDriver();
}
} else {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName(browser);
capabilities.setPlatform(Platform.fromString(System.getProperty("platform", "win7")));
wd = new RemoteWebDriver(new URL(properties.getProperty("selenium.server")), capabilities);
}
wd.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
wd.get(properties.getProperty("web.baseUrl"));
groupHelper = new GroupHelper(wd);
contactHelper = new ContactHelper(wd);
navigationHelper = new NavigationHelper(wd);
sessionHelper = new SessionHelper(wd);
sessionHelper.login(properties.getProperty("web.adminLogin"), properties.getProperty("web.adminPassword"));
}
public void stop() {
wd.quit();
}
public GroupHelper group() {
return groupHelper;
}
public ContactHelper contact() {
return contactHelper;
}
public NavigationHelper goTo() {
return navigationHelper;
}
public DBHelper db() {
return dbHelper;
}
public byte[] takeScreenshot(){
return ((TakesScreenshot) wd).getScreenshotAs(OutputType.BYTES);
}
}
|
9243e319ba2699628fcc523d45d208198c574fd0 | 9,542 | java | Java | SisDistClient/src/sisdistclient/ClientController.java | reneerojas/dist-sys | b8b52c888276a5271db5d16615d1ea08f91c438f | [
"MIT"
] | null | null | null | SisDistClient/src/sisdistclient/ClientController.java | reneerojas/dist-sys | b8b52c888276a5271db5d16615d1ea08f91c438f | [
"MIT"
] | null | null | null | SisDistClient/src/sisdistclient/ClientController.java | reneerojas/dist-sys | b8b52c888276a5271db5d16615d1ea08f91c438f | [
"MIT"
] | null | null | null | 32.127946 | 234 | 0.530706 | 1,002,812 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sisdistclient;
import com.ComExecutor;
import com.ConnectionManager;
import core.Client;
import core.DynamicClassManager;
import core.Response;
import java.net.URL;
import java.util.NoSuchElementException;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lib.json.JsonArray;
import lib.json.JsonObject;
/**
*
* @author renee
*/
public class ClientController implements Initializable
{
private Client cli;
private ConnectionManager con = ConnectionManager.getInstance();
private Response resp;
private DynamicClassManager dynamicClassManager = DynamicClassManager.getInstance();
@FXML
private Button button;
@FXML
private TextArea txAreaCode;
@FXML
private Button btSolicitarCod;
@FXML
private TextField inputIp;
@FXML
private TextField tfClasse;
@FXML
private TextField tfversao;
@FXML
private Label labelStatus;
@FXML
private TextArea txAreaResults;
@FXML
private Label label;
@FXML
private TextField tfParametros;
@FXML
private Button btSolicitar;
@FXML
private TextField tfMethod;
@FXML
private TextField inputName;
@FXML
private void handleButtonAction(ActionEvent event)
{
//Configura dados de conexao
cli = Client.getInstance();
cli.serverAddressProperty().set(inputIp.getText());
cli.nameProperty().set(inputName.getText());
startListeners();
con.newConnection(cli.serverAddressProperty().get());
con.getConnectInstance().setName(cli.nameProperty().get());
ComExecutor.getInstance().getExecutor().execute(con.getConnectInstance());
inputName.setDisable(true);
inputIp.setDisable(true);
}
private void startListeners()
{
labelStatus.textProperty().bind(ConnectionManager.getInstance().getMessage());
ConnectionManager.getInstance().getStatus().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) ->
{
if(newValue.intValue() == 4)
{
button.setVisible(false);
} else
{
inputName.setDisable(false);
inputIp.setDisable(false);
Response.getInstance().setWait(true);
button.setVisible(true);
}
});
}
@Override
public void initialize(URL url, ResourceBundle rb)
{
initilizaClasses();
resp = Response.getInstance();
txAreaResults.textProperty().bind(resp.responseProperty());
listenButton();
}
public void initilizaClasses()
{
dynamicClassManager.insert("Fibonacci", "public class Fibonacci{public int fib(int n){int i = 1, j = 0;int t;for(int k = 0; k < n; k++){t = i + j;i = j;j = t;}return j;}public int getVersion(){return 1;}}", 1);
dynamicClassManager.insert("Math", "public class Math{public int soma(int x, int y){return x + y;}public int mult(int x, int y){return x * y;}public int sub(int x, int y){return x - y;}public int getVersion(){return 1;}}", 1);
}
private boolean capturaValores(JsonArray jArray)
{
if(!tfParametros.getText().toString().equals(""))
{
String str = tfParametros.getText().toString();
StringTokenizer s = new StringTokenizer(str, ",");
boolean cont = true;
while(cont)
{
try
{
jArray.add(Integer.parseInt(s.nextToken()));
} catch(NumberFormatException e)
{
return false;
} catch(NoSuchElementException e)
{
cont = false;
}
}
} else
{
// Platform.runLater(() ->
// {
// tfParametros.setText("0");
// });
// jArray.add(0);
}
return true;
}
private void listenButton()
{
btSolicitar.disableProperty().bind(Response.getInstance().waitProperty());
btSolicitarCod.disableProperty().bind(Response.getInstance().waitProperty());
txAreaCode.disableProperty().bind(Response.getInstance().waitProperty());
tfClasse.disableProperty().bind(Response.getInstance().waitProperty());
tfversao.disableProperty().bind(Response.getInstance().waitProperty());
tfMethod.disableProperty().bind(Response.getInstance().waitProperty());
tfParametros.disableProperty().bind(Response.getInstance().waitProperty());
}
@FXML
void solicitar(ActionEvent event)
{
JsonObject jObj = new JsonObject();
JsonArray jArray = new JsonArray();
if(!tfClasse.getText().toString().equals(""))
{
if(!tfMethod.getText().toString().equals(""))
{
if(capturaValores(jArray))
{
try
{
jObj.add("success", true);
jObj.add("op", "request");
jObj.add("class", tfClasse.getText().toString());
jObj.add("method", tfMethod.getText().toString());
// jObj.add("version", 1);
jObj.add("params", jArray);
Response.getInstance().setWait(true);
con.getConnectInstance().sendJson(jObj);
} catch(NumberFormatException x)
{
mensagemErro("Dados Incorretos");
}
} else
{
mensagemErro("Parametros Errados");
}
} else
{
mensagemErro("Campo Metodo Vazio");
}
} else
{
mensagemErro("Campo Classe Vazio");
}
}
@FXML
void solicitarCod(ActionEvent event)
{
JsonObject jObj = new JsonObject();
JsonArray jArray = new JsonArray();
if(!tfClasse.getText().toString().equals(""))
{
if(!tfMethod.getText().toString().equals(""))
{
if(!txAreaCode.getText().toString().equals(""))
{
if(!tfversao.getText().toString().equals(""))
{
if(capturaValores(jArray))
{
try
{
jObj.add("success", true);
jObj.add("op", "newclass");
jObj.add("class", tfClasse.getText().toString());
jObj.add("method", tfMethod.getText().toString());
jObj.add("version", Integer.parseInt(tfversao.getText().toString()));
jObj.add("code", txAreaCode.getText().toString());
jObj.add("params", jArray);
Response.getInstance().setWait(true);
con.getConnectInstance().sendJson(jObj);
if(dynamicClassManager.verificaVersaoMaior(tfClasse.getText().toString(), Integer.parseInt(tfversao.getText().toString())))
{
dynamicClassManager.remove(tfClasse.getText().toString());
dynamicClassManager.insert(tfClasse.getText().toString(), txAreaCode.getText().toString(), Integer.parseInt(tfversao.getText().toString()));
}
} catch(NumberFormatException x)
{
mensagemErro("Dados Incorretos");
}
} else
{
mensagemErro("Parametros Errados");
}
} else
{
mensagemErro("Campo Versão Vazio");
}
} else
{
mensagemErro("Campo Código Vazio");
}
} else
{
mensagemErro("Campo Metodo Vazio");
}
} else
{
mensagemErro("Campo Classe Vazio");
}
}
private void mensagemErro(String str)
{
Stage dialog = new Stage();
dialog.setHeight(85);
dialog.setWidth(200);
dialog.setTitle("Erro");
dialog.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(new Group(new Text(50, 25, str)));
dialog.setScene(scene);
dialog.show();
}
}
|
9243e32cc4abaf05da31d4de301025e9067bd36b | 3,973 | java | Java | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/InternalSinkWriterMetricGroup.java | raymondk/flink | 2738c02db7100ff172b4ca7bd4c294419fe7ba7c | [
"Apache-2.0"
] | 9 | 2016-09-22T22:53:13.000Z | 2019-11-30T03:07:29.000Z | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/InternalSinkWriterMetricGroup.java | raymondk/flink | 2738c02db7100ff172b4ca7bd4c294419fe7ba7c | [
"Apache-2.0"
] | 1 | 2022-02-25T03:04:41.000Z | 2022-02-25T03:04:41.000Z | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/InternalSinkWriterMetricGroup.java | raymondk/flink | 2738c02db7100ff172b4ca7bd4c294419fe7ba7c | [
"Apache-2.0"
] | 1 | 2022-03-25T07:25:23.000Z | 2022-03-25T07:25:23.000Z | 38.95098 | 95 | 0.76894 | 1,002,813 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.metrics.groups;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.Gauge;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.groups.OperatorIOMetricGroup;
import org.apache.flink.metrics.groups.OperatorMetricGroup;
import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
import org.apache.flink.metrics.groups.UnregisteredMetricsGroup;
import org.apache.flink.runtime.metrics.MetricNames;
/** Special {@link org.apache.flink.metrics.MetricGroup} representing an Operator. */
@Internal
public class InternalSinkWriterMetricGroup extends ProxyMetricGroup<MetricGroup>
implements SinkWriterMetricGroup {
// deprecated, use numRecordsSendErrors instead.
@Deprecated private final Counter numRecordsOutErrors;
private final Counter numRecordsSendErrors;
private final Counter numRecordsWritten;
private final Counter numBytesWritten;
private final OperatorIOMetricGroup operatorIOMetricGroup;
private InternalSinkWriterMetricGroup(
MetricGroup parentMetricGroup, OperatorIOMetricGroup operatorIOMetricGroup) {
super(parentMetricGroup);
numRecordsOutErrors = parentMetricGroup.counter(MetricNames.NUM_RECORDS_OUT_ERRORS);
numRecordsSendErrors = parentMetricGroup.counter(MetricNames.NUM_RECORDS_SEND_ERRORS);
numRecordsWritten = parentMetricGroup.counter(MetricNames.NUM_RECORDS_SEND);
numBytesWritten = parentMetricGroup.counter(MetricNames.NUM_BYTES_SEND);
this.operatorIOMetricGroup = operatorIOMetricGroup;
}
public static InternalSinkWriterMetricGroup wrap(OperatorMetricGroup operatorMetricGroup) {
return new InternalSinkWriterMetricGroup(
operatorMetricGroup, operatorMetricGroup.getIOMetricGroup());
}
@VisibleForTesting
public static InternalSinkWriterMetricGroup mock(MetricGroup metricGroup) {
return new InternalSinkWriterMetricGroup(
metricGroup, UnregisteredMetricsGroup.createOperatorIOMetricGroup());
}
@VisibleForTesting
public static InternalSinkWriterMetricGroup mock(
MetricGroup metricGroup, OperatorIOMetricGroup operatorIOMetricGroup) {
return new InternalSinkWriterMetricGroup(metricGroup, operatorIOMetricGroup);
}
@Override
public OperatorIOMetricGroup getIOMetricGroup() {
return operatorIOMetricGroup;
}
@Deprecated
@Override
public Counter getNumRecordsOutErrorsCounter() {
return numRecordsOutErrors;
}
@Override
public Counter getNumRecordsSendErrorsCounter() {
return numRecordsSendErrors;
}
@Override
public Counter getNumRecordsSendCounter() {
return numRecordsWritten;
}
@Override
public Counter getNumBytesSendCounter() {
return numBytesWritten;
}
@Override
public void setCurrentSendTimeGauge(Gauge<Long> currentSendTimeGauge) {
parentMetricGroup.gauge(MetricNames.CURRENT_SEND_TIME, currentSendTimeGauge);
}
}
|
9243e393b3fefaa508e783fe619c708abd70065d | 4,334 | java | Java | src/main/groovy/com/blackducksoftware/integration/hub/detect/DetectPhoneHomeManager.java | fossabot/hub-detect | 19ccde0a7ad35cb30fa3872d9f33ee493c30bc01 | [
"Apache-2.0"
] | null | null | null | src/main/groovy/com/blackducksoftware/integration/hub/detect/DetectPhoneHomeManager.java | fossabot/hub-detect | 19ccde0a7ad35cb30fa3872d9f33ee493c30bc01 | [
"Apache-2.0"
] | 1 | 2018-06-28T10:18:58.000Z | 2018-06-28T10:18:58.000Z | src/main/groovy/com/blackducksoftware/integration/hub/detect/DetectPhoneHomeManager.java | fossabot/hub-detect | 19ccde0a7ad35cb30fa3872d9f33ee493c30bc01 | [
"Apache-2.0"
] | 1 | 2018-06-28T10:14:38.000Z | 2018-06-28T10:14:38.000Z | 39.4 | 176 | 0.73581 | 1,002,814 | /**
* hub-detect
*
* Copyright (C) 2018 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.blackducksoftware.integration.hub.detect;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.blackducksoftware.integration.hub.detect.model.BomToolType;
import com.blackducksoftware.integration.hub.service.PhoneHomeService;
import com.blackducksoftware.integration.hub.service.model.PhoneHomeResponse;
import com.blackducksoftware.integration.phonehome.PhoneHomeRequestBody;
@Component
public class DetectPhoneHomeManager {
@Autowired
private DetectInfo detectInfo;
@Autowired
private DetectConfiguration detectConfiguration;
private PhoneHomeService phoneHomeService;
private PhoneHomeResponse phoneHomeResponse;
public void init(final PhoneHomeService phoneHomeService) {
this.phoneHomeService = phoneHomeService;
}
public void startPhoneHome() {
// hub-detect will attempt to phone home twice - once upon startup and
// once upon getting all the bom tool metadata.
//
// We would prefer to always wait for all the bom tool metadata, but
// sometimes there is not enough time to complete a phone home before
// hub-detect exits (if the scanner is disabled, for example).
performPhoneHome(null);
}
public void startPhoneHome(final Set<BomToolType> applicableBomToolTypes) {
performPhoneHome(applicableBomToolTypes);
}
private void performPhoneHome(final Set<BomToolType> applicableBomToolTypes) {
endPhoneHome();
// TODO When we begin to phone home in offline mode, we should re-address this section
if (null != phoneHomeService) {
final PhoneHomeRequestBody.Builder phoneHomeRequestBodyBuilder = createBuilder();
if (applicableBomToolTypes != null) {
final String applicableBomToolsString = StringUtils.join(applicableBomToolTypes, ", ");
phoneHomeRequestBodyBuilder.addToMetaData("bomToolTypes", applicableBomToolsString);
}
final PhoneHomeRequestBody phoneHomeRequestBody = phoneHomeRequestBodyBuilder.build();
phoneHomeResponse = phoneHomeService.startPhoneHome(phoneHomeRequestBody);
}
}
public void endPhoneHome() {
if (phoneHomeResponse != null) {
phoneHomeResponse.endPhoneHome();
}
}
public PhoneHomeResponse getPhoneHomeResponse() {
return phoneHomeResponse;
}
private PhoneHomeRequestBody.Builder createBuilder() {
final PhoneHomeRequestBody.Builder phoneHomeRequestBodyBuilder = phoneHomeService.createInitialPhoneHomeRequestBodyBuilder("hub-detect", detectInfo.getDetectVersion());
detectConfiguration.getAdditionalPhoneHomePropertyNames().stream().forEach(propertyName -> {
final String actualKey = getKeyWithoutPrefix(propertyName, DetectConfiguration.PHONE_HOME_PROPERTY_PREFIX);
final String value = detectConfiguration.getDetectProperty(propertyName);
phoneHomeRequestBodyBuilder.addToMetaData(actualKey, value);
});
return phoneHomeRequestBodyBuilder;
}
private String getKeyWithoutPrefix(final String key, final String prefix) {
final int prefixIndex = key.indexOf(prefix) + prefix.length();
return key.substring(prefixIndex);
}
}
|
9243e41b5bb8095bacefe642aaf8d8bef46b566b | 34,636 | java | Java | proto-google-cloud-error-reporting-v1beta1/src/main/java/com/google/devtools/clouderrorreporting/v1beta1/ServiceContextFilter.java | renovate-bot/java-errorreportin | 8e4b9194c2354f13be230fd487f5a5f0c9570585 | [
"Apache-2.0"
] | 3 | 2020-07-16T13:20:04.000Z | 2021-10-05T08:00:23.000Z | proto-google-cloud-error-reporting-v1beta1/src/main/java/com/google/devtools/clouderrorreporting/v1beta1/ServiceContextFilter.java | renovate-bot/java-errorreportin | 8e4b9194c2354f13be230fd487f5a5f0c9570585 | [
"Apache-2.0"
] | 579 | 2019-11-07T16:32:36.000Z | 2022-03-29T17:53:02.000Z | proto-google-cloud-error-reporting-v1beta1/src/main/java/com/google/devtools/clouderrorreporting/v1beta1/ServiceContextFilter.java | renovate-bot/java-errorreportin | 8e4b9194c2354f13be230fd487f5a5f0c9570585 | [
"Apache-2.0"
] | 15 | 2019-10-30T21:26:20.000Z | 2021-10-07T04:48:27.000Z | 33.497099 | 118 | 0.677648 | 1,002,815 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/clouderrorreporting/v1beta1/error_stats_service.proto
package com.google.devtools.clouderrorreporting.v1beta1;
/**
*
*
* <pre>
* Specifies criteria for filtering a subset of service contexts.
* The fields in the filter correspond to the fields in `ServiceContext`.
* Only exact, case-sensitive matches are supported.
* If a field is unset or empty, it matches arbitrary values.
* </pre>
*
* Protobuf type {@code google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter}
*/
public final class ServiceContextFilter extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter)
ServiceContextFilterOrBuilder {
private static final long serialVersionUID = 0L;
// Use ServiceContextFilter.newBuilder() to construct.
private ServiceContextFilter(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ServiceContextFilter() {
service_ = "";
version_ = "";
resourceType_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ServiceContextFilter();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ServiceContextFilter(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
service_ = s;
break;
}
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
version_ = s;
break;
}
case 34:
{
java.lang.String s = input.readStringRequireUtf8();
resourceType_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.clouderrorreporting.v1beta1.ErrorStatsServiceProto
.internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContextFilter_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.clouderrorreporting.v1beta1.ErrorStatsServiceProto
.internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContextFilter_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter.class,
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter.Builder.class);
}
public static final int SERVICE_FIELD_NUMBER = 2;
private volatile java.lang.Object service_;
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The service.
*/
@java.lang.Override
public java.lang.String getService() {
java.lang.Object ref = service_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
service_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for service.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceBytes() {
java.lang.Object ref = service_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
service_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 3;
private volatile java.lang.Object version_;
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The version.
*/
@java.lang.Override
public java.lang.String getVersion() {
java.lang.Object ref = version_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
version_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for version.
*/
@java.lang.Override
public com.google.protobuf.ByteString getVersionBytes() {
java.lang.Object ref = version_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_TYPE_FIELD_NUMBER = 4;
private volatile java.lang.Object resourceType_;
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The resourceType.
*/
@java.lang.Override
public java.lang.String getResourceType() {
java.lang.Object ref = resourceType_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceType_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for resourceType.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceTypeBytes() {
java.lang.Object ref = resourceType_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resourceType_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(service_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, service_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, version_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceType_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, resourceType_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(service_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, service_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, version_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceType_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, resourceType_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter)) {
return super.equals(obj);
}
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter other =
(com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter) obj;
if (!getService().equals(other.getService())) return false;
if (!getVersion().equals(other.getVersion())) return false;
if (!getResourceType().equals(other.getResourceType())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + SERVICE_FIELD_NUMBER;
hash = (53 * hash) + getService().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
hash = (37 * hash) + RESOURCE_TYPE_FIELD_NUMBER;
hash = (53 * hash) + getResourceType().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Specifies criteria for filtering a subset of service contexts.
* The fields in the filter correspond to the fields in `ServiceContext`.
* Only exact, case-sensitive matches are supported.
* If a field is unset or empty, it matches arbitrary values.
* </pre>
*
* Protobuf type {@code google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter)
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilterOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.clouderrorreporting.v1beta1.ErrorStatsServiceProto
.internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContextFilter_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.clouderrorreporting.v1beta1.ErrorStatsServiceProto
.internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContextFilter_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter.class,
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter.Builder.class);
}
// Construct using
// com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
service_ = "";
version_ = "";
resourceType_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.devtools.clouderrorreporting.v1beta1.ErrorStatsServiceProto
.internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContextFilter_descriptor;
}
@java.lang.Override
public com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
getDefaultInstanceForType() {
return com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
.getDefaultInstance();
}
@java.lang.Override
public com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter build() {
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter buildPartial() {
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter result =
new com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter(this);
result.service_ = service_;
result.version_ = version_;
result.resourceType_ = resourceType_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter) {
return mergeFrom(
(com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter other) {
if (other
== com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
.getDefaultInstance()) return this;
if (!other.getService().isEmpty()) {
service_ = other.service_;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
onChanged();
}
if (!other.getResourceType().isEmpty()) {
resourceType_ = other.resourceType_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object service_ = "";
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The service.
*/
public java.lang.String getService() {
java.lang.Object ref = service_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
service_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for service.
*/
public com.google.protobuf.ByteString getServiceBytes() {
java.lang.Object ref = service_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
service_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The service to set.
* @return This builder for chaining.
*/
public Builder setService(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
service_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearService() {
service_ = getDefaultInstance().getService();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.service`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.service).
* </pre>
*
* <code>string service = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for service to set.
* @return This builder for chaining.
*/
public Builder setServiceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
service_ = value;
onChanged();
return this;
}
private java.lang.Object version_ = "";
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The version.
*/
public java.lang.String getVersion() {
java.lang.Object ref = version_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
version_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for version.
*/
public com.google.protobuf.ByteString getVersionBytes() {
java.lang.Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The version to set.
* @return This builder for chaining.
*/
public Builder setVersion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
version_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearVersion() {
version_ = getDefaultInstance().getVersion();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.version`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.version).
* </pre>
*
* <code>string version = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for version to set.
* @return This builder for chaining.
*/
public Builder setVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
version_ = value;
onChanged();
return this;
}
private java.lang.Object resourceType_ = "";
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The resourceType.
*/
public java.lang.String getResourceType() {
java.lang.Object ref = resourceType_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceType_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for resourceType.
*/
public com.google.protobuf.ByteString getResourceTypeBytes() {
java.lang.Object ref = resourceType_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resourceType_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The resourceType to set.
* @return This builder for chaining.
*/
public Builder setResourceType(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resourceType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearResourceType() {
resourceType_ = getDefaultInstance().getResourceType();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The exact value to match against
* [`ServiceContext.resource_type`](/error-reporting/reference/rest/v1beta1/ServiceContext#FIELDS.resource_type).
* </pre>
*
* <code>string resource_type = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for resourceType to set.
* @return This builder for chaining.
*/
public Builder setResourceTypeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resourceType_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter)
}
// @@protoc_insertion_point(class_scope:google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter)
private static final com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter();
}
public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ServiceContextFilter> PARSER =
new com.google.protobuf.AbstractParser<ServiceContextFilter>() {
@java.lang.Override
public ServiceContextFilter parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ServiceContextFilter(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ServiceContextFilter> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ServiceContextFilter> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.devtools.clouderrorreporting.v1beta1.ServiceContextFilter
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
9243e47caef72e422676aa1d99f1aa707b710d73 | 4,900 | java | Java | corejava/src/main/java/com/findshen/corejava/utils/extensions/StringUtils.java | Easzz/easycloud | 5d13b91bffb08356c12ecf44a515bfab2b94f4d6 | [
"Apache-2.0"
] | null | null | null | corejava/src/main/java/com/findshen/corejava/utils/extensions/StringUtils.java | Easzz/easycloud | 5d13b91bffb08356c12ecf44a515bfab2b94f4d6 | [
"Apache-2.0"
] | 3 | 2021-05-08T18:05:42.000Z | 2022-02-09T22:28:40.000Z | corejava/src/main/java/com/findshen/corejava/utils/extensions/StringUtils.java | Easzz/easycloud | 5d13b91bffb08356c12ecf44a515bfab2b94f4d6 | [
"Apache-2.0"
] | null | null | null | 26.203209 | 98 | 0.543265 | 1,002,816 | package com.findshen.corejava.utils.extensions;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* 字符串工具类
* Created by 李溪林 on 16-8-10.
*/
public class StringUtils {
private static final String currentClassName = "StringUtils";
/**
* 是否为null或空字符串
*
* @param str 要判定的字符串
* @return 若为空或空字符串, 则返回 true,否则返回 false.
*/
public static boolean isNullOrEmpty(String str) {
return str == null || str.equals("");
}
/**
* 是否为null或空字符串或空格
*
* @param str 要判定的字符串
* @return 若为空或空字符串或空格, 则返回 true,否则返回 false.
*/
public static boolean isNullOrWhiteSpace(String str) {
return isNullOrEmpty(str) || Pattern.compile("\\s+").matcher(str).matches();
}
/**
* 将字符串以指定符号分割
*
* @param str 要分割的字符串
* @param op 符号
* @return 字符串数组
*/
public static String[] split(String str, String op) {
return split(str, op, false);
}
/**
* 将字符串以指定符号分割
*
* @param str 要分割的字符串
* @param op 符号
* @param removeEmpty 是否移除空字符串
* @return 字符串数组
*/
public static String[] split(String str, String op, boolean removeEmpty) {
if (str == null) {
return null;
}
checkSplitOpIsNotNull(op, "split");
if(op.equals(".")){
op = "\\.";
}
String[] r = str.split(op, -1);
if (!removeEmpty) {
return r;
}
List<String> list = new ArrayList();
for (String item : r) {
if (!isNullOrEmpty(item)) {
list.add(item);
}
}
String[] result = new String[list.size()];
list.toArray(result);
return result;
}
/**
* 将字符串以指定符号分割并返回整型List集合
*
* @param str 要分割的字符串
* @param op 符号
* @param ignoreConvertException 是否忽略转化异常
* @return 整型List集合
*/
public static List<Integer> toIntList(String str, String op, boolean ignoreConvertException) {
if (str == null) {
return null;
}
checkSplitOpIsNotNull(op, "toIntList");
String[] arr = split(str, op);
return ArrayUtils.toList(ArrayUtils.toIntArray(arr, ignoreConvertException));
}
/**
* 将字符串以指定符号分割并返回整型Set集合
*
* @param str 要分割的字符串
* @param op 符号
* @param ignoreConvertException 是否忽略转化异常
* @return 整型Set集合
*/
public static Set<Integer> toIntSet(String str, String op, boolean ignoreConvertException) {
if (str == null) {
return null;
}
checkSplitOpIsNotNull(op, "toIntSet");
String[] arr = split(str, op);
return ArrayUtils.toSet(ArrayUtils.toIntArray(arr, ignoreConvertException));
}
/**
* 将字符串以指定符号分割并返回长整型List集合
*
* @param str 要分割的字符串
* @param op 符号
* @param ignoreConvertException 是否忽略转化异常
* @return 长整型List集合
*/
public static List<Long> toLongList(String str, String op, boolean ignoreConvertException) {
if (str == null) {
return null;
}
checkSplitOpIsNotNull(op, "toLongList");
String[] arr = split(str, op);
return ArrayUtils.toList(ArrayUtils.toLongArray(arr, ignoreConvertException));
}
/**
* 将字符串以指定符号分割并返回长整型Set集合
*
* @param str 要分割的字符串
* @param op 符号
* @param ignoreConvertException 是否忽略转化异常
* @return 长整型Set集合
*/
public static Set<Long> toLongSet(String str, String op, boolean ignoreConvertException) {
if (str == null) {
return null;
}
checkSplitOpIsNotNull(op, "toLongSet");
String[] arr = split(str, op);
return ArrayUtils.toSet(ArrayUtils.toLongArray(arr, ignoreConvertException));
}
/**
* 获取字符串的字节长度
*
* @param value 字符串
* @return 字节长度, 汉字按2个字节算
*/
public static long getByteLength(String value) {
if (isNullOrEmpty(value)) {
return 0;
}
int strLen = 0;
try {
char[] cs = value.toCharArray();
for (int i = 0; i < cs.length; i++) {
strLen += String.valueOf(cs[i]).getBytes("gbk").length;
}
} catch (Exception e) {
throw new UtilsException(currentClassName + "中的方法[getByteLength]发生异常.", e);
}
return strLen;
}
/**
* 检查分割符号是否为null,为null则抛出异常.
* @param op 分割符号
* @param method 方法名
*/
private static void checkSplitOpIsNotNull(String op, String method) {
if (op == null) {
throw new UtilsException(currentClassName + "中的方法[" + method + "]发生异常:分割符号不能为null.");
}
}
}
|
9243e4d550ecf5acb233dbaa00ad84ab0f84aeb6 | 24,362 | java | Java | polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/newengine/meta/PersistentReadWriteLock.java | chenzl25/galaxysql | 2fe3dac5146c48701d0f60651ae27811b4fe92fd | [
"Apache-2.0"
] | 480 | 2021-10-16T06:00:00.000Z | 2022-03-28T05:54:49.000Z | polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/newengine/meta/PersistentReadWriteLock.java | chenzl25/galaxysql | 2fe3dac5146c48701d0f60651ae27811b4fe92fd | [
"Apache-2.0"
] | 31 | 2021-10-20T02:59:55.000Z | 2022-03-29T03:38:33.000Z | polardbx-executor/src/main/java/com/alibaba/polardbx/executor/ddl/newengine/meta/PersistentReadWriteLock.java | chenzl25/galaxysql | 2fe3dac5146c48701d0f60651ae27811b4fe92fd | [
"Apache-2.0"
] | 96 | 2021-10-17T14:19:49.000Z | 2022-03-23T09:25:37.000Z | 38.854864 | 117 | 0.553526 | 1,002,817 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.executor.ddl.newengine.meta;
import com.alibaba.polardbx.common.exception.TddlNestableRuntimeException;
import com.alibaba.polardbx.common.utils.logger.Logger;
import com.alibaba.polardbx.common.utils.logger.LoggerFactory;
import com.alibaba.polardbx.gms.metadb.misc.ReadWriteLockAccessor;
import com.alibaba.polardbx.gms.metadb.misc.ReadWriteLockRecord;
import com.alibaba.polardbx.gms.util.MetaDbUtil;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.sql.Connection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* a read-write lock based on metaDB
* 支持读写锁
* 支持读写锁重入
* 支持隐式锁升级
* 不支持隐式锁降级
* 获取写锁后无需再获取读锁
* 非公平锁, 偏向读者,使用不当可能会写者形成活锁
* 支持批量获取读锁、写锁
* 为了性能以及避免死锁,推荐使用批量获取锁的接口
* <p>
* 未来支持死锁打破,目前使用的是死锁避免
* 未来考虑支持其他的锁优先级,比如公平锁、偏向写者
* 未来考虑整合进MdlLock
* 未来考虑提供锁超时接口
*/
public class PersistentReadWriteLock {
private static final Logger LOGGER = LoggerFactory.getLogger(PersistentReadWriteLock.class);
private static final String EXCLUSIVE = "EXCLUSIVE";
private static final long RETRY_INTERVAL = 1000L;
private PersistentReadWriteLock() {
}
public static PersistentReadWriteLock create() {
return new PersistentReadWriteLock();
}
public void readLock(String schemaName, String owner, String resource) {
readLockBatch(schemaName, owner, Sets.newHashSet(resource));
}
/**
* try to get the write lock, blocked if unable to
*/
public void readLockBatch(String schemaName, String owner, Set<String> resourceList) {
while (true) {
if (tryReadLockBatch(schemaName, owner, resourceList)) {
return;
}
try {
Thread.sleep(RETRY_INTERVAL);
} catch (InterruptedException e) {
// interrupt it if necessary
Thread.currentThread().interrupt();
return;
}
}
}
/**
* try to get the read lock, return false immediately if unable to
*
* @return if get read lock success
*/
public boolean tryReadLock(String schemaName, String owner, String resource) {
return tryReadLockBatch(schemaName, owner, Sets.newHashSet(resource));
}
/**
* 暂不支持锁降级
*/
public boolean tryReadLockBatch(String schemaName, String owner, Set<String> readLocks) {
if (StringUtils.isEmpty(owner)) {
throw new IllegalArgumentException("owner is empty");
}
if (CollectionUtils.isEmpty(readLocks)) {
return true;
}
return tryReadWriteLockBatch(schemaName, owner, readLocks, new HashSet<>());
}
public int unlockRead(String owner, String resource) {
return unlockReadBatch(owner, Sets.newHashSet(resource));
}
public int unlockReadBatch(String owner, Set<String> resourceList) {
if (StringUtils.isEmpty(owner)) {
throw new IllegalArgumentException("owner or resource is empty");
}
if (CollectionUtils.isEmpty(resourceList)) {
return 0;
}
int count = new ReadWriteLockAccessDelegate<Integer>() {
@Override
protected Integer invoke() {
try {
MetaDbUtil.beginTransaction(connection);
int c = 0;
for (String resource : resourceList) {
c += accessor.deleteByOwnerAndResourceAndType(owner, resource, owner);
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return c;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return 0;
}
}
}.execute();
return count;
}
public int unlockReadByOwner(String owner) {
int count = new ReadWriteLockAccessDelegate<Integer>() {
@Override
protected Integer invoke() {
try {
MetaDbUtil.beginTransaction(connection);
List<ReadWriteLockRecord> currentLocks = accessor.query(owner);
int c = 0;
for (ReadWriteLockRecord r : currentLocks) {
c += accessor.deleteByOwnerAndResourceAndType(owner, r.resource, r.owner);
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return c;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return 0;
}
}
}.execute();
return count;
}
/**
* try to get the write lock, blocked if unable to
*/
public void writeLock(String schemaName, String owner, String resource) {
writeLockBatch(schemaName, owner, Sets.newHashSet(resource));
}
/**
* try to get the write lock, blocked if unable to
*/
public void writeLockBatch(String schemaName, String owner, Set<String> resourceList) {
while (true) {
if (tryWriteLockBatch(schemaName, owner, resourceList)) {
return;
}
try {
Thread.sleep(RETRY_INTERVAL);
} catch (InterruptedException e) {
// interrupt it if necessary
Thread.currentThread().interrupt();
return;
}
}
}
/**
* try to get the write lock, return false immediately if unable to
*
* @return if get write lock success
*/
public boolean tryWriteLock(String schemaName, String owner, String resource) {
return tryWriteLockBatch(schemaName, owner, Sets.newHashSet(resource));
}
public boolean tryWriteLockBatch(String schemaName, String owner, Set<String> writeLocks) {
if (StringUtils.isEmpty(owner)) {
throw new IllegalArgumentException("owner or resource is empty");
}
if (CollectionUtils.isEmpty(writeLocks)) {
return true;
}
return tryReadWriteLockBatch(schemaName, owner, new HashSet<>(), writeLocks);
}
/**
* unlock the write lock, since only the owner can
* unlock it's write lock. so we need jobId and resource here
*
* @return unlock count
*/
public int unlockWrite(String owner, String resource) {
return unlockWriteBatch(owner, Sets.newHashSet(resource));
}
/**
* unlock the write lock, since only the owner can
* unlock it's write lock. so we need jobId and resource here
*
* @return unlock count
*/
public int unlockWriteBatch(String owner, Set<String> resourceList) {
if (StringUtils.isEmpty(owner)) {
throw new IllegalArgumentException("owner or resource is empty");
}
if (CollectionUtils.isEmpty(resourceList)) {
return 0;
}
int count = new ReadWriteLockAccessDelegate<Integer>() {
@Override
protected Integer invoke() {
try {
MetaDbUtil.beginTransaction(connection);
int c = 0;
for (String resource : resourceList) {
c += accessor.deleteByOwnerAndResourceAndType(owner, resource, EXCLUSIVE);
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return c;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return 0;
}
}
}.execute();
return count;
}
public int unlockWriteByOwner(String owner) {
int count = new ReadWriteLockAccessDelegate<Integer>() {
@Override
protected Integer invoke() {
try {
MetaDbUtil.beginTransaction(connection);
List<ReadWriteLockRecord> currentLocks = accessor.query(owner);
int c = 0;
for (ReadWriteLockRecord r : currentLocks) {
c += accessor.deleteByOwnerAndResourceAndType(owner, r.resource, EXCLUSIVE);
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return c;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return 0;
}
}
}.execute();
return count;
}
/**
* 释放所有属于这个owner的锁
*/
public int unlockReadWriteByOwner(String owner) {
int count = new ReadWriteLockAccessDelegate<Integer>() {
@Override
protected Integer invoke() {
try {
MetaDbUtil.beginTransaction(connection);
List<ReadWriteLockRecord> currentLocks = accessor.query(owner);
int c = 0;
for (ReadWriteLockRecord r : currentLocks) {
c += accessor.deleteByOwnerAndResourceAndType(owner, r.resource, r.type);
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return c;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return 0;
}
}
}.execute();
return count;
}
/**
* 释放所有属于这个owner的锁
*/
public int unlockReadWriteByOwner(Connection connection, String owner) {
final ReadWriteLockAccessor accessor = new ReadWriteLockAccessor();
accessor.setConnection(connection);
List<ReadWriteLockRecord> currentLocks = accessor.query(owner);
int count = 0;
for (ReadWriteLockRecord r : currentLocks) {
count += accessor.deleteByOwnerAndResourceAndType(owner, r.resource, r.type);
}
return count;
}
public int unlockReadWriteByOwner(Connection connection,
String owner,
Set<String> locks){
final ReadWriteLockAccessor accessor = new ReadWriteLockAccessor();
accessor.setConnection(connection);
List<ReadWriteLockRecord> currentLocks = accessor.query(owner);
int count = 0;
for (ReadWriteLockRecord r : currentLocks) {
if(locks.contains(r.resource)){
count += accessor.deleteByOwnerAndResourceAndType(owner, r.resource, r.type);
}
}
return count;
}
/**
* iff there's no record's type is 'EXCLUSIVE' and there's exactly one record's owner equals to 'owner'
*/
public boolean hasReadLock(String owner, String resource) {
return new ReadWriteLockAccessDelegate<Boolean>() {
@Override
protected Boolean invoke() {
try {
MetaDbUtil.beginTransaction(connection);
List<ReadWriteLockRecord> currentLocks = accessor.queryReader(resource);
boolean hasReadLock = false;
for (ReadWriteLockRecord r : currentLocks) {
if (isWriteLock(r.type)) {
return false;
}
if (isOwner(r, owner)) {
hasReadLock = true;
}
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return hasReadLock;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return false;
}
}
}.execute();
}
/**
* iff there's one record and it's type is 'EXCLUSIVE', and it's owner equals to 'owner'
*/
public boolean hasWriteLock(String owner, String resource) {
return new ReadWriteLockAccessDelegate<Boolean>() {
@Override
protected Boolean invoke() {
try {
MetaDbUtil.beginTransaction(connection);
List<ReadWriteLockRecord> currentLocks = accessor.queryReader(resource);
if (CollectionUtils.size(currentLocks) != 1) {
return false;
}
ReadWriteLockRecord r = currentLocks.get(0);
if (isWriteLock(r.type) && isOwner(r, owner)) {
return true;
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return false;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
return false;
}
}
}.execute();
}
/**
* query the blocker of the resource set
* 查看锁被谁阻塞了
*/
public Set<String> queryBlocker(Set<String> resource) {
return new ReadWriteLockAccessDelegate<Set<String>>() {
@Override
protected Set<String> invoke() {
Set<String> blockerSet = new HashSet<>(resource.size());
try {
MetaDbUtil.beginTransaction(connection);
List<ReadWriteLockRecord> currentLocks = accessor.query(resource, false);
for (ReadWriteLockRecord r : currentLocks) {
if (isWriteLock(r.type)) {
blockerSet.add(r.owner);
}
}
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return blockerSet;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "release write lock");
throw new TddlNestableRuntimeException(e);
}
}
}.execute();
}
public boolean tryReadWriteLockBatch(String schemaName,
String owner,
Set<String> readLockSet,
Set<String> writeLockSet){
return tryReadWriteLockBatch(schemaName, owner, readLockSet, writeLockSet, (Connection conn) -> true);
}
/**
* 批量获取读锁和写锁
* readLocks和writeLocks不允许出现交集
*/
public boolean tryReadWriteLockBatch(String schemaName,
String owner,
Set<String> readLockSet,
Set<String> writeLockSet,
Function<Connection, Boolean> func) {
if (StringUtils.isEmpty(owner)) {
throw new IllegalArgumentException("owner is empty");
}
final Set<String> writeLocks = Sets.newHashSet(writeLockSet);
final Set<String> readLocks = Sets.newHashSet(Sets.difference(readLockSet, writeLockSet));
boolean isSuccess = new ReadWriteLockAccessDelegate<Boolean>() {
@Override
protected Boolean invoke() {
try {
MetaDbUtil.beginTransaction(connection);
if (CollectionUtils.isEmpty(readLocks) && CollectionUtils.isEmpty(writeLocks)) {
func.apply(connection);
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return true;
}
List<ReadWriteLockRecord> currentLocks = accessor.query(Sets.union(readLocks, writeLocks), true);
for (ReadWriteLockRecord record : currentLocks) {
//write lock held by other owner
if (isWriteLock(record.type) && !isOwner(record, owner)) {
return false;
}
//try to acquire the write lock, but held by other reader
if (isReadLock(record.type)
&& !isOwner(record, owner)
&& writeLocks.contains(record.resource)) {
return false;
}
}
Set<String> acquiredReadLocks = getAcquiredReadLocks(currentLocks, owner);
Set<String> acquiredWriteLocks = getAcquiredWriteLocks(currentLocks, owner);
Set<String> needToUpgrade =
Sets.intersection(writeLocks, acquiredReadLocks);
Set<String> needToSkip =
Sets.union(acquiredWriteLocks, Sets.intersection(readLocks, acquiredReadLocks));
Set<String> needToAcquiredReadLocks =
Sets.difference(readLocks, Sets.union(needToSkip, needToUpgrade));
Set<String> needToAcquiredWriteLocks =
Sets.difference(writeLocks, Sets.union(needToSkip, needToUpgrade));
if (CollectionUtils.isEmpty(needToAcquiredReadLocks)
&& CollectionUtils.isEmpty(needToAcquiredWriteLocks)
&& CollectionUtils.isEmpty(needToUpgrade)) {
func.apply(connection);
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return true;
}
for (String r : needToUpgrade) {
accessor.deleteByOwnerAndResourceAndType(owner, r, owner);
}
List<ReadWriteLockRecord> readLockRecords = needToAcquiredReadLocks.stream().map(e -> {
ReadWriteLockRecord record = new ReadWriteLockRecord();
record.schemaName = schemaName;
record.owner = owner;
record.resource = e;
record.type = owner;
return record;
}).collect(Collectors.toList());
accessor.insert(readLockRecords);
List<ReadWriteLockRecord> writeLockRecords =
Sets.union(needToUpgrade, needToAcquiredWriteLocks).stream().map(e -> {
ReadWriteLockRecord record = new ReadWriteLockRecord();
record.schemaName = schemaName;
record.owner = owner;
record.resource = e;
record.type = EXCLUSIVE;
return record;
}).collect(Collectors.toList());
accessor.insert(writeLockRecords);
func.apply(connection);
MetaDbUtil.commit(connection);
MetaDbUtil.endTransaction(connection, LOGGER);
return true;
} catch (Exception e) {
//rollback all, if any resource is unable to acquire
MetaDbUtil.rollback(connection, e, LOGGER, "acquire write lock");
return false;
}
}
}.execute().booleanValue();
return isSuccess;
}
public boolean downGradeWriteLock(Connection connection,
String owner,
String writeLock){
Preconditions.checkArgument(StringUtils.isNotEmpty(owner), "owner is empty");
Preconditions.checkArgument(StringUtils.isNotEmpty(writeLock), "writeLock is empty");
final ReadWriteLockAccessor accessor = new ReadWriteLockAccessor();
accessor.setConnection(connection);
Optional<ReadWriteLockRecord> writeLockOptionalRecord = accessor.queryInShareMode(writeLock, EXCLUSIVE);
if(!writeLockOptionalRecord.isPresent()){
return false;
}
if(!StringUtils.equals(writeLockOptionalRecord.get().owner, owner)){
return false;
}
int count = accessor.deleteByOwnerAndResourceAndType(owner, writeLock, EXCLUSIVE);
if(count > 0){
ReadWriteLockRecord readLockRecord = new ReadWriteLockRecord();
readLockRecord.schemaName = writeLockOptionalRecord.get().schemaName;
readLockRecord.owner = owner;
readLockRecord.resource = writeLock;
readLockRecord.type = owner;
accessor.insert(Lists.newArrayList(readLockRecord));
return true;
}
return false;
}
/***************************************** privete function ***********************************************/
private Set<String> getAcquiredWriteLocks(List<ReadWriteLockRecord> currentLocks, String owner) {
Set<String> acquiredWriteLocks = Sets.newHashSet();
if (CollectionUtils.isNotEmpty(currentLocks)) {
currentLocks.forEach(e -> {
boolean isOwner = isOwner(e, owner);
boolean isWriteLock = isWriteLock(e.type);
if (isOwner && isWriteLock) {
acquiredWriteLocks.add(e.resource);
}
});
}
return acquiredWriteLocks;
}
private Set<String> getAcquiredReadLocks(List<ReadWriteLockRecord> currentLocks, String owner) {
Set<String> acquiredReadLocks = Sets.newHashSet();
if (CollectionUtils.isNotEmpty(currentLocks)) {
currentLocks.forEach(e -> {
boolean isOwner = isOwner(e, owner);
boolean isWriteLock = isWriteLock(e.type);
if (isOwner && !isWriteLock) {
acquiredReadLocks.add(e.resource);
}
});
}
return acquiredReadLocks;
}
private boolean isOwner(ReadWriteLockRecord record, String owner) {
return record != null && StringUtils.equals(record.owner, owner);
}
private boolean isWriteLock(String str) {
return StringUtils.equals(str, EXCLUSIVE);
}
private boolean isReadLock(String str) {
return !StringUtils.equals(str, EXCLUSIVE);
}
}
|
9243e52bea1c03cf6cb741e2e2c3446c3e676468 | 2,339 | java | Java | HattrickScoreboard-L/app/src/main/java/org/hattrickscoreboardl/services/process/HProcess.java | rpenco/hattrick-scoreboard | 46f66eec2e9c8087b067a1bcafc6b609f41c867d | [
"MIT"
] | null | null | null | HattrickScoreboard-L/app/src/main/java/org/hattrickscoreboardl/services/process/HProcess.java | rpenco/hattrick-scoreboard | 46f66eec2e9c8087b067a1bcafc6b609f41c867d | [
"MIT"
] | null | null | null | HattrickScoreboard-L/app/src/main/java/org/hattrickscoreboardl/services/process/HProcess.java | rpenco/hattrick-scoreboard | 46f66eec2e9c8087b067a1bcafc6b609f41c867d | [
"MIT"
] | 1 | 2021-04-16T23:14:45.000Z | 2021-04-16T23:14:45.000Z | 24.113402 | 79 | 0.619496 | 1,002,818 | package org.hattrickscoreboardl.services.process;
import android.content.Context;
import android.util.Log;
import org.hattrick.providers.abstracts.IParam;
import org.hattrick.providers.abstracts.IRequest;
import org.hattrick.providers.exceptions.ParserException;
import org.hattrickscoreboardl.services.UpdateCode;
import org.hattrickscoreboardl.services.UpdateListener;
import org.hattrickscoreboardl.services.loaders.Validity;
import java.io.IOException;
/**
* Created by romain
* on 21/11/2014.
*/
public abstract class HProcess {
Context context;
protected IRequest request;
boolean forceUpdate;
UpdateListener listener;
public HProcess(Context ctx, IRequest request, boolean forceUpdate){
this.context = ctx;
this.request = request;
this.forceUpdate = forceUpdate;
}
protected abstract String getTAG();
public void setListener(UpdateListener listener){
this.listener = listener;
}
public void perform(Object... args) {
fireStart();
}
protected void fireStart() {
if(listener != null)
listener.onUpdateStart(getTAG());
}
protected void fireError(String TAG, int code) {
if(listener != null)
listener.onUpdateError(getTAG(), code);
}
protected void fireSuccess() {
if(listener != null)
listener.onUpdateSuccess(getTAG());
}
/**
* Check if row is up to date
* @param fetchedDate row fetched date
* @param validity
* @return
*/
protected boolean isUpToDate(String fetchedDate, int validity){
return Validity.isUpToDate(getTAG(),forceUpdate,fetchedDate,validity);
}
protected <T> Object getResource(String TAG, IParam hparam){
//Get resource
T res = null;
try {
res = (T) request.get(hparam);
} catch (IOException e) {
e.printStackTrace();
fireError(TAG, UpdateCode.CODE_UNKNOWN_ERROR);
} catch (ParserException e) {
Log.e(TAG,"Exception: "+e.getCode()+" : "+e.getContent());
e.printStackTrace();
fireError(TAG, UpdateCode.CODE_UNKNOWN_ERROR);
}
return res;
}
}
|
9243e534170466d0e93268ab9887c4d272783d0e | 10,019 | java | Java | tsfile/src/main/java/org/apache/iotdb/tsfile/compress/ICompressor.java | marisuki/iotdb | 7f70d980667b223958e7f0139ebcaf41341e2613 | [
"Apache-2.0"
] | 945 | 2018-12-13T00:39:04.000Z | 2020-10-01T04:17:02.000Z | tsfile/src/main/java/org/apache/iotdb/tsfile/compress/ICompressor.java | marisuki/iotdb | 7f70d980667b223958e7f0139ebcaf41341e2613 | [
"Apache-2.0"
] | 923 | 2019-01-18T01:12:04.000Z | 2020-10-01T02:17:11.000Z | tsfile/src/main/java/org/apache/iotdb/tsfile/compress/ICompressor.java | marisuki/iotdb | 7f70d980667b223958e7f0139ebcaf41341e2613 | [
"Apache-2.0"
] | 375 | 2018-12-23T06:40:33.000Z | 2020-10-01T02:49:20.000Z | 31.806349 | 100 | 0.695578 | 1,002,819 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.tsfile.compress;
import org.apache.iotdb.tsfile.exception.compress.CompressionTypeNotSupportedException;
import org.apache.iotdb.tsfile.exception.compress.GZIPCompressOverflowException;
import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import org.xerial.snappy.Snappy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static org.apache.iotdb.tsfile.file.metadata.enums.CompressionType.GZIP;
import static org.apache.iotdb.tsfile.file.metadata.enums.CompressionType.LZ4;
import static org.apache.iotdb.tsfile.file.metadata.enums.CompressionType.SNAPPY;
/** compress data according to type in schema. */
public interface ICompressor extends Serializable {
static ICompressor getCompressor(String name) {
return getCompressor(CompressionType.valueOf(name));
}
/**
* get Compressor according to CompressionType.
*
* @param name CompressionType
* @return the Compressor of specified CompressionType
*/
static ICompressor getCompressor(CompressionType name) {
if (name == null) {
throw new CompressionTypeNotSupportedException("NULL");
}
switch (name) {
case UNCOMPRESSED:
return new NoCompressor();
case SNAPPY:
return new SnappyCompressor();
case LZ4:
return new IOTDBLZ4Compressor();
case GZIP:
return new GZIPCompressor();
default:
throw new CompressionTypeNotSupportedException(name.toString());
}
}
byte[] compress(byte[] data) throws IOException;
/**
* abstract method of compress. this method has an important overhead due to the fact that it
* needs to allocate a byte array to compress into, and then needs to resize this buffer to the
* actual compressed length.
*
* @return byte array of compressed data.
*/
byte[] compress(byte[] data, int offset, int length) throws IOException;
/**
* abstract method of compress.
*
* @return byte length of compressed data.
*/
int compress(byte[] data, int offset, int length, byte[] compressed) throws IOException;
/**
* If the data is large, this function is better than byte[].
*
* @param data MUST be DirectByteBuffer for Snappy.
* @param compressed MUST be DirectByteBuffer for Snappy.
* @return byte length of compressed data.
*/
int compress(ByteBuffer data, ByteBuffer compressed) throws IOException;
/**
* Get the maximum byte size needed for compressing data of the given byte size. For GZIP, this
* method is insecure and may cause {@code GZIPCompressOverflowException}
*
* @param uncompressedDataSize byte size of the data to compress
* @return maximum byte size of the compressed data
*/
int getMaxBytesForCompression(int uncompressedDataSize);
CompressionType getType();
/** NoCompressor will do nothing for data and return the input data directly. */
class NoCompressor implements ICompressor {
@Override
public byte[] compress(byte[] data) {
return data;
}
@Override
public byte[] compress(byte[] data, int offset, int length) throws IOException {
throw new IOException("No Compressor does not support compression function");
}
@Override
public int compress(byte[] data, int offset, int length, byte[] compressed) throws IOException {
throw new IOException("No Compressor does not support compression function");
}
@Override
public int compress(ByteBuffer data, ByteBuffer compressed) throws IOException {
throw new IOException("No Compressor does not support compression function");
}
@Override
public int getMaxBytesForCompression(int uncompressedDataSize) {
return uncompressedDataSize;
}
@Override
public CompressionType getType() {
return CompressionType.UNCOMPRESSED;
}
}
class SnappyCompressor implements ICompressor {
@Override
public byte[] compress(byte[] data) throws IOException {
if (data == null) {
return new byte[0];
}
return Snappy.compress(data);
}
@Override
public byte[] compress(byte[] data, int offset, int length) throws IOException {
byte[] maxCompressed = new byte[getMaxBytesForCompression(length)];
int compressedSize = Snappy.compress(data, offset, length, maxCompressed, 0);
byte[] compressed = null;
if (compressedSize < maxCompressed.length) {
compressed = new byte[compressedSize];
System.arraycopy(maxCompressed, 0, compressed, 0, compressedSize);
} else {
compressed = maxCompressed;
}
return compressed;
}
@Override
public int compress(byte[] data, int offset, int length, byte[] compressed) throws IOException {
return Snappy.compress(data, offset, length, compressed, 0);
}
@Override
public int compress(ByteBuffer data, ByteBuffer compressed) throws IOException {
return Snappy.compress(data, compressed);
}
@Override
public int getMaxBytesForCompression(int uncompressedDataSize) {
return Snappy.maxCompressedLength(uncompressedDataSize);
}
@Override
public CompressionType getType() {
return SNAPPY;
}
}
class IOTDBLZ4Compressor implements ICompressor {
private LZ4Compressor compressor;
public IOTDBLZ4Compressor() {
super();
LZ4Factory factory = LZ4Factory.fastestInstance();
compressor = factory.fastCompressor();
}
@Override
public byte[] compress(byte[] data) {
if (data == null) {
return new byte[0];
}
return compressor.compress(data);
}
@Override
public byte[] compress(byte[] data, int offset, int length) throws IOException {
return compressor.compress(data, offset, length);
}
@Override
public int compress(byte[] data, int offset, int length, byte[] compressed) {
return compressor.compress(data, offset, length, compressed, 0);
}
@Override
public int compress(ByteBuffer data, ByteBuffer compressed) {
compressor.compress(data, compressed);
return data.limit();
}
@Override
public int getMaxBytesForCompression(int uncompressedDataSize) {
return compressor.maxCompressedLength(uncompressedDataSize);
}
@Override
public CompressionType getType() {
return LZ4;
}
}
class GZIPCompress {
public static byte[] compress(byte[] data) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(data);
gzip.close();
return out.toByteArray();
}
public static byte[] uncompress(byte[] data) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(data);
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
in.close();
return out.toByteArray();
}
}
class GZIPCompressor implements ICompressor {
@Override
public byte[] compress(byte[] data) throws IOException {
if (null == data) {
return new byte[0];
}
return GZIPCompress.compress(data);
}
@Override
public byte[] compress(byte[] data, int offset, int length) throws IOException {
byte[] dataBefore = new byte[length];
System.arraycopy(data, offset, dataBefore, 0, length);
return GZIPCompress.compress(dataBefore);
}
/** @exception GZIPCompressOverflowException if compressed byte array is too small. */
@Override
public int compress(byte[] data, int offset, int length, byte[] compressed) throws IOException {
byte[] dataBefore = new byte[length];
System.arraycopy(data, offset, dataBefore, 0, length);
byte[] res = GZIPCompress.compress(dataBefore);
if (res.length > compressed.length) {
throw new GZIPCompressOverflowException();
}
System.arraycopy(res, 0, compressed, 0, res.length);
return res.length;
}
/** @exception GZIPCompressOverflowException if compressed ByteBuffer is too small. */
@Override
public int compress(ByteBuffer data, ByteBuffer compressed) throws IOException {
int length = data.remaining();
byte[] dataBefore = new byte[length];
data.get(dataBefore, 0, length);
byte[] res = GZIPCompress.compress(dataBefore);
if (res.length > compressed.capacity()) {
throw new GZIPCompressOverflowException();
}
compressed.put(res);
return res.length;
}
@Override
public int getMaxBytesForCompression(int uncompressedDataSize) {
// hard to estimate
return Math.max(40 + uncompressedDataSize / 2, uncompressedDataSize);
}
@Override
public CompressionType getType() {
return GZIP;
}
}
}
|
9243e6ffb18a1fbbfb61151942e0ad1a4b8a02b8 | 706 | java | Java | schedule/src/main/java/com/baidu/rigel/biplatform/schedule/constant/ScheduleConstant.java | 7inspire/BIPlatform | 160cd03fc82892fd04e03130f107bca88e24faf6 | [
"Apache-2.0"
] | 218 | 2017-06-09T05:01:29.000Z | 2022-01-13T23:32:37.000Z | schedule/src/main/java/com/baidu/rigel/biplatform/schedule/constant/ScheduleConstant.java | 7inspire/BIPlatform | 160cd03fc82892fd04e03130f107bca88e24faf6 | [
"Apache-2.0"
] | 21 | 2017-06-09T06:30:30.000Z | 2020-11-18T10:17:53.000Z | schedule/src/main/java/com/baidu/rigel/biplatform/schedule/constant/ScheduleConstant.java | 7inspire/BIPlatform | 160cd03fc82892fd04e03130f107bca88e24faf6 | [
"Apache-2.0"
] | 141 | 2017-06-09T05:01:12.000Z | 2022-03-05T03:30:14.000Z | 20.764706 | 76 | 0.650142 | 1,002,820 | package com.baidu.rigel.biplatform.schedule.constant;
import java.io.Serializable;
/**
* 调度模块常量类
*
* @author majun04
*
*/
public class ScheduleConstant implements Serializable {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 8260197320680566472L;
/**
* excuteAction参数名称
*/
public static final String EXCUTE_ACTION_KEY = "excuteAction";
/**
* 调度任务对象key
*/
public static final String SCHEDULE_TASK_OBJ_KEY = "scheduleTaskObjKey";
/**
* taskId参数key
*/
public static final String TASK_ID = "taskId";
/**
* 产品线名称
*/
public static final String PRODUCT_LINE_NAME = "productLineName";
}
|
9243e71944ac842f91be30d76f1c1499626a6da0 | 1,890 | java | Java | app/HslCommunication/Core/IMessage/S7Message.java | karateboy/iocom | ccaa62533e614943d2c1913e1d29b46983edc3c0 | [
"CC0-1.0"
] | null | null | null | app/HslCommunication/Core/IMessage/S7Message.java | karateboy/iocom | ccaa62533e614943d2c1913e1d29b46983edc3c0 | [
"CC0-1.0"
] | null | null | null | app/HslCommunication/Core/IMessage/S7Message.java | karateboy/iocom | ccaa62533e614943d2c1913e1d29b46983edc3c0 | [
"CC0-1.0"
] | null | null | null | 16.016949 | 71 | 0.525926 | 1,002,821 | package HslCommunication.Core.IMessage;
public class S7Message implements INetMessage
{
/**
* 消息头的指令长度
*/
public int ProtocolHeadBytesLength(){
return 4;
}
/**
* 从当前的头子节文件中提取出接下来需要接收的数据长度
* @return 返回接下来的数据内容长度
*/
public int GetContentLengthByHeadBytes(){
if(HeadBytes == null) return 0;
return (HeadBytes[2] & 0xff) * 256 + (HeadBytes[3] & 0xff) - 4;
}
/**
* 检查头子节的合法性
* @param token 特殊的令牌,有些特殊消息的验证
* @return 是否合法的验证
*/
public boolean CheckHeadBytesLegal(byte[] token)
{
if(HeadBytes == null) return false;
if(HeadBytes[0]==0x03 && HeadBytes[1] == 0x00){
return true;
}
else {
return false;
}
}
/**
* 获取头子节里的消息标识
* @return
*/
public int GetHeadBytesIdentity(){
return 0;
}
/**
* 获取消息头字节
*
* @return
*/
@Override
public byte[] getHeadBytes() {
return HeadBytes;
}
/**
* 获取消息内容字节
*
* @return
*/
@Override
public byte[] getContentBytes() {
return ContentBytes;
}
/**
* 获取发送的消息
*
* @return
*/
@Override
public byte[] getSendBytes() {
return SendBytes;
}
/**
* 设置消息头子节
* @param headBytes 字节数据
*/
public void setHeadBytes(byte[] headBytes){
HeadBytes = headBytes;
}
/**
* 设置消息内容字节
* @param contentBytes 内容字节
*/
public void setContentBytes(byte[] contentBytes){
ContentBytes = contentBytes;
}
/**
* 设置发送的字节信息
* @param sendBytes 发送的字节信息
*/
public void setSendBytes(byte[] sendBytes){
SendBytes = sendBytes;
}
private byte[] HeadBytes = null;
private byte[] ContentBytes = null;
private byte[] SendBytes = null;
}
|
9243e7416188dfb73d6dde325e67c42c1cb1de6e | 764 | java | Java | MathParser/src/com/aghajari/math/exception/MathVariableNotFoundException.java | Aghajari/MathParser | 6ae3c9cdcc0cc383de994aecc0f136cb34cc89c0 | [
"Apache-2.0"
] | 33 | 2022-02-17T22:07:06.000Z | 2022-03-09T14:22:59.000Z | MathParser/src/com/aghajari/math/exception/MathVariableNotFoundException.java | Aghajari/MathParser | 6ae3c9cdcc0cc383de994aecc0f136cb34cc89c0 | [
"Apache-2.0"
] | null | null | null | MathParser/src/com/aghajari/math/exception/MathVariableNotFoundException.java | Aghajari/MathParser | 6ae3c9cdcc0cc383de994aecc0f136cb34cc89c0 | [
"Apache-2.0"
] | 2 | 2022-02-24T08:11:48.000Z | 2022-02-24T11:49:45.000Z | 28.296296 | 100 | 0.670157 | 1,002,822 | package com.aghajari.math.exception;
public class MathVariableNotFoundException extends MathParserException {
final String variableName, guess;
public MathVariableNotFoundException(String src, int index, String variableName) {
super(src, index, variableName + " not found!");
this.variableName = variableName;
guess = null;
}
public MathVariableNotFoundException(String src, int index, String variableName, String guess) {
super(src, index, variableName + " not found, did you mean " + guess + "?");
this.variableName = variableName;
this.guess = guess;
}
public String getVariableName() {
return variableName;
}
public String getGuess() {
return guess;
}
}
|
9243e799581e4f2b9c1ae60f561fce98ef1319dd | 1,004 | java | Java | src/main/java/de/guntram/mcmod/worldtime/WorldTime.java | Haseck/WorldTime | 61ef612220a9548f35bdd2eb1cdf31994777826d | [
"MIT"
] | 6 | 2020-04-09T13:35:05.000Z | 2022-01-06T07:19:16.000Z | src/main/java/de/guntram/mcmod/worldtime/WorldTime.java | Haseck/WorldTime | 61ef612220a9548f35bdd2eb1cdf31994777826d | [
"MIT"
] | 6 | 2020-03-14T11:02:36.000Z | 2022-03-13T10:45:08.000Z | src/main/java/de/guntram/mcmod/worldtime/WorldTime.java | Haseck/WorldTime | 61ef612220a9548f35bdd2eb1cdf31994777826d | [
"MIT"
] | 5 | 2020-04-04T05:40:05.000Z | 2022-01-06T05:23:55.000Z | 30.424242 | 79 | 0.747012 | 1,002,823 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.guntram.mcmod.worldtime;
import de.guntram.mcmod.crowdintranslate.CrowdinTranslate;
import de.guntram.mcmod.fabrictools.ConfigurationProvider;
import net.fabricmc.api.ClientModInitializer;
/**
*
* @author gbl
*/
public class WorldTime implements ClientModInitializer {
public static final String MODID = "worldtime";
public static final String MODNAME = "World Time";
public static final String VERSION = "1.0";
public static WorldTime instance;
@Override
public void onInitializeClient() {
CrowdinTranslate.downloadTranslations(MODID);
ConfigurationHandler confHandler = ConfigurationHandler.getInstance();
ConfigurationProvider.register(MODNAME, confHandler);
confHandler.load(ConfigurationProvider.getSuggestedFile(MODID));
}
}
|
9243ead602740f80ee2773240f88e58db30fe416 | 989 | java | Java | rx_billing_service/src/main/java/com/miguelbcr/io/rx_billing_service/GsonAdapterFactory.java | miguelbcr/RxBillingService | d44897e89e4c9e8934c6fc089bca4f4fa898a279 | [
"Apache-2.0"
] | 28 | 2016-11-01T20:22:49.000Z | 2021-07-24T06:11:14.000Z | rx_billing_service/src/main/java/com/miguelbcr/io/rx_billing_service/GsonAdapterFactory.java | miguelbcr/RxBillingService | d44897e89e4c9e8934c6fc089bca4f4fa898a279 | [
"Apache-2.0"
] | null | null | null | rx_billing_service/src/main/java/com/miguelbcr/io/rx_billing_service/GsonAdapterFactory.java | miguelbcr/RxBillingService | d44897e89e4c9e8934c6fc089bca4f4fa898a279 | [
"Apache-2.0"
] | 4 | 2016-11-07T17:07:38.000Z | 2021-03-05T22:41:19.000Z | 30.90625 | 75 | 0.75632 | 1,002,824 | /*
* Copyright 2016 Miguel Garcia
*
* 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.miguelbcr.io.rx_billing_service;
import com.google.gson.TypeAdapterFactory;
import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory;
/**
* Created by miguel on 17/08/2016.
*/
@GsonTypeAdapterFactory
abstract class GsonAdapterFactory implements TypeAdapterFactory {
static GsonAdapterFactory create() {
return new AutoValueGson_GsonAdapterFactory();
}
}
|
9243eb56b9bd920e1f94f1e4063dbf89e73de4af | 9,258 | java | Java | src/main/i5/las2peer/services/servicePackage/lucene/searcher/LuceneSearcher.java | rwth-acis/Recommendation-Service | c80ba95891f7d91ab9539dabf7625a3a32cde1a5 | [
"Apache-2.0"
] | 2 | 2017-12-02T19:19:13.000Z | 2022-03-05T17:22:53.000Z | src/main/i5/las2peer/services/servicePackage/lucene/searcher/LuceneSearcher.java | rwth-acis/Expert-Recommender-Service | c80ba95891f7d91ab9539dabf7625a3a32cde1a5 | [
"Apache-2.0"
] | null | null | null | src/main/i5/las2peer/services/servicePackage/lucene/searcher/LuceneSearcher.java | rwth-acis/Expert-Recommender-Service | c80ba95891f7d91ab9539dabf7625a3a32cde1a5 | [
"Apache-2.0"
] | null | null | null | 30.86 | 142 | 0.680169 | 1,002,825 | package i5.las2peer.services.servicePackage.lucene.searcher;
import i5.las2peer.services.servicePackage.models.SemanticToken;
import i5.las2peer.services.servicePackage.models.Token;
import i5.las2peer.services.servicePackage.utils.semanticTagger.SemanticTagger;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Bits;
import com.google.common.collect.HashMultimap;
/**
* This class uses Apache Lucene searcher to search for the documents containing
* the query terms.
* Indexes are searched in the folder where it was original created.
* This is also used to create Question to Answers map and posts to author map.
*
*
* @author sathvik
*
*/
public class LuceneSearcher {
private IndexSearcher dataSearcher = null;
private IndexSearcher semanticDataSearcher = null;
private QueryParser dataParser = null;
private String queryString = null;
private HashMultimap<Long, Token> postid2Tokens = HashMultimap.create();
private HashMultimap<Long, Long> parentId2postIds = HashMultimap.create();
private HashMap<Long, Long> parentId2postId = new HashMap<Long, Long>();
private HashMap<Long, Long> postId2userId;
private QueryParser semanticDataParser;
private int maxNoOfResults = Integer.MAX_VALUE;
private static String dataIndexBasePath = "luceneIndex/%s/data";
/**
*
* @param query
* @param indexFilepath
* @throws IOException
*/
public LuceneSearcher(String query, String indexFilepath) throws IOException {
dataSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File(String.format(dataIndexBasePath, indexFilepath)).toPath())));
semanticDataSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File(String.format(dataIndexBasePath, indexFilepath))
.toPath())));
dataParser = new QueryParser("searchableText", new StandardAnalyzer());
semanticDataParser = new QueryParser("searchableText", new StandardAnalyzer());
queryString = query;
postId2userId = new HashMap<Long, Long>();
}
/**
*
* @param queryString
* A query string.
* @param n
* Integer value for the maximum number of results to be returned
* by lucene searcher.
* @return
* @throws IOException
* @throws ParseException
*/
public TopDocs performSearch(String queryString, int n) throws IOException, ParseException {
Query query = dataParser.parse(queryString);
TopDocs docs = dataSearcher.search(query, n);
System.out.println("No of HITS:: " + docs.totalHits);
maxNoOfResults = n;
return docs;
}
public TopDocs performSemanticSearch() throws IOException, ParseException {
SemanticTagger tagger = new SemanticTagger(queryString);
String tags = tagger.getSemanticData().getTags().replaceAll(",", " ");
tags = tags + queryString; // Add query terms to the semantic tags to
// search(Experimental, can remote
// queryString)
TopDocs docs = null;
System.out.println(tags);
try {
Query terms = null;
if (tags != null && tags.length() > 0) {
terms = semanticDataParser.parse(QueryParser.escape(tags));
docs = semanticDataSearcher.search(terms, maxNoOfResults);
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
// System.out.println("No of Semantic HITS:: " + docs.totalHits);
return docs;
}
public int getTotalNumberOfDocs() {
return dataSearcher.getIndexReader().numDocs();
}
/**
*
* @param docs
* @throws IOException
*/
public void buildQnAMap(TopDocs docs, Date date) throws IOException {
Token token = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date fmtCreationDate = null;
// This condition is specifically for Phpbb forums where parentId is not
// the postId but another unique id.
for (ScoreDoc scoreDoc : docs.scoreDocs) {
Document doc = dataSearcher.doc(scoreDoc.doc);
long postId = doc.get("postid") != null ? Long.parseLong(doc.get("postid")) : -1;
long parentId = doc.get("parentid") != null ? Long.parseLong(doc.get("parentid")) : -1;
long postTypeId = doc.get("postTypeId") != null ? Long.parseLong(doc.get("postTypeId")) : -1;
// If it is a question, for Phpbb forum
if (postTypeId == 1) {
parentId2postId.put(parentId, postId);
}
}
for (ScoreDoc scoreDoc : docs.scoreDocs) {
Document doc = dataSearcher.doc(scoreDoc.doc);
long postId = doc.get("postid") != null ? Long.parseLong(doc.get("postid")) : -1;
long parentId = doc.get("parentid") != null ? Long.parseLong(doc.get("parentid")) : -1;
long userId = doc.get("userid") != null ? Long.parseLong(doc.get("userid")) : -1;
// String creationDate = doc.get("creationDate");
//
// if (creationDate != null) {
// try {
// // If timestamp, use this.
// // fmtCreationDate =new
// // java.util.Date(Long.parseLong(creationDate)*1000);
// fmtCreationDate = format.parse(creationDate);
// } catch (java.text.ParseException e) {
// e.printStackTrace();
// }
// }
String text = doc.get("searchableText");
// System.out.println(postId + " :: " + parentId);
if (postId > 0) {
token = new Token(postId, text);
token.setFrequnecy(0);
}
postid2Tokens.put(postId, token);
// If parentId is present and the post was created before the
// requested date add the value to the map.
if (parentId > 0 && fmtCreationDate != null) {
// System.out.println("Parent Id > 0"+parentId);
// This condition is specifically for Phpbb forums where
// parentId is not the postId but another id.
if (parentId2postId.size() > 0) {
parentId = parentId2postId.get(parentId); // Retrieve the id
// of the question.
}
parentId2postIds.put(parentId, postId);
}
// System.out.println("USERID::" + userId);
if (userId > 0) {
postId2userId.put(postId, userId);
}
}
searchSemantics(date);
}
public void buildQnANetworkMap() throws IOException {
IndexReader reader = dataSearcher.getIndexReader();
Document doc = null;
Token token = null;
Bits liveDocs = MultiFields.getLiveDocs(reader);
for (int i = 0; i < reader.maxDoc(); i++) {
if (liveDocs != null && !liveDocs.get(i))
continue;
doc = reader.document(i);
long postId = doc.get("postid") != null ? Long.parseLong(doc.get("postid")) : -1;
long parentId = doc.get("parentid") != null ? Long.parseLong(doc.get("parentid")) : -1;
long userId = doc.get("userid") != null ? Long.parseLong(doc.get("userid")) : -1;
String text = doc.get("searchableText");
if (postId > 0) {
token = new Token(postId, text);
token.setFrequnecy(0);
}
postid2Tokens.put(postId, token);
if (parentId > 0) {
parentId2postIds.put(parentId, postId);
}
if (userId > 0) {
postId2userId.put(postId, userId);
}
}
}
private void searchSemantics(Date date) {
System.out.println("Search in Semantics...");
SemanticToken token = null;
try {
TopDocs docs = performSemanticSearch();
for (ScoreDoc scoreDoc : docs.scoreDocs) {
Document doc = dataSearcher.doc(scoreDoc.doc);
long postId = doc.get("postid") != null ? Long.parseLong(doc.get("postid")) : -1;
long parentId = doc.get("parentid") != null ? Long.parseLong(doc.get("parentid")) : -1;
long userId = doc.get("userid") != null ? Long.parseLong(doc.get("userid")) : -1;
String text = doc.get("searchableText");
// System.out.println(postId + " :: " + parentId);
if (postId > 0) {
token = new SemanticToken(postId, text);
token.setFrequnecy(0);
}
postid2Tokens.put(postId, token);
// If parentId is present and the post was created before
// the
// requested date add the value to the map.
if (parentId > 0) {
parentId2postIds.put(parentId, postId);
}
// System.out.println("USERID::" + userId);
if (userId > 0) {
postId2userId.put(postId, userId);
}
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public HashMap<Long, Long> getPostId2UserIdMap() {
return postId2userId;
}
public Map<Long, Collection<Long>> getQnAMap() {
return (Map<Long, Collection<Long>>) parentId2postIds.asMap();
}
public Document getDocument(int docId) throws IOException {
return dataSearcher.doc(docId);
}
}
|
9243ebeecc1647aae62bea60123e49bfc2dd4d8a | 227 | java | Java | src/java/pl/za/xvacuum/guilds/utils/ListUtils.java | tpacce/qGuilds | b51cd11530e677634b874784d0cc1b289570e315 | [
"MIT"
] | null | null | null | src/java/pl/za/xvacuum/guilds/utils/ListUtils.java | tpacce/qGuilds | b51cd11530e677634b874784d0cc1b289570e315 | [
"MIT"
] | null | null | null | src/java/pl/za/xvacuum/guilds/utils/ListUtils.java | tpacce/qGuilds | b51cd11530e677634b874784d0cc1b289570e315 | [
"MIT"
] | 1 | 2018-08-14T09:31:05.000Z | 2018-08-14T09:31:05.000Z | 17.461538 | 53 | 0.718062 | 1,002,826 | package pl.za.xvacuum.guilds.utils;
import java.lang.reflect.Field;
import java.util.List;
public class ListUtils {
public static boolean isList(Field f) {
return List.class.isAssignableFrom(f.getType());
}
}
|
9243ec6fda6540a418bfa764be4d8d23b1ec4a0f | 8,498 | java | Java | TRTCSDK/Android/TRTC-API-Example/Advanced/LocalRecord/src/main/java/com/tencent/trtc/localrecord/LocalRecordActivity.java | aliyunvideo/Queen_SDK_Android | e46e32e16f8a6ecf3746a5c397a6a1f36189e93c | [
"Apache-2.0"
] | 2 | 2021-07-06T03:32:25.000Z | 2021-12-17T02:24:16.000Z | TRTCSDK/Android/TRTC-API-Example/Advanced/LocalRecord/src/main/java/com/tencent/trtc/localrecord/LocalRecordActivity.java | aliyunvideo/Queen_SDK_Android | e46e32e16f8a6ecf3746a5c397a6a1f36189e93c | [
"Apache-2.0"
] | null | null | null | TRTCSDK/Android/TRTC-API-Example/Advanced/LocalRecord/src/main/java/com/tencent/trtc/localrecord/LocalRecordActivity.java | aliyunvideo/Queen_SDK_Android | e46e32e16f8a6ecf3746a5c397a6a1f36189e93c | [
"Apache-2.0"
] | 1 | 2022-03-31T09:07:26.000Z | 2022-03-31T09:07:26.000Z | 38.279279 | 166 | 0.644269 | 1,002,827 | package com.tencent.trtc.localrecord;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.basic.TRTCBaseActivity;
import com.tencent.liteav.TXLiteAVCode;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
import com.tencent.trtc.debug.GenerateTestUserSig;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Random;
/**
* TRTC本地视频录制页面
*
* 包含如下简单功能:
* - 开始视频录制{@link TRTCCloud#startLocalRecording(TRTCCloudDef.TRTCLocalRecordingParams)}
* - 停止视频录制{@link TRTCCloud#stopLocalRecording()}
*
* - 详见API说明文档{https://liteav.sdk.qcloud.com/doc/api/zh-cn/group__TRTCCloud__android.html#a5d6bf60e9d3051f601988e55106b296c}
*/
/**
* Local Video Recording
*
* Features:
* - Start video recording: {@link TRTCCloud#startLocalRecording(TRTCCloudDef.TRTCLocalRecordingParams)}
* - Stop video recording: {@link TRTCCloud#stopLocalRecording()}
*
* - For more information, please see the API document {https://liteav.sdk.qcloud.com/doc/api/zh-cn/group__TRTCCloud__android.html#a5d6bf60e9d3051f601988e55106b296c}.
*/
public class LocalRecordActivity extends TRTCBaseActivity implements View.OnClickListener {
private static final String TAG = "LocalRecordActivity";
private ImageView mImageBack;
private TextView mTextTitle;
private Button mButtonStartPush;
private Button mButtonRecord;
private EditText mEditRoomId;
private EditText mEditRecordPath;
private TXCloudVideoView mTXCloudPreviewView;
private TRTCCloud mTRTCCloud;
private boolean mStartPushFlag = false;
private boolean mStartRecordFlag = false;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local_record);
getSupportActionBar().hide();
if (checkPermission()) {
initView();
}
}
private void initView() {
mImageBack = findViewById(R.id.iv_back);
mTextTitle = findViewById(R.id.tv_room_number);
mButtonStartPush = findViewById(R.id.btn_start_push);
mButtonRecord = findViewById(R.id.btn_record);
mEditRoomId = findViewById(R.id.et_room_id);
mEditRecordPath = findViewById(R.id.et_record_path);
mTXCloudPreviewView = findViewById(R.id.txcvv_main_local);
mImageBack.setOnClickListener(this);
mButtonStartPush.setOnClickListener(this);
mButtonRecord.setOnClickListener(this);
mTextTitle.setText(getString(R.string.localrecord_roomid) + ":" + mEditRoomId.getText().toString());
}
private void enterRoom(String roomId) {
mTRTCCloud = TRTCCloud.sharedInstance(getApplicationContext());
mTRTCCloud.setListener(new TRTCCloudImplListener(LocalRecordActivity.this));
TRTCCloudDef.TRTCParams mTRTCParams = new TRTCCloudDef.TRTCParams();
mTRTCParams.sdkAppId = GenerateTestUserSig.SDKAPPID;
mTRTCParams.userId = new Random().nextInt(100000) + 1000000 + "";
mTRTCParams.roomId = Integer.parseInt(roomId);
mTRTCParams.userSig = GenerateTestUserSig.genTestUserSig(mTRTCParams.userId);
mTRTCParams.role = TRTCCloudDef.TRTCRoleAnchor;
mTRTCCloud.startLocalPreview(true, mTXCloudPreviewView);
mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
mTRTCCloud.enterRoom(mTRTCParams, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
}
private void exitRoom(){
if (mTRTCCloud != null) {
mTRTCCloud.stopAllRemoteView();
mTRTCCloud.stopLocalAudio();
mTRTCCloud.stopLocalPreview();
mTRTCCloud.exitRoom();
mTRTCCloud.setListener(null);
}
mTRTCCloud = null;
TRTCCloud.destroySharedInstance();
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.iv_back){
finish();
}else if(view.getId() == R.id.btn_start_push){
String roomId = mEditRoomId.getText().toString();
if(!mStartPushFlag){
if(!TextUtils.isEmpty(roomId)){
mButtonStartPush.setText(getString(R.string.localrecord_stop_push));
enterRoom(roomId);
mButtonRecord.setBackgroundColor(getResources().getColor(R.color.localrecord_button_select));
mStartPushFlag = true;
}else{
Toast.makeText(LocalRecordActivity.this, getString(R.string.localrecord_please_input_roomid_and_userid), Toast.LENGTH_SHORT).show();
}
}else{
mButtonRecord.setBackgroundColor(getResources().getColor(R.color.localrecord_button_select_off));
mButtonStartPush.setText(getString(R.string.localrecord_start_push));
exitRoom();
mStartPushFlag = false;
}
}else if(view.getId() == R.id.btn_record){
if(!mStartPushFlag){
return;
}
String recordFile = mEditRecordPath.getText().toString();
if(!mStartRecordFlag){
if(!TextUtils.isEmpty(recordFile)){
mStartRecordFlag = true;
mButtonRecord.setText(R.string.localrecord_stop_record);
startRecord(recordFile);
}else{
Toast.makeText(LocalRecordActivity.this, getString(R.string.localrecord_please_input_record_file_name), Toast.LENGTH_SHORT).show();
}
}else{
mStartRecordFlag = false;
mButtonRecord.setText(R.string.localrecord_start_record);
stopRecord();
}
}
}
private void stopRecord() {
mTRTCCloud.stopLocalRecording();
saveVideo();
}
private void saveVideo() {
String videoPath = getExternalFilesDir(null).getAbsolutePath() + File.separator + mEditRecordPath.getText().toString();
String coverPath = getExternalFilesDir(null).getAbsolutePath() + File.separator + "albun.png";
AlbumUtils.saveVideoToDCIM(LocalRecordActivity.this, videoPath, coverPath);
}
private void startRecord(String recordFile) {
String recordPath = getExternalFilesDir(null).getAbsolutePath();
Log.d(TAG, "recordPath = " + recordPath);
File file = new File(recordPath + File.separator + recordFile);
if(file.exists()){
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
TRTCCloudDef.TRTCLocalRecordingParams params = new TRTCCloudDef.TRTCLocalRecordingParams();
params.recordType = TRTCCloudDef.TRTC_RECORD_TYPE_BOTH;
params.filePath = recordPath + File.separator + recordFile;
mTRTCCloud.startLocalRecording(params);
}
protected class TRTCCloudImplListener extends TRTCCloudListener {
private WeakReference<LocalRecordActivity> mContext;
public TRTCCloudImplListener(LocalRecordActivity activity) {
super();
mContext = new WeakReference<>(activity);
}
@Override
public void onError(int errCode, String errMsg, Bundle extraInfo) {
Log.d(TAG, "sdk callback onError");
LocalRecordActivity activity = mContext.get();
if (activity != null) {
Toast.makeText(activity, "onError: " + errMsg + "[" + errCode+ "]" , Toast.LENGTH_SHORT).show();
if (errCode == TXLiteAVCode.ERR_ROOM_ENTER_FAIL) {
activity.exitRoom();
}
}
}
}
@Override
protected void onPermissionGranted() {
initView();
}
@Override
protected void onDestroy() {
super.onDestroy();
exitRoom();
}
}
|
9243ed59751238456385d6b54d9d1099a47fd77a | 15,424 | java | Java | library/core/src/main/java/com/google/android/exoplayer2/source/ProgressiveMediaSource.java | harismexis/ExoPlayer | 8430965723ab9afe511ad7f507f535076fa7f24d | [
"Apache-2.0"
] | 19,920 | 2015-01-02T16:05:01.000Z | 2022-03-31T16:18:05.000Z | library/core/src/main/java/com/google/android/exoplayer2/source/ProgressiveMediaSource.java | harismexis/ExoPlayer | 8430965723ab9afe511ad7f507f535076fa7f24d | [
"Apache-2.0"
] | 9,682 | 2015-01-02T17:31:39.000Z | 2022-03-31T17:12:41.000Z | library/core/src/main/java/com/google/android/exoplayer2/source/ProgressiveMediaSource.java | harismexis/ExoPlayer | 8430965723ab9afe511ad7f507f535076fa7f24d | [
"Apache-2.0"
] | 6,627 | 2015-01-01T12:47:35.000Z | 2022-03-31T16:18:09.000Z | 39.548718 | 100 | 0.729383 | 1,002,828 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import android.net.Uri;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.drm.DefaultDrmSessionManagerProvider;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.DrmSessionManagerProvider;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.upstream.Allocator;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultLoadErrorHandlingPolicy;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.upstream.LoadErrorHandlingPolicy;
import com.google.android.exoplayer2.upstream.TransferListener;
/**
* Provides one period that loads data from a {@link Uri} and extracted using an {@link Extractor}.
*
* <p>If the possible input stream container formats are known, pass a factory that instantiates
* extractors for them to the constructor. Otherwise, pass a {@link DefaultExtractorsFactory} to use
* the default extractors. When reading a new stream, the first {@link Extractor} in the array of
* extractors created by the factory that returns {@code true} from {@link Extractor#sniff} will be
* used to extract samples from the input stream.
*
* <p>Note that the built-in extractor for FLV streams does not support seeking.
*/
public final class ProgressiveMediaSource extends BaseMediaSource
implements ProgressiveMediaPeriod.Listener {
/** Factory for {@link ProgressiveMediaSource}s. */
public static final class Factory implements MediaSourceFactory {
private final DataSource.Factory dataSourceFactory;
private ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory;
private boolean usingCustomDrmSessionManagerProvider;
private DrmSessionManagerProvider drmSessionManagerProvider;
private LoadErrorHandlingPolicy loadErrorHandlingPolicy;
private int continueLoadingCheckIntervalBytes;
@Nullable private String customCacheKey;
@Nullable private Object tag;
/**
* Creates a new factory for {@link ProgressiveMediaSource}s, using the extractors provided by
* {@link DefaultExtractorsFactory}.
*
* @param dataSourceFactory A factory for {@link DataSource}s to read the media.
*/
public Factory(DataSource.Factory dataSourceFactory) {
this(dataSourceFactory, new DefaultExtractorsFactory());
}
/**
* Equivalent to {@link #Factory(DataSource.Factory, ProgressiveMediaExtractor.Factory) new
* Factory(dataSourceFactory, () -> new BundledExtractorsAdapter(extractorsFactory)}.
*/
public Factory(DataSource.Factory dataSourceFactory, ExtractorsFactory extractorsFactory) {
this(dataSourceFactory, () -> new BundledExtractorsAdapter(extractorsFactory));
}
/**
* Creates a new factory for {@link ProgressiveMediaSource}s.
*
* @param dataSourceFactory A factory for {@link DataSource}s to read the media.
* @param progressiveMediaExtractorFactory A factory for the {@link ProgressiveMediaExtractor}
* to extract media from its container.
*/
public Factory(
DataSource.Factory dataSourceFactory,
ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory) {
this.dataSourceFactory = dataSourceFactory;
this.progressiveMediaExtractorFactory = progressiveMediaExtractorFactory;
drmSessionManagerProvider = new DefaultDrmSessionManagerProvider();
loadErrorHandlingPolicy = new DefaultLoadErrorHandlingPolicy();
continueLoadingCheckIntervalBytes = DEFAULT_LOADING_CHECK_INTERVAL_BYTES;
}
/**
* @deprecated Pass the {@link ExtractorsFactory} via {@link #Factory(DataSource.Factory,
* ExtractorsFactory)}. This is necessary so that proguard can treat the default extractors
* factory as unused.
*/
@Deprecated
public Factory setExtractorsFactory(@Nullable ExtractorsFactory extractorsFactory) {
this.progressiveMediaExtractorFactory =
() ->
new BundledExtractorsAdapter(
extractorsFactory != null ? extractorsFactory : new DefaultExtractorsFactory());
return this;
}
/**
* @deprecated Use {@link MediaItem.Builder#setCustomCacheKey(String)} and {@link
* #createMediaSource(MediaItem)} instead.
*/
@Deprecated
public Factory setCustomCacheKey(@Nullable String customCacheKey) {
this.customCacheKey = customCacheKey;
return this;
}
/**
* @deprecated Use {@link MediaItem.Builder#setTag(Object)} and {@link
* #createMediaSource(MediaItem)} instead.
*/
@Deprecated
public Factory setTag(@Nullable Object tag) {
this.tag = tag;
return this;
}
/**
* Sets the {@link LoadErrorHandlingPolicy}. The default value is created by calling {@link
* DefaultLoadErrorHandlingPolicy#DefaultLoadErrorHandlingPolicy()}.
*
* @param loadErrorHandlingPolicy A {@link LoadErrorHandlingPolicy}.
* @return This factory, for convenience.
*/
public Factory setLoadErrorHandlingPolicy(
@Nullable LoadErrorHandlingPolicy loadErrorHandlingPolicy) {
this.loadErrorHandlingPolicy =
loadErrorHandlingPolicy != null
? loadErrorHandlingPolicy
: new DefaultLoadErrorHandlingPolicy();
return this;
}
/**
* Sets the number of bytes that should be loaded between each invocation of {@link
* MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}. The default value is
* {@link #DEFAULT_LOADING_CHECK_INTERVAL_BYTES}.
*
* @param continueLoadingCheckIntervalBytes The number of bytes that should be loaded between
* each invocation of {@link
* MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}.
* @return This factory, for convenience.
*/
public Factory setContinueLoadingCheckIntervalBytes(int continueLoadingCheckIntervalBytes) {
this.continueLoadingCheckIntervalBytes = continueLoadingCheckIntervalBytes;
return this;
}
@Override
public Factory setDrmSessionManagerProvider(
@Nullable DrmSessionManagerProvider drmSessionManagerProvider) {
if (drmSessionManagerProvider != null) {
this.drmSessionManagerProvider = drmSessionManagerProvider;
this.usingCustomDrmSessionManagerProvider = true;
} else {
this.drmSessionManagerProvider = new DefaultDrmSessionManagerProvider();
this.usingCustomDrmSessionManagerProvider = false;
}
return this;
}
public Factory setDrmSessionManager(@Nullable DrmSessionManager drmSessionManager) {
if (drmSessionManager == null) {
setDrmSessionManagerProvider(null);
} else {
setDrmSessionManagerProvider(unusedMediaItem -> drmSessionManager);
}
return this;
}
@Override
public Factory setDrmHttpDataSourceFactory(
@Nullable HttpDataSource.Factory drmHttpDataSourceFactory) {
if (!usingCustomDrmSessionManagerProvider) {
((DefaultDrmSessionManagerProvider) drmSessionManagerProvider)
.setDrmHttpDataSourceFactory(drmHttpDataSourceFactory);
}
return this;
}
@Override
public Factory setDrmUserAgent(@Nullable String userAgent) {
if (!usingCustomDrmSessionManagerProvider) {
((DefaultDrmSessionManagerProvider) drmSessionManagerProvider).setDrmUserAgent(userAgent);
}
return this;
}
/** @deprecated Use {@link #createMediaSource(MediaItem)} instead. */
@SuppressWarnings("deprecation")
@Deprecated
@Override
public ProgressiveMediaSource createMediaSource(Uri uri) {
return createMediaSource(new MediaItem.Builder().setUri(uri).build());
}
/**
* Returns a new {@link ProgressiveMediaSource} using the current parameters.
*
* @param mediaItem The {@link MediaItem}.
* @return The new {@link ProgressiveMediaSource}.
* @throws NullPointerException if {@link MediaItem#playbackProperties} is {@code null}.
*/
@Override
public ProgressiveMediaSource createMediaSource(MediaItem mediaItem) {
checkNotNull(mediaItem.playbackProperties);
boolean needsTag = mediaItem.playbackProperties.tag == null && tag != null;
boolean needsCustomCacheKey =
mediaItem.playbackProperties.customCacheKey == null && customCacheKey != null;
if (needsTag && needsCustomCacheKey) {
mediaItem = mediaItem.buildUpon().setTag(tag).setCustomCacheKey(customCacheKey).build();
} else if (needsTag) {
mediaItem = mediaItem.buildUpon().setTag(tag).build();
} else if (needsCustomCacheKey) {
mediaItem = mediaItem.buildUpon().setCustomCacheKey(customCacheKey).build();
}
return new ProgressiveMediaSource(
mediaItem,
dataSourceFactory,
progressiveMediaExtractorFactory,
drmSessionManagerProvider.get(mediaItem),
loadErrorHandlingPolicy,
continueLoadingCheckIntervalBytes);
}
@Override
public int[] getSupportedTypes() {
return new int[] {C.TYPE_OTHER};
}
}
/**
* The default number of bytes that should be loaded between each each invocation of {@link
* MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}.
*/
public static final int DEFAULT_LOADING_CHECK_INTERVAL_BYTES = 1024 * 1024;
private final MediaItem mediaItem;
private final MediaItem.PlaybackProperties playbackProperties;
private final DataSource.Factory dataSourceFactory;
private final ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory;
private final DrmSessionManager drmSessionManager;
private final LoadErrorHandlingPolicy loadableLoadErrorHandlingPolicy;
private final int continueLoadingCheckIntervalBytes;
private boolean timelineIsPlaceholder;
private long timelineDurationUs;
private boolean timelineIsSeekable;
private boolean timelineIsLive;
@Nullable private TransferListener transferListener;
private ProgressiveMediaSource(
MediaItem mediaItem,
DataSource.Factory dataSourceFactory,
ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory,
DrmSessionManager drmSessionManager,
LoadErrorHandlingPolicy loadableLoadErrorHandlingPolicy,
int continueLoadingCheckIntervalBytes) {
this.playbackProperties = checkNotNull(mediaItem.playbackProperties);
this.mediaItem = mediaItem;
this.dataSourceFactory = dataSourceFactory;
this.progressiveMediaExtractorFactory = progressiveMediaExtractorFactory;
this.drmSessionManager = drmSessionManager;
this.loadableLoadErrorHandlingPolicy = loadableLoadErrorHandlingPolicy;
this.continueLoadingCheckIntervalBytes = continueLoadingCheckIntervalBytes;
this.timelineIsPlaceholder = true;
this.timelineDurationUs = C.TIME_UNSET;
}
@Override
public MediaItem getMediaItem() {
return mediaItem;
}
@Override
protected void prepareSourceInternal(@Nullable TransferListener mediaTransferListener) {
transferListener = mediaTransferListener;
drmSessionManager.prepare();
notifySourceInfoRefreshed();
}
@Override
public void maybeThrowSourceInfoRefreshError() {
// Do nothing.
}
@Override
public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator, long startPositionUs) {
DataSource dataSource = dataSourceFactory.createDataSource();
if (transferListener != null) {
dataSource.addTransferListener(transferListener);
}
return new ProgressiveMediaPeriod(
playbackProperties.uri,
dataSource,
progressiveMediaExtractorFactory.createProgressiveMediaExtractor(),
drmSessionManager,
createDrmEventDispatcher(id),
loadableLoadErrorHandlingPolicy,
createEventDispatcher(id),
this,
allocator,
playbackProperties.customCacheKey,
continueLoadingCheckIntervalBytes);
}
@Override
public void releasePeriod(MediaPeriod mediaPeriod) {
((ProgressiveMediaPeriod) mediaPeriod).release();
}
@Override
protected void releaseSourceInternal() {
drmSessionManager.release();
}
// ProgressiveMediaPeriod.Listener implementation.
@Override
public void onSourceInfoRefreshed(long durationUs, boolean isSeekable, boolean isLive) {
// If we already have the duration from a previous source info refresh, use it.
durationUs = durationUs == C.TIME_UNSET ? timelineDurationUs : durationUs;
if (!timelineIsPlaceholder
&& timelineDurationUs == durationUs
&& timelineIsSeekable == isSeekable
&& timelineIsLive == isLive) {
// Suppress no-op source info changes.
return;
}
timelineDurationUs = durationUs;
timelineIsSeekable = isSeekable;
timelineIsLive = isLive;
timelineIsPlaceholder = false;
notifySourceInfoRefreshed();
}
// Internal methods.
private void notifySourceInfoRefreshed() {
// TODO: Split up isDynamic into multiple fields to indicate which values may change. Then
// indicate that the duration may change until it's known. See [internal: b/69703223].
Timeline timeline =
new SinglePeriodTimeline(
timelineDurationUs,
timelineIsSeekable,
/* isDynamic= */ false,
/* useLiveConfiguration= */ timelineIsLive,
/* manifest= */ null,
mediaItem);
if (timelineIsPlaceholder) {
// TODO: Actually prepare the extractors during preparation so that we don't need a
// placeholder. See https://github.com/google/ExoPlayer/issues/4727.
timeline =
new ForwardingTimeline(timeline) {
@Override
public Window getWindow(
int windowIndex, Window window, long defaultPositionProjectionUs) {
super.getWindow(windowIndex, window, defaultPositionProjectionUs);
window.isPlaceholder = true;
return window;
}
@Override
public Period getPeriod(int periodIndex, Period period, boolean setIds) {
super.getPeriod(periodIndex, period, setIds);
period.isPlaceholder = true;
return period;
}
};
}
refreshSourceInfo(timeline);
}
}
|
9243ee1b44fcb9de04db64d613fd2c038ac27c09 | 1,429 | java | Java | Epidemic-illness/src/main/java/zstu/epidemic/illness/domain/EpidemicDrugIllness.java | Iwannnn/Epidemic | c97e679848e8eacccf9f5c1e616ab8c98a2636ad | [
"MIT"
] | null | null | null | Epidemic-illness/src/main/java/zstu/epidemic/illness/domain/EpidemicDrugIllness.java | Iwannnn/Epidemic | c97e679848e8eacccf9f5c1e616ab8c98a2636ad | [
"MIT"
] | null | null | null | Epidemic-illness/src/main/java/zstu/epidemic/illness/domain/EpidemicDrugIllness.java | Iwannnn/Epidemic | c97e679848e8eacccf9f5c1e616ab8c98a2636ad | [
"MIT"
] | null | null | null | 21.651515 | 71 | 0.638209 | 1,002,829 | package zstu.epidemic.illness.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import zstu.epidemic.common.annotation.Excel;
import zstu.epidemic.common.core.domain.BaseEntity;
/**
* 疾病药品对象 epidemic_drug_illness
*
* @author iwan
* @date 2022-05-04
*/
public class EpidemicDrugIllness extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 药品疾病id */
private Long drugIllnessId;
/** 疾病id */
@Excel(name = "疾病id")
private Long diseaseId;
/** 药物id */
@Excel(name = "药物id")
private Long drugId;
public void setDrugIllnessId(Long drugIllnessId)
{
this.drugIllnessId = drugIllnessId;
}
public Long getDrugIllnessId()
{
return drugIllnessId;
}
public void setDiseaseId(Long diseaseId)
{
this.diseaseId = diseaseId;
}
public Long getDiseaseId()
{
return diseaseId;
}
public void setDrugId(Long drugId)
{
this.drugId = drugId;
}
public Long getDrugId()
{
return drugId;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("drugIllnessId", getDrugIllnessId())
.append("diseaseId", getDiseaseId())
.append("drugId", getDrugId())
.toString();
}
}
|
9243ef989291b78fd77e68eedf5bb38315e282df | 2,266 | java | Java | littleims-hss/src/main/java/org/cipango/ims/hss/model/Scscf.java | ahoka/littleims | 8a388f7c068ccaf3833281f47b37ef3eb9763186 | [
"Apache-1.1"
] | 1 | 2016-02-02T15:38:17.000Z | 2016-02-02T15:38:17.000Z | littleims-hss/src/main/java/org/cipango/ims/hss/model/Scscf.java | AmeniCA/littleims | 8a388f7c068ccaf3833281f47b37ef3eb9763186 | [
"Apache-1.1"
] | null | null | null | littleims-hss/src/main/java/org/cipango/ims/hss/model/Scscf.java | AmeniCA/littleims | 8a388f7c068ccaf3833281f47b37ef3eb9763186 | [
"Apache-1.1"
] | null | null | null | 20.414414 | 75 | 0.653133 | 1,002,830 | // ========================================================================
// Copyright 2008-2009 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.ims.hss.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Scscf
{
@Id @GeneratedValue
private Long _id;
@Column(unique=true)
private String _name;
@Column (unique=true)
private String _uri;
@Column (unique=true)
private String _diameterHost;
@OneToMany(mappedBy = "_scscf")
private Set<Subscription> _subscriptions = new HashSet<Subscription>();
@OneToMany(mappedBy = "_scscf")
private Set<PSI> _psis = new HashSet<PSI>();
public Set<PSI> getPsis()
{
return _psis;
}
public void setPsis(Set<PSI> psis)
{
_psis = psis;
}
public Long getId()
{
return _id;
}
public void setId(Long id)
{
_id = id;
}
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
public String getUri()
{
return _uri;
}
public void setUri(String uri)
{
_uri = uri;
}
public String toString()
{
return _name;
}
public Set<Subscription> getSubscriptions()
{
return _subscriptions;
}
public void setSubscriptions(Set<Subscription> subscriptions)
{
_subscriptions = subscriptions;
}
public String getDiameterHost()
{
return _diameterHost;
}
public void setDiameterHost(String diameterHost)
{
_diameterHost = diameterHost;
}
}
|
9243efe42acede168637a729db5c1bc698c659ac | 492 | java | Java | vcell-client/src/test/java/org/vcell/client/logicalwindow/TestJOptionDialog.java | JoshTDN03/vcell | 41bfdfa81c6f6e6b20876152b3bb6e9509923fc7 | [
"MIT"
] | 38 | 2017-09-08T08:51:43.000Z | 2022-02-08T02:25:19.000Z | vcell-client/src/test/java/org/vcell/client/logicalwindow/TestJOptionDialog.java | nikitamahoviya/vcell | 5603702ec134b2df6b1b0554718da38e83fb7b53 | [
"MIT"
] | 79 | 2018-04-01T16:37:58.000Z | 2022-03-30T18:10:23.000Z | vcell-client/src/test/java/org/vcell/client/logicalwindow/TestJOptionDialog.java | nikitamahoviya/vcell | 5603702ec134b2df6b1b0554718da38e83fb7b53 | [
"MIT"
] | 17 | 2017-09-12T18:21:56.000Z | 2022-01-04T19:49:35.000Z | 21.391304 | 89 | 0.711382 | 1,002,831 | package org.vcell.client.logicalwindow;
import javax.swing.JOptionPane;
public class TestJOptionDialog extends LWOptionPaneDialog{
/**
*
*/
private static final long serialVersionUID = 1L;
TestJOptionDialog(LWContainerHandle parent, String title,JOptionPane pane) {
//super(parent, "Yes No", new JOptionPane("Good?", JOptionPane.YES_NO_CANCEL_OPTION));
super(parent, title, pane);
}
@Override
public String menuDescription() {
return null;
}
}
|
9243f1493c57ed3ba55b73ed684ca3d1471200d3 | 1,628 | java | Java | gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/transactional/common/TFSMConstants.java | rostam/gradoop | 12f5487b48332e90bb79047f8614a4c495a5d0b4 | [
"Apache-2.0"
] | 2 | 2018-12-24T14:16:05.000Z | 2019-01-09T12:20:27.000Z | gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/transactional/common/TFSMConstants.java | rostam/gradoop | 12f5487b48332e90bb79047f8614a4c495a5d0b4 | [
"Apache-2.0"
] | null | null | null | gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/transactional/common/TFSMConstants.java | rostam/gradoop | 12f5487b48332e90bb79047f8614a4c495a5d0b4 | [
"Apache-2.0"
] | null | null | null | 29.071429 | 75 | 0.714988 | 1,002,832 | /*
* Copyright © 2014 - 2020 Leipzig University (Database Research Group)
*
* 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.gradoop.flink.algorithms.fsm.transactional.common;
/**
* Collection of broadcast dataset names used for frequent subgraph mining.
*/
public class TFSMConstants {
/**
* Cache counter name for the total number of graphs.
*/
public static final String GRAPH_COUNT = "graphCount";
/**
* frequent vertex labels
*/
public static final String FREQUENT_VERTEX_LABELS = "fvl";
/**
* frequent edge labels
*/
public static final String FREQUENT_EDGE_LABELS = "fel";
/**
* set of frequent patterns
*/
public static final String FREQUENT_PATTERNS = "fp";
/**
* Graph head label of frequent subgraphs
*/
public static final String FREQUENT_PATTERN_LABEL = "FrequentPattern";
/**
* Property key to store a frequent subgraphs's frequency.
*/
public static final String SUPPORT_KEY = "frequency";
/**
* Property key to store the canonical label.
*/
public static final String CANONICAL_LABEL_KEY = "canonicalLabel";
}
|
9243f17a526272eb9fd38222c61f449ebecaef4b | 5,296 | java | Java | ui/src/main/java/ucar/nc2/ui/grid/GridTable.java | joansmith2/thredds | ac321ce2a15f020f0cdef1ff9a2cf82261d8297c | [
"NetCDF"
] | 1 | 2018-04-24T13:53:46.000Z | 2018-04-24T13:53:46.000Z | ui/src/main/java/ucar/nc2/ui/grid/GridTable.java | joansmith/thredds | 3e10f07b4d2f6b0f658e86327b8d4a5872fe1aa8 | [
"NetCDF"
] | 16 | 2016-04-11T06:42:41.000Z | 2019-05-03T04:04:50.000Z | ui/src/main/java/ucar/nc2/ui/grid/GridTable.java | joansmith/thredds | 3e10f07b4d2f6b0f658e86327b8d4a5872fe1aa8 | [
"NetCDF"
] | 1 | 2019-07-22T19:57:26.000Z | 2019-07-22T19:57:26.000Z | 35.306667 | 100 | 0.672205 | 1,002,833 | /*
* Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata
*
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package ucar.nc2.ui.grid;
import ucar.nc2.Dimension;
import ucar.nc2.dt.GridDatatype;
import ucar.nc2.ui.event.ActionSourceListener;
import ucar.nc2.ui.event.ActionValueEvent;
import ucar.nc2.ui.table.JTableSorted;
import ucar.nc2.ui.table.TableRowAbstract;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.util.ArrayList;
import java.util.Formatter;
/**
* Put the fields of a GridDatatype dataset in a JTable.
* Uses ActionSourceListener for events.
*
* @see ucar.nc2.ui.event.ActionSourceListener
*
* @author caron
*/
public class GridTable {
private JTableSorted table;
private ArrayList<Row> list = null;
private ActionSourceListener actionSource;
private boolean eventOK = true;
private boolean debug = false;
public GridTable(String actionName) {
// the main delegate
table = new JTableSorted(colName, list);
// event management
actionSource = new ActionSourceListener(actionName) {
public void actionPerformed( ActionValueEvent e) {
if (list == null) return;
String want = e.getValue().toString();
int count = 0;
for (Row row : list) {
if (want.equals(row.gg.getFullName())) {
eventOK = false;
table.setSelected(count);
eventOK = true;
break;
}
count++;
}
}
};
// send event when selected row changes
table.addListSelectionListener( new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (eventOK && !e.getValueIsAdjusting()) {
// new variable is selected
Row row = (Row) table.getSelected();
if (row != null) {
if (debug) System.out.println(" GridTable new gg = "+ row.gg.getFullName());
actionSource.fireActionValueEvent(ActionSourceListener.SELECTED, row.gg.getFullName());
}
}
}
});
}
public void clear() {
list.clear();
table.setList(list);
}
public void setDataset(java.util.List<GridDatatype> fields) {
if (fields == null) return;
list = new ArrayList<Row>(fields.size());
for (GridDatatype gg : fields)
list.add(new Row(gg));
table.setList(list);
}
public JPanel getPanel() { return table; }
/* better way to do event management */
public ActionSourceListener getActionSourceListener() { return actionSource; }
/// inner classes
private static String[] colName = {"Name", "Dimensions", "Units", "Long Name"};
private static class Row extends TableRowAbstract {
GridDatatype gg;
String dims;
Row( GridDatatype gg) {
this.gg = gg;
Formatter f = new Formatter();
for (Dimension dim : gg.getDimensions())
f.format("%s ", dim.getShortName());
dims = f.toString();
}
public Object getUserObject() { return gg; }
public Object getValueAt( int col) {
switch (col) {
case 0: return gg.getFullName();
case 1: return dims;
case 2: return gg.getUnitsString();
case 3: return gg.getDescription();
default: return "error";
}
}
}
}
|
9243f2c15652689042e47e0bbc4da22f865be849 | 1,950 | java | Java | src/main/java/com/bajagym/model/Serie.java | JavierGB99/BajaGym | 1338f70fd5c38378cb25a840bd15cb4cb6dfc0b7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/bajagym/model/Serie.java | JavierGB99/BajaGym | 1338f70fd5c38378cb25a840bd15cb4cb6dfc0b7 | [
"Apache-2.0"
] | 2 | 2022-02-21T17:15:18.000Z | 2022-02-22T04:31:41.000Z | src/main/java/com/bajagym/model/Serie.java | JavierGB99/BajaGym | 1338f70fd5c38378cb25a840bd15cb4cb6dfc0b7 | [
"Apache-2.0"
] | 1 | 2022-01-27T10:17:17.000Z | 2022-01-27T10:17:17.000Z | 24.074074 | 90 | 0.667692 | 1,002,834 | package com.bajagym.model;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.io.Serializable;
import java.text.SimpleDateFormat;
@Entity
@Table(name = "serie")
public class Serie {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idSerie;
@Column(name = "repeticiones", nullable = false)
private int repeticiones;
@Column(name = "descanso", nullable = false)
private int descanso;
@Fetch(FetchMode.JOIN)
@ManyToOne(fetch = FetchType.LAZY, optional = false, targetEntity = Rutina.class)
@JoinColumn(name = "rutina_id", referencedColumnName = "id_externo", nullable = false)
private Rutina rutina_id;
@Fetch(FetchMode.JOIN)
@OneToOne(fetch = FetchType.EAGER, optional = false, targetEntity = Ejercicio.class)
@JoinColumn(name = "ejercicio_id", referencedColumnName = "id", nullable = false)
private Ejercicio ejercicio;
public Long getIdSerie() {
return idSerie;
}
public void setIdSerie(Long idSerie) {
this.idSerie = idSerie;
}
public int getRepeticiones() {
return repeticiones;
}
public void setRepeticiones(int repeticiones) {
this.repeticiones = repeticiones;
}
public int getDescanso() {
return descanso;
}
public void setDescanso(int descanso) {
this.descanso = descanso;
}
public Rutina getIdRutina() {
return rutina_id;
}
public void setIdRutina(Rutina idRutina) {
rutina_id=idRutina;
}
public Ejercicio getEjercicio() {
return ejercicio;
}
public void setEjercicio(Ejercicio ejercicio) {
this.ejercicio = ejercicio;
}
@Override
public String toString(){
return "Repeticiones: "+getRepeticiones()+", Descanso:"+getDescanso();
}
}
|
9243f4c4e6ea43c54dcd77fdfc0cdcd006c869ec | 1,547 | java | Java | project-set/components/cli-utils/src/main/java/org/openrepose/cli/command/datastore/distributed/CacheKeyEncoder.java | sharwell/repose | 5d169ccad00ec4518d01379990d4e44e4e55e90e | [
"Apache-2.0"
] | null | null | null | project-set/components/cli-utils/src/main/java/org/openrepose/cli/command/datastore/distributed/CacheKeyEncoder.java | sharwell/repose | 5d169ccad00ec4518d01379990d4e44e4e55e90e | [
"Apache-2.0"
] | null | null | null | project-set/components/cli-utils/src/main/java/org/openrepose/cli/command/datastore/distributed/CacheKeyEncoder.java | sharwell/repose | 5d169ccad00ec4518d01379990d4e44e4e55e90e | [
"Apache-2.0"
] | null | null | null | 35.159091 | 142 | 0.737557 | 1,002,835 | package org.openrepose.cli.command.datastore.distributed;
import com.rackspace.papi.commons.util.io.charset.CharacterSets;
import com.rackspace.papi.service.datastore.encoding.UUIDEncodingProvider;
import com.rackspace.papi.service.datastore.hash.MD5MessageDigestFactory;
import org.openrepose.cli.command.AbstractCommand;
import org.openrepose.cli.command.results.*;
import java.security.NoSuchAlgorithmException;
/**
*
* @author zinic
*/
public class CacheKeyEncoder extends AbstractCommand {
@Override
public String getCommandDescription() {
return "Encodes a cache key into a representation that the distributed datastore can address.";
}
@Override
public String getCommandToken() {
return "encode-key";
}
@Override
public CommandResult perform(String[] arguments) {
if (arguments.length != 1) {
return new InvalidArguments("The cache key encoder expects one, string argument.");
}
try {
final byte[] hashBytes = MD5MessageDigestFactory.getInstance().newMessageDigest().digest(arguments[0].getBytes(CharacterSets.UTF_8));
final String encodedCacheKey = UUIDEncodingProvider.getInstance().encode(hashBytes);
return new MessageResult(encodedCacheKey);
} catch (NoSuchAlgorithmException noSuchAlgorithmException) {
return new CommandFailure(StatusCodes.SYSTEM_PRECONDITION_FAILURE.getStatusCode(),
"Your instance of the Java Runtime Environment does not support the MD5 hash algorithm.");
}
}
}
|
9243f5024a8b504bf4687579f607e6a522aa9729 | 287 | java | Java | src/main/java/com/yangyang/service/ClasssNoticeService.java | wzy6432/ClassWebsite | 47a8770926db2613ad6765e913a8c4b1bf1b4e97 | [
"MIT"
] | 3 | 2021-12-27T14:52:35.000Z | 2021-12-28T12:25:48.000Z | src/main/java/com/yangyang/service/ClasssNoticeService.java | wzy6432/ClassWebsite | 47a8770926db2613ad6765e913a8c4b1bf1b4e97 | [
"MIT"
] | null | null | null | src/main/java/com/yangyang/service/ClasssNoticeService.java | wzy6432/ClassWebsite | 47a8770926db2613ad6765e913a8c4b1bf1b4e97 | [
"MIT"
] | 1 | 2021-12-27T04:47:46.000Z | 2021-12-27T04:47:46.000Z | 35.875 | 68 | 0.815331 | 1,002,836 | package com.yangyang.service;
import com.yangyang.dao.ClassNoticeDao;
import com.yangyang.pojo.ClassNoticeDo;
public interface ClasssNoticeService {
public ClassNoticeDo queryClassNoticeByClassId(String classId);
public int sendClassNotice(ClassNoticeDo ClassNoticeDo);
}
|
9243f64747abaeeb87f894091d36ec2614113394 | 2,003 | java | Java | app/src/main/java/com/decSports/measureme/MainScreenActivity.java | tylernickr/MeasureMe | 24611adc4731fde657042849224304d0f7a26aa9 | [
"MIT"
] | 1 | 2018-10-10T01:15:34.000Z | 2018-10-10T01:15:34.000Z | app/src/main/java/com/decSports/measureme/MainScreenActivity.java | tylernickr/MeasureMe | 24611adc4731fde657042849224304d0f7a26aa9 | [
"MIT"
] | null | null | null | app/src/main/java/com/decSports/measureme/MainScreenActivity.java | tylernickr/MeasureMe | 24611adc4731fde657042849224304d0f7a26aa9 | [
"MIT"
] | null | null | null | 28.614286 | 89 | 0.759361 | 1,002,837 | package com.decSports.measureme;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class MainScreenActivity extends Activity {
private static final String TAG = "MainScreenActivity";
private static final int REQUEST_PHOTO = 1;
private Button mStartButton;
private Button mHelpButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainscreen);
mStartButton = (Button)findViewById(R.id.start_button);
mStartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainScreenActivity.this, MeasureCameraActivity.class);
startActivity(i);
}
});
mHelpButton = (Button)findViewById(R.id.help_button);
mHelpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(MainScreenActivity.this, R.string.not_yet, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.preview, menu);
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_PHOTO) {
String filename = data.getStringExtra(MeasureCameraFragment.EXTRA_PHOTO_FILENAME);
if (filename != null) {
Log.i(TAG, "filename: " + filename);
}
}
}
static final int REQUEST_IMAGE_CAPTURE = 1;
static boolean IMAGE_TAKEN = false;
}
|
9243f69cf4ffab7157009d6c34c7bfa54466c0e6 | 3,330 | java | Java | src/cc/mallet/classify/MostFrequentClassAssignmentTrainer.java | michaelslater/Mallet | 79614b8b61bac87cef39cbeb29f4f00f7d61bb9c | [
"Apache-2.0"
] | 836 | 2015-01-02T12:13:19.000Z | 2022-03-30T23:30:48.000Z | src/cc/mallet/classify/MostFrequentClassAssignmentTrainer.java | michaelslater/Mallet | 79614b8b61bac87cef39cbeb29f4f00f7d61bb9c | [
"Apache-2.0"
] | 142 | 2015-01-08T16:40:27.000Z | 2022-03-04T23:01:10.000Z | src/cc/mallet/classify/MostFrequentClassAssignmentTrainer.java | michaelslater/Mallet | 79614b8b61bac87cef39cbeb29f4f00f7d61bb9c | [
"Apache-2.0"
] | 365 | 2015-01-07T22:20:12.000Z | 2022-03-26T19:05:08.000Z | 35.849462 | 127 | 0.739352 | 1,002,838 | /* This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package cc.mallet.classify;
import cc.mallet.classify.ClassifierTrainer;
import cc.mallet.pipe.Pipe;
import cc.mallet.types.Alphabet;
import cc.mallet.types.AlphabetCarrying;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import cc.mallet.types.Label;
/**
* A Classifier Trainer to be used with MostFrequentClassifier.
*
* @see MostFrequentClassifier
*
* @author Martin Wunderlich <a href="mailto:[email protected]">[email protected]</a>
*/
public class MostFrequentClassAssignmentTrainer extends ClassifierTrainer<MostFrequentClassifier> implements AlphabetCarrying {
MostFrequentClassifier classifier = null;
Pipe instancePipe; // Needed to construct a new classifier
Alphabet dataAlphabet; // Extracted from InstanceList. Must be the same for all calls to incrementalTrain()
Alphabet targetAlphabet; // Extracted from InstanceList. Must be the same for all calls to incrementalTrain
@Override
public MostFrequentClassifier getClassifier() {
return this.classifier;
}
/**
* Create a MostFrequent classifier from a set of training data.
*
* @param trainingList The InstanceList to be used to train the classifier.
* @return The MostFrequent classifier as trained on the trainingList
*/
@Override
public MostFrequentClassifier train(InstanceList trainingSet) {
// Initialize or check the instancePipe
if (trainingSet != null) {
if (this.instancePipe == null)
this.instancePipe = trainingSet.getPipe();
else if (this.instancePipe != trainingSet.getPipe())
// Make sure that this pipes match. Is this really necessary??
// I don't think so, but it could be confusing to have each returned classifier have a different pipe? -akm 1/08
throw new IllegalArgumentException ("Training set pipe does not match that of NaiveBayesTrainer.");
this.dataAlphabet = this.instancePipe.getDataAlphabet();
this.targetAlphabet = this.instancePipe.getTargetAlphabet();
}
this.classifier = new MostFrequentClassifier(this.instancePipe);
// Init alphabets and extract label from instance
for(Instance instance : trainingSet) {
if (dataAlphabet == null) {
this.dataAlphabet = instance.getDataAlphabet();
this.targetAlphabet = instance.getTargetAlphabet();
} else if (!Alphabet.alphabetsMatch(instance, this))
// Make sure the alphabets match
throw new IllegalArgumentException ("Training set alphabets do not match those of NaiveBayesTrainer.");
Label label = (Label) instance.getTarget();
this.classifier.addTargetLabel(label);
}
return this.classifier;
}
// AlphabetCarrying interface
public boolean alphabetsMatch(AlphabetCarrying object) {
return Alphabet.alphabetsMatch (this, object);
}
@Override
public Alphabet getAlphabet() {
return dataAlphabet;
}
@Override
public Alphabet[] getAlphabets() {
return new Alphabet[] { dataAlphabet, targetAlphabet };
}
}
|
9243f722eae9c2b507c9dca524d171d6eb19a817 | 3,605 | java | Java | presto-main/src/main/java/com/facebook/presto/metadata/CatalogManager.java | sameeragarwal/presto | 25f921fb81be4d23a68e52634ed763568188df05 | [
"Apache-2.0"
] | 58 | 2015-01-14T09:41:49.000Z | 2022-02-18T08:15:29.000Z | presto-main/src/main/java/com/facebook/presto/metadata/CatalogManager.java | josephmisiti/presto | 69d42f2fbf14cc6ee99d7479535a844bc99ac5c5 | [
"Apache-2.0"
] | 2 | 2016-06-21T17:02:32.000Z | 2022-01-21T23:54:47.000Z | presto-main/src/main/java/com/facebook/presto/metadata/CatalogManager.java | josephmisiti/presto | 69d42f2fbf14cc6ee99d7479535a844bc99ac5c5 | [
"Apache-2.0"
] | 21 | 2015-01-14T09:41:56.000Z | 2021-07-05T03:42:45.000Z | 34.009434 | 125 | 0.701803 | 1,002,839 | /*
* 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.facebook.presto.metadata;
import com.facebook.presto.connector.ConnectorManager;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import io.airlift.log.Logger;
import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Maps.fromProperties;
public class CatalogManager
{
private static final Logger log = Logger.get(CatalogManager.class);
private final ConnectorManager connectorManager;
private final File catalogConfigurationDir;
private final AtomicBoolean catalogsLoaded = new AtomicBoolean();
@Inject
public CatalogManager(ConnectorManager connectorManager, CatalogManagerConfig config)
{
this(connectorManager, config.getCatalogConfigurationDir());
}
public CatalogManager(ConnectorManager connectorManager, File catalogConfigurationDir)
{
this.connectorManager = connectorManager;
this.catalogConfigurationDir = catalogConfigurationDir;
}
public void loadCatalogs()
throws Exception
{
if (!catalogsLoaded.compareAndSet(false, true)) {
return;
}
for (File file : listFiles(catalogConfigurationDir)) {
if (file.isFile() && file.getName().endsWith(".properties")) {
loadCatalog(file);
}
}
}
private void loadCatalog(File file)
throws Exception
{
Map<String, String> properties = new HashMap<>(loadProperties(file));
String connectorName = properties.remove("connector.name");
checkState(connectorName != null, "Catalog configuration %s does not contain conector.name", file.getAbsoluteFile());
String catalogName = Files.getNameWithoutExtension(file.getName());
connectorManager.createConnection(catalogName, connectorName, ImmutableMap.copyOf(properties));
log.info("Added catalog %s using connector %s", catalogName, connectorName);
}
private List<File> listFiles(File installedPluginsDir)
{
if (installedPluginsDir != null && installedPluginsDir.isDirectory()) {
File[] files = installedPluginsDir.listFiles();
if (files != null) {
return ImmutableList.copyOf(files);
}
}
return ImmutableList.of();
}
private static Map<String, String> loadProperties(File file)
throws Exception
{
checkNotNull(file, "file is null");
Properties properties = new Properties();
try (FileInputStream in = new FileInputStream(file)) {
properties.load(in);
}
return fromProperties(properties);
}
}
|
9243f7dad64af35dc1b5bd3a01c5617e6cde78b0 | 28,663 | java | Java | output/4c7d06483b354f7c870d612e70bc1b63.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/4c7d06483b354f7c870d612e70bc1b63.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | output/4c7d06483b354f7c870d612e70bc1b63.java | comprakt/comprakt-fuzz-tests | c0082d105d7c54ad31ab4ea461c3b8319358eaaa | [
"Apache-2.0",
"MIT"
] | null | null | null | 37.080207 | 253 | 0.4884 | 1,002,840 | class qnK5zBcPnYA {
}
class fCtdP {
public void[][][][] pIpAFlS_huuQY6 (boolean[] ru7bnETWJ, void[] mVOGekQUk, int CB) throws T25vnp {
return !!-zf.sKlbY9ulqNWA();
;
JpGkZG9n4S2o[] FR13JW = !true.b();
void[] lgE40CjhH = _fegJOK().rofuJdm = -true[ !qBBA0N9aiCj().CiftnJmH()];
avVK5EXu4A4X().H8K_Y6AWEj2();
int[] r = !new void[ true[ !-DpryPZCL.M2QAEe7]].L51zGIKmjG;
return -null.ezP();
return bZmJ65A7uAG().ZQWL0O1bB9K();
if ( kFd6vG8mdTy()[ -null.Y1]) if ( !----new MeUobUvUt[ new QhNuQESsMRkN7u()[ -t7eMcFG2y1TV().agYlu5xaMUihZ]].wML4hhp4JN2) !this[ true[ !new Lr()[ W8.G10sCuiyWpOJF]]];
int[][] h9N1 = this.pzW9vWxJIE8g();
while ( --!531.Jy) {
boolean[] pxfQ7wcIx8pA4t;
}
while ( !false.zkB4GSoP3kD2od) while ( new int[ new boolean[ !false[ ER2SH()[ A5XfI[ !!TLECScie6().wos0Sh]]]].VgmQglh2TQE()].lNaOzhRYwRhWfQ) !-!-( !new ZDVk[ !YyfYx[ !--!!!false.fWC()]][ false.Du24_trQW()]).MP07bj();
int u = -!-new kK().cOG2PbRNnJomT;
;
Nc_pKsK0dTUi[][][] AKym = new ajriI().Q9QGC3_RhLrp();
while ( false[ ( null.x2())[ !true.ATRhGve2vpobOL()]]) ;
void[][][][][] t;
}
public void[] gFqyUJ (int OoRJbXO2iCr) throws cdb {
i4RM xJ = !false[ new boolean[ -749439[ !this[ new AO59wVO()[ !-W.En7ac0VJS7C7n()]]]].kiRBhTq()] = -6904.Z();
int[] lemsQaHCYhfS = --!SXxOx9X.yReym = null[ true.p2];
{
{
EvsjS lREUtSe8svaVi_;
}
YU9Vvbum6vo[] JWzmu7nnrjLl3;
true.HKrgQwcPm();
while ( 4[ !!-3627.mV5()]) ---!!true.Ug9j;
true.RkK2o3ht();
boolean iX5PdNMGm;
int[][] c0n;
int fz;
!new OX7b().H();
while ( false[ !new int[ null.aXfvgShIL3RZNe()].JIDUEJC()]) if ( -!!!!!new eL8XMaTrklmL[ ( -true[ 2[ !!new boolean[ Ekii_8oa().BanCnVr0CR0b7()][ QO9.poIljEHicsvpL()]]]).uX892yjvzis()][ ( !-true.tgld9c)[ !this[ !!( !!pO().L()).kve3zY9Bj]]]) ;
-er().myriQX_TpM();
void QUGTz6W;
boolean[] so;
while ( this.sXvZgxv()) ;
{
void[] qoV4;
}
return;
boolean[] Enw;
}
rOh44Ri[] ZjokPgo3 = -new void[ null.FiK2A76X7jX2][ ---!!--!-true.Zn205YS3J];
A0ClX_pNBRCV CrXfnQcCpbOG;
void qmsJ = !IGCEgFEGRGMwo.rMqle2H() = new boolean[ --this[ !!true.LsFkj()]].LOZFAA7SUl();
CNPx bXboTqyP;
}
public int lm5gbYXwzDy6nJ () throws fx {
y55Fc4.b6Igc();
{
boolean Sl;
void[] Cz;
D5C65_n[][] Hr3X3g;
void[][][] vQ;
while ( !new int[ !!new boolean[ dQ().KFN2()][ nNEKYv3Ip0().j5HJjtWEkVjLb5]].rB11Sxpuk) if ( !-jO().VnW0A16qy) while ( !2282920[ this.nD()]) return;
{
{
while ( true.pTi2TSd2ywe) while ( Ri().GK6hQ) return;
}
}
return;
void[][][][][][][] x2sqhUg;
int[] zicKj8xLe;
}
return;
{
if ( !875868.o) nrU5L9L.Bq6_87sGhayS5();
return;
if ( ( false.uzB6rv)[ -084.rx()]) return;
boolean[] M;
int[][][] PnP_Yc907bX7;
!-!!!--( !false.QtXSG0)[ !false.GgZHn0u78()];
vz[] zO;
JTL iLJ;
boolean[] l_L;
return;
boolean[][][][] y8cK;
;
}
int[] Z2bJhN;
--new MZUWADAJhdqx1().Z0bxW;
void IOrgaNaIM;
int[] OsQbBNBz5ax = !-!!new int[ 3576[ -!!new int[ !OUrjlR()[ new IaAoAM().wCr()]].lF2Cb_()]].Yap2_W1IBgPXZG = false.wUHqUWcZpCY5();
;
laD4KM X2Zyc;
}
public fjfGbik3Rq4V[] vphsmSBRc6gUJP;
public int InK6WXhgjRp () {
return !rOHSbXCs46qE()[ new CnzYnYjx[ null.D20N2c()].cu70l];
false.rWY5XEy_DCZlT;
WxzzC[] w633zlWj = B.K2cevMLNv3r() = !!( -( !-!--!this.aFW0TM())[ !!this.ZR()]).ME;
QOMm[] OQkeuSq = new q0Pgy0hIM[ !!e().r()].LIXlHuGyZDHNs8;
{
return;
---null[ !--this.Y()];
( null.GQhD3v)[ -false.C];
{
if ( !( -false.oBkwtBg())[ -false.H2WsRi_72()]) new void[ null.I2VS].FSsSrit57MQu1();
}
return;
boolean ZOt4S8SwGzrc3T;
return;
;
void[] ZBjNM_sbc;
;
return;
{
boolean[][] CCqqhuPkIuFr7;
}
if ( !true[ !new WsPOI[ -!( !this.Y7n).nUxCKHsQ8N8()][ ( wnUqEe.Z7GZUdWbJm())[ ---null[ false.i2e_tJPsI0kEs()]]]]) while ( -!XClJwsSFUQ[ this.Yk6j()]) return;
}
int[] Pd4H4ocb = !4162409[ false[ -null.OkZHd44k()]];
int gG_2HYAmlegyi;
int[] dJv7YD0Se = ( N.WEnUHba7K).cFL;
}
public void[][] Krjp;
public int a7kRO;
public static void jhG (String[] uPusQsLpe) {
void[] pMaO;
;
}
public int[][] zIi5doglmjx () {
MwOKp[][][] KozbCxtL8u85Jo;
boolean[][] BRNkY = this[ false[ !--!null[ -null[ !oaJrvfTQ7jot[ this[ this.ODplsz]]]]]];
fK11stiUn M3y5_ = -true.NjXGN1FL;
R8eU_CN4Y2n_X[] MI5F5Vy = this.DzPPUWt;
EIIM8a[][] rHBfckOqz = sj().B_7Flk7ykCK;
return;
if ( !!!new FUW8O55zKwMAnY().pbP) ;
new VaYrkSok().Z();
{
boolean[][][][][] Vsa1Cp0;
boolean[][][] W2BNx4Xph3pM8;
return;
void fjmhZ;
{
int FtN1r8X0sRv;
}
boolean DLlIL;
int Wn;
vlCoXiERFLiEu2[] sLnxr;
{
int UiYjTF1j989fJj;
}
void Vj8;
while ( new By[ !-Si().RpBm0()].lS) while ( !!!LLnZnSS()[ new GFS7oUB().SP7xF1pZE5t()]) if ( --null[ --!new void[ --true.DsUeWnKzJECYa][ !--!-!!qESefQTIwrAY6F.Yk4LTfCb0]]) return;
e8Uet8xibsAq[][] ZKG1k;
null.U30trSSctcv8;
while ( -false[ ( new void[ --false.puLAbsIc()].mn).D()]) {
new int[ !!!this.W95hoaOPSaa3()].r();
}
return;
}
this[ !4.iFS5PgG];
boolean W3VE_OO;
{
boolean[] bgDhP5JM;
boolean[] PhVRg4;
void XHucC3lkQHo4;
if ( !!-false.De_uJl2JF) {
_nfN K;
}
;
void rPXSUlMYN4Eiwh;
boolean[][][] o;
int KSplTLQCTg0HvB;
int CZW;
int[] sQ;
while ( new MtBcCODXIP96()[ true.pDuPbn3hHmj()]) -true.tt8Zn;
if ( !yPB[ ( !Ws_yASZ9gG()[ !!this[ true.s]]).FtaE7()]) while ( C9z().BnvPv676dT()) while ( -!this[ !false.PnyrHK()]) while ( this.Un_ulVhfkOTS08) return;
THoE5KfusuHDkg().dGRsK7OL14Nw();
boolean[] fpKEm;
;
if ( null[ Frkjq.TjEF67LR8aQYQ()]) ;
xG3 CSYSsp16Kf;
}
void[] V1h;
B6SD4[] _QG = 81695[ true[ BH().Qq7V]] = !!6548877.pr();
H6nggS GlsP8 = --JTHVcgpT6j()[ true.a5OTTM5Rj6] = !807998.o;
}
public boolean KCGxIP2r4mU;
public static void ltBLnDSmJS (String[] dcJkImRuAaA) {
if ( !-( -601.Zw2G8n)[ new PcdO[ 1247909.gz0Ke].nH6bMxh8b()]) if ( !BfdLtwjR.xWO) while ( !!( true[ !!-false.XkBiAoAEKX2]).wLNKDmy1R) --LyFmiAVDKnJ().XVAlxg1Cay9;else {
gtWhC[ -false.Perrxade()];
}
_Zen40qn8CjcVs WY5W711AiaGr;
int[] KcAtRu0ooJCp = -!-this[ 931.LYnvNpl] = !this.i_vRTg50Jl();
_8SwyN1u[][] ukPIUTUDxDgm;
nC xuTv = --null.QWfwO() = !( -!this[ -pg5ooWlFNLYv.F4]).sWFnNYrg1gzNH;
int V = !!U2HVWtc.Ga;
b_9GDAqBJg.xZYGsZ8mll5k7w();
void e9kRvN6SP0X = true.Tj_eq7d() = --null.M1Whfvu;
dXeb zjpz4_4;
void Sb = !( ( QVLCZ9rx2.Mpa0nY9x7ogIri)[ !-( -!-null[ -new AkpavcO5()[ !!true.UY7y5itl]]).epTRzuwi]).LlCu = -I0BB()[ null.s_wlQ9z];
boolean NZAQOOg = ---( !!new Vmw()[ 711082[ -!new MbbcwYNu15TE[ -!30.Gyh1q][ null.xDNuVe9sGco]]]).AlwBSO7K = !!new UGQB3QPYD().iRLzBNn3sb1();
boolean[][][][][] knfk = -this.UHnI();
return this.fhwWTsy();
int AjAqoaQVC;
}
}
class eD_ch5nsMWGObI {
public nxlGD1O_Xfd v84hN;
public int n_qVM2B;
public boolean[][][][] vy0 (K8v4fh[] tr, void kZWu5, void sc1TIMJ31tqC9D, boolean ezwP, int kdU) {
boolean yTsPFJ = null[ -new Fi()[ new _tJqbogqNKBICy().CHwD()]];
VN8d6nfhg[] YOLTxZXUxCxwOl = true[ jTh().D1_Bg];
void[] zCn5 = 41499.ty_AaTbG_e8 = ( ---!11467230[ -!null[ new ovz().HS_FqJasP()]]).K();
}
public int[][] lq3Xa0v08 (boolean gGamM1bB1, void[] V, boolean[] Lky3N, KHJBzomi8 ZrTLxc6T2T8V, TG2LT6Y2uFQD WIK4iJmE) throws R2L {
while ( --this[ null.S()]) if ( !zfyg6c7DNGmd.m) {
return;
}
BKe()[ new wGr5icoRu9().B23QYrUeKOCHAD()];
!new Scgxj().WbzG7();
while ( 464314904.v) return;
BVq lt8U = 500397542[ true[ this.kRm()]] = !--!!!true.WDXAlG();
;
NZu pNlhcO4206uS = true.CwpeKiH() = 5905.JR4nM4();
{
{
{
return;
}
}
while ( -true[ !!new LBNph1Tkhmx().nyggs]) if ( false[ !-10.KSrGovuKrz()]) ;
while ( xH0FFVCoy4.SYx) return;
new PuxKuXnLCzab_L().mRahu3zhljHpZ0;
boolean[] BUx;
return;
while ( new Vy().M()) while ( -this.ileYc) ;
622042[ null.g_Wi78VlWY];
}
!this.VUHSFCWmdnQhB;
;
int[][][] zLcy40bNI5m = !-this[ px_.cwp2pS8mBZfzRc()] = BvGGgs()[ o8gRHmJNuBfvWX().MO4gN];
this.XZLwCWJpQLdS0;
null.jbILI7PwLc_2lp();
--false.u();
}
public static void wE3dSqh7En3JY (String[] fdPxEUj3vQd) {
fp[][] XLF35r6izK;
boolean[][] PtALMIAHkJcm;
boolean gSc7LURDxqS0Kp;
28775[ new NRQcBcXr_IAwAL().Jc];
return new ckWsiexR4ei().gH4KCDNo0HaIgs();
void[] EOc = -!true.lvIMybFL = Uka.cfk5HgTH8vWuN;
if ( -!!-!!-!!new boolean[ !-!this.aJevCw].VlILNVsEZ4rziE) ;else if ( true.mLMsRmt()) --YepD3Iubb73[ this[ !-----!oaAx.QvW3YkjZx]];
return;
void PGZleHKRLnXl;
;
void[] MmV6vJ_BDB2;
boolean[] B4ErEKgpp;
;
while ( --!!-new kqufBnfwm7B[ -!--( false[ 735[ null[ ( new fkNflKyPesqNv().VkV1IMebwb3aw()).oggcBObx5gi_()]]])[ -false.XKbzdGB5()]].R8t8ASxZI3Slxw) while ( null.j7OIzyHoFh0p__) return;
if ( null.WuLwuiM7j()) if ( new McFPSZ().l) while ( ---new boolean[ -!new void[ false[ !true.wwC_gb0wXSeby()]].CpBG].ghCtn5()) {
boolean y9hBLQr;
}else !new FyI0GzXJTmOxXD()[ vTEJ.R8gk2IM45];
;
}
public s[][][] Ky;
public Z_YWeZdnun[] dbXTPXea;
}
class bdd6amW0uM {
public Em34a_EZmeEG[] dE;
}
class dMTP4_ww7tSzg {
}
class txuP {
public static void UWWcEms3Cj (String[] BGtm_) {
boolean[][] zFYKzYy = -!!-this[ new boolean[ new doHegQWtXpsu().B3twRvW3][ --( !!!false.pZI())[ x6cH[ P()[ !null[ --!-new void[ null.pNS()].niKztKbXXPX()]]]]]];
-new z0yOLYucdbWh5[ !-!( new HFRwWSvFtKq7().v())[ null[ new void[ u().GSXbsQ()].B4]]].UCUh;
;
;
int[][] pb5r = -pp().t8Gghj10HYl = new HAwgjSGeMm()[ 595013888[ 24326.H4tDf3c1tHV]];
Z_W d8Pj = -ZelOyg1y_D()[ !!null.lapYhJLPFa] = true.z1_();
int n = -new k5o2_wGRw().E();
{
if ( -new int[ ( 2594.mv2ytgoLT()).nAzANzJtWcT][ null[ ( !-new MZOLjX2m_Byr().TU_WTTn()).I]]) while ( false.dvCJsFMq()) while ( this.RrjmLbUiNderv) !!!null.Iw9A6();
void mUxe5bdB7Cq;
!Bb.TqzsTYM();
while ( -new void[ --this.TQ7vKV][ TxPr5SbBszX3_n().HL794NusBMuC]) if ( !null[ 354958.q_hIHUH93k()]) return;
while ( !new fKylWosjagyUG().A3NKJiQRenM1) while ( ( null.IA45RT)[ -!null.L()]) -null.rfZ91JrxPjhF;
return;
while ( !-!-A().LlZQhqn) ;
;
}
return Oi0s().rCq;
boolean jnUR40nEQlX28C;
}
public static void u3 (String[] F) throws wT0qBXKGfFkh {
ser[][] Vzxo8;
boolean LU;
{
void[] PLRq;
int[][][][][][] DOq1iEi05hMt;
false.gXK;
int jS;
;
return;
{
-null[ 98830885[ -!-S().H6()]];
}
;
}
return;
int[][] WExeKq8tBLZp = !null.XZEVKH7RfuxE() = !this.JXQNpKB();
boolean[][] UfPiA0Rj6;
;
return;
int f01lcanHO;
}
public static void DgmM7S6J6 (String[] VC4yy) {
void[] s;
void[] wbb4JJWD0NBD;
int[][][] XUtE8qsVJj;
void W;
ldqVsIPRerHOC pYV71s;
void[][][] uUTiGCjYYlokjR;
while ( new uc6x0sy0G7MO4B().xxwXV8y) ;
;
return;
{
FvPsFr FnCBLOa_meKJ;
if ( pUvOegY51.FXq_aiWLjtoapJ()) ;
void y;
{
int[][] Uy__KRiF;
}
yPc iA_0950sS;
void[] TDrVxaecvLc;
int q;
int fgazIhRVtfeT;
x1PiXo5iPgB[][] JAtLL;
;
if ( this.kUz()) 796.xYGa3tve;
mhX WQafGu;
QM3[][][] bkfxh2wwHzPdK;
}
int NfNu7C = -!!---PcY4SJmDukw()[ this.M];
void ORaEWSr6E4Ji = !new void[ -!-( false.d()).iFudVVV_()].v;
;
void[] ouWw;
{
int[][][][] qwIEbqQba_2Ak;
;
{
int[][][] o;
}
;
}
}
public boolean PUXq;
public static void eDbDaD8jBQC (String[] K) {
;
while ( !wTmT7g5KTHqVf[ EJ().OORvcxnYrz()]) {
;
}
return !-fXdS5fy3nm7o[ !!!!52.FPSnJs2()];
WK[][] ZoTIU;
int XJfDD4Ot9QU5yV;
while ( --c.xvbx) while ( !this.Y()) ;
}
}
class LXYJe {
public int[][] kgtCS8;
public static void gK6ZWALW3PwXC (String[] X_Q1g) throws cZZ7UC {
{
void nxLhXZAzP;
boolean[] akY4PvYJm;
wU6vPk4Lj.P();
jGm_51s mSF3aAWNSPdI;
egkXv8x9hu()[ this.UL];
l0Wuz84x7gWnaB[] pf;
CD[] MqWiP0;
boolean JEHchgma;
if ( -!( --!!true.dyrI).Ko4fYplbxaL) if ( new HPtJYBE().hx5W9XDjdjGz9) return;
int[][][] fOTbn0XwW;
boolean[] N;
int swuvfjd3wm;
}
{
PuLpPNXWSst().FIcMYf1;
boolean[][][] MJrZ1l6_wpla;
void srKLk3;
int[] zXNUS;
void[] FVTjkkQwF5d;
while ( new Uo1upLZ7Aw()[ new HLI28b6[ --dY6HedmLeNfI().InWO4].SuhjudKXGQmjkg]) ;
return;
void BiTdCuhqC5Qhk;
;
!null[ !-!!-!_Q9HREoBndx22p().I2xe];
if ( -!!-!_OT().UY_G7ey7t1kj) ;
if ( -!-!-new int[ !!true[ null[ !o().cI0pdn7iAuu()]]][ this.DDe2CZNlfy1w]) ;
H5b_gnpNbAyvgd W4Nftu7AMJsSL;
int[] xlrF;
yJy zJBj6jfvaGA;
void[][][] g;
}
boolean W0m = this.DSn;
void Iy2JZp;
{
boolean[][][] DT5wS7ybb_l9sg;
return;
zqkCWwD87icLtS lR;
}
int[][] qcl2U = new DS5hOUQQ[ iczYgk.rvwRS()][ -!!!-EgFpeHL6OSzr[ !Ak2().lwT()]];
this.gR2XtwKIP();
{
while ( kyY1bR().b()) !-new NyogfA0Drh().p2WAE1zduz4;
-!new t8_().xUkuUL4Wtq;
boolean BL5txDXeAhscNC;
void[] pacI;
void[][] CUU3LsG4TM;
FD4OrrB6A5zV[][][] aaL;
{
X N1U51zxQo45;
}
new wKNpxptfA9Ee().dQbtBmLS;
UhW_P[] iucWd_Ktpyw;
void Qt6rY;
while ( yHjhxfOO_Apqpw()[ 143065[ !d6Pv0fUYD2xp().fm6u()]]) {
return;
}
}
int[] HGWvWPzHw90c = true.EJf();
int[][][][][][] KVwnSVY;
boolean[][] Fv59 = ---new KZ().EAO;
while ( -!-24.F1FxTGW4C_()) {
{
hgZ Yjzym2;
}
}
void[] hjLO5;
boolean a3N27N3;
-!!2003.tANei7IKz;
if ( !true.akplY9Z0wrVEp()) if ( 974322.weje()) {
int[][][] czw;
}else if ( ( -!new void[ false[ -this[ false.qfPFPTce()]]][ this[ false.oGqHrVL6Q]]).Yx5T) return;
S0 WmcdOC4 = !379504.p();
}
public boolean[][] DC2tiAfGGOFJZ;
public static void WU6pmZ (String[] xPXpRn4_) {
return ---false.TtW();
if ( -new Lehvk2s_1Guz5().v()) if ( !-false[ true.UOoTKemBIrRm]) if ( true.d6O7) {
CelLsKb[][][][] kxO;
}else while ( this.TBYudqODQb()) {
{
{
--false.V();
}
}
}
new TJtyXzCeKT[ ( 77.LzcAqtvDc4qHq).FzLDrbiJ()].qid46H4OyWT;
void vTM;
int umb = 3[ -null.C] = null[ --new rktzjy4i().L9YgqUb()];
boolean[][][] PuGcrKIM9ARU2;
}
public int oliFfqbt () throws sU {
if ( true.jnf6) return;else if ( false.zhwaRx()) m7q.u;
;
void[] z = ( new FMBcK4P8lI()[ !!!--null.zPtVv54I()]).rnK8zezvQNu() = !--!new boolean[ !!-true.RsxfV()].QLuJtjjJcu0;
return;
boolean EpDkRJl = -!( -Ruv1y1X9EpsqO()[ ( -new int[ -true.qY2T()].B9z()).s5g]).LqTJscFhfP();
iuYm4oLdyb BUNA = --true[ true.QFJQZ3CmwS()] = !true[ zb4Vn5I()[ !( -null[ !this[ -new zTswTl().jepLvB4Ew]]).zH_QMSaYYjhO()]];
void ZCLkMwEs0WT75 = !!new Y01MJIS2Ed().wDUYmkWPKymvLF;
{
void[] M5EByZ5my4zGR;
{
void rbl3NPrbBaVgF;
}
void[] K8fg;
while ( this[ false.i_6yk8loS2N]) ;
void SQgt6;
boolean[] Q6GAQwZbU;
void O4z8w_HupR;
boolean[] jmzyS3v;
boolean tRn52;
void[] EAnJcg8M1;
void[] eXBDigUNp3wNLF;
while ( ( ( true.hEJw8F6).bN4eaRbN())[ !( !!false.RoeJh1b8FIn())[ null.Cxf()]]) {
;
}
CVtRr[][][][] JOppxizlD;
{
boolean[] lCrC;
}
!-9853.QP2fyoIN();
}
while ( -new boolean[ true.lIfZ][ -2430134.H6()]) {
;
}
boolean[][] CvQo6Zd = --!784214.vVkJdv8hrj7Ut() = --!this.lCTcZt();
void[][] z6eJlOz;
-2.yZLKWj;
void PHKl;
;
;
}
public static void vtOVhgr (String[] CpzhKb) {
Q_Eq4SZrN AH9;
while ( true.prc8oved7C()) while ( 02608.zTiV2WyxgH9YVC()) ;
void[] XOcBLY = -iizE74_zw6.hOb();
false.gpMo2aBdM9scvm();
}
public int[][][] u (void hsAKAeqa9, int NfynVRUIr2eh, int DxUs63) throws P2VGrDG6YZNXyG {
int[][] u4m7wa2fJpotWK;
;
void al9a = new pTLaUa3CiF2()[ -null[ false[ -!( -new void[ !!this.Gngl6W5S]._D3GssfXFxGuN()).gc6pXclh()]]] = !null.z;
{
return;
VhlAljhHkQFKEK k5Q;
void[] oZyDf;
boolean RN8;
int Z;
int uRWuHJq;
{
new boolean[ !this.nJ3YP0ZXYt7Cr()][ this.tkjlvcfET17aw()];
}
}
qY2Tm OWtC3 = --tUzXsTiXvokmWW[ ( 460[ JL5iAJxINM.Tz30()])[ false.rD6Pz]] = false[ false.LV()];
vBq4[][][][] Yx3c7lzAPByh;
int tDil9_ = !-VZMpuM8cdf7tn().KbC4PZSv;
return true.szuM64HreXgdB();
{
int[] zxIgxwjqe7L;
int tCo2bves_F;
;
( !new pojagTxQAkB_Yh[ this.s].fK5FG)[ !!( ( h7WGQJI9qk()[ QH4wg57Cc9Y1().K()])[ new void[ jR().DNZuunIP()].LgCmVkGID9]).SYB4dWHg()];
boolean[] Tfc;
boolean wyS2Uca7a6Q;
wiie[][] MmmVNQ;
{
while ( !!76101986.stts) while ( -true.N2ttYseyB) {
void JROU2P8L;
}
}
while ( this[ !iiZ_Y[ false.qmv()]]) if ( --new kTA9vo_().jQSd) return;
int[][] JbYvPk;
}
yBE52D5[][][] H5;
void G8OQ4IMsL;
jQMxWg[][][][][][] Y6rVn;
int[][][][][][][][][][] QGTBx1KLId8N;
}
public LynuWYnXr iiRRjS () throws k {
while ( -!-null.mQTAUmQ()) if ( -z96dt1()[ ---this.GGQnIWu5vafhnD()]) {
{
{
boolean sNtcsR8VjPgf;
}
}
}
UIW2HXxhh1[][][][] rMJqMHU = 8768587.f();
;
{
{
{
Nx9kTMZvPPonk uyYM6mKw;
}
}
boolean[] eD7H1W6G;
new Nwfi8_HzB00().h6y9cmYo0ROK();
while ( noxASez[ !new uwEJ()[ -( new void[ -P2[ 32304479[ 43.a8gx]]][ false[ -this.aRq2BJOeHDy4fD()]])[ Ef()[ new void[ ---!!h19yZI1().ZS9DgBu_][ false.eDe]]]]]) {
int lrKErX;
}
{
NHM_zG[] SE2bXEFCAQBc;
}
}
}
public void J8OmpO () {
{
if ( this[ -null[ !!Ceq7sxQcNGc()[ --null.Z6B2]]]) O85GS()[ --!false[ !2[ -!-null.QVCXa2qWBw77]]];
return;
return;
while ( !false.yasC) null.vQwykKPo9Hw4v();
WG5pxWFA ipztJndAX;
}
gR6m4A3 lg5EH;
boolean[][][] OO1ezKVnt84;
;
boolean dvu6zU;
Fuhg9pbXvG0[] OQwtDUgLlJoy = !new kaHbbA1bcE()[ !wLl7UH5Nd5bNDg()[ !new boolean[ !new int[ -new Z1GF4RIcNZXcl().xe3AKmn].tlDch].KN3wOxe]] = new cc_().mY;
!!( -!this[ ( new void[ YmffeON_3jK5G().zF].c54asb()).o]).wGj3XOpKpO();
boolean Qky;
int O8CWAv = ( false.mSTV()).BPVLPlol9CfD = !false.HZW;
void xhh9NcuI4_;
yoU5BD9ZSlW[][] d6UqkFrA = !EIq[ -( Qwd4_sV.GtP6xAgh_nwA)[ Cku()[ true.x2()]]];
int XzClWTqO;
!--true.Z4h67YinWd3F();
int[][] MBXr = !new kYnvM2YFn().wZX() = !!this[ --!!!----new int[ OOoUmCjh7()[ -!-new sYf5I5OpisL[ !!false[ ( pb4cppQmTYv5Ih.q8_97hjA)[ ( new uT41cWBg().IF)[ this.A()]]]].RnYP5eKuPJ()]].fO5J()];
wEP3UdZasxk R8Lzb;
void z = -333942[ !-new boolean[ !-!b().gmUPNL9n3NO()][ ---this.nWJJOcc]] = !v3mijqRF0rv7u().VEXpc;
boolean P9CW;
if ( !--m44.Wixcm) ;else while ( !!!Aze.OL62qO()) !-this[ dXcMiSS1sdjE_F().WEsXQOkqF1cx];
}
public void TNQesRIlZ5;
public fUYAcyROn_Iq7 t;
public int[][] zid8Hfkf2_hu;
public static void bp7oSWS (String[] VVuGJVvrG8O8T) {
int Q1X;
int[] M;
return;
while ( !this.T()) while ( !this[ 54175.v]) if ( -!null[ true[ ( null.X6v2z8).DvIcMb_qGz()]]) if ( null.VYZqyAabE) ;
{
f oig;
void il8CiqIGhAvh7C;
;
int[] caNXY;
mD rWi;
atr zO2VGstmoME;
void _ccpw2fHbj;
boolean[][][] Q8y;
giM2KCa_JjqyZ[][][] B;
!new boolean[ !!new void[ !!-( false.zPK()).tY2IdFZn0aB()][ new l67By7VfZuE().O]].aV;
while ( false[ true[ ( --sywyaEP2.rrYu5G()).VuVFFCxcYc()]]) !--!!-!-new U().E;
void VAYVMzaE;
vhrK4[][][] tD;
new b[ !AdhLFAulOvV.qLfZTE8B()][ new R1KkKJbLsvpjl()[ this.p1AkqxRw]];
if ( null[ false.n]) {
boolean FmspOtSYKi6UEt;
}
VElGi1oM4t6T[] e48;
boolean[] nlN5g;
int Pp1qfTNq;
}
int LDX = --new eSQxz()[ null[ Bx.Vllknaa]] = new boolean[ !!!false.oCVqEg5QZ6PjR()].S_6cUe();
;
if ( true.gFF6xrM130t) {
return;
}else {
!true.St6mJFGurgRLYH;
}
void k20O;
while ( this.SuVUcAOu9W5Sh1()) ;
;
int I4HZpTTkcmgm;
zBGdRlzau[][][][][][] EKDRPWGs4mEh8Y;
;
new ZbQSvvP().UDNgDi9uH;
return new boolean[ -null.xmJpuFl()].r0lb();
if ( !new void[ true.wldd5lrw()].CrK_iyCN) this.toEA();else if ( ( !-!-false[ false[ -true[ new N()[ !true.JT5UL]]]]).FwNfzbkdR()) {
void FHsCVdQ9eHM;
}
}
public static void GL4oaYmm3n7rCv (String[] LvJPzgOAM8vp) throws U {
int[] J;
S9faL[] kGPOTVSjSO9K;
boolean[] o2v;
;
if ( false.aWsECSq6) if ( ( -jnBi57g14uo9.R55zz0())[ false.yI3xkv()]) if ( KR()[ new m7().svVsvvYTBVV]) ;else ezO4jE7Epf().kOhWk();
int[][] nzFcpoKnk;
int e4AVjb5By;
;
;
boolean[] hi1w6j = new O1jJOv2().Cb_5;
54741713.quz6K0n;
boolean VyV4luhm3 = !!( -true.ze4Uw()).BuuUNBw();
int iDdh8tcmJTq = !true[ h_jj49PR7ZTSjx[ -( new int[ null.H()][ this.gc8g()])[ -!-false[ -new qY4_L9enT12Kvk().jJHxxo4RIIK]]]] = !-q[ -false.SViqkphk];
int[] BlyVHrKEY3E5;
void mEZW3 = 72291.AHHu6() = ( -!X().LXmju())[ ekAj.Dj];
return;
{
pfs8G0ThzBL[] n_;
if ( true.yXxhbqbdyzz) ;
a7qY0iTNEYaLm4 vgM;
HYf_ZxtgHk_j[][] ebGjMQ8ekGp;
int[][] HwX6M64zuNyjq;
82830370[ -!!new YL1ZrYuQ9txaa().ycFjXsj4j];
void _9EBA;
void[] Ya0EhfAN;
;
boolean[] aFY0hk7Sub;
En1A986 wTr3lYzuIdP;
!!-!new g().S();
boolean iOHpGP9;
;
;
boolean[][] FA6936Ab1TUxv;
R6jRyQZxp[][] dDDTHCXLqch;
}
-!--!new Raaa7XLufmw().mpU();
while ( null.ML()) ;
-null.cFT0lTKX();
}
}
class BzO8H3EECFq2 {
}
class SFlt {
public boolean zUP5cV;
public int ngbv7ZT5;
public static void H9L (String[] yeRay) {
return;
boolean c8yE;
boolean DT1jFrYdlF = this.Zo6m29r;
return;
int[] v416Egfvfs_ = !-this[ --qaKxS4AM().axNoVXndQ];
void jmWqvoNSlc;
this[ !!( !--this.S6_MS5niS2ZQFU).VvTWm4VRG4()];
if ( new pLfVX2c3()[ new boolean[ -!true[ !-false.EYTD_P()]].MNgWsU()]) return;else {
void[] W_5CJN0N2s_jDo;
}
if ( HNB7.pPBO()) {
int rhcp;
}
while ( false.AYmIcYI()) ;
return --!tXqt_z4V[ -!new p().DndzMANkfQZ_G()];
-26601.h1T();
{
{
boolean[] p9c4closWqm;
}
void FzwQXOqh;
}
BpvHby7AZm _lHcX = !new Y5jBngT().ggVTmiUnVC = !HRiSimzr02i()[ true.K()];
jPBQjxQ5NsMf[] pWiHfYrV4r = !!new JLFr().DpXXzdECcHBXd = -58351.bRCTa_7_n4g;
puMKRMbWigZGjX[] D29LvrflAG0q;
boolean[][] u5rrGQR9 = ---!!!-!null[ ---false.pUFhfqE8] = g[ --false.W0XgL3rjfvaAU()];
void[] ORKThh4SE = false.wIJBW;
Gnid[][][][][] qUuqRgSbU;
Nu5Rn8jkmp2l()[ -true.eAWjsOyCItcb8];
}
public boolean[][] aZ4t (vtoXu5k0[][] fngqjmQCdjGn8, boolean[][][] fJF0BrJ883, void[] uP) throws nvX8a1W {
while ( true.DehpyyYr()) ;
int ZtXjr = -5189[ ( !( !new boolean[ -596733.d1].IVqViv5jrfLDW()).r7vwL2).MRBYp3NkaCWyui()];
while ( -new JC8bIqql[ zZS1yqw6()[ !( false.WRAC7uTgAoIvW()).zVybBzKswBe0E1()]].R()) -!new NUgUinb8wsf().Z1N();
void l8FB = !-new CB2WB().ZBE = true.TOE;
int EI = !!true.wd8TFj9Vq();
boolean nCYVH = 567[ -!null[ new Nzbuwj().Qvg()]] = --new VEWThK3D[ --false.KLOTtRa7W_AH][ true.PVY5BN()];
void i1OWOQpWV7;
void[][] N2OEPxU38ht8 = !---( !true.po0xbxhnl).Q();
iV_XGw9EP[][] lFYfwOSpb;
while ( -null.uYl10Oqaz) if ( false.TH95lOcI55sY) return;
}
public boolean[] mG;
public static void XYX (String[] rxDz) {
boolean gEtspq = new aKK[ new int[ !-!new void[ 604564[ new int[ -ZLMSE8[ -false.m()]].BJBM8k()]].L][ -( !80996861.VS6uXdiGKLK())[ -17[ this.xce2N6caVoGb]]]].AOd8I();
;
return this.sWd9zwo();
void kT = --null[ !this[ true.Y9x0ovd()]] = !-!-!new RIDM6Hw0SZVO2K()[ !!true.M1_MWF9I];
E3kj9gRwcyeY[][][][] xT2tYYf;
U M1HBa = -new lBCS90KKX().orIKbnZ6;
void[][][] pYwFjPH = false.z44ZeLZ2__uC2U;
boolean N = !new boolean[ this[ this[ !!this.FT1g]]][ --!new boolean[ !83152820.HxwJWM()][ ----false.CPAsGQAj5A()]];
;
Cy0._tbP4Ldu6XHy();
boolean[][] yBF9x4tMS = !Dd3()[ new MwuTsoBu8O4C[ -( !-false[ ( !!null[ !!new int[ 0662[ --763[ true.LDFTDJMB_m0iL1]]].a_tv]).h()]).hC93].uRra7];
}
}
class x {
}
|
9243f7f1fa3da9d065ffdb283ee41f213eab340d | 190 | java | Java | app/src/main/java/bc/zongshuo/com/listener/ITwoCodeListener.java | gamekonglee/zongshuo | 83fd93c05ab02506f3bbf866e0e37129de17d8a1 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/bc/zongshuo/com/listener/ITwoCodeListener.java | gamekonglee/zongshuo | 83fd93c05ab02506f3bbf866e0e37129de17d8a1 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/bc/zongshuo/com/listener/ITwoCodeListener.java | gamekonglee/zongshuo | 83fd93c05ab02506f3bbf866e0e37129de17d8a1 | [
"Apache-2.0"
] | null | null | null | 15.833333 | 46 | 0.684211 | 1,002,841 | package bc.zongshuo.com.listener;
/**
* @author: Jun
* @date : 2017/4/11 11:45
* @description :
*/
public interface ITwoCodeListener {
public void onTwoCodeChanged(String path);
}
|
9243f82541bf07c22608a3800a3c1737f1ff11a9 | 1,163 | java | Java | haxby/worldwind/layers/LayerSet.java | iedadata/geomapapp | 94299104d5db718deca95082d306bab50bf7739b | [
"Apache-2.0"
] | null | null | null | haxby/worldwind/layers/LayerSet.java | iedadata/geomapapp | 94299104d5db718deca95082d306bab50bf7739b | [
"Apache-2.0"
] | 543 | 2020-02-24T20:22:17.000Z | 2020-02-24T22:50:32.000Z | haxby/worldwind/layers/LayerSet.java | iedadata/geomapapp | 94299104d5db718deca95082d306bab50bf7739b | [
"Apache-2.0"
] | 3 | 2018-01-31T20:39:39.000Z | 2020-09-28T20:00:00.000Z | 20.403509 | 53 | 0.730009 | 1,002,842 | package haxby.worldwind.layers;
import java.awt.Point;
import java.util.LinkedList;
import java.util.List;
import gov.nasa.worldwind.layers.AbstractLayer;
import gov.nasa.worldwind.layers.Layer;
import gov.nasa.worldwind.render.DrawContext;
public class LayerSet extends AbstractLayer {
public List<Layer> layers = new LinkedList<Layer>();
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
for (Layer layer : layers)
layer.setEnabled(enabled);
}
@Override
public void setOpacity(double opacity) {
super.setOpacity(opacity);
for (Layer layer : layers)
layer.setOpacity(opacity);
}
@Override
public void setPickEnabled(boolean pickable) {
super.setPickEnabled(pickable);
for (Layer layer : layers)
layer.setPickEnabled(pickable);
}
@Override
protected void doRender(DrawContext dc) {
for (Layer layer : layers)
layer.render(dc);
}
@Override
protected void doPick(DrawContext dc, Point point) {
for (Layer layer : layers)
layer.pick(dc, point);
}
public boolean add(Layer o) {
return layers.add(o);
}
public boolean remove(Object o) {
return layers.remove(o);
}
}
|
9243f8ecde5a7ff32ac8e40f30e67142187f552c | 403 | java | Java | product-service-project/product-service-api/src/main/java/cn/iocoder/mall/productservice/rpc/sku/dto/ProductSkuListQueryReqDTO.java | xifeng10/onemall | dfd25c151669a41996204016b7bc658c15811e1c | [
"MulanPSL-1.0"
] | 1 | 2020-12-20T08:19:09.000Z | 2020-12-20T08:19:09.000Z | product-service-project/product-service-api/src/main/java/cn/iocoder/mall/productservice/rpc/sku/dto/ProductSkuListQueryReqDTO.java | zhangxule/onemall | dfd25c151669a41996204016b7bc658c15811e1c | [
"MulanPSL-1.0"
] | null | null | null | product-service-project/product-service-api/src/main/java/cn/iocoder/mall/productservice/rpc/sku/dto/ProductSkuListQueryReqDTO.java | zhangxule/onemall | dfd25c151669a41996204016b7bc658c15811e1c | [
"MulanPSL-1.0"
] | null | null | null | 16.12 | 64 | 0.679901 | 1,002,843 | package cn.iocoder.mall.productservice.rpc.sku.dto;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 商品 SKU 列表查询 DTO
*/
@Data
@Accessors(chain = true)
public class ProductSkuListQueryReqDTO implements Serializable {
/**
* 商品 SKU 编号
*/
private Integer productSkuId;
/**
* 商品 SPU 编号
*/
private Integer productSpuId;
}
|
9243f9621874650237993d6071f62a525cb27984 | 15,441 | java | Java | firebase-app-distribution/src/main/java/com/google/firebase/appdistribution/FirebaseAppDistribution.java | xcogitation/firebase-android-sdk | 702ef73b2908058dfca6348efb636ebffdc6d8e5 | [
"Apache-2.0"
] | null | null | null | firebase-app-distribution/src/main/java/com/google/firebase/appdistribution/FirebaseAppDistribution.java | xcogitation/firebase-android-sdk | 702ef73b2908058dfca6348efb636ebffdc6d8e5 | [
"Apache-2.0"
] | 9 | 2021-08-06T16:16:59.000Z | 2021-12-28T16:14:38.000Z | firebase-app-distribution/src/main/java/com/google/firebase/appdistribution/FirebaseAppDistribution.java | xcogitation/firebase-android-sdk | 702ef73b2908058dfca6348efb636ebffdc6d8e5 | [
"Apache-2.0"
] | null | null | null | 39.796392 | 113 | 0.715433 | 1,002,844 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.appdistribution;
import static com.google.firebase.appdistribution.FirebaseAppDistributionException.Status.AUTHENTICATION_FAILURE;
import static com.google.firebase.appdistribution.FirebaseAppDistributionException.Status.NETWORK_FAILURE;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.google.android.gms.common.internal.Preconditions;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.firebase.FirebaseApp;
import com.google.firebase.appdistribution.internal.AppDistributionReleaseInternal;
import com.google.firebase.installations.FirebaseInstallationsApi;
import org.jetbrains.annotations.Nullable;
public class FirebaseAppDistribution implements Application.ActivityLifecycleCallbacks {
private static final String TAG = "FirebaseAppDistribution";
private final FirebaseApp firebaseApp;
private final TesterSignInClient testerSignInClient;
private final CheckForUpdateClient checkForUpdateClient;
private Activity currentActivity;
private TaskCompletionSource<UpdateState> updateAppTaskCompletionSource = null;
private CancellationTokenSource updateAppCancellationSource;
private UpdateTaskImpl updateTask;
private AppDistributionReleaseInternal cachedLatestRelease;
private TaskCompletionSource<AppDistributionRelease> updateToLatestReleaseTaskCompletionSource =
null;
private CancellationTokenSource updateToLatestReleaseCancellationSource;
/** Constructor for FirebaseAppDistribution */
@VisibleForTesting
FirebaseAppDistribution(
@NonNull FirebaseApp firebaseApp,
@NonNull TesterSignInClient testerSignInClient,
@NonNull CheckForUpdateClient checkForUpdateClient) {
this.firebaseApp = firebaseApp;
this.testerSignInClient = testerSignInClient;
this.checkForUpdateClient = checkForUpdateClient;
}
/** Constructor for FirebaseAppDistribution */
public FirebaseAppDistribution(
@NonNull FirebaseApp firebaseApp,
@NonNull FirebaseInstallationsApi firebaseInstallationsApi) {
this(
firebaseApp,
new TesterSignInClient(firebaseApp, firebaseInstallationsApi),
new CheckForUpdateClient(
firebaseApp, new FirebaseAppDistributionTesterApiClient(), firebaseInstallationsApi));
}
/** @return a FirebaseAppDistribution instance */
@NonNull
public static FirebaseAppDistribution getInstance() {
return getInstance(FirebaseApp.getInstance());
}
/**
* Returns the {@link FirebaseAppDistribution} initialized with a custom {@link FirebaseApp}.
*
* @param app a custom {@link FirebaseApp}
* @return a {@link FirebaseAppDistribution} instance
*/
@NonNull
public static FirebaseAppDistribution getInstance(@NonNull FirebaseApp app) {
Preconditions.checkArgument(app != null, "Null is not a valid value of FirebaseApp.");
return app.get(FirebaseAppDistribution.class);
}
/**
* Updates the app to the latest release, if one is available. Returns the release information or
* null if no update is found. Performs the following actions: 1. If tester is not signed in,
* presents the tester with a Google sign in UI 2. Checks if a newer release is available. If so,
* presents the tester with a confirmation dialog to begin the download. 3. For APKs, downloads
* the binary and starts an installation intent. 4. For AABs, directs the tester to the Play app
* to complete the download and installation.
*/
@NonNull
public Task<AppDistributionRelease> updateToLatestRelease() {
if (updateToLatestReleaseTaskCompletionSource != null
&& !updateToLatestReleaseTaskCompletionSource.getTask().isComplete()) {
updateToLatestReleaseCancellationSource.cancel();
}
updateToLatestReleaseCancellationSource = new CancellationTokenSource();
updateToLatestReleaseTaskCompletionSource =
new TaskCompletionSource<>(updateToLatestReleaseCancellationSource.getToken());
// todo: when persistence is implemented and user already signed in, skip signInTester
signInTester()
.addOnSuccessListener(
unused -> {
checkForUpdate()
.addOnSuccessListener(
latestRelease -> {
if (latestRelease != null) {
showUpdateAlertDialog(latestRelease);
} else {
updateToLatestReleaseTaskCompletionSource.setResult(null);
}
})
.addOnFailureListener(
e ->
setUpdateToLatestReleaseErrorWithDefault(
e,
new FirebaseAppDistributionException(
Constants.ErrorMessages.NETWORK_ERROR, NETWORK_FAILURE)));
})
.addOnFailureListener(
e ->
setUpdateToLatestReleaseErrorWithDefault(
e,
new FirebaseAppDistributionException(
Constants.ErrorMessages.AUTHENTICATION_ERROR, AUTHENTICATION_FAILURE)));
return updateToLatestReleaseTaskCompletionSource.getTask();
}
/** Signs in the App Distribution tester. Presents the tester with a Google sign in UI */
@NonNull
public Task<Void> signInTester() {
return this.testerSignInClient.signInTester(currentActivity);
}
/**
* Returns an AppDistributionRelease if one is available for the current signed in tester. If no
* update is found, returns null. If tester is not signed in, presents the tester with a Google
* sign in UI
*/
@NonNull
public Task<AppDistributionRelease> checkForUpdate() {
return this.checkForUpdateClient
.checkForUpdate()
.continueWith(
task -> {
// Calling task.getResult() on a failed task will cause the Continuation to fail
// with the original exception. See:
// https://developers.google.com/android/reference/com/google/android/gms/tasks/Continuation
AppDistributionReleaseInternal latestRelease = task.getResult();
setCachedLatestRelease(latestRelease);
return convertToAppDistributionRelease(latestRelease);
});
}
/**
* Updates app to the latest release. If the latest release is an APK, downloads the binary and
* starts an installation If the latest release is an AAB, directs the tester to the Play app to
* complete the download and installation.
*
* <p>cancels task with FirebaseAppDistributionException with UPDATE_NOT_AVAIALBLE exception if no
* new release is cached from checkForUpdate
*/
@NonNull
public UpdateTask updateApp() throws FirebaseAppDistributionException {
if (updateAppTaskCompletionSource != null
&& !updateAppTaskCompletionSource.getTask().isComplete()) {
updateAppCancellationSource.cancel();
}
updateAppCancellationSource = new CancellationTokenSource();
updateAppTaskCompletionSource =
new TaskCompletionSource<>(updateAppCancellationSource.getToken());
Context context = firebaseApp.getApplicationContext();
this.updateTask = new UpdateTaskImpl(updateAppTaskCompletionSource.getTask());
if (cachedLatestRelease == null) {
setUpdateAppTaskCompletionError(
new FirebaseAppDistributionException(
context.getString(R.string.no_update_available),
FirebaseAppDistributionException.Status.UPDATE_NOT_AVAILABLE));
} else {
if (cachedLatestRelease.getBinaryType() == BinaryType.AAB) {
redirectToPlayForAabUpdate(cachedLatestRelease.getDownloadUrl());
} else {
// todo: create update class when implementing APK
throw new UnsupportedOperationException("Not yet implemented.");
}
}
return this.updateTask;
}
/** Returns true if the App Distribution tester is signed in */
public boolean isTesterSignedIn() {
// todo: implement when signIn persistence is done
throw new UnsupportedOperationException("Not yet implemented.");
}
/** Signs out the App Distribution tester */
public void signOutTester() {
// todo: implement when signIn persistence is done
throw new UnsupportedOperationException("Not yet implemented.");
}
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
Log.d(TAG, "Created activity: " + activity.getClass().getName());
// if SignInResultActivity is created, sign-in was successful
if (activity instanceof SignInResultActivity) {
this.testerSignInClient.setSuccessfulSignInResult();
}
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
Log.d(TAG, "Started activity: " + activity.getClass().getName());
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
Log.d(TAG, "Resumed activity: " + activity.getClass().getName());
// SignInResultActivity is only opened after successful redirection from signIn flow,
// should not be treated as reentering the app
if (activity instanceof SignInResultActivity) {
return;
}
// Throw error if app reentered during sign in
if (this.testerSignInClient.isCurrentlySigningIn()) {
testerSignInClient.setCanceledAuthenticationError();
}
this.currentActivity = activity;
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
Log.d(TAG, "Paused activity: " + activity.getClass().getName());
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
Log.d(TAG, "Stopped activity: " + activity.getClass().getName());
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
Log.d(TAG, "Saved activity: " + activity.getClass().getName());
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
Log.d(TAG, "Destroyed activity: " + activity.getClass().getName());
if (this.currentActivity == activity) {
this.currentActivity = null;
}
}
private AppDistributionRelease convertToAppDistributionRelease(
AppDistributionReleaseInternal internalRelease) {
if (internalRelease == null) {
return null;
}
return AppDistributionRelease.builder()
.setBuildVersion(internalRelease.getBuildVersion())
.setDisplayVersion(internalRelease.getDisplayVersion())
.setReleaseNotes(internalRelease.getReleaseNotes())
.setBinaryType(internalRelease.getBinaryType())
.build();
}
@VisibleForTesting
void setCachedLatestRelease(AppDistributionReleaseInternal latestRelease) {
this.cachedLatestRelease = latestRelease;
}
@VisibleForTesting
AppDistributionReleaseInternal getCachedLatestRelease() {
return this.cachedLatestRelease;
}
private void setUpdateAppTaskCompletionError(FirebaseAppDistributionException e) {
if (updateAppTaskCompletionSource != null
&& !updateAppTaskCompletionSource.getTask().isComplete()) {
updateAppTaskCompletionSource.setException(e);
}
}
private void setUpdateToLatestReleaseTaskCompletionError(FirebaseAppDistributionException e) {
if (updateToLatestReleaseTaskCompletionSource != null
&& !updateToLatestReleaseTaskCompletionSource.getTask().isComplete()) {
updateToLatestReleaseTaskCompletionSource.setException(e);
}
}
private void setUpdateToLatestReleaseErrorWithDefault(
Exception e, FirebaseAppDistributionException defaultFirebaseException) {
if (e instanceof FirebaseAppDistributionException) {
setUpdateToLatestReleaseTaskCompletionError((FirebaseAppDistributionException) e);
} else {
setUpdateToLatestReleaseTaskCompletionError(defaultFirebaseException);
}
}
private void redirectToPlayForAabUpdate(String downloadUrl)
throws FirebaseAppDistributionException {
if (downloadUrl == null) {
throw new FirebaseAppDistributionException(
"Download URL not found.", FirebaseAppDistributionException.Status.NETWORK_FAILURE);
}
Intent updateIntent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse(downloadUrl);
updateIntent.setData(uri);
updateIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
currentActivity.startActivity(updateIntent);
UpdateState updateState =
UpdateState.builder()
.setApkBytesDownloaded(-1)
.setApkTotalBytesToDownload(-1)
.setUpdateStatus(UpdateStatus.REDIRECTED_TO_PLAY)
.build();
updateAppTaskCompletionSource.setResult(updateState);
this.updateTask.updateProgress(updateState);
}
private void showUpdateAlertDialog(AppDistributionRelease latestRelease) {
Context context = firebaseApp.getApplicationContext();
AlertDialog alertDialog = new AlertDialog.Builder(currentActivity).create();
alertDialog.setTitle(context.getString(R.string.update_dialog_title));
alertDialog.setMessage(
String.format(
"Version %s (%s) is available.",
latestRelease.getDisplayVersion(), latestRelease.getBuildVersion()));
alertDialog.setButton(
AlertDialog.BUTTON_POSITIVE,
context.getString(R.string.update_yes_button),
(dialogInterface, i) -> {
try {
updateApp()
.addOnSuccessListener(
updateState ->
updateToLatestReleaseTaskCompletionSource.setResult(latestRelease))
.addOnFailureListener(
e ->
setUpdateToLatestReleaseErrorWithDefault(
e,
new FirebaseAppDistributionException(
Constants.ErrorMessages.NETWORK_ERROR, NETWORK_FAILURE)));
} catch (FirebaseAppDistributionException e) {
setUpdateToLatestReleaseTaskCompletionError(e);
}
});
alertDialog.setButton(
AlertDialog.BUTTON_NEGATIVE,
context.getString(R.string.update_no_button),
(dialogInterface, i) -> {
dialogInterface.dismiss();
setUpdateToLatestReleaseTaskCompletionError(
new FirebaseAppDistributionException(
Constants.ErrorMessages.UPDATE_CANCELLED,
FirebaseAppDistributionException.Status.INSTALLATION_CANCELED));
});
alertDialog.show();
}
}
|
9243fa51dccc9907ada91c98471f1c2f5bb6e15a | 1,710 | java | Java | libraries/sql/src/main/java/org/apache/polygene/library/sql/datasource/DataSourceConfigurationState.java | apache/polygene-java | 031beef870302a0bd01bd5895ce849e00f2d5d5b | [
"MIT"
] | 60 | 2017-02-06T10:42:51.000Z | 2022-02-12T14:41:17.000Z | libraries/sql/src/main/java/org/apache/polygene/library/sql/datasource/DataSourceConfigurationState.java | DalavanCloud/attic-polygene-java | 031beef870302a0bd01bd5895ce849e00f2d5d5b | [
"MIT"
] | 3 | 2015-07-28T10:23:31.000Z | 2016-12-03T14:56:17.000Z | libraries/sql/src/main/java/org/apache/polygene/library/sql/datasource/DataSourceConfigurationState.java | DalavanCloud/attic-polygene-java | 031beef870302a0bd01bd5895ce849e00f2d5d5b | [
"MIT"
] | 17 | 2015-07-26T14:19:10.000Z | 2016-11-29T17:38:05.000Z | 38 | 76 | 0.751462 | 1,002,845 | /*
* 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.polygene.library.sql.datasource;
import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.common.UseDefaults;
import org.apache.polygene.api.configuration.Enabled;
import org.apache.polygene.api.property.Property;
/**
* Describe DataSourceConfiguration properties.
*/
// START SNIPPET: config
public interface DataSourceConfigurationState extends Enabled
{
Property<String> driver();
Property<String> url();
@UseDefaults Property<String> username();
@UseDefaults Property<String> password();
@Optional Property<Integer> minPoolSize();
@Optional Property<Integer> maxPoolSize();
@Optional Property<Integer> loginTimeoutSeconds();
@Optional Property<Integer> maxConnectionAgeSeconds();
@Optional Property<String> validationQuery();
@UseDefaults Property<String> properties();
}
// END SNIPPET: config
|
9243fa78508eb34e777d384667f6b5c182c716ab | 982 | java | Java | springfox-swagger-extension-core/src/main/java/com/talor/core/util/TypeUtils.java | luffytalory/srpingfox-swagger-extension | 0caf411b191d9f4b9a1a1bcb688ff1c9e4cd56a3 | [
"Apache-2.0"
] | 2 | 2020-02-10T08:37:32.000Z | 2020-02-10T08:37:35.000Z | springfox-swagger-extension-core/src/main/java/com/talor/core/util/TypeUtils.java | luffytalory/srpingfox-swagger-extension | 0caf411b191d9f4b9a1a1bcb688ff1c9e4cd56a3 | [
"Apache-2.0"
] | null | null | null | springfox-swagger-extension-core/src/main/java/com/talor/core/util/TypeUtils.java | luffytalory/srpingfox-swagger-extension | 0caf411b191d9f4b9a1a1bcb688ff1c9e4cd56a3 | [
"Apache-2.0"
] | null | null | null | 26.540541 | 82 | 0.677189 | 1,002,846 | package com.talor.core.util;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static springfox.documentation.schema.Types.typeNameFor;
/**
* @author luffy
* @version 1.0
* @className TypeUtils
* @description TODO
*/
public class TypeUtils {
public static boolean isContainerType(Class type) {
return List.class.isAssignableFrom(type) ||
Set.class.isAssignableFrom(type) ||
(Collection.class.isAssignableFrom(type) && !isMapType(type)) ||
type.isArray();
}
public static boolean isBaseType(Class type) {
return springfox.documentation.schema.Types.isBaseType(typeNameFor(type));
}
public static boolean isMapType(Class type) {
return Map.class.isAssignableFrom(type);
}
public static boolean isComplexObjectType(Class<?> type) {
return !isContainerType(type) && !isBaseType(type) && !isMapType(type);
}
}
|
9243fed835f9625aa93c9d688f475a94bab61c40 | 2,181 | java | Java | src/main/java/com/diguage/algorithm/leetcode/_0042_TrappingRainWater.java | diguage/leetcode | e72299539a319c94b435ff26cf077371a353b00c | [
"Apache-2.0"
] | 4 | 2020-02-05T10:08:43.000Z | 2021-06-10T02:15:20.000Z | src/main/java/com/diguage/algorithm/leetcode/_0042_TrappingRainWater.java | diguage/leetcode | e72299539a319c94b435ff26cf077371a353b00c | [
"Apache-2.0"
] | 1,062 | 2018-10-04T16:04:06.000Z | 2020-06-17T02:11:44.000Z | src/main/java/com/diguage/algorithm/leetcode/_0042_TrappingRainWater.java | diguage/leetcode | e72299539a319c94b435ff26cf077371a353b00c | [
"Apache-2.0"
] | 3 | 2019-10-03T01:42:58.000Z | 2020-03-02T13:53:02.000Z | 36.35 | 271 | 0.565337 | 1,002,847 | package com.diguage.algorithm.leetcode;
/**
* = 42. Trapping Rain Water
*
* https://leetcode.com/problems/trapping-rain-water/[Trapping Rain Water - LeetCode]
*
* Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
*
* image::https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png[title="The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!"]
*
* .Example:
* [source]
* ----
* Input: [0,1,0,2,1,0,1,3,2,1,2,1]
* Output: 6
* ----
*
* @author D瓜哥, https://www.diguage.com/
* @since 2019-07-26 08:49
*/
public class _0042_TrappingRainWater {
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Trapping Rain Water.
* Memory Usage: 38.3 MB, less than 91.10% of Java online submissions for Trapping Rain Water.
*
* Copy from: https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/[详细通俗的思路分析,多解法 - 接雨水 - 力扣(LeetCode)]
*/
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int result = 0;
int leftMax = 0, rightMax = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
result += (leftMax - height[left]);
}
++left;
} else {
if (height[right] > rightMax) {
rightMax = height[right];
} else {
result += (rightMax - height[right]);
}
--right;
}
}
return result;
}
public static void main(String[] args) {
_0042_TrappingRainWater solution = new _0042_TrappingRainWater();
int r1 = solution.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1});
System.out.println((r1 == 6) + " : " + r1);
}
}
|
9243ff1caecce4511db11b5691343ef22dd344f8 | 1,500 | java | Java | gm-incubator/algorithms/src/main/java/demo/algorithms/sort/DivideAndConquer.java | bluzioo/GoingMerry | 85da9bca3cb503c85677a5868690c091d7103bb3 | [
"Apache-2.0"
] | 3 | 2018-03-29T13:12:31.000Z | 2018-04-19T02:38:02.000Z | gm-incubator/algorithms/src/main/java/demo/algorithms/sort/DivideAndConquer.java | bluzioo/GoingMerry | 85da9bca3cb503c85677a5868690c091d7103bb3 | [
"Apache-2.0"
] | null | null | null | gm-incubator/algorithms/src/main/java/demo/algorithms/sort/DivideAndConquer.java | bluzioo/GoingMerry | 85da9bca3cb503c85677a5868690c091d7103bb3 | [
"Apache-2.0"
] | null | null | null | 20.833333 | 69 | 0.433333 | 1,002,848 | package demo.algorithms.sort;
import demo.algorithms.RandomArray;
import java.util.Arrays;
import static demo.algorithms.Print.println;
/**
* 分治法
*/
public class DivideAndConquer {
public static void merge (int[] arr, int p, int q, int r) {
int n1 = q-p+1;
int n2 = r-q;
int[] left = new int[n1+1];
int[] right = new int[n2+1];
for (int i=0; i<n1; i++) {
left[i] = arr[p+i];
}
for (int i=0; i<n2; i++) {
right[i] = arr[q+i+1];
}
left[n1] = Integer.MAX_VALUE;
right[n2] = Integer.MAX_VALUE;
int i = 0;
int j = 0;
while(p <= r) {
if (left[i] <= right[j]) {
arr[p] = left[i];
i++;
} else {
arr[p] = right[j];
j++;
}
p++;
}
}
public static void sort(int[] arr, int p, int r) {
if (p<r){
int q = (p+r)/2;
sort(arr, p, q);
sort(arr, q+1, r);
merge(arr, p, q, r);
}
}
public static void main(String[] args) {
int[] arr = RandomArray.random(1000000);
long start = System.currentTimeMillis();
sort(arr, 0, arr.length-1);
println("taken time: " + (System.currentTimeMillis()-start));
for(int i=0; i<arr.length-1; i++) {
if(arr[i] > arr[i+1]){
println(false);
}
}
}
}
|
9243ff91a2ceb633744d9e8f1bd66eb375c73ad7 | 311 | java | Java | ironhoist-container-core/src/main/java/com/github/codeteapot/ironhoist/container/descriptor/PlatformPlugin.java | codeteapot/ironhoist-container | 71d2dfee71bfc0d43a09e598a16fc2e789402bac | [
"Apache-2.0"
] | null | null | null | ironhoist-container-core/src/main/java/com/github/codeteapot/ironhoist/container/descriptor/PlatformPlugin.java | codeteapot/ironhoist-container | 71d2dfee71bfc0d43a09e598a16fc2e789402bac | [
"Apache-2.0"
] | 2 | 2022-02-23T22:25:47.000Z | 2022-02-28T20:47:31.000Z | ironhoist-container-core/src/main/java/com/github/codeteapot/ironhoist/container/descriptor/PlatformPlugin.java | codeteapot/ironhoist-container | 71d2dfee71bfc0d43a09e598a16fc2e789402bac | [
"Apache-2.0"
] | null | null | null | 18.294118 | 61 | 0.675241 | 1,002,849 | package com.github.codeteapot.ironhoist.container.descriptor;
/**
* Platform plug-in.
*/
public interface PlatformPlugin {
/**
* Add a bean of this plug-in.
*
* @param className Class name of the bean.
*
* @return The bean object builder.
*/
ObjectBuilder addBean(String className);
}
|
9243ffc8ea2882705e849e8a74f2c23e8b54ddca | 1,246 | java | Java | bigquery-connector-common/src/main/java/com/google/cloud/bigquery/connector/common/BigQueryConfig.java | himanshukohli09/spark-bigquery-connector | 1221996f88b54970f8f3d3ed2d68b72dfd9d3eee | [
"Apache-2.0"
] | 135 | 2020-02-03T09:54:47.000Z | 2022-03-24T20:58:05.000Z | bigquery-connector-common/src/main/java/com/google/cloud/bigquery/connector/common/BigQueryConfig.java | himanshukohli09/spark-bigquery-connector | 1221996f88b54970f8f3d3ed2d68b72dfd9d3eee | [
"Apache-2.0"
] | 472 | 2020-01-16T00:11:39.000Z | 2022-03-31T20:53:54.000Z | bigquery-connector-common/src/main/java/com/google/cloud/bigquery/connector/common/BigQueryConfig.java | himanshukohli09/spark-bigquery-connector | 1221996f88b54970f8f3d3ed2d68b72dfd9d3eee | [
"Apache-2.0"
] | 93 | 2020-01-20T17:28:55.000Z | 2022-03-31T21:14:37.000Z | 27.688889 | 75 | 0.766453 | 1,002,850 | /*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery.connector.common;
import com.google.api.gax.retrying.RetrySettings;
import java.util.Optional;
public interface BigQueryConfig {
Optional<String> getCredentialsKey();
Optional<String> getCredentialsFile();
Optional<String> getAccessToken();
String getParentProjectId();
boolean isViewsEnabled();
Optional<String> getMaterializationProject();
Optional<String> getMaterializationDataset();
int getBigQueryClientConnectTimeout();
int getBigQueryClientReadTimeout();
RetrySettings getBigQueryClientRetrySettings();
BigQueryProxyConfig getBigQueryProxyConfig();
}
|
924400a535894f4f4c21db70fba1535815308080 | 1,703 | java | Java | cli/src/main/java/org/onosproject/cli/net/NeighbourHandlersListCommand.java | mary-grace/onos | c0e351f8b84537bb7562e148d4cb2b9f06e8a727 | [
"Apache-2.0"
] | 1,091 | 2015-01-06T11:10:40.000Z | 2022-03-30T09:09:05.000Z | cli/src/main/java/org/onosproject/cli/net/NeighbourHandlersListCommand.java | mary-grace/onos | c0e351f8b84537bb7562e148d4cb2b9f06e8a727 | [
"Apache-2.0"
] | 39 | 2015-02-13T19:58:32.000Z | 2022-03-02T02:38:07.000Z | cli/src/main/java/org/onosproject/cli/net/NeighbourHandlersListCommand.java | mary-grace/onos | c0e351f8b84537bb7562e148d4cb2b9f06e8a727 | [
"Apache-2.0"
] | 914 | 2015-01-05T19:42:35.000Z | 2022-03-30T09:25:18.000Z | 34.755102 | 83 | 0.716383 | 1,002,851 | /*
* 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.cli.net;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.intf.Interface;
import org.onosproject.net.neighbour.NeighbourResolutionService;
/**
* Lists neighbour message handlers.
*/
@Service
@Command(scope = "onos", name = "neighbour-handlers",
description = "Lists neighbour message handlers")
public class NeighbourHandlersListCommand extends AbstractShellCommand {
private static final String FORMAT = "%20s: interface=%s, class=%s";
@Override
protected void doExecute() {
NeighbourResolutionService service = get(NeighbourResolutionService.class);
service.getHandlerRegistrations().forEach((cp, list) -> {
list.forEach(hr -> print(FORMAT, cp, intfToName(hr.intf()),
hr.handler().getClass().getCanonicalName()));
});
}
private String intfToName(Interface intf) {
return (intf == null) ? "(None)" : intf.name();
}
}
|
9244037eada3312f69f9e9aff325280badebfb19 | 4,960 | java | Java | core/hdb/src/main/java/org/iipg/hurricane/db/HDocument.java | SagittariusZhu/hurricane | bc210d4c32143bcd70ea451d24195bce9f91c27f | [
"Apache-2.0"
] | null | null | null | core/hdb/src/main/java/org/iipg/hurricane/db/HDocument.java | SagittariusZhu/hurricane | bc210d4c32143bcd70ea451d24195bce9f91c27f | [
"Apache-2.0"
] | 2 | 2020-02-12T19:30:52.000Z | 2020-11-16T16:46:17.000Z | core/hdb/src/main/java/org/iipg/hurricane/db/HDocument.java | SagittariusZhu/hurricane | bc210d4c32143bcd70ea451d24195bce9f91c27f | [
"Apache-2.0"
] | null | null | null | 25.435897 | 157 | 0.665524 | 1,002,852 | package org.iipg.hurricane.db;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.iipg.hurricane.ParseFieldException;
import org.iipg.hurricane.db.metadata.*;
import org.iipg.hurricane.db.schema.Field;
import org.iipg.hurricane.db.schema.HTyper;
import org.iipg.hurricane.db.schema.Relation;
import org.iipg.hurricane.db.schema.SchemaParser;
import org.iipg.hurricane.model.HMWDocument;
import org.iipg.hurricane.util.HDocBuilder;
import org.iipg.hurricane.util.TypeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
public class HDocument {
private static final Logger LOG = LoggerFactory.getLogger(HDocument.class);
private Map<String, HDBBaseObject> record = null;
private String schemaName = "";
private SchemaParser parser = null;
public HDocument() {
record = new HashMap<String, HDBBaseObject>();
}
public String getSchemaName() {
return this.schemaName;
}
public SchemaParser getSchema() {
return this.parser;
}
public void setSchemaName(String schemaName) throws IOException, ParserConfigurationException, SAXException {
this.schemaName = schemaName;
parser = new SchemaParser(schemaName);
}
//Solr record
public HDBRecord getSolrObject() {
HDBRecord ro = (HDBRecord) record.get("ro");
return ro;
}
public void setROObject(HDBRecord ro) {
record.put("ro", ro);
}
//Raw byte array
public HDBBlob getBlobObject() {
HDBBlob blob = (HDBBlob) record.get("blob");
return blob;
}
public void setBlobObject(HDBBlob blob) {
record.put("blob", blob);
}
public void setUniqueKey(Object uniqueValue) {
String uniqueKey = parser.getUniqueKey().getName();
HDBRecord ro = getSolrObject();
if (ro != null) {
ro.put(uniqueKey, uniqueValue);
}
}
public static HDocument parse(HMWDocument record) throws IOException, ParserConfigurationException, SAXException {
Map pro = HDocBuilder.parse(record.dict);
HDBBlob blob = new HDBBlob();
if (record.blob != null) {
blob.setBlob(record.blob);
}
return parse(pro, blob, record.schema);
}
public static HDocument parse(Map<String, Object> dataMap, HDBBlob blob, String schemaName) throws IOException, ParserConfigurationException, SAXException {
HDocument doc = new HDocument();
doc.setSchemaName(schemaName);
Object uuid = null;
HDBRecord ro = new HDBRecord();
HDBRecord rw = new HDBRecord();
HDBSRShip cr = null;
HDBTShip er = null;
Relation relation1 = doc.getSchema().getRelation("send_receive");
if (relation1 != null)
cr = new HDBSRShip();
Relation relation2 = doc.getSchema().getRelation("together");
if (relation2 != null)
er = new HDBTShip();
Iterator iter = dataMap.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
// inner field, ignore it
if (key.equalsIgnoreCase("signature")) continue;
//Skip System reverse keyword
if (key.startsWith("__")) {
continue;
}
if (key.indexOf("\\.") >= 0) {
String[] arr = key.split("\\.");
key = arr[0];
}
Object value = dataMap.get(key);
LOG.debug(key + ":" + value);
Field field = null;
field = doc.getSchema().getField(key);
if (field == null) {
field = doc.getSchema().getDynamicField(key);
}
if (field == null) {
String msg = "Not defined field: " + key;
LOG.warn(msg);
throw new ParseFieldException(msg);
}
String type = field.getType();
if (HTyper.isExtType(type)) {
try {
HTyper typer = HTyper.getTyper(field);
ro.push(key, typer.run(value));
if (typer.hasBinary()) {
blob.addExt(key, typer.getBinary());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
} else {
//TODO: check whether value type is matched fieldType
if (!TypeUtil.isType(value, type)) {
String msg = "Type match failed: " + type + " - " + value;
LOG.warn(msg);
throw new ParseFieldException(msg);
}
}
if(field.isUnique()) {
uuid = value;
ro.push(key, value);
rw.push(key, value);
blob.setUuid(uuid);
continue;
}
String mode = field.getMode();
if (mode == null) {
ro.push(key, value);
} else if (mode.equalsIgnoreCase("ro")) {
ro.push(key, value);
} else {
LOG.warn("未知存储方式:" + key);
continue;
}
// if (relation1 != null) {
// cr.setType(type);
// if (relation1.getFrom().equalsIgnoreCase(key))
// cr.setSnode((String) value);
// if (relation1.getTo().equalsIgnoreCase(key))
// cr.setEnode((String) value);
// }
//
// if (relation2 != null) {
// er.setType(type);
// if (relation2.getField().endsWith(key))
// er.setContent_entity((String) value);
// }
}
doc.setROObject(ro);
doc.setBlobObject(blob);
return doc;
}
}
|
924403c4676c879838363c84ce409d11f9a7dbba | 2,913 | java | Java | src/main/java/tanks/event/EventBulletAddAttributeModifier.java | Panadero1/Tanks | 23f258acacb25a441b2632cae38097785ed1abbd | [
"MIT"
] | 20 | 2018-11-18T18:15:25.000Z | 2022-02-23T21:37:14.000Z | src/main/java/tanks/event/EventBulletAddAttributeModifier.java | Panadero1/Tanks | 23f258acacb25a441b2632cae38097785ed1abbd | [
"MIT"
] | 13 | 2021-06-23T04:19:09.000Z | 2022-02-05T16:55:19.000Z | src/main/java/tanks/event/EventBulletAddAttributeModifier.java | Panadero1/Tanks | 23f258acacb25a441b2632cae38097785ed1abbd | [
"MIT"
] | 16 | 2018-12-08T05:10:29.000Z | 2022-03-22T04:38:04.000Z | 27.742857 | 94 | 0.616547 | 1,002,853 | package tanks.event;
import io.netty.buffer.ByteBuf;
import tanks.AttributeModifier;
import tanks.bullet.Bullet;
import tanks.network.NetworkUtils;
public class EventBulletAddAttributeModifier extends PersonalEvent
{
public int bullet;
public String name;
public double duration = 0;
public double deteriorationAge = 0;
public double warmupAge = 0;
public double value;
public String effect;
public double age;
public String type;
public boolean expired;
public boolean unduplicate;
public EventBulletAddAttributeModifier()
{
}
public EventBulletAddAttributeModifier(Bullet b, AttributeModifier m, boolean unduplicate)
{
this.bullet = b.networkID;
this.name = m.name;
this.duration = m.duration;
this.deteriorationAge = m.deteriorationAge;
this.warmupAge = m.warmupAge;
this.value = m.value;
this.effect = m.effect.toString();
this.age = m.age;
this.type = m.type;
this.expired = m.expired;
this.unduplicate = unduplicate;
}
@Override
public void write(ByteBuf b)
{
b.writeInt(this.bullet);
NetworkUtils.writeString(b, this.name);
b.writeDouble(this.duration);
b.writeDouble(this.deteriorationAge);
b.writeDouble(this.warmupAge);
b.writeDouble(this.value);
NetworkUtils.writeString(b, this.effect);
b.writeDouble(this.age);
NetworkUtils.writeString(b, this.type);
b.writeBoolean(this.expired);
b.writeBoolean(this.unduplicate);
}
@Override
public void read(ByteBuf b)
{
this.bullet = b.readInt();
this.name = NetworkUtils.readString(b);
this.duration = b.readDouble();
this.deteriorationAge = b.readDouble();
this.warmupAge = b.readDouble();
this.value = b.readDouble();
this.effect = NetworkUtils.readString(b);
this.age = b.readDouble();
this.type = NetworkUtils.readString(b);
this.expired = b.readBoolean();
this.unduplicate = b.readBoolean();
}
@Override
public void execute()
{
Bullet b = Bullet.idMap.get(this.bullet);
if (b != null && this.clientID == null)
{
AttributeModifier.Operation o = AttributeModifier.Operation.add;
if (this.effect.equals("multiply"))
o = AttributeModifier.Operation.multiply;
AttributeModifier m = new AttributeModifier(this.name, this.type, o, this.value);
m.duration = this.duration;
m.deteriorationAge = this.deteriorationAge;
m.warmupAge = this.warmupAge;
m.age = this.age;
m.expired = this.expired;
if (unduplicate)
b.addUnduplicateAttribute(m);
else
b.addAttribute(m);
}
}
}
|
924403ef0d26a60d5a0c595f1edc1284825c90b5 | 1,394 | java | Java | src/main/java/com/opteral/springsms/config/RootConfig.java | amalio/spring-json-sms-gateway | a29c374efe709f41e46bfd1a29dcae6ffc1aea7d | [
"Unlicense"
] | 11 | 2015-09-02T05:14:15.000Z | 2021-12-06T03:53:45.000Z | src/main/java/com/opteral/springsms/config/RootConfig.java | amalio/spring-json-sms-gateway | a29c374efe709f41e46bfd1a29dcae6ffc1aea7d | [
"Unlicense"
] | 1 | 2017-01-31T12:52:03.000Z | 2017-01-31T12:52:03.000Z | src/main/java/com/opteral/springsms/config/RootConfig.java | amalio/spring-json-sms-gateway | a29c374efe709f41e46bfd1a29dcae6ffc1aea7d | [
"Unlicense"
] | 19 | 2016-08-01T04:54:48.000Z | 2022-03-30T16:13:44.000Z | 24.892857 | 76 | 0.674319 | 1,002,854 | package com.opteral.springsms.config;
import com.opteral.springsms.Utilities;
import org.jsmpp.session.SMPPSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.annotation.PostConstruct;
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan(basePackages={"com.opteral.springsms"},
excludeFilters={
@Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)
})
public class RootConfig {
@Bean
public LoggerAOP loggerAOP(){
return new LoggerAOP();
}
@Bean
public SMPPSession sMPPSession(){
return new SMPPSession();
}
@Autowired
Environment env;
@PostConstruct
public void init()
{
try {
Utilities.getConfig(isTest());
}
catch (Exception e)
{
throw new RuntimeException("Failed loading configuration file");
}
}
private boolean isTest()
{
String[] profiles = env.getActiveProfiles();
for (String profile : profiles){
if (profile.equals("test"))
return true;
}
return false;
}
}
|
9244041c2e280e40504282941f9f79c474a8a7f4 | 1,416 | java | Java | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/js/generic/expression/PrimitiveValueExpression.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 14 | 2019-10-09T23:59:32.000Z | 2022-03-01T08:34:56.000Z | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/js/generic/expression/PrimitiveValueExpression.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 1,549 | 2019-08-16T01:07:16.000Z | 2022-03-31T23:57:34.000Z | Platform/Plugins/com.tle.web.sections/src/com/tle/web/sections/js/generic/expression/PrimitiveValueExpression.java | mrblippy/Charliequella | f4d233d8e42dd72935b80c2abea06efb20cea989 | [
"Apache-2.0"
] | 24 | 2019-09-05T00:09:35.000Z | 2021-10-19T05:10:39.000Z | 31.466667 | 91 | 0.752825 | 1,002,855 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.sections.js.generic.expression;
import com.tle.web.sections.js.ServerSideValue;
public class PrimitiveValueExpression extends ScriptExpression implements ServerSideValue {
public PrimitiveValueExpression(int expr) {
super(Integer.toString(expr));
}
public PrimitiveValueExpression(long expr) {
super(Long.toString(expr));
}
public PrimitiveValueExpression(double expr) {
super(Double.toString(expr));
}
public PrimitiveValueExpression(boolean expr) {
super(Boolean.toString(expr));
}
@Override
public String getJavaString() {
return expr;
}
}
|
9244046094bf6dd68826bfa6daf1758dc391009b | 50,610 | java | Java | src/test/java/io/geekstore/e2e/OrderPromotionTest.java | spring2go/geekstore | ee16678ee6de5c26f8c7231c2a1961ba4ba857a2 | [
"MIT"
] | 10 | 2021-09-16T16:00:38.000Z | 2022-02-25T11:33:21.000Z | src/test/java/io/geekstore/e2e/OrderPromotionTest.java | spring2go/geekstore | ee16678ee6de5c26f8c7231c2a1961ba4ba857a2 | [
"MIT"
] | null | null | null | src/test/java/io/geekstore/e2e/OrderPromotionTest.java | spring2go/geekstore | ee16678ee6de5c26f8c7231c2a1961ba4ba857a2 | [
"MIT"
] | 5 | 2021-09-17T11:58:21.000Z | 2021-09-18T01:23:23.000Z | 43.180034 | 119 | 0.705238 | 1,002,856 | /*
* Copyright (c) 2020 GeekStore.
* All rights reserved.
*/
package io.geekstore.e2e;
import io.geekstore.*;
import io.geekstore.config.TestConfig;
import io.geekstore.config.payment.TestSuccessfulPaymentMethod;
import io.geekstore.config.payment_method.PaymentMethodHandler;
import io.geekstore.config.payment_method.PaymentOptions;
import io.geekstore.config.promotion.actions.FacetValuesDiscountAction;
import io.geekstore.config.promotion.actions.OrderPercentageDiscount;
import io.geekstore.config.promotion.actions.ProductDiscountAction;
import io.geekstore.config.promotion.conditions.ContainsProductsCondition;
import io.geekstore.config.promotion.conditions.CustomerGroupCondition;
import io.geekstore.config.promotion.conditions.HasFacetValuesCondition;
import io.geekstore.config.promotion.conditions.MinimumOrderAmountCondition;
import io.geekstore.service.helpers.order_state_machine.OrderState;
import io.geekstore.types.common.AdjustmentType;
import io.geekstore.types.common.ConfigArgInput;
import io.geekstore.types.common.ConfigurableOperationInput;
import io.geekstore.types.common.CreateCustomerInput;
import io.geekstore.types.customer.CreateCustomerGroupInput;
import io.geekstore.types.customer.Customer;
import io.geekstore.types.customer.CustomerGroup;
import io.geekstore.types.customer.CustomerList;
import io.geekstore.types.facet.FacetList;
import io.geekstore.types.facet.FacetValue;
import io.geekstore.types.history.HistoryEntry;
import io.geekstore.types.history.HistoryEntryType;
import io.geekstore.types.order.Order;
import io.geekstore.types.order.OrderLine;
import io.geekstore.types.product.Product;
import io.geekstore.types.product.ProductList;
import io.geekstore.types.product.ProductListOptions;
import io.geekstore.types.product.ProductVariant;
import io.geekstore.types.promotion.CreatePromotionInput;
import io.geekstore.types.promotion.Promotion;
import io.geekstore.utils.TestHelper;
import io.geekstore.utils.TestOrderUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import com.graphql.spring.boot.test.GraphQLResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.annotation.DirtiesContext;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import static org.assertj.core.api.Assertions.*;
/**
* Created on Dec, 2020 by @author bobo
*/
@GeekStoreGraphQLTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@DirtiesContext
public class OrderPromotionTest {
static final String ADMIN_ORDER_GRAPHQL_RESOURCE_TEMPLATE = "graphql/admin/order/%s.graphqls";
static final String GET_PROMO_PRODUCTS =
String.format(ADMIN_ORDER_GRAPHQL_RESOURCE_TEMPLATE, "get_promo_products");
static final String DELETE_PROMOTION =
String.format(ADMIN_ORDER_GRAPHQL_RESOURCE_TEMPLATE, "delete_promotion");
static final String SHARED_GRAPHQL_RESOURCE_TEMPLATE = "graphql/shared/%s.graphqls";
static final String FACET_WITH_VALUES_FRAGMENT =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "facet_with_values_fragment");
static final String FACET_VALUE_FRAGMENT =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "facet_value_fragment");
static final String GET_FACET_LIST =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "get_facet_list");
static final String CREATE_PROMOTION =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "create_promotion");
static final String PROMOTION_FRAGMENT =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "promotion_fragment");
static final String CONFIGURABLE_FRAGMENT =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "configurable_fragment");
static final String CREATE_CUSTOMER_GROUP =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "create_customer_group");
static final String CUSTOMER_GROUP_FRAGMENT =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "customer_group_fragment");
static final String GET_CUSTOMER_LIST =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "get_customer_list");
static final String REMOVE_CUSTOMERS_FROM_GROUP =
String.format(SHARED_GRAPHQL_RESOURCE_TEMPLATE, "remove_customers_from_group");
static final String SHOP_GRAPHQL_RESOURCE_TEMPLATE = "graphql/shop/%s.graphqls";
static final String ADD_ITEM_TO_ORDER =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "add_item_to_order");
static final String APPLY_COUPON_CODE =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "apply_coupon_code");
static final String TEST_ORDER_FRAGMENT =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "test_order_fragment");
static final String GET_ACTIVE_ORDER =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "get_active_order");
static final String REMOVE_COUPON_CODE =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "remove_coupon_code");
static final String ADJUST_ITEM_QUANTITY =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "adjust_item_quantity");
static final String SET_CUSTOMER =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "set_customer");
static final String GET_ORDER_PROMOTIONS_BY_CODE =
String.format(SHOP_GRAPHQL_RESOURCE_TEMPLATE, "get_order_promotions_by_code");
@Autowired
TestHelper testHelper;
@Autowired
TestOrderUtils testOrderUtils;
@Autowired
@Qualifier(TestConfig.ADMIN_CLIENT_BEAN)
ApiClient adminClient;
@Autowired
@Qualifier(TestConfig.SHOP_CLIENT_BEAN)
ApiClient shopClient;
@Autowired
ObjectMapper objectMapper;
@Autowired
MockDataService mockDataService;
@Autowired
PaymentOptions paymentOptions;
@Autowired
MinimumOrderAmountCondition minimumOrderAmount;
@Autowired
OrderPercentageDiscount orderPercentageDiscount;
@Autowired
HasFacetValuesCondition hasFacetValuesCondition;
@Autowired
ContainsProductsCondition containsProductsCondition;
@Autowired
CustomerGroupCondition customerGroupCondition;
@Autowired
FacetValuesDiscountAction facetValuesDiscountAction;
@Autowired
ProductDiscountAction productDiscountAction;
PaymentMethodHandler testSuccessfulPaymentMethod;
List<Product> products;
List<Customer> customers;
String password = MockDataService.TEST_PASSWORD;
@TestConfiguration
static class ContextConfiguration {
@Bean
@Primary
public PaymentOptions testPaymentOptions() {
return new PaymentOptions(
Arrays.asList(
new TestSuccessfulPaymentMethod()
)
);
}
}
@BeforeAll
void beforeAll() throws IOException {
PopulateOptions populateOptions = PopulateOptions.builder().customerCount(2).build();
populateOptions.setInitialData(testHelper.getInitialData());
populateOptions.setProductCsvPath(testHelper.getTestFixture("e2e-products-promotions.csv"));
mockDataService.populate(populateOptions);
adminClient.asSuperAdmin();
GraphQLResponse graphQLResponse = adminClient.perform(
GET_CUSTOMER_LIST, null);
CustomerList customerList = graphQLResponse.get("$.data.customers", CustomerList.class);
customers = customerList.getItems();
testSuccessfulPaymentMethod = paymentOptions.getPaymentMethodHandlers().get(0);
getProducts();
createGlobalPromotions();
}
/**
* coupon codes test casese
*/
final String TEST_COUPON_CODE = "TESTCOUPON";
final String EXPIRED_COUPON_CODE = "EXPIRED";
Promotion promoFreeWithCoupon;
Promotion promoFreeWithExpiredCoupon;
private void before_test_01() throws IOException {
CreatePromotionInput input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Free with test coupon");
input.setCouponCode(TEST_COUPON_CODE);
input.getActions().add(getFreeOrderAction());
promoFreeWithCoupon = createPromotion(input);
input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Expired coupon");
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 0, 1);
input.setStartsAt(calendar.getTime());
input.setEndsAt(calendar.getTime());
input.setCouponCode(EXPIRED_COUPON_CODE);
input.getActions().add(getFreeOrderAction());
promoFreeWithExpiredCoupon = createPromotion(input);
shopClient.asAnonymousUser();
ProductVariant item60 = getVariantBySlug("item-60");
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", item60.getId());
variables.put("quantity", 1);
shopClient.perform(ADD_ITEM_TO_ORDER, variables);
}
@Test
@org.junit.jupiter.api.Order(1)
public void applyCouponCode_throws_with_nonexistant_code() throws IOException {
before_test_01();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", "bad code");
try {
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
fail("should have thrown");
} catch (ApiException apiEx) {
assertThat(apiEx.getErrorMessage()).isEqualTo(
"Coupon code \"{ bad code }\" is not valid"
);
}
}
@Test
@org.junit.jupiter.api.Order(2)
public void applyCouponCode_throws_with_expired_code() throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", EXPIRED_COUPON_CODE);
try {
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
fail("should have thrown");
} catch (ApiException apiEx) {
assertThat(apiEx.getErrorMessage()).isEqualTo(
"Coupon code \"{ " + EXPIRED_COUPON_CODE + " }\" has expired"
);
}
}
@Test
@org.junit.jupiter.api.Order(3)
public void apply_a_valid_coupon_code() throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getCouponCodes()).containsExactly(TEST_COUPON_CODE);
assertThat(order.getAdjustments()).hasSize(1);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo("Free with test coupon");
assertThat(order.getTotal()).isEqualTo(0);
}
@Test
@org.junit.jupiter.api.Order(4)
public void order_history_records_application() throws IOException {
GraphQLResponse graphQLResponse =
shopClient.perform(GET_ACTIVE_ORDER, null, Arrays.asList(TEST_ORDER_FRAGMENT));
Order activeOrder = graphQLResponse.get("$.data.activeOrder", Order.class);
assertThat(activeOrder.getHistory().getItems()).hasSize(1);
HistoryEntry historyEntry = activeOrder.getHistory().getItems().get(0);
assertThat(historyEntry.getType()).isEqualTo(HistoryEntryType.ORDER_COUPON_APPLIED);
assertThat(historyEntry.getData()).containsExactlyInAnyOrderEntriesOf(
ImmutableMap.of("couponCode", TEST_COUPON_CODE, "promotionId", "3")
);
}
@Test
@org.junit.jupiter.api.Order(5)
public void de_duplicates_existing_codes() throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getCouponCodes()).containsExactly(TEST_COUPON_CODE);
}
@Test
@org.junit.jupiter.api.Order(6)
public void removes_a_coupon_code() throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(REMOVE_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.removeCouponCode", Order.class);
assertThat(order.getAdjustments()).hasSize(0);
assertThat(order.getTotal()).isEqualTo(5000);
}
@Test
@org.junit.jupiter.api.Order(7)
public void order_history_records_removal() throws IOException {
GraphQLResponse graphQLResponse =
shopClient.perform(GET_ACTIVE_ORDER, null, Arrays.asList(TEST_ORDER_FRAGMENT));
Order activeOrder = graphQLResponse.get("$.data.activeOrder", Order.class);
assertThat(activeOrder.getHistory().getItems()).hasSize(2);
HistoryEntry historyEntry1 = activeOrder.getHistory().getItems().get(0);
assertThat(historyEntry1.getType()).isEqualTo(HistoryEntryType.ORDER_COUPON_APPLIED);
assertThat(historyEntry1.getData()).containsExactlyInAnyOrderEntriesOf(
ImmutableMap.of("couponCode", TEST_COUPON_CODE, "promotionId", "3")
);
HistoryEntry historyEntry2 = activeOrder.getHistory().getItems().get(1);
assertThat(historyEntry2.getType()).isEqualTo(HistoryEntryType.ORDER_COUPON_REMOVED);
assertThat(historyEntry2.getData()).containsExactlyInAnyOrderEntriesOf(
ImmutableMap.of("couponCode", TEST_COUPON_CODE)
);
}
@Test
@org.junit.jupiter.api.Order(8)
public void does_not_record_removal_of_coupon_code_that_was_not_added() throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", "NOT_THERE");
GraphQLResponse graphQLResponse =
shopClient.perform(REMOVE_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.removeCouponCode", Order.class);
assertThat(order.getHistory().getItems()).hasSize(2);
HistoryEntry historyEntry1 = order.getHistory().getItems().get(0);
assertThat(historyEntry1.getType()).isEqualTo(HistoryEntryType.ORDER_COUPON_APPLIED);
assertThat(historyEntry1.getData()).containsExactlyInAnyOrderEntriesOf(
ImmutableMap.of("couponCode", TEST_COUPON_CODE, "promotionId", "3")
);
HistoryEntry historyEntry2 = order.getHistory().getItems().get(1);
assertThat(historyEntry2.getType()).isEqualTo(HistoryEntryType.ORDER_COUPON_REMOVED);
assertThat(historyEntry2.getData()).containsExactlyInAnyOrderEntriesOf(
ImmutableMap.of("couponCode", TEST_COUPON_CODE)
);
// end coupon codes test cases
deletePromotion(promoFreeWithCoupon.getId());
deletePromotion(promoFreeWithExpiredCoupon.getId());
}
/**
* default PromotionConditions test cases
*/
@Test
@org.junit.jupiter.api.Order(9)
public void minimumOrderAmount() throws IOException {
shopClient.asAnonymousUser();
CreatePromotionInput input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Free if order total greater than 100");
input.getConditions().add(getMinOrderAmountCondition(10000));
input.getActions().add(getFreeOrderAction());
Promotion promotion = createPromotion(input);
ProductVariant item60 = getVariantBySlug("item-60");
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", item60.getId());
variables.put("quantity", 1);
GraphQLResponse graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getTotal()).isEqualTo(5000);
assertThat(order.getAdjustments()).isEmpty();
variables = objectMapper.createObjectNode();
variables.put("orderLineId", order.getLines().get(0).getId());
variables.put("quantity", 2);
graphQLResponse = shopClient.perform(ADJUST_ITEM_QUANTITY, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.adjustOrderLine", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo(
"Free if order total greater than 100"
);
assertThat(order.getAdjustments().get(0).getAmount()).isEqualTo(-10000);
deletePromotion(promotion.getId());
}
@Test
@org.junit.jupiter.api.Order(10)
public void atLeastNWithFacets() throws IOException {
shopClient.asAnonymousUser();
GraphQLResponse graphQLResponse =
adminClient.perform(
GET_FACET_LIST, null, Arrays.asList(FACET_VALUE_FRAGMENT, FACET_WITH_VALUES_FRAGMENT));
FacetList facetList = graphQLResponse.get("$.data.facets", FacetList.class);
FacetValue saleFacetValue = facetList.getItems().get(0).getValues().get(0);
CreatePromotionInput input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Free if order contains 2 items with Sale facet value");
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(hasFacetValuesCondition.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("minimum");
configArgInput.setValue("2");
configurableOperationInput.getArguments().add(configArgInput);
configArgInput = new ConfigArgInput();
configArgInput.setName("facets");
configArgInput.setValue("[\"" + saleFacetValue.getId() + "\"]");
configurableOperationInput.getArguments().add(configArgInput);
input.getConditions().add(configurableOperationInput);
input.getActions().add(getFreeOrderAction());
Promotion promotion = createPromotion(input);
ProductVariant itemSale1 = getVariantBySlug("item-sale-1");
ProductVariant itemSale12 = getVariantBySlug("item-sale-12");
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", itemSale1.getId());
variables.put("quantity", 1);
graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getTotal()).isEqualTo(100);
assertThat(order.getAdjustments()).isEmpty();
variables = objectMapper.createObjectNode();
variables.put("productVariantId", itemSale12.getId());
variables.put("quantity", 1);
graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getAdjustments()).hasSize(1);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo(
"Free if order contains 2 items with Sale facet value"
);
assertThat(order.getAdjustments().get(0).getAmount()).isEqualTo(-1100);
deletePromotion(promotion.getId());
}
@Test
@org.junit.jupiter.api.Order(11)
public void containsProducts() throws IOException {
shopClient.asAnonymousUser();
ProductVariant item60 = getVariantBySlug("item-60");
ProductVariant item12 = getVariantBySlug("item-12");
CreatePromotionInput input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Free if buying 3 or more offer products");
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(containsProductsCondition.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("minimum");
configArgInput.setValue("3");
configurableOperationInput.getArguments().add(configArgInput);
configArgInput = new ConfigArgInput();
configArgInput.setName("productVariantIds");
configArgInput.setValue(objectMapper.writeValueAsString(Arrays.asList(item60.getId(), item12.getId())));
configurableOperationInput.getArguments().add(configArgInput);
input.getConditions().add(configurableOperationInput);
input.getActions().add(getFreeOrderAction());
Promotion promotion = createPromotion(input);
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", item60.getId());
variables.put("quantity", 1);
shopClient.perform(ADD_ITEM_TO_ORDER, variables);
variables = objectMapper.createObjectNode();
variables.put("productVariantId", item12.getId());
variables.put("quantity", 1);
GraphQLResponse graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getTotal()).isEqualTo(6000);
assertThat(order.getAdjustments()).isEmpty();
variables = objectMapper.createObjectNode();
variables.put("orderLineId", order.getLines().get(0).getId());
variables.put("quantity", 2);
graphQLResponse = shopClient.perform(ADJUST_ITEM_QUANTITY, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.adjustOrderLine", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo(
"Free if buying 3 or more offer products"
);
assertThat(order.getAdjustments().get(0).getAmount()).isEqualTo(-11000);
deletePromotion(promotion.getId());
}
@Test
@org.junit.jupiter.api.Order(12)
public void customerGroup() throws IOException {
shopClient.asAnonymousUser();
CreateCustomerGroupInput input = new CreateCustomerGroupInput();
input.setName("Test Group");
input.getCustomerIds().add(customers.get(0).getId());
JsonNode inputNode = objectMapper.valueToTree(input);
ObjectNode variables = objectMapper.createObjectNode();
variables.set("input", inputNode);
GraphQLResponse graphQLResponse = adminClient.perform(
CREATE_CUSTOMER_GROUP, variables, Arrays.asList(CUSTOMER_GROUP_FRAGMENT));
CustomerGroup createdCustomerGroup =
graphQLResponse.get("$.data.createCustomerGroup", CustomerGroup.class);
shopClient.asUserWithCredentials(customers.get(0).getEmailAddress(), password);
CreatePromotionInput createPromotionInput = new CreatePromotionInput();
createPromotionInput.setEnabled(true);
createPromotionInput.setName("Free for group members");
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(customerGroupCondition.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("customerGroupId");
configArgInput.setValue(createdCustomerGroup.getId().toString());
configurableOperationInput.getArguments().add(configArgInput);
createPromotionInput.getConditions().add(configurableOperationInput);
createPromotionInput.getActions().add(getFreeOrderAction());
Promotion promotion = createPromotion(createPromotionInput);
variables = objectMapper.createObjectNode();
variables.put("productVariantId", getVariantBySlug("item-60").getId());
variables.put("quantity", 1);
graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getAdjustments()).hasSize(1);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo("Free for group members");
assertThat(order.getAdjustments().get(0).getAmount()).isEqualTo(-5000);
variables = objectMapper.createObjectNode();
variables.put("groupId", createdCustomerGroup.getId());
variables.putArray("customerIds").add(customers.get(0).getId());
adminClient.perform(REMOVE_CUSTOMERS_FROM_GROUP, variables, Arrays.asList(CUSTOMER_GROUP_FRAGMENT));
customerGroupCondition.clearCache(); // 清除customerGroupCondition对customerId的缓存
variables = objectMapper.createObjectNode();
variables.put("orderLineId", order.getLines().get(0).getId());
variables.put("quantity", 2);
graphQLResponse = shopClient.perform(ADJUST_ITEM_QUANTITY, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.adjustOrderLine", Order.class);
assertThat(order.getTotal()).isEqualTo(10000);
assertThat(order.getAdjustments()).isEmpty();
deletePromotion(promotion.getId());
}
/**
* default PromotionActions test cases
*/
@Test
@org.junit.jupiter.api.Order(13)
public void orderPercentageDiscount() throws IOException {
shopClient.asAnonymousUser();
String couponCode = "50%_off_order";
CreatePromotionInput createPromotionInput = new CreatePromotionInput();
createPromotionInput.setEnabled(true);
createPromotionInput.setName("50% discount on order");
createPromotionInput.setCouponCode(couponCode);
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(orderPercentageDiscount.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("discount");
configArgInput.setValue("50");
configurableOperationInput.getArguments().add(configArgInput);
createPromotionInput.getActions().add(configurableOperationInput);
Promotion promotion = createPromotion(createPromotionInput);
ProductVariant item60 = getVariantBySlug("item-60");
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", item60.getId());
variables.put("quantity", 1);
GraphQLResponse graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getTotal()).isEqualTo(5000);
assertThat(order.getAdjustments()).isEmpty();
variables = objectMapper.createObjectNode();
variables.put("couponCode", couponCode);
graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getAdjustments()).hasSize(1);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo("50% discount on order");
assertThat(order.getTotal()).isEqualTo(2500);
deletePromotion(promotion.getId());
}
@Test
@org.junit.jupiter.api.Order(14)
public void discountOnItemWithFacets() throws IOException {
shopClient.asAnonymousUser();
GraphQLResponse graphQLResponse =
adminClient.perform(
GET_FACET_LIST, null, Arrays.asList(FACET_VALUE_FRAGMENT, FACET_WITH_VALUES_FRAGMENT));
FacetList facetList = graphQLResponse.get("$.data.facets", FacetList.class);
FacetValue saleFacetValue = facetList.getItems().get(0).getValues().get(0);
String couponCode = "50%_off_sale_items";
CreatePromotionInput createPromotionInput = new CreatePromotionInput();
createPromotionInput.setEnabled(true);
createPromotionInput.setName("50% off sale items");
createPromotionInput.setCouponCode(couponCode);
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(facetValuesDiscountAction.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("discount");
configArgInput.setValue("50");
configurableOperationInput.getArguments().add(configArgInput);
configArgInput = new ConfigArgInput();
configArgInput.setName("facets");
configArgInput.setValue("[\"" + saleFacetValue.getId() + "\"]");
configurableOperationInput.getArguments().add(configArgInput);
createPromotionInput.getActions().add(configurableOperationInput);
Promotion promotion = createPromotion(createPromotionInput);
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", getVariantBySlug("item-12").getId());
variables.put("quantity", 1);
shopClient.perform(ADD_ITEM_TO_ORDER, variables);
variables = objectMapper.createObjectNode();
variables.put("productVariantId", getVariantBySlug("item-sale-12").getId());
variables.put("quantity", 1);
shopClient.perform(ADD_ITEM_TO_ORDER, variables);
variables = objectMapper.createObjectNode();
variables.put("productVariantId", getVariantBySlug("item-sale-1").getId());
variables.put("quantity", 2);
graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getAdjustments()).isEmpty();
assertThat(getItemSale1Line(order.getLines()).getAdjustments()).isEmpty();
assertThat(order.getTotal()).isEqualTo(2200);
variables = objectMapper.createObjectNode();
variables.put("couponCode", couponCode);
graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getTotal()).isEqualTo(1600);
assertThat(getItemSale1Line(order.getLines()).getAdjustments()).hasSize(2);
variables = objectMapper.createObjectNode();
variables.put("couponCode", couponCode);
graphQLResponse =
shopClient.perform(REMOVE_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.removeCouponCode", Order.class);
assertThat(getItemSale1Line(order.getLines()).getAdjustments()).isEmpty();
assertThat(order.getTotal()).isEqualTo(2200);
graphQLResponse =
shopClient.perform(GET_ACTIVE_ORDER, null, Arrays.asList(TEST_ORDER_FRAGMENT));
Order activeOrder = graphQLResponse.get("$.data.activeOrder", Order.class);
assertThat(getItemSale1Line(activeOrder.getLines()).getAdjustments()).isEmpty();
assertThat(activeOrder.getTotal()).isEqualTo(2200);
}
@Test
@org.junit.jupiter.api.Order(15)
public void productsPercentageDiscount() throws IOException {
shopClient.asAnonymousUser();
ProductVariant item60 = getVariantBySlug("item-60");
String couponCode = "50%_off_product";
CreatePromotionInput createPromotionInput = new CreatePromotionInput();
createPromotionInput.setEnabled(true);
createPromotionInput.setName("50% off product");
createPromotionInput.setCouponCode(couponCode);
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(productDiscountAction.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("discount");
configArgInput.setValue("50");
configurableOperationInput.getArguments().add(configArgInput);
configArgInput = new ConfigArgInput();
configArgInput.setName("productVariantIds");
configArgInput.setValue("[\"" + item60.getId() + "\"]");
configurableOperationInput.getArguments().add(configArgInput);
createPromotionInput.getActions().add(configurableOperationInput);
Promotion promotion = createPromotion(createPromotionInput);
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", item60.getId());
variables.put("quantity", 1);
GraphQLResponse graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
assertThat(order.getAdjustments()).isEmpty();
assertThat(order.getLines().get(0).getAdjustments()).isEmpty();
assertThat(order.getTotal()).isEqualTo(5000);
variables = objectMapper.createObjectNode();
variables.put("couponCode", couponCode);
graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getTotal()).isEqualTo(2500);
assertThat(order.getLines().get(0).getAdjustments()).hasSize(1);
variables = objectMapper.createObjectNode();
variables.put("couponCode", couponCode);
graphQLResponse =
shopClient.perform(REMOVE_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.removeCouponCode", Order.class);
assertThat(order.getLines().get(0).getAdjustments()).isEmpty();
assertThat(order.getTotal()).isEqualTo(5000);
deletePromotion(promotion.getId());
}
@Test
@org.junit.jupiter.api.Order(15)
public void multiple_promotions_simultaneously() throws IOException {
shopClient.asAnonymousUser();
GraphQLResponse graphQLResponse =
adminClient.perform(
GET_FACET_LIST, null, Arrays.asList(FACET_VALUE_FRAGMENT, FACET_WITH_VALUES_FRAGMENT));
FacetList facetList = graphQLResponse.get("$.data.facets", FacetList.class);
FacetValue saleFacetValue = facetList.getItems().get(0).getValues().get(0);
CreatePromotionInput createPromotionInput = new CreatePromotionInput();
createPromotionInput.setEnabled(true);
createPromotionInput.setName("item promo");
createPromotionInput.setCouponCode("CODE1");
ConfigurableOperationInput configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(facetValuesDiscountAction.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("discount");
configArgInput.setValue("50");
configurableOperationInput.getArguments().add(configArgInput);
configArgInput = new ConfigArgInput();
configArgInput.setName("facets");
configArgInput.setValue("[\"" + saleFacetValue.getId() + "\"]");
configurableOperationInput.getArguments().add(configArgInput);
createPromotionInput.getActions().add(configurableOperationInput);
Promotion promotion1 = createPromotion(createPromotionInput);
createPromotionInput = new CreatePromotionInput();
createPromotionInput.setEnabled(true);
createPromotionInput.setName("order promo");
createPromotionInput.setCouponCode("CODE2");
configurableOperationInput = new ConfigurableOperationInput();
configurableOperationInput.setCode(orderPercentageDiscount.getCode());
configArgInput = new ConfigArgInput();
configArgInput.setName("discount");
configArgInput.setValue("50");
configurableOperationInput.getArguments().add(configArgInput);
createPromotionInput.getActions().add(configurableOperationInput);
Promotion promotion2 = createPromotion(createPromotionInput);
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", getVariantBySlug("item-sale-12").getId());
variables.put("quantity", 1);
shopClient.perform(ADD_ITEM_TO_ORDER, variables);
// Apply the OrderItem-level promo
variables = objectMapper.createObjectNode();
variables.put("couponCode", "CODE1");
graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getLines().get(0).getAdjustments()).hasSize(1);
assertThat(order.getLines().get(0).getAdjustments().stream()
.filter(a -> Objects.equals(a.getType(), AdjustmentType.PROMOTION))
.findFirst()
.get()
.getDescription()
).isEqualTo("item promo");
assertThat(order.getAdjustments()).isEmpty();
// Apply the Order-level promo
variables = objectMapper.createObjectNode();
variables.put("couponCode", "CODE2");
graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getLines().get(0).getAdjustments()).hasSize(1);
assertThat(order.getLines().get(0).getAdjustments().stream()
.filter(a -> Objects.equals(a.getType(), AdjustmentType.PROMOTION))
.findFirst()
.get()
.getDescription()
).isEqualTo("item promo");
assertThat(order.getAdjustments()).hasSize(1);
assertThat(order.getAdjustments().get(0).getDescription()).isEqualTo("order promo");
}
private OrderLine getItemSale1Line(List<OrderLine> lines) {
return lines.stream()
.filter(l -> Objects.equals(l.getProductVariant().getId(), getVariantBySlug("item-sale-1").getId()))
.findFirst().get();
}
/**
* per-customer usage limit
*/
Promotion promoWithUsageLimit;
private void before_test_16() throws IOException {
CreatePromotionInput input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Free with test coupon");
input.setCouponCode(TEST_COUPON_CODE);
input.setPerCustomerUsageLimit(1);
input.getActions().add(getFreeOrderAction());
Promotion promoWithUsageLimit = createPromotion(input);
}
private Order createNewActiveOrder() throws IOException {
ProductVariant item60 = getVariantBySlug("item-60");
ObjectNode variables = objectMapper.createObjectNode();
variables.put("productVariantId", item60.getId());
variables.put("quantity", 1);
GraphQLResponse graphQLResponse = shopClient.perform(ADD_ITEM_TO_ORDER, variables);
Order order = graphQLResponse.get("$.data.addItemToOrder", Order.class);
return order;
}
/**
* guest customer
*/
String GUEST_EMAIL_ADDRESS = "[email protected]";
String orderCode;
private void addGuestCustomerToOrder() throws IOException {
CreateCustomerInput input = new CreateCustomerInput();
input.setEmailAddress(GUEST_EMAIL_ADDRESS);
input.setFirstName("Guest");
input.setLastName("Customer");
JsonNode inputNode = objectMapper.valueToTree(input);
ObjectNode variables = objectMapper.createObjectNode();
variables.set("input", inputNode);
shopClient.perform(SET_CUSTOMER, variables);
}
@Test
@org.junit.jupiter.api.Order(16)
public void allows_initial_usage() throws IOException {
before_test_16();
shopClient.asAnonymousUser();
createNewActiveOrder();
addGuestCustomerToOrder();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getCouponCodes()).containsExactly(TEST_COUPON_CODE);
testOrderUtils.proceedToArrangingPayment(shopClient);
order = testOrderUtils.addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
assertThat(order.getState()).isEqualTo(OrderState.PaymentSettled.name());
assertThat(order.getActive()).isFalse();
orderCode = order.getCode();
}
@Test
@org.junit.jupiter.api.Order(17)
public void adds_Promotions_to_Order_once_payment_arranged() throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("code", orderCode);
GraphQLResponse graphQLResponse =
shopClient.perform(GET_ORDER_PROMOTIONS_BY_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.orderByCode", Order.class);
assertThat(order.getPromotions()).hasSize(1);
assertThat(order.getPromotions().get(0).getName()).isEqualTo("Free with test coupon");
}
@Test
@org.junit.jupiter.api.Order(18)
public void throws_when_usage_exceeds_limit() throws IOException {
shopClient.asAnonymousUser();
createNewActiveOrder();
addGuestCustomerToOrder();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
try {
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
fail("should have thrown");
} catch (ApiException apiEx) {
assertThat(apiEx.getErrorMessage()).isEqualTo(
"Coupon code cannot be used more than 1 time(s) per customer"
);
}
}
@Test
@org.junit.jupiter.api.Order(19)
public void removes_couponCode_from_order_when_adding_customer_after_code_applied() throws IOException {
shopClient.asAnonymousUser();
createNewActiveOrder();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getCouponCodes()).containsExactly(TEST_COUPON_CODE);
addGuestCustomerToOrder();
graphQLResponse =
shopClient.perform(GET_ACTIVE_ORDER, null, Arrays.asList(TEST_ORDER_FRAGMENT));
Order activeOrder = graphQLResponse.get("$.data.activeOrder", Order.class);
assertThat(activeOrder.getCouponCodes()).isEmpty();
assertThat(activeOrder.getTotal()).isEqualTo(5000);
}
/**
* signed-in customer
*/
private void loginAsRegisteredCustomer() throws IOException {
shopClient.asUserWithCredentials(customers.get(0).getEmailAddress(), password);
}
@Test
@org.junit.jupiter.api.Order(20)
public void allows_initial_usage_02() throws IOException {
loginAsRegisteredCustomer();
createNewActiveOrder();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getTotal()).isEqualTo(0);
assertThat(order.getCouponCodes()).containsExactly(TEST_COUPON_CODE);
testOrderUtils.proceedToArrangingPayment(shopClient);
order = testOrderUtils.addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
assertThat(order.getState()).isEqualTo(OrderState.PaymentSettled.name());
assertThat(order.getActive()).isFalse();
}
@Test
@org.junit.jupiter.api.Order(21)
public void throws_when_usage_exceeds_limit_02() throws IOException {
loginAsRegisteredCustomer();
createNewActiveOrder();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
try {
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
fail("should have thrown");
} catch (ApiException apiEx) {
assertThat(apiEx.getErrorMessage()).isEqualTo(
"Coupon code cannot be used more than 1 time(s) per customer"
);
}
}
@Test
@org.junit.jupiter.api.Order(22)
public void removes_couponCode_from_order_when_logging_in_after_code_applied() throws IOException {
shopClient.asAnonymousUser();
createNewActiveOrder();
ObjectNode variables = objectMapper.createObjectNode();
variables.put("couponCode", TEST_COUPON_CODE);
GraphQLResponse graphQLResponse =
shopClient.perform(APPLY_COUPON_CODE, variables, Arrays.asList(TEST_ORDER_FRAGMENT));
Order order = graphQLResponse.get("$.data.applyCouponCode", Order.class);
assertThat(order.getCouponCodes()).containsExactly(TEST_COUPON_CODE);
assertThat(order.getTotal()).isEqualTo(0);
loginAsRegisteredCustomer();
graphQLResponse =
shopClient.perform(GET_ACTIVE_ORDER, null, Arrays.asList(TEST_ORDER_FRAGMENT));
Order activeOrder = graphQLResponse.get("$.data.activeOrder", Order.class);
assertThat(activeOrder.getTotal()).isEqualTo(5000);
assertThat(activeOrder.getCouponCodes()).isEmpty();
}
private void getProducts() throws IOException {
ProductListOptions options = new ProductListOptions();
options.setPageSize(10);
options.setCurrentPage(1);
JsonNode optionsNode = objectMapper.valueToTree(options);
ObjectNode variables = objectMapper.createObjectNode();
variables.set("options", optionsNode);
GraphQLResponse graphQLResponse = adminClient.perform(
GET_PROMO_PRODUCTS, variables);
ProductList productList = graphQLResponse.get("$.data.adminProducts", ProductList.class);
products = productList.getItems();
}
private void createGlobalPromotions() throws IOException {
CreatePromotionInput input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Promo not yet started");
Calendar calendar = Calendar.getInstance();
calendar.set(2199, 0, 1);
input.setStartsAt(calendar.getTime());
input.getConditions().add(getMinOrderAmountCondition(100));
input.getActions().add(getFreeOrderAction());
this.createPromotion(input);
input = new CreatePromotionInput();
input.setEnabled(true);
input.setName("Deleted promotion");
input.getConditions().add(getMinOrderAmountCondition(100));
input.getActions().add(getFreeOrderAction());
Promotion promotion = createPromotion(input);
deletePromotion(promotion.getId());
}
private Promotion createPromotion(CreatePromotionInput input) throws IOException {
JsonNode inputNode = objectMapper.valueToTree(input);
ObjectNode variables = objectMapper.createObjectNode();
variables.set("input", inputNode);
GraphQLResponse graphQLResponse = adminClient.perform(
CREATE_PROMOTION, variables, Arrays.asList(PROMOTION_FRAGMENT, CONFIGURABLE_FRAGMENT));
Promotion promotion = graphQLResponse.get("$.data.createPromotion", Promotion.class);
return promotion;
}
private ProductVariant getVariantBySlug(String slug) {
return products.stream().filter(p -> Objects.equals(p.getSlug(), slug)).findFirst().get().getVariants().get(0);
}
private void deletePromotion(Long id) throws IOException {
ObjectNode variables = objectMapper.createObjectNode();
variables.put("id", id);
adminClient.perform(DELETE_PROMOTION, variables);
}
private ConfigurableOperationInput getMinOrderAmountCondition(Integer amount) {
ConfigurableOperationInput input = new ConfigurableOperationInput();
input.setCode(minimumOrderAmount.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("amount");
configArgInput.setValue(amount.toString());
input.getArguments().add(configArgInput);
return input;
}
private ConfigurableOperationInput getFreeOrderAction() {
ConfigurableOperationInput input = new ConfigurableOperationInput();
input.setCode(orderPercentageDiscount.getCode());
ConfigArgInput configArgInput = new ConfigArgInput();
configArgInput.setName("discount");
configArgInput.setValue("100");
input.getArguments().add(configArgInput);
return input;
}
}
|
92440470bda966dea7d2b665108dad01d1f71f35 | 5,486 | java | Java | sharding-core/sharding-core-parse/sharding-core-parse-test/src/test/java/org/apache/shardingsphere/core/parse/EncryptIntegrateParsingTest.java | lanweigreatperson/incubator-shardingsphere | d3f3d0e7aa1ab2ce540020fb09890b2ee47ab522 | [
"Apache-2.0"
] | 1 | 2019-03-26T02:48:04.000Z | 2019-03-26T02:48:04.000Z | sharding-core/sharding-core-parse/sharding-core-parse-test/src/test/java/org/apache/shardingsphere/core/parse/EncryptIntegrateParsingTest.java | woaixiatian/sharding-sphere | 7b934216e6ee7b7d3be430dd3dab7dc90cb85583 | [
"Apache-2.0"
] | null | null | null | sharding-core/sharding-core-parse/sharding-core-parse-test/src/test/java/org/apache/shardingsphere/core/parse/EncryptIntegrateParsingTest.java | woaixiatian/sharding-sphere | 7b934216e6ee7b7d3be430dd3dab7dc90cb85583 | [
"Apache-2.0"
] | null | null | null | 49.872727 | 197 | 0.772147 | 1,002,857 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.parse;
import com.google.common.base.Preconditions;
import lombok.RequiredArgsConstructor;
import org.antlr.v4.runtime.ANTLRErrorListener;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.apache.shardingsphere.core.constant.DatabaseType;
import org.apache.shardingsphere.core.parse.api.SQLParser;
import org.apache.shardingsphere.core.parse.entry.EncryptSQLParseEntry;
import org.apache.shardingsphere.core.parse.integrate.asserts.EncryptParserResultSetLoader;
import org.apache.shardingsphere.core.parse.integrate.asserts.EncryptSQLStatementAssert;
import org.apache.shardingsphere.core.parse.integrate.asserts.ParserResultSetLoader;
import org.apache.shardingsphere.core.parse.integrate.engine.AbstractBaseIntegrateSQLParsingTest;
import org.apache.shardingsphere.core.parse.integrate.jaxb.root.ParserResult;
import org.apache.shardingsphere.core.parse.parser.SQLParserFactory;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.yaml.config.encrypt.YamlEncryptRuleConfiguration;
import org.apache.shardingsphere.core.yaml.engine.YamlEngine;
import org.apache.shardingsphere.core.yaml.swapper.impl.EncryptRuleConfigurationYamlSwapper;
import org.apache.shardingsphere.test.sql.EncryptSQLCasesLoader;
import org.apache.shardingsphere.test.sql.SQLCaseType;
import org.apache.shardingsphere.test.sql.SQLCasesLoader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@RunWith(Parameterized.class)
@RequiredArgsConstructor
public final class EncryptIntegrateParsingTest extends AbstractBaseIntegrateSQLParsingTest {
private static SQLCasesLoader sqlCasesLoader = EncryptSQLCasesLoader.getInstance();
private static ParserResultSetLoader parserResultSetLoader = EncryptParserResultSetLoader.getInstance();
private final String sqlCaseId;
private final DatabaseType databaseType;
private final SQLCaseType sqlCaseType;
@Parameters(name = "{0} ({2}) -> {1}")
public static Collection<Object[]> getTestParameters() {
return sqlCasesLoader.getSupportedSQLTestParameters(Arrays.<Enum>asList(DatabaseType.values()), DatabaseType.class);
}
private static EncryptRule buildShardingRule() throws IOException {
URL url = AbstractBaseIntegrateSQLParsingTest.class.getClassLoader().getResource("yaml/encrypt-rule-for-parser.yaml");
Preconditions.checkNotNull(url, "Cannot found parser rule yaml configuration.");
YamlEncryptRuleConfiguration encryptConfig = YamlEngine.unmarshal(new File(url.getFile()), YamlEncryptRuleConfiguration.class);
return new EncryptRule(new EncryptRuleConfigurationYamlSwapper().swap(encryptConfig));
}
@Test
public void parsingSupportedSQL() throws Exception {
String sql = sqlCasesLoader.getSupportedSQL(sqlCaseId, sqlCaseType, Collections.emptyList());
SQLParser sqlParser = SQLParserFactory.newInstance(databaseType, sql);
Method addErrorListener = sqlParser.getClass().getMethod("addErrorListener", ANTLRErrorListener.class);
addErrorListener.invoke(sqlParser, new BaseErrorListener() {
@Override
public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException ex) {
throw new RuntimeException();
}
});
sqlParser.execute();
}
@Test
public void assertSupportedSQL() throws Exception {
ParserResult parserResult = parserResultSetLoader.getParserResult(sqlCaseId);
if (null != parserResult) {
String sql = sqlCasesLoader.getSupportedSQL(sqlCaseId, sqlCaseType, parserResult.getParameters());
DatabaseType execDatabaseType = databaseType;
if (DatabaseType.H2 == databaseType) {
execDatabaseType = DatabaseType.MySQL;
}
new EncryptSQLStatementAssert(new EncryptSQLParseEntry(execDatabaseType, buildShardingRule(), AbstractBaseIntegrateSQLParsingTest.getShardingTableMetaData()).parse(sql, false),
sqlCaseId, sqlCaseType, sqlCasesLoader, parserResultSetLoader, execDatabaseType).assertSQLStatement();
}
}
}
|
9244058e5c0845ec070fa12498bd61ab3c8f8785 | 1,714 | java | Java | src/main/java/org/hildan/candyboxcheater/controllers/widgets/IntegerFieldController.java | joffrey-bion/candybox-cheater | 603ad660d50905cee1b0d4d339948791cba8a8d5 | [
"MIT"
] | null | null | null | src/main/java/org/hildan/candyboxcheater/controllers/widgets/IntegerFieldController.java | joffrey-bion/candybox-cheater | 603ad660d50905cee1b0d4d339948791cba8a8d5 | [
"MIT"
] | null | null | null | src/main/java/org/hildan/candyboxcheater/controllers/widgets/IntegerFieldController.java | joffrey-bion/candybox-cheater | 603ad660d50905cee1b0d4d339948791cba8a8d5 | [
"MIT"
] | null | null | null | 23.805556 | 87 | 0.715286 | 1,002,858 | package org.hildan.candyboxcheater.controllers.widgets;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.util.converter.NumberStringConverter;
public class IntegerFieldController implements Initializable {
private static final int MIN = 0;
private static final int MAX = Integer.MAX_VALUE;
@FXML
private TextField field;
private IntegerProperty value;
@Override
public void initialize(URL location, ResourceBundle resources) {
field.setText("0");
field.addEventFilter(KeyEvent.KEY_TYPED, (KeyEvent inputevent) -> {
if (!inputevent.getCharacter().matches("\\d")) {
inputevent.consume();
}
});
value = new SimpleIntegerProperty(0);
Bindings.bindBidirectional(field.textProperty(), value, new NumberStringConverter() {
@Override
public String toString(Number n) {
// no formatting at all, for string variable value
return String.valueOf(n);
}
});
}
public IntegerProperty valueProperty() {
return value;
}
@FXML
void decrement(@SuppressWarnings("unused") ActionEvent event) {
int i = value.get();
if (i > MAX) {
value.set(MAX);
} else if (MIN < i) {
value.set(i - 1);
} else {
value.set(MIN);
}
}
@FXML
void increment(@SuppressWarnings("unused") ActionEvent event) {
int i = value.get();
if (i < MIN) {
value.set(MIN);
} else if (i < MAX) {
value.set(i + 1);
} else {
value.set(MAX);
}
}
}
|
924405a396ba12eb174e5c213759f6e115ecadda | 1,533 | java | Java | src/test/java/ad/dummies/p01basics/c03datastructures/E10IteratorTest.java | CSchoel/ad-dummies-java | ffeaa10597a2efb22d9f9d74e5b77ba02fe8e6a1 | [
"MIT"
] | 2 | 2019-10-26T19:31:28.000Z | 2020-03-04T21:49:47.000Z | src/test/java/ad/dummies/p01basics/c03datastructures/E10IteratorTest.java | CSchoel/ad-dummies-java | ffeaa10597a2efb22d9f9d74e5b77ba02fe8e6a1 | [
"MIT"
] | 1 | 2019-12-02T15:59:21.000Z | 2019-12-02T15:59:21.000Z | src/test/java/ad/dummies/p01basics/c03datastructures/E10IteratorTest.java | CSchoel/ad-dummies-java | ffeaa10597a2efb22d9f9d74e5b77ba02fe8e6a1 | [
"MIT"
] | null | null | null | 24.725806 | 79 | 0.654273 | 1,002,859 | package ad.dummies.p01basics.c03datastructures;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static ad.dummies.p01basics.c03datastructures.E10Iterator.*;
/**
* <p>Unit tests for an example from the german book "Algorithms and data
* structures for dummies":</p>
*
* <p>A. Gogol-Döring and T. Letschert, <i>Algorithmen und Datenstrukturen für
* Dummies</i>. Weinheim, Germany: Wiley-VCH, 2019.</p>
*
* <p>The current version of these examples with unit tests and benchmarks can
* be found <a href="https://github.com/CSchoel/ad-dummies-java">on GitHub</a>.
* </p>
*
* @author Christopher Schölzel
* @see E10Iterator
*/
class E10IteratorTest {
private IntList lstZero;
private IntList lstFive;
@BeforeEach
public void createLists() {
lstZero = new Nil();
lstFive = new Nil();
for(int x : new int[]{5, 1, -3, 13, -8}) {
lstFive = new Cons(x, lstFive);
}
}
@Test
void listSumInnerNil() {
assertEquals(0, listSumInner(lstZero));
}
@Test
void listSumInnerFiveElements() {
assertEquals(8, listSumInner(lstFive));
}
@Test
void listSumOuterNil() {
assertEquals(0, listSumOuter(lstZero));
}
@Test
void listSumOuterFiveElements() {
assertEquals(8, listSumOuter(lstFive));
}
@Test
public void mainMethodDoesNotThrowAnyExceptions() {
E10Iterator.main(new String[0]);
}
} |
924407be2e24eb2bf01d118aa948a5e8ad1b7ae5 | 15,213 | java | Java | opentaps/opentaps-common/src/common/org/opentaps/common/domain/order/PurchaseOrderLookupRepository.java | opentaps/opentaps-1 | 49f3ebcd3645b7e76fe3d71f43904ce65d7901b8 | [
"Apache-2.0"
] | 10 | 2015-12-10T11:53:32.000Z | 2022-02-28T13:00:09.000Z | opentaps/opentaps-common/src/common/org/opentaps/common/domain/order/PurchaseOrderLookupRepository.java | alainrk/opentaps | 1b234c74a55c0eb39170b9a9e88a0586a0408c77 | [
"Apache-2.0"
] | null | null | null | opentaps/opentaps-common/src/common/org/opentaps/common/domain/order/PurchaseOrderLookupRepository.java | alainrk/opentaps | 1b234c74a55c0eb39170b9a9e88a0586a0408c77 | [
"Apache-2.0"
] | 13 | 2015-11-16T10:01:22.000Z | 2021-12-05T06:47:00.000Z | 43.968208 | 196 | 0.623546 | 1,002,860 | /*
* Copyright (c) Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentaps.common.domain.order;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.hibernate.Criteria;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.opentaps.base.constants.OrderTypeConstants;
import org.opentaps.base.constants.RoleTypeConstants;
import org.opentaps.base.constants.StatusItemConstants;
import org.opentaps.base.entities.OrderHeader;
import org.opentaps.base.entities.OrderItem;
import org.opentaps.base.entities.OrderRole;
import org.opentaps.base.entities.ProductAndGoodIdentification;
import org.opentaps.common.util.UtilDate;
import org.opentaps.domain.DomainsDirectory;
import org.opentaps.domain.order.OrderViewForListing;
import org.opentaps.domain.order.PurchaseOrderLookupRepositoryInterface;
import org.opentaps.domain.product.Product;
import org.opentaps.domain.product.ProductRepositoryInterface;
import org.opentaps.foundation.entity.Entity;
import org.opentaps.foundation.entity.EntityNotFoundException;
import org.opentaps.foundation.entity.hibernate.HibernateUtil;
import org.opentaps.foundation.entity.hibernate.Session;
import org.opentaps.foundation.infrastructure.InfrastructureException;
import org.opentaps.foundation.repository.RepositoryException;
import org.opentaps.foundation.repository.ofbiz.CommonLookupRepository;
/**
* Repository to lookup Purchase Orders.
*/
public class PurchaseOrderLookupRepository extends CommonLookupRepository implements PurchaseOrderLookupRepositoryInterface {
@SuppressWarnings("unused")
private static final String MODULE = PurchaseOrderLookupRepository.class.getName();
private String orderId;
private String productPattern;
private String statusId;
private String orderName;
private String organizationPartyId;
private String createdBy;
private String supplierPartyId;
private Timestamp fromDate;
private String fromDateStr;
private Timestamp thruDate;
private String thruDateStr;
private boolean findDesiredOnly = false;
private Locale locale;
private TimeZone timeZone;
private List<String> orderBy;
private ProductRepositoryInterface productRepository;
/**
* Default constructor.
*/
public PurchaseOrderLookupRepository() {
super();
}
/** {@inheritDoc} */
public List<OrderViewForListing> findOrders() throws RepositoryException {
// convert fromDateStr / thruDateStr into Timestamps if the string versions were given
if (UtilValidate.isNotEmpty(fromDateStr)) {
fromDate = UtilDate.toTimestamp(fromDateStr, timeZone, locale);
}
if (UtilValidate.isNotEmpty(thruDateStr)) {
thruDate = UtilDate.toTimestamp(thruDateStr, timeZone, locale);
}
Session session = null;
try {
// get a hibernate session
session = getInfrastructure().getSession();
Criteria criteria = session.createCriteria(OrderHeader.class);
// always filter by the current organization
criteria.add(Restrictions.eq(OrderHeader.Fields.billToPartyId.name(), organizationPartyId));
// filters by order type, we only want purchase order
criteria.add(Restrictions.eq(OrderHeader.Fields.orderTypeId.name(), OrderTypeConstants.PURCHASE_ORDER));
// set the from/thru date filter if they were given
if (fromDate != null) {
criteria.add(Restrictions.ge(OrderHeader.Fields.orderDate.name(), fromDate));
}
if (thruDate != null) {
criteria.add(Restrictions.le(OrderHeader.Fields.orderDate.name(), thruDate));
}
// filter the role assoc, there is only one supplier role per order
Criteria roleCriteria = criteria.createAlias("orderRoles", "or");
roleCriteria.add(Restrictions.eq("or.id." + OrderRole.Fields.roleTypeId.name(), RoleTypeConstants.BILL_FROM_VENDOR));
// filter by order status
if (findDesiredOnly) {
List<String> statuses = UtilMisc.toList(StatusItemConstants.OrderStatus.ORDER_APPROVED, StatusItemConstants.OrderStatus.ORDER_CREATED, StatusItemConstants.OrderStatus.ORDER_HOLD);
criteria.add(Restrictions.in(OrderHeader.Fields.statusId.name(), statuses));
}
// filter by the given orderId string
if (UtilValidate.isNotEmpty(orderId)) {
criteria.add(Restrictions.ilike(OrderHeader.Fields.orderId.name(), orderId, MatchMode.START));
}
// filter by exact matching status, if a statusId was given
if (UtilValidate.isNotEmpty(statusId)) {
criteria.add(Restrictions.eq(OrderHeader.Fields.statusId.name(), statusId));
}
// filter by the user who created the order if given
if (UtilValidate.isNotEmpty(createdBy)) {
criteria.add(Restrictions.eq(OrderHeader.Fields.createdBy.name(), createdBy));
}
// filter by the given orderName string
if (UtilValidate.isNotEmpty(orderName)) {
criteria.add(Restrictions.ilike(OrderHeader.Fields.orderName.name(), orderName, MatchMode.START));
}
// filter by the given supplierPartyId string, from the OrderRole entity
if (UtilValidate.isNotEmpty(supplierPartyId)) {
roleCriteria.add(Restrictions.ilike("or.id." + OrderRole.Fields.partyId.name(), supplierPartyId, MatchMode.START));
}
// filter by product, if given
criteria.createAlias("orderItems", "oi");
if (UtilValidate.isNotEmpty(productPattern)) {
try {
// try to get product by using productPattern as productId
Product product = getProductRepository().getProductById(productPattern);
criteria.add(Restrictions.eq("oi." + OrderItem.Fields.productId.name(), product.getProductId()));
} catch (EntityNotFoundException e) {
// could not get the product by using productPattern as productId
// find all the products that may match
String likePattern = "%" + productPattern + "%";
EntityCondition conditionList = EntityCondition.makeCondition(EntityOperator.OR,
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.productId.getName(), EntityOperator.LIKE, likePattern),
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.internalName.getName(), EntityOperator.LIKE, likePattern),
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.productName.getName(), EntityOperator.LIKE, likePattern),
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.comments.getName(), EntityOperator.LIKE, likePattern),
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.description.getName(), EntityOperator.LIKE, likePattern),
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.longDescription.getName(), EntityOperator.LIKE, likePattern),
EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.idValue.getName(), EntityOperator.LIKE, likePattern)
);
List<ProductAndGoodIdentification> products = findList(ProductAndGoodIdentification.class, conditionList);
if (products.size() > 0) {
criteria.add(Restrictions.in("oi." + OrderItem.Fields.productId.name(), Entity.getDistinctFieldValues(products, ProductAndGoodIdentification.Fields.productId)));
}
}
}
// specify the fields to return
criteria.setProjection(Projections.projectionList()
.add(Projections.distinct(Projections.property(OrderHeader.Fields.orderId.name())))
.add(Projections.property(OrderHeader.Fields.orderName.name()))
.add(Projections.property(OrderHeader.Fields.statusId.name()))
.add(Projections.property(OrderHeader.Fields.grandTotal.name()))
.add(Projections.property(OrderHeader.Fields.orderDate.name()))
.add(Projections.property(OrderHeader.Fields.currencyUom.name()))
.add(Projections.property("or.id." + OrderRole.Fields.partyId.name())));
// set the order by
if (orderBy == null) {
orderBy = Arrays.asList(OrderHeader.Fields.orderDate.desc());
}
// some substitution is needed to fit the hibernate field names
// this also maps the calculated fields and indicates the non sortable fields
Map<String, String> subs = new HashMap<String, String>();
subs.put("partyId", "or.id.partyId");
subs.put("partyName", "or.id.partyId");
subs.put("orderDateString", "orderDate");
subs.put("orderNameId", "orderId");
subs.put("statusDescription", "statusId");
HibernateUtil.setCriteriaOrder(criteria, orderBy, subs);
ScrollableResults results = null;
List<OrderViewForListing> results2 = new ArrayList<OrderViewForListing>();
try {
// fetch the paginated results
results = criteria.scroll(ScrollMode.SCROLL_INSENSITIVE);
if (usePagination()) {
results.setRowNumber(getPageStart());
} else {
results.first();
}
// convert them into OrderViewForListing objects which will also calculate or format some fields for display
Object[] o = results.get();
int n = 0; // number of results actually read
while (o != null) {
OrderViewForListing r = new OrderViewForListing();
r.initRepository(this);
int i = 0;
r.setOrderId((String) o[i++]);
r.setOrderName((String) o[i++]);
r.setStatusId((String) o[i++]);
r.setGrandTotal((BigDecimal) o[i++]);
r.setOrderDate((Timestamp) o[i++]);
r.setCurrencyUom((String) o[i++]);
r.setPartyId((String) o[i++]);
r.calculateExtraFields(getDelegator(), timeZone, locale);
results2.add(r);
n++;
if (!results.next()) {
break;
}
if (usePagination() && n >= getPageSize()) {
break;
}
o = results.get();
}
results.last();
// note: row number starts at 0
setResultSize(results.getRowNumber() + 1);
} finally {
results.close();
}
return results2;
} catch (InfrastructureException e) {
throw new RepositoryException(e);
} finally {
if (session != null) {
session.close();
}
}
}
protected ProductRepositoryInterface getProductRepository() throws RepositoryException {
if (productRepository == null) {
productRepository = DomainsDirectory.getDomainsDirectory(this).getProductDomain().getProductRepository();
}
return productRepository;
}
/** {@inheritDoc} */
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/** {@inheritDoc} */
public void setOrderBy(List<String> orderBy) {
this.orderBy = orderBy;
}
/** {@inheritDoc} */
public void setSupplierPartyId(String supplierPartyId) {
this.supplierPartyId = supplierPartyId;
}
/** {@inheritDoc} */
public void setFromDate(String fromDate) {
this.fromDateStr = fromDate;
}
/** {@inheritDoc} */
public void setFromDate(Timestamp fromDate) {
this.fromDate = fromDate;
}
/** {@inheritDoc} */
public void setThruDate(String thruDate) {
this.thruDateStr = thruDate;
}
/** {@inheritDoc} */
public void setThruDate(Timestamp thruDate) {
this.thruDate = thruDate;
}
/** {@inheritDoc} */
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/** {@inheritDoc} */
public void setStatusId(String statusId) {
this.statusId = statusId;
}
/** {@inheritDoc} */
public void setProductPattern(String productPattern) {
this.productPattern = productPattern;
}
/** {@inheritDoc} */
public void setOrderName(String orderName) {
this.orderName = orderName;
}
/** {@inheritDoc} */
public void setOrganizationPartyId(String organizationPartyId) {
this.organizationPartyId = organizationPartyId;
}
/** {@inheritDoc} */
public void setLocale(Locale locale) {
this.locale = locale;
}
/** {@inheritDoc} */
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
/** {@inheritDoc} */
public void setFindDesiredOnly(boolean findDesiredOnly) {
this.findDesiredOnly = findDesiredOnly;
}
}
|
924408f1d4c39f390403e54dbbe4bad0f9b70f68 | 964 | java | Java | contact-app/server/src/main/java/com/example/contacts/model/User.java | puneetj-flock/Contacts-App | 1dfb4e4c54631e57d95bb4cebc42fcce8fca7652 | [
"MIT"
] | null | null | null | contact-app/server/src/main/java/com/example/contacts/model/User.java | puneetj-flock/Contacts-App | 1dfb4e4c54631e57d95bb4cebc42fcce8fca7652 | [
"MIT"
] | null | null | null | contact-app/server/src/main/java/com/example/contacts/model/User.java | puneetj-flock/Contacts-App | 1dfb4e4c54631e57d95bb4cebc42fcce8fca7652 | [
"MIT"
] | 2 | 2022-01-17T13:45:52.000Z | 2022-01-17T13:53:44.000Z | 18.188679 | 93 | 0.660788 | 1,002,861 | package com.example.contacts.model;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class User {
private Integer id;
private String name;
private String email;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean validateEmail()
{
Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(email);
return matcher.find();
}
}
|
924408f38b45136ffc12c2dc8f8eda20838c751e | 1,401 | java | Java | src/main/java/system/Professor.java | marcelorvergara/java_tp3 | 58e3e379697c9ee1be906006cee2126dae3452c6 | [
"MIT"
] | null | null | null | src/main/java/system/Professor.java | marcelorvergara/java_tp3 | 58e3e379697c9ee1be906006cee2126dae3452c6 | [
"MIT"
] | null | null | null | src/main/java/system/Professor.java | marcelorvergara/java_tp3 | 58e3e379697c9ee1be906006cee2126dae3452c6 | [
"MIT"
] | null | null | null | 21.890625 | 79 | 0.618844 | 1,002,862 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package system;
/**
*
* @author marcelo
*/
public class Professor extends Pessoa {
private String departamento;
private double salario;
public Professor() {
}
public Professor(String departamento, double salario) {
super();
this.departamento = departamento;
this.salario = salario;
}
@Override
public void consultarSituacao() {
System.out.println("Nome do Professor: " + super.getNomeCompleto());
System.out.println("Situação professor: " + super.getSituacao());
System.out.println("Departamento: " + getDepartamento());
System.out.println("Salário: " + getSalario());
}
/**
* @return the salario
*/
public double getSalario() {
return salario;
}
/**
* @param salario the salario to set
*/
public void setSalario(double salario) {
this.salario = salario;
}
/**
* @return the departamento
*/
public String getDepartamento() {
return departamento;
}
/**
* @param departamento the departamento to set
*/
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
}
|
924409e109f8423f9ffedccede86b0461ea7266f | 352 | java | Java | src/main/java/com/github/syuchan1005/gitprefix/codestyle/PrefixResourceCodeStyle.java | siosio/GitPrefix | d2f79fe5b096f79a378dc87d41a4d158ff2f3b89 | [
"MIT"
] | 32 | 2018-07-11T05:16:09.000Z | 2021-11-11T17:36:46.000Z | src/main/java/com/github/syuchan1005/gitprefix/codestyle/PrefixResourceCodeStyle.java | siosio/GitPrefix | d2f79fe5b096f79a378dc87d41a4d158ff2f3b89 | [
"MIT"
] | 26 | 2018-07-11T15:44:39.000Z | 2022-02-10T15:46:18.000Z | src/main/java/com/github/syuchan1005/gitprefix/codestyle/PrefixResourceCodeStyle.java | siosio/GitPrefix | d2f79fe5b096f79a378dc87d41a4d158ff2f3b89 | [
"MIT"
] | 9 | 2018-07-11T05:16:13.000Z | 2022-03-26T02:11:50.000Z | 32 | 70 | 0.849432 | 1,002,863 | package com.github.syuchan1005.gitprefix.codestyle;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CustomCodeStyleSettings;
public class PrefixResourceCodeStyle extends CustomCodeStyleSettings {
public PrefixResourceCodeStyle(CodeStyleSettings container) {
super("PrefixResourceCodeStyle", container);
}
}
|
92440a67aa19ce711d6907cba533cbabddf616cc | 2,356 | java | Java | src/main/java/org/bian/dto/BQInsightExchangeInputModel.java | bianapis/sd-customer-behavioral-insights-v2.0 | cf4c8edcca3746f48cf5c2a1c83c9ac17adf16b1 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQInsightExchangeInputModel.java | bianapis/sd-customer-behavioral-insights-v2.0 | cf4c8edcca3746f48cf5c2a1c83c9ac17adf16b1 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQInsightExchangeInputModel.java | bianapis/sd-customer-behavioral-insights-v2.0 | cf4c8edcca3746f48cf5c2a1c83c9ac17adf16b1 | [
"Apache-2.0"
] | null | null | null | 35.69697 | 199 | 0.835314 | 1,002,864 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.CRCustomerBehaviorAnalysisExchangeInputModelCustomerBehaviorAnalysisExchangeActionRequest;
import javax.validation.Valid;
/**
* BQInsightExchangeInputModel
*/
public class BQInsightExchangeInputModel {
private String customerBehaviorAnalysisInstanceReference = null;
private Object insightExchangeActionTaskRecord = null;
private CRCustomerBehaviorAnalysisExchangeInputModelCustomerBehaviorAnalysisExchangeActionRequest insightExchangeActionRequest = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the parent Customer Behavior Analysis instance
* @return customerBehaviorAnalysisInstanceReference
**/
public String getCustomerBehaviorAnalysisInstanceReference() {
return customerBehaviorAnalysisInstanceReference;
}
public void setCustomerBehaviorAnalysisInstanceReference(String customerBehaviorAnalysisInstanceReference) {
this.customerBehaviorAnalysisInstanceReference = customerBehaviorAnalysisInstanceReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The exchange service call consolidated processing record
* @return insightExchangeActionTaskRecord
**/
public Object getInsightExchangeActionTaskRecord() {
return insightExchangeActionTaskRecord;
}
public void setInsightExchangeActionTaskRecord(Object insightExchangeActionTaskRecord) {
this.insightExchangeActionTaskRecord = insightExchangeActionTaskRecord;
}
/**
* Get insightExchangeActionRequest
* @return insightExchangeActionRequest
**/
public CRCustomerBehaviorAnalysisExchangeInputModelCustomerBehaviorAnalysisExchangeActionRequest getInsightExchangeActionRequest() {
return insightExchangeActionRequest;
}
public void setInsightExchangeActionRequest(CRCustomerBehaviorAnalysisExchangeInputModelCustomerBehaviorAnalysisExchangeActionRequest insightExchangeActionRequest) {
this.insightExchangeActionRequest = insightExchangeActionRequest;
}
}
|
92440a76276bc144d3c4092e78da1e7e171095d8 | 2,858 | java | Java | src/main/java/com/tencentcloudapi/ckafka/v20190819/models/Topic.java | mndfcked/tencentcloud-sdk-java-intl-en | ab27205ca3485c63bcb3d5d0699df730970ad455 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tencentcloudapi/ckafka/v20190819/models/Topic.java | mndfcked/tencentcloud-sdk-java-intl-en | ab27205ca3485c63bcb3d5d0699df730970ad455 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tencentcloudapi/ckafka/v20190819/models/Topic.java | mndfcked/tencentcloud-sdk-java-intl-en | ab27205ca3485c63bcb3d5d0699df730970ad455 | [
"Apache-2.0"
] | null | null | null | 25.981818 | 83 | 0.655353 | 1,002,865 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.ckafka.v20190819.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class Topic extends AbstractModel{
/**
* Topic ID
*/
@SerializedName("TopicId")
@Expose
private String TopicId;
/**
* Topic name
*/
@SerializedName("TopicName")
@Expose
private String TopicName;
/**
* Remarks
Note: this field may return null, indicating that no valid values can be obtained.
*/
@SerializedName("Note")
@Expose
private String Note;
/**
* Get Topic ID
* @return TopicId Topic ID
*/
public String getTopicId() {
return this.TopicId;
}
/**
* Set Topic ID
* @param TopicId Topic ID
*/
public void setTopicId(String TopicId) {
this.TopicId = TopicId;
}
/**
* Get Topic name
* @return TopicName Topic name
*/
public String getTopicName() {
return this.TopicName;
}
/**
* Set Topic name
* @param TopicName Topic name
*/
public void setTopicName(String TopicName) {
this.TopicName = TopicName;
}
/**
* Get Remarks
Note: this field may return null, indicating that no valid values can be obtained.
* @return Note Remarks
Note: this field may return null, indicating that no valid values can be obtained.
*/
public String getNote() {
return this.Note;
}
/**
* Set Remarks
Note: this field may return null, indicating that no valid values can be obtained.
* @param Note Remarks
Note: this field may return null, indicating that no valid values can be obtained.
*/
public void setNote(String Note) {
this.Note = Note;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "TopicId", this.TopicId);
this.setParamSimple(map, prefix + "TopicName", this.TopicName);
this.setParamSimple(map, prefix + "Note", this.Note);
}
}
|
92440af65b9ffe7b701c7c87a9042e40bfe1db69 | 2,469 | java | Java | starter/critter/src/main/java/com/udacity/jdnd/course3/critter/services/impl/CustomerServiceImpl.java | OpeyemiOluwa12/nd035-c3-data-stores-and-persistence-project-starter | bd6845509e30a13211681ec00602780f028c6b4b | [
"MIT"
] | null | null | null | starter/critter/src/main/java/com/udacity/jdnd/course3/critter/services/impl/CustomerServiceImpl.java | OpeyemiOluwa12/nd035-c3-data-stores-and-persistence-project-starter | bd6845509e30a13211681ec00602780f028c6b4b | [
"MIT"
] | null | null | null | starter/critter/src/main/java/com/udacity/jdnd/course3/critter/services/impl/CustomerServiceImpl.java | OpeyemiOluwa12/nd035-c3-data-stores-and-persistence-project-starter | bd6845509e30a13211681ec00602780f028c6b4b | [
"MIT"
] | null | null | null | 33.364865 | 102 | 0.697043 | 1,002,866 | package com.udacity.jdnd.course3.critter.services.impl;
import com.udacity.jdnd.course3.critter.entities.CustomerEntity;
import com.udacity.jdnd.course3.critter.entities.PetEntity;
import com.udacity.jdnd.course3.critter.repositories.CustomerRepository;
import com.udacity.jdnd.course3.critter.repositories.PetRepository;
import com.udacity.jdnd.course3.critter.services.CustomerService;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerServiceImpl implements CustomerService {
private final CustomerRepository customerRepository;
private final PetRepository petRepository;
public CustomerServiceImpl(CustomerRepository customerRepository, PetRepository petRepository) {
this.customerRepository = customerRepository;
this.petRepository = petRepository;
}
/**
* Save customers details
*
* @param customerEntity form
* @param petIds
* @return saved customers details
*/
@Override
public CustomerEntity saveCustomer(CustomerEntity customerEntity, List<Long> petIds) {
List<PetEntity> petsToAssignedToCustomer = new ArrayList<>();
if (petIds != null && petIds.size() > 0) {
petIds.forEach(petId -> {
Optional<PetEntity> retrievedPet = petRepository.findById(petId);
if (retrievedPet.isPresent() && retrievedPet.get().getCustomer() == null) {
retrievedPet.get().setCustomer(customerEntity);
petsToAssignedToCustomer.add(retrievedPet.get());
}
});
}
customerEntity.setPets(petsToAssignedToCustomer);
return customerRepository.save(customerEntity);
}
/**
* @return the list of all customers
*/
@Override
public List<CustomerEntity> getAllCustomers() {
return customerRepository.findAll();
}
/**
* get the owner by pet
*
* @param petId of the pet
* @return customer
*/
@Override
public CustomerEntity getOwnerByPet(long petId) {
PetEntity petEntity = petRepository.findById(petId).orElseThrow(EntityNotFoundException::new);
return petEntity.getCustomer();
}
@Override
public CustomerEntity getCustomer(long customerId) {
return customerRepository.getOne(customerId);
}
}
|
92440b10309bd06bec54dd4c8eabc108892f6720 | 1,486 | java | Java | tool-parent/tool-actions/src/main/java/com/speedment/tool/actions/internal/resources/ProjectTreeIcon.java | YunLemon/speedment | 09211a6b65887b51e3d21581d583c0fd4b268b10 | [
"ECL-2.0",
"Apache-2.0"
] | 2,206 | 2015-05-21T04:43:59.000Z | 2022-03-28T13:57:16.000Z | tool-parent/tool-actions/src/main/java/com/speedment/tool/actions/internal/resources/ProjectTreeIcon.java | YunLemon/speedment | 09211a6b65887b51e3d21581d583c0fd4b268b10 | [
"ECL-2.0",
"Apache-2.0"
] | 877 | 2015-06-09T13:36:15.000Z | 2022-03-29T11:20:44.000Z | tool-parent/tool-actions/src/main/java/com/speedment/tool/actions/internal/resources/ProjectTreeIcon.java | anniyanvr/speedment | 27fa6fe4ad9e6e68d1c0e98655d1d52fbbc3f4d6 | [
"ECL-2.0",
"Apache-2.0"
] | 299 | 2015-05-29T12:36:04.000Z | 2022-03-31T12:33:40.000Z | 28.037736 | 80 | 0.703903 | 1,002,867 | /*
*
* Copyright (c) 2006-2020, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.tool.actions.internal.resources;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.io.InputStream;
/**
* Enumeration of all the icons used in the project tree by default. This enum
* might change in future versions!
*
* @author Emil Forslund
* @since 3.0.17
*/
public enum ProjectTreeIcon {
BOOK ("/com/speedment/tool/actions/icons/book.png"),
BOOK_OPEN ("/com/speedment/tool/actions/icons/bookOpen.png");
private final String filename;
ProjectTreeIcon(String filename) {
this.filename = filename;
}
public ImageView view() {
return new ImageView(image());
}
public Image image() {
return new Image(inputStream());
}
private InputStream inputStream() {
return getClass().getResourceAsStream(filename);
}
} |
92440b433e26548d871d36cd83f8169ad512d5f9 | 5,730 | java | Java | app/src/main/java/com/example/android/movie/modules/review/ReviewFragment.java | rodriguezVR/android-movie-app | f466252d599769a3a04aefe683a6bce401dd6cef | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/movie/modules/review/ReviewFragment.java | rodriguezVR/android-movie-app | f466252d599769a3a04aefe683a6bce401dd6cef | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/movie/modules/review/ReviewFragment.java | rodriguezVR/android-movie-app | f466252d599769a3a04aefe683a6bce401dd6cef | [
"Apache-2.0"
] | null | null | null | 34.727273 | 112 | 0.687609 | 1,002,868 | package com.example.android.movie.modules.review;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.movie.R;
import com.example.android.movie.databinding.FragmentReviewBinding;
import com.example.android.movie.model.Movie;
import com.example.android.movie.model.Review;
import com.example.android.movie.model.ReviewResponse;
import com.example.android.movie.utils.InjectorUtils;
import java.util.ArrayList;
import java.util.List;
import static com.example.android.movie.utils.Constant.EXTRA_MOVIE;
public class ReviewFragment extends Fragment implements ReviewAdapter.ReviewAdapterOnClickHandler {
/** Tag for a log message */
private static final String TAG = ReviewFragment.class.getSimpleName();
/** Member variable for the list of reviews */
private List<Review> mReviews;
/** This field is used for data binding */
private FragmentReviewBinding mReviewBinding;
/** Member variable for ReviewAdapter */
private ReviewAdapter mReviewAdapter;
/** Member variable for the Movie object */
private Movie mMovie;
/** ViewModel for ReviewFragment */
private ReviewViewModel mReviewViewModel;
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment
*/
public ReviewFragment() {
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Intent intent = getActivity().getIntent();
if (intent != null) {
if (intent.hasExtra(EXTRA_MOVIE)) {
Bundle b = intent.getBundleExtra(EXTRA_MOVIE);
mMovie = b.getParcelable(EXTRA_MOVIE);
}
}
setupViewModel(this.getActivity());
}
/**
* Every time the user data is updated, the onChanged callback will be invoked and update the UI
*/
private void setupViewModel(Context context) {
ReviewViewModelFactory factory = InjectorUtils.provideReviewViewModelFactory(context, mMovie.getId());
mReviewViewModel = ViewModelProviders.of(this, factory).get(ReviewViewModel.class);
mReviewViewModel.getReviewResponse().observe(this, new Observer<ReviewResponse>() {
@Override
public void onChanged(@Nullable ReviewResponse reviewResponse) {
if (reviewResponse != null) {
mReviews = reviewResponse.getReviewResults();
reviewResponse.setReviewResults(mReviews);
if (!mReviews.isEmpty()) {
mReviewAdapter.addAll(mReviews);
} else {
showNoReviewsMessage();
}
}
}
});
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mReviewBinding = DataBindingUtil.inflate(
inflater, R.layout.fragment_review, container, false);
View rootView = mReviewBinding.getRoot();
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
mReviewBinding.rvReview.setLayoutManager(layoutManager);
mReviewBinding.rvReview.setHasFixedSize(true);
mReviews = new ArrayList<>();
mReviewAdapter = new ReviewAdapter(mReviews, this);
mReviewBinding.rvReview.setAdapter(mReviewAdapter);
showOfflineMessage(isOnline());
return rootView;
}
/**
* Handles RecyclerView item clicks to open a website that displays the user review.
*
* @param url The URL that displays the user review
*/
@Override
public void onItemClick(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
/**
* This method will make the message that says no reviews found visible and
* hide the View for the review data
*/
private void showNoReviewsMessage() {
mReviewBinding.rvReview.setVisibility(View.INVISIBLE);
mReviewBinding.tvNoReviews.setVisibility(View.VISIBLE);
}
/**
* Make the offline message visible and hide the review View when offline
*
* @param isOnline True when connected to the network
*/
private void showOfflineMessage(boolean isOnline) {
if (isOnline) {
mReviewBinding.tvOffline.setVisibility(View.INVISIBLE);
mReviewBinding.rvReview.setVisibility(View.VISIBLE);
} else {
mReviewBinding.rvReview.setVisibility(View.INVISIBLE);
mReviewBinding.tvOffline.setVisibility(View.VISIBLE);
}
}
/**
* Check if there is the network connectivity
*
* @return true if connected to the network
*/
private boolean isOnline() {
ConnectivityManager connectivityManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
}
|
92440b58c8b857d6526344abfa981ca489ee11a4 | 869 | java | Java | app/src/main/java/cn/bmob/imdemo/Config.java | pan452124/NewIM | d1697fd8405155221fec22c95fdd398fdb652276 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/cn/bmob/imdemo/Config.java | pan452124/NewIM | d1697fd8405155221fec22c95fdd398fdb652276 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/cn/bmob/imdemo/Config.java | pan452124/NewIM | d1697fd8405155221fec22c95fdd398fdb652276 | [
"Apache-2.0"
] | null | null | null | 28.966667 | 87 | 0.721519 | 1,002,869 | package cn.bmob.imdemo;
/**
* @author :smile
* @project:Config
* @date :2016-01-15-18:23
*/
public class Config {
/**
* Bmob应用key
*/
// public static final String DEFAULT_APPKEY="d6f44e8f1ba9d3dcf4fab7a487fa97dd";//内
public static final String DEFAULT_APPKEY="87ab0f9bee41bce86dfadd69af692873";//外
// public static final String DEFAULT_APPKEY="74t3tndxag9o7h0890bnpfzh4olk2h9x";//潮州
//是否是debug模式
public static final boolean DEBUG=true;
//好友请求:未读-未添加->接收到别人发给我的好友添加请求,初始状态
public static final int STATUS_VERIFY_NONE=0;
//好友请求:已读-未添加->点击查看了新朋友,则都变成已读状态
public static final int STATUS_VERIFY_READED=2;
//好友请求:已添加
public static final int STATUS_VERIFIED=1;
//好友请求:拒绝
public static final int STATUS_VERIFY_REFUSE=3;
//好友请求:我发出的好友请求-暂未存储到本地数据库中
public static final int STATUS_VERIFY_ME_SEND=4;
}
|
92440ba1058ed9757266e07ee585dd59d8daacfe | 1,316 | java | Java | com.microsoft.java.lsif.core/src/com/microsoft/java/lsif/core/internal/protocol/Event.java | Microsoft/lsif-java | 5bae762a9093598f29a0643b28d59d8b23b80fc4 | [
"MIT"
] | 2 | 2019-05-03T00:08:16.000Z | 2019-05-06T01:55:24.000Z | com.microsoft.java.lsif.core/src/com/microsoft/java/lsif/core/internal/protocol/Event.java | Microsoft/lsif-java | 5bae762a9093598f29a0643b28d59d8b23b80fc4 | [
"MIT"
] | 1 | 2019-04-29T03:31:30.000Z | 2019-04-29T04:43:41.000Z | com.microsoft.java.lsif.core/src/com/microsoft/java/lsif/core/internal/protocol/Event.java | Microsoft/lsif-java | 5bae762a9093598f29a0643b28d59d8b23b80fc4 | [
"MIT"
] | null | null | null | 24.830189 | 80 | 0.639058 | 1,002,870 | /*******************************************************************************
* Copyright (c) 2021 Microsoft Corporation and others.
* 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:
* Microsoft Corporation - initial API and implementation
*******************************************************************************/
package com.microsoft.java.lsif.core.internal.protocol;
public class Event extends Vertex {
private String kind;
private String scope;
private String data;
public Event(String id, String scope, String kind, String data) {
super(id, Vertex.EVENT);
this.scope = scope;
this.kind = kind;
this.data = data;
}
public String getScope() {
return scope;
}
public String getKind() {
return kind;
}
public String getData() {
return data;
}
public static class EventScope {
public static final String Group = "group";
public static final String Project = "project";
public static final String DOCUMENT = "document";
}
public static class EventKind {
public static final String BEGIN = "begin";
public static final String END = "end";
}
}
|
92440be623b87ff0d12effb3587d803b0a063ee2 | 299 | java | Java | src/org/pipservices3/commons/convert/TypeCode.java | pip-services3-java/pip-services3-commons-java | 39ffcb7fcf0bbec7f1351139e1f8eedb7bd5b802 | [
"MIT"
] | null | null | null | src/org/pipservices3/commons/convert/TypeCode.java | pip-services3-java/pip-services3-commons-java | 39ffcb7fcf0bbec7f1351139e1f8eedb7bd5b802 | [
"MIT"
] | 3 | 2020-05-15T21:04:22.000Z | 2021-12-09T20:30:41.000Z | src/org/pipservices3/commons/convert/TypeCode.java | pip-services3-java/pip-services3-commons-java | 39ffcb7fcf0bbec7f1351139e1f8eedb7bd5b802 | [
"MIT"
] | null | null | null | 12.458333 | 41 | 0.688963 | 1,002,871 | package org.pipservices3.commons.convert;
/**
* Codes for the data types that can be
* converted using {@link TypeConverter}.
*
* @see TypeConverter
*/
public enum TypeCode {
Unknown,
String,
Boolean,
Integer,
Long,
Float,
Double,
DateTime,
Duration,
Object,
Enum,
Array,
Map,
}
|
92440d0e7b04fc6e4aa344eb74bfce86ec59b810 | 6,768 | java | Java | zap/src/main/java/org/zaproxy/zap/view/ZapMenuItem.java | ACME-Corp-Demo/zaproxy | 394113149cde858b4ebc5d3737fdc83931837280 | [
"Apache-2.0"
] | 10,016 | 2015-06-03T17:30:01.000Z | 2022-03-31T23:48:56.000Z | zap/src/main/java/org/zaproxy/zap/view/ZapMenuItem.java | ekmixon/zaproxy | acce44eb7c020265956bf5dbb465d2e1d08803cb | [
"Apache-2.0"
] | 7,043 | 2015-06-04T11:50:06.000Z | 2022-03-31T16:25:45.000Z | zap/src/main/java/org/zaproxy/zap/view/ZapMenuItem.java | ekmixon/zaproxy | acce44eb7c020265956bf5dbb465d2e1d08803cb | [
"Apache-2.0"
] | 2,258 | 2015-06-04T16:37:05.000Z | 2022-03-31T14:43:54.000Z | 37.6 | 100 | 0.683363 | 1,002,872 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2014 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.view;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import org.parosproxy.paros.Constant;
/**
* A {@code JMenuItem} that has an identifier, allows to define the default accelerator and uses a
* internationalised text and, optionally, a mnemonic, both read from resource files.
*
* <p>The use of this class is preferred to {@code JMenuItem} as it allows the user to configure its
* accelerator through the options dialogue. The identifier is used to save/load its configurations.
*
* <p>Example usage:
*
* <blockquote>
*
* <pre>{@code
* // Obtain the system dependent accelerator modifier key
* int acceleratorModifierKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
* KeyStroke defaultAccelerator = KeyStroke.getKeyStroke(KeyEvent.VK_R, acceleratorModifierKey);
* ZapMenuItem menuItem = new ZapMenuItem("menu.report", defaultAccelerator);
* }</pre>
*
* </blockquote>
*
* and in the resource file (e.g. Messages.properties) define the keys:
*
* <blockquote>
*
* <pre>{@code
* menu.report = Report
* # Optionally define its mnemonic
* menu.report.mnemonic = R
* }</pre>
*
* </blockquote>
*
* @since 2.3.0
*/
public class ZapMenuItem extends JMenuItem {
private static final long serialVersionUID = 1L;
private String identifier;
private KeyStroke defaultAccelerator;
/**
* Constructs a {@code ZapMenuItem} with the text for the menu obtained from the resource files
* (e.g. Messages.properties) using as key the parameter {@code i18nKey} and using the given
* {@code KeyStroke} as default accelerator (the user can override the accelerator through the
* configurations).
*
* <p>The parameter {@code i18nKey} is used as identifier (to save/load configurations, like its
* accelerator) and it will also be used to attempt to create its mnemonic, by using as key
* {@code <i18nKey>.mnemonic}. No mnemonic is set if the key does not exist in the resource
* files.
*
* <p><strong>Note:</strong> This constructor is preferred to {@link #ZapMenuItem(String,
* String, KeyStroke)}, as it supports the (automatic) load of internationalised text and
* definition of the mnemonic.
*
* @param i18nKey the key used to read the internationalised text for the menu item and,
* optionally, its mnemonic
* @param defaultAccelerator the default accelerator for the menu item, might be {@code null}.
* @see #setMnemonic(int)
* @see #setAccelerator(KeyStroke)
* @throws NullPointerException if {@code i18nKey} is {@code null}.
*/
public ZapMenuItem(String i18nKey, KeyStroke defaultAccelerator) {
this(i18nKey, Constant.messages.getString(i18nKey), defaultAccelerator);
// This will handle missing i18n keys ok
this.setMnemonic(Constant.messages.getChar(i18nKey + ".mnemonic"));
}
/**
* Constructs a {@code ZapMenuItem} with the given {@code identifier}, {@code text} and default
* accelerator (user can override the accelerator through the configurations).
*
* <p><strong>Note:</strong> The constructor {@link #ZapMenuItem(String, KeyStroke)} is
* preferred to this one, as it supports the (automatic) load of internationalised text and
* definition of the mnemonic.
*
* @param identifier the identifier for the menu item (used to save/load configurations), should
* not be {@code null}
* @param text the text shown in the menu item
* @param defaultAccelerator the default accelerator for the menu item, might be {@code null}
* @see #setMnemonic(int)
*/
public ZapMenuItem(String identifier, String text, KeyStroke defaultAccelerator) {
super(text);
this.identifier = identifier;
this.defaultAccelerator = defaultAccelerator;
if (defaultAccelerator != null) {
// Note that this can be overridden by the Keyboard extension
this.setAccelerator(defaultAccelerator);
}
}
/**
* Constructs a {@code ZapMenuItem} with the text for the menu obtained from the resources file
* (e.g. Messages.properties) using as key the given parameter and with no default accelerator.
*
* <p>The given parameter is used as identifier (to save/load configurations, like its
* accelerator) and it will also be used to attempt to create its mnemonic, by using as key
* {@code <i18nKey>.mnemonic}. No mnemonic is set if the key does not exist in the resource
* files.
*
* @param i18nKey the key used to read the internationalised text for the menu item and,
* optionally, its mnemonic
* @throws NullPointerException if {@code i18nKey} is {@code null}.
* @see ZapMenuItem#ZapMenuItem(String, KeyStroke)
* @see #setMnemonic(int)
*/
public ZapMenuItem(String i18nKey) {
this(i18nKey, null);
}
/**
* Gets the identifier of the menu item.
*
* @return the identifier, might be {@code null}.
* @since 2.8.0
*/
public String getIdentifier() {
return this.identifier;
}
/**
* Gets the identifier of the menu item.
*
* @return the identifier, might be {@code null}
* @deprecated (2.8.0) Use {@link #getIdentifier()} instead.
*/
@Deprecated
public String getIdenfifier() {
return this.identifier;
}
/**
* Resets the accelerator to default value (which might be {@code null} thus just removing any
* accelerator previously set).
*
* @see #getDefaultAccelerator()
*/
public void resetAccelerator() {
this.setAccelerator(this.defaultAccelerator);
}
/**
* Gets the default accelerator, defined when the menu item was constructed.
*
* @return a {@code KeyStroke} with the default accelerator, might be {@code null}.
* @see #resetAccelerator()
*/
public KeyStroke getDefaultAccelerator() {
return defaultAccelerator;
}
}
|
92440f49a74e0e841aafa032b4a0f00fff338bc9 | 428 | java | Java | Development/org.mdse.pts.common/src/org/mdse/pts/common/util/ExtensionToFactoryMap.java | JnxF/mosyl | d6645a0cb42615bed4e77de25af8bd3248668d6e | [
"MIT"
] | null | null | null | Development/org.mdse.pts.common/src/org/mdse/pts/common/util/ExtensionToFactoryMap.java | JnxF/mosyl | d6645a0cb42615bed4e77de25af8bd3248668d6e | [
"MIT"
] | null | null | null | Development/org.mdse.pts.common/src/org/mdse/pts/common/util/ExtensionToFactoryMap.java | JnxF/mosyl | d6645a0cb42615bed4e77de25af8bd3248668d6e | [
"MIT"
] | null | null | null | 21.4 | 74 | 0.742991 | 1,002,873 | package org.mdse.pts.common.util;
public class ExtensionToFactoryMap {
private String extension;
private Object resourceFactory;
public ExtensionToFactoryMap(String extension, Object resourceFactory) {
this.extension = extension;
this.resourceFactory = resourceFactory;
}
public String getExtension() {
return extension;
}
public Object getResourceFactory() {
return resourceFactory;
}
}
|
92440fcf1f5cb9e3316163851d79466f6f24eb67 | 418 | java | Java | src/main/java/com/crm/erk/server/CrmErkServerApplication.java | shicham/erk-server | 4c87c9091cc875738df87c259010b8b73293ae4d | [
"MIT"
] | null | null | null | src/main/java/com/crm/erk/server/CrmErkServerApplication.java | shicham/erk-server | 4c87c9091cc875738df87c259010b8b73293ae4d | [
"MIT"
] | null | null | null | src/main/java/com/crm/erk/server/CrmErkServerApplication.java | shicham/erk-server | 4c87c9091cc875738df87c259010b8b73293ae4d | [
"MIT"
] | null | null | null | 26.125 | 74 | 0.837321 | 1,002,874 | package com.crm.erk.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class CrmErkServerApplication {
public static void main(String[] args) {
SpringApplication.run(CrmErkServerApplication.class, args);
}
}
|
9244113871af2ff16edd692299cb64d802680a8b | 2,690 | java | Java | jung-3d/src/main/java/edu/uci/ics/jung/visualization3d/PickVertexBehavior.java | JanSurft/jung2 | 26831d3428482407a9c48e662d2d64527703cb12 | [
"BSD-3-Clause"
] | null | null | null | jung-3d/src/main/java/edu/uci/ics/jung/visualization3d/PickVertexBehavior.java | JanSurft/jung2 | 26831d3428482407a9c48e662d2d64527703cb12 | [
"BSD-3-Clause"
] | null | null | null | jung-3d/src/main/java/edu/uci/ics/jung/visualization3d/PickVertexBehavior.java | JanSurft/jung2 | 26831d3428482407a9c48e662d2d64527703cb12 | [
"BSD-3-Clause"
] | null | null | null | 26.95 | 105 | 0.748423 | 1,002,875 | /*
* Copyright (c) 2003, the JUNG Project and the Regents of the University of
* California All rights reserved.
*
* This software is open-source under the BSD license; see either "license.txt"
* or http://jung.sourceforge.net/license.txt for a description.
*/
package edu.uci.ics.jung.visualization3d;
/**
*/
import java.awt.event.MouseEvent;
import javax.media.j3d.Bounds;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.TransformGroup;
import javax.swing.event.ChangeListener;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.PickTool;
import com.sun.j3d.utils.picking.behaviors.PickTranslateBehavior;
import edu.uci.ics.jung.visualization.picking.PickedState;
import edu.uci.ics.jung.visualization.util.ChangeEventSupport;
import edu.uci.ics.jung.visualization.util.DefaultChangeEventSupport;
/**
*
* @author Tom Nelson - [email protected]
*
*/
public class PickVertexBehavior<V,E> extends PickTranslateBehavior implements ChangeEventSupport {
Bounds bounds;
BranchGroup root;
ChangeEventSupport support = new DefaultChangeEventSupport(this);
PickedState<V> pickedState;
public PickVertexBehavior(BranchGroup root, Canvas3D canvas, Bounds bounds, PickedState<V> pickedState){
super(root, canvas, bounds);
this.setSchedulingBounds(bounds);
this.bounds = bounds;
this.root = root;
this.pickedState = pickedState;
pickCanvas.setMode(PickTool.GEOMETRY);
}
public void updateScene(int xpos, int ypos){
if(mevent.getButton() == MouseEvent.BUTTON1) { // ButtonOne
int buttonOne = MouseEvent.BUTTON1_MASK;
int shiftButtonOne = MouseEvent.BUTTON1_MASK | MouseEvent.SHIFT_MASK;
int modifiers = mevent.getModifiers();
if(modifiers == buttonOne) {
// clear previous picked stuff
pickedState.clear();
doPick(xpos, ypos);
} else if(modifiers == shiftButtonOne) {
doPick(xpos, ypos);
}
}
}
private void doPick(int xpos, int ypos) {
pickCanvas.setShapeLocation(xpos, ypos);
PickResult result = pickCanvas.pickClosest();
if(result != null) {
TransformGroup tg = (TransformGroup)result.getNode(PickResult.TRANSFORM_GROUP);
if(tg instanceof VertexGroup) {
System.err.println("picked "+tg);
pickedState.pick(((VertexGroup<V>)tg).vertex, true);
fireStateChanged();
}
}
}
public void addChangeListener(ChangeListener l) {
support.addChangeListener(l);
}
public void fireStateChanged() {
support.fireStateChanged();
}
public ChangeListener[] getChangeListeners() {
return support.getChangeListeners();
}
public void removeChangeListener(ChangeListener l) {
support.removeChangeListener(l);
}
}
|
924411a0993885534e31c4e73a9c0f6a210525b6 | 1,940 | java | Java | dd-java-agent/agent-profiling/profiling-auxiliary-async/src/main/java/com/datadog/profiling/auxiliary/async/AsyncProfilerRecording.java | owendavisco/dd-trace-java | 975790206c4d55d79d504d6a5d1e4fa19c0496d3 | [
"Apache-2.0"
] | null | null | null | dd-java-agent/agent-profiling/profiling-auxiliary-async/src/main/java/com/datadog/profiling/auxiliary/async/AsyncProfilerRecording.java | owendavisco/dd-trace-java | 975790206c4d55d79d504d6a5d1e4fa19c0496d3 | [
"Apache-2.0"
] | null | null | null | dd-java-agent/agent-profiling/profiling-auxiliary-async/src/main/java/com/datadog/profiling/auxiliary/async/AsyncProfilerRecording.java | owendavisco/dd-trace-java | 975790206c4d55d79d504d6a5d1e4fa19c0496d3 | [
"Apache-2.0"
] | null | null | null | 28.529412 | 97 | 0.72732 | 1,002,876 | package com.datadog.profiling.auxiliary.async;
import com.datadog.profiling.controller.OngoingRecording;
import com.datadog.profiling.controller.RecordingData;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class AsyncProfilerRecording implements OngoingRecording {
private static final Logger log = LoggerFactory.getLogger(AsyncProfilerRecording.class);
private final AuxiliaryAsyncProfiler profiler;
private volatile Path recordingFile;
private final Instant started = Instant.now();
/**
* Do not use this constructor directly. Rather use {@linkplain AuxiliaryAsyncProfiler#start()}
*
* @param profiler the associated profiler
* @throws IOException
*/
AsyncProfilerRecording(AuxiliaryAsyncProfiler profiler) throws IOException {
this.profiler = profiler;
this.recordingFile = profiler.newRecording();
}
@Nonnull
@Override
public RecordingData stop() {
profiler.stopProfiler();
return new AsyncProfilerRecordingData(recordingFile, started, Instant.now());
}
@Nonnull
@Override
public RecordingData snapshot(@Nonnull Instant start) {
profiler.stop(this);
RecordingData data = new AsyncProfilerRecordingData(recordingFile, start, Instant.now());
try {
recordingFile = profiler.newRecording();
} catch (IOException | IllegalStateException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to start async profiler recording", e);
} else {
log.warn("Unable to start async profiler recording: {}", e.getMessage());
}
}
return data;
}
@Override
public void close() {
try {
Files.deleteIfExists(recordingFile);
} catch (IOException ignored) {
}
}
// used for tests only
Path getRecordingFile() {
return recordingFile;
}
}
|
92441234b38917711a1f2d98e37ee65869ca7dc9 | 664 | java | Java | src/main/java/com/microsoft/graph/models/generated/AndroidEapType.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/graph/models/generated/AndroidEapType.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | 1 | 2021-02-23T20:48:12.000Z | 2021-02-23T20:48:12.000Z | src/main/java/com/microsoft/graph/models/generated/AndroidEapType.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | null | null | null | 22.133333 | 152 | 0.46988 | 1,002,877 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.generated;
/**
* The Enum Android Eap Type.
*/
public enum AndroidEapType
{
/**
* eap Tls
*/
EAP_TLS,
/**
* eap Ttls
*/
EAP_TTLS,
/**
* peap
*/
PEAP,
/**
* For AndroidEapType values that were not expected from the service
*/
UNEXPECTED_VALUE
}
|
9244148a841a03249676ceeb8a1db460eeaaf4d0 | 3,011 | java | Java | src/main/java/com/therandomlabs/utils/platform/WindowsVersion.java | TheRandomLabs/TRLUtils-Platform | 6ddf3cc304c533110ee8f4eb83f6820877ede489 | [
"MIT"
] | 1 | 2020-06-22T10:48:23.000Z | 2020-06-22T10:48:23.000Z | src/main/java/com/therandomlabs/utils/platform/WindowsVersion.java | TheRandomLabs/TRLUtils-Platform | 6ddf3cc304c533110ee8f4eb83f6820877ede489 | [
"MIT"
] | 2 | 2020-01-02T04:24:52.000Z | 2020-01-02T04:27:29.000Z | src/main/java/com/therandomlabs/utils/platform/WindowsVersion.java | TheRandomLabs/TRLUtils-Platform | 6ddf3cc304c533110ee8f4eb83f6820877ede489 | [
"MIT"
] | null | null | null | 29.23301 | 91 | 0.726337 | 1,002,878 | /*
* The MIT License (MIT)
*
* Copyright (c) 2019-2020 TheRandomLabs
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.therandomlabs.utils.platform;
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
/**
* Contains {@link OSVersion}s that represent Windows versions that can run JRE 8 or newer.
*/
public final class WindowsVersion {
/**
* Windows Vista.
*/
public static final OSVersion WINDOWS_VISTA = get("Vista");
/**
* Windows 7.
*/
public static final OSVersion WINDOWS_7 = get("7");
/**
* Windows Server 2008, the server version of Windows Vista,
* or Windows Server 2008 R2, the server version of Windows 7.
*/
public static final OSVersion WINDOWS_SERVER_2008 = get("Server 2008");
/**
* Windows 8.
*/
public static final OSVersion WINDOWS_8 = get("8");
/**
* Windows 8.1.
*/
public static final OSVersion WINDOWS_8_1 = get("8.1");
/**
* Windows Server 2012, the server version of Windows 8.
*/
public static final OSVersion WINDOWS_SERVER_2012 = get("Server 2012");
/**
* Windows 10.
*/
public static final OSVersion WINDOWS_10 = get("10");
/**
* Windows Server 2016, the server version of Windows 10.
*/
public static final OSVersion WINDOWS_SERVER_2016 = get("Server 2016");
private static final Set<OSVersion> versions = ImmutableSet.of(
WINDOWS_VISTA,
WINDOWS_7,
WINDOWS_SERVER_2008,
WINDOWS_8,
WINDOWS_8_1,
WINDOWS_SERVER_2012,
WINDOWS_10,
WINDOWS_SERVER_2016
);
private WindowsVersion() {}
/**
* Returns all {@link OSVersion} instances that represent known Windows versions.
*
* @return a mutable {@link Set} containing all {@link OSVersion} instances that represent
* known Windows versions.
*/
public static Set<OSVersion> getVersions() {
return new HashSet<>(versions);
}
private static OSVersion get(String versionNumber) {
return new OSVersion("Windows " + versionNumber, versionNumber);
}
}
|
Subsets and Splits