hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
f977c94eb1b42dc15600bd8e71084db586fb13d7 | 26,953 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2019 Guardsquare NV
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.configuration;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
/**
* This class can be injected in applications to log information about reflection
* being used in the application code, and suggest appropriate ProGuard rules for
* keeping the reflected classes, methods and/or fields.
*
* @author Johan Leys
*/
public class ConfigurationLogger implements Runnable
{
public static final boolean LOG_ONCE = true;
private static final String LOG_TAG = "ProGuard";
public static final String CLASS_MAP_FILENAME = "classmap.txt";
private static final String EMPTY_LINE = "\u00a0\n";
// Set with missing class names.
private static final Set<String> missingClasses = new HashSet<String>();
// Map from class name to missing constructors.
private static final Map<String, Set<MethodSignature>> missingConstructors = new HashMap<String, Set<MethodSignature>>();
// Set of classes on which getConstructors or getDeclaredConstructors is invoked.
private static final Set<String> constructorListingClasses = new HashSet<String>();
// Map from class name to missing method signatures.
private static final Map<String, Set<MethodSignature>> missingMethods = new HashMap<String, Set<MethodSignature>>();
// Set of classes on which getMethods or getDeclaredMethods is invoked.
private static final Set<String> methodListingClasses = new HashSet<String>();
// Map from class name to missing field names.
private static final Map<String, Set<String>> missingFields = new HashMap<String, Set<String>>();
// Set of classes on which getFields or getDeclaredFields is invoked.
private static final Set<String> fieldListingCLasses = new HashSet<String>();
// Map from obfuscated class name to original class name.
private static Map<String, String> classNameMap;
// Set of classes that have renamed or removed methods.
private static Set<String> classesWithObfuscatedMethods;
// Set of classes that have renamed or removed fields.
private static Set<String> classesWithObfuscatedFields;
private static Method logMethod;
// Try to find the Android logging class.
static
{
try
{
Class<?> logClass = Class.forName("android.util.Log");
logMethod = logClass.getMethod("w", String.class, String. class);
}
catch (Exception e) {}
}
// Classes.
/**
* Log a failed call to Class.forName().
*
* @param callingClassName
* @param missingClassName
*/
public static void logForName(String callingClassName,
String missingClassName)
{
logMissingClass(callingClassName, "Class", "forName", missingClassName);
}
/**
* Log a failed call to ClassLoader.loadClass().
*
* @param callingClassName
* @param missingClassName
*/
public static void logLoadClass(String callingClassName,
String missingClassName)
{
logMissingClass(callingClassName, "ClassLoader", "loadClass", missingClassName);
}
/**
* Log a failed call to Class.forName().
*
* @param callingClassName
* @param missingClassName
*/
public static void logMissingClass(String callingClassName,
String invokedClassName,
String invokedMethodName,
String missingClassName)
{
if (!LOG_ONCE || !missingClasses.contains(missingClassName))
{
missingClasses.add(missingClassName);
log(
"The class '" + originalClassName(callingClassName) + "' is calling " + invokedClassName + "." + invokedMethodName + " to retrieve\n" +
"the class '" + missingClassName + "', but the latter could not be found.\n" +
"It may have been obfuscated or shrunk.\n" +
"You should consider preserving the class with its original name,\n" +
"with a setting like:\n" +
EMPTY_LINE +
keepClassRule(missingClassName) + "\n" +
EMPTY_LINE);
}
}
// Constructors.
/**
* Log a failed call to Class.getDeclaredConstructor().
*
* @param invokingClassName
* @param reflectedClass
* @param constructorParameters
*/
public static void logGetDeclaredConstructor(String invokingClassName,
Class reflectedClass,
Class[] constructorParameters)
{
logGetConstructor(invokingClassName, "getDeclaredConstructor", reflectedClass, constructorParameters);
}
/**
* Log a failed call to Class.getConstructor().
*
* @param invokingClassName
* @param reflectedClass
* @param constructorParameters
*/
public static void logGetConstructor(String invokingClassName,
Class reflectedClass,
Class[] constructorParameters)
{
logGetConstructor(invokingClassName, "getConstructor", reflectedClass, constructorParameters);
}
/**
* Log a failed call to one of the constructor retrieving methods on Class.
*
* @param invokingClassName
* @param invokedMethodName
* @param reflectedClass
* @param constructorParameters
*/
public static void logGetConstructor(String invokingClassName,
String invokedMethodName,
Class reflectedClass,
Class[] constructorParameters)
{
MethodSignature signature = new MethodSignature("<init>", constructorParameters);
Set<MethodSignature> constructors = missingConstructors.get(reflectedClass.getName());
if (constructors == null)
{
constructors = new HashSet<MethodSignature>();
missingConstructors.put(reflectedClass.getName(), constructors);
}
if ((!LOG_ONCE || !constructors.contains(signature)) && !isLibraryClass(reflectedClass))
{
constructors.add(signature);
log(
"The class '" + originalClassName(invokingClassName) + "' is calling Class." + invokedMethodName + "\n" +
"on class '" + originalClassName(reflectedClass) + "' to retrieve\n" +
"the constructor with signature (" + originalSignature(signature) + "), but the latter could not be found.\n" +
"It may have been obfuscated or shrunk.\n" +
"You should consider preserving the constructor, with a setting like:\n" +
EMPTY_LINE +
keepConstructorRule(reflectedClass.getName(), signature) + "\n" +
EMPTY_LINE);
}
}
/**
* Log a call to Class.getDeclaredConstructors().
*
* @param invokingClassName
* @param reflectedClass
*/
public static void logGetDeclaredConstructors(String invokingClassName,
Class reflectedClass )
{
logGetConstructors(invokingClassName, reflectedClass, "getDeclaredConstructors");
}
/**
* Log a call to Class.getConstructors().
*
* @param invokingClassName
* @param reflectedClass
*/
public static void logGetConstructors(String invokingClassName,
Class reflectedClass )
{
logGetConstructors(invokingClassName, reflectedClass, "getConstructors");
}
/**
* Log a call to one of the constructor listing methods on Class.
*
* @param invokingClassName
* @param reflectedClass
* @param reflectedMethodName
*/
private static void logGetConstructors(String invokingClassName,
Class reflectedClass,
String reflectedMethodName)
{
initializeMappings();
if (classesWithObfuscatedMethods.contains(reflectedClass.getName()) &&
!constructorListingClasses.contains(reflectedClass.getName()) &&
!isLibraryClass(reflectedClass))
{
constructorListingClasses.add(reflectedClass.getName());
log(
"The class '" + originalClassName(invokingClassName) + "' is calling Class." + reflectedMethodName + "\n" +
"on class '" + originalClassName(reflectedClass) + "' to retrieve its constructors.\n" +
"You might consider preserving all constructors with their original names,\n" +
"with a setting like:\n" +
EMPTY_LINE +
keepAllConstructorsRule(reflectedClass) + "\n" +
EMPTY_LINE);
}
}
// Methods.
/**
* Log a failed call to Class.getDeclaredMethod().
*
* @param invokingClassName
* @param reflectedClass
* @param reflectedMethodName
* @param methodParameters
*/
public static void logGetDeclaredMethod(String invokingClassName,
Class reflectedClass,
String reflectedMethodName,
Class[] methodParameters )
{
logGetMethod(invokingClassName, "getDeclaredMethod", reflectedClass, reflectedMethodName, methodParameters);
}
/**
* Log a failed call to Class.getMethod().
*
* @param invokingClassName
* @param reflectedClass
* @param reflectedMethodName
* @param methodParameters
*/
public static void logGetMethod(String invokingClassName,
Class reflectedClass,
String reflectedMethodName,
Class[] methodParameters )
{
logGetMethod(invokingClassName, "getMethod", reflectedClass, reflectedMethodName, methodParameters);
}
/**
* Log a failed call to one of the method retrieving methods on Class.
* @param invokingClassName
* @param invokedReflectionMethodName
* @param reflectedClass
* @param reflectedMethodName
* @param methodParameters
*/
private static void logGetMethod(String invokingClassName,
String invokedReflectionMethodName,
Class reflectedClass,
String reflectedMethodName,
Class[] methodParameters )
{
Set<MethodSignature> methods = missingMethods.get(reflectedClass.getName());
if (methods == null)
{
methods = new HashSet<MethodSignature>();
missingMethods.put(reflectedClass.getName(), methods);
}
MethodSignature signature = new MethodSignature(reflectedMethodName, methodParameters);
if (!methods.contains(signature) && !isLibraryClass(reflectedClass))
{
methods.add(signature);
log(
"The class '" + originalClassName(invokingClassName) +
"' is calling Class." + invokedReflectionMethodName + "\n" +
"on class '" + originalClassName(reflectedClass) +
"' to retrieve the method\n" +
reflectedMethodName + "(" + originalSignature(signature) + "),\n" +
"but the latter could not be found. It may have been obfuscated or shrunk.\n" +
"You should consider preserving the method with its original name,\n" +
"with a setting like:\n" +
EMPTY_LINE +
keepMethodRule(reflectedClass.getName(), reflectedMethodName, signature) + "\n" +
EMPTY_LINE);
}
}
/**
* Log a call to Class.getDeclaredMethods().
*
* @param invokingClassName
* @param reflectedClass
*/
public static void logGetDeclaredMethods(String invokingClassName,
Class reflectedClass )
{
logGetMethods(invokingClassName, "getDeclaredMethods", reflectedClass);
}
/**
* Log a call to Class.getMethods().
*
* @param invokingClassName
* @param reflectedClass
*/
public static void logGetMethods(String invokingClassName,
Class reflectedClass )
{
logGetMethods(invokingClassName, "getMethods", reflectedClass);
}
/**
* Log a call to one of the method listing methods on Class.
*
* @param invokingClassName
* @param invokedReflectionMethodName
* @param reflectedClass
*/
private static void logGetMethods(String invokingClassName,
String invokedReflectionMethodName,
Class reflectedClass )
{
initializeMappings();
if (classesWithObfuscatedMethods.contains(reflectedClass.getName()) &&
!methodListingClasses.contains(reflectedClass.getName()) &&
!isLibraryClass(reflectedClass))
{
methodListingClasses.add(reflectedClass.getName());
log(
"The class '" + originalClassName(invokingClassName) +
"' is calling Class." + invokedReflectionMethodName + "\n" +
"on class '" + originalClassName(reflectedClass) +
"' to retrieve its methods.\n" +
"You might consider preserving all methods with their original names,\n" +
"with a setting like:\n" +
EMPTY_LINE +
keepAllMethodsRule(reflectedClass) + "\n" +
EMPTY_LINE);
}
}
// Fields.
/**
* Log a failed call to Class.getField().
*
* @param invokingClassName
* @param reflectedClass
* @param reflectedFieldName
*/
public static void logGetField(String invokingClassName,
Class reflectedClass,
String reflectedFieldName)
{
logGetField(invokingClassName, "getField", reflectedClass, reflectedFieldName);
}
/**
* Log a failed call to Class.getDeclaredField().
*
* @param invokingClassName
* @param reflectedClass
* @param reflectedFieldName
*/
public static void logGetDeclaredField(String invokingClassName,
Class reflectedClass,
String reflectedFieldName)
{
logGetField(invokingClassName, "getDeclaredField", reflectedClass, reflectedFieldName);
}
/**
* Log a failed call to one of the field retrieving methods of Class.
*
* @param invokingClassName
* @param invokedReflectionMethodName
* @param reflectedClass
* @param reflectedFieldName
*/
private static void logGetField(String invokingClassName,
String invokedReflectionMethodName,
Class reflectedClass,
String reflectedFieldName )
{
Set<String> fields = missingFields.get(reflectedClass.getName());
if (fields == null)
{
fields = new HashSet<String>();
missingFields.put(reflectedClass.getName(), fields);
}
if ((!LOG_ONCE || !fields.contains(reflectedFieldName)) &&
!isLibraryClass(reflectedClass))
{
fields.add(reflectedFieldName);
log(
"The class '" + originalClassName(invokingClassName) +
"' is calling Class." + invokedReflectionMethodName + "\n" +
"on class '" + originalClassName(reflectedClass) +
"' to retrieve the field '" + reflectedFieldName + "',\n" +
"but the latter could not be found. It may have been obfuscated or shrunk.\n" +
"You should consider preserving the field with its original name,\n" +
"with a setting like:\n" +
EMPTY_LINE +
keepFieldRule(reflectedClass.getName(), reflectedFieldName) + "\n" +
EMPTY_LINE);
}
}
/**
* Log a call to Class.getDeclaredFields().
*
* @param invokingClassName
* @param reflectedClass
*/
public static void logGetDeclaredFields(String invokingClassName,
Class reflectedClass )
{
logGetFields(invokingClassName, "getDeclaredFields", reflectedClass);
}
/**
* Log a call to Class.getFields().
*
* @param invokingClassName
* @param reflectedClass
*/
public static void logGetFields(String invokingClassName,
Class reflectedClass )
{
logGetFields(invokingClassName, "getFields", reflectedClass);
}
/**
* Log a call to one of the field listing methods on Class.
*
* @param invokingClassName
* @param invokedReflectionMethodName
* @param reflectedClass
*/
private static void logGetFields(String invokingClassName,
String invokedReflectionMethodName,
Class reflectedClass )
{
initializeMappings();
if (classesWithObfuscatedFields.contains(reflectedClass.getName()) &&
!fieldListingCLasses.contains(reflectedClass.getName()) &&
!isLibraryClass(reflectedClass))
{
fieldListingCLasses.add(reflectedClass.getName());
log(
"The class '" + originalClassName(invokingClassName) +
"' is calling Class." + invokedReflectionMethodName + "\n" +
"on class '" + originalClassName(reflectedClass) +
"' to retrieve its fields.\n" +
"You might consider preserving all fields with their original names,\n" +
"with a setting like:\n" +
EMPTY_LINE +
keepAllFieldsRule(reflectedClass) + "\n" +
EMPTY_LINE);
}
}
// Implementations for Runnable.
public void run()
{
printConfiguration();
}
private static void printConfiguration()
{
log("The following settings may help solving issues related to\n" +
"missing classes, methods and/or fields:\n");
for (String clazz : missingClasses)
{
log(keepClassRule(clazz) + "\n");
}
for (String clazz : missingConstructors.keySet())
{
for (MethodSignature constructor : missingConstructors.get(clazz))
{
log(keepConstructorRule(clazz, constructor) + "\n");
}
}
for (String clazz : missingMethods.keySet())
{
for (MethodSignature method : missingMethods.get(clazz))
{
log(keepMethodRule(clazz, method.name, method) + "\n");
}
}
for (String clazz : missingFields.keySet())
{
for (String field : missingFields.get(clazz))
{
log(keepFieldRule(clazz, field) + "\n");
}
}
}
// ProGuard rules.
private static String keepClassRule(String className)
{
return "-keep class " + className;
}
private static String keepConstructorRule(String className,
MethodSignature constructorParameters)
{
return "-keepclassmembers class " + originalClassName(className) + " {\n" +
" public <init>(" + originalSignature(constructorParameters) + ");\n" +
"}";
}
private static String keepMethodRule(String className,
String methodName,
MethodSignature constructorParameters)
{
return "-keepclassmembers class " + originalClassName(className) + " {\n" +
" *** " + methodName + "(" + originalSignature(constructorParameters) + ");\n" +
"}";
}
private static String keepFieldRule(String className,
String fieldName)
{
return "-keepclassmembers class " + originalClassName(className) + " {\n" +
" *** " + fieldName + ";\n" +
"}";
}
private static String keepAllConstructorsRule(Class className)
{
return "-keepclassmembers class " + originalClassName(className) + " {\n" +
" <init>(...);\n" +
"}";
}
private static String keepAllMethodsRule(Class className)
{
return "-keepclassmembers class " + originalClassName(className) + " {\n" +
" <methods>;\n" +
"}";
}
private static String keepAllFieldsRule(Class className)
{
return "-keepclassmembers class " + originalClassName(className) + " {\n" +
" <fields>;\n" +
"}";
}
private static String originalClassName(Class className)
{
return originalClassName(className.getName());
}
private static String originalClassName(String className)
{
initializeMappings();
String originalClassName = classNameMap.get(className);
return originalClassName != null ? originalClassName : className;
}
/**
* Simple heuristic to see if the given class is a library class or not.
*
* @param clazz
* @return
*/
private static boolean isLibraryClass(Class clazz)
{
return clazz.getClassLoader() == String.class.getClassLoader();
}
/**
* Log a message, either on the Android Logcat, if available, or on the
* Standard error outputstream otherwise.
*
* @param message the message to be logged.
*/
private static void log(String message)
{
if (logMethod != null)
{
try
{
logMethod.invoke(null, LOG_TAG, message);
}
catch (Exception e)
{
System.err.println(message);
}
}
else
{
System.err.println(message);
}
}
private static void initializeMappings()
{
if (classNameMap == null)
{
classNameMap = new HashMap<String, String> ();
classesWithObfuscatedMethods = new HashSet<String> ();
classesWithObfuscatedFields = new HashSet<String> ();
String line;
try
{
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
ConfigurationLogger.class.getClassLoader().getResourceAsStream(CLASS_MAP_FILENAME)));
while ((line = reader.readLine()) != null)
{
StringTokenizer tokenizer = new StringTokenizer(line, ",");
String originalClassName = tokenizer.nextToken();
String obfuscatedClassName = tokenizer.nextToken();
boolean hasObfuscatedMethods = tokenizer.nextToken().equals("1");
boolean hasObfuscatedFields = tokenizer.nextToken().equals("1");
classNameMap.put(obfuscatedClassName, originalClassName);
if (hasObfuscatedMethods)
{
classesWithObfuscatedMethods.add(obfuscatedClassName);
}
if (hasObfuscatedFields)
{
classesWithObfuscatedFields.add(obfuscatedClassName);
}
}
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private static String originalSignature(MethodSignature signature)
{
StringBuilder stringBuilder = new StringBuilder();
boolean first = true;
for (String clazz : signature.parameters)
{
if (first)
{
first = false;
}
else
{
stringBuilder.append(",");
}
stringBuilder.append(originalClassName(clazz));
}
return stringBuilder.toString();
}
public static class MethodSignature
{
private String name;
private String[] parameters;
public MethodSignature(String name, Class[] parameters)
{
this.name = name;
this.parameters = new String[parameters.length];
for (int i = 0; i < parameters.length; i++)
{
this.parameters[i] = parameters[i].getName();
}
}
// Implementations for Object.
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MethodSignature that = (MethodSignature)o;
if (!name.equals(that.name)) return false;
return Arrays.equals(parameters, that.parameters);
}
public int hashCode()
{
int result = name.hashCode();
result = 31 * result + Arrays.hashCode(parameters);
return result;
}
}
}
| 34.117722 | 151 | 0.565503 |
47df6d0c8097a55b156faa323ae34590453b6d7a | 4,007 | package com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker;
import com.github.zhuyizhuo.generator.enums.TemplateTypeEnums;
import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums;
import com.github.zhuyizhuo.generator.mybatis.generator.service.template.TemplateGenerateService;
import com.github.zhuyizhuo.generator.mybatis.vo.GenerateInfo;
import com.github.zhuyizhuo.generator.mybatis.vo.GenerateMetaData;
import com.github.zhuyizhuo.generator.mybatis.vo.ModulePathInfo;
import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo;
import com.github.zhuyizhuo.generator.utils.Freemarker;
import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils;
import com.github.zhuyizhuo.generator.utils.LogUtils;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* freemarker 模板生成
*/
public abstract class FreemarkerGenerateService implements TemplateGenerateService {
/**
* TemplateType_moduleType_hasPrivateKey -> templatePath
*/
private Map<String,String> templatePathMap = new ConcurrentHashMap<>();
protected abstract TemplateTypeEnums getTemplateType();
protected void addTemplatePath(ModuleTypeEnums moduleType, Boolean hasPrivateKey, String templatePath){
if (hasPrivateKey == null){
addTemplate(moduleType.name(), templatePath);
} else {
this.templatePathMap.put(getTemplateType() + "_" + moduleType+ "_" + hasPrivateKey, templatePath);
}
}
protected void addTemplatePath(ModuleTypeEnums moduleType, String templatePath) {
addTemplate(moduleType.name(), templatePath);
}
@Override
public void addTemplate(String moduleType, String templatePath) {
this.templatePathMap.put(getTemplateType() + "_" + moduleType + "_true", templatePath);
this.templatePathMap.put(getTemplateType() + "_" + moduleType + "_false", templatePath);
}
/**
* 获取模板路径
* @param moduleType 模块类型
* @param hasPrivateKey 是否有主键
* @return 模板路径
*/
protected String getTemplatePath(String moduleType, boolean hasPrivateKey) {
return this.templatePathMap.get(getTemplateType() + "_" + moduleType + "_" + hasPrivateKey);
}
@Override
public void generate(GenerateMetaData generateMetaData) {
try {
Map<String, List<ModulePathInfo>> tableInfosMap = generateMetaData.getModulePathInfoMap();
for (Map.Entry<String, List<ModulePathInfo>> entry : tableInfosMap.entrySet()) {
List<ModulePathInfo> value = entry.getValue();
GenerateInfo generateInfo = generateMetaData.getGenerateInfoByTableName(entry.getKey());
TableInfo tableInfo = generateInfo.getTableInfo();
LogUtils.info(">>>>>>>>>>>>>>>>> generate [" + tableInfo.getTableName() + "] start <<<<<<<<<<<<<<<");
LogUtils.info(tableInfo.getTableName() + " 表共 " + tableInfo.getColumnLists().size() + " 列");
LogUtils.logGenerateInfo(generateInfo);
boolean hasPrimaryKey = tableInfo.isHasPrimaryKey();
for (int i = 0; i < value.size(); i++) {
ModulePathInfo templateGenerateInfo = value.get(i);
String templatePath = this.getTemplatePath(templateGenerateInfo.getModuleType(), hasPrimaryKey);
if (GeneratorStringUtils.isNotBlank(templatePath)){
Freemarker.printFile(templatePath,
templateGenerateInfo.getFileOutputPath(), generateInfo);
LogUtils.info("文件输出路径:"+templateGenerateInfo.getFileOutputPath());
}
}
LogUtils.info(">>>>>>>>>>>>>>>>> generate [" + tableInfo.getTableName() + "] end <<<<<<<<<<<<<<<<<");
}
}catch (Exception e){
LogUtils.error("FreemarkerGenerateService.generate error!");
LogUtils.printException(e);
}
}
}
| 46.057471 | 117 | 0.66883 |
6dbb8f0e77c3c00fba189c9b12eb901d526508c9 | 2,538 | /**
* Copyright 2014 NAVER Corp.
* 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.navercorp.pinpoint.profiler.plugin.objectfactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author Jongho Moon
*
*/
public class ConstructorResolver {
private final Class<?> type;
private final ArgumentsResolver argumentsResolver;
private Constructor<?> resolvedConstructor;
private Object[] resolvedArguments;
public ConstructorResolver(Class<?> type, ArgumentsResolver argumentsResolver) {
this.type = type;
this.argumentsResolver = argumentsResolver;
}
public boolean resolve() {
Constructor<?>[] constructors = (Constructor<?>[]) type.getConstructors();
Arrays.sort(constructors, CONSTRUCTOR_COMPARATOR);
for (Constructor<?> constructor : constructors) {
Class<?>[] types = constructor.getParameterTypes();
Annotation[][] annotations = constructor.getParameterAnnotations();
Object[] resolvedArguments = argumentsResolver.resolve(types, annotations);
if (resolvedArguments != null) {
this.resolvedConstructor = constructor;
this.resolvedArguments = resolvedArguments;
return true;
}
}
return false;
}
public Constructor<?> getResolvedConstructor() {
return resolvedConstructor;
}
public Object[] getResolvedArguments() {
return resolvedArguments;
}
private static final Comparator<Constructor<?>> CONSTRUCTOR_COMPARATOR = new Comparator<Constructor<?>>() {
@Override
public int compare(Constructor<?> o1, Constructor<?> o2) {
int p1 = o1.getParameterTypes().length;
int p2 = o2.getParameterTypes().length;
return (p1 < p2) ? 1 : ((p1 == p2) ? 0 : -1);
}
};
}
| 32.126582 | 111 | 0.652876 |
4610b6df01c9cac419250c52b415e746239d5d21 | 119 | package com.google.android.gms.tagmanager;
interface zzau {
void dispatch();
void zzg(long j, String str);
}
| 14.875 | 42 | 0.689076 |
7ddbc99e4f07bc15d55105a755f615881e83c07c | 2,461 | package com.creed;
import com.creed.constant.JobType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Date;
import java.util.Optional;
/**
* @className: BatchApplication
* @author: Ethan
* @date: 7/12/2021
**/
@Slf4j
@SpringBootApplication
public class BatchApplication implements CommandLineRunner {
private ApplicationContext applicationContext;
private JobLauncher jobLauncher;
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(BatchApplication.class).web(WebApplicationType.NONE).run(args);
System.exit(SpringApplication.exit(context));
}
@Override
public void run(String... args) throws Exception {
String jobName = "JOB_BEAN1";
// if (args.length > 0) {
// jobName = args[0];
// }
Optional<JobType> jobTypeOptional = JobType.findByName(jobName);
if (jobTypeOptional.isPresent()) {
String jobBeanName = jobTypeOptional.get().getJobBeanName();
log.info("Batch Start with {}", jobName);
Job job = applicationContext.getBean(jobBeanName, Job.class);
JobExecution run = jobLauncher.run(job, jobParameters());
log.info("status:{}", run.getExitStatus());
}
}
private JobParameters jobParameters() {
return new JobParametersBuilder().addDate("date", new Date()).toJobParameters();
}
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Autowired
public void setJobLauncher(JobLauncher jobLauncher) {
this.jobLauncher = jobLauncher;
}
}
| 36.731343 | 151 | 0.739943 |
247eacfd70a856f9edccaf1f8fd60241489f2eda | 86,134 | /*
* This file was automatically generated by EvoSuite
* Fri May 22 19:41:09 GMT 2020
*/
package com.alibaba.fastjson.parser;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.shaded.org.mockito.Mockito.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONReaderScanner;
import com.alibaba.fastjson.parser.JSONScanner;
import com.alibaba.fastjson.parser.ParseContext;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ASMDeserializerFactory;
import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider;
import com.alibaba.fastjson.parser.deserializer.FieldTypeResolver;
import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer;
import com.alibaba.fastjson.parser.deserializer.MapDeserializer;
import com.alibaba.fastjson.parser.deserializer.PropertyProcessable;
import com.alibaba.fastjson.parser.deserializer.ThrowableDeserializer;
import com.alibaba.fastjson.serializer.JavaBeanSerializer;
import java.awt.GridBagConstraints;
import java.awt.ImageCapabilities;
import java.awt.Insets;
import java.awt.JobAttributes;
import java.awt.RenderingHints;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.BreakIterator;
import java.text.Collator;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.MessageFormat;
import java.text.RuleBasedCollator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.ViolatedAssumptionAnswer;
import org.evosuite.runtime.mock.java.text.MockDateFormat;
import org.evosuite.runtime.mock.java.text.MockSimpleDateFormat;
import org.evosuite.runtime.mock.java.util.MockDate;
import org.evosuite.runtime.mock.java.util.MockGregorianCalendar;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.junit.runner.RunWith;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class DefaultJSONParser_ESTest extends DefaultJSONParser_ESTest_scaffolding {
@Test(timeout = 4000)
public void test000() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
ImageCapabilities imageCapabilities0 = new ImageCapabilities(true);
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) "[biSj[9%X\")qg", (Object) imageCapabilities0);
DefaultJSONParser.ResolveTask defaultJSONParser_ResolveTask0 = new DefaultJSONParser.ResolveTask(parseContext0, "[biSj[9%X\")qg");
}
@Test(timeout = 4000)
public void test001() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("pa");
BitSet bitSet0 = new BitSet(1);
JSONScanner jSONScanner0 = new JSONScanner("pa");
Double double0 = new Double(1);
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) jSONScanner0, (Object) double0);
defaultJSONParser0.setContext(parseContext0, (Object) bitSet0, (Object) parseContext0);
BitSet bitSet1 = (BitSet)defaultJSONParser0.resolveReference("$.$");
assertEquals(0, bitSet1.cardinality());
}
@Test(timeout = 4000)
public void test002() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("4|");
Double double0 = new Double(0);
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) ")y[mUAOHfar\nT+%", (Object) double0);
defaultJSONParser0.setContext(parseContext0, (Object) null, (Object) parseContext0);
Object object0 = defaultJSONParser0.resolveReference("$");
assertEquals(")y[mUAOHfar\nT+%", object0);
assertNotNull(object0);
}
@Test(timeout = 4000)
public void test003() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.global;
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(";UO%|>d~d ", parserConfig0, 1);
// Undeclared exception!
try {
defaultJSONParser0.close();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// not close json text, token : ;
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test004() throws Throwable {
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(",<?ZHKQp=Qd)Gehcjv", 15);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(jSONReaderScanner0);
// Undeclared exception!
try {
defaultJSONParser0.accept(0, 15);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect Unknown, actual ,
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test005() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("", parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.accept(3129);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect Unknown, actual EOF
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test006() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
MockDateFormat mockDateFormat0 = new MockDateFormat();
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) mockDateFormat0, (Object) "[biSj[9%X\")qg");
DecimalFormatSymbols decimalFormatSymbols0 = DecimalFormatSymbols.getInstance();
defaultJSONParser0.setContext(parseContext0, (Object) parseContext0, (Object) decimalFormatSymbols0);
// Undeclared exception!
try {
defaultJSONParser0.parseKey();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3[biSj[9%X\")qg
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test007() throws Throwable {
JSONScanner jSONScanner0 = new JSONScanner("matchStat", 866);
ParserConfig parserConfig0 = new ParserConfig(false);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(jSONScanner0, parserConfig0);
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) "matchStat", (Object) "matchStat");
Class<ThrowableDeserializer> class0 = ThrowableDeserializer.class;
JavaBeanDeserializer javaBeanDeserializer0 = new JavaBeanDeserializer(parserConfig0, class0, class0);
ParseContext parseContext1 = new ParseContext(parseContext0, defaultJSONParser0, javaBeanDeserializer0);
ImageCapabilities imageCapabilities0 = new ImageCapabilities(true);
ParseContext parseContext2 = defaultJSONParser0.setContext(parseContext1, (Object) jSONScanner0, (Object) imageCapabilities0);
assertEquals(2, parseContext2.level);
}
@Test(timeout = 4000)
public void test008() throws Throwable {
JSONScanner jSONScanner0 = new JSONScanner("matchStat", 866);
ParserConfig parserConfig0 = new ParserConfig(false);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(jSONScanner0, parserConfig0);
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) "matchStat", (Object) "matchStat");
ImageCapabilities imageCapabilities0 = new ImageCapabilities(true);
defaultJSONParser0.setContext(parseContext0, (Object) jSONScanner0, (Object) imageCapabilities0);
defaultJSONParser0.popContext();
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test009() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig(true);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(";w}AggIxsy})d}gPn", parserConfig0, (-531));
LinkedHashSet<JavaBeanDeserializer> linkedHashSet0 = new LinkedHashSet<JavaBeanDeserializer>();
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Collection) linkedHashSet0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect [, actual ;, pos 0, fieldName null
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test010() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("@");
defaultJSONParser0.setResolveStatus(132);
IdentityHashMap<ImageCapabilities, BigInteger> identityHashMap0 = new IdentityHashMap<ImageCapabilities, BigInteger>();
defaultJSONParser0.checkMapResolve(identityHashMap0, "@");
assertEquals(132, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test011() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
BigDecimal bigDecimal0 = new BigDecimal(bigInteger0);
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner("q+>g&nw/I89s\u0000", 1);
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(bigDecimal0, jSONReaderScanner0, parserConfig0);
Hashtable<String, Field> hashtable0 = new Hashtable<String, Field>();
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) parserConfig0, (Object) hashtable0);
GridBagConstraints gridBagConstraints0 = new GridBagConstraints();
StringCharacterIterator stringCharacterIterator0 = new StringCharacterIterator("fastjson.parser.autoTypeAccept", 0);
defaultJSONParser0.setContext(parseContext0, (Object) gridBagConstraints0, (Object) stringCharacterIterator0);
Object object0 = defaultJSONParser0.getObject("fastjson.parser.deny.internal");
assertNull(object0);
}
@Test(timeout = 4000)
public void test012() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("Th:L}k]oroJ", parserConfig0, (-2795));
// Undeclared exception!
try {
defaultJSONParser0.acceptType("Th:L}k]oroJ");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// type not match error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test013() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig(true);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("unterminated json string, ", parserConfig0, 548);
Insets insets0 = new Insets(0, 2, 1, 1);
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Object) insets0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual ident
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test014() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSjy9%X\"qg");
defaultJSONParser0.setResolveStatus(17);
Type[] typeArray0 = new Type[18];
// Undeclared exception!
try {
defaultJSONParser0.parseArray(typeArray0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3[biSjy9%X\"qg
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test015() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
Type[] typeArray0 = new Type[4];
// Undeclared exception!
try {
defaultJSONParser0.parseArray(typeArray0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error : EOF
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test016() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.global;
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$4PG-s[NHG94H", parserConfig0);
Type[] typeArray0 = new Type[1];
// Undeclared exception!
try {
defaultJSONParser0.parseArray(typeArray0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error : error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test017() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$.$", parserConfig0, 3460);
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser(defaultJSONParser0.lexer);
Class<Time> class0 = Time.class;
// Undeclared exception!
try {
defaultJSONParser1.parseArray(class0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// expect '[', but ., pos 2, line 1, column 3$.$
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test018() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
ParserConfig parserConfig0 = new ParserConfig(false);
defaultJSONParser0.setConfig(parserConfig0);
assertFalse(ParserConfig.AUTO_SUPPORT);
}
@Test(timeout = 4000)
public void test019() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("3", parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.parseObject();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual int, pos 1, line 1, column 23
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test020() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(">03");
defaultJSONParser0.handleResovleTask(">03");
assertEquals("yyyy-MM-dd HH:mm:ss", defaultJSONParser0.getDateFomartPattern());
}
@Test(timeout = 4000)
public void test021() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("TODO : ");
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) null, (Object) classLoader0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 4, line 1, column 5TODO :
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test022() throws Throwable {
// Undeclared exception!
try {
JSON.parseObject("63");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// can not cast to JSONObject.
//
verifyException("com.alibaba.fastjson.JSON", e);
}
}
@Test(timeout = 4000)
public void test023() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("4|");
Double double0 = new Double(0);
defaultJSONParser0.setContext((Object) ")y[mUAOHfar\nT+%", (Object) double0);
Object object0 = defaultJSONParser0.resolveReference("$");
assertNotNull(object0);
assertEquals(")y[mUAOHfar\nT+%", object0);
}
@Test(timeout = 4000)
public void test024() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
TreeMap<DateFormatSymbols, MessageFormat> treeMap0 = new TreeMap<DateFormatSymbols, MessageFormat>();
Object object0 = defaultJSONParser0.parseObject((Map) treeMap0);
assertNull(object0);
}
@Test(timeout = 4000)
public void test025() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
Class<Integer> class0 = Integer.TYPE;
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) class0);
// fail("Expecting exception: RuntimeException");
// Unstable assertion
} catch(RuntimeException e) {
//
// syntax error,except start with { or [,but actually start with EOF
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test026() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
Object object0 = defaultJSONParser0.parse();
assertNull(object0);
}
@Test(timeout = 4000)
public void test027() throws Throwable {
MockDate mockDate0 = new MockDate(5474268165959054648L);
StringReader stringReader0 = new StringReader("N#MV@]d?R1dc(_B.Ym");
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(stringReader0);
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(mockDate0, jSONReaderScanner0, parserConfig0);
Feature feature0 = Feature.DisableASM;
boolean boolean0 = defaultJSONParser0.isEnabled(feature0);
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test028() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
defaultJSONParser0.addResolveTask((DefaultJSONParser.ResolveTask) null);
List<DefaultJSONParser.ResolveTask> list0 = defaultJSONParser0.getResolveTaskList();
assertFalse(list0.isEmpty());
}
@Test(timeout = 4000)
public void test029() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("error parse null or new");
defaultJSONParser0.resolveStatus = 1986;
int int0 = defaultJSONParser0.getResolveStatus();
assertEquals(1986, int0);
}
@Test(timeout = 4000)
public void test030() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biWjy99X \",qg");
defaultJSONParser0.resolveStatus = (int) (byte) (-52);
int int0 = defaultJSONParser0.getResolveStatus();
assertEquals((-52), int0);
}
@Test(timeout = 4000)
public void test031() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("pa");
ParserConfig parserConfig0 = defaultJSONParser0.getConfig();
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser(defaultJSONParser0, defaultJSONParser0.lexer, parserConfig0);
JSONScanner jSONScanner0 = (JSONScanner)defaultJSONParser0.getLexer();
assertNull(jSONScanner0.stringDefaultValue());
}
@Test(timeout = 4000)
public void test032() throws Throwable {
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
JSONScanner jSONScanner0 = new JSONScanner("Y,OtE", (-18));
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(jSONScanner0, parserConfig0);
JSONLexer jSONLexer0 = defaultJSONParser0.getLexer();
assertSame(jSONScanner0, jSONLexer0);
}
@Test(timeout = 4000)
public void test033() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
BigDecimal bigDecimal0 = new BigDecimal(bigInteger0);
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner("q+>g&nw/I89s\u0000", 1);
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(bigDecimal0, jSONReaderScanner0, parserConfig0);
Hashtable<String, Field> hashtable0 = new Hashtable<String, Field>();
defaultJSONParser0.setContext((Object) parserConfig0, (Object) hashtable0);
ParseContext parseContext0 = defaultJSONParser0.getContext();
assertEquals(0, parseContext0.level);
}
@Test(timeout = 4000)
public void test034() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
parserConfig0.setAsmEnable(false);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("3", parserConfig0);
ParserConfig parserConfig1 = defaultJSONParser0.getConfig();
assertFalse(parserConfig1.isSafeMode());
}
@Test(timeout = 4000)
public void test035() throws Throwable {
DecimalFormat decimalFormat0 = new DecimalFormat("W");
char[] charArray0 = new char[4];
charArray0[1] = 't';
charArray0[2] = 'O';
charArray0[3] = 'X';
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(charArray0, 'X');
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
jSONReaderScanner0.ch = ',';
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(decimalFormat0, jSONReaderScanner0, parserConfig0);
LinkedHashMap<Float, RuleBasedCollator> linkedHashMap0 = new LinkedHashMap<Float, RuleBasedCollator>();
Insets insets0 = new Insets(11, 5034, 0, 't');
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) linkedHashMap0, (Object) insets0);
fail("Expecting exception: StringIndexOutOfBoundsException");
} catch(StringIndexOutOfBoundsException e) {
}
}
@Test(timeout = 4000)
public void test036() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("com.alibaba.fastjson.asm.Item");
// Undeclared exception!
defaultJSONParser0.parseObject((Object) bigInteger0);
}
@Test(timeout = 4000)
public void test037() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("unzip bytes error.");
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Object) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test038() throws Throwable {
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("J-Tnbf", parserConfig0, 3474);
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser(defaultJSONParser0.lexer);
// Undeclared exception!
try {
defaultJSONParser1.parseKey();
fail("Expecting exception: NumberFormatException");
} catch(NumberFormatException e) {
//
// -
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test039() throws Throwable {
TreeMap<BreakIterator, Float> treeMap0 = new TreeMap<BreakIterator, Float>();
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("G", parserConfig0, (-2980));
// Undeclared exception!
try {
defaultJSONParser0.parseExtra(treeMap0, "fastjson.parser.deny.internal");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// not match : - \u001A, info : pos 1, line 1, column 2G
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test040() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("63");
// Undeclared exception!
try {
defaultJSONParser0.parseArrayWithType((Type) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test041() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("(CLjava/lang/Strig;");
Class<Long> class0 = Long.TYPE;
// Undeclared exception!
try {
defaultJSONParser0.parseArrayWithType(class0);
fail("Expecting exception: ClassCastException");
} catch(ClassCastException e) {
//
// java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test042() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biWjy99X \",qg");
Class<JavaBeanDeserializer> class0 = JavaBeanDeserializer.class;
Type[] typeArray0 = new Type[1];
typeArray0[0] = (Type) class0;
// Undeclared exception!
defaultJSONParser0.parseArray(typeArray0);
}
@Test(timeout = 4000)
public void test043() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
MockDateFormat mockDateFormat0 = new MockDateFormat();
defaultJSONParser0.setContext((Object) mockDateFormat0, (Object) "[biSj[9%X\")qg");
// Undeclared exception!
try {
defaultJSONParser0.getObject((String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
@Test(timeout = 4000)
public void test044() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("m<C_Ey$qC(B!+{>^");
defaultJSONParser0.getResolveTaskList();
// Undeclared exception!
try {
defaultJSONParser0.getLastResolveTask();
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test045() throws Throwable {
JSONScanner jSONScanner0 = new JSONScanner("", 0);
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(jSONScanner0, parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.getInput();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.evosuite.runtime.System", e);
}
}
@Test(timeout = 4000)
public void test046() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
char[] charArray0 = new char[4];
charArray0[0] = '/';
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser(charArray0, 1, parserConfig0, 0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// invalid comment
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test047() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
char[] charArray0 = new char[0];
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser(charArray0, 2, parserConfig0, 0);
fail("Expecting exception: StringIndexOutOfBoundsException");
} catch(StringIndexOutOfBoundsException e) {
}
}
@Test(timeout = 4000)
public void test048() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser("fastjson.parser.deny.internal", parserConfig0, 0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// error parse false
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test049() throws Throwable {
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser("I", (ParserConfig) null, 754);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test050() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser("fastjson.parser.deny", parserConfig0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// error parse false
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test051() throws Throwable {
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser("1r(S$/VeBMio2z0fF", (ParserConfig) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test052() throws Throwable {
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser("fastjson.parser.deny");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// error parse false
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test053() throws Throwable {
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser((String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.alibaba.fastjson.parser.JSONScanner", e);
}
}
@Test(timeout = 4000)
public void test054() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
JSONScanner jSONScanner0 = new JSONScanner("fastjson.parser.safeMode");
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser(parserConfig0, jSONScanner0, parserConfig0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// error parse false
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test055() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("~_K1^3");
DefaultJSONParser defaultJSONParser1 = null;
try {
defaultJSONParser1 = new DefaultJSONParser(defaultJSONParser0, defaultJSONParser0.lexer, (ParserConfig) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test056() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
JSONScanner jSONScanner0 = new JSONScanner("fastjson.parser.deny.internal");
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser(jSONScanner0, parserConfig0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// error parse false
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test057() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser((JSONLexer) null, parserConfig0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test058() throws Throwable {
JSONScanner jSONScanner0 = new JSONScanner("fastjson.parser.deny.internal");
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser(jSONScanner0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// error parse false
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test059() throws Throwable {
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser((JSONLexer) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test060() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
Class<ImageCapabilities> class0 = ImageCapabilities.class;
JavaBeanDeserializer javaBeanDeserializer0 = new JavaBeanDeserializer(parserConfig0, class0);
Object object0 = defaultJSONParser0.parse((Object) javaBeanDeserializer0);
assertNull(object0);
}
@Test(timeout = 4000)
public void test061() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("\"@type\":\"", parserConfig0, 2488);
Object object0 = defaultJSONParser0.parse((Object) "ZVMa\"@4}$G\"$8 ,D~.y");
assertEquals("@type", object0);
}
@Test(timeout = 4000)
public void test062() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
BigDecimal bigDecimal0 = new BigDecimal(bigInteger0);
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(".D", parserConfig0, 1);
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) bigDecimal0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 1, line 1, column 2.D
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test063() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("(Ljava/util/Collection;)V");
defaultJSONParser0.accept(10, 48);
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) "#3pmV");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3(Ljava/util/Collection;)V
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test064() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Object object0 = defaultJSONParser0.parse((Object) "null");
assertNull(object0);
}
@Test(timeout = 4000)
public void test065() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig(false);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("(Ljava/util/Collection;)V", parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) "(Ljava/util/Collection;)V");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 1, line 1, column 2(Ljava/util/Collection;)V
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test066() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
BigDecimal bigDecimal0 = new BigDecimal(bigInteger0);
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("6D", parserConfig0, 15);
Object object0 = defaultJSONParser0.parse((Object) bigDecimal0);
assertEquals(6.0, object0);
}
@Test(timeout = 4000)
public void test067() throws Throwable {
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("+)^?_9>7&", parserConfig0, 12);
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser(defaultJSONParser0.lexer);
// Undeclared exception!
try {
defaultJSONParser1.parse((Object) defaultJSONParser0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3+)^?_9>7&
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test068() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) "[biSj[9%X\")qg");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3[biSj[9%X\")qg
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test069() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("TD1: ");
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser(";UO%|>d~d ", defaultJSONParser0.lexer, parserConfig0);
// Undeclared exception!
try {
defaultJSONParser1.parse((Object) classLoader0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 4, line 1, column 5TD1:
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test070() throws Throwable {
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(",<?ZHKQp=Qd)Gehcjv", 15);
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("+)^?_9>7&", jSONReaderScanner0, parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error,
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test071() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
BigDecimal bigDecimal0 = new BigDecimal(bigInteger0);
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(",<?ZHKQp=Qd)Gehcjv", 1);
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(bigDecimal0, jSONReaderScanner0, parserConfig0);
Hashtable<String, Field> hashtable0 = new Hashtable<String, Field>();
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) null, (Object) parserConfig0);
ParseContext parseContext1 = defaultJSONParser0.setContext((Object) parserConfig0, (Object) hashtable0);
assertFalse(parseContext1.equals((Object)parseContext0));
}
@Test(timeout = 4000)
public void test072() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biWjy99X \",qg");
HashSet<DecimalFormatSymbols> hashSet0 = new HashSet<DecimalFormatSymbols>();
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Collection) hashSet0, (Object) "[biWjy99X \",qg");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3[biWjy99X \",qg
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test073() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("(CLjava/lang/Strig;");
HashSet<DecimalFormatSymbols> hashSet0 = new HashSet<DecimalFormatSymbols>();
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Collection) hashSet0, (Object) "(CLjava/lang/Strig;");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect [, actual (, pos 0, fieldName (CLjava/lang/Strig;
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test074() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSjy9%X\"qg");
Class<Boolean> class0 = Boolean.TYPE;
LinkedHashMap<Timestamp, DateFormatSymbols> linkedHashMap0 = new LinkedHashMap<Timestamp, DateFormatSymbols>();
Collection<DateFormatSymbols> collection0 = linkedHashMap0.values();
JobAttributes jobAttributes0 = new JobAttributes();
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Type) class0, (Collection) collection0, (Object) jobAttributes0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual error, pos 1, fastjson-version 1.2.68
//
verifyException("com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer", e);
}
}
@Test(timeout = 4000)
public void test075() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(",<?ZHKQp=Qd)Gehcjv");
Class<Short> class0 = Short.TYPE;
ArrayList<BigInteger> arrayList0 = new ArrayList<BigInteger>();
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Type) class0, (Collection) arrayList0, (Object) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// expect '[', but ,, pos 1, line 1, column 2,<?ZHKQp=Qd)Gehcjv
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test076() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.global;
Class<Boolean> class0 = Boolean.class;
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$4PG-s[NHG94H", parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) class0, (Object) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error,except start with { or [,but actually start with error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test077() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Class<GridBagConstraints> class0 = GridBagConstraints.class;
JavaBeanSerializer javaBeanSerializer0 = new JavaBeanSerializer(class0);
Class<?> class1 = javaBeanSerializer0.getType();
TreeSet<ThrowableDeserializer> treeSet0 = defaultJSONParser0.parseObject((Type) class1, (Object) classLoader0);
assertNull(treeSet0);
}
@Test(timeout = 4000)
public void test078() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(", property ");
TreeMap<BreakIterator, Float> treeMap0 = new TreeMap<BreakIterator, Float>();
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) treeMap0, (Object) ", property ");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// expect ':' at 0, actual \u001A
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test079() throws Throwable {
DecimalFormat decimalFormat0 = new DecimalFormat("W");
char[] charArray0 = new char[4];
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(charArray0, 'X');
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
jSONReaderScanner0.ch = ',';
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(decimalFormat0, jSONReaderScanner0, parserConfig0);
LinkedHashMap<Float, RuleBasedCollator> linkedHashMap0 = new LinkedHashMap<Float, RuleBasedCollator>();
Insets insets0 = new Insets(11, 5034, 0, 't');
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) linkedHashMap0, (Object) insets0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// illegal identifier : \u0000
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test080() throws Throwable {
DecimalFormat decimalFormat0 = new DecimalFormat("W");
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner("W");
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
jSONReaderScanner0.ch = ',';
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(decimalFormat0, jSONReaderScanner0, parserConfig0);
LinkedHashMap<Float, RuleBasedCollator> linkedHashMap0 = new LinkedHashMap<Float, RuleBasedCollator>();
Insets insets0 = new Insets(11, 5034, 0, 't');
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) linkedHashMap0, (Object) insets0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test081() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("\"@type\":\"", parserConfig0, 2527);
JSONObject jSONObject0 = new JSONObject();
Object object0 = new Object();
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) jSONObject0, object0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual string, pos 7, line 1, column 8\"@type\":\"
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test082() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("}");
IdentityHashMap<Boolean, RenderingHints> identityHashMap0 = new IdentityHashMap<Boolean, RenderingHints>();
Locale locale0 = Locale.TRADITIONAL_CHINESE;
DecimalFormatSymbols decimalFormatSymbols0 = new DecimalFormatSymbols(locale0);
IdentityHashMap identityHashMap1 = (IdentityHashMap)defaultJSONParser0.parseObject((Map) identityHashMap0, (Object) decimalFormatSymbols0);
assertTrue(identityHashMap1.isEmpty());
}
@Test(timeout = 4000)
public void test083() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
IdentityHashMap<Boolean, RenderingHints> identityHashMap0 = new IdentityHashMap<Boolean, RenderingHints>();
MockSimpleDateFormat mockSimpleDateFormat0 = new MockSimpleDateFormat();
Object object0 = defaultJSONParser0.parseObject((Map) identityHashMap0, (Object) mockSimpleDateFormat0);
assertNull(object0);
}
@Test(timeout = 4000)
public void test084() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("8<,33_x==2b");
List<DefaultJSONParser.ResolveTask> list0 = defaultJSONParser0.getResolveTaskList();
Class<DateFormatSymbols> class0 = DateFormatSymbols.class;
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Class<?>) class0, (Collection) list0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// expect '[', but int, pos 1, line 1, column 28<,33_x==2b
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test085() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("R|x;O");
Class<Boolean> class0 = Boolean.TYPE;
LinkedList<DateFormatSymbols> linkedList0 = new LinkedList<DateFormatSymbols>();
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Type) class0, (Collection) linkedList0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// expect '[', but error, pos 1, line 1, column 2R|x;O
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test086() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.global;
char[] charArray0 = new char[0];
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(charArray0, 0, parserConfig0, 0);
assertEquals(2, DefaultJSONParser.TypeNameRedirect);
}
@Test(timeout = 4000)
public void test087() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
HashMap<DateFormatSymbols, MockGregorianCalendar> hashMap0 = new HashMap<DateFormatSymbols, MockGregorianCalendar>();
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) hashMap0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual EOF, pos 0, line 1, column 1
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test088() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("pa");
// Undeclared exception!
try {
defaultJSONParser0.parse((PropertyProcessable) null, (Object) defaultJSONParser0.TypeNameRedirect);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect [, actual error, pos 0, fieldName 2
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test089() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("3");
defaultJSONParser0.setContext((ParseContext) null, (Object) null, (Object) "java.lang.String@0000000003");
Object object0 = defaultJSONParser0.resolveReference("$");
assertNull(object0);
}
@Test(timeout = 4000)
public void test090() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Object object0 = defaultJSONParser0.resolveReference("1.2.68");
assertNull(object0);
}
@Test(timeout = 4000)
public void test091() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
MockDateFormat mockDateFormat0 = new MockDateFormat();
defaultJSONParser0.setContext((Object) mockDateFormat0, (Object) "[biSj[9%X\")qg");
Object object0 = defaultJSONParser0.resolveReference("[biSj[9%X\")qg");
assertNull(object0);
}
@Test(timeout = 4000)
public void test092() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biWjy99X \",qg");
// Undeclared exception!
try {
defaultJSONParser0.close();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// not close json text, token : [
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test093() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$.$", parserConfig0, 6510);
defaultJSONParser0.close();
assertEquals(0, DefaultJSONParser.NONE);
}
@Test(timeout = 4000)
public void test094() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(">03");
// Undeclared exception!
try {
defaultJSONParser0.accept(528, 528);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect Unknown, actual error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test095() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$.color=monochrome,media=iso-a4,orientation-requested=portrait,origin=physical,print-quality=normal,printer-resolution=[72,72,3].{}.java.text.StringCharacterIterator@c55e7668");
// Undeclared exception!
try {
defaultJSONParser0.accept(0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect Unknown, actual error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test096() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("NaN");
Object object0 = defaultJSONParser0.parse((Object) ", name ");
assertNull(object0);
}
@Test(timeout = 4000)
public void test097() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("\"@ype\":\"", parserConfig0);
Object object0 = defaultJSONParser0.parse((Object) "ZVMa\"@4}$G\"$8 ,D~.y");
assertEquals("@ype", object0);
}
@Test(timeout = 4000)
public void test098() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$.$", parserConfig0, 3484);
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser(defaultJSONParser0.lexer);
// Undeclared exception!
try {
defaultJSONParser0.parseKey();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3$.$
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test099() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ParserConfig parserConfig0 = ParserConfig.global;
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(";UO%|>d~d ", parserConfig0, 1);
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) classLoader0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 1, line 1, column 2;UO%|>d~d
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test100() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("unzip bytes error.");
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) null);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 5, line 1, column 6unzip bytes error.
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test101() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("}");
MapDeserializer mapDeserializer0 = MapDeserializer.instance;
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) mapDeserializer0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 1, line 1, column 2}
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test102() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("(CLjava/lang/String;");
// Undeclared exception!
try {
defaultJSONParser0.parse();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 1, line 1, column 2(CLjava/lang/String;
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test103() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Object object0 = defaultJSONParser0.parseKey();
assertNull(object0);
}
@Test(timeout = 4000)
public void test104() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("-dZ)L\"-JO/fl9");
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) "-dZ)L\"-JO/fl9");
fail("Expecting exception: NumberFormatException");
} catch(NumberFormatException e) {
//
// -
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test105() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("TD1: ");
Object object0 = defaultJSONParser0.parseKey();
assertEquals("TD1", object0);
}
@Test(timeout = 4000)
public void test106() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$.$", parserConfig0, 3484);
ParseContext parseContext0 = defaultJSONParser0.setContext((ParseContext) null, (Object) null, (Object) parserConfig0);
assertNull(parseContext0);
}
@Test(timeout = 4000)
public void test107() throws Throwable {
BigInteger bigInteger0 = BigInteger.ZERO;
BigDecimal bigDecimal0 = new BigDecimal(bigInteger0);
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner("q+>g&nw/I89s\u0000", (-37));
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(bigDecimal0, jSONReaderScanner0, parserConfig0);
Hashtable<String, Field> hashtable0 = new Hashtable<String, Field>();
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) parserConfig0, (Object) hashtable0);
assertNull(parseContext0);
}
@Test(timeout = 4000)
public void test108() throws Throwable {
JSONScanner jSONScanner0 = new JSONScanner("matchStat", 866);
ParserConfig parserConfig0 = new ParserConfig(false);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(jSONScanner0, parserConfig0);
ParseContext parseContext0 = defaultJSONParser0.setContext((Object) "matchStat", (Object) "matchStat");
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser("matchStat");
defaultJSONParser1.setContext(parseContext0);
defaultJSONParser1.popContext();
assertFalse(defaultJSONParser1.equals((Object)defaultJSONParser0));
}
@Test(timeout = 4000)
public void test109() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
MockDateFormat mockDateFormat0 = new MockDateFormat();
defaultJSONParser0.setContext((Object) mockDateFormat0, (Object) "[biSj[9%X\")qg");
defaultJSONParser0.popContext();
assertEquals(2, DefaultJSONParser.TypeNameRedirect);
}
@Test(timeout = 4000)
public void test110() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("$.$", parserConfig0, 3499);
defaultJSONParser0.popContext();
assertEquals(0, DefaultJSONParser.NONE);
}
@Test(timeout = 4000)
public void test111() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("63");
// Undeclared exception!
try {
defaultJSONParser0.popContext();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test112() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
defaultJSONParser0.getExtraTypeProviders();
List<ExtraTypeProvider> list0 = defaultJSONParser0.getExtraTypeProviders();
assertTrue(list0.isEmpty());
}
@Test(timeout = 4000)
public void test113() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("3", parserConfig0);
defaultJSONParser0.getExtraProcessors();
List<ExtraProcessor> list0 = defaultJSONParser0.getExtraProcessors();
assertTrue(list0.isEmpty());
}
@Test(timeout = 4000)
public void test114() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(":5[76:16K#aT2s{ 5", parserConfig0, 2);
DefaultJSONParser defaultJSONParser1 = new DefaultJSONParser("(CLjava/lang/Strig;", defaultJSONParser0.lexer, parserConfig0);
defaultJSONParser1.accept(2);
PropertyProcessable propertyProcessable0 = mock(PropertyProcessable.class, new ViolatedAssumptionAnswer());
// Undeclared exception!
try {
defaultJSONParser1.parse(propertyProcessable0, (Object) "(CLjava/lang/Strig;");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 6, line 1, column 7:5[76:16K#aT2s{ 5
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test115() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("+RoH4gGH.^<U=");
Stack<Boolean> stack0 = new Stack<Boolean>();
defaultJSONParser0.checkListResolve(stack0);
assertEquals("[]", stack0.toString());
}
@Test(timeout = 4000)
public void test116() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ParserConfig parserConfig0 = new ParserConfig(classLoader0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("q:", parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.acceptType("fastjson.parser.autoTypeSupport");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// type not match error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test117() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Class<Long> class0 = Long.TYPE;
defaultJSONParser0.parseArrayWithType(class0);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test118() throws Throwable {
BigInteger bigInteger0 = BigInteger.ONE;
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ParserConfig parserConfig0 = new ParserConfig(classLoader0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(", column ", parserConfig0);
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Object) bigInteger0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// not match : - \u001A, info : pos 9, line 1, column 10, column
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test119() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("{_WQ!Z`j/", parserConfig0, 77);
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Object) parserConfig0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// setter not found, class com.alibaba.fastjson.parser.ParserConfig, property _WQ
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test120() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Object) "[biSj[9%X\")qg");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual [
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test121() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("63");
LinkedHashMap<Collator, MockDateFormat> linkedHashMap0 = new LinkedHashMap<Collator, MockDateFormat>();
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Object) linkedHashMap0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual int
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test122() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSjy9%X\"qg");
Type[] typeArray0 = new Type[1];
// Undeclared exception!
try {
defaultJSONParser0.parseArray(typeArray0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3[biSjy9%X\"qg
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test123() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSjy9%X\"qg");
// Undeclared exception!
try {
defaultJSONParser0.parseArray((Type[]) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test124() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
defaultJSONParser0.parseArray((Type[]) null);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test125() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSjy9%X\"qg");
ParameterizedTypeImpl parameterizedTypeImpl0 = (ParameterizedTypeImpl)TypeReference.LIST_STRING;
// Undeclared exception!
try {
defaultJSONParser0.parseArrayWithType(parameterizedTypeImpl0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, pos 2, line 1, column 3[biSjy9%X\"qg
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test126() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSjy9%X\"qg");
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory((ClassLoader) null);
Class<Short> class0 = Short.TYPE;
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) class0, (Object) aSMDeserializerFactory0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect {, actual [, pos 0, fastjson-version 1.2.68
//
verifyException("com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer", e);
}
}
@Test(timeout = 4000)
public void test127() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("{h{Nt<d0^G>I:Q<Lu");
Class<Short> class0 = Short.TYPE;
BigDecimal bigDecimal0 = BigDecimal.ZERO;
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) class0, (Object) bigDecimal0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// not match : - {, info : pos 2, line 1, column 3{h{Nt<d0^G>I:Q<Lu
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test128() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("\"hype\":\"", parserConfig0, 2488);
Class<Float> class0 = Float.TYPE;
// Undeclared exception!
try {
defaultJSONParser0.parseObject(class0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// parseLong error, field : null
//
verifyException("com.alibaba.fastjson.serializer.FloatCodec", e);
}
}
@Test(timeout = 4000)
public void test129() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Class<Float> class0 = Float.class;
defaultJSONParser0.parseObject(class0);
BitSet bitSet0 = new BitSet();
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) bitSet0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// unterminated json string, pos 4, line 1, column 5null
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test130() throws Throwable {
ParserConfig parserConfig0 = new ParserConfig(true);
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("{_WQ!Z`j/", parserConfig0, 11);
Class<Float> class0 = Float.TYPE;
TreeMap<GridBagConstraints, ThrowableDeserializer> treeMap0 = new TreeMap<GridBagConstraints, ThrowableDeserializer>();
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Map) treeMap0, (Object) class0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test131() throws Throwable {
DecimalFormat decimalFormat0 = new DecimalFormat("W");
char[] charArray0 = new char[4];
JSONReaderScanner jSONReaderScanner0 = new JSONReaderScanner(charArray0, 44);
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
jSONReaderScanner0.ch = ',';
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(decimalFormat0, jSONReaderScanner0, parserConfig0);
Class<JSONObject> class0 = JSONObject.class;
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) class0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// illegal identifier : \u0000
//
verifyException("com.alibaba.fastjson.parser.JSONLexerBase", e);
}
}
@Test(timeout = 4000)
public void test132() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("}");
JSONObject jSONObject0 = defaultJSONParser0.parseObject();
assertNotNull(jSONObject0);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test133() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
defaultJSONParser0.parseObject();
// Undeclared exception!
try {
defaultJSONParser0.parse();
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// unterminated json string, pos 4, line 1, column 5null
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test134() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("63");
defaultJSONParser0.getInput();
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test135() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("{w7Ae&vrVMb5lO", parserConfig0, 3484);
// Undeclared exception!
try {
defaultJSONParser0.parse((Object) "{w7Ae&vrVMb5lO");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// expect ':' at 0, actual &
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test136() throws Throwable {
ParserConfig parserConfig0 = ParserConfig.getGlobalInstance();
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("8.X,7@*2 y_\"!", parserConfig0, 4);
defaultJSONParser0.getDateFormat();
DateFormat dateFormat0 = defaultJSONParser0.getDateFormat();
assertEquals(0, defaultJSONParser0.resolveStatus);
assertNotNull(dateFormat0);
}
@Test(timeout = 4000)
public void test137() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
DateFormat dateFormat0 = DateFormat.getDateInstance();
defaultJSONParser0.setDateFomrat(dateFormat0);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test138() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("6K1^3");
defaultJSONParser0.getSymbolTable();
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test139() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("");
defaultJSONParser0.getContext();
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test140() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(",<?ZHKQp=Qd)Gehcjv");
defaultJSONParser0.setFieldTypeResolver((FieldTypeResolver) null);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test141() throws Throwable {
ClassLoader classLoader0 = ClassLoader.getSystemClassLoader();
ASMDeserializerFactory aSMDeserializerFactory0 = new ASMDeserializerFactory(classLoader0);
ParserConfig parserConfig0 = new ParserConfig(aSMDeserializerFactory0);
DefaultJSONParser defaultJSONParser0 = null;
try {
defaultJSONParser0 = new DefaultJSONParser((char[]) null, 0, parserConfig0, 2);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test142() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(",<?ZHKQp=Qd)Gehcjv");
Class<Integer> class0 = Integer.TYPE;
// Undeclared exception!
try {
defaultJSONParser0.parseObject((Type) class0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error,except start with { or [,but actually start with ,
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test143() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("null");
Feature feature0 = Feature.AllowSingleQuotes;
defaultJSONParser0.isEnabled(feature0);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test144() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("[biSj[9%X\")qg");
Feature feature0 = Feature.SupportArrayToBean;
defaultJSONParser0.config(feature0, false);
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test145() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("8<,33_x==2b");
// Undeclared exception!
try {
defaultJSONParser0.getLastResolveTask();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test146() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("NaN");
int int0 = defaultJSONParser0.getResolveStatus();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test147() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("(CLjava/lang/Str(g;");
// Undeclared exception!
try {
defaultJSONParser0.throwException(3);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// syntax error, expect float, actual (
//
verifyException("com.alibaba.fastjson.parser.DefaultJSONParser", e);
}
}
@Test(timeout = 4000)
public void test148() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser(", property ");
defaultJSONParser0.getFieldTypeResolver();
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test149() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("pa");
defaultJSONParser0.getDateFomartPattern();
assertEquals(0, defaultJSONParser0.resolveStatus);
}
@Test(timeout = 4000)
public void test150() throws Throwable {
DefaultJSONParser defaultJSONParser0 = new DefaultJSONParser("63");
defaultJSONParser0.setDateFormat("writeWithFormat");
assertEquals(0, defaultJSONParser0.resolveStatus);
}
}
| 39.348561 | 245 | 0.681322 |
b9dde7db2fd46f159f2b4079067b131cb56f38ce | 631 | package org.cang24.tests.changemaking.model.vault;
import org.cang24.tests.changemaking.model.ItemValue;
public class Cash implements ItemValue {
public enum CASH_TYPE{
COIN,
TICKET
}
private static int idCounters[] = new int[2];
private CASH_TYPE type;
private int value;
private int id;
public Cash(CASH_TYPE type, int value) {
super();
this.type = type;
this.value = value;
this.id = ++idCounters[type == CASH_TYPE.COIN ? 0:1];
}
public int getValue() {
return value;
}
public CASH_TYPE getType() {
return type;
}
public int getId() {
return id;
}
}
| 18.028571 | 56 | 0.651347 |
dbab22348806b01aa79e37a9b00734c88de49c5a | 220 | package de.dieklaut.camtool;
import java.time.Instant;
/**
* A {@link SourceFile} is the initial artifact of a {@link Group}
* @author mboonk
*
*/
public interface SourceFile {
public Instant getCreationDate();
}
| 16.923077 | 66 | 0.713636 |
05f93667ab68ab92a2f92d81950135852d8cb99e | 2,659 | package com.george.recipeapp.services;
import com.george.recipeapp.commands.RecipeCommand;
import com.george.recipeapp.converters.RecipeCommandToRecipe;
import com.george.recipeapp.converters.RecipeToRecipeCommand;
import com.george.recipeapp.domain.Recipe;
import com.george.recipeapp.repositories.reactive.RecipeReactiveRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Slf4j
@Service
public class RecipeServiceImpl implements RecipeService {
private final RecipeReactiveRepository recipeReactiveRepository;
private final RecipeCommandToRecipe recipeCommandToRecipe;
private final RecipeToRecipeCommand recipeToRecipeCommand;
public RecipeServiceImpl(RecipeReactiveRepository recipeReactiveRepository, RecipeCommandToRecipe recipeCommandToRecipe, RecipeToRecipeCommand recipeToRecipeCommand) {
this.recipeReactiveRepository = recipeReactiveRepository;
this.recipeCommandToRecipe = recipeCommandToRecipe;
this.recipeToRecipeCommand = recipeToRecipeCommand;
}
@Override
public Flux<Recipe> getRecipes() {
log.debug("I'm in the service");
return recipeReactiveRepository.findAll();
}
@Override
public Mono<Recipe> findById(String id) {
return recipeReactiveRepository.findById(id)
.doOnError(thr -> log.warn("Error reading Recipe. ID value: {}", id, thr));
}
@Override
public Mono<RecipeCommand> findCommandById(String id) {
return recipeReactiveRepository.findById(id)
.map(recipe -> {
RecipeCommand recipeCommand = recipeToRecipeCommand.convert(recipe);
recipeCommand.getIngredients().forEach(rc -> rc.setRecipeId(recipeCommand.getId()));
return recipeCommand;
});
/*return findById(id)
.map(recipeToRecipeCommand::convert)
.doOnError(thr -> log.warn("Recipe Not Found. ID value: " + id));*/
}
@Override
public Mono<RecipeCommand> saveRecipeCommand(RecipeCommand command) {
Recipe recipe = recipeCommandToRecipe.convert(command);
return recipeReactiveRepository.save(recipe)
.map(recipeToRecipeCommand::convert)
.doOnNext(savedRecipe -> log.debug("Saved recipe {}", savedRecipe.getId()));
}
@Override
public Mono<Void> deleteById(String idToDelete) {
return recipeReactiveRepository.deleteById(idToDelete)
.doOnSuccess(tmp -> log.info("Deleted recipe {}", idToDelete));
}
}
| 38.536232 | 171 | 0.711922 |
ce7593a2dc746e09dbb21ffbe22d84f2f2eb9df6 | 186 | class BitWiseNOT
{
public static void main(String arr[])
{
int x=2;
int a ;
a = ~x; // Bit-wise NOT operator
System.out.println("The bit-wise NOT of 2 is: " +a) ;
}
}
| 16.909091 | 55 | 0.580645 |
bf6203cf81ffce76f85d6d1abb14eb9f396bdf7b | 3,125 | package com.droidfoundry.droidmetronome.control;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Vibrator;
/**
* Created by pedro on 27/06/15.
*/
public class HardwareActions {
private static HardwareActions ourInstance = new HardwareActions();
private Vibrator vibrate;
private Camera camera;
private Context context;
private boolean isVibrating;
private boolean isLighting;
private boolean hardwareSupported;
private long delay;
private HardwareActions() {}
public static HardwareActions getInstance() {
return ourInstance;
}
/**
* Iniciando configuração de sistema do metronomo
*/
public void startConfiguration(){
// Configurações gerais
this.vibrate = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
this.hardwareSupported = hardwareSupported();
}
/**
* Define as configurações de hardware
* @param vibrating - Define vibrações
* @param lighting - Define luz
* @param context - Contexto da aplicacao
*/
public void setHardwareConfiguration(boolean vibrating ,boolean lighting ,Context context){
this.isVibrating = vibrating;
this.isLighting = lighting;
this.context = context;
this.hardwareSupported = this.hardwareSupported();
}
/**
* Define o tempo da vibração
* @param delay
*/
public void setDelay(long delay) {
this.delay = delay;
}
/**
* Verifica se o hardware é compativel
* @return
*/
private boolean hardwareSupported(){
PackageManager pm = context.getPackageManager();
boolean switchFlash = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
boolean switchCamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
return switchFlash && switchCamera;
}
/**
* Ativando vibração
*/
public void activeVibration(){
if(isVibrating) {
vibrate.vibrate(delay / 10);
}
}
/**
* Ativa a luz
*/
public void activeLighting(){
if((isLighting) && (hardwareSupported) && (camera == null)){
new Thread(){
@Override
public void run() {
camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
}
}.start();
}
}
/**
* Desativa a luz
*/
public void desactiveLighting(){
if((isLighting) && (hardwareSupported) && (camera != null)){
new Thread(){
@Override
public void run() {
camera.release();
camera = null;
}
}.start();
}
}
}
| 26.939655 | 95 | 0.57888 |
36ae40ba5ddc8f1ede15cae1b546f245345d5311 | 847 | package it.unibo.pensilina14.bullet.ballet;
import it.unibo.pensilina14.bullet.ballet.menu.controller.Difficulties;
import it.unibo.pensilina14.bullet.ballet.menu.controller.Resolutions;
public class GameInfoImpl implements GameInfo{
private Resolutions resolution;
private Difficulties difficulty;
public GameInfoImpl(final Resolutions resolution, final Difficulties difficulty) {
this.resolution = resolution;
this.difficulty = difficulty;
}
@Override
public Resolutions getCurrentResolution() {
return this.resolution;
}
@Override
public Difficulties getCurrentDifficulty() {
return this.difficulty;
}
@Override
public void setResolution(final Resolutions resolution) {
this.resolution = resolution;
}
@Override
public void setDifficulty(final Difficulties difficulty) {
this.difficulty = difficulty;
}
}
| 22.891892 | 83 | 0.792208 |
3a44c967c405a723e2d0033672320dddd0933f95 | 3,951 | package sample;
import javafx.application.Application;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import sample.api.APIWrapper;
import sample.data.Champion;
import sample.data.RunePage;
import sample.imgcap.WindowScraper;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class Main extends Application {
private static final Logger logger = Logger.getLogger(Main.class);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
// Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
// primaryStage.setTitle("Hello World");
// primaryStage.setScene(new Scene(root, 300, 275));
// primaryStage.show();
WindowScraper windowScraper = new WindowScraper();
windowScraper.findLoLWindow();
APIWrapper apiWrapper = new APIWrapper();
apiWrapper.setLoLClientInfo();
apiWrapper.getAPIData();
while(true) {
if(windowScraper.getHWnd() == 0 || apiWrapper.getPid().equals("null")) {
windowScraper = new WindowScraper();
windowScraper.findLoLWindow();
apiWrapper = new APIWrapper();
apiWrapper.setLoLClientInfo();
if(windowScraper.getHWnd() == 0 || apiWrapper.getPid().equals("null")) {
logger.error("Unable to find LoL client.");
} else {
logger.info("Found LoL client.");
apiWrapper.getAPIData();
}
Thread.sleep(5000);
} else {
Thread.sleep(1000);
String approxChampName = windowScraper.update();
if(!approxChampName.equals("")) {
logger.info("Name scraped from screenshot: " + approxChampName);
Champion champion = apiWrapper.getChampionBySkinName(approxChampName);
if(champion == null) {
logger.info("Cannot find champion with name: " + approxChampName);
int minLevenshteinDistance = Integer.MAX_VALUE;
String closestChampionName = null;
for(String champName : apiWrapper.getSkinIdMap().keySet()) {
int currLevenshteinDistance = StringUtils.getLevenshteinDistance(champName, approxChampName);
if(currLevenshteinDistance < minLevenshteinDistance) {
minLevenshteinDistance = currLevenshteinDistance;
closestChampionName = champName;
}
}
logger.info("Closest match to " + approxChampName + " is " + closestChampionName);
champion = apiWrapper.getChampionBySkinName(closestChampionName);
} else {
champion = apiWrapper.getChampionBySkinName(approxChampName);
}
logger.info("Found champion info: " + champion);
List<RunePage> runePageList = apiWrapper.getPages();
RunePage apiPage = runePageList.stream().filter(o -> o.getName().equalsIgnoreCase("AutoRune")).findFirst().orElse(null);
if(apiPage != null) {
Set<String> roles = champion.getMostFrequentRoleRuneMap().keySet();
String role = roles.iterator().next();
List<String> runes = champion.getMostFrequentRoleRuneMap().get(role);
apiPage.setPrimaryStyleId(Integer.parseInt(runes.get(0)));
apiPage.setSubStyleId(Integer.parseInt(runes.get(5)));
List<Integer> selectedPerkIds = new ArrayList<>();
selectedPerkIds.add(Integer.parseInt(runes.get(1)));
selectedPerkIds.add(Integer.parseInt(runes.get(2)));
selectedPerkIds.add(Integer.parseInt(runes.get(3)));
selectedPerkIds.add(Integer.parseInt(runes.get(4)));
selectedPerkIds.add(Integer.parseInt(runes.get(6)));
selectedPerkIds.add(Integer.parseInt(runes.get(7)));
apiPage.setSelectedPerkIds(selectedPerkIds);
System.out.println(champion);
System.out.println(apiPage);
apiWrapper.replacePage(apiPage.getId(), apiPage);
logger.info("Set rune page. Timeout for 10 seconds. ");
Thread.sleep(10000);
} else {
logger.error("Cannot find rune page named AutoRune. Please create page.");
}
}
}
}
}
}
| 35.918182 | 125 | 0.700076 |
7a75dd125b77b51ff2ca75d54c298736855ccd92 | 4,423 | /*
* 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.codehaus.groovy.transform.sc.transformers;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.transform.sc.StaticCompilationMetadataKeys;
import org.codehaus.groovy.transform.stc.StaticTypesMarker;
import static org.codehaus.groovy.ast.tools.GeneralUtils.propX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.thisPropX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
/**
* Transformer for VariableExpression the bytecode backend wouldn't be able to
* handle otherwise.
*/
public class VariableExpressionTransformer {
public Expression transformVariableExpression(final VariableExpression expr) {
Expression trn = tryTransformDelegateToProperty(expr);
if (trn == null) {
trn = tryTransformPrivateFieldAccess(expr);
}
return trn != null ? trn : expr;
}
private static Expression tryTransformDelegateToProperty(final VariableExpression expr) {
// we need to transform variable expressions that go to a delegate
// to a property expression, as ACG would lose the information in
// processClassVariable before it reaches any makeCall, that could handle it
Object val = expr.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER);
if (val == null) return null;
// TODO: handle the owner and delegate cases better for nested scenarios and potentially remove the need for the implicit this case
Expression receiver = varX("owner".equals(val) ? (String) val : "delegate".equals(val) ? (String) val : "this");
// GROOVY-9136 -- object expression should not overlap source range of property; property stands in for original variable expression
receiver.setLineNumber(expr.getLineNumber());
receiver.setColumnNumber(expr.getColumnNumber());
PropertyExpression pexp = propX(receiver, expr.getName());
pexp.getProperty().setSourcePosition(expr);
pexp.copyNodeMetaData(expr);
pexp.setImplicitThis(true);
ClassNode owner = expr.getNodeMetaData(StaticCompilationMetadataKeys.PROPERTY_OWNER);
if (owner != null) {
receiver.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, owner);
receiver.putNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER, val);
}
pexp.removeNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER);
return pexp;
}
private static Expression tryTransformPrivateFieldAccess(final VariableExpression expr) {
FieldNode field = expr.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);
if (field == null) {
field = expr.getNodeMetaData(StaticTypesMarker.PV_FIELDS_MUTATION);
}
if (field != null) {
// access to a private field from a section of code that normally doesn't have access to it, like a closure or an inner class
PropertyExpression pexp = thisPropX(true, expr.getName());
// store the declaring class so that the class writer knows that it will have to call a bridge method
pexp.getObjectExpression().putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, field.getDeclaringClass());
pexp.putNodeMetaData(StaticTypesMarker.DECLARATION_INFERRED_TYPE, field.getOriginType());
pexp.getProperty().setSourcePosition(expr);
return pexp;
}
return null;
}
}
| 48.076087 | 140 | 0.727108 |
7684f6a187831d1fcc16e24954a890f228969160 | 6,331 | package com.khorium.publicfarm.database;
import com.khorium.publicfarm.Utils.LogUtil;
import com.khorium.publicfarm.Utils.MsgUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
public class Database {
private DatabaseCore core;
/**
* Creates a new database and validates its connection.
* <p>
* If the connection is invalid, this will throw a ConnectionException.
*
* @param core The core for the database, either MySQL or SQLite.
* @throws ConnectionException If the connection was invalid
*/
public Database(DatabaseCore core) throws ConnectionException {
try {
if (core.getConnectionTest() == null) {
throw new ConnectionException("Database doesn not appear to " +
"be valid!");
}
} catch (AbstractMethodError e) {
// You don't need to validate this core.
}
this.core = core;
}
/**
* Returns the database core object, that this database runs on.
*
* @return the database core object, that this database runs on.
*/
public DatabaseCore getCore() {
return core;
}
/**
* Fetches the connection to this database for querying. Try to avoid doing
* this in the main thread.
*
* @return Fetches the connection to this database for querying.
*/
public Connection getConnection() {
return core.getConnection();
}
/**
* Executes the given statement either immediately, or soon.
*
* @param query The query
* @param objs The string values for each ? in the given query.
*/
public void execute(String query, Object... objs) {
BufferStatement bs = new BufferStatement(query, objs);
core.queue(bs);
}
/**
* Returns true if the table exists
*
* @param table The table to check for
* @return True if the table is found
*/
public boolean hasTable(String table) throws SQLException {
ResultSet rs = getConnection().getMetaData().getTables(null, null,
"%", null);
while (rs.next()) {
if (table.equalsIgnoreCase(rs.getString("TABLE_NAME"))) {
rs.close();
return true;
}
}
rs.close();
return false;
}
/**
* Closes the database
*/
public void close() {
this.core.close();
}
/**
* Returns true if the given table has the given column
*
* @param table The table
* @param column The column
* @return True if the given table has the given column
* @throws SQLException If the database isn't connected
*/
public boolean hasColumn(String table, String column) throws SQLException {
if (!hasTable(table))
return false;
String query = "SELECT * FROM " + table + " LIMIT 0,1";
try {
PreparedStatement ps = this.getConnection().prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
rs.getString(column); // Throws an exception if it can't find
// that column
return true;
}
} catch (SQLException e) {
return false;
}
return false; // Uh, wtf.
}
/**
* Represents a connection error, generally when the server can't connect to
* MySQL or something.
*/
public static class ConnectionException extends Exception {
private static final long serialVersionUID = 8348749992936357317L;
public ConnectionException(String msg) {
super(msg);
}
}
/**
* Copies the contents of this database into the given database. Does not
* delete the contents of this database, or change any settings. This may
* take a long time, and will print out progress reports to System.out
* <p>
* This method does not create the tables in the new database. You need to
* do that yourself.
*
* @param db The database to copy data to
* @throws SQLException if an error occurs.
*/
public void copyTo(Database db) throws SQLException {
ResultSet rs = getConnection().getMetaData().getTables(null, null,
"%", null);
List<String> tables = new LinkedList<String>();
while (rs.next()) {
tables.add(rs.getString("TABLE_NAME"));
}
rs.close();
core.flush();
// For each table
for (String table : tables) {
if (table.toLowerCase().startsWith("sqlite_autoindex_"))
continue;
System.out.println("Copying " + table);
// Wipe the old records
db.getConnection().prepareStatement("DELETE FROM " + table)
.execute();
// Fetch all the data from the existing database
rs = getConnection().prepareStatement("SELECT * FROM " + table)
.executeQuery();
int n = 0;
// Build the query
String query = "INSERT INTO " + table + " VALUES (";
// Append another placeholder for the value
query += "?";
for (int i = 2; i <= rs.getMetaData().getColumnCount(); i++) {
// Add the rest of the placeholders and values. This is so we
// have (?, ?, ?) and not (?, ?, ?, ).
query += ", ?";
}
// End the query
query += ")";
PreparedStatement ps = db.getConnection().prepareStatement(query);
while (rs.next()) {
n++;
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
ps.setObject(i, rs.getObject(i));
}
ps.addBatch();
if (n % 100 == 0) {
ps.executeBatch();
System.out.println(n + " records copied...");
}
}
ps.executeBatch();
// Close the resultset of that table
rs.close();
}
// Success!
db.getConnection().close();
this.getConnection().close();
}
} | 32.803109 | 80 | 0.559153 |
092b524c7bcf629f55a7b6cbf705518871a715a4 | 274 | package client1;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import generic.Client;
import service.Service;
public class Client1 extends Client {
@Inject
public Client1(@Named("client1") Service service) {
super(service);
}
}
| 19.571429 | 55 | 0.722628 |
f4950b3e1602ffc2b0fdb01a57c06fb4f0fdc5bb | 948 |
interface Shape {
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
class ShapeMaker {
private final Shape circle;
private final Shape rectangle;
private final Shape square;
public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle() {
circle.draw();
}
public void drawRectangle() {
rectangle.draw();
}
public void drawSquare() {
square.draw();
}
}
public class Facade {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}
| 15.290323 | 43 | 0.67827 |
30041df8a8ae2148649e62c04b1ad9acda2d1f39 | 2,641 | /*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI 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.eigenbase.rel;
import org.eigenbase.rel.metadata.*;
import org.eigenbase.relopt.*;
/**
* <code>IntersectRel</code> returns the intersection of the rows of its inputs.
* If "all" is true, then multiset intersection is performed; otherwise, set
* intersection is performed (implying no duplicates in the results).
*
* @author jhyde
* @version $Id$
* @since 23 September, 2001
*/
public final class IntersectRel
extends SetOpRel
{
//~ Constructors -----------------------------------------------------------
public IntersectRel(
RelOptCluster cluster,
RelNode [] inputs,
boolean all)
{
super(
cluster,
new RelTraitSet(CallingConvention.NONE),
inputs,
all);
}
//~ Methods ----------------------------------------------------------------
// implement RelNode
public double getRows()
{
// REVIEW jvs 30-May-2005: I just pulled this out of a hat.
double dRows = Double.MAX_VALUE;
for (int i = 0; i < inputs.length; i++) {
dRows =
Math.min(
dRows,
RelMetadataQuery.getRowCount(inputs[i]));
}
dRows *= 0.25;
return dRows;
}
public IntersectRel clone()
{
IntersectRel clone =
new IntersectRel(
getCluster(),
RelOptUtil.clone(inputs),
all);
clone.inheritTraitsFrom(this);
return clone;
}
public IntersectRel clone(RelNode [] inputs, boolean all)
{
final IntersectRel clone =
new IntersectRel(
getCluster(),
inputs,
all);
clone.inheritTraitsFrom(this);
return clone;
}
}
// End IntersectRel.java
| 28.706522 | 80 | 0.588413 |
902ed52e7fc3b42c2104676f9e1a9e9737fb48c0 | 573 | package duke.learn.lesson09.di.ci.inheritance.xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ci-inherit-beans.xml");
Employee parent = (Employee) context.getBean("emp1");
parent.print();
System.out.println("************************************");
Employee child = (Employee) context.getBean("emp2");
child.print();
}
}
| 33.705882 | 90 | 0.701571 |
2637551fab261a373b0e73d9285f562ca579ee2c | 2,665 | /**
* LEIDOS CONFIDENTIAL
* __________________
*
* (C)[2007]-[2014] Leidos
* Unpublished - All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the exclusive property of Leidos and its suppliers, if any.
* The intellectual and technical concepts contained
* herein are proprietary to Leidos and its suppliers
* and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Leidos.
*/
package com.deleidos.rtws.commons.cloud.environment.monitor.tasks;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.deleidos.rtws.commons.cloud.environment.monitor.representations.InstanceDescription;
import com.google.common.base.Splitter;
public class EucaDescribeInstances {
private static Logger logger = LoggerFactory.getLogger(EucaDescribeInstances.class);
private EucaDescribeCommand command;
public List<InstanceDescription> fetch() {
String data = command.execute();
if (data.length() > 0)
return parse(data);
return null;
}
private static List<InstanceDescription> parse(String input) {
List<InstanceDescription> instanceDescriptions = new LinkedList<InstanceDescription>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new StringReader(input));
int ct = 0;
String line = null;
while (reader.ready() && (line = reader.readLine()) != null) {
if (line != null) {
if (!line.startsWith("#") && line.length() > 0) {
// Process odd # lines because event number lines are RESERVATION lines
if ( line.startsWith("INSTANCE")) {
if (logger.isDebugEnabled())
logger.debug("line {} => trimmed {}", line, line.replaceAll("\\s++", "|"));
Splitter sp = Splitter.on("|").trimResults();
List<String> tokens = sp.splitToList(line.replaceAll("\\s++", "|"));
instanceDescriptions.add(new InstanceDescription(tokens.get(1), tokens.get(3),
tokens.get(4), tokens.get(5),
tokens.get(8)));
}
}
}
ct++;
}
} catch (IOException e) {
logger.error(e.getMessage());
} finally {
IOUtils.closeQuietly(reader);
}
return instanceDescriptions;
}
public EucaDescribeInstances(EucaDescribeCommand command) {
this.command = command;
}
}
| 28.052632 | 95 | 0.697186 |
b5b51ca78304629b51f6c5ec741a9fd769ad4e4d | 206 | package com.deer.wms.bill.manage.model;
import com.deer.wms.project.seed.core.service.QueryCriteria;
/**
* Created by on 2018/12/30.
*/
public class MtAloneTagCriteria extends QueryCriteria {
}
| 20.6 | 61 | 0.73301 |
59d8650327391887f8b84a22d444f6a472679900 | 832 | package study.ywork.web.test.request.path;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 此处没有明确正则表达会引起二义性
*/
@Controller
@RequestMapping("/employees")
public class EmployeeController {
@GetMapping("{id}")
public String handleRequest(@PathVariable("id") String userId, Model model) {
model.addAttribute("msg", "雇员ID: " + userId);
return "message";
}
@GetMapping("{employeeName}")
public String handleRequest2(@PathVariable("employeeName") String userName, Model model) {
model.addAttribute("msg", "雇员名字: " + userName);
return "message";
}
}
| 29.714286 | 94 | 0.725962 |
3c56fafb939453dc2c1e7282d6172058e4371091 | 810 | package cn.felord.wepay.ali.sdk.api.domain;
import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;
/**
* yufalingsanyaowub
*
* @author auto create
* @version $Id: $Id
*/
public class AlipayOpenAppYufalingsanyaowubYufalingsanyaowubQueryModel extends AlipayObject {
private static final long serialVersionUID = 1264358665464973355L;
/**
* yufaa
*/
@ApiField("yufaa")
private String yufaa;
/**
* <p>Getter for the field <code>yufaa</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getYufaa() {
return this.yufaa;
}
/**
* <p>Setter for the field <code>yufaa</code>.</p>
*
* @param yufaa a {@link java.lang.String} object.
*/
public void setYufaa(String yufaa) {
this.yufaa = yufaa;
}
}
| 20.25 | 93 | 0.690123 |
da0d9537d69bc7ec7abba300e184bb17a7b9d56a | 826 | package io.yaoo.test;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Map;
public class JWTSignVerify {
private byte[] secret;
public JWTSignVerify(String secret){
this.secret = secret.getBytes();
}
public String sign(Map payload, Date expiration) {
String token = Jwts.builder()
.setClaims(payload)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
return token;
}
public Claims verify(String token){
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
return claims;
}
} | 22.944444 | 59 | 0.605327 |
53dce6d8d1954c999703ce03de6238ab94369c6c | 1,101 |
public class recursividadpregunta0a {
public static void main (String[] args) {
// Inicio
int kwconsumidos;
// Leer Consumo Kw/h en Cada Departamento del Condominio
kwconsumidos=358;
double precio;
precio=0;
// Calcular Precio
// Variable contador =1
// Variable preciotemporal=0.0
// Para cada incremento del contador hasta el Consumo
for (int i=1;i<=kwconsumidos;i++) {
// Si Contador>150
if (i>150)
// preciotemporal=preciotemporal+2.00;
precio=precio+2.00;
// SI Contador>50 Y Contador <=150
if ((i>50)&&(i<=150))
// preciotemporal=preciotemporal+1.50;
precio=precio+1.50;
// SI Contador>0 Y Contador <=50
if((i>0)&&(i<=50))
// preciotemporal=preciotemporal+0.50;
precio=precio+0.50;
// Fin Incremento
// Fin
}
System.out.println("El precio final es:");
System.out.println(precio);
}
}
| 28.230769 | 66 | 0.518619 |
bbecd1b3b7a427a36fc31e6c86cc5ed633769927 | 3,171 | /*
* Copyright (c) 2022 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.opengauss.mppdbide.parser.alias;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.opengauss.mppdbide.bl.queryparser.IParseContextGetter;
import org.opengauss.mppdbide.bl.queryparser.ParseContext;
import org.opengauss.mppdbide.parser.factory.PostgresParserFactory;
import org.opengauss.mppdbide.parser.runtimehandler.RunTimeParserException;
import org.opengauss.mppdbide.parser.runtimehandler.RuntimeErrorStrategyManager;
import org.opengauss.mppdbide.utils.logger.MPPDBIDELoggerUtility;
/**
* Title: class Description: The Class AliasParser.
*
* @since 3.0.0
*/
public class AliasParser implements IParseContextGetter {
private ParseContext aliases;
private LexerErrorListener lexerErrlorListener;
private AliasParserErrorListener parserErrlorListener;
private ParseTreeWalker walker;
/**
* Instantiates a new alias parser.
*/
public AliasParser() {
aliases = null;
lexerErrlorListener = new LexerErrorListener();
parserErrlorListener = new AliasParserErrorListener();
walker = new ParseTreeWalker();
}
/**
* parse a query using antlr4
*
* @param query - query to be parsed
*/
public void parseQuery(String query) {
Lexer lexer = PostgresParserFactory.getPostgresLexer(query);
lexer.removeErrorListeners();
lexer.addErrorListener(lexerErrlorListener);
Parser parser = PostgresParserFactory.getPostgresParser(lexer);
parser.setErrorHandler(RuntimeErrorStrategyManager.getRuntimeErrorhandler());
parser.removeErrorListeners();
parser.addErrorListener(parserErrlorListener);
AliasParseListener parseListener = new AliasParseListener();
try {
ParseTree tree = PostgresParserFactory.getPostgresParserAllStmt(parser);
walker.walk(parseListener, tree);
aliases = parseListener.getAliasParseContext();
} catch (Exception exception) {
if (exception instanceof RunTimeParserException) {
MPPDBIDELoggerUtility.error("Alias parser worker interrupted", exception);
throw exception;
} else {
MPPDBIDELoggerUtility.error("Error while parsing", exception);
}
}
}
/**
* getter method for the parsed information
*
* @return - parse context for the query parsed
*/
public ParseContext getParseContext() {
return aliases;
}
}
| 34.096774 | 90 | 0.705456 |
0d4d4a029e72cb5f4a03ffb751befeafd4c81659 | 774 | package com.alibaba.alink.operator.batch.classification;
import org.apache.flink.ml.api.misc.param.Params;
import org.apache.flink.types.Row;
import com.alibaba.alink.operator.common.tree.TreeModelInfo;
import com.alibaba.alink.operator.common.tree.TreeModelInfo.GbdtModelInfo;
import com.alibaba.alink.operator.common.tree.TreeModelInfoBatchOp;
import java.util.List;
public class GbdtModelInfoBatchOp
extends TreeModelInfoBatchOp<TreeModelInfo.GbdtModelInfo, GbdtModelInfoBatchOp> {
private static final long serialVersionUID = -3480110970465880504L;
public GbdtModelInfoBatchOp() {
}
public GbdtModelInfoBatchOp(Params params) {
super(params);
}
@Override
protected GbdtModelInfo createModelInfo(List <Row> rows) {
return new GbdtModelInfo(rows);
}
}
| 27.642857 | 82 | 0.813953 |
4c5f8e2bc052143eb4d06f4cf1e7a56462edba21 | 1,115 | package ast;
import lib.FOOLlib;
public class IfNode implements Node {
private Node cond;
private Node th;
private Node el;
public IfNode (Node c, Node t, Node e) {
cond=c;
th=t;
el=e;
}
public String toPrint(String s) {
return s+"If\n" + cond.toPrint(s+" ")
+ th.toPrint(s+" ")
+ el.toPrint(s+" ") ;
}
public Node typeCheck() {
if ( !(FOOLlib.isSubtype(cond.typeCheck(), new BoolTypeNode())) ) {
System.out.println("non boolean condition in if");
System.exit(0);
}
Node t= th.typeCheck();
Node e= el.typeCheck();
if (FOOLlib.isSubtype(t, e))
return e;
if (FOOLlib.isSubtype(e, t))
return t;
System.out.println("Incompatible types in then-else branches");
System.exit(0);
return null;
}
public String codeGeneration() {
String l1= FOOLlib.freshLabel();
String l2= FOOLlib.freshLabel();
return cond.codeGeneration()+
"push 1\n"+
"beq "+l1+"\n"+
el.codeGeneration()+
"b "+l2+"\n"+
l1+": \n"+
th.codeGeneration()+
l2+": \n"
;
}
} | 21.037736 | 68 | 0.565919 |
26ea3f6bd879fefa3212823c69811c081be89220 | 364 | class Solution {
public int longestPalindrome(String s) {
int[] map = new int[128];
for(char a : s.toCharArray()){
map[a] += 1;
}
boolean hasOdd = false;
int total = 0;
for(int m : map){
total += (m/2 * 2);
}
if(total < s.length()) total++;
return total;
}
} | 24.266667 | 44 | 0.442308 |
15ae0ee6aef6d717705cb36efd41d6b7e22d1966 | 2,972 | package com.baomidou.mybatisplus.test.h2;
import com.baomidou.mybatisplus.test.h2.keygenerator.mapper.ExtendKeyGeneratorMapper;
import com.baomidou.mybatisplus.test.h2.keygenerator.mapper.KeyGeneratorMapper;
import com.baomidou.mybatisplus.test.h2.keygenerator.mapper.LongKeyGeneratorMapper;
import com.baomidou.mybatisplus.test.h2.keygenerator.mapper.StringKeyGeneratorMapper;
import com.baomidou.mybatisplus.test.h2.keygenerator.model.ExtendKeyGeneratorModel;
import com.baomidou.mybatisplus.test.h2.keygenerator.model.KeyGeneratorModel;
import com.baomidou.mybatisplus.test.h2.keygenerator.model.LongKeyGeneratorModel;
import com.baomidou.mybatisplus.test.h2.keygenerator.model.StringKeyGeneratorModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {"classpath:h2/spring-keygenerator-h2.xml"})
class H2KeyGeneratorTest {
@Autowired
private KeyGeneratorMapper keyGeneratorMapper;
@Autowired
private LongKeyGeneratorMapper longKeyGeneratorMapper;
@Autowired
private StringKeyGeneratorMapper stringKeyGeneratorMapper;
@Autowired
private ExtendKeyGeneratorMapper extendKeyGeneratorMapper;
@Test
void test() {
KeyGeneratorModel keyGeneratorModel = new KeyGeneratorModel();
keyGeneratorModel.setName("我举起了咩咩");
keyGeneratorMapper.insert(keyGeneratorModel);
Assertions.assertNotNull(keyGeneratorModel.getUid());
Assertions.assertEquals(keyGeneratorModel.getUid(), 1L);
LongKeyGeneratorModel longKeyGeneratorModel = new LongKeyGeneratorModel();
longKeyGeneratorModel.setName("我举起了个栗子");
longKeyGeneratorMapper.insert(longKeyGeneratorModel);
Assertions.assertNotNull(longKeyGeneratorModel.getId());
Assertions.assertEquals(longKeyGeneratorModel.getId(), 2L);
StringKeyGeneratorModel stringKeyGeneratorModel = new StringKeyGeneratorModel();
stringKeyGeneratorModel.setName("我举起了个锤子");
stringKeyGeneratorMapper.insert(stringKeyGeneratorModel);
Assertions.assertNotNull(stringKeyGeneratorModel.getId());
Assertions.assertEquals(stringKeyGeneratorModel.getId(), "3");
ExtendKeyGeneratorModel extendKeyGeneratorModel = new ExtendKeyGeneratorModel();
extendKeyGeneratorModel.setName("我举起了句号");
extendKeyGeneratorMapper.insert(extendKeyGeneratorModel);
Assertions.assertNotNull(extendKeyGeneratorModel.getUid());
Assertions.assertEquals(extendKeyGeneratorModel.getUid(), 4L);
}
}
| 45.723077 | 88 | 0.80249 |
8449cb15cb36c06eca143bf6f8e7554375070714 | 204 | package com.example.openticket.command;
public class BookingCommand implements IBookingCommand {
@Override
public void bookShow() {
}
@Override
public void unBookShow() {
}
}
| 14.571429 | 57 | 0.676471 |
5a0af1cf0198900ed57ddc52eecee8e380a1a1cc | 3,736 | /* file: DataStructuresHomogenTensor.java */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* 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.
*******************************************************************************/
/*
// Content:
// Java example of using homogeneous data structures
////////////////////////////////////////////////////////////////////////////////
*/
/**
* <a name="DAAL-EXAMPLE-JAVA-DATASTRUCTURESHOMOGENTENSOR">
* @example DataStructuresHomogenTensor.java
*/
package com.intel.daal.examples.datasource;
import java.nio.FloatBuffer;
import com.intel.daal.data_management.data.HomogenTensor;
import com.intel.daal.examples.utils.Service;
import com.intel.daal.services.DaalContext;
class DataStructuresHomogenTensor {
private static DaalContext context = new DaalContext();
public static void main(String[] args) {
int readFeatureIdx;
float[] data = {1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,21,22,23,24,25,26,27,28,29};
long[] dims = {3,3,3};
System.out.println("Initial data:");
for(int i= 0;i<dims[0]*dims[1]*dims[2];i++)
{
System.out.format("% 5.1f ", data[i]);
}
System.out.println("");
HomogenTensor dataTensor = new HomogenTensor(context, dims, data);
long fDims[] = {0,1};
FloatBuffer dataFloatSubtensor = FloatBuffer.allocate(2);
dataTensor.getSubtensor(fDims, 1, 2, dataFloatSubtensor);
int sub_demension = dataFloatSubtensor.arrayOffset() + 1;
int sub_size = dataFloatSubtensor.capacity();
System.out.format("Subtensor dimensions: % 5.1f\n", (float)sub_demension);
System.out.format("Subtensor size: % 5.1f\n", (float)sub_size);
System.out.println("Subtensor data:");
for(int i= 0;i<sub_size;i++)
{
System.out.format("% 5.1f ", dataFloatSubtensor.get(i));
}
System.out.println("");
dataFloatSubtensor.put(-1);
dataTensor.releaseSubtensor(fDims, 1, 2, dataFloatSubtensor);
System.out.println("Data after modification:");
for(int i= 0;i<dims[0]*dims[1]*dims[2];i++)
{
System.out.format("% 5.1f ", data[i]);
}
System.out.println("");
context.dispose();
}
private static void printFloatBuffer(FloatBuffer buf, long nColumns, long nRows, String message) {
int step = (int) nColumns;
System.out.println(message);
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nColumns; j++) {
System.out.format("%6.3f ", buf.get(i * step + j));
}
System.out.println("");
}
System.out.println("");
}
private static void printFloatArray(float[] buf, long nColumns, long nRows, String message) {
int step = (int) nColumns;
System.out.println(message);
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nColumns; j++) {
System.out.format("%6.3f ", buf[i * step + j]);
}
System.out.println("");
}
System.out.println("");
}
}
| 33.357143 | 102 | 0.574143 |
544e9aff75aa9b8cedc26e3a41243a143f683907 | 6,324 | package com.radish.master.controller.project;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.cnpc.framework.base.entity.Dict;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.BaseService;
import com.cnpc.framework.utils.SecurityUtil;
import com.radish.master.entity.BuildDiary;
import com.radish.master.entity.Project;
import com.radish.master.pojo.Options;
@Controller
@RequestMapping("/prodiary")
public class ProjectDiaryController {
private String prefix = "newDiary/";
@Autowired
private BaseService baseService;
@RequestMapping("/grlist")
public String grlist(HttpServletRequest request){
//列表添加人员条件
User u = SecurityUtil.getUser();
request.setAttribute("ryid", u.getId());
request.setAttribute("ry", u.getName());
//判断人员是否存在班组人员表,存在,搜出班组的项目,不存在 搜出全部项目
String sql = "select a.id value, a.project_name data from tbl_project a where "
+ " exists (select b.* from tbl_user_team b where a.id = b.project_id and b.user_id = '"+u.getId()+"')";
List tjxm = baseService.findMapBySql(sql, new Object[]{}, new Type[]{StringType.INSTANCE}, Options.class);
if(tjxm.size()>0){
request.setAttribute("xm", JSONArray.toJSONString(tjxm));
}else{
List xm = baseService.findMapBySql("select id value, project_name data from tbl_project", new Object[]{}, new Type[]{StringType.INSTANCE}, Options.class);
request.setAttribute("xm", JSONArray.toJSONString(xm));
}
return prefix +"grlist";
}
@RequestMapping("/gllist")
public String gllist(HttpServletRequest request){
List xm = baseService.findMapBySql("select id value, project_name data from tbl_project", new Object[]{}, new Type[]{StringType.INSTANCE}, Options.class);
request.setAttribute("xm", JSONArray.toJSONString(xm));
return prefix +"gllist";
}
@RequestMapping("/addindex")
public String addindex(HttpServletRequest request){
String xmid=request.getParameter("xmid");
String rq=request.getParameter("rq");
String ryid=request.getParameter("ryid");
String rzid=request.getParameter("rzid");
String lx=request.getParameter("lx");
Project xm = baseService.get(Project.class, xmid);
User u = baseService.get(User.class, ryid);
request.setAttribute("xmid", xmid);
request.setAttribute("rq", rq);
request.setAttribute("ryid", ryid);
request.setAttribute("rzid", rzid);
request.setAttribute("lx", lx);
request.setAttribute("xmmc", xm.getProjectName());
request.setAttribute("rymc", u.getName());
String jobid = u.getJobId();
if(jobid==null){
request.setAttribute("job", "");
}else{
Dict d = baseService.get(Dict.class, jobid);
if(d==null){
request.setAttribute("job", "");
}else{
request.setAttribute("job", d.getName());
}
}
return prefix +"addIndex";
}
//获取选择年月的对于 人 项目 的整月日志数据
@RequestMapping("/getRq")
@ResponseBody
public Result getRq(HttpServletRequest request){
Result r = new Result();
String rq = request.getParameter("rzdate");
String xmid = request.getParameter("xmid");
String ryid = request.getParameter("ryid");
String[] rqs = rq.split("-");
int year =Integer.valueOf(rqs[0]);
int month = Integer.valueOf(rqs[1]);
Calendar c = Calendar.getInstance();
c.set(year, month, 0);
//获取选择月的天数
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
//System.out.println(dayOfMonth);
List<Map<String,Object>> sj = new ArrayList<Map<String,Object>>();
for(int i=1;i<=dayOfMonth;i++){
Map<String,Object> m = new HashMap<String, Object>();
String ts = "";
if(i<10){
ts = "0"+i;
}else{
ts = ""+i;
}
//完整日期
m.put("rq", rq+"-"+ts);
//当前日
m.put("ts", ts);
m.put("ishave", "0");
sj.add(m);
}
//获取 人员-项目-日期 的施工日志
String hql = " from BuildDiary where xmid='"+xmid+"' "
+ " and userid='"+ryid+"' "
+ " and date_format(rzdate, '%Y-%m') = '"+rq+"' ";
List<BuildDiary> rzs = baseService.find(hql);
//将查出的结果填入对于的list,
for(BuildDiary rz:rzs){
Calendar cal = Calendar.getInstance();
cal.setTime(rz.getRzdate());
int t = cal.get(Calendar.DATE);
sj.get(t-1).put("ishave", "1");
sj.get(t-1).put("rzid", rz.getId());
}
r.setData(sj);
return r;
}
@RequestMapping("/save")
@ResponseBody
public Result save(HttpServletRequest request,BuildDiary rz ){
String rzid = rz.getId();
Result r = new Result();
Project xm = baseService.get(Project.class, rz.getXmid());
User u = baseService.get(User.class, rz.getUserid());
if(rzid==null){
rz.setXmmc(xm.getProjectName());
rz.setRymc(u.getName());
String i = (String)baseService.save(rz);
r.setCode(i);
}else{
BuildDiary lrz = baseService.get(BuildDiary.class, rzid);
lrz.setWeather(rz.getWeather());
lrz.setAirTemp(rz.getAirTemp());
lrz.setSgnr(rz.getSgnr());
lrz.setRemark(rz.getRemark());
lrz.setJobname(rz.getJobname());
baseService.update(lrz);
r.setCode(rzid);
}
return r;
}
@RequestMapping("/load")
@ResponseBody
public Result load(HttpServletRequest request){
String id = request.getParameter("id");
BuildDiary rz= baseService.get(BuildDiary.class, id);
Map<String,Object> map = new HashMap<String,Object>();
map.put("rz", rz);
Result r = new Result();
r.setSuccess(true);
r.setData(map);
return r;
}
@RequestMapping("/getRy")
@ResponseBody
public Result getRy(HttpServletRequest request){
Result r = new Result();
String xmid = request.getParameter("xmid");
String sql = "select a.id value, a.name data from tbl_user a where "
+ " (exists (select b.* from tbl_user_team b where a.id = b.user_id and b.project_id = '"+xmid+"')"
+ " or exists (select c.* from v_gckry c where a.id = c.id) )";
List tjxm = baseService.findMapBySql(sql, new Object[]{}, new Type[]{StringType.INSTANCE}, Options.class);
r.setData(tjxm);
return r;
}
}
| 31.939394 | 157 | 0.695446 |
7f62b5f6695e328765f317291a0159a4f471c224 | 7,059 | package SortedMap;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import SkipList.*;
/* Coverage is 97.8 %, if you only look at the Sorted Map package and all 19 tests pass.
*/
public class UnitTesting {
SortedMap MAP = new SortedMap();
SkipList sl = new SkipList();
@Before
public void setUp(){
MAP.resetSkipList();
sl = new SkipList();
}
@Test
public void removeNotExistingKey() {
Integer value = MAP.remove(5.0);
Integer expected = null;
assertEquals(value, expected);
}
@Test
public void removeAnExistingKey() {
Node inserted = MAP.useSkipList().insert(14.0, 2); // using the skip list's method, because it was already tested and I know it works 100 %
Integer value = MAP.remove(inserted.getKey());
Integer expected = 2;
assertEquals(value, expected);
}
@Test
public void putInAWholeEntry() {
Integer getNull = MAP.put(10.0, 5);
assertEquals(getNull, null);
}
@Test
public void usePutToReplaceAValue() {
Node inserted = MAP.useSkipList().insert(14.0, 2);
Integer changeValue = MAP.put(inserted.getKey(), 5);
Integer expected = 2; // return the old value
assertEquals(changeValue, expected);
}
@Test
public void checkSize() {
MAP.put(12, 6);
int size = MAP.size();
assertEquals(size, 1);
}
@Test
public void checkIsEmpty() {
boolean empty = MAP.isEmpty();
assertTrue(empty);
}
@Test
public void checkIsNotEmpty() {
MAP.put(12, 6);
boolean empty = MAP.isEmpty();
assertTrue(empty == false);
}
@Test
public void getExistingValue() {
MAP.put(12.0, 6);
Integer value = MAP.get(12.0);
Integer expected = 6;
assertEquals(value, expected);
}
@Test
public void getNotExistingValue() {
Integer shouldBeNull = MAP.get(20.0);
Integer expected = null;
assertEquals(shouldBeNull, expected);
}
@Test
public void testCollectionOfKeys() {
ArrayList<Double> expectedKeys = new ArrayList<>(5);
MAP.put(20.0, 5);
MAP.put(15.0, 4);
MAP.put(10.0, 3);
MAP.put(5.0, 2);
MAP.put(1.0, 1);
expectedKeys.add(1.0);
expectedKeys.add(5.0);
expectedKeys.add(10.0);
expectedKeys.add(15.0);
expectedKeys.add(20.0);
ArrayList<Double> keySet = MAP.keySet();
assertTrue(expectedKeys.toString().equals( keySet.toString() ));
}
@Test
public void testCollectionOfValues() {
ArrayList<Integer> expectedValues = new ArrayList<>(5);
MAP.put(20.0, 5);
MAP.put(15.0, 4);
MAP.put(10.0, 3);
MAP.put(5.0, 2);
MAP.put(1.0, 1);
expectedValues.add(MAP.get(1.0));
expectedValues.add(MAP.get(5.0));
expectedValues.add(MAP.get(10.0));
expectedValues.add(MAP.get(15.0));
expectedValues.add(MAP.get(20.0));
ArrayList<Integer> valueSet = MAP.values();
assertTrue(expectedValues.toString().equals( valueSet.toString() ));
}
@Test
public void testCollectionOfEntries() {
ArrayList<Node> expectedNodes = new ArrayList<>(5);
MAP.put(20.0, 5);
MAP.put(15.0, 4);
MAP.put(10.0, 3);
MAP.put(5.0, 2);
MAP.put(1.0, 1);
expectedNodes.add(MAP.useSkipList().skipSearch(1.0));
expectedNodes.add(MAP.useSkipList().skipSearch(5.0));
expectedNodes.add(MAP.useSkipList().skipSearch(10.0));
expectedNodes.add(MAP.useSkipList().skipSearch(15.0));
expectedNodes.add(MAP.useSkipList().skipSearch(20.0));
ArrayList<Node> nodes = MAP.entrySet();
assertTrue(expectedNodes.get(0).mainProperties().equals(nodes.get(0).mainProperties()));
assertTrue(expectedNodes.get(1).mainProperties().equals(nodes.get(1).mainProperties()));
assertTrue(expectedNodes.get(2).mainProperties().equals(nodes.get(2).mainProperties()));
assertTrue(expectedNodes.get(3).mainProperties().equals(nodes.get(3).mainProperties()));
assertTrue(expectedNodes.get(4).mainProperties().equals(nodes.get(4).mainProperties()));
}
@Test
public void getFirstEntry() {
Node firstExpected = MAP.useSkipList().insert(1.0, 1);
MAP.useSkipList().insert(5.0, 2);
MAP.useSkipList().insert(10.0, 3);
Node first = MAP.firstEntry();
assertTrue(firstExpected.compareNodes(first));
}
@Test
public void getLastEntry() {
MAP.useSkipList().insert(1.0, 1);
MAP.useSkipList().insert(5.0, 2);
Node lastExpected = MAP.useSkipList().insert(10.0, 3);
Node last = MAP.lastEntry();
assertTrue(lastExpected.compareNodes(last));
}
@Test
public void getCeilingEntry() {
MAP.useSkipList().insert(1.0, 1);
MAP.useSkipList().insert(5.0, 2);
Node expected = MAP.useSkipList().insert(10.0, 3);
MAP.useSkipList().insert(12.0, 9);
MAP.useSkipList().insert(15.0, 8);
Node ceilingEntry = MAP.ceilingEntry(9.0);
assertTrue(ceilingEntry.compareNodes(expected));
}
@Test
public void getFloorEntry() {
MAP.useSkipList().insert(1.0, 1);
Node expected = MAP.useSkipList().insert(5.0, 2);
MAP.useSkipList().insert(10.0, 3);
MAP.useSkipList().insert(12.0, 9);
MAP.useSkipList().insert(15.0, 8);
Node ceilingEntry = MAP.floorEntry(9.0);
assertTrue(ceilingEntry.compareNodes(expected));
}
@Test
public void getLowerEntry() {
MAP.useSkipList().insert(1.0, 1);
Node expected = MAP.useSkipList().insert(5.0, 2);
MAP.useSkipList().insert(10.0, 3);
MAP.useSkipList().insert(12.0, 9);
MAP.useSkipList().insert(15.0, 8);
Node ceilingEntry = MAP.lowerEntry(7.0);
assertTrue(ceilingEntry.compareNodes(expected));
}
@Test
public void getHigherEntry() {
MAP.useSkipList().insert(1.0, 1);
Node expected = MAP.useSkipList().insert(5.0, 2);
MAP.useSkipList().insert(10.0, 3);
MAP.useSkipList().insert(12.0, 9);
MAP.useSkipList().insert(15.0, 8);
Node ceilingEntry = MAP.higherEntry(2.0);
assertTrue(ceilingEntry.compareNodes(expected));
}
@Test
public void testSubMap() {
MAP.useSkipList().insert(1.0, 1);
MAP.useSkipList().insert(5.0, 2);
MAP.useSkipList().insert(10.0, 3);
MAP.useSkipList().insert(12.0, 9);
MAP.useSkipList().insert(14.0, 10);
MAP.useSkipList().insert(15.0, 8);
SortedMap subMap = MAP.subMap(5.0, 14.0); // nodes with key 5.0, 10.0 and 12.0
SkipList testSkipList = new SkipList();
testSkipList.insert(5.0, 2);
testSkipList.insert(10.0, 3);
testSkipList.insert(12.0, 9);
SortedMap expected = new SortedMap(testSkipList);
System.out.println("Expected: " + expected.entrySet().toString());
System.out.println("Submap: " + subMap.entrySet().toString());
// 3 nodes expected in the subMap: nodes with key 5.0, 10.0 and 12.0
assertTrue(expected.entrySet().get(0).mainProperties().equals(subMap.entrySet().get(0).mainProperties()));
assertTrue(expected.entrySet().get(1).mainProperties().equals(subMap.entrySet().get(1).mainProperties()));
assertTrue(expected.entrySet().get(2).mainProperties().equals(subMap.entrySet().get(2).mainProperties()));
}
}
| 27.466926 | 142 | 0.657742 |
c427f0e1f564276a07d9407b78d09831679eaa00 | 2,431 | package com.github.jvmgo.classfile.attributes;
import com.github.jvmgo.classfile.ClassReader;
import com.github.jvmgo.classfile.constantpool.ConstantPool;
/*
attribute_info {
u2 attribute_name_index;
u4 attribute_length;
u1 info[attribute_length];
}
*/
public interface AttributeInfo {
void readInfo(ClassReader reader);
static AttributeInfo[] readAttributes(ClassReader reader, ConstantPool cp) {
int attributesCount = reader.nextU2ToInt();
AttributeInfo[] attributes = new AttributeInfo[attributesCount];
for (int i = 0; i < attributesCount; i++) {
attributes[i] = readAttribute(reader, cp);
}
return attributes;
}
static AttributeInfo readAttribute(ClassReader reader, ConstantPool cp) {
int attrNameIndex = reader.nextU2ToInt();
String attrName = cp.getUTF8(attrNameIndex);
long attrLen = reader.nextU4ToInt();
AttributeInfo attributeInfo = newAttributeInfo(attrName, attrLen, cp);
attributeInfo.readInfo(reader);
return attributeInfo;
}
//todo 工厂方法xml配置?
static AttributeInfo newAttributeInfo(String attrName, long attrLen, ConstantPool cp) {
switch (attrName) {
//method属性
case "Code"://方法体
return new CodeAttribute(cp);
//field属性
case "ConstantValue"://常量表达式的值 存常量池索引
return new ConstantValueAttribute();
//method属性
case "Exceptions"://变长属性,记录方法抛出的异常表
return new ExceptionsAttribute();
//以下3是调试信息 不一定要 使用javac编译器编译Java程序时,默认会在class文件中生成 这些信息
// method属性的Code属性的属性
case "LineNumberTable"://方法行号
return new LineNumberTableAttribute();
// method属性的Code属性的属性
case "LocalVariableTable"://方法局部变量
return new LocalVariableTableAttribute();
//class属性
case "SourceFile"://源文件名 如 XXX.java
return new SourceFileAttribute(cp);
//最简单的两种属性,仅起标记作用,不包含任何数据。
//ClassFile、field_info和method_info都可以用
case "Synthetic"://为了支持嵌套类和嵌套接口
return new SyntheticAttribute();
case "Deprecated"://废弃标记
return new DeprecatedAttribute();
//不支持
default:
return new UnparsedAttribute(attrName, (int) attrLen);
}
}
}
| 33.763889 | 91 | 0.620732 |
87f89ce0f54dfd61f291689c9e6bc0f310cd69cb | 682 | package com.raven.example.dp.structural.proxy.ex2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class InvocationSubject implements InvocationHandler {
private Object target;
public InvocationSubject(Object target) {
this.target = target;
}
private void before() {
System.out.println("Proxy before");
}
private void after() {
System.out.println("Proxy after");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object invoke = method.invoke(target, args);
after();
return invoke;
}
}
| 22 | 87 | 0.658358 |
57a6e086102bc07ce5a3613417160596ba7958fe | 930 | package com.plugin.gateway.configs;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
final String expired = (String) httpServletRequest.getAttribute("Expired");
if(expired!=null){
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,expired);
}
else{
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Invalid login details");
}
}
}
| 40.434783 | 170 | 0.788172 |
2950a0d52f12b27bb043c795f8fea6f7940bc1ce | 44,722 | /*******************************************************************************
* Copyright (c) 2017 Microsoft Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Microsoft Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ls.core.internal.correction;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.junit.Before;
import org.junit.Test;
/**
* @author qisun
*
*/
public class ModifierCorrectionsQuickFixTest extends AbstractQuickFixTest {
private IJavaProject fJProject;
private IPackageFragmentRoot fSourceFolder;
private static final String proposal = "Remove invalid modifiers";
@Before
public void setup() throws Exception {
fJProject = newEmptyProject();
fJProject.setOptions(TestOptions.getDefaultOptions());
fSourceFolder = fJProject.getPackageFragmentRoot(fJProject.getProject().getFolder("src"));
}
@Test
public void testInvalidInterfaceModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public static interface E {\n");
buf.append(" public void foo();\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public void foo();\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidMemberInterfaceModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" private interface Inner {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" interface Inner {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidInterfaceFieldModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public native int i;\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public int i;\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidInterfaceMethodModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" private strictfp void foo();\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" void foo();\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidClassModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public volatile class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidMemberClassModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" private class Inner {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" class Inner {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidLocalClassModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" static class Local {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" class Local {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidClassFieldModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" strictfp public native int i;\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" public int i;\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidClassMethodModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public abstract class E {\n");
buf.append(" volatile abstract void foo();\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public abstract class E {\n");
buf.append(" abstract void foo();\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidConstructorModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public class Bug {\n");
buf.append(" public static Bug() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("Bug.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public class Bug {\n");
buf.append(" public Bug() {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidParamModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" private void foo(private int x) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" private void foo(int x) {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidVariableModifiers() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" native int x;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" int x;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidEnumModifier() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("private final strictfp enum E {\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("strictfp enum E {\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidEnumModifier2() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public abstract enum E {\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public enum E {\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidEnumConstructorModifier() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("enum E {\n");
buf.append(" WHITE(1);\n");
buf.append("\n");
buf.append(" public final E(int foo) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("enum E {\n");
buf.append(" WHITE(1);\n");
buf.append("\n");
buf.append(" E(int foo) {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidMemberEnumModifier() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("class E {\n");
buf.append(" final enum A {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("class E {\n");
buf.append(" enum A {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidArgumentModifier() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public void foo(static String a);\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public void foo(String a);\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidModifierCombinationFinalVolatileForField() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public final volatile String A;\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" public final String A;\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidStaticModifierForField() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" private static String A = \"Test\";\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" static String A = \"Test\";\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvalidStaticModifierForMethod() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" private static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public interface E {\n");
buf.append(" static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected(proposal, buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testOverrideStaticMethod() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("C.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'static' modifier of 'C.foo'(..)", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testOverrideFinalMethod() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" protected final void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" protected void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("C.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" protected void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" protected void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'final' modifier of 'C.foo'(..)", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleFieldRequestedInSamePackage1() throws Exception {
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("}\n");
buf.append("public class E {\n");
buf.append(" public void foo (C c) {\n");
buf.append(" c.test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" int test;\n");
buf.append("}\n");
buf.append("public class E {\n");
buf.append(" public void foo (C c) {\n");
buf.append(" c.test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'test' to 'package'", buf.toString());
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * @return the test\n");
buf.append(" */\n");
buf.append(" public int getTest() {\n");
buf.append(" return test;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * @param test the test to set\n");
buf.append(" */\n");
buf.append(" public void setTest(int test) {\n");
buf.append(" this.test = test;\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("public class E {\n");
buf.append(" public void foo (C c) {\n");
buf.append(" c.setTest(1);\n");
buf.append(" }\n");
buf.append("}\n");
Expected e2 = new Expected("Create getter and setter for 'test'", buf.toString());
assertCodeActions(cu, e1, e2);
}
@Test
public void testInvisibleFieldRequestedInSamePackage2() throws Exception {
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo () {\n");
buf.append(" test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" protected int test;\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo () {\n");
buf.append(" test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'test' to 'protected'", buf.toString());
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo () {\n");
buf.append(" int test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e2 = new Expected("Create local variable 'test'", buf.toString());
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" private int test;\n");
buf.append("\n");
buf.append(" public void foo () {\n");
buf.append(" test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e3 = new Expected("Create field 'test'", buf.toString());
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo (int test) {\n");
buf.append(" test = 1;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e4 = new Expected("Create parameter 'test'", buf.toString());
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo () {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e5 = new Expected("Remove assignment", buf.toString());
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class C {\n");
buf.append(" private int test;\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * @return the test\n");
buf.append(" */\n");
buf.append(" public int getTest() {\n");
buf.append(" return test;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * @param test the test to set\n");
buf.append(" */\n");
buf.append(" public void setTest(int test) {\n");
buf.append(" this.test = test;\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("public class E extends C {\n");
buf.append(" public void foo () {\n");
buf.append(" setTest(1);\n");
buf.append(" }\n");
buf.append("}\n");
Expected e6 = new Expected("Create getter and setter for 'test'", buf.toString());
assertCodeActions(cu, e1, e2, e3, e4, e5, e6);
}
@Test
public void testInvisibleMethodRequestedInOtherType() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" private void test() {}\n");
buf.append("}\n");
buf.append("class D {\n");
buf.append(" public void foo () {\n");
buf.append(" C c = new C();\n");
buf.append(" c.test();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("C.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" void test() {}\n");
buf.append("}\n");
buf.append("class D {\n");
buf.append(" public void foo () {\n");
buf.append(" C c = new C();\n");
buf.append(" c.test();\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'test()' to 'package'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleMethodRequestedInOtherPackage() throws Exception {
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" private void add() {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("C.java", buf.toString(), false, null);
IPackageFragment pack2 = fSourceFolder.createPackageFragment("test1", false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("import test.C;\n");
buf.append("public class E {\n");
buf.append(" public void foo (C c) {\n");
buf.append(" c.add();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack2.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" public void add() {\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'add()' to 'public'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleConstructorRequestedInOtherType() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" private C() {}\n");
buf.append("}\n");
buf.append("class D {\n");
buf.append(" public void foo () {\n");
buf.append(" C c = new C();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("C.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" C() {}\n");
buf.append("}\n");
buf.append("class D {\n");
buf.append(" public void foo () {\n");
buf.append(" C c = new C();\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'C()' to 'package'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleConstructorRequestedInInSuperType() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" private C() {}\n");
buf.append("}\n");
pack.createCompilationUnit("C.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("class D extends C{\n");
buf.append(" public D() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class C {\n");
buf.append(" protected C() {}\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'C()' to 'protected'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleTypeRequestedInOtherPackage() throws Exception {
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("class A {}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack2 = fSourceFolder.createPackageFragment("test2", false, null);
buf = new StringBuilder();
buf.append("package test2;\n");
buf.append("public class B {\n");
buf.append(" public void foo () {\n");
buf.append(" test1.A a = null;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack2.createCompilationUnit("B.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class A {}\n");
Expected e1 = new Expected("Change visibility of 'A' to 'public'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleTypeRequestedInGenericType() throws Exception {
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("class A<T> {}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack2 = fSourceFolder.createPackageFragment("test2", false, null);
buf = new StringBuilder();
buf.append("package test2;\n");
buf.append("public class B {\n");
buf.append(" public void foo () {\n");
buf.append(" test1.A<String> a = null;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack2.createCompilationUnit("B.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("public class A<T> {}\n");
Expected e1 = new Expected("Change visibility of 'A' to 'public'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testInvisibleTypeRequestedFromSuperClass() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class A {\n");
buf.append(" private class InnerA {}\n");
buf.append("}\n");
pack.createCompilationUnit("A.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class B extends A{\n");
buf.append(" public void foo () {\n");
buf.append(" InnerA a = null;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("B.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class A {\n");
buf.append(" class InnerA {}\n");
buf.append("}\n");
Expected e1 = new Expected("Change visibility of 'InnerA' to 'package'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testNonBlankFinalLocalAssignment() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" void foo() {\n");
buf.append(" final String s = \"\";\n");
buf.append(" if (false) {\n");
buf.append(" s = \"\";\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}");
ICompilationUnit cu = pack.createCompilationUnit("X.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" void foo() {\n");
buf.append(" String s = \"\";\n");
buf.append(" if (false) {\n");
buf.append(" s = \"\";\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}");
Expected e1 = new Expected("Remove 'final' modifier of 's'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testDuplicateFinalLocalInitialization() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" private int a;");
buf.append(" public X (int a) {\n");
buf.append(" this.a = a;\n");
buf.append(" }\n");
buf.append(" public int returnA () {\n");
buf.append(" return a;\n");
buf.append(" }\n");
buf.append(" public static boolean comparison (X x, int val) {\n");
buf.append(" return (x.returnA() == val);\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" final X abc;\n");
buf.append(" boolean comp = X.comparison((abc = new X(2)), (abc = new X(1)).returnA());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("X.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" private int a;");
buf.append(" public X (int a) {\n");
buf.append(" this.a = a;\n");
buf.append(" }\n");
buf.append(" public int returnA () {\n");
buf.append(" return a;\n");
buf.append(" }\n");
buf.append(" public static boolean comparison (X x, int val) {\n");
buf.append(" return (x.returnA() == val);\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" X abc;\n");
buf.append(" boolean comp = X.comparison((abc = new X(2)), (abc = new X(1)).returnA());\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'final' modifier of 'abc'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testFinalFieldAssignment() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" final int contents;\n");
buf.append(" \n");
buf.append(" X() {\n");
buf.append(" contents = 3;\n");
buf.append(" }\n");
buf.append(" X(X other) {\n");
buf.append(" other.contents = 5;\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public static void main(String[] args) {\n");
buf.append(" X one = new X();\n");
buf.append(" System.out.println(\"one.contents: \" + one.contents);\n");
buf.append(" X two = new X(one);\n");
buf.append(" System.out.println(\"one.contents: \" + one.contents);\n");
buf.append(" System.out.println(\"two.contents: \" + two.contents);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("X.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" int contents;\n");
buf.append(" \n");
buf.append(" X() {\n");
buf.append(" contents = 3;\n");
buf.append(" }\n");
buf.append(" X(X other) {\n");
buf.append(" other.contents = 5;\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public static void main(String[] args) {\n");
buf.append(" X one = new X();\n");
buf.append(" System.out.println(\"one.contents: \" + one.contents);\n");
buf.append(" X two = new X(one);\n");
buf.append(" System.out.println(\"one.contents: \" + one.contents);\n");
buf.append(" System.out.println(\"two.contents: \" + two.contents);\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'final' modifier of 'contents'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testDuplicateBlankFinalFieldInitialization() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" private int a;\n");
buf.append(" final int x;\n");
buf.append(" {\n");
buf.append(" x = new X(x = 2).returnA();");
buf.append(" }\n");
buf.append(" public X (int a) {\n");
buf.append(" this.a = a;\n");
buf.append(" }\n");
buf.append(" public int returnA () {\n");
buf.append(" return a;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("X.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("public class X {\n");
buf.append(" private int a;\n");
buf.append(" int x;\n");
buf.append(" {\n");
buf.append(" x = new X(x = 2).returnA();");
buf.append(" }\n");
buf.append(" public X (int a) {\n");
buf.append(" this.a = a;\n");
buf.append(" }\n");
buf.append(" public int returnA () {\n");
buf.append(" return a;\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'final' modifier of 'x'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testAnonymousClassCannotExtendFinalClass() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public final class X implements Serializable {\n");
buf.append(" class SMember extends String {} \n");
buf.append(" @Annot(value = new SMember())\n");
buf.append(" void bar() {}\n");
buf.append(" @Annot(value = \n");
buf.append(" new X(){\n");
buf.append(" ZorkAnonymous1 z;\n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork2 z;\n");
buf.append(" }\n");
buf.append(" })\n");
buf.append(" void foo() {}\n");
buf.append("}\n");
buf.append("@interface Annot {\n");
buf.append(" String value();\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("X.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public class X implements Serializable {\n");
buf.append(" class SMember extends String {} \n");
buf.append(" @Annot(value = new SMember())\n");
buf.append(" void bar() {}\n");
buf.append(" @Annot(value = \n");
buf.append(" new X(){\n");
buf.append(" ZorkAnonymous1 z;\n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork2 z;\n");
buf.append(" }\n");
buf.append(" })\n");
buf.append(" void foo() {}\n");
buf.append("}\n");
buf.append("@interface Annot {\n");
buf.append(" String value();\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'final' modifier of 'X'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testClassExtendFinalClass() throws Exception {
IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test;\n");
buf.append("import java.io.Serializable;\n");
buf.append("\n");
buf.append("public final class X implements Serializable {\n");
buf.append("\n");
buf.append(" void bar() {}\n");
buf.append("\n");
buf.append(" interface IM {}\n");
buf.append(" class SMember extends String {}\n");
buf.append("\n");
buf.append(" class Member extends X { \n");
buf.append(" ZorkMember z;\n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork1 z;\n");
buf.append(" } \n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo() {\n");
buf.append(" new X().new IM();\n");
buf.append(" class Local extends X { \n");
buf.append(" ZorkLocal z;\n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork3 z;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" new X() {\n");
buf.append(" ZorkAnonymous2 z; \n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork4 z;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu = pack.createCompilationUnit("X.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("import java.io.Serializable;\n");
buf.append("\n");
buf.append("public class X implements Serializable {\n");
buf.append("\n");
buf.append(" void bar() {}\n");
buf.append("\n");
buf.append(" interface IM {}\n");
buf.append(" class SMember extends String {}\n");
buf.append("\n");
buf.append(" class Member extends X { \n");
buf.append(" ZorkMember z;\n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork1 z;\n");
buf.append(" } \n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo() {\n");
buf.append(" new X().new IM();\n");
buf.append(" class Local extends X { \n");
buf.append(" ZorkLocal z;\n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork3 z;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" new X() {\n");
buf.append(" ZorkAnonymous2 z; \n");
buf.append(" void foo() {\n");
buf.append(" this.bar();\n");
buf.append(" Zork4 z;\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
Expected e1 = new Expected("Remove 'final' modifier of 'X'", buf.toString());
assertCodeActions(cu, e1);
}
@Test
public void testAddSealedMissingClassModifierProposal() throws Exception {
Map<String, String> options15 = new HashMap<>();
JavaModelUtil.setComplianceOptions(options15, JavaCore.VERSION_15);
options15.put(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, JavaCore.ENABLED);
options15.put(JavaCore.COMPILER_PB_REPORT_PREVIEW_FEATURES, JavaCore.IGNORE);
fJProject.setOptions(options15);
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test", false, null);
assertNoErrors(fJProject.getResource());
StringBuilder buf = new StringBuilder();
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public sealed class Shape permits Square {}\n");
buf.append("\n");
buf.append("class Square extends Shape {}\n");
ICompilationUnit cu = pack1.createCompilationUnit("Shape.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public sealed class Shape permits Square {}\n");
buf.append("\n");
buf.append("final class Square extends Shape {}\n");
Expected e1 = new Expected("Change 'Square' to 'final'", buf.toString());
assertCodeActions(cu, e1);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public sealed class Shape permits Square {}\n");
buf.append("\n");
buf.append("non-sealed class Square extends Shape {}\n");
Expected e2 = new Expected("Change 'Square' to 'non-sealed'", buf.toString());
assertCodeActions(cu, e2);
buf = new StringBuilder();
buf.append("package test;\n");
buf.append("\n");
buf.append("public sealed class Shape permits Square {}\n");
buf.append("\n");
buf.append("sealed class Square extends Shape {}\n");
Expected e3 = new Expected("Change 'Square' to 'sealed'", buf.toString());
assertCodeActions(cu, e3);
}
}
| 35.521843 | 95 | 0.620366 |
af81a63c89294313ae3aaadc048ad33a034e3c02 | 3,408 | package enigma.core.util;
import org.junit.jupiter.api.Test;
import static enigma.core.util.Letter.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* LetterTest
*
* @author diegodc 2017-02-05
*/
class LetterTest {
@Test
void shouldReturnTheNextLetterDownTheAlphabet() {
Letter[] letters = {A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z};
Letter[] expectedLetters = {B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, A};
for (int i = 0; i < 26; i++) {
Letter letter = letters[i];
Letter expectedLetter = expectedLetters[i];
assertEquals(expectedLetter, letter.nextLetter());
}
}
@Test
void shouldShiftLetterDownOrUpTheAlphabet() {
assertEquals(A, A.shiftBy(0));
assertEquals(B, A.shiftBy(1));
assertEquals(Z, A.shiftBy(-1));
assertEquals(A, A.shiftBy(26));
assertEquals(A, A.shiftBy(-26));
assertEquals(A, Z.shiftBy(1));
assertEquals(Y, Z.shiftBy(-1));
assertEquals(G, D.shiftBy(3));
assertEquals(U, N.shiftBy(7));
assertEquals(T, N.shiftBy(-20));
assertEquals(G, D.shiftBy(29));
assertEquals(G, D.shiftBy(55));
assertEquals(Z, D.shiftBy(-30));
assertEquals(Z, D.shiftBy(-56));
}
@Test
void testAllShiftPositionsDownTheAlphabet() {
Letter expectedLetter = A;
for (int i = 0; i < 26; i++) {
assertEquals(expectedLetter, A.shiftBy(i));
expectedLetter = expectedLetter.nextLetter();
}
}
@Test
void testAllShiftPositionsUpTheAlphabet() {
Letter expectedLetter = Z;
for (int i = -26; i < 1; i++) {
assertEquals(expectedLetter, Z.shiftBy(i));
expectedLetter = expectedLetter.nextLetter();
}
}
@Test
void shouldGetLetterFromChar() {
assertEquals(A, Letter.fromChar('A'));
assertEquals(A, Letter.fromChar('a'));
}
@Test
void invalidCharShouldThrowException() {
assertThrows(IllegalArgumentException.class, () -> Letter.fromChar('4'));
assertThrows(IllegalArgumentException.class, () -> Letter.fromChar('.'));
assertThrows(IllegalArgumentException.class, () -> Letter.fromChar('-'));
}
@Test
void shouldConvertLetterToChar() {
assertEquals('A', A.asChar());
assertEquals('J', J.asChar());
assertEquals('P', P.asChar());
assertEquals('Z', Z.asChar());
}
@Test
void testConversionFromCharToLetterWithAllChars() {
Letter[] letters = Letter.values();
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCaseChars = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < letters.length; i++) {
assertEquals(letters[i], Letter.fromChar(chars.charAt(i)));
assertEquals(letters[i], Letter.fromChar(lowerCaseChars.charAt(i)));
}
}
@Test
void testConversionFromLetterToCharWithAllLetters() {
String expectedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Letter letter = A;
for (int i = 0; i < 26; i++) {
assertEquals(expectedChars.charAt(i), letter.asChar());
letter = letter.nextLetter();
}
}
} | 28.881356 | 114 | 0.588908 |
f93f4c4c8621384df74f13f6f76391fd3fab91b7 | 1,347 | package com.github.coderoute.users;
import com.github.coderoute.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User create(User user) {
UserEntity userEntity = new UserEntity(user.getName());
userRepository.save(userEntity);
user.setUuid(userEntity.getUuid());
return user;
}
public User find(UUID userUuid) {
UserEntity userEntity = userRepository.findOne(userUuid);
if (userEntity == null) {
throw new ResourceNotFoundException("No such user: " + userUuid);
}
return convertToUserFacade(userEntity);
}
private User convertToUserFacade(UserEntity userEntity) {
User user = new User();
user.setName(userEntity.getName());
user.setUuid(userEntity.getUuid());
return user;
}
public List<User> findAll() {
return userRepository.findAll().stream().map(u -> convertToUserFacade(u)).collect(Collectors.toList());
}
public void delete(String userUuid) {
userRepository.delete(UUID.fromString(userUuid));
}
}
| 28.659574 | 111 | 0.689681 |
05e86f5256366f7ba259b5caee2d4136953b444a | 7,595 | package io.scribeapp.settings;
import java.util.ArrayList;
import io.scribeapp.R;
import io.scribeapp.input.Utils;
import io.scribeapp.classifier.gesture.GestureLibraryClassifier;
import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TrainGesturesActivity extends Activity implements OnClickListener {
private static final String TAG = "TrainGestures";
private static final float LENGTH_THRESHOLD = 5.0f;
private TextView characterLabel;
private Button nextButton;
private Button backButton;
private Button finishButton;
private int currentChar;
private GestureOverlayView gestureView;
private GestureLibrary small_library;
private GestureLibrary capital_library;
private GestureLibrary digit_library;
private Gesture currentGesture;
private String characters;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.train_gestures);
characters = "0123456789";
for (char c : Utils.LETTERS) {
characters += c;
characters += Character.toUpperCase(c);
}
characterLabel = (TextView) findViewById(R.id.characterLabel);
currentChar = 0;
characterLabel.setText(Character.toString(characters.charAt(currentChar)));
nextButton = (Button) findViewById(R.id.nextButton);
backButton = (Button) findViewById(R.id.backButton);
finishButton = (Button) findViewById(R.id.finishButton);
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
finishButton.setOnClickListener(this);
gestureView = (GestureOverlayView) findViewById(R.id.gestures_overlay);
gestureView.addOnGestureListener(new GesturesProcessor());
// getFileStreamPath(ALPHA_FILENAME).delete();
// getFileStreamPath(NUMBER_FILENAME).delete();
small_library = GestureLibraries.fromFile(getFileStreamPath(GestureLibraryClassifier.USER_SMALL_FILENAME));
small_library.load();
capital_library = GestureLibraries.fromFile(getFileStreamPath(GestureLibraryClassifier.USER_CAPITAL_FILENAME));
capital_library.load();
digit_library = GestureLibraries.fromFile(getFileStreamPath(GestureLibraryClassifier.USER_DIGIT_FILENAME));
digit_library.load();
currentGesture = loadGesture(characters.charAt(currentChar));
if (currentGesture != null) {
gestureView.post(new Runnable() {
public void run() {
gestureView.setGesture(currentGesture);
}
});
}
Log.d(TAG, "Number of gestures in small_lib " + small_library.getGestureEntries().size());
Log.d(TAG, "Number of gestures in capital_lib " + capital_library.getGestureEntries().size());
Log.d(TAG, "Number of gestures in digit_lib " + digit_library.getGestureEntries().size());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (currentGesture != null) {
outState.putParcelable("gesture", currentGesture);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentGesture = savedInstanceState.getParcelable("gesture");
if (currentGesture != null) {
gestureView.post(new Runnable() {
public void run() {
gestureView.setGesture(currentGesture);
}
});
handleEnabled(nextButton);
handleEnabled(backButton);
}
}
public void onClick(View v) {
if (v.getId() == R.id.nextButton) {
if (currentGesture != null) {
saveGesture();
gestureView.clear(false);
currentChar++;
if (currentChar >= characters.length()) currentChar = characters.length() - 1;
characterLabel.setText(Character.toString(characters.charAt(currentChar)));
Gesture nextGesture = loadGesture(characters.charAt(currentChar));
if (nextGesture != null) {
gestureView.setGesture(nextGesture);
currentGesture = nextGesture;
}
else {
currentGesture = null;
}
}
else {
Toast.makeText(this, getResources().getString(R.string.no_gesture_alert), Toast.LENGTH_LONG).show();
}
}
if (v.getId() == R.id.backButton) {
if (currentGesture != null) {
saveGesture();
}
currentChar--;
if (currentChar < 0) currentChar = 0;
characterLabel.setText(Character.toString(characters.charAt(currentChar)));
currentGesture = null;
Gesture prevGesture = loadGesture(characters.charAt(currentChar));
if (prevGesture != null) {
gestureView.setGesture(prevGesture);
currentGesture = prevGesture;
}
else {
currentGesture = null;
}
}
if (v.getId() == R.id.finishButton) {
if (currentGesture != null) {
saveGesture();
finish();
}
else {
Toast.makeText(this, getResources().getString(R.string.no_gesture_alert), Toast.LENGTH_LONG).show();
}
}
handleEnabled(nextButton);
handleEnabled(backButton);
}
private Gesture loadGesture(Character label) {
GestureLibrary current_library = null;
if (Character.isDigit(label)) {
current_library = digit_library;
}
else if (Character.isUpperCase(label)) {
current_library = capital_library;
}
else if (Character.isLowerCase(label)) {
current_library = small_library;
}
else return null;
ArrayList<Gesture> result = current_library.getGestures(Character.toString(characters.charAt(currentChar)));
if (result == null || result.isEmpty()) return null;
else return result.get(0);
}
private void saveGesture() {
Character label = characters.charAt(currentChar);
Gesture lastGesture = loadGesture(label);
GestureLibrary current_library = null;
if (Character.isDigit(label)) {
current_library = digit_library;
}
else if (Character.isUpperCase(label)) {
current_library = capital_library;
}
else if (Character.isLowerCase(label)) {
current_library = small_library;
}
else return;
if (lastGesture != null) {
current_library.removeGesture(Character.toString(label), lastGesture);
}
current_library.addGesture(Character.toString(characters.charAt(currentChar)), currentGesture);
current_library.save();
}
private void handleEnabled(Button b) {
if (b == nextButton) {
if (currentChar == characters.length() - 1) {
nextButton.setEnabled(false);
nextButton.setVisibility(View.GONE);
finishButton.setVisibility(View.VISIBLE);
}
else {
nextButton.setEnabled(true);
nextButton.setVisibility(View.VISIBLE);
finishButton.setVisibility(View.GONE);
}
}
else if (b == backButton) {
if (currentChar == 0) {
backButton.setEnabled(false);
}
else {
backButton.setEnabled(true);
}
}
}
private class GesturesProcessor implements GestureOverlayView.OnGestureListener {
public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
nextButton.setEnabled(false);
backButton.setEnabled(false);
currentGesture = null;
}
public void onGesture(GestureOverlayView overlay, MotionEvent event) {}
public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
currentGesture = overlay.getGesture();
if (currentGesture.getLength() < LENGTH_THRESHOLD) {
overlay.clear(false);
}
handleEnabled(nextButton);
handleEnabled(backButton);
}
public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {}
}
}
| 29.324324 | 113 | 0.741409 |
5b96ec4c4c5048a2f2340c73ca2b38891627dd68 | 1,904 | package org.colorcoding.tools.btulz.transformer;
import java.io.File;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.colorcoding.tools.btulz.Environment;
import org.colorcoding.tools.btulz.transformer.region.RegionDomain;
/**
* 分析jar包中的sql,并在数据库中执行
*
* @author Niuren.Zhu
*
*/
public class SqlTransformer4Jar extends SqlTransformer {
@Override
public void transform() throws Exception {
File file = new File(this.getSqlFile());
if (!file.isFile() || !file.exists()) {
return;
}
if (file.getName().toLowerCase().endsWith(".jar")) {
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> jarEntries = jarFile.entries();
if (jarEntries != null) {
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
if (jarEntry.isDirectory()) {
continue;
}
String name = jarEntry.getName().toLowerCase();
if (name.startsWith("datastructures/sql_") && name.endsWith(".xml")) {
if (this.getSqlFilter() != null) {
if (name.indexOf(this.getSqlFilter()) < 0) {
continue;
}
}
try {
Environment.getLogger().info(String.format("parsing jar entry [%s]. ", name));
InputStream inputStream = jarFile.getInputStream(jarEntry);
RegionDomain template = new RegionDomain();
template.setEncoding("utf-8");
template.parse(inputStream);
File outputFile = new File(this.getOutputFile(name.replace("datastructures/sql_", "sql_")));
template.export(this.getRuntimeParameters(), outputFile);
this.execute(outputFile);
} catch (Exception e) {
Environment.getLogger().error(e);
}
}
}
}
jarFile.close();
} else {
// 普通文件
super.transform();
}
}
}
| 29.75 | 100 | 0.638655 |
210342b8a60f47296da61977ffa7ec288c2edc56 | 6,560 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.loganalytics.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
/** A management group that is connected to a workspace. */
@JsonFlatten
@Fluent
public class ManagementGroupInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ManagementGroupInner.class);
/*
* The number of servers connected to the management group.
*/
@JsonProperty(value = "properties.serverCount")
private Integer serverCount;
/*
* Gets or sets a value indicating whether the management group is a
* gateway.
*/
@JsonProperty(value = "properties.isGateway")
private Boolean isGateway;
/*
* The name of the management group.
*/
@JsonProperty(value = "properties.name")
private String name;
/*
* The unique ID of the management group.
*/
@JsonProperty(value = "properties.id")
private String id;
/*
* The datetime that the management group was created.
*/
@JsonProperty(value = "properties.created")
private OffsetDateTime created;
/*
* The last datetime that the management group received data.
*/
@JsonProperty(value = "properties.dataReceived")
private OffsetDateTime dataReceived;
/*
* The version of System Center that is managing the management group.
*/
@JsonProperty(value = "properties.version")
private String version;
/*
* The SKU of System Center that is managing the management group.
*/
@JsonProperty(value = "properties.sku")
private String sku;
/**
* Get the serverCount property: The number of servers connected to the management group.
*
* @return the serverCount value.
*/
public Integer serverCount() {
return this.serverCount;
}
/**
* Set the serverCount property: The number of servers connected to the management group.
*
* @param serverCount the serverCount value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withServerCount(Integer serverCount) {
this.serverCount = serverCount;
return this;
}
/**
* Get the isGateway property: Gets or sets a value indicating whether the management group is a gateway.
*
* @return the isGateway value.
*/
public Boolean isGateway() {
return this.isGateway;
}
/**
* Set the isGateway property: Gets or sets a value indicating whether the management group is a gateway.
*
* @param isGateway the isGateway value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withIsGateway(Boolean isGateway) {
this.isGateway = isGateway;
return this;
}
/**
* Get the name property: The name of the management group.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Set the name property: The name of the management group.
*
* @param name the name value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withName(String name) {
this.name = name;
return this;
}
/**
* Get the id property: The unique ID of the management group.
*
* @return the id value.
*/
public String id() {
return this.id;
}
/**
* Set the id property: The unique ID of the management group.
*
* @param id the id value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withId(String id) {
this.id = id;
return this;
}
/**
* Get the created property: The datetime that the management group was created.
*
* @return the created value.
*/
public OffsetDateTime created() {
return this.created;
}
/**
* Set the created property: The datetime that the management group was created.
*
* @param created the created value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withCreated(OffsetDateTime created) {
this.created = created;
return this;
}
/**
* Get the dataReceived property: The last datetime that the management group received data.
*
* @return the dataReceived value.
*/
public OffsetDateTime dataReceived() {
return this.dataReceived;
}
/**
* Set the dataReceived property: The last datetime that the management group received data.
*
* @param dataReceived the dataReceived value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withDataReceived(OffsetDateTime dataReceived) {
this.dataReceived = dataReceived;
return this;
}
/**
* Get the version property: The version of System Center that is managing the management group.
*
* @return the version value.
*/
public String version() {
return this.version;
}
/**
* Set the version property: The version of System Center that is managing the management group.
*
* @param version the version value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withVersion(String version) {
this.version = version;
return this;
}
/**
* Get the sku property: The SKU of System Center that is managing the management group.
*
* @return the sku value.
*/
public String sku() {
return this.sku;
}
/**
* Set the sku property: The SKU of System Center that is managing the management group.
*
* @param sku the sku value to set.
* @return the ManagementGroupInner object itself.
*/
public ManagementGroupInner withSku(String sku) {
this.sku = sku;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 27.679325 | 109 | 0.647256 |
18ae7a8a982f054d92ee7917fc8d9c73067e0b73 | 2,601 | // Template Source: BaseMethodCollectionPage.java.tt
// ------------------------------------------------------------------------------
// 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.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.RetireScheduledManagedDevice;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.requests.DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionRequestBuilder;
import com.microsoft.graph.requests.DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionPage;
import com.microsoft.graph.requests.DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionResponse;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Device Compliance Policy Get Devices Scheduled To Retire Collection Page.
*/
public class DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionPage extends BaseCollectionPage<RetireScheduledManagedDevice, DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionRequestBuilder> {
/**
* A collection page for RetireScheduledManagedDevice.
*
* @param response The serialized DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionResponse from the service
* @param builder The request builder for the next collection page
*/
public DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionPage(@Nonnull final DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionResponse response, @Nonnull final DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionRequestBuilder builder) {
super(response, builder);
}
/**
* Creates the collection page for DeviceCompliancePolicyGetDevicesScheduledToRetire
*
* @param pageContents the contents of this page
* @param nextRequestBuilder the request builder for the next page
*/
public DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionPage(@Nonnull final java.util.List<RetireScheduledManagedDevice> pageContents, @Nullable final DeviceCompliancePolicyGetDevicesScheduledToRetireCollectionRequestBuilder nextRequestBuilder) {
super(pageContents, nextRequestBuilder);
}
}
| 54.1875 | 267 | 0.7797 |
5e6f905dbe6887774ad34a95a578d3531e54d06d | 2,807 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import java.util.Iterator;
import java.util.function.Consumer;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class SplitIteratorNullTest extends ContextTestSupport {
private MyIterator myIterator = new MyIterator();
@Test
public void testSplitIteratorNull() throws Exception {
assertFalse(myIterator.isNullReturned());
getMockEndpoint("mock:line").expectedBodiesReceived("A", "B", "C");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
assertTrue(myIterator.isNullReturned());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.split(constant(myIterator))
.to("mock:line");
}
};
}
private class MyIterator implements Iterator<String> {
private int count = 4;
private boolean nullReturned;
@Override
public boolean hasNext() {
// we return true one extra time, and cause next to return null
return count > 0;
}
@Override
public String next() {
count--;
if (count == 0) {
nullReturned = true;
return null;
} else if (count == 1) {
return "C";
} else if (count == 2) {
return "B";
} else {
return "A";
}
}
public boolean isNullReturned() {
return nullReturned;
}
@Override
public void remove() {
// noop
}
@Override
public void forEachRemaining(Consumer<? super String> action) {
// noop
}
}
}
| 29.861702 | 75 | 0.609191 |
24a5a87da8a4c8a1da9bc4207f022d1e425fbffc | 2,145 | package data7.model.vulnerability;
/*-
* #%L
* Data7
* %%
* Copyright (C) 2018 University of Luxembourg, Matthieu Jimenez
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import data7.project.Project;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Vulnerability Dataset class
*/
public class VulnerabilitySet implements Serializable {
private static final long serialVersionUID = 20180531L;
private final Map<String, Vulnerability> vulnerabilityDataset;
private long lastUpdated;
private final String projectName;
/**
* Constructor
*
* @param projectName name of the project can be obtain through
* @see Project#getName()
* the last update correspond to the current time
*/
public VulnerabilitySet(String projectName) {
this.projectName = projectName;
this.vulnerabilityDataset = new HashMap<>();
this.lastUpdated = System.currentTimeMillis();
}
/**
* @return
*/
public Map<String, Vulnerability> getVulnerabilityDataset() {
return vulnerabilityDataset;
}
/**
* @return the timestamp of the last modification of the dataset
*/
public long getLastUpdated() {
return lastUpdated;
}
/**
* update the dataset last modification timestamp to the current time
*/
public void setLastUpdated(long updateTime) {
this.lastUpdated = updateTime;
}
/**
* @return the name of the project the dataset was built around
*/
public String getProjectName() {
return projectName;
}
}
| 25.843373 | 75 | 0.67972 |
7fc9ca8012c427067fb3ef34e9acbacbe4d5342c | 2,068 | package ssm;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Objects;
public class Parameter {
private final String name;
private final Environment environment;
private String value;
public Parameter(String name, Environment environment) {
this.name = name;
this.environment = environment;
}
public Parameter(String name, Environment environment, String value) {
this.name = name;
this.environment = environment;
this.value = value;
}
public String getName() {
return name;
}
public Environment getEnvironment() {
return environment;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
/**
* Two Parameter are considered to be equal if they have the same name and same environment.
*
* @param object The object to compare this {@code Parameter} against.
* @return True if the given object represents a Parameter equivalent to this Parameter, false otherwise.
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Parameter)) {
return false;
}
Parameter parameter = (Parameter) object;
if (hashCode() != parameter.hashCode()) {
return false;
}
return name.equals(parameter.getName()) && environment.equals(parameter.getEnvironment());
}
/**
* Returns the hash code value for the object. This method is supported for the benefit of hash data structures
* such as those provided by {@link HashMap}.
*
* @return The hash code value for the object.
*/
@Override
public int hashCode() {
int hash = 17;
hash = 157 * hash + Objects.hash(name, environment);
return hash;
}
@Override
public String toString() {
Gson gson = new Gson();
return gson.toJson(this);
}
}
| 25.85 | 115 | 0.612669 |
710351b08604244e85cd4451e998fc6d608b5431 | 607 | package com.google.android.play.core.internal;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
/* renamed from: com.google.android.play.core.internal.ca */
public abstract class C1967ca implements Closeable {
/* renamed from: a */
public abstract long mo33992a();
/* access modifiers changed from: protected */
/* renamed from: a */
public abstract InputStream mo33993a(long j, long j2) throws IOException;
/* renamed from: b */
public synchronized InputStream mo34189b() throws IOException {
return mo33993a(0, mo33992a());
}
}
| 28.904762 | 77 | 0.710049 |
724aebf1fd8b2a393e57984e334c76eaf43d7293 | 3,280 | package com.btaz.util.files;
import com.btaz.util.mr.MapReduceException;
import com.btaz.util.mr.Mapper;
import com.btaz.util.mr.OutputCollector;
import com.btaz.util.unit.ResourceUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
/**
* User: msundell
*/
public class FileMapperTest {
private FileTracker tracker;
@Before
public void setUp() throws Exception {
tracker = new FileTracker();
}
@After
public void tearDown() throws Exception {
tracker.deleteAll();
}
@Test
public void testOfMappingInputFileShouldMapFile() throws Exception {
// given
File testDir = tracker.createDir(new File("target/test-dir"));
File inputFile = tracker.getTestResource("test-3.txt");
Mapper mapper = new FruitMapper("Lime");
// when
List<File> mappedFiles = FileMapper.map(testDir, inputFile, mapper, null);
tracker.add(mappedFiles);
// then
assertThat(mappedFiles, is(not(nullValue())));
assertThat(mappedFiles.size(), is(equalTo(1)));
String mappedData = ResourceUtil.readFromFileIntoString(mappedFiles.get(0));
assertThat(countOccurrences(mappedData, "lime"), is(equalTo(4)));
}
/**
* Helper method that tests to see how many times a string occur in an input string. All matches ignore case.
* @param input input string
* @param substring substring
* @return int count
*/
private int countOccurrences(String input, String substring) {
int count = 0;
int index = 0;
input = input.toLowerCase();
substring = substring.toLowerCase();
while(true) {
index = input.indexOf(substring, index);
if(index == -1) {
break;
}
count += 1;
index += substring.length();
}
return count;
}
/**
* Map input data to fruit and Id. In this case we only about a specific fruit.
* Map(,[fruit,id,description]) ==> list(fruit,id)
*/
public static class FruitMapper implements Mapper {
private String fruit;
private FruitMapper(String fruit) {
this.fruit = fruit;
}
@Override
public void map(String value, OutputCollector collector) {
if(value == null || value.trim().length() == 0) {
// skip empty rows
return;
}
String [] fields = value.split("\t");
if(fields.length != 3) {
throw new MapReduceException("Invalid field count, expected 3 but found: " + fields.length);
} else if("ID".equalsIgnoreCase(fields[0])) {
// skip header row
} else if(fruit.equalsIgnoreCase(fields[1])) {
// found a matching fruit KEY(fruit,ID)
collector.write(fields[1].toLowerCase() + "\t" + fields[0]);
}
// non-matching fruit
}
}
}
| 30.37037 | 113 | 0.604573 |
80b63b3e652b36af858e9cacf6a3d0d92686bdb8 | 1,002 | package com.javayh.common.exception;
import com.javayh.common.constants.ResponseCode;
import com.javayh.common.constants.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @ClassName javayh-rabbitmq → com.javayh.exception → ControllerAdvice
* @Description
* @Author Dylan
* @Date 2019/9/12 17:38
* @Version
*/
@Slf4j
@ControllerAdvice
public class MyControllerAdvice {
@ResponseBody
@ExceptionHandler(ServiceException.class)
public ServerResponse serviceExceptionHandler(ServiceException se) {
return ServerResponse.error(se.getMsg());
}
@ResponseBody
@ExceptionHandler(Exception.class)
public ServerResponse exceptionHandler(Exception e) {
log.error("Exception: ", e);
return ServerResponse.error(ResponseCode.SERVER_ERROR.getMsg());
}
}
| 28.628571 | 72 | 0.765469 |
383014392040d9b8c5d70ef90cc7d27338735003 | 16,984 | /*
* Copyright 2022 Red Hat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apicurio.registry.utils.protobuf.schema;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Descriptors;
import com.google.protobuf.DynamicMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class DynamicSchema {
// --- public static ---
/**
* Creates a new dynamic schema builder
*
* @return the schema builder
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* Parses a serialized schema descriptor (from input stream; closes the stream)
*
* @param schemaDescIn the descriptor input stream
* @return the schema object
*/
public static DynamicSchema parseFrom(InputStream schemaDescIn)
throws Descriptors.DescriptorValidationException, IOException {
try {
int len;
byte[] buf = new byte[4096];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = schemaDescIn.read(buf)) > 0) {
baos.write(buf, 0, len);
}
return parseFrom(baos.toByteArray());
} finally {
schemaDescIn.close();
}
}
/**
* Parses a serialized schema descriptor (from byte array)
*
* @param schemaDescBuf the descriptor byte array
* @return the schema object
*/
public static DynamicSchema parseFrom(byte[] schemaDescBuf)
throws Descriptors.DescriptorValidationException, IOException {
return new DynamicSchema(DescriptorProtos.FileDescriptorSet.parseFrom(schemaDescBuf));
}
// --- public ---
/**
* Gets the protobuf file descriptor proto
*
* @return the file descriptor proto
*/
public DescriptorProtos.FileDescriptorProto getFileDescriptorProto() {
return mFileDescSet.getFile(0);
}
/**
* Creates a new dynamic message builder for the given message type
*
* @param msgTypeName the message type name
* @return the message builder (null if not found)
*/
public DynamicMessage.Builder newMessageBuilder(String msgTypeName) {
Descriptors.Descriptor msgType = getMessageDescriptor(msgTypeName);
if (msgType == null) {
return null;
}
return DynamicMessage.newBuilder(msgType);
}
/**
* Gets the protobuf message descriptor for the given message type
*
* @param msgTypeName the message type name
* @return the message descriptor (null if not found)
*/
public Descriptors.Descriptor getMessageDescriptor(String msgTypeName) {
Descriptors.Descriptor msgType = mMsgDescriptorMapShort.get(msgTypeName);
if (msgType == null) {
msgType = mMsgDescriptorMapFull.get(msgTypeName);
}
return msgType;
}
/**
* Gets the enum value for the given enum type and name
*
* @param enumTypeName the enum type name
* @param enumName the enum name
* @return the enum value descriptor (null if not found)
*/
public Descriptors.EnumValueDescriptor getEnumValue(String enumTypeName, String enumName) {
Descriptors.EnumDescriptor enumType = getEnumDescriptor(enumTypeName);
if (enumType == null) {
return null;
}
return enumType.findValueByName(enumName);
}
/**
* Gets the enum value for the given enum type and number
*
* @param enumTypeName the enum type name
* @param enumNumber the enum number
* @return the enum value descriptor (null if not found)
*/
public Descriptors.EnumValueDescriptor getEnumValue(String enumTypeName, int enumNumber) {
Descriptors.EnumDescriptor enumType = getEnumDescriptor(enumTypeName);
if (enumType == null) {
return null;
}
return enumType.findValueByNumber(enumNumber);
}
/**
* Gets the protobuf enum descriptor for the given enum type
*
* @param enumTypeName the enum type name
* @return the enum descriptor (null if not found)
*/
public Descriptors.EnumDescriptor getEnumDescriptor(String enumTypeName) {
Descriptors.EnumDescriptor enumType = mEnumDescriptorMapShort.get(enumTypeName);
if (enumType == null) {
enumType = mEnumDescriptorMapFull.get(enumTypeName);
}
return enumType;
}
/**
* Returns the message types registered with the schema
*
* @return the set of message type names
*/
public Set<String> getMessageTypes() {
return new TreeSet<String>(mMsgDescriptorMapFull.keySet());
}
/**
* Returns the enum types registered with the schema
*
* @return the set of enum type names
*/
public Set<String> getEnumTypes() {
return new TreeSet<String>(mEnumDescriptorMapFull.keySet());
}
/**
* Serializes the schema
*
* @return the serialized schema descriptor
*/
public byte[] toByteArray() {
return mFileDescSet.toByteArray();
}
/**
* Returns a string representation of the schema
*
* @return the schema string
*/
public String toString() {
Set<String> msgTypes = getMessageTypes();
Set<String> enumTypes = getEnumTypes();
return "types: " + msgTypes + "\nenums: " + enumTypes + "\n" + mFileDescSet;
}
// --- private ---
private DynamicSchema(DescriptorProtos.FileDescriptorSet fileDescSet) throws Descriptors.DescriptorValidationException {
mFileDescSet = fileDescSet;
Map<String, Descriptors.FileDescriptor> fileDescMap = init(fileDescSet);
Set<String> msgDupes = new HashSet<String>();
Set<String> enumDupes = new HashSet<String>();
for (Descriptors.FileDescriptor fileDesc : fileDescMap.values()) {
for (Descriptors.Descriptor msgType : fileDesc.getMessageTypes()) {
addMessageType(msgType, null, msgDupes, enumDupes);
}
for (Descriptors.EnumDescriptor enumType : fileDesc.getEnumTypes()) {
addEnumType(enumType, null, enumDupes);
}
}
for (String msgName : msgDupes) {
mMsgDescriptorMapShort.remove(msgName);
}
for (String enumName : enumDupes) {
mEnumDescriptorMapShort.remove(enumName);
}
}
@SuppressWarnings("unchecked")
private Map<String, Descriptors.FileDescriptor> init(DescriptorProtos.FileDescriptorSet fileDescSet)
throws Descriptors.DescriptorValidationException {
// check for dupes
Set<String> allFdProtoNames = new HashSet<String>();
for (DescriptorProtos.FileDescriptorProto fdProto : fileDescSet.getFileList()) {
if (allFdProtoNames.contains(fdProto.getName())) {
throw new IllegalArgumentException("duplicate name: " + fdProto.getName());
}
allFdProtoNames.add(fdProto.getName());
}
// build FileDescriptors, resolve dependencies (imports) if any
Map<String, Descriptors.FileDescriptor> resolvedFileDescMap = new HashMap<String, Descriptors.FileDescriptor>();
while (resolvedFileDescMap.size() < fileDescSet.getFileCount()) {
for (DescriptorProtos.FileDescriptorProto fdProto : fileDescSet.getFileList()) {
if (resolvedFileDescMap.containsKey(fdProto.getName())) {
continue;
}
// getDependencyList() signature was changed and broke compatibility in 2.6.1; workaround
// with reflection
//List<String> dependencyList = fdProto.getDependencyList();
List<String> dependencyList = null;
try {
Method m = fdProto.getClass().getMethod("getDependencyList", (Class<?>[]) null);
dependencyList = (List<String>) m.invoke(fdProto, (Object[]) null);
} catch (Exception e) {
throw new RuntimeException(e);
}
List<Descriptors.FileDescriptor> resolvedFdList = new ArrayList<Descriptors.FileDescriptor>();
for (String depName : dependencyList) {
if (!allFdProtoNames.contains(depName)) {
throw new IllegalArgumentException("cannot resolve import " + depName + " in " + fdProto
.getName());
}
Descriptors.FileDescriptor fd = resolvedFileDescMap.get(depName);
if (fd != null) {
resolvedFdList.add(fd);
}
}
if (resolvedFdList.size() == dependencyList.size()) { // dependencies resolved
Descriptors.FileDescriptor[] fds = new Descriptors.FileDescriptor[resolvedFdList.size()];
Descriptors.FileDescriptor fd = Descriptors.FileDescriptor.buildFrom(fdProto, resolvedFdList.toArray(fds));
resolvedFileDescMap.put(fdProto.getName(), fd);
}
}
}
return resolvedFileDescMap;
}
private void addMessageType(
Descriptors.Descriptor msgType,
String scope,
Set<String> msgDupes,
Set<String> enumDupes
) {
String msgTypeNameFull = msgType.getFullName();
String msgTypeNameShort = (scope == null ? msgType.getName() : scope + "." + msgType.getName());
if (mMsgDescriptorMapFull.containsKey(msgTypeNameFull)) {
throw new IllegalArgumentException("duplicate name: " + msgTypeNameFull);
}
if (mMsgDescriptorMapShort.containsKey(msgTypeNameShort)) {
msgDupes.add(msgTypeNameShort);
}
mMsgDescriptorMapFull.put(msgTypeNameFull, msgType);
mMsgDescriptorMapShort.put(msgTypeNameShort, msgType);
for (Descriptors.Descriptor nestedType : msgType.getNestedTypes()) {
addMessageType(nestedType, msgTypeNameShort, msgDupes, enumDupes);
}
for (Descriptors.EnumDescriptor enumType : msgType.getEnumTypes()) {
addEnumType(enumType, msgTypeNameShort, enumDupes);
}
}
private void addEnumType(Descriptors.EnumDescriptor enumType, String scope, Set<String> enumDupes) {
String enumTypeNameFull = enumType.getFullName();
String enumTypeNameShort = (
scope == null
? enumType.getName()
: scope + "." + enumType.getName());
if (mEnumDescriptorMapFull.containsKey(enumTypeNameFull)) {
throw new IllegalArgumentException("duplicate name: " + enumTypeNameFull);
}
if (mEnumDescriptorMapShort.containsKey(enumTypeNameShort)) {
enumDupes.add(enumTypeNameShort);
}
mEnumDescriptorMapFull.put(enumTypeNameFull, enumType);
mEnumDescriptorMapShort.put(enumTypeNameShort, enumType);
}
private DescriptorProtos.FileDescriptorSet mFileDescSet;
private Map<String, Descriptors.Descriptor> mMsgDescriptorMapFull = new HashMap<String, Descriptors.Descriptor>();
private Map<String, Descriptors.Descriptor> mMsgDescriptorMapShort = new HashMap<String, Descriptors.Descriptor>();
private Map<String, Descriptors.EnumDescriptor> mEnumDescriptorMapFull = new HashMap<String,
Descriptors.EnumDescriptor>();
private Map<String, Descriptors.EnumDescriptor> mEnumDescriptorMapShort = new HashMap<String,
Descriptors.EnumDescriptor>();
/**
* DynamicSchema.Builder
*/
public static class Builder {
// --- public ---
/**
* Builds a dynamic schema
*
* @return the schema object
*/
public DynamicSchema build() throws Descriptors.DescriptorValidationException {
DescriptorProtos.FileDescriptorSet.Builder fileDescSetBuilder = DescriptorProtos.FileDescriptorSet.newBuilder();
fileDescSetBuilder.addFile(mFileDescProtoBuilder.build());
fileDescSetBuilder.mergeFrom(mFileDescSetBuilder.build());
return new DynamicSchema(fileDescSetBuilder.build());
}
public Builder setSyntax(String syntax) {
mFileDescProtoBuilder.setSyntax(syntax);
return this;
}
public Builder setName(String name) {
mFileDescProtoBuilder.setName(name);
return this;
}
public Builder setPackage(String name) {
mFileDescProtoBuilder.setPackage(name);
return this;
}
public Builder addMessageDefinition(MessageDefinition msgDef) {
mFileDescProtoBuilder.addMessageType(msgDef.getMessageType());
return this;
}
public Builder addEnumDefinition(EnumDefinition enumDef) {
mFileDescProtoBuilder.addEnumType(enumDef.getEnumType());
return this;
}
// Note: added
public Builder addDependency(String dependency) {
mFileDescProtoBuilder.addDependency(dependency);
return this;
}
// Note: added
public Builder addPublicDependency(String dependency) {
for (int i = 0; i < mFileDescProtoBuilder.getDependencyCount(); i++) {
if (mFileDescProtoBuilder.getDependency(i).equals(dependency)) {
mFileDescProtoBuilder.addPublicDependency(i);
return this;
}
}
mFileDescProtoBuilder.addDependency(dependency);
mFileDescProtoBuilder.addPublicDependency(mFileDescProtoBuilder.getDependencyCount() - 1);
return this;
}
// Note: added
public Builder setJavaPackage(String javaPackage) {
DescriptorProtos.FileOptions.Builder optionsBuilder =
DescriptorProtos.FileOptions.newBuilder();
optionsBuilder.setJavaPackage(javaPackage);
mFileDescProtoBuilder.mergeOptions(optionsBuilder.build());
return this;
}
// Note: added
public Builder setJavaOuterClassname(String javaOuterClassname) {
DescriptorProtos.FileOptions.Builder optionsBuilder =
DescriptorProtos.FileOptions.newBuilder();
optionsBuilder.setJavaOuterClassname(javaOuterClassname);
mFileDescProtoBuilder.mergeOptions(optionsBuilder.build());
return this;
}
// Note: added
public Builder setJavaMultipleFiles(boolean javaMultipleFiles) {
DescriptorProtos.FileOptions.Builder optionsBuilder =
DescriptorProtos.FileOptions.newBuilder();
optionsBuilder.setJavaMultipleFiles(javaMultipleFiles);
mFileDescProtoBuilder.mergeOptions(optionsBuilder.build());
return this;
}
// Note: changed
public Builder addSchema(DynamicSchema schema) {
for (DescriptorProtos.FileDescriptorProto file : schema.mFileDescSet.getFileList()) {
if (!contains(file)) {
mFileDescSetBuilder.addFile(file);
}
}
return this;
}
// Note: added
private boolean contains(DescriptorProtos.FileDescriptorProto fileDesc) {
List<DescriptorProtos.FileDescriptorProto> files = mFileDescSetBuilder.getFileList();
for (DescriptorProtos.FileDescriptorProto file : files) {
if (file.getName().equals(fileDesc.getName())) {
return true;
}
}
return false;
}
// --- private ---
private Builder() {
mFileDescProtoBuilder = DescriptorProtos.FileDescriptorProto.newBuilder();
mFileDescSetBuilder = DescriptorProtos.FileDescriptorSet.newBuilder();
}
private DescriptorProtos.FileDescriptorProto.Builder mFileDescProtoBuilder;
private DescriptorProtos.FileDescriptorSet.Builder mFileDescSetBuilder;
}
}
| 37.492274 | 127 | 0.633302 |
55a3842d7def46bbba4eb13858302d4070e0bf6a | 354 | package com.moysklad.dao.domain.documentsDaoHibernate;
import com.moysklad.dao.hibernateDao.CrudHibernateDao;
import com.moysklad.model.MovingOfProduct;
import java.util.List;
public interface DocumentsMovingHibDao extends CrudHibernateDao<MovingOfProduct, Integer> {
List<MovingOfProduct> findAll();
MovingOfProduct findById(Integer id);
}
| 27.230769 | 91 | 0.819209 |
72eb0cc141bef507ce3704b9ca08ae4532b84bb0 | 8,091 | /**
* 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.hcatalog.hbase;
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.FileOutputCommitter;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobContext;
import org.apache.hadoop.mapred.OutputCommitter;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.SequenceFileOutputFormat;
import org.apache.hadoop.mapred.TaskAttemptContext;
import org.apache.hadoop.util.Progressable;
import org.apache.hcatalog.hbase.snapshot.RevisionManager;
/**
* Class which imports data into HBase via it's "bulk load" feature. Wherein
* regions are created by the MR job using HFileOutputFormat and then later
* "moved" into the appropriate region server.
*/
class HBaseBulkOutputFormat extends HBaseBaseOutputFormat {
private final static ImmutableBytesWritable EMPTY_LIST = new ImmutableBytesWritable(
new byte[0]);
private SequenceFileOutputFormat<WritableComparable<?>, Object> baseOutputFormat;
public HBaseBulkOutputFormat() {
baseOutputFormat = new SequenceFileOutputFormat<WritableComparable<?>, Object>();
}
@Override
public void checkOutputSpecs(FileSystem ignored, JobConf job)
throws IOException {
baseOutputFormat.checkOutputSpecs(ignored, job);
HBaseUtil.addHBaseDelegationToken(job);
addJTDelegationToken(job);
}
@Override
public RecordWriter<WritableComparable<?>, Object> getRecordWriter(
FileSystem ignored, JobConf job, String name, Progressable progress)
throws IOException {
HBaseHCatStorageHandler.setHBaseSerializers(job);
job.setOutputKeyClass(ImmutableBytesWritable.class);
job.setOutputValueClass(Put.class);
long version = HBaseRevisionManagerUtil.getOutputRevision(job);
return new HBaseBulkRecordWriter(baseOutputFormat.getRecordWriter(
ignored, job, name, progress), version);
}
private void addJTDelegationToken(JobConf job) throws IOException {
// Get jobTracker delegation token if security is enabled
// we need to launch the ImportSequenceFile job
if (User.isSecurityEnabled()) {
JobClient jobClient = new JobClient(new JobConf(job));
try {
job.getCredentials().addToken(new Text("my mr token"),
jobClient.getDelegationToken(null));
} catch (InterruptedException e) {
throw new IOException("Error while getting JT delegation token", e);
}
}
}
private static class HBaseBulkRecordWriter implements
RecordWriter<WritableComparable<?>, Object> {
private RecordWriter<WritableComparable<?>, Object> baseWriter;
private final Long outputVersion;
public HBaseBulkRecordWriter(
RecordWriter<WritableComparable<?>, Object> baseWriter,
Long outputVersion) {
this.baseWriter = baseWriter;
this.outputVersion = outputVersion;
}
@Override
public void write(WritableComparable<?> key, Object value)
throws IOException {
Put original = toPut(value);
Put put = original;
if (outputVersion != null) {
put = new Put(original.getRow(), outputVersion.longValue());
for (List<? extends Cell> row : original.getFamilyMap().values()) {
for (Cell cell : row) {
KeyValue el = (KeyValue)cell;
put.add(el.getFamily(), el.getQualifier(), el.getValue());
}
}
}
// we ignore the key
baseWriter.write(EMPTY_LIST, put);
}
@Override
public void close(Reporter reporter) throws IOException {
baseWriter.close(reporter);
}
}
public static class HBaseBulkOutputCommitter extends OutputCommitter {
private final OutputCommitter baseOutputCommitter;
public HBaseBulkOutputCommitter() {
baseOutputCommitter = new FileOutputCommitter();
}
@Override
public void abortTask(TaskAttemptContext taskContext)
throws IOException {
baseOutputCommitter.abortTask(taskContext);
}
@Override
public void commitTask(TaskAttemptContext taskContext)
throws IOException {
// baseOutputCommitter.commitTask(taskContext);
}
@Override
public boolean needsTaskCommit(TaskAttemptContext taskContext)
throws IOException {
return baseOutputCommitter.needsTaskCommit(taskContext);
}
@Override
public void setupJob(JobContext jobContext) throws IOException {
baseOutputCommitter.setupJob(jobContext);
}
@Override
public void setupTask(TaskAttemptContext taskContext)
throws IOException {
baseOutputCommitter.setupTask(taskContext);
}
@Override
public void abortJob(JobContext jobContext, int status)
throws IOException {
baseOutputCommitter.abortJob(jobContext, status);
RevisionManager rm = null;
try {
rm = HBaseRevisionManagerUtil
.getOpenedRevisionManager(jobContext.getConfiguration());
rm.abortWriteTransaction(HBaseRevisionManagerUtil
.getWriteTransaction(jobContext.getConfiguration()));
} finally {
cleanIntermediate(jobContext);
if (rm != null)
rm.close();
}
}
@Override
public void commitJob(JobContext jobContext) throws IOException {
baseOutputCommitter.commitJob(jobContext);
RevisionManager rm = null;
try {
Configuration conf = jobContext.getConfiguration();
Path srcPath = FileOutputFormat.getOutputPath(jobContext.getJobConf());
if (!FileSystem.get(conf).exists(srcPath)) {
throw new IOException("Failed to bulk import hfiles. " +
"Intermediate data directory is cleaned up or missing. " +
"Please look at the bulk import job if it exists for failure reason");
}
Path destPath = new Path(srcPath.getParent(), srcPath.getName() + "_hfiles");
boolean success = ImportSequenceFile.runJob(jobContext,
conf.get(HBaseConstants.PROPERTY_OUTPUT_TABLE_NAME_KEY),
srcPath,
destPath);
if (!success) {
cleanIntermediate(jobContext);
throw new IOException("Failed to bulk import hfiles." +
" Please look at the bulk import job for failure reason");
}
rm = HBaseRevisionManagerUtil.getOpenedRevisionManager(conf);
rm.commitWriteTransaction(HBaseRevisionManagerUtil.getWriteTransaction(conf));
cleanIntermediate(jobContext);
} finally {
if (rm != null)
rm.close();
}
}
private void cleanIntermediate(JobContext jobContext)
throws IOException {
FileSystem fs = FileSystem.get(jobContext.getConfiguration());
fs.delete(FileOutputFormat.getOutputPath(jobContext.getJobConf()), true);
}
}
}
| 35.800885 | 86 | 0.718205 |
e0085d57def9cbf51a047e511d196bc9853fc034 | 3,860 | package detailedTechnology.blocks.tanks.blockEntity;
import detailedTechnology.code.TankUtilities;
import detailedTechnology.code.ImplementedInventory;
import detailedTechnology.group.machine.Pipes;
import detailedTechnology.group.items.Materials;
import detailedTechnology.blocks.tanks.screenHandler.BarrelScreenHandler;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventories;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.screen.NamedScreenHandlerFactory;
import net.minecraft.screen.PropertyDelegate;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Tickable;
import net.minecraft.util.collection.DefaultedList;
public class FirebrickBarrelEntity extends BlockEntity implements ImplementedInventory, NamedScreenHandlerFactory, Tickable{
private final DefaultedList<ItemStack> inventory = DefaultedList.ofSize(2, ItemStack.EMPTY);
public static final int MaximumCapacitance = 16000;
public String liquidName;
public int liquidAmount;
public TankUtilities tankUtilities;
private final PropertyDelegate propertyDelegate = new PropertyDelegate() {
@Override
public int get(int index) {
if(index==0){
for (int i = 0; i < Materials.LiquidList.size(); i++) {
if(liquidName.equals(Materials.LiquidList.get(i))) return i;
}
return -1;
} else{
return liquidAmount;
}
}
@Override
public void set(int index, int value) {
liquidAmount = value;
}
//this is supposed to return the amount of integers you have in your delegate, in our example only one
@Override
public int size() {
return 2;
}
};
public FirebrickBarrelEntity(){
super(Pipes.firebrickBarrelEntity);
liquidName="air";
liquidAmount=0;
tankUtilities = new TankUtilities(MaximumCapacitance,liquidAmount,liquidName);
}
@Override
public DefaultedList<ItemStack> getItems() {
return inventory;
}
@Override
public Text getDisplayName() {
return new TranslatableText(getCachedState().getBlock().getTranslationKey());
}
@Override
public void fromTag(BlockState state,CompoundTag tag) {
super.fromTag(state,tag);
liquidName = tag.getString("liquid name");
liquidAmount = tag.getInt("liquid amount");
tankUtilities = new TankUtilities(MaximumCapacitance,liquidAmount,liquidName);
}
@Override
public CompoundTag toTag(CompoundTag tag) {
super.toTag(tag);
Inventories.toTag(tag, this.inventory);
Inventories.fromTag(tag,inventory);
tag.putString("liquid name",liquidName);
tag.putInt("liquid amount",liquidAmount);
return tag;
}
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory playerInventory, PlayerEntity player) {
return new BarrelScreenHandler(syncId, playerInventory, this,propertyDelegate);
}
private void checkBreak() {
}
public void loadTank(TankUtilities tankUtilties){
this.tankUtilities = tankUtilties;
this.liquidName = tankUtilties.liquidName;
this.liquidAmount = tankUtilties.liquidAmount;
}
@Override
public void tick() {
tankUtilities.InventoryManipulate((Inventory)this);
this.liquidName = tankUtilities.liquidName;
this.liquidAmount = tankUtilities.liquidAmount;
}
}
| 32.991453 | 124 | 0.703368 |
83be08c64918ff40d8f85266dd6eb06f7869e7b8 | 1,686 | package com.rkb.springboot.caching.service;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.rkb.springboot.caching.entity.User;
import com.rkb.springboot.caching.repo.UserRepo;
@Service
public class UserServiceImpl {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
UserRepo userRepo;
public String save() {
long start = System.currentTimeMillis();
List<User> users = new ArrayList<User>();
for (int count = 0; count < 50000; count++) {
User user = new User();
user.setFirstName("FirstName" + count + 1);
user.setLastName("LastName" + count + 1);
user.setAddress("Address" + count + 1);
users.add(user);
}
userRepo.saveAll(users);
long end = System.currentTimeMillis();
return "10K Records inserted successfully: " + "StartTime :" + start + " EndTime: " + end;
}
@Cacheable(cacheNames = { "userCache" })
public List<User> findAll() {
LOGGER.info("1st time hitting the db");
return userRepo.findAll();
}
@Cacheable(cacheNames = { "userCache" }, key = "#id", unless = "#result==null")
public User findOneById(int id) {
return userRepo.findOneById(id);
}
@CacheEvict(cacheNames = { "userCache" })
public String delete(int id) {
userRepo.deleteById(id);
return "Deleted successfully";
}
@CacheEvict(cacheNames = { "userCache" })
public void deleteAll() {
userRepo.deleteAll();
}
}
| 27.639344 | 93 | 0.723013 |
ed681767f2ec8cbf5b3addc449b6b5afcb69b2d3 | 4,789 | package net.savantly.aloha.importer.domain.itm;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.cache.annotation.Cacheable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import net.savantly.aloha.importer.dbf.ImportIdentifiable;
@Data
@Entity
@EqualsAndHashCode(exclude = {"posKey", "importId", "importDate"})
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Item implements ImportIdentifiable {
private Long posKey;
private Long importId;
private Date importDate;
@Id
private Long id;
private Long ownerid;
private Long usernumber;
@Column(length = 15)
private String shortname;
@Column(length = 15)
private String chitname;
@Column(length = 25)
private String longname;
@Column(length = 25)
private String longname2;
@Column(length = 20)
private String bohname;
@Column(length = 4)
private String abbrev;
private BigDecimal taxid;
private BigDecimal taxid2;
private BigDecimal vtaxid;
private Long priority;
private Long routing;
@Column(length = 1)
private String printonchk;
@Column(length = 1)
private String combine;
@Column(length = 1)
private String highlight;
private BigDecimal surcharge;
@Column(length = 1)
private String surchrgmod;
private BigDecimal cost;
private Long mod1;
private Long mod2;
private Long mod3;
private Long mod4;
private Long mod5;
private Long mod6;
private Long mod7;
private Long mod8;
private Long mod9;
private Long mod10;
@Column(length = 1)
private String askdesc;
@Column(length = 1)
private String askprice;
@Column(length = 1)
private String isrefill;
private Long vrouting;
private Long is_kvi;
@Column(length = 1)
private String trackfoh;
private BigDecimal price_id;
private BigDecimal price;
private Long slavetoitm;
private Long defweight;
@Column(length = 15)
private String sku;
@Column(length = 1)
private String modprice;
private Long itemmult;
private Long itempercnt;
private BigDecimal modpriceid;
private BigDecimal mod_price;
private Long ampri;
@Column(length = 1)
private String neverprint;
private Long prtrecipe;
@Column(length = 1)
private String nogratuity;
private Long compositid;
@Column(length = 1)
private String adisprecp;
@Column(length = 1)
private String independnt;
@Column(length = 1)
private String printheld;
@Column(length = 1)
private String donotshow;
@Column(length = 1)
private String donotshwm;
@Column(length = 1)
private String showndpnt;
@Column(length = 1)
private String giftcert;
@Column(length = 1)
private String itemhilite;
private Long delaytime;
private Long label;
private Long guests;
private Long siteflags;
private BigDecimal flextax;
@Column(length = 1)
private String cashcard;
private Long concept;
private Long multiplier;
@Column(length = 15)
private String sku2;
@Column(length = 15)
private String sku3;
@Column(length = 15)
private String sku4;
@Column(length = 15)
private String sku5;
@Column(length = 1)
private String revitem;
@Column(length = 1)
private String con1stmod;
private Long chitjust;
@Column(length = 1)
private String chitbold;
private BigDecimal flextax2;
@Column(length = 1)
private String dntshwsm;
@Column(length = 1)
private String swtrcksm;
@Column(length = 1)
private String giftcard;
@Column(length = 1)
private String gcactivate;
@Column(length = 1)
private String gcaddvalue;
@Column(length = 1)
private String tokenover;
private Long tokenqty;
private Long guestwght;
@Column(length = 1)
private String dntshwsmmd;
@Column(length = 1)
private String usebkclr;
private Long bkred;
private Long bkgreen;
private Long bkblue;
@Column(length = 1)
private String usetxtclr;
private Long txtred;
private Long txtgreen;
private Long txtblue;
@Column(length = 1)
private String dispbmp;
@Column(length = 12)
private String bitmapfile;
@Column(length = 1)
private String hidetxt;
@Column(length = 15)
private String chitname2;
private Long ctxpnlid;
@Column(length = 1)
private String mdspctxpnl;
@Column(length = 1)
private String pizza;
@Column(length = 1)
private String topping;
private Long inittop;
private Long pizzasize;
@Column(length = 1)
private String mustbwhole;
@Column(length = 1)
private String fraction;
private Long fractype;
private Long fracprcovr;
private Long type;
@Column(length = 1)
private String fsitem;
private Long fsmatrix;
private Long exportid;
private Long camprovide;
private Long planindex;
private Long camaction;
private BigDecimal occtax;
} | 18.490347 | 77 | 0.751096 |
d9158838a960410ce2a39099041a675b5cf03aba | 862 | package ec.edu.espe.monster.aerolineacondor.model.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Entity
@Table(name = "Agencia")
@Data
public class Agency {
@Id
@Column(name = "id_agencia")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "agencia_RUC", length = 20)
private String RUC;
@Column(name = "agencia_razon_social", length = 300)
private String name;
@JsonIgnore
@OneToMany(mappedBy = "agency", fetch = FetchType.LAZY)
private List<Tickets> tickets;
}
| 22.102564 | 57 | 0.774942 |
647009c89db30f09f5490a02b18cddbe43b14ed1 | 4,392 | package com.evvanErb.minesweeper.view.terminalview;
import com.evvanErb.minesweeper.model.board.GameStatus;
import com.evvanErb.minesweeper.viewmodel.gamemanager.GameManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TerminalView {
public void main() throws IOException {
boolean gameRunning = true;
GameManager currentGame = new GameManager();
while (gameRunning) {
int boardSize = this.getDesiredBoardSize(System.in, System.out);
currentGame.startGame(boardSize);
gameRunning = this.runCurrentGame(currentGame, System.in, System.out);
}
}
protected boolean runCurrentGame(GameManager currentGame, InputStream inputStream, OutputStream outputStream) throws IOException {
Scanner scanner = new Scanner(inputStream);
boolean currentGameRunning = true;
while (currentGameRunning) {
outputStream.write((currentGame.getBoardAsString() + "\nEnter a command: ").getBytes());
String userInput = scanner.nextLine();
userInput = userInput.toLowerCase();
if (userInput.equals("quit") || userInput.equals("q")) {
return false;
}
else {
currentGameRunning = this.handleUserInput(userInput, currentGame, outputStream);
}
}
return true;
}
protected boolean handleUserInput(String userInput, GameManager currentGame, OutputStream outputStream) throws IOException {
if (this.regexMatch(userInput, "^f[0-9]+,[0-9]+$")) {
String[] toFlagPoint = userInput.substring(1).split(",");
currentGame.changeCellFlag(Integer.parseInt(toFlagPoint[0]), Integer.parseInt(toFlagPoint[1]));
return true;
}
else if (this.regexMatch(userInput, "^[0-9]+,[0-9]+$")) {
String[] toRevealPoint = userInput.split(",");
return this.revealCell(Integer.parseInt(toRevealPoint[0]), Integer.parseInt(toRevealPoint[1]), currentGame, outputStream);
}
else if (userInput.equals("help") || userInput.equals("h")) {
outputStream.write(
"""
To Quit: "quit" or "q"
For New Game: "new game" or "new" or "n"
To Flag a Point: "FX,Y"
To Reveal a Point: "X,Y"
To Print this Menu: "help" or "h"\n
""".getBytes()
);
return true;
}
else if (userInput.equals("new game") || userInput.equals("new") || userInput.equals("n")) {
return false;
}
else {
outputStream.write("[!] Unknown Command: type \"help\" for list of commands\n".getBytes());
return true;
}
}
protected boolean revealCell(int xPos, int yPos, GameManager game, OutputStream outputStream) throws IOException {
GameStatus resultingStatusAfterReveal = game.revealCell(xPos, yPos);
if (resultingStatusAfterReveal == GameStatus.VICTORY) {
outputStream.write("YOU WON!\n".getBytes());
return false;
}
else if (resultingStatusAfterReveal == GameStatus.LOST) {
outputStream.write(game.getBoardAsString().getBytes());
outputStream.write("YOU LOST!\n".getBytes());
return false;
}
return true;
}
protected boolean regexMatch(String input, String regex) {
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
return matcher.find();
}
protected int getDesiredBoardSize(InputStream inputStream, OutputStream outputStream) throws IOException {
Scanner scanner = new Scanner(inputStream);
boolean gotInteger = false;
int size = 0;
do {
try {
outputStream.write("Enter a board size: ".getBytes());
size = Integer.parseInt(scanner.nextLine());
gotInteger = true;
} catch (NumberFormatException error) { outputStream.write("[!] Please enter a number\n".getBytes()); }
} while(! gotInteger);
return size;
}
}
| 36.907563 | 134 | 0.607468 |
87a12a57653481df82902566101948395777c0a5 | 1,959 | package com.bartosektom.letsplayfolks.controller;
import com.bartosektom.letsplayfolks.constants.ActiveTabConstants;
import com.bartosektom.letsplayfolks.constants.GameConstants;
import com.bartosektom.letsplayfolks.exception.EntityNotFoundException;
import com.bartosektom.letsplayfolks.repository.GameRepository;
import com.bartosektom.letsplayfolks.service.LeaderboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
@Controller
@RequestMapping("/leaderboard")
@SessionAttributes(ActiveTabConstants.ACTIVE_TAB)
public class LeaderboardController {
private static final String GAME_ID_REQUEST_PARAM = "gameId";
private static final String GAMES_MODEL_KEY = "games";
private static final String LEADERBOARD_MODELS_MODEL_KEY = "leaderboardModels";
private static final String LEADERBOARD_LIST_VIEW_NAME = "/leaderboard/list";
@Autowired
GameRepository gameRepository;
@Autowired
LeaderboardService leaderboardService;
@GetMapping("/list")
public ModelAndView leaderboardList(@RequestParam(value = GAME_ID_REQUEST_PARAM, defaultValue = "1") Integer gameId,
Map<String, Object> model) throws EntityNotFoundException {
model.put(ActiveTabConstants.ACTIVE_TAB, ActiveTabConstants.LEADERBOARD);
model.put(LEADERBOARD_MODELS_MODEL_KEY, leaderboardService.prepareLeaderboardModels(gameId));
model.put(GAMES_MODEL_KEY, gameRepository.findByApproved(GameConstants.GAME_APPROVED));
return new ModelAndView(LEADERBOARD_LIST_VIEW_NAME, model);
}
}
| 42.586957 | 120 | 0.806023 |
6d2b4aa91237c17163ad49426dce9975a1d1ef3f | 7,674 | /*
* Copyright 2016 - 2019 Acosix GmbH
*
* 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 de.acosix.maven.jshint;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.WrappedException;
/**
* @author Axel Faust, <a href="http://acosix.de">Acosix GmbH</a>
*/
public class RhinoJSHinter extends AbstractJSHinter
{
protected final Object jshintScript;
protected Scriptable scope;
protected Script runnerScript;
public RhinoJSHinter(final Log log, final String versionOrResourcePath, final boolean resourcePath)
{
super(log);
if (StringUtils.isBlank(versionOrResourcePath))
{
throw new IllegalArgumentException("versionOrResourcePath not provided");
}
if (!resourcePath)
{
final String scriptName = "jshint-" + versionOrResourcePath + "-rhino.js";
this.jshintScript = RhinoJSHinter.class.getResource(scriptName);
if (this.jshintScript == null)
{
this.log.error("JSHint script could not be resolved for version " + versionOrResourcePath);
throw new RuntimeException(new MojoExecutionException("Error resolving " + scriptName));
}
}
else
{
this.jshintScript = RhinoJSHinter.class.getClassLoader().getResource(versionOrResourcePath);
if (this.jshintScript == null)
{
this.log.error("JSHint script could not be resolved from resource path " + versionOrResourcePath);
throw new RuntimeException(new MojoExecutionException("Error resolving " + versionOrResourcePath));
}
}
}
public RhinoJSHinter(final Log log, final File jshintScriptFile)
{
super(log);
this.jshintScript = jshintScriptFile;
}
/**
*
* {@inheritDoc}
*/
@Override
protected List<Error> executeJSHintImpl(final File baseDirectory, final String path, final String effectiveJSHintConfigContent)
{
this.ensureEngineInitialisation();
final List<Error> errors = new ArrayList<>();
final Context cx = Context.enter();
try
{
final List<String> sourceLines = this.readSourceLines(baseDirectory, path);
final Scriptable sourceLinesArr = cx.newArray(this.scope, sourceLines.toArray(new Object[0]));
this.scope.put("errors", this.scope, errors);
this.scope.put("sourceLines", this.scope, sourceLinesArr);
this.scope.put("jshintConfig", this.scope, effectiveJSHintConfigContent);
this.runnerScript.exec(cx, this.scope);
}
catch (final JavaScriptException jse)
{
// a Java exception triggered via JS code may be wrapped in this
Object value = jse.getValue();
if (value instanceof NativeJavaObject)
{
value = ((NativeJavaObject) value).unwrap();
}
if (value instanceof RuntimeException)
{
throw (RuntimeException) value;
}
throw jse;
}
catch (final WrappedException we)
{
final Throwable wrapped = we.getWrappedException();
if (wrapped instanceof RuntimeException)
{
throw (RuntimeException) wrapped;
}
throw we;
}
finally
{
Context.exit();
}
return errors;
}
protected void ensureEngineInitialisation()
{
if (this.scope == null)
{
this.log.debug("Initialising Rhino context for JSHint");
final Context cx = Context.enter();
try
{
this.scope = cx.initStandardObjects(null, false);
final Script jshintScript = this.compileJSHintScript(cx);
// execute once to actually load JSHINT
jshintScript.exec(cx, this.scope);
// the runner script is our wrapper for repeated execution
this.runnerScript = this.compileInternalScriptScript(cx, "jshint-rhino-runner.js");
}
catch (final IOException ioex)
{
this.log.error("Error initialising Rhino context for JSHint");
throw new RuntimeException(new MojoExecutionException("Error initialising Rhino context for JSHint", ioex));
}
finally
{
Context.exit();
}
}
}
protected Script compileJSHintScript(final Context cx) throws IOException
{
Script jshintScript;
if (this.jshintScript instanceof URL)
{
final URL jshintScriptURL = (URL) this.jshintScript;
final InputStream scriptInputStream = jshintScriptURL.openStream();
try
{
jshintScript = this.compileScript(cx, jshintScriptURL.toExternalForm(), scriptInputStream);
}
finally
{
IOUtil.close(scriptInputStream);
}
}
else if (this.jshintScript instanceof File)
{
final InputStream scriptInputStream = new FileInputStream((File) this.jshintScript);
try
{
jshintScript = this.compileScript(cx, ((File) this.jshintScript).getAbsolutePath(), scriptInputStream);
}
finally
{
IOUtil.close(scriptInputStream);
}
}
else
{
throw new RuntimeException(new MojoExecutionException("JSHint script has not been resolved"));
}
return jshintScript;
}
protected Script compileInternalScriptScript(final Context cx, final String scriptName) throws IOException
{
final InputStream scriptInputStream = RhinoJSHinter.class.getResourceAsStream(scriptName);
try
{
final Script script = this.compileScript(cx, scriptName, scriptInputStream);
return script;
}
finally
{
IOUtil.close(scriptInputStream);
}
}
protected Script compileScript(final Context cx, final String name, final InputStream is) throws IOException
{
final Reader scriptReader = new InputStreamReader(is, StandardCharsets.UTF_8);
final Script script = cx.compileReader(scriptReader, name, 1, null);
return script;
}
}
| 33.220779 | 131 | 0.623664 |
1de0d75651ebc65b6778aebbf497b9211bd45638 | 643 | package edu.tamu.scholars.middleware.graphql.config.model;
import java.util.ArrayList;
import java.util.List;
public class Composite {
private String type;
private List<CompositeReference> references;
public Composite() {
this.references = new ArrayList<CompositeReference>();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<CompositeReference> getReferences() {
return references;
}
public void setReferences(List<CompositeReference> references) {
this.references = references;
}
}
| 19.484848 | 68 | 0.66874 |
e766a61617cadfb7329597e6162e73d42c3040cd | 1,104 | package com.java110.things.dao;
import com.java110.things.entity.parkingArea.ParkingBoxDto;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @ClassName IParkingBoxServiceDao
* @Description TODO
* @Author wuxw
* @Date 2020/5/15 21:02
* @Version 1.0
* add by wuxw 2020/5/15
**/
@Mapper
public interface IParkingBoxServiceDao {
/**
* 保存停车场信息
*
* @param parkingBoxDto 停车场信息
* @return 返回影响记录数
*/
int saveParkingBox(ParkingBoxDto parkingBoxDto);
/**
* 查询停车场信息
*
* @param parkingBoxDto 停车场信息
* @return
*/
List<ParkingBoxDto> getParkingBoxs(ParkingBoxDto parkingBoxDto);
/**
* 查询停车场总记录数
*
* @param parkingBoxDto 停车场信息
* @return
*/
long getParkingBoxCount(ParkingBoxDto parkingBoxDto);
/**
* 修改停车场信息
*
* @param parkingBoxDto 停车场信息
* @return 返回影响记录数
*/
int updateParkingBox(ParkingBoxDto parkingBoxDto);
/**
* 删除指令
*
* @param parkingBoxDto 指令id
* @return 返回影响记录数
*/
int delete(ParkingBoxDto parkingBoxDto);
}
| 18.711864 | 68 | 0.632246 |
4cce4918b6f721f9d046738cddc5ca169f46e35b | 3,216 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. 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. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
package org.apache.abdera.examples.simple;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.bidi.BidiHelper;
import org.apache.abdera.i18n.text.Bidi.Direction;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
/**
* Simple example demonstrating Abdera's i18n support
*/
public class i18nExample {
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
Feed feed = abdera.newFeed();
feed.getDocument().setCharset("UTF-8");
// Set the language context and default text direction
feed.setLanguage("ar"); // Arabic
BidiHelper.setDirection(Direction.RTL, feed);
feed.setBaseUri("http://\u0645\u062b\u0627\u0644.org/ar/feed.xml");
feed.setId("tag:\u0645\u062b\u0627\u0644.org,2007:/\u0645\u062b\u0627\u0644");
feed.setUpdated(new Date());
feed
.setTitle("\u0645\u062b\u0644\u0627\u0020\u0627\u0644\u0646\u0635\u0020\u0627\u0644\u0639\u0631\u0628\u064a");
feed.addAuthor("\u062c\u064a\u0645\u0633");
feed.addLink("", "self");
feed.addLink("http://\u0645\u062b\u0627\u0644.org/ar/blog");
Entry entry = feed.addEntry();
entry.setId("tag:\u0645\u062b\u0627\u0644.org,2007:/\u0645\u062b\u0627\u0644/1");
entry.setTitle("\u0645\u062b\u0627\u0644\u0020\u062f\u062e\u0648\u0644");
entry.setUpdated(new Date());
entry.addLink("http://\u0645\u062b\u0627\u0644.org/ar/blog/1");
entry
.setSummaryAsXhtml("<p xml:lang=\"ar\" dir=\"rtl\">\u0648\u0647\u0630\u0627\u0020\u0645\u062b\u0627\u0644\u0020\u0639\u0644\u0649\u0020\u0648\u062c\u0648\u062f\u0020\u0041\u0074\u006f\u006d\u0020\u0031\u002e\u0030\u0020\u0052\u0054\u004c\u0020\u0627\u0644\u0627\u0639\u0644\u0627\u0641\u0020\u0627\u0644\u062a\u064a\u0020\u062a\u062d\u062a\u0648\u064a\u0020\u0639\u0644\u0649\u0020\u0627\u0644\u0646\u0635\u0020\u0627\u0644\u0639\u0631\u0628\u064a</p>");
feed.writeTo("prettyxml", System.out);
System.out.println();
Element el = feed.getEntries().get(0).getSummaryElement().getValueElement().getFirstChild();
System.out.println("Incorrect: " + el.getText());
System.out.println("Correct: " + BidiHelper.getBidiElementText(el));
}
}
| 45.942857 | 466 | 0.708022 |
5c52985f84eab5e3c5275220386625dcbdde0d54 | 4,586 | package io.github.muddz.styleabletoast.demo;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import io.github.muddz.styleabletoast.StyleableToast;
import io.github.muddz.styleabletoast.demo.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
String toastMsg = "Hello World!";
int redColor = Color.parseColor("#FF5A5F");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setMain(this);
}
public void coloredBackground() {
StyleableToast.Builder st = new StyleableToast.Builder(this)
.text(toastMsg)
.backgroundColor(redColor)
.build();
st.show();
}
public boolean coloredBackgroundXML() {
StyleableToast.makeText(this, toastMsg, R.style.ColoredBackground).show();
return true;
}
public void coloredText() {
new StyleableToast.Builder(this)
.text(toastMsg)
.textColor(redColor)
.show();
}
public boolean coloredTextXML() {
StyleableToast.makeText(this, toastMsg, R.style.ColoredText).show();
return true;
}
public void coloredBoldText() {
new StyleableToast.Builder(this)
.text(toastMsg)
.textColor(redColor)
.textBold()
.show();
}
public boolean coloredBoldTextXML() {
StyleableToast.makeText(this, toastMsg, R.style.ColoredBoldText).show();
return true;
}
public void customFont() {
new StyleableToast.Builder(this)
.text(toastMsg)
.font(R.font.dosis)
.show();
}
public boolean customFontXML() {
StyleableToast.makeText(this, toastMsg, R.style.CustomFont).show();
return true;
}
public void cornerRadius() {
new StyleableToast.Builder(this)
.text(toastMsg)
.cornerRadius(5)
.show();
}
public boolean cornerRadiusXML() {
StyleableToast.makeText(this, toastMsg, R.style.CornerRadius5Dp).show();
return true;
}
public void iconStart() {
new StyleableToast.Builder(this)
.text(toastMsg)
.iconStart(getIcon())
.show();
}
public boolean iconStartXML() {
StyleableToast.makeText(this, toastMsg, R.style.IconStart).show();
return true;
}
public void iconEnd() {
new StyleableToast.Builder(this)
.text(toastMsg)
.iconEnd(getIcon())
.show();
}
public boolean iconEndXML() {
StyleableToast.makeText(this, toastMsg, R.style.IconEnd).show();
return true;
}
public void iconStartEnd() {
new StyleableToast.Builder(this)
.text(toastMsg)
.iconStart(getIcon())
.iconEnd(getIcon())
.show();
}
public boolean iconStartEndXML() {
StyleableToast.makeText(this, toastMsg, R.style.IconStartEnd).show();
return true;
}
public void coloredStroke() {
new StyleableToast.Builder(this)
.text(toastMsg)
.stroke(2, redColor)
.show();
}
public boolean coloredStrokeXML() {
StyleableToast.makeText(this, toastMsg, R.style.ColoredStroke).show();
return true;
}
public void allStyles() {
new StyleableToast.Builder(this)
.text(toastMsg)
.stroke(2, Color.BLACK)
.backgroundColor(Color.WHITE)
.solidBackground()
.textColor(Color.RED)
.textBold()
.font(R.font.dosis)
.iconStart(getIcon())
.iconEnd(getIcon())
.cornerRadius(12)
.textSize(18)
.show();
}
public boolean allStylesXML() {
StyleableToast.makeText(this, toastMsg, R.style.AllStyles).show();
return true;
}
public int getIcon() {
if (android.os.Build.VERSION.SDK_INT >= 27) {
return R.drawable.ic_autorenew_black_24dp;
} else {
return R.drawable.ic_autorenew_white_24dp;
}
}
}
| 26.508671 | 99 | 0.573266 |
590d716af54e3872a4b902525945e6aa288daa17 | 13,137 | package mekanism.common.item;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mekanism.api.Coord4D;
import mekanism.api.EnumColor;
import mekanism.common.config.MekanismConfig.general;
import mekanism.common.util.ItemDataUtils;
import mekanism.common.util.LangUtils;
import mekanism.common.util.ListUtils;
import mekanism.common.util.MekanismUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDirt;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import com.google.common.collect.Multimap;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemAtomicDisassembler extends ItemEnergized
{
public double HOE_USAGE = 10 * general.DISASSEMBLER_USAGE;
public ItemAtomicDisassembler()
{
super(1000000);
}
@Override
public boolean canHarvestBlock(IBlockState state, ItemStack stack)
{
return state.getBlock() != Blocks.BEDROCK;
}
@SideOnly(Side.CLIENT)
@Override
public void addInformation(ItemStack itemstack, World world, List<String> list, ITooltipFlag flag)
{
super.addInformation(itemstack, world, list, flag);
list.add(LangUtils.localize("tooltip.mode") + ": " + EnumColor.INDIGO + getModeName(itemstack));
list.add(LangUtils.localize("tooltip.efficiency") + ": " + EnumColor.INDIGO + getEfficiency(itemstack));
}
@Override
public boolean hitEntity(ItemStack itemstack, EntityLivingBase target, EntityLivingBase attacker)
{
if(getEnergy(itemstack) > 0)
{
if(attacker instanceof EntityPlayer)
{
target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) attacker), 20);
}
else {
target.attackEntityFrom(DamageSource.causeMobDamage(attacker), 20);
}
setEnergy(itemstack, getEnergy(itemstack) - 2000);
}
else {
if(attacker instanceof EntityPlayer)
{
target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer)attacker), 4);
}
else {
target.attackEntityFrom(DamageSource.causeMobDamage(attacker), 4);
}
}
return false;
}
@Override
public float getStrVsBlock(ItemStack itemstack, IBlockState state)
{
return getEnergy(itemstack) != 0 ? getEfficiency(itemstack) : 1F;
}
@Override
public boolean onBlockDestroyed(ItemStack itemstack, World world, IBlockState state, BlockPos pos, EntityLivingBase entityliving)
{
if(state.getBlockHardness(world, pos) != 0.0D)
{
setEnergy(itemstack, getEnergy(itemstack) - (general.DISASSEMBLER_USAGE*getEfficiency(itemstack)));
}
else {
setEnergy(itemstack, getEnergy(itemstack) - (general.DISASSEMBLER_USAGE*(getEfficiency(itemstack))/2));
}
return true;
}
private RayTraceResult doRayTrace(IBlockState state, BlockPos pos, EntityPlayer player)
{
Vec3d positionEyes = player.getPositionEyes(1.0F);
Vec3d playerLook = player.getLook(1.0F);
double blockReachDistance = player.getAttributeMap().getAttributeInstance(EntityPlayer.REACH_DISTANCE).getAttributeValue();
Vec3d maxReach = positionEyes.addVector(playerLook.x * blockReachDistance, playerLook.y * blockReachDistance, playerLook.z * blockReachDistance);
RayTraceResult res = state.collisionRayTrace(player.world, pos, playerLook, maxReach);
//noinspection ConstantConditions - idea thinks it's nonnull due to package level annotations, but it's not
return res != null ? res : new RayTraceResult(RayTraceResult.Type.MISS, Vec3d.ZERO, EnumFacing.UP, pos);
}
@Override
public boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, EntityPlayer player)
{
super.onBlockStartBreak(itemstack, pos, player);
if(!player.world.isRemote)
{
IBlockState state = player.world.getBlockState(pos);
Block block = state.getBlock();
int meta = block.getMetaFromState(state);
if(block == Blocks.LIT_REDSTONE_ORE)
{
block = Blocks.REDSTONE_ORE;
}
RayTraceResult raytrace = doRayTrace(state, pos, player);
ItemStack stack = block.getPickBlock(state, raytrace, player.world, pos, player);
Coord4D orig = new Coord4D(pos, player.world);
List<String> names = MekanismUtils.getOreDictName(stack);
boolean isOre = false;
for(String s : names)
{
if(s.startsWith("ore") || s.equals("logWood"))
{
isOre = true;
}
}
if(getMode(itemstack) == 3 && isOre && !player.capabilities.isCreativeMode)
{
Set<Coord4D> found = new Finder(player.world, stack, new Coord4D(pos, player.world), raytrace).calc();
for(Coord4D coord : found)
{
if(coord.equals(orig) || getEnergy(itemstack) < (general.DISASSEMBLER_USAGE*getEfficiency(itemstack)))
{
continue;
}
Block block2 = coord.getBlock(player.world);
block2.onBlockDestroyedByPlayer(player.world, coord.getPos(), state);
player.world.playEvent(null, 2001, coord.getPos(), Block.getStateId(state));
player.world.setBlockToAir(coord.getPos());
block2.breakBlock(player.world, coord.getPos(), state);
block2.dropBlockAsItem(player.world, coord.getPos(), state, 0);
setEnergy(itemstack, getEnergy(itemstack) - (general.DISASSEMBLER_USAGE*getEfficiency(itemstack)));
}
}
}
return false;
}
@Override
public boolean isFull3D()
{
return true;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer entityplayer, EnumHand hand)
{
ItemStack itemstack = entityplayer.getHeldItem(hand);
if(entityplayer.isSneaking())
{
if(!world.isRemote)
{
toggleMode(itemstack);
entityplayer.sendMessage(new TextComponentString(EnumColor.DARK_BLUE + "[Mekanism] " + EnumColor.GREY + LangUtils.localize("tooltip.modeToggle") + " " + EnumColor.INDIGO + getModeName(itemstack) + EnumColor.AQUA + " (" + getEfficiency(itemstack) + ")"));
}
return new ActionResult<>(EnumActionResult.SUCCESS, itemstack);
}
return new ActionResult<>(EnumActionResult.PASS, itemstack);
}
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)
{
ItemStack stack = player.getHeldItem(hand);
Block block = world.getBlockState(pos).getBlock();
if(!player.isSneaking() && (block == Blocks.DIRT || block == Blocks.GRASS || block == Blocks.GRASS_PATH))
{
if(useHoe(stack, player, world, pos, side) == EnumActionResult.FAIL)
{
return EnumActionResult.FAIL;
}
switch(getEfficiency(stack))
{
case 20:
for(int x1 = -1; x1 <= +1; x1++)
{
for(int z1 = -1; z1 <= +1; z1++)
{
useHoe(stack, player, world, pos.add(x1, 0, z1), side);
}
}
break;
case 128:
for(int x1 = -2; x1 <= +2; x1++)
{
for(int z1 = -2; z1 <= +2; z1++)
{
useHoe(stack, player, world, pos.add(x1, 0, z1), side);
}
}
break;
}
return EnumActionResult.SUCCESS;
}
return EnumActionResult.PASS;
}
@SuppressWarnings("incomplete-switch")
private EnumActionResult useHoe(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing facing)
{
if(!playerIn.canPlayerEdit(pos.offset(facing), facing, stack))
{
return EnumActionResult.FAIL;
}
else {
int hook = net.minecraftforge.event.ForgeEventFactory.onHoeUse(stack, playerIn, worldIn, pos);
if(hook != 0) return hook > 0 ? EnumActionResult.SUCCESS : EnumActionResult.FAIL;
IBlockState iblockstate = worldIn.getBlockState(pos);
Block block = iblockstate.getBlock();
if(facing != EnumFacing.DOWN && worldIn.isAirBlock(pos.up()))
{
if(block == Blocks.GRASS || block == Blocks.GRASS_PATH)
{
setBlock(stack, playerIn, worldIn, pos, Blocks.FARMLAND.getDefaultState());
return EnumActionResult.SUCCESS;
}
if(block == Blocks.DIRT)
{
switch((BlockDirt.DirtType)iblockstate.getValue(BlockDirt.VARIANT))
{
case DIRT:
setBlock(stack, playerIn, worldIn, pos, Blocks.FARMLAND.getDefaultState());
return EnumActionResult.SUCCESS;
case COARSE_DIRT:
setBlock(stack, playerIn, worldIn, pos, Blocks.DIRT.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT));
return EnumActionResult.SUCCESS;
}
}
}
return EnumActionResult.PASS;
}
}
protected void setBlock(ItemStack stack, EntityPlayer player, World worldIn, BlockPos pos, IBlockState state)
{
worldIn.playSound(player, pos, SoundEvents.ITEM_HOE_TILL, SoundCategory.BLOCKS, 1.0F, 1.0F);
if(!worldIn.isRemote)
{
worldIn.setBlockState(pos, state, 11);
stack.damageItem(1, player);
}
}
public int getEfficiency(ItemStack itemStack)
{
switch(getMode(itemStack))
{
case 0:
return 20;
case 1:
return 8;
case 2:
return 128;
case 3:
return 20;
case 4:
return 0;
}
return 0;
}
public int getMode(ItemStack itemStack)
{
return ItemDataUtils.getInt(itemStack, "mode");
}
public String getModeName(ItemStack itemStack)
{
int mode = getMode(itemStack);
switch(mode)
{
case 0:
return LangUtils.localize("tooltip.disassembler.normal");
case 1:
return LangUtils.localize("tooltip.disassembler.slow");
case 2:
return LangUtils.localize("tooltip.disassembler.fast");
case 3:
return LangUtils.localize("tooltip.disassembler.vein");
case 4:
return LangUtils.localize("tooltip.disassembler.off");
}
return null;
}
public void toggleMode(ItemStack itemStack)
{
ItemDataUtils.setInt(itemStack, "mode", getMode(itemStack) < 4 ? getMode(itemStack)+1 : 0);
}
@Override
public boolean canSend(ItemStack itemStack)
{
return false;
}
@Override
public Multimap<String, AttributeModifier> getItemAttributeModifiers(EntityEquipmentSlot equipmentSlot)
{
Multimap<String, AttributeModifier> multimap = super.getItemAttributeModifiers(equipmentSlot);
if(equipmentSlot == EntityEquipmentSlot.MAINHAND)
{
multimap.put(SharedMonsterAttributes.ATTACK_SPEED.getName(), new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", -2.4000000953674316D, 0));
}
return multimap;
}
public static class Finder
{
public World world;
public ItemStack stack;
public Coord4D location;
public Set<Coord4D> found = new HashSet<>();
private Block startBlock;
public static Map<Block, List<Block>> ignoreBlocks = new HashMap<>();
RayTraceResult rayTraceResult;
public Finder(World w, ItemStack s, Coord4D loc, RayTraceResult traceResult)
{
world = w;
stack = s;
location = loc;
startBlock = loc.getBlock(w);
rayTraceResult = traceResult;
}
public void loop(Coord4D pointer)
{
if(found.contains(pointer) || found.size() > 128)
{
return;
}
found.add(pointer);
for(EnumFacing side : EnumFacing.VALUES)
{
Coord4D coord = pointer.offset(side);
ItemStack blockStack = coord.getBlock(world).getPickBlock(coord.getBlockState(world), rayTraceResult, world, coord.getPos(), null);
if(coord.exists(world) && checkID(coord.getBlock(world)) && (stack.isItemEqual(blockStack) || (coord.getBlock(world) == startBlock && MekanismUtils.getOreDictName(stack).contains("logWood") && coord.getBlockMeta(world) % 4 == stack.getItemDamage() % 4)))
{
loop(coord);
}
}
}
public Set<Coord4D> calc()
{
loop(location);
return found;
}
public boolean checkID(Block b)
{
Block origBlock = location.getBlock(world);
return (ignoreBlocks.get(origBlock) == null && b == origBlock) || (ignoreBlocks.get(origBlock) != null && ignoreBlocks.get(origBlock).contains(b));
}
static {
ignoreBlocks.put(Blocks.REDSTONE_ORE, ListUtils.asList(Blocks.REDSTONE_ORE, Blocks.LIT_REDSTONE_ORE));
ignoreBlocks.put(Blocks.LIT_REDSTONE_ORE, ListUtils.asList(Blocks.REDSTONE_ORE, Blocks.LIT_REDSTONE_ORE));
}
}
}
| 29.721719 | 258 | 0.696125 |
59883c8066076292b0f32e05669e8d27382c4225 | 778 | package wxm.example.comical_music_server.exception;
/**
* @author Alex Wang
* @date 2020/05/12
*/
public class ParamIsNullException extends RuntimeException {
private final String parameterName;
private final String parameterType;
public ParamIsNullException(String parameterName, String parameterType) {
super("");
this.parameterName = parameterName;
this.parameterType = parameterType;
}
@Override
public String getMessage() {
return "Required " + this.parameterType + " parameter \'" + this.parameterName + "\' must be not null !";
}
public final String getParameterName() {
return this.parameterName;
}
public final String getParameterType() {
return this.parameterType;
}
} | 26.827586 | 113 | 0.679949 |
7fc787df0a9464fed06b0e6ed6f11a96a7eeadc8 | 3,107 | /*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.models.datamodel.rule;
/**
* Holds field and Work Item definition parameters for actions
*/
public class ActionWorkItemFieldValue extends ActionFieldValue {
private static final long serialVersionUID = 540L;
private String workItemName;
private String workItemParameterName;
private String workItemParameterClassName;
public ActionWorkItemFieldValue() {
}
public ActionWorkItemFieldValue( String factField,
String fieldType,
String workItemName,
String workItemParameterName,
String workItemParameterClassName ) {
super( factField,
null,
fieldType );
this.workItemName = workItemName;
this.workItemParameterName = workItemParameterName;
this.workItemParameterClassName = workItemParameterClassName;
}
public String getWorkItemName() {
return workItemName;
}
public String getWorkItemParameterName() {
return workItemParameterName;
}
public String getWorkItemParameterClassName() {
return workItemParameterClassName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ActionWorkItemFieldValue that = (ActionWorkItemFieldValue) o;
if (workItemName != null ? !workItemName.equals(that.workItemName) : that.workItemName != null) return false;
if (workItemParameterClassName != null ? !workItemParameterClassName.equals(that.workItemParameterClassName) : that.workItemParameterClassName != null)
return false;
if (workItemParameterName != null ? !workItemParameterName.equals(that.workItemParameterName) : that.workItemParameterName != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (workItemName != null ? workItemName.hashCode() : 0);
result = ~~result;
result = 31 * result + (workItemParameterName != null ? workItemParameterName.hashCode() : 0);
result = ~~result;
result = 31 * result + (workItemParameterClassName != null ? workItemParameterClassName.hashCode() : 0);
result = ~~result;
return result;
}
}
| 36.127907 | 159 | 0.657869 |
17626d012afe43194ab8f382b5edbea3ccea14ff | 2,243 | package controllers.ddmstructure;
import play.data.validation.ValidationError;
import java.util.ArrayList;
import java.util.List;
/**
* Backing class for the Ddmstructure data form.
* Requirements:
* <ul>
* <li> All fields are public,
* <li> All fields are of type String or List[String].
* <li> A public no-arg constructor.
* <li> A validate() method that returns null or a List[ValidationError].
* </ul>
*
* @author Manuel de la Peña
* @generated
*/
public class DdmstructureFormData {
public String uuid;
public String structureId;
public String groupId;
public String companyId;
public String userId;
public String userName;
public String createDate;
public String modifiedDate;
public String parentStructureId;
public String classNameId;
public String structureKey;
public String version;
public String name;
public String description;
public String definition;
public String storageType;
public String customtype;
public DdmstructureFormData() {
}
public DdmstructureFormData(
String uuid,
String structureId,
String groupId,
String companyId,
String userId,
String userName,
String createDate,
String modifiedDate,
String parentStructureId,
String classNameId,
String structureKey,
String version,
String name,
String description,
String definition,
String storageType,
String customtype
) {
this.uuid = uuid;
this.structureId = structureId;
this.groupId = groupId;
this.companyId = companyId;
this.userId = userId;
this.userName = userName;
this.createDate = createDate;
this.modifiedDate = modifiedDate;
this.parentStructureId = parentStructureId;
this.classNameId = classNameId;
this.structureKey = structureKey;
this.version = version;
this.name = name;
this.description = description;
this.definition = definition;
this.storageType = storageType;
this.customtype = customtype;
}
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<>();
if (structureId == null || structureId.length() == 0) {
errors.add(new ValidationError("structureId", "No structureId was given."));
}
if(errors.size() > 0) {
return errors;
}
return null;
}
}
| 22.887755 | 79 | 0.724922 |
4176089ced9735f7a4f296ce1d6d89d024c2aef8 | 1,244 | /**
* Definition of Events
*/
package eventbus2;
public interface Event{
public int filter();
}
/**
*
* Example Level1 Market Data Event published by the publisher
*
*/
class MarketDataL1Event implements Event{
/**
* Event Filters
*/
public static final int OPEN = 1;
public static final int ALL = 2;
public static final int CLOSE = 3;
MarketDataL1Event(){
this.filter=ALL;
}
MarketDataL1Event(int filter){
this.filter=filter;
}
public int filter;
@Override
public int filter() {
// TODO Auto-generated method stub
return this.filter;
}
}
/**
*
* Another example of event - Level2 Market Data
*
*/
class MarketDataL2Event implements Event{
public static final int OPEN = 1;
public static final int ALL = 2;
public static final int CLOSE = 3;
MarketDataL2Event(int filter){
this.filter = filter;
}
MarketDataL2Event(){
this.filter=OPEN;
}
public int filter;
@Override
public int filter() {
return this.filter;
}
}
/**
* Publisher sends out Exit or End of day event
*/
class ExitEvent implements Event{
public static final int EXITEVENT = 999;//To terminate the queue polling.
ExitEvent(int filter){
}
ExitEvent(){
}
@Override
public int filter() {
return EXITEVENT;
}
}
| 17.521127 | 74 | 0.692122 |
8b33eef55fcacba1b8e737cfc4abb59b4476b4d2 | 17,766 | package hu.unideb.inf.kondibazis.szolg.test;
import hu.unideb.inf.kondibazis.db.entitas.Konditerem;
import hu.unideb.inf.kondibazis.db.entitas.KonditeremBerlet;
import hu.unideb.inf.kondibazis.db.entitas.KonditeremTag;
import hu.unideb.inf.kondibazis.db.tarolo.KonditeremTagTarolo;
import hu.unideb.inf.kondibazis.szolg.impl.KonditeremTagSzolgaltatasImpl;
import hu.unideb.inf.kondibazis.szolg.mapper.KonditeremMapper;
import hu.unideb.inf.kondibazis.szolg.vo.KonditeremBerletVo;
import hu.unideb.inf.kondibazis.szolg.vo.KonditeremTagVo;
import hu.unideb.inf.kondibazis.szolg.vo.KonditeremVo;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.*;
import org.mockito.runners.MockitoJUnitRunner;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@RunWith(MockitoJUnitRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class KonditeremTagTest {
@Mock
private KonditeremTagTarolo konditeremTagTarolo;
@Spy
@InjectMocks
private KonditeremTagSzolgaltatasImpl konditeremTagSzolgaltatas;
private static Konditerem tesztKonditeremA;
private static Konditerem tesztKonditeremB;
private static List<KonditeremBerlet> tesztKonditeremABerletei = new ArrayList<>();
private static List<KonditeremBerlet> tesztKonditeremBBerletei = new ArrayList<>();
private static List<KonditeremTag> tesztKonditeremATagjai = new ArrayList<>();
private static List<KonditeremTag> tesztKonditeremBTagjai = new ArrayList<>();
@BeforeClass
public static void setUpClass() {
Konditerem ujKonditerem1 = new Konditerem();
ujKonditerem1.setId(1L);
ujKonditerem1.setKonditeremNeve("TezstKonditeremNev");
ujKonditerem1.setFelhasznalonev("TesztKonditerem");
ujKonditerem1.setJelszo("TesztJelszo");
ujKonditerem1.setRegisztralasDatuma(LocalDate.now());
ujKonditerem1.setKonditeremTagok(new ArrayList<>());
ujKonditerem1.setKonditeremBerletek(new ArrayList<>());
ujKonditerem1.setKonditeremElerhetosegek(new ArrayList<>());
tesztKonditeremA = ujKonditerem1;
Konditerem ujKonditerem2 = new Konditerem();
ujKonditerem2.setId(2L);
ujKonditerem2.setKonditeremNeve("TezstKonditeremNev");
ujKonditerem2.setFelhasznalonev("TesztKonditerem");
ujKonditerem2.setJelszo("TesztJelszo");
ujKonditerem2.setRegisztralasDatuma(LocalDate.now());
ujKonditerem2.setKonditeremTagok(new ArrayList<>());
ujKonditerem2.setKonditeremBerletek(new ArrayList<>());
ujKonditerem2.setKonditeremElerhetosegek(new ArrayList<>());
tesztKonditeremB = ujKonditerem2;
KonditeremBerlet ujKonditeremBerlet1 = new KonditeremBerlet();
ujKonditeremBerlet1.setId(3L);
ujKonditeremBerlet1.setBerletNeve("TesztHavi");
ujKonditeremBerlet1.setBerletAra(10000);
ujKonditeremBerlet1.setBerletTipusa("Havi");
ujKonditeremBerlet1.setMennyiAlkalom(0);
ujKonditeremBerlet1.setMennyiHonap(1);
ujKonditeremBerlet1.setMennyiNap(0);
ujKonditeremBerlet1.setKonditerem(tesztKonditeremA);
KonditeremBerlet ujKonditeremBerlet2 = new KonditeremBerlet();
ujKonditeremBerlet2.setId(4L);
ujKonditeremBerlet2.setBerletNeve("Teszt2Napos");
ujKonditeremBerlet2.setBerletAra(10000);
ujKonditeremBerlet2.setBerletTipusa("2 napos");
ujKonditeremBerlet2.setMennyiAlkalom(2);
ujKonditeremBerlet2.setMennyiHonap(0);
ujKonditeremBerlet2.setMennyiNap(0);
ujKonditeremBerlet2.setKonditerem(tesztKonditeremA);
KonditeremBerlet ujKonditeremBerlet3 = new KonditeremBerlet();
ujKonditeremBerlet3.setId(5L);
ujKonditeremBerlet3.setBerletNeve("TesztHavi");
ujKonditeremBerlet3.setBerletAra(10000);
ujKonditeremBerlet3.setBerletTipusa("Havi");
ujKonditeremBerlet3.setMennyiAlkalom(0);
ujKonditeremBerlet3.setMennyiHonap(1);
ujKonditeremBerlet3.setMennyiNap(0);
ujKonditeremBerlet3.setKonditerem(tesztKonditeremB);
KonditeremBerlet ujKonditeremBerlet4 = new KonditeremBerlet();
ujKonditeremBerlet2.setId(6L);
ujKonditeremBerlet2.setBerletNeve("Teszt2Napos");
ujKonditeremBerlet2.setBerletAra(10000);
ujKonditeremBerlet2.setBerletTipusa("2 napos");
ujKonditeremBerlet2.setMennyiAlkalom(2);
ujKonditeremBerlet2.setMennyiHonap(0);
ujKonditeremBerlet2.setMennyiNap(0);
ujKonditeremBerlet2.setKonditerem(tesztKonditeremB);
KonditeremTag ujTag1 = new KonditeremTag();
ujTag1.setId(7L);
ujTag1.setTagVezeteknev("Ujtag1Vezeteknev");
ujTag1.setTagKeresztnev("Ujtag1Keresztnev");
ujTag1.setTagNeve(ujTag1.getTagVezeteknev() + " " + ujTag1.getTagKeresztnev());
ujTag1.setTagNeme("Nő");
ujTag1.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag1.setTagKora(20);
ujTag1.setVasaroltBerletNeve("BerletNeve1");
ujTag1.setVasaroltBerletTipusa("Időkorlátos bérlet");
ujTag1.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag1.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag1.setTagVarosa("Varos1");
ujTag1.setTagMegyeje("Megye1");
ujTag1.setKonditeremBerlet(ujKonditeremBerlet1);
ujTag1.setKonditerem(tesztKonditeremA);
KonditeremTag ujTag2 = new KonditeremTag();
ujTag2.setId(8L);
ujTag2.setTagVezeteknev("Ujtag2Vezeteknev");
ujTag2.setTagKeresztnev("Ujtag2Keresztnev");
ujTag2.setTagNeve(ujTag1.getTagVezeteknev() + " " + ujTag1.getTagKeresztnev());
ujTag2.setTagNeme("Férfi");
ujTag2.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag2.setTagKora(20);
ujTag2.setVasaroltBerletNeve("BerletNeve2");
ujTag2.setVasaroltBerletTipusa("Alkalmas bérlet");
ujTag2.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag2.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag2.setTagVarosa("Varos2");
ujTag2.setTagMegyeje("Megye2");
ujTag2.setKonditeremBerlet(ujKonditeremBerlet2);
ujTag2.setKonditerem(tesztKonditeremA);
KonditeremTag ujTag3 = new KonditeremTag();
ujTag3.setId(9L);
ujTag3.setTagVezeteknev("Ujtag3Vezeteknev");
ujTag3.setTagKeresztnev("Ujtag3Keresztnev");
ujTag3.setTagNeve(ujTag1.getTagVezeteknev() + " " + ujTag1.getTagKeresztnev());
ujTag3.setTagNeme("Férfi");
ujTag3.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag3.setTagKora(20);
ujTag3.setVasaroltBerletNeve("BerletNeve3");
ujTag3.setVasaroltBerletTipusa("Iődkorlátos bérlet");
ujTag3.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag3.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag3.setTagVarosa("Varos3");
ujTag3.setTagMegyeje("Megye3");
ujTag3.setKonditeremBerlet(ujKonditeremBerlet3);
ujTag3.setKonditerem(tesztKonditeremA);
KonditeremTag ujTag4 = new KonditeremTag();
ujTag4.setId(10L);
ujTag4.setTagVezeteknev("Ujtag4Vezeteknev");
ujTag4.setTagKeresztnev("Ujtag4Keresztnev");
ujTag4.setTagNeve(ujTag1.getTagVezeteknev() + " " + ujTag1.getTagKeresztnev());
ujTag4.setTagNeme("Nő");
ujTag4.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag4.setTagKora(20);
ujTag4.setVasaroltBerletNeve("BerletNeve4");
ujTag4.setVasaroltBerletTipusa("Időkorlátos bérlet");
ujTag4.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag4.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag4.setTagVarosa("Varos4");
ujTag4.setTagMegyeje("Megye4");
ujTag4.setKonditeremBerlet(ujKonditeremBerlet4);
ujTag4.setKonditerem(tesztKonditeremB);
KonditeremTag ujTag5 = new KonditeremTag();
ujTag5.setId(11L);
ujTag5.setTagVezeteknev("Ujtag5Vezeteknev");
ujTag5.setTagKeresztnev("Ujtag5Keresztnev");
ujTag5.setTagNeve(ujTag1.getTagVezeteknev() + " " + ujTag1.getTagKeresztnev());
ujTag5.setTagNeme("Férfi");
ujTag5.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag5.setTagKora(20);
ujTag5.setVasaroltBerletNeve("BerletNeve5");
ujTag5.setVasaroltBerletTipusa("Időkorlátos bérlet");
ujTag5.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag5.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag5.setTagVarosa("Varos5");
ujTag5.setTagMegyeje("Megye5");
ujTag5.setKonditeremBerlet(ujKonditeremBerlet3);
ujTag5.setKonditerem(tesztKonditeremB);
KonditeremTag ujTag6 = new KonditeremTag();
ujTag6.setId(12L);
ujTag6.setTagVezeteknev("Ujtag6Vezeteknev");
ujTag6.setTagKeresztnev("Ujtag6Keresztnev");
ujTag6.setTagNeve(ujTag1.getTagVezeteknev() + " " + ujTag1.getTagKeresztnev());
ujTag6.setTagNeme("Nő");
ujTag6.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag6.setTagKora(20);
ujTag6.setVasaroltBerletNeve("BerletNeve6");
ujTag6.setVasaroltBerletTipusa("Alkalmas bérlet");
ujTag6.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag6.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag6.setTagVarosa("Varos6");
ujTag6.setTagMegyeje("Megye6");
ujTag6.setKonditeremBerlet(ujKonditeremBerlet3);
ujTag6.setKonditerem(tesztKonditeremB);
tesztKonditeremA.getKonditeremBerletek().addAll(Arrays.asList(ujKonditeremBerlet1, ujKonditeremBerlet2));
tesztKonditeremA.getKonditeremTagok().addAll(Arrays.asList(ujTag1, ujTag2, ujTag3));
tesztKonditeremB.getKonditeremBerletek().addAll(Arrays.asList(ujKonditeremBerlet3, ujKonditeremBerlet4));
tesztKonditeremB.getKonditeremTagok().addAll(Arrays.asList(ujTag4, ujTag5, ujTag6));
tesztKonditeremABerletei.addAll(Arrays.asList(ujKonditeremBerlet1, ujKonditeremBerlet2));
tesztKonditeremBBerletei.add(ujKonditeremBerlet4);
tesztKonditeremATagjai.addAll(Arrays.asList(ujTag1, ujTag2, ujTag3));
tesztKonditeremBTagjai.addAll(Arrays.asList(ujTag4, ujTag5, ujTag6));
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
Mockito.when(konditeremTagTarolo.save(Mockito.any(KonditeremTag.class)))
.thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
if (((KonditeremTag) args[0]).getId() == null) {
((KonditeremTag) args[0]).setId(87L);
}
return args[0];
});
Mockito.when(konditeremTagTarolo.findOne(Mockito.any(Long.class)))
.thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
switch (((Long) args[0]).intValue()) {
case 7:
return tesztKonditeremATagjai.get(0);
case 8:
return tesztKonditeremATagjai.get(1);
case 9:
return tesztKonditeremATagjai.get(2);
default:
return null;
}
});
Mockito.when(konditeremTagTarolo.findByKonditerem(Mockito.any(Konditerem.class)))
.thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
if (((Konditerem) args[0]).getId().equals(tesztKonditeremA.getId())) {
return tesztKonditeremATagjai;
} else if (((Konditerem) args[0]).getId().equals(tesztKonditeremB.getId())) {
return tesztKonditeremBTagjai;
} else {
return null;
}
});
}
@Test
public void letrehozKonditeremTagotTeszt() {
KonditeremTagVo ujTag = new KonditeremTagVo();
ujTag.setTagVezeteknev("Ujtag1Vezeteknev");
ujTag.setTagKeresztnev("Ujtag1Keresztnev");
ujTag.setTagNeve(ujTag.getTagVezeteknev() + " " + ujTag.getTagKeresztnev());
ujTag.setTagNeme("Férfi");
ujTag.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag.setTagKora(20);
ujTag.setVasaroltBerletNeve("BerletNeve1");
ujTag.setVasaroltBerletTipusa("Havi1");
ujTag.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag.setTagVarosa("Varos1");
ujTag.setTagMegyeje("Megye1");
ujTag.setKonditeremBerlet(new KonditeremBerletVo());
ujTag.setKonditerem(KonditeremMapper.toVo(tesztKonditeremA));
KonditeremTagVo mentett = konditeremTagSzolgaltatas.leterehozTagot(ujTag);
Assert.assertNotNull(mentett);
Assert.assertNotNull(mentett.getId());
}
@Test
public void keresKonditeremTagokTeszt() {
KonditeremTagVo leszIlyenTag = konditeremTagSzolgaltatas.keresTagot(7L);
Assert.assertNotNull(leszIlyenTag);
KonditeremTagVo nemLeszIlyenTag = konditeremTagSzolgaltatas.keresTagot(20L);
Assert.assertNull(nemLeszIlyenTag);
}
@Test
public void frissitKonditeremTagotTeszt() {
KonditeremTagVo ujTag = new KonditeremTagVo();
ujTag.setTagVezeteknev("Ujtag1Vezeteknev");
ujTag.setTagKeresztnev("Ujtag1Keresztnev");
ujTag.setTagNeve(ujTag.getTagVezeteknev() + " " + ujTag.getTagKeresztnev());
ujTag.setTagNeme("Férfi");
ujTag.setTagSzuletesidatuma(LocalDate.now().minusMonths(12));
ujTag.setTagKora(20);
ujTag.setVasaroltBerletNeve("BerletNeve1");
ujTag.setVasaroltBerletTipusa("Havi1");
ujTag.setBerletVasarlasideje(LocalDate.now().minusWeeks(4));
ujTag.setBerletLejaratiIdeje(LocalDate.now().minusWeeks(2));
ujTag.setTagVarosa("Varos1");
ujTag.setTagMegyeje("Megye1");
ujTag.setKonditeremBerlet(new KonditeremBerletVo());
ujTag.setKonditerem(KonditeremMapper.toVo(tesztKonditeremA));
KonditeremTagVo mentett = konditeremTagSzolgaltatas.leterehozTagot(ujTag);
mentett.setTagVezeteknev("UjtagModositottVezeteknev");
mentett.setTagKeresztnev("Ujtag1Keresztnev");
mentett.setTagNeve(ujTag.getTagVezeteknev() + " " + ujTag.getTagKeresztnev());
KonditeremTagVo frissített = konditeremTagSzolgaltatas.frissitKonditeremTagot(mentett);
Assert.assertEquals("UjtagModositottVezeteknev", frissített.getTagVezeteknev());
}
@Test
public void konditeremOsszesTagjaTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremA);
List<KonditeremTagVo> konditeremTagjai = konditeremTagSzolgaltatas.konditeremOsszesTagja(konditerem);
Assert.assertNotNull(konditeremTagjai);
Assert.assertEquals(3, konditeremTagjai.size());
}
@Test
public void konditeremNoiTagjaiTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremA);
List<KonditeremTagVo> konditeremNoiTagjai = konditeremTagSzolgaltatas.noiTagok(konditerem);
Assert.assertNotNull(konditeremNoiTagjai);
Assert.assertEquals(1, konditeremNoiTagjai.size());
}
@Test
public void konditeremFerfiTagjaiTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremB);
List<KonditeremTagVo> konditeremFerfiTagjai = konditeremTagSzolgaltatas.ferfiTagok(konditerem);
Assert.assertNotNull(konditeremFerfiTagjai);
Assert.assertEquals(1, konditeremFerfiTagjai.size());
}
@Test
public void konditeremAlkalmasBerletuTagjaiTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremA);
List<KonditeremTagVo> konditeremAlkalmasBerletuTagjai = konditeremTagSzolgaltatas.alkalmasBerletuTagok(konditerem);
Assert.assertNotNull(konditeremAlkalmasBerletuTagjai);
Assert.assertEquals(1, konditeremAlkalmasBerletuTagjai.size());
}
@Test
public void konditeremIdokorlatosBerletuTagjaiTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremB);
List<KonditeremTagVo> konditeremIdokorlatosBerletuTagjai = konditeremTagSzolgaltatas.idokorlatosBerletuTagok(konditerem);
Assert.assertNotNull(konditeremIdokorlatosBerletuTagjai);
Assert.assertEquals(2, konditeremIdokorlatosBerletuTagjai.size());
}
@Test
public void konditeremLejartAlkalmasBerletuTagjaiTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremA);
List<KonditeremTagVo> konditeremLejartAlkalmasBerletuTagjai = konditeremTagSzolgaltatas.lejartAlkalmasBerletuTagok(konditerem);
Assert.assertNotNull(konditeremLejartAlkalmasBerletuTagjai);
Assert.assertEquals(1, konditeremLejartAlkalmasBerletuTagjai.size());
}
@Test
public void konditeremLejartIdokorlatosBerletuTagjaiTeszt() {
KonditeremVo konditerem = KonditeremMapper.toVo(tesztKonditeremB);
List<KonditeremTagVo> konditeremLejartIdokorlatosBerletuTagjai = konditeremTagSzolgaltatas.lejartIdokorlatosBerletuTagok(konditerem);
Assert.assertNotNull(konditeremLejartIdokorlatosBerletuTagjai);
Assert.assertEquals(2, konditeremLejartIdokorlatosBerletuTagjai.size());
}
}
| 43.758621 | 141 | 0.70224 |
0ebb57eaae2b8f02c3adc1162c36232f52698255 | 9,233 | package iiit.speech.dialog;
import android.graphics.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import iiit.speech.domain.HealthDomain;
import iiit.speech.itra.R;
import iiit.speech.itra.VaidyaActivity;
import iiit.speech.nlu.NLU;
/**
* Created by brij on 15/9/15.
*/
public class DiagnosisState extends DialogState {
private VaidyaActivity app;
private NLU nlu;
public boolean sym_Expain_Flag = false;
private Map<Integer, Set<String>> possible_symptoms;
private Set<String> possible_diseases;
private String symptom_toask;
private List<String> already_asked_symptoms;
private boolean expect_binary = false;
public DiagnosisState(VaidyaActivity a, NLU nlu1) {
entered = false;
app = a;
nlu = nlu1;
this.setName("diagnosis");
already_asked_symptoms = new ArrayList<>();
}
private Integer[] intersect(Integer[] a, Integer[] b) {
Integer[] res = new Integer[a.length];
for(int i = 0; i < a.length; i++) {
res[i] = a[i] * b[i];
}
return res;
}
private List<Integer> getOneIndices(Integer[] a) {
List<Integer> idx = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i] == 1) idx.add(i);
}
return idx;
}
@Override
public void onEntry() {
System.out.println("+++++++++++++++++ Diagnosis state entered +++++++++++++++++++++");
if(app.langName.equals("_te")) {
app.speakOut(app.getString(R.string.initial_symps), app.getString(R.string.initial_symps_te));
}
else{
app.speakOut(app.getString(R.string.initial_symps),null);
}
// Set appropriate grammar
current_grammar = app.BINARY_RESPONSE;
entered = true;
next_state = "diagnosis";
//expect_binary = false;
Integer[] final_symp_vec = new Integer[((HealthDomain)domain).SYMPTOM_VEC_DIM];
Arrays.fill(final_symp_vec, 1);
Map<Integer, Boolean> ack_symptoms = ((HealthDomain)domain).getSymptoms();
for (Map.Entry<Integer, Boolean> e: ack_symptoms.entrySet()) {
Integer [] symp_vector = ((HealthDomain)domain).SYMPTOM_VECTOR.get(e.getKey());
System.out.println("Vector for =========> " + e.getKey());
printIntArray(symp_vector);
System.out.println("Final vector : before =========> ");
printIntArray(final_symp_vec);
final_symp_vec = intersect(final_symp_vec, symp_vector);
System.out.println("Final vector : after =========> ");
printIntArray(final_symp_vec);
}
possible_diseases = new HashSet<>();
for (Integer idx: getOneIndices(final_symp_vec)) {
possible_diseases.add(((HealthDomain)domain).DISEASE_IDX.get(idx));
}
if(app.langName.equals("_te")) {
app.speakOut(app.getString(R.string.disease_count, possible_diseases.size()), app.getString(R.string.disease_count_te, possible_diseases.size()));
}
else{
app.speakOut(app.getString(R.string.disease_count, possible_diseases.size()), null);
}
// Speak out if there are less than 5 diseases
if (possible_diseases.size() < 5) {
for (String dis: possible_diseases) {
app.speakOut(dis.replaceAll("_", " "), null);
}
}
// If there are more than one possible disease then ask for more symptoms to resolve
if (possible_diseases.size() > 1) {
for (String dis: possible_diseases) {
System.out.println(dis.replaceAll("_", " "));
}
getPossibleSymptoms();
}
if (possible_diseases.size() == 0) {
conclude = true;
next_state = "greet";
current_grammar = app.GREET_RESPONSE;
}
}
@Override
public void onRecognize(String hyp) {
sym_Expain_Flag = false;
if (expect_binary) {
System.out.println("Resolving symtom =========> " + symptom_toask);
if (nlu.resolveSymptomQueryHyp(hyp).equalsIgnoreCase("yes")) {
possible_diseases = possible_symptoms.get(((HealthDomain)domain).SYMPTOM_CID.get(symptom_toask));
System.out.println("Remaining diseases ============>>>>");
for (String rdis : possible_diseases) {
System.out.println(rdis);
}
} else if (nlu.resolveSymptomQueryHyp(hyp).equalsIgnoreCase("no")) {
possible_diseases.removeAll(possible_symptoms.get(((HealthDomain)domain).SYMPTOM_CID.get(symptom_toask)));
System.out.println("Remaining diseases ============>>>>");
for (String rdis : possible_diseases) {
System.out.println(rdis);
}
} else {
((HealthDomain) domain).symptom_explain = symptom_toask;
conclude = true;
sym_Expain_Flag = true;
}
already_asked_symptoms.add(symptom_toask);
}
if(!sym_Expain_Flag) {
app.sendChatMessage(true, "Disease count = " + possible_diseases.size(), null);
if (possible_diseases.size() > 1) {
getPossibleSymptoms();
} else {
for (String d : possible_diseases) {
d = d.replaceAll("_", " ");
if(app.langName.equals("_te")) {
app.speakOut(app.getString(R.string.probable_diagnosis, d), app.getString(R.string.probable_diagnosis_te, d));
}
else{
app.speakOut(app.getString(R.string.probable_diagnosis, d), null);
}
app.appendColoredText(app.result_text, "Diagnosis = " + d, Color.WHITE);
((HealthDomain) domain).setDisease(d);
conclude = true;
break;
}
}
}
}
private void getPossibleSymptoms() {
Integer[] dis_vec;
Integer poss_sym;
possible_symptoms = new HashMap<>();
Set<String> dis_list;
for (String dis: possible_diseases) {
dis_vec = ((HealthDomain)domain).DISEASE_VECTOR.get(dis);
System.out.println("Vector for disease====================>" + dis);
printIntArray(dis_vec);
for (Integer idx: getOneIndices(dis_vec)) {
poss_sym = idx;
System.out.println("Poss Sym===================>" + poss_sym);
if(poss_sym != null) {
dis_list = possible_symptoms.get(poss_sym);
if (dis_list == null) {
dis_list = new HashSet<>();
possible_symptoms.put(poss_sym, dis_list);
}
dis_list.add(dis);
}
}
}
int Dc = possible_diseases.size() / 2;
symptom_toask = null;
int min_dif = 9999;
for (Map.Entry<Integer, Set<String>> e: possible_symptoms.entrySet()) {
if (!already_asked_symptoms.contains(e.getKey())) {
System.out.println("Symptom ==> " + e.getKey() + " ; disease count ==>" + e.getValue().size());
for (String cdis : e.getValue()) {
System.out.println(cdis);
}
if (Math.abs(Dc - e.getValue().size()) < min_dif) {
symptom_toask = ((HealthDomain)domain).LCONCEPT_SYMPTOM_MAP.get(app.langName).get(e.getKey());
min_dif = Math.abs(Dc - e.getValue().size()) ;
}
}
}
if(app.langName.equals("_te")) {
app.speakOut(app.getString(R.string.shortlist_symp, symptom_toask.replaceAll("_", " ")), app.getString(R.string.shortlist_symp_te, symptom_toask.replaceAll("_", " ")));
}
else{
app.speakOut(app.getString(R.string.shortlist_symp, symptom_toask.replaceAll("_", " ")), null);
}
current_grammar = app.SYMPTOM_QUERY_RESPONSE;
expect_binary = true;
}
@Override
public void onExit() {
if(sym_Expain_Flag) {
System.out.println("1");
next_state = "symptom_details";
//next_state = "disease_details";
}
else if (possible_diseases.size() == 1) {
System.out.println("2");
next_state = "disease_details";
} else {
System.out.println("3");
next_state = "greet";
}
System.out.println("Next state : " + next_state);
}
void printIntArray(Integer [] arr) {
int len = arr.length;
for (int i = 0; i < len; i++) {
System.out.print(String.valueOf(arr[i]) + " ");
}
System.out.println();
}
}
| 37.685714 | 180 | 0.5515 |
e6297e61ebc772439972ac2369d4c99256631901 | 3,754 | import java.util.Scanner;
public class Bank1
{
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int userInput ;
//System.out.println(userInput); //this is use to test weather scanner works or not
int size=0; // id of customer
double[] accountBalance = new double[250];
String[] accountName = new String[250];
for(;true;) // it is simply a infinite loop to take input untill user press quit (0) , Some compilers (with warnings turned all the way up) will complain that while(true) is a conditional statement that can never fail, whereas they are happy with for (;;)
{
System.out.println("\n --------Bank Admin(SOUMYA KANTI MANDAL) Menu---------- \n");
System.out.println("plz enter a menu option here :");
System.out.println("1. Add customer To The Bank ");
System.out.println("2. Change customer Name In The Bank");
System.out.println("3. check Account Balance ");
System.out.println("4. Modify Account Balance ");
System.out.println("5. Summary Of All Bank Accounts");
System.out.println("0. Quit From Here");
userInput =input.nextInt();
if(userInput == 1)
{
System.out.println("Bank customer Details ");
System.out.println("plz enter a account balance : ");
double balance =input.nextDouble();
accountBalance[size] = balance ;
System.out.println("plz enter the account name : ");
input.nextLine();
String name =input.nextLine();
accountName[size] = name ;
System.out.println("New Customer ID is :"+ size + "\n");
size=size+1;
}
else if(userInput == 2)
{
System.out.println("ok, so you want to change the customer name ? ");
System.out.println("Plz enter the Customer ID to change the name :");
int index =input.nextInt();
System.out.println("Plz type Customer New Name :");
input.nextLine();
accountName[index] =input.nextLine();
}
else if(userInput == 3)
{
System.out.println(" Check Your Account Balance :");
System.out.println("Plz enter the Customer ID to Check Balance :");
int index=input.nextInt(); // we name it again (index) because we use it in diffrent block otherwise we have to name it some other variable
double balance =accountBalance[index];
System.out.println("The Customer has Rs " + balance + " In His Account \n ");
}
else if(userInput == 4)
{
System.out.println(" Modify Your Account Balance :");
System.out.println("Plz enter the Customer ID to Modify Balance :");
int index=input.nextInt(); // we name it again (index) because we use it in diffrent block otherwise we have to name it some other variable
System.out.println("plz input your new Balance :");
accountBalance[index] =input.nextDouble();
}
else if(userInput == 5)
{
System.out.println("Summary Of Bank Account Customers :");
double total = 0;
for( int i=0 ; i<size ; i++ )
{
total = total +accountBalance[i];
System.out.println(accountName[i] + " has Rs " + accountBalance[i] + " in the Account\n");
}
System.out.println("In Total, There is Rs " + total + " In the Bank \n \n");
}
else if(userInput == 0)
{
System.exit(0); // exit korbe 0 press a
}
else
{
System.out.println("ERROR : plz Enter Correct Input ");
}
}
}
}
| 41.711111 | 264 | 0.577251 |
39e998dbc9788043e237612c01be8db9362b6304 | 1,505 | package com.amankj.news.viewmodel;
import com.amankj.news.BaseTest;
import com.amankj.news.UseCaseProvider;
import com.amankj.news.usecase.TopHeadlinesUseCase;
import io.reactivex.Flowable;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.reactivestreams.Subscriber;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;
@PrepareForTest({UseCaseProvider.class})
public class TopHeadlinesViewModelTest extends BaseTest {
@Mock
private TopHeadlinesUseCase topHeadlinesUseCase;
private TopHeadlinesViewModel topHeadlinesViewModel;
private Flowable<Object> objectFlowable = new Flowable<Object>() {
@Override
protected void subscribeActual(Subscriber<? super Object> s) {
}
};
@Override
@Before
public void setUp() {
super.setUp();
PowerMockito.mockStatic(UseCaseProvider.class);
when(UseCaseProvider.getTopHeadlinesUseCase()).thenReturn(topHeadlinesUseCase);
when(topHeadlinesUseCase.getTopHeadlines()).thenReturn(objectFlowable);
topHeadlinesViewModel = new TopHeadlinesViewModel();
}
@Test
public void getArticleListObservable() {
topHeadlinesViewModel.getTopHeadlines();
verify(topHeadlinesUseCase, times(1)).getTopHeadlines();
}
} | 30.714286 | 87 | 0.757475 |
5b711884ef50e13aac0f0fc70a756a5f85207a32 | 87 | /**
* The home for all rest interfaces
*/
package fr.labri.progress.comet.endpoint;
| 14.5 | 41 | 0.712644 |
16bbcea49cfe3cc89d9534b5f3fcd67d289f9c1d | 3,148 | package de.unisiegen.gtitool.core.entities;
import de.unisiegen.gtitool.core.exceptions.alphabet.AlphabetException;
import de.unisiegen.gtitool.core.exceptions.state.StateException;
import de.unisiegen.gtitool.core.exceptions.transition.TransitionSymbolNotInAlphabetException;
import de.unisiegen.gtitool.core.exceptions.transition.TransitionSymbolOnlyOneTimeException;
/**
* The test class of the entities.
*
* @author Christian Fehler
* @version $Id$
*/
public class EntitiesTest
{
/**
* The main method.
*
* @param arguments The arguments.
*/
public static void main ( String [] arguments )
{
Symbol a = new DefaultSymbol ( "a" ); //$NON-NLS-1$
Symbol b = new DefaultSymbol ( "b" );//$NON-NLS-1$
Symbol c = new DefaultSymbol ( "c" );//$NON-NLS-1$
Stack stack = new DefaultStack ();
// stack abc
stack.push ( c );
stack.push ( b );
stack.push ( a );
System.out.println ( stack.peak ( 2 ) );
System.out.println ( stack );
System.out.println ( stack.pop () );
System.out.println ( stack );
Alphabet alphabet = null;
try
{
alphabet = new DefaultAlphabet ( a, b, c );
}
catch ( AlphabetException e )
{
e.printStackTrace ();
System.exit ( 1 );
}
Alphabet pushDownAlphabet = null;
try
{
pushDownAlphabet = new DefaultAlphabet ( a, b, c );
}
catch ( AlphabetException e )
{
e.printStackTrace ();
System.exit ( 1 );
}
State z0 = null;
State z1 = null;
State z2 = null;
try
{
z0 = new DefaultState ( alphabet, pushDownAlphabet, "z0", true, false );//$NON-NLS-1$
z1 = new DefaultState ( alphabet, pushDownAlphabet, "z1", false, false );//$NON-NLS-1$
z2 = new DefaultState ( alphabet, pushDownAlphabet, "z2", false, true );//$NON-NLS-1$
}
catch ( StateException e )
{
e.printStackTrace ();
System.exit ( 1 );
}
Transition t0 = null;
Transition t1 = null;
Transition t2 = null;
Transition t3 = null;
Transition t4 = null;
try
{
t0 = new DefaultTransition ( alphabet, pushDownAlphabet,
new DefaultWord (), new DefaultWord (), z0, z0, a, b );
t1 = new DefaultTransition ( alphabet, pushDownAlphabet,
new DefaultWord (), new DefaultWord (), z0, z1, c );
t2 = new DefaultTransition ( alphabet, pushDownAlphabet,
new DefaultWord (), new DefaultWord (), z1, z1, a, b );
t3 = new DefaultTransition ( alphabet, pushDownAlphabet,
new DefaultWord (), new DefaultWord (), z1, z2, c );
t4 = new DefaultTransition ( alphabet, pushDownAlphabet,
new DefaultWord (), new DefaultWord (), z2, z2, a, b, c );
System.out.println ( t0 );
System.out.println ( t1 );
System.out.println ( t2 );
System.out.println ( t3 );
System.out.println ( t4 );
}
catch ( TransitionSymbolNotInAlphabetException e )
{
e.printStackTrace ();
System.exit ( 1 );
}
catch ( TransitionSymbolOnlyOneTimeException e )
{
e.printStackTrace ();
System.exit ( 1 );
}
}
}
| 27.137931 | 94 | 0.609911 |
f003ea86cbc599b88ab8ce0a0cd3cca953415564 | 3,040 | package com.numberone.project.system.areaelectric.service.impl;
import java.util.List;
import java.util.ArrayList;
import com.numberone.framework.web.domain.Ztree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.numberone.project.system.areaelectric.mapper.AreaelectricMapper;
import com.numberone.project.system.areaelectric.domain.Areaelectric;
import com.numberone.project.system.areaelectric.service.IAreaelectricService;
import com.numberone.common.utils.text.Convert;
/**
* areaelectricService业务层处理
*
* @author sqalong
* @date 2021-01-11
*/
@Service
public class AreaelectricServiceImpl implements IAreaelectricService
{
@Autowired
private AreaelectricMapper areaelectricMapper;
/**
* 查询areaelectric
*
* @param id areaelectricID
* @return areaelectric
*/
@Override
public Areaelectric selectAreaelectricById(Long id)
{
return areaelectricMapper.selectAreaelectricById(id);
}
/**
* 查询areaelectric列表
*
* @param areaelectric areaelectric
* @return areaelectric
*/
@Override
public List<Areaelectric> selectAreaelectricList(Areaelectric areaelectric)
{
return areaelectricMapper.selectAreaelectricList(areaelectric);
}
/**
* 新增areaelectric
*
* @param areaelectric areaelectric
* @return 结果
*/
@Override
public int insertAreaelectric(Areaelectric areaelectric)
{
return areaelectricMapper.insertAreaelectric(areaelectric);
}
/**
* 修改areaelectric
*
* @param areaelectric areaelectric
* @return 结果
*/
@Override
public int updateAreaelectric(Areaelectric areaelectric)
{
return areaelectricMapper.updateAreaelectric(areaelectric);
}
/**
* 删除areaelectric对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteAreaelectricByIds(String ids)
{
return areaelectricMapper.deleteAreaelectricByIds(Convert.toStrArray(ids));
}
/**
* 删除areaelectric信息
*
* @param id areaelectricID
* @return 结果
*/
@Override
public int deleteAreaelectricById(Long id)
{
return areaelectricMapper.deleteAreaelectricById(id);
}
/**
* 查询areaelectric树列表
*
* @return 所有areaelectric信息
*/
@Override
public List<Ztree> selectAreaelectricTree()
{
List<Areaelectric> areaelectricList = areaelectricMapper.selectAreaelectricList(new Areaelectric());
List<Ztree> ztrees = new ArrayList<Ztree>();
for (Areaelectric areaelectric : areaelectricList)
{
Ztree ztree = new Ztree();
ztree.setId(areaelectric.getId());
ztree.setpId(areaelectric.getPid());
ztree.setName(areaelectric.getLargeareaname());
ztree.setTitle(areaelectric.getLargeareaname());
ztrees.add(ztree);
}
return ztrees;
}
}
| 25.546218 | 108 | 0.672697 |
2b641a7ef6749e1983892e160c0e2124d13e9aa6 | 341 | package me.melyukhov.messenger.common.packages;
import me.melyukhov.messenger.common.messages.TextMessage;
public class MessageFromClientPackage extends Package<TextMessage> {
private static final long serialVersionUID = 9146511765720612075L;
public MessageFromClientPackage(TextMessage message) {
super(message);
}
}
| 26.230769 | 69 | 0.791789 |
b420fd2788c9bdcba207075f57d2b6975e881c0d | 237 | import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ FileNotFoundTest.class, InvalidInputFormatTest.class, InvalidArgumentTest.class})
public class SparkIndependentTestsSuite {
}
| 26.333333 | 103 | 0.827004 |
aa4632c53cbeb9d05f7abb91518103b09c0c5e81 | 511 | package jenkins.model;
import org.junit.Test;
import static org.junit.Assert.*;
public class IDStrategyTest {
@Test public void hex() throws Exception {
String fn = "$0041";
IdStrategy.CaseSensitive cs = new IdStrategy.CaseSensitive();
assertEquals("A", cs.idFromFilename(fn));
}
@Test public void empty() throws Exception {
String fn = "";
IdStrategy.CaseSensitive cs = new IdStrategy.CaseSensitive();
assertEquals("", cs.idFromFilename(fn));
}
} | 25.55 | 69 | 0.659491 |
e98a89fe9c380c781529ce3292a71e0a94db15b0 | 212 | package com.fractal.model;
public class Debouncer {
private int lastvalue = 0;
public int debounce(int value) {
int ret = value < lastvalue ? 1 : 0;
lastvalue = value;
return ret;
}
}
| 15.142857 | 39 | 0.622642 |
45cae4badae368e2a5b687a1459431ede6528375 | 11,110 | /*
* 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.netbeans.modules.tomcat5.config;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.deploy.spi.DeploymentManager;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.modules.j2ee.deployment.common.api.ConfigurationException;
import org.netbeans.modules.j2ee.deployment.common.api.Datasource;
import org.netbeans.modules.j2ee.deployment.common.api.DatasourceAlreadyExistsException;
import org.netbeans.modules.j2ee.deployment.plugins.spi.DatasourceManager;
import org.netbeans.modules.tomcat5.deploy.TomcatManager;
import org.netbeans.modules.tomcat5.deploy.TomcatManager.TomcatVersion;
import org.netbeans.modules.tomcat5.config.gen.GlobalNamingResources;
import org.netbeans.modules.tomcat5.config.gen.Parameter;
import org.netbeans.modules.tomcat5.config.gen.ResourceParams;
import org.netbeans.modules.tomcat5.config.gen.Server;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* DataSourceManager implementation
*
* @author sherold
*/
public class TomcatDatasourceManager implements DatasourceManager {
private static final Logger LOGGER = Logger.getLogger(TomcatDatasourceManager.class.getName());
private final TomcatManager tm;
/**
* Creates a new instance of TomcatDatasourceManager
*/
public TomcatDatasourceManager(DeploymentManager dm) {
tm = (TomcatManager) dm;
}
@CheckForNull
public static Datasource createDatasource(String name, String data) {
Properties props = new Properties();
try {
props.load(new StringReader(data));
} catch (IOException ex) {
LOGGER.log(Level.WARNING, null, ex);
return null;
}
String username = props.getProperty("userName"); // NOI18N
String url = props.getProperty("jdbcUrl"); // NOI18N
String password = props.getProperty("password"); // NOI18N
String driverClassName = props.getProperty("jdbcDriver"); // NOI18N
if (name != null && username != null && url != null && driverClassName != null) {
// return the datasource only if all the needed params are non-null except the password param
return new TomcatDatasource(username, url, password, name, driverClassName);
}
return null;
}
@Override
public Set<Datasource> getDatasources() throws ConfigurationException {
Set<Datasource> result = new HashSet<Datasource>();
result.addAll(getTomcatDatasources());
result.addAll(getTomeeDatasources());
return result;
}
/**
* Get the global datasources defined in the GlobalNamingResources element
* in the server.xml configuration file.
*/
public Set<Datasource> getTomcatDatasources() {
HashSet<Datasource> result = new HashSet<Datasource>();
File serverXml = tm.getTomcatProperties().getServerXml();
Server server;
try {
server = Server.createGraph(serverXml);
} catch (IOException e) {
// ok, log it and give up
Logger.getLogger(TomcatDatasourceManager.class.getName()).log(Level.INFO, null, e);
return Collections.<Datasource>emptySet();
} catch (RuntimeException e) {
// server.xml file is most likely not parseable, log it and give up
Logger.getLogger(TomcatDatasourceManager.class.getName()).log(Level.INFO, null, e);
return Collections.<Datasource>emptySet();
}
GlobalNamingResources[] globalNamingResources = server.getGlobalNamingResources();
if (globalNamingResources.length > 0) {
// only one GlobalNamingResources element is allowed
GlobalNamingResources globalNR = globalNamingResources[0];
if (tm.getTomcatVersion() != TomcatVersion.TOMCAT_50) {
// Tomcat 5.5.x or Tomcat 6.0.x
int length = globalNR.getResource().length;
for (int i = 0; i < length; i++) {
String type = globalNR.getResourceType(i);
if ("javax.sql.DataSource".equals(type)) { // NOI18N
String name = globalNR.getResourceName(i);
String username = globalNR.getResourceUsername(i);
String url = globalNR.getResourceUrl(i);
String password = globalNR.getResourcePassword(i);
String driverClassName = globalNR.getResourceDriverClassName(i);
if (name != null && username != null && url != null && driverClassName != null) {
// return the datasource only if all the needed params are non-null except the password param
result.add(new TomcatDatasource(username, url, password, name, driverClassName));
}
}
}
} else {
// Tomcat 5.0.x
int length = globalNR.getResource().length;
ResourceParams[] resourceParams = globalNR.getResourceParams();
for (int i = 0; i < length; i++) {
String type = globalNR.getResourceType(i);
if ("javax.sql.DataSource".equals(type)) { // NOI18N
String name = globalNR.getResourceName(i);
// find the resource params for the selected resource
for (int j = 0; j < resourceParams.length; j++) {
if (name.equals(resourceParams[j].getName())) {
Parameter[] params = resourceParams[j].getParameter();
HashMap paramNameValueMap = new HashMap(params.length);
for (Parameter parameter : params) {
paramNameValueMap.put(parameter.getName(), parameter.getValue());
}
String username = (String) paramNameValueMap.get("username"); // NOI18N
String url = (String) paramNameValueMap.get("url"); // NOI18N
String password = (String) paramNameValueMap.get("password"); // NOI18N
String driverClassName = (String) paramNameValueMap.get("driverClassName"); // NOI18N
if (username != null && url != null && driverClassName != null) {
// return the datasource only if all the needed params are non-null except the password param
result.add(new TomcatDatasource(username, url, password, name, driverClassName));
}
}
}
}
}
}
}
return result;
}
public Set<Datasource> getTomeeDatasources() {
if (!tm.isTomEE()) {
return Collections.emptySet();
}
File tomeeXml = tm.getTomcatProperties().getTomeeXml();
if (tomeeXml == null) {
return Collections.emptySet();
}
try {
try (InputStream is = new BufferedInputStream(new FileInputStream(tomeeXml))) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DatasourceHandler handler = new DatasourceHandler();
saxParser.parse(is, handler);
return handler.getDataSources();
} catch (IOException e) {
// ok, log it and give up
Logger.getLogger(TomcatDatasourceManager.class.getName()).log(Level.INFO, null, e);
}
} catch (ParserConfigurationException | SAXException ex) {
// ok, log it and give up
Logger.getLogger(TomcatDatasourceManager.class.getName()).log(Level.INFO, null, ex);
}
return Collections.<Datasource>emptySet();
}
@Override
public void deployDatasources(Set<Datasource> datasources)
throws ConfigurationException, DatasourceAlreadyExistsException {
// nothing needs to be done here
}
private static class DatasourceHandler extends DefaultHandler {
private final StringBuilder content = new StringBuilder();
private final Set<Datasource> dataSources = new HashSet<>();
private boolean isResource = false;
private String name;
public Set<Datasource> getDataSources() {
return dataSources;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
content.setLength(0);
if ("Resource".equals(qName) // NOI18N
&& "javax.sql.DataSource".equals(attributes.getValue("type")) // NOI18N
&& attributes.getValue("id") != null) { // NOI18N
isResource = true;
name = attributes.getValue("id"); // NOI18N
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (isResource) {
if ("Resource".equals(qName)) { // NOI18N
dataSources.add(createDatasource(name, content.toString()));
isResource = false;
name = null;
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (isResource) {
content.append(ch, start, length);
}
}
}
}
| 43.740157 | 129 | 0.611971 |
b6891f0e7d134139da9d77c882ecd65d06b40d67 | 2,803 | /**
* Copyright © 2016 Alibaba Inc . All rights reserved.
*
* @Title: Callback.java
* @Prject: tsmock
* @Package: com.alibaba.tsmock.model
* @Description: TODO
* @author: qinjun.qj
* @date: 2016年12月27日下午1:58:26
* @version: v1.0
*/
package com.alibaba.tsmock.po.http;
/**
* The Class Callback.
*
* @ClassName: Callback
* @Description: TODO
* @author: qinjun.qj
* @date: 2016年12月27日下午1:58:26
*/
public class HttpRouteCallback {
/** The type. */
private String type;
/** The info. */
private String info;
/** The value. */
private String value;
/** The sleep. */
private Integer sleep;
/** The script. */
private String script;
/**
* Instantiates a new callback.
*/
public HttpRouteCallback() {
}
/**
* Instantiates a new callback.
*
* @param type
* the type
* @param info
* the info
* @param value
* the value
* @param sleep
* the sleep
* @param script
* the script
* @Title:HttpRouteCallback
* @Description:TODO
*/
public HttpRouteCallback(final String type, final String info, final String value, Integer sleep, String script) {
super();
this.type = type;
this.info = info;
this.value = value;
this.sleep = sleep;
this.script = script;
}
/**
* Gets the type.
*
* @return the type
*/
public String getType() {
return type;
}
/**
* Sets the type.
*
* @param type
* the new type
*/
public void setType(final String type) {
this.type = type;
}
/**
* Gets the info.
*
* @return the info
*/
public String getInfo() {
return info;
}
/**
* Sets the info.
*
* @param info
* the new info
*/
public void setInfo(final String info) {
this.info = info;
}
/**
* Gets the value.
*
* @return the value
*/
public String getValue() {
return value;
}
/**
* Sets the value.
*
* @param value
* the new value
*/
public void setValue(final String value) {
this.value = value;
}
/**
* Gets the sleep.
*
* @return the sleep
*/
public Integer getSleep() {
return sleep;
}
/**
* Sets the sleep.
*
* @param sleep
* the new sleep
*/
public void setSleep(Integer sleep) {
this.sleep = sleep;
}
/**
* Gets the script.
*
* @return the script
*/
public String getScript() {
return script;
}
/**
* Sets the script.
*
* @param script
* the new script
*/
public void setScript(String script) {
this.script = script;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "HTTP Route Callback{" + "type=" + type + ", info='" + info + "'" + ", value='" + value + "'"
+ ", sleep=" + sleep + ", script='" + script + "'}";
}
}
| 15.836158 | 115 | 0.569033 |
887b9695560d94033fab820837337f628e6a1793 | 2,594 | package com.eu.habbo.messages.outgoing.friends;
import com.eu.habbo.habbohotel.messenger.MessengerBuddy;
import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.ServerMessage;
import com.eu.habbo.messages.outgoing.MessageComposer;
import com.eu.habbo.messages.outgoing.Outgoing;
import gnu.trove.set.hash.THashSet;
public class UserSearchResultComposer extends MessageComposer
{
private final THashSet<MessengerBuddy> users;
private final THashSet<MessengerBuddy> friends;
private final Habbo habbo;
public UserSearchResultComposer(THashSet<MessengerBuddy> users, THashSet<MessengerBuddy> friends, Habbo habbo)
{
this.users = users;
this.friends = friends;
this.habbo = habbo;
}
@Override
public ServerMessage compose()
{
this.response.init(Outgoing.UserSearchResultComposer);
THashSet<MessengerBuddy> u = new THashSet<MessengerBuddy>();
for(MessengerBuddy buddy : this.users)
{
if(!buddy.getUsername().equals(this.habbo.getHabboInfo().getUsername()) && !inFriendList(buddy))
{
u.add(buddy);
}
}
this.response.appendInt(this.friends.size());
for(MessengerBuddy buddy : this.friends)
{
this.response.appendInt(buddy.getId());
this.response.appendString(buddy.getUsername());
this.response.appendString(buddy.getMotto());
this.response.appendBoolean(false);
this.response.appendBoolean(false);
this.response.appendString("");
this.response.appendInt(1);
this.response.appendString(buddy.getLook());
this.response.appendString("");
}
this.response.appendInt(u.size());
for(MessengerBuddy buddy : u)
{
this.response.appendInt(buddy.getId());
this.response.appendString(buddy.getUsername());
this.response.appendString(buddy.getMotto());
this.response.appendBoolean(false);
this.response.appendBoolean(false);
this.response.appendString("");
this.response.appendInt(1);
this.response.appendString(buddy.getLook());
this.response.appendString("");
}
return this.response;
}
private boolean inFriendList(MessengerBuddy buddy)
{
for(MessengerBuddy friend : this.friends)
{
if(friend.getUsername().equals(buddy.getUsername()))
return true;
}
return false;
}
}
| 32.835443 | 114 | 0.634927 |
4b45927fb10e9774e6cdd109bec8dae18362e7b5 | 8,638 | /**
* 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.atlas.web.resources;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.atlas.AtlasClient;
import org.apache.atlas.utils.AtlasPerfTracer;
import org.apache.atlas.web.filters.AtlasCSRFPreventionFilter;
import org.apache.atlas.web.service.ServiceState;
import org.apache.atlas.web.util.Servlets;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import com.google.inject.Inject;
/**
* Jersey Resource for admin operations.
*/
@Path("admin")
@Singleton
public class AdminResource {
private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.AdminResource");
private static final String isCSRF_ENABLED = "atlas.rest-csrf.enabled";
private static final String BROWSER_USER_AGENT_PARAM = "atlas.rest-csrf.browser-useragents-regex";
private static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "atlas.rest-csrf.methods-to-ignore";
private static final String CUSTOM_HEADER_PARAM = "atlas.rest-csrf.custom-header";
private static final String isTaxonomyEnabled = "atlas.feature.taxonomy.enable";
private Response version;
private ServiceState serviceState;
@Inject
public AdminResource(ServiceState serviceState) {
this.serviceState = serviceState;
}
/**
* Fetches the thread stack dump for this application.
*
* @return json representing the thread stack dump.
*/
@GET
@Path("stack")
@Produces(MediaType.TEXT_PLAIN)
public String getThreadDump() {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "AdminResource.getThreadDump()");
}
ThreadGroup topThreadGroup = Thread.currentThread().getThreadGroup();
while (topThreadGroup.getParent() != null) {
topThreadGroup = topThreadGroup.getParent();
}
Thread[] threads = new Thread[topThreadGroup.activeCount()];
int nr = topThreadGroup.enumerate(threads);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nr; i++) {
builder.append(threads[i].getName()).append("\nState: ").
append(threads[i].getState()).append("\n");
String stackTrace = StringUtils.join(threads[i].getStackTrace(), "\n");
builder.append(stackTrace);
}
return builder.toString();
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Fetches the version for this application.
*
* @return json representing the version.
*/
@GET
@Path("version")
@Produces(Servlets.JSON_MEDIA_TYPE)
public Response getVersion() {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "AdminResource.getVersion()");
}
if (version == null) {
try {
PropertiesConfiguration configProperties = new PropertiesConfiguration("atlas-buildinfo.properties");
JSONObject response = new JSONObject();
response.put("Version", configProperties.getString("build.version", "UNKNOWN"));
response.put("Name", configProperties.getString("project.name", "apache-atlas"));
response.put("Description", configProperties.getString("project.description",
"Metadata Management and Data Governance Platform over Hadoop"));
// todo: add hadoop version?
// response.put("Hadoop", VersionInfo.getVersion() + "-r" + VersionInfo.getRevision());
version = Response.ok(response).build();
} catch (JSONException | ConfigurationException e) {
throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
}
}
return version;
} finally {
AtlasPerfTracer.log(perf);
}
}
@GET
@Path("status")
@Produces(Servlets.JSON_MEDIA_TYPE)
public Response getStatus() {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "AdminResource.getStatus()");
}
JSONObject responseData = new JSONObject();
try {
responseData.put(AtlasClient.STATUS, serviceState.getState().toString());
Response response = Response.ok(responseData).build();
return response;
} catch (JSONException e) {
throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
}
} finally {
AtlasPerfTracer.log(perf);
}
}
@GET
@Path("session")
@Produces(Servlets.JSON_MEDIA_TYPE)
public Response getUserProfile() {
JSONObject responseData = new JSONObject();
Boolean enableTaxonomy = null;
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "AdminResource.getUserProfile()");
}
PropertiesConfiguration configProperties = new PropertiesConfiguration("atlas-application.properties");
enableTaxonomy = new Boolean(configProperties.getString(isTaxonomyEnabled, "false"));
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userName = null;
Set<String> groups = new HashSet<String>();
if (auth != null) {
userName = auth.getName();
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
for (GrantedAuthority c : authorities) {
groups.add(c.getAuthority());
}
}
responseData.put(isCSRF_ENABLED, AtlasCSRFPreventionFilter.isCSRF_ENABLED);
responseData.put(BROWSER_USER_AGENT_PARAM, AtlasCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT);
responseData.put(CUSTOM_METHODS_TO_IGNORE_PARAM, AtlasCSRFPreventionFilter.METHODS_TO_IGNORE_DEFAULT);
responseData.put(CUSTOM_HEADER_PARAM, AtlasCSRFPreventionFilter.HEADER_DEFAULT);
responseData.put(isTaxonomyEnabled, enableTaxonomy);
responseData.put("userName", userName);
responseData.put("groups", groups);
Response response = Response.ok(responseData).build();
return response;
} catch (JSONException | ConfigurationException e) {
throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
} finally {
AtlasPerfTracer.log(perf);
}
}
}
| 39.990741 | 123 | 0.655823 |
ee70ff85ebf79ce7bab1a366b33b0a2cb5a5da7a | 2,313 | package cn.org.rookie.jeesdp.core.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
/**
* JSON工具类
*
* @author LIHAITAO
*/
public abstract class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
/**
* 将对象转为JSON字符串
*
* @param bean 要转换的实体
* @return 转换后JSON字符串
*/
public static String toJsonString(Object bean) {
try {
return MAPPER.writeValueAsString(bean);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将对象转为格式化的JSON字符串
*
* @param bean 要转换的实体
* @return 转换后JSON字符串
*/
public static String toIndentedJsonString(Object bean) {
try {
MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
String jsonString = MAPPER.writeValueAsString(bean);
MAPPER.disable(SerializationFeature.INDENT_OUTPUT);
return jsonString;
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将JSON字符串转为对象
*
* @param json JSON字符串
* @param type 要转换的对象的类型
* @param <T> 转换后的类型
* @return 转换后的对象
*/
public static <T> T toObject(String json, Class<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将字符串转换为JSON对象
*
* @param json 要转换的字符串
* @return 返回JSON对象
*/
public static JsonNode toJsonNode(String json) {
try {
return MAPPER.readTree(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 将实体转换为JSON对象
*
* @param bean 要转换的实体
* @return 返回JSON对象
*/
public static JsonNode toJsonNode(Object bean) {
return MAPPER.valueToTree(bean);
}
}
| 21.820755 | 74 | 0.589278 |
bd2e8bed19203ada4c47894e93d0ea987cbe4f64 | 3,421 | package test.tck.msgflow.callflows.recroute;
import java.util.Hashtable;
import javax.sip.SipListener;
import javax.sip.SipProvider;
import org.apache.log4j.Logger;
import test.tck.msgflow.callflows.AssertUntil;
import test.tck.msgflow.callflows.NetworkPortAssigner;
import test.tck.msgflow.callflows.ScenarioHarness;
/**
* @author M. Ranganathan
* @author Jeroen van Bemmel
*
*/
public class AbstractRecRouteTestCase extends ScenarioHarness implements
SipListener {
protected Shootist shootist;
private static Logger logger = Logger.getLogger("test.tck");
protected Shootme shootme;
private Proxy proxy;
private static final int TIMEOUT = 5000;
static {
if ( !logger.isAttached(console))
logger.addAppender(console);
}
// private Appender appender;
public AbstractRecRouteTestCase() {
super("TCPRecRouteTest", true);
try {
providerTable = new Hashtable();
} catch (Exception ex) {
logger.error("unexpected exception", ex);
fail("unexpected exception ");
}
}
public void setUp() {
try {
int shootistPort = NetworkPortAssigner.retrieveNextPort();
int shootmePort = NetworkPortAssigner.retrieveNextPort();
int proxyPort = NetworkPortAssigner.retrieveNextPort();
super.setUp(false);
shootist = new Shootist(shootistPort, proxyPort, getTiProtocolObjects());
SipProvider shootistProvider = shootist.createSipProvider();
providerTable.put(shootistProvider, shootist);
shootistProvider.addSipListener(this);
this.shootme = new Shootme(shootmePort, getTiProtocolObjects());
SipProvider shootmeProvider = shootme.createProvider();
providerTable.put(shootmeProvider, shootme);
shootmeProvider.addSipListener(this);
this.proxy = new Proxy(proxyPort, shootmePort, getRiProtocolObjects());
SipProvider provider = proxy.createSipProvider();
//provider.setAutomaticDialogSupportEnabled(false);
providerTable.put(provider, proxy);
provider.addSipListener(this);
getTiProtocolObjects().start();
if (getTiProtocolObjects() != getRiProtocolObjects())
getRiProtocolObjects().start();
} catch (Exception ex) {
logger.error("Unexpected exception",ex);
fail("unexpected exception ");
}
}
public void tearDown() {
try {
assertTrue(
"Should see an INFO",
AssertUntil.assertUntil(shootist.getAssertion(), TIMEOUT));
assertTrue(AssertUntil.assertUntil(shootme.getAssertion(), TIMEOUT));
assertTrue(
"INVITE should be seen by proxy"
+ "and Should see two INFO messages"
+ "and BYE should be seen by proxy"
+ "and ACK should be seen by proxy",
AssertUntil.assertUntil(proxy.getAssertion(), TIMEOUT));
super.tearDown();
Thread.sleep(2000);
this.providerTable.clear();
super.logTestCompleted();
} catch (Exception ex) {
logger.error("unexpected exception", ex);
fail("unexpected exception ");
}
}
}
| 30.274336 | 85 | 0.616779 |
689c56c5f44d892ab37911df6532890273d8708e | 3,718 | /*
*
* * Copyright 2022 EPAM Systems, Inc. (https://www.epam.com/)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*
*/
package com.epam.grid.engine.provider.host.slurm;
import com.epam.grid.engine.cmd.GridEngineCommandCompiler;
import com.epam.grid.engine.cmd.SimpleCmdExecutor;
import com.epam.grid.engine.entity.CommandResult;
import com.epam.grid.engine.entity.EngineType;
import com.epam.grid.engine.entity.HostFilter;
import com.epam.grid.engine.entity.Listing;
import com.epam.grid.engine.entity.host.Host;
import com.epam.grid.engine.entity.host.slurm.SlurmHost;
import com.epam.grid.engine.mapper.host.slurm.SlurmHostMapper;
import com.epam.grid.engine.provider.host.HostProvider;
import com.epam.grid.engine.provider.utils.CommandsUtils;
import com.epam.grid.engine.provider.utils.slurm.host.ScontrolShowNodeParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import java.util.List;
import java.util.stream.Collectors;
/**
* This is the implementation of the host provider for SLURM.
*
* @see com.epam.grid.engine.provider.host.HostProvider
*/
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(name = "grid.engine.type", havingValue = "SLURM")
public class SlurmHostProvider implements HostProvider {
private static final String FILTER = "filter";
private static final String SCONTROL_COMMAND = "scontrol";
private final SimpleCmdExecutor simpleCmdExecutor;
private final GridEngineCommandCompiler commandCompiler;
private final SlurmHostMapper slurmHostMapper;
@Override
public EngineType getProviderType() {
return EngineType.SLURM;
}
@Override
public Listing<Host> listHosts(final HostFilter hostFilter) {
final Context context = new Context();
context.setVariable(FILTER, hostFilter);
final String[] hostCommand = commandCompiler.compileCommand(getProviderType(), SCONTROL_COMMAND, context);
final CommandResult commandResult = simpleCmdExecutor.execute(hostCommand);
if (commandResult.getExitCode() != 0) {
CommandsUtils.throwExecutionDetails(commandResult);
} else if (!commandResult.getStdErr().isEmpty()) {
log.warn(commandResult.getStdErr().toString());
}
final List<String> stdOut = commandResult.getStdOut().stream()
.filter(ScontrolShowNodeParser::checkStdOutLine)
.collect(Collectors.toList());
if (stdOut.isEmpty()) {
CommandsUtils.throwExecutionDetails(commandResult);
}
return mapToHosts(commandResult.getStdOut().stream()
.map(ScontrolShowNodeParser::mapHostDataToSlurmHost)
.collect(Collectors.toList()));
}
private Listing<Host> mapToHosts(final List<SlurmHost> hostList) {
return new Listing<>(
hostList.stream()
.map(slurmHostMapper::mapToHost)
.collect(Collectors.toList())
);
}
}
| 37.555556 | 114 | 0.71759 |
a11baf2f7242f2515e9000ef3aad9cc0cfe8b081 | 5,812 | package com.tramchester.livedata.repository;
import com.netflix.governator.guice.lazy.LazySingleton;
import com.tramchester.config.TramchesterConfig;
import com.tramchester.domain.Platform;
import com.tramchester.domain.places.Location;
import com.tramchester.domain.places.Station;
import com.tramchester.domain.places.StationGroup;
import com.tramchester.domain.reference.TransportMode;
import com.tramchester.domain.time.TramTime;
import com.tramchester.geo.MarginInMeters;
import com.tramchester.geo.StationLocationsRepository;
import com.tramchester.livedata.domain.liveUpdates.UpcomingDeparture;
import com.tramchester.livedata.openLdb.TrainDeparturesRepository;
import com.tramchester.livedata.tfgm.TramDepartureRepository;
import org.apache.commons.collections4.SetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.time.Duration;
import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.String.format;
@LazySingleton
public class DeparturesRepository {
private static final Logger logger = LoggerFactory.getLogger(DeparturesRepository.class);
private final StationLocationsRepository stationLocationsRepository;
private final TramDepartureRepository tramDepartureRepository;
private final TrainDeparturesRepository trainDeparturesRepository;
private final TramchesterConfig config;
@Inject
public DeparturesRepository(StationLocationsRepository stationLocationsRepository,
TramDepartureRepository tramDepartureRepository, TrainDeparturesRepository trainDeparturesRepository, TramchesterConfig config) {
this.stationLocationsRepository = stationLocationsRepository;
this.tramDepartureRepository = tramDepartureRepository;
this.trainDeparturesRepository = trainDeparturesRepository;
this.config = config;
}
public List<UpcomingDeparture> dueTramsForLocation(Location<?> location, LocalDate date, TramTime time,
Set<TransportMode> modes) {
List<UpcomingDeparture> departures = switch (location.getLocationType()) {
case Station -> getStationDepartures((Station) location, modes);
case StationGroup -> getStationGroupDepartures((StationGroup) location, modes);
case MyLocation, Postcode -> getDeparturesNearTo(location, modes);
case Platform -> getPlatformDepartrues((Platform) location, modes);
};
return departures.stream().
filter(departure -> departure.getDate().equals(date)).
filter(departure -> isTimely(time, departure)).
collect(Collectors.toList());
}
private boolean isTimely(TramTime time, UpcomingDeparture departure) {
TramTime beginRange = time.minus(Duration.ofMinutes(20));
TramTime endRange = time.plus(Duration.ofMinutes(20));
return departure.getWhen().between(beginRange, endRange);
}
private List<UpcomingDeparture> getPlatformDepartrues(Platform platform, Set<TransportMode> modes) {
if (!TransportMode.intersects(modes, platform.getTransportModes())) {
logger.error(format("Platform %s does not match supplied modes %s", platform, modes));
}
return tramDepartureRepository.forStation(platform.getStation()).
stream().
filter(UpcomingDeparture::hasPlatform).
filter(departure -> departure.getPlatform().equals(platform)).
collect(Collectors.toList());
}
private List<UpcomingDeparture> getDeparturesNearTo(Location<?> location, Set<TransportMode> modes) {
final MarginInMeters margin = MarginInMeters.of(config.getNearestStopRangeKM());
final int numOfNearestStopsToOffer = config.getNumOfNearestStopsToOffer();
List<Station> nearbyStations = stationLocationsRepository.nearestStationsSorted(location, numOfNearestStopsToOffer,
margin, modes);
return nearbyStations.stream().
flatMap(station -> getStationDepartures(station, modes).stream()).
distinct().
collect(Collectors.toList());
}
private List<UpcomingDeparture> getStationGroupDepartures(StationGroup stationGroup, Set<TransportMode> modes) {
return stationGroup.getContained().stream().
filter(station -> TransportMode.intersects(station.getTransportModes(), modes)).
flatMap(station -> getStationDepartures(station, modes).stream()).
distinct().collect(Collectors.toList());
}
private List<UpcomingDeparture> getStationDepartures(Station station, Set<TransportMode> modes) {
SetUtils.SetView<TransportMode> toFetch = SetUtils.intersection(station.getTransportModes(), modes);
if (toFetch.isEmpty()) {
logger.error(format("Station modes %s and filter modes %s do not overlap", station, modes));
}
return toFetch.stream().
flatMap(mode -> getDeparturesFor(mode, station)).
collect(Collectors.toList());
}
private Stream<UpcomingDeparture> getDeparturesFor(TransportMode mode, Station station) {
switch (mode) {
case Tram -> {
return tramDepartureRepository.forStation(station).stream();
}
case Train -> {
return trainDeparturesRepository.forStation(station).stream();
}
default -> {
final String msg = "TODO - live data for " + mode + " is not implemented yet";
logger.error(msg);
return Stream.empty(); }
}
}
}
| 45.76378 | 161 | 0.701308 |
fa2794edc461a8b2b556de5c627b4668b2840056 | 80 | package generics;
public abstract class State implements Comparable<State> {
}
| 16 | 58 | 0.8 |
900fdd43ea99027f55e260cad099eeb47380e22e | 1,913 | package com.tibco.as.spacebar.ui.handlers.space.browse;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import com.tibco.as.spacebar.ui.SpaceBarPlugin;
import com.tibco.as.spacebar.ui.editor.SpaceEditorExport;
import com.tibco.as.spacebar.ui.editor.SpaceEditorInput;
import com.tibco.as.spacebar.ui.handlers.space.AbstractSpaceHandler;
import com.tibco.as.spacebar.ui.model.Space;
import com.tibco.as.spacebar.ui.navigator.MetaspaceNavigator;
import com.tibco.as.spacebar.ui.preferences.Preferences;
public abstract class AbstractBrowseHandler extends AbstractSpaceHandler {
@Override
protected void handle(ExecutionEvent event, Space space)
throws ExecutionException {
final IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event)
.getActivePage();
final MetaspaceNavigator navigator = (MetaspaceNavigator) page
.findView(SpaceBarPlugin.ID_METASPACES);
navigator.getCommonViewer().addSelectionChangedListener(
new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
page.activate(navigator);
}
});
SpaceEditorExport export = Preferences.getSpaceEditorExport(getTimeScope());
try {
openEditor(page, new SpaceEditorInput(space, export));
} catch (PartInitException e) {
throw new ExecutionException("Could not open space editor", e);
}
}
protected void openEditor(IWorkbenchPage page, SpaceEditorInput input)
throws PartInitException {
page.openEditor(input, input.getEditorId(), true);
}
protected abstract String getTimeScope();
}
| 36.788462 | 79 | 0.778881 |
29031b893f5ce3522eed4f3c32c3c2a4be75b026 | 2,355 | package utils.generators.base;
import static assertions.Assertions.assertGenerates;
import static assertions.Assertions.assertGeneratesNone;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import utils.generators.Generator;
public class TerminatingGeneratorTest {
private static final List<Integer> EMPTY = Collections.unmodifiableList(Collections.emptyList());
private static final List<Integer> LIST = Collections.unmodifiableList(Arrays.asList(1, 2, 3));
private static final List<Integer> SINGLETON = Collections.unmodifiableList(Arrays.asList(5));
@Test
public void terminating_emptyGenerator_givesEmptyGenerator() {
Generator<Integer> original = new IteratorWrappingGenerator<>(EMPTY.iterator());
Generator<Integer> generator = new TerminatingGenerator<>(original, i -> false);
assertGeneratesNone(generator);
}
@Test
public void terminating_falsePredicate_givesIdenticalGenerator() {
Generator<Integer> original = new IteratorWrappingGenerator<>(LIST.iterator());
Generator<Integer> generator = new TerminatingGenerator<>(original, i -> false);
assertGenerates(generator, 1, 2, 3);
}
@Test
public void terminating_truePredicate_givesEmptyGenerator() {
Generator<Integer> original = new IteratorWrappingGenerator<>(LIST.iterator());
Generator<Integer> generator = new TerminatingGenerator<>(original, i -> true);
assertGeneratesNone(generator);
}
@Test
public void terminating_stopsBeforeTerminalPredicate() {
Generator<Integer> original = new IteratorWrappingGenerator<>(LIST.iterator());
Generator<Integer> generator = new TerminatingGenerator<>(original, i -> i == 2);
assertGenerates(generator, 1);
}
@Test
public void terminating_singletonWithFalsePredicate_generatesExpected() {
Generator<Integer> original = new IteratorWrappingGenerator<>(SINGLETON.iterator());
Generator<Integer> generator = new TerminatingGenerator<>(original, i -> false);
assertGenerates(generator, 5);
}
@Test
public void terminating_singletonWithTruePredicate_generatesNone() {
Generator<Integer> original = new IteratorWrappingGenerator<>(SINGLETON.iterator());
Generator<Integer> generator = new TerminatingGenerator<>(original, i -> true);
assertGeneratesNone(generator);
}
}
| 32.708333 | 99 | 0.764756 |
13ffe12481a850940af417d69e46a993ad0c13fd | 876 | /**
*
*/
package com.github.cobolio.internal.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* A loader class for messages used in the library.
*
* @author Andrew
*
*/
public final class Messages {
private static final String BUNDLE_NAME = "com.github.cobolio.internal.util.messages"; //$NON-NLS-1$
public static final String BUILD_IDENTIFIER = "20200822-2149";
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
private Messages() {
throw new IllegalStateException();
}
@SuppressWarnings({ "java:S1166" }) // Suppressing MissingResourceException sonar because this cannot occur when
// built correctly.
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 25.764706 | 113 | 0.737443 |
e689aa50266fe6f8d221525e1e57a2c02fc707bf | 289 |
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BookList bookList = new BookList();
UserInterface ui = new UserInterface(scanner, bookList);
ui.start();
}
}
| 20.642857 | 64 | 0.640138 |
b55133bebfc28f368fb5487b8e8dd20a3d5484df | 1,595 | package net.minecraft.world.level.levelgen.feature;
import java.util.Optional;
import java.util.Random;
import net.minecraft.core.BlockPosition;
import net.minecraft.world.level.GeneratorAccessSeed;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.feature.configurations.WorldGenFeatureConfiguration;
public class FeaturePlaceContext<FC extends WorldGenFeatureConfiguration> {
private final Optional<WorldGenFeatureConfigured<?, ?>> topFeature;
private final GeneratorAccessSeed level;
private final ChunkGenerator chunkGenerator;
private final Random random;
private final BlockPosition origin;
private final FC config;
public FeaturePlaceContext(Optional<WorldGenFeatureConfigured<?, ?>> optional, GeneratorAccessSeed generatoraccessseed, ChunkGenerator chunkgenerator, Random random, BlockPosition blockposition, FC fc) {
this.topFeature = optional;
this.level = generatoraccessseed;
this.chunkGenerator = chunkgenerator;
this.random = random;
this.origin = blockposition;
this.config = fc;
}
public Optional<WorldGenFeatureConfigured<?, ?>> topFeature() {
return this.topFeature;
}
public GeneratorAccessSeed level() {
return this.level;
}
public ChunkGenerator chunkGenerator() {
return this.chunkGenerator;
}
public Random random() {
return this.random;
}
public BlockPosition origin() {
return this.origin;
}
public FC config() {
return this.config;
}
}
| 30.673077 | 207 | 0.725392 |
b5ec9a6c79c845d6116d3b61548e759a8db22d67 | 95 | package eta.runtime.exception;
public class TrampolineBounceException extends StgException {}
| 23.75 | 62 | 0.852632 |
b068a9b49dae7bddf6971d3886f7b3b8fb1350d8 | 3,430 | package org.endeavourhealth.transform.tpp.csv.schema.unused.theatre;
import org.endeavourhealth.transform.common.AbstractCsvParser;
import org.endeavourhealth.transform.common.CsvCell;
import org.endeavourhealth.transform.tpp.TppCsvToFhirTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class SRTheatreSession extends AbstractCsvParser {
private static final Logger LOG = LoggerFactory.getLogger(SRTheatreSession.class);
public SRTheatreSession(UUID serviceId, UUID systemId, UUID exchangeId, String version, String filePath) throws Exception {
super(serviceId, systemId, exchangeId, version, filePath,
TppCsvToFhirTransformer.CSV_FORMAT,
TppCsvToFhirTransformer.DATE_FORMAT,
TppCsvToFhirTransformer.TIME_FORMAT,
TppCsvToFhirTransformer.ENCODING);
}
@Override
protected String[] getCsvHeaders(String version) {
return new String[]{
"RowIdentifier",
"IDOrganisationVisibleTo",
"DateCreated",
"DateDeleted",
"DatePreparationStarted",
"DateTheatreSessionStarted",
"DateTheatreSessionEnded",
"DateClearUpOfTheatreFinished",
"TheatreDescription",
"Specialty",
"IDConsultant",
"IDProfileConsultant",
"IDAnaesthetist",
"IDProfileAnaesthetist",
"IDOda",
"IDProfileOda",
"IDOrganisation"
};
}
public CsvCell getRowIdentifier() {
return super.getCell("RowIdentifier");
}
public CsvCell getIDOrganisationVisibleTo() {
return super.getCell("IDOrganisationVisibleTo");
}
public CsvCell getDateCreated() {
return super.getCell("DateCreated");
}
public CsvCell getDateDeleted() {
return super.getCell("DateDeleted");
}
public CsvCell getDatePreparationStarted() {
return super.getCell("DatePreparationStarted");
}
public CsvCell getDateTheatreSessionStarted() {
return super.getCell("DateTheatreSessionStarted");
}
public CsvCell getDateTheatreSessionEnded() {
return super.getCell("DateTheatreSessionEnded");
}
public CsvCell getDateClearUpOfTheatreFinished() {
return super.getCell("DateClearUpOfTheatreFinished");
}
public CsvCell getTheatreDescription() {
return super.getCell("TheatreDescription");
}
public CsvCell getSpecialty() {
return super.getCell("Specialty");
}
public CsvCell getIDConsultant() {
return super.getCell("IDConsultant");
}
public CsvCell getIDProfileConsultant() {
return super.getCell("IDProfileConsultant");
}
public CsvCell getIDAnaesthetist() {
return super.getCell("IDAnaesthetist");
}
public CsvCell getIDProfileAnaesthetist() {
return super.getCell("IDProfileAnaesthetist");
}
public CsvCell getIDOda() {
return super.getCell("IDOda");
}
public CsvCell getIDProfileOda() {
return super.getCell("IDProfileOda");
}
public CsvCell getIDOrganisation() {
return super.getCell("IDOrganisation");
}
@Override
protected boolean isFileAudited() {
return true;
}
}
| 27.66129 | 127 | 0.646356 |
c0750383adbb1772326cff6d2d17afd2ea14ceaf | 17,644 | /*
* Simplicite(R) for Google Android(R)
* http://www.simplicite.fr
*/
package com.simplicite.android.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import org.json.*;
import android.os.AsyncTask;
/**
* <p>Application user session data</p>
*/
public class AppSession extends Common {
private static final long serialVersionUID = 1L;
/**
* </p>Constructor for external usage outside of generic web UI</p>
* @param login User login
* @param password user password
* @param baseURL Base URL of current application generic web services gateway (e.g. http://myserver:8080/myapp<u>ws</u>)
*/
public AppSession(String login, String password, String baseURL) {
super(login, password, baseURL, null);
_serviceURI = "jsonappservice.jsp";
clear();
}
/**
* <p>Clears all session data</p>
*/
public void clear() {
name = null;
version = null;
platformVersion = null;
encoding = null;
sysinfo = null;
session = null;
grant = null;
menu = null;
texts = null;
sysparams = null;
news = null;
clearBusinessObjects();
clearExternalObjects();
clearBusinessProcesses();
}
/**
* <p>Clears business objects</p>
*/
public void clearBusinessObjects() {
if (businessObjects == null)
businessObjects = new HashMap<String, BusinessObject>();
else
businessObjects.clear();
}
/**
* <p>Clears external objects</p>
*/
public void clearExternalObjects() {
if (externalObjects == null)
externalObjects = new HashMap<String, ExternalObject>();
else
externalObjects.clear();
}
/**
* <p>Clears business processes</p>
*/
public void clearBusinessProcesses() {
if (businessProcesses == null)
businessProcesses = new HashMap<String, BusinessProcess>();
else
businessProcesses.clear();
}
/**
* <p>Application name</p>
*/
public String name;
/**
* <p>Application version</p>
*/
public String version;
/**
* <p>Platform version</p>
*/
public String platformVersion;
/**
* <p>Encoding</p>
*/
public String encoding;
/**
* <p>System info</p>
*/
public SysInfo sysinfo;
/**
* <p>Session ID</p>
*/
public String session;
/**
* <p>User data</p>
*/
public Grant grant;
/**
* <p>Main menu</p>
*/
public MainMenu menu;
/**
* <p>System parameters</p>
*/
public HashMap<String, String> sysparams;
/**
* <p>Texts</p>
*/
public HashMap<String, String> texts;
/**
* <p>List of values</p>
*/
public HashMap<String, HashMap<String, String>> listOfValues;
/**
* <p>News</p>
*/
public ArrayList<News> news;
protected Object _parse(String json) throws AppException {
try {
JSONObject msg = (JSONObject)super._parse(json);
String type = msg.getString("type");
if (type.equals("info")) {
JSONObject i = msg.getJSONObject("response");
// ZZZ Upward compatibility
name = i.has("name") ? i.getString("name") : "";
version = i.getString("version");
platformVersion = i.getString("platformversion");
encoding = i.getString("encoding");
return name;
} else if (type.equals("sysinfo")) {
JSONObject si = msg.getJSONObject("response");
sysinfo = new SysInfo();
sysinfo.cacheobject = si.getInt("cacheobject");
sysinfo.cacheobjectmax = si.getInt("cacheobjectmax");
// ZZZ Upward compatibility
sysinfo.cachegrant = si.has("cachegrant") ? si.getInt("cachegrant") : 0;
sysinfo.cachegrantmax = si.has("cachegrantmax") ? si.getInt("cachegrantmax") : 0;
// ZZZ Upward compatibility
sysinfo.heapsize = si.has("heapsize") ? si.getLong("heapsize") : 0;
sysinfo.heapfreesize = si.has("heapfreesize") ? si.getLong("heapfreesize") : 0;
sysinfo.heapmaxsize = si.has("heapmaxsize") ? si.getLong("heapmaxsize") : 0;
// ZZZ Upward compatibility
sysinfo.dirdbdoc = si.has("dirdbdoc") ? si.getLong("dirdbdoc") : 0;
sysinfo.dircache = si.has("dircache") ? si.getLong("dircache") : 0;
sysinfo.dirrecyclebin = si.has("dirrecyclebin") ? si.getLong("dirrecyclebin") : 0;
sysinfo.diskfree = si.has("diskfree") ? si.getLong("diskfree") : 0;
return sysinfo;
} else if (type.equals("session")) {
JSONObject s = msg.getJSONObject("response");
session = s.getString("id");
return session;
} else if (type.equals("grant")) {
JSONObject g = msg.getJSONObject("response");
session = g.getString("sessionid");
grant = new Grant();
grant.userid = g.getInt("userid");
grant.login = g.getString("login");
grant.lang = g.getString("lang");
grant.firstname = g.getString("firstname");
grant.lastname = g.getString("lastname");
grant.email = g.getString("email");
// ZZZ Upward compatibility
grant.picture = g.has("picture") ? _parseDocument(g, "picture") : null;
grant.responsibilities.clear();
JSONArray rs = g.getJSONArray("responsibilities");
for (int i = 0; i < rs.length(); i++) {
grant.responsibilities.add(rs.getString(i));
}
return grant;
} else if (type.equals("menu")) {
JSONArray ds = msg.getJSONArray("response");
menu = new MainMenu();
for (int i = 0; i < ds.length(); i++) {
JSONObject d = ds.getJSONObject(i);
MenuDomain domain = new MenuDomain();
domain.name = d.getString("name");
domain.label = d.getString("label");
JSONArray its = d.getJSONArray("items");
for (int j = 0; j < its.length(); j++) {
JSONObject it = its.getJSONObject(j);
MenuEntry entry = new MenuEntry();
entry.type = it.getString("type");
entry.name = it.getString("name");
entry.label = it.getString("label");
domain.entries.add(entry);
}
menu.domains.add(domain);
}
return menu;
} else if (type.equals("sysparams")) {
JSONArray sps = msg.getJSONArray("response");
sysparams = new HashMap<String, String>();
for (int i = 0; i < sps.length(); i++) {
JSONObject sp = sps.getJSONObject(i);
sysparams.put(sp.getString("name"), sp.getString("value"));
}
return sysparams;
} else if (type.equals("sysparam")) {
if (sysparams == null) sysparams = new HashMap<String, String>();
JSONObject sp = msg.getJSONObject("response");
String val = sp.getString("value");
sysparams.put(sp.getString("name"), val);
return val;
} else if (type.equals("sysparamdb")) {
// TODO : to be completed...
return null;
} else if (type.equals("listofvalue")) {
// TODO : to be completed...
return null;
} else if (type.equals("texts")) {
JSONArray ts = msg.getJSONArray("response");
texts = new HashMap<String, String>();
for (int i = 0; i < ts.length(); i++) {
JSONObject t = ts.getJSONObject(i);
texts.put(t.getString("code"), t.getString("value"));
}
return texts;
} else if (type.equals("text")) {
if (texts == null) texts = new HashMap<String, String>();
JSONObject t = msg.getJSONObject("response");
String val = t.getString("value");
texts.put(t.getString("code"), val);
return val;
} else if (type.equals("news")) {
JSONArray ns = msg.getJSONArray("response");
news = new ArrayList<News>();
for (int i = 0; ns != null && i < ns.length(); i++) {
JSONObject n = ns.getJSONObject(i);
News nw = new News();
//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//nw.date = null;
//try { nw.date = df.parse(n.getString("date")); } catch (ParseException e) {}
nw.date = n.getString("date");
//nw.expdate = null;
//try { nw.expdate = df.parse(n.getString("expdate")); } catch (ParseException e) {}
nw.expdate = n.getString("expdate");
nw.title = n.getString("title");
nw.image = _parseDocument(n, "image");
nw.content = n.getString("content");
news.add(nw);
}
return news;
} else if (type.equals("extobject")) {
JSONObject e = msg.getJSONObject("response");
ExternalObject extobj = new ExternalObject();
extobj.id = e.getString("id");
extobj.name = e.getString("name");
extobj.label = e.getString("label");
extobj.help = e.getString("help");
extobj.icon = e.getString("icon");
extobj.url = e.getString("url");
extobj.mime = e.getString("mime");
return extobj;
} else
throw new AppException("Unhandled " + type + " response type");
} catch (JSONException e) {
throw new AppException("Parsing exception: " + e.getMessage());
}
}
private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
public Exception exception;
@Override
protected String doInBackground(Void... params) {
try {
debug("Get info");
return (String)_parse(_get("?data=info"));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets application info</p>
*/
public String getInfo() throws Exception {
if (name == null) {
InfoAsyncTask t = new InfoAsyncTask();
if (t.execute().get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return name;
}
private class SysInfoAsyncTask extends AsyncTask<Void, Void, SysInfo> {
public Exception exception;
@Override
protected SysInfo doInBackground(Void... params) {
try {
debug("Get system info");
return (SysInfo)_parse(_get("?data=sysinfo"));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets system info</p>
*/
public SysInfo getSysInfo() throws Exception {
SysInfoAsyncTask t = new SysInfoAsyncTask();
if (t.execute().get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
return sysinfo;
}
private class SessionAsyncTask extends AsyncTask<Void, Void, String> {
public Exception exception;
@Override
protected String doInBackground(Void... params) {
try {
debug("Get session");
return (String)_parse(_get("?data=session"));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets user session ID</p>
*/
public String getSession() throws Exception {
if (session == null) {
SessionAsyncTask t = new SessionAsyncTask();
if (t.execute().get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return session;
}
private class GrantAsyncTask extends AsyncTask<String, Void, Grant> {
public Exception exception;
@Override
protected Grant doInBackground(String... params) {
try {
debug("Get grant");
return (Grant)_parse(_get("?data=grant" + (params != null && params.length>0 ? params[0] : "")));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets user grant data</p>
*/
public Grant getGrant(boolean inlinePicture) throws Exception {
if (grant == null) {
GrantAsyncTask t = new GrantAsyncTask();
if (t.execute(inlinePicture ? "&inline_picture=true" : "").get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return grant;
}
private class SysParamAsyncTask extends AsyncTask<Void, Void, HashMap<String, String>> {
public Exception exception;
@SuppressWarnings("unchecked")
@Override
protected HashMap<String, String> doInBackground(Void... params) {
try {
debug("Get system parameters");
return (HashMap<String, String>)_parse(_get("?data=sysparams"));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets system parameters</p>
*/
public HashMap<String, String> getSysParams() throws Exception {
if (sysparams == null) {
SysParamAsyncTask t = new SysParamAsyncTask();
if (t.execute().get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return sysparams;
}
private class TextAsyncTask extends AsyncTask<Void, Void, HashMap<String, String>> {
public Exception exception;
@SuppressWarnings("unchecked")
@Override
protected HashMap<String, String> doInBackground(Void... params) {
try {
debug("Get texts");
return (HashMap<String, String>)_parse(_get("?data=texts"));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets translated texts in user's language</p>
*/
public HashMap<String, String> getTexts() throws Exception {
if (texts == null) {
TextAsyncTask t = new TextAsyncTask();
if (t.execute().get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return texts;
}
/**
* <p>Get text for specified code (must be called after getTexts)</p>
* @param code Text code
* @param def Default value
*/
public String getText(String code, String def) {
String val = texts != null ? texts.get(code) : null;
return val == null ? def : val;
}
private class MenuAsyncTask extends AsyncTask<Void, Void, MainMenu> {
public Exception exception;
@Override
protected MainMenu doInBackground(Void... params) {
try {
debug("Get menu");
return (MainMenu)_parse(_get("?data=menu"));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets user menu</p>
*/
public MainMenu getMenu() throws Exception {
if (menu == null) {
MenuAsyncTask t = new MenuAsyncTask();
if (t.execute().get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return menu;
}
private class NewsAsyncTask extends AsyncTask<String, Void, ArrayList<News>> {
public Exception exception;
@SuppressWarnings("unchecked")
@Override
protected ArrayList<News> doInBackground(String... params) {
try {
debug("Get news");
return (ArrayList<News>)_parse(_get("?data=news" + (params != null && params.length>0 ? params[0] : "")));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets news</p>
* @param inlineImages Inline images ?
* @param refresh Force refresh ?
*/
public ArrayList<News> getNews(boolean inlineImages, boolean refresh) throws Exception {
if (news == null || refresh) {
NewsAsyncTask t = new NewsAsyncTask();
if (t.execute(inlineImages ? "&inline_images=true" : "").get(getTimeout(), TimeUnit.SECONDS) == null)
throw t.exception;
}
return news;
}
private HashMap<String, BusinessObject> businessObjects;
/**
* <p>Gets a business object instance for current user session</p>
* @param name Business object logical name
*/
public BusinessObject getBusinessObject(String name) throws Exception {
return getBusinessObject(name, null);
}
/**
* <p>Gets a business object instance for current user session</p>
* @param name Business object logical name
* @param instance Business object logical instance name
*/
public BusinessObject getBusinessObject(String name, String instance) throws Exception {
BusinessObject obj = businessObjects.get(name + ":" + instance);
if (obj == null) {
obj = new BusinessObject(name, instance, this);
obj.setDebug(isDebug());
obj.setTimeout(getTimeout());
obj.getMetaData();
businessObjects.put(name + ":" + instance, obj);
}
return obj;
}
private HashMap<String, ExternalObject> externalObjects;
private class ExtObjectAsyncTask extends AsyncTask<String, Void, ExternalObject> {
public Exception exception;
@Override
protected ExternalObject doInBackground(String... params) {
try {
debug("Get external object");
return (ExternalObject)_parse(_get("?data=extobject" + (params != null && params.length>0 ? params[0] : "")));
} catch (Exception e) {
this.exception = e;
return null;
}
}
}
/**
* <p>Gets an external object for current user session</p>
* @param name External object logical name
*/
public ExternalObject getExternalObject(String name) throws Exception {
ExternalObject extobj = externalObjects.get(name);
if (extobj == null) {
ExtObjectAsyncTask t = new ExtObjectAsyncTask();
if ((extobj = t.execute("&name=" + name).get(getTimeout(), TimeUnit.SECONDS)) == null)
throw t.exception;
}
return extobj;
}
private HashMap<String, BusinessProcess> businessProcesses;
/**
* <p>Gets a business process for current user session</p>
* @param name Business process logical name
*/
public BusinessProcess getBusinessProcess(String name) throws Exception {
BusinessProcess pcs = businessProcesses.get(name);
if (pcs == null) {
pcs = new BusinessProcess(name, this);
pcs.setDebug(isDebug());
pcs.setTimeout(getTimeout());
businessProcesses.put(name, pcs);
}
return pcs;
}
/**
* <p>String representation</p>
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("Session:" + session + "\n");
s.append(grant.toString());
s.append("System params:\n");
for (String key : sysparams.keySet()) {
s.append("\t" + key + " = [" + sysparams.get(key) + "]\n");
}
s.append("Texts:\n");
for (String key : texts.keySet()) {
s.append("\t" + key + " = [" + texts.get(key) + "]\n");
}
return s.toString();
}
} | 27.917722 | 123 | 0.618907 |
ace3e69be4bba3e59d18c01b04f806f877b665b9 | 1,142 | //
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.client;
import org.eclipse.jetty.client.api.Request;
public class HttpRequestException extends RuntimeException
{
private final Request request;
public HttpRequestException(String message, Request request)
{
super(message);
this.request = request;
}
public Request getRequest()
{
return request;
}
}
| 30.052632 | 75 | 0.626095 |
775ada5c0db6d4f99a9229ed38f63dacb838c467 | 682 | package models;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import models.Car;
//import Car;
import static org.junit.Assert.assertEquals;
public class CarTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void NewCarObjectGetsCorrectlyCreated_true() throws Exception {
Car car = new Car("hi", 45,56);
assertEquals(true, car instanceof Car);
}
@Test
public void NewCarObjectGetsCorrectlyCreated_false() throws Exception {
Car car = new Car("subaru", 1,6);
assertEquals(true, car instanceof Car);
}
}
| 21.3125 | 75 | 0.673021 |
3d95ad803a29e115b1e8bedd649dd2d7c019f683 | 531 | package com.parse.starter;
/**
* Created by hau on 4/12/2015.
*/
public class DTTinTuc {
String idtuade;
String tuade;
String ngaytao;
String noidung;
public DTTinTuc() {
this.idtuade = null;
this.tuade = null;
this.ngaytao = null;
this.noidung = null;
}
public DTTinTuc(String idtuade, String tuade, String ngaytao, String noidung) {
this.idtuade = idtuade;
this.tuade = tuade;
this.ngaytao = ngaytao;
this.noidung = noidung;
}
}
| 21.24 | 83 | 0.595104 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.