proj_name
stringclasses 157
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
49
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjAopInterceptor.java | AspectjAopInterceptor | checkAndProceed | class AspectjAopInterceptor {
private final CacheHandler cacheHandler;
public AspectjAopInterceptor(CacheHandler cacheHandler) {
this.cacheHandler = cacheHandler;
}
public Object checkAndProceed(ProceedingJoinPoint pjp) throws Throwable {<FILL_FUNCTION_BODY>}
public void checkAndDeleteCache(JoinPoint jp, Object retVal) throws Throwable {
Signature signature = jp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(CacheDelete.class)) {
CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class);
this.deleteCache(jp, cacheDelete, retVal);
}
}
public Object checkAndDeleteCacheTransactional(ProceedingJoinPoint pjp) throws Throwable {
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cache = method.getAnnotation(CacheDeleteTransactional.class);// method.getAnnotationsByType(Cache.class)[0];
return this.deleteCacheTransactional(pjp, cache);
}
try {
return pjp.proceed();
} catch (Throwable e) {
throw e;
}
}
public Object proceed(ProceedingJoinPoint aopProxyChain, Cache cache) throws Throwable {
return cacheHandler.proceed(new AspectjCacheAopProxyChain(aopProxyChain), cache);
}
public void deleteCache(JoinPoint aopProxyChain, CacheDelete cacheDelete, Object retVal) throws Throwable {
cacheHandler.deleteCache(new AspectjDeleteCacheAopProxyChain(aopProxyChain), cacheDelete, retVal);
}
public Object deleteCacheTransactional(ProceedingJoinPoint aopProxyChain,
CacheDeleteTransactional cacheDeleteTransactional) throws Throwable {
return cacheHandler.proceedDeleteCacheTransactional(
new AspectjDeleteCacheTransactionalAopProxyChain(aopProxyChain), cacheDeleteTransactional);
}
public CacheHandler getCacheHandler() {
return cacheHandler;
}
} |
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(Cache.class)) {
Cache cache = method.getAnnotation(Cache.class);// method.getAnnotationsByType(Cache.class)[0];
return this.proceed(pjp, cache);
}
try {
return pjp.proceed();
} catch (Throwable e) {
throw e;
}
| 591 | 134 | 725 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjCacheAopProxyChain.java | AspectjCacheAopProxyChain | getMethod | class AspectjCacheAopProxyChain implements CacheAopProxyChain {
private final ProceedingJoinPoint jp;
private Method method;
public AspectjCacheAopProxyChain(ProceedingJoinPoint jp) {
this.jp = jp;
}
@Override
public Object[] getArgs() {
return jp.getArgs();
}
@Override
public Object getTarget() {
return jp.getTarget();
}
@Override
public Method getMethod() {<FILL_FUNCTION_BODY>}
@Override
public Object doProxyChain(Object[] arguments) throws Throwable {
return jp.proceed(arguments);
}
} |
if (null == method) {
Signature signature = jp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
this.method = methodSignature.getMethod();
}
return method;
| 188 | 57 | 245 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-aop/autoload-cache-aop-aspectj/src/main/java/com/jarvis/cache/aop/aspectj/AspectjDeleteCacheAopProxyChain.java | AspectjDeleteCacheAopProxyChain | getMethod | class AspectjDeleteCacheAopProxyChain implements DeleteCacheAopProxyChain {
private JoinPoint jp;
public AspectjDeleteCacheAopProxyChain(JoinPoint jp) {
this.jp = jp;
}
@Override
public Object[] getArgs() {
return jp.getArgs();
}
@Override
public Object getTarget() {
return jp.getTarget();
}
@Override
public Method getMethod() {<FILL_FUNCTION_BODY>}
} |
Signature signature = jp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
return methodSignature.getMethod();
| 140 | 37 | 177 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/CacheUtil.java | CacheUtil | getMiscHashCode | class CacheUtil {
private static final String SPLIT_STR = "_";
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object obj) {
if (null == obj) {
return true;
}
if (obj instanceof String) {
return ((String) obj).length() == 0;
}
Class cl = obj.getClass();
if (cl.isArray()) {
int len = Array.getLength(obj);
return len == 0;
}
if (obj instanceof Collection) {
Collection tempCol = (Collection) obj;
return tempCol.isEmpty();
}
if (obj instanceof Map) {
Map tempMap = (Map) obj;
return tempMap.isEmpty();
}
return false;
}
/**
* 生成字符串的HashCode
*
* @param buf
* @return int hashCode
*/
private static int getHashCode(String buf) {
int hash = 5381;
int len = buf.length();
while (len-- > 0) {
hash = ((hash << 5) + hash) + buf.charAt(len);
}
return hash;
}
/**
* 将Object 对象转换为唯一的Hash字符串
*
* @param obj Object
* @return Hash字符串
*/
public static String getUniqueHashStr(Object obj) {
return getMiscHashCode(BeanUtil.toString(obj));
}
/**
* 通过混合Hash算法,将长字符串转为短字符串(字符串长度小于等于20时,不做处理)
*
* @param str String
* @return Hash字符串
*/
public static String getMiscHashCode(String str) {<FILL_FUNCTION_BODY>}
/**
* 生成缓存Key
*
* @param className 类名称
* @param method 方法名称
* @param arguments 参数
* @return CacheKey 缓存Key
*/
public static String getDefaultCacheKey(String className, String method, Object[] arguments) {
StringBuilder sb = new StringBuilder();
sb.append(getDefaultCacheKeyPrefix(className, method, arguments));
if (null != arguments && arguments.length > 0) {
sb.append(getUniqueHashStr(arguments));
}
return sb.toString();
}
/**
* 生成缓存Key的前缀
*
* @param className 类名称
* @param method 方法名称
* @param arguments 参数
* @return CacheKey 缓存Key
*/
public static String getDefaultCacheKeyPrefix(String className, String method, Object[] arguments) {
StringBuilder sb = new StringBuilder();
sb.append(className);
if (null != method && method.length() > 0) {
sb.append(".").append(method);
}
return sb.toString();
}
} |
if (null == str || str.length() == 0) {
return "";
}
int originSize = 20;
if (str.length() <= originSize) {
return str;
}
StringBuilder tmp = new StringBuilder();
tmp.append(str.hashCode()).append(SPLIT_STR).append(getHashCode(str));
int mid = str.length() / 2;
String str1 = str.substring(0, mid);
String str2 = str.substring(mid);
tmp.append(SPLIT_STR).append(str1.hashCode());
tmp.append(SPLIT_STR).append(str2.hashCode());
return tmp.toString();
| 778 | 183 | 961 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/comparator/AutoLoadOldestComparator.java | AutoLoadOldestComparator | compare | class AutoLoadOldestComparator implements Comparator<AutoLoadTO> {
@Override
public int compare(AutoLoadTO autoLoadTO1, AutoLoadTO autoLoadTO2) {<FILL_FUNCTION_BODY>}
} |
if (autoLoadTO1 == null && autoLoadTO2 != null) {
return 1;
} else if (autoLoadTO1 != null && autoLoadTO2 == null) {
return -1;
} else if (autoLoadTO1 == null && autoLoadTO2 == null) {
return 0;
}
long now = System.currentTimeMillis();
long dif1 = now - autoLoadTO1.getLastLoadTime() - autoLoadTO1.getCache().expire() * 1000;
long dif2 = now - autoLoadTO2.getLastLoadTime() - autoLoadTO2.getCache().expire() * 1000;
if (dif1 > dif2) {
return -1;
} else if (dif1 < dif2) {
return 1;
} else {
if (autoLoadTO1.getAverageUseTime() > autoLoadTO2.getAverageUseTime()) {
return -1;
} else if (autoLoadTO1.getAverageUseTime() < autoLoadTO2.getAverageUseTime()) {
return 1;
}
}
return 0;
| 62 | 298 | 360 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/comparator/AutoLoadRequestTimesComparator.java | AutoLoadRequestTimesComparator | compare | class AutoLoadRequestTimesComparator implements Comparator<AutoLoadTO> {
@Override
public int compare(AutoLoadTO autoLoadTO1, AutoLoadTO autoLoadTO2) {<FILL_FUNCTION_BODY>}
} |
if (autoLoadTO1 == null && autoLoadTO2 != null) {
return 1;
} else if (autoLoadTO1 != null && autoLoadTO2 == null) {
return -1;
} else if (autoLoadTO1 == null && autoLoadTO2 == null) {
return 0;
}
if (autoLoadTO1.getRequestTimes() > autoLoadTO2.getRequestTimes()) {
return -1;
} else if (autoLoadTO1.getRequestTimes() < autoLoadTO2.getRequestTimes()) {
return 1;
}
return 0;
| 62 | 158 | 220 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/reflect/generics/ParameterizedTypeImpl.java | ParameterizedTypeImpl | validateConstructorArguments | class ParameterizedTypeImpl implements ParameterizedType {
private Type[] actualTypeArguments;
private Class<?> rawType;
private Type ownerType;
private ParameterizedTypeImpl(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) {
this.actualTypeArguments = paramArrayOfType;
this.rawType = paramClass;
if (paramType != null) {
this.ownerType = paramType;
} else {
this.ownerType = paramClass.getDeclaringClass();
}
validateConstructorArguments();
}
private void validateConstructorArguments() {<FILL_FUNCTION_BODY>}
public static ParameterizedTypeImpl make(Class<?> paramClass, Type[] paramArrayOfType, Type paramType) {
return new ParameterizedTypeImpl(paramClass, paramArrayOfType, paramType);
}
@Override
public Type[] getActualTypeArguments() {
return (Type[]) this.actualTypeArguments.clone();
}
@Override
public Class<?> getRawType() {
return this.rawType;
}
@Override
public Type getOwnerType() {
return this.ownerType;
}
@Override
public boolean equals(Object paramObject) {
if ((paramObject instanceof ParameterizedType)) {
ParameterizedType localParameterizedType = (ParameterizedType) paramObject;
if (this == localParameterizedType) {
return true;
}
Type localType1 = localParameterizedType.getOwnerType();
Type localType2 = localParameterizedType.getRawType();
return (this.ownerType == null ? localType1 == null : this.ownerType.equals(localType1))
&& (this.rawType == null ? localType2 == null : this.rawType.equals(localType2))
&& (Arrays.equals(this.actualTypeArguments, localParameterizedType.getActualTypeArguments()));
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(this.actualTypeArguments) ^ (this.ownerType == null ? 0 : this.ownerType.hashCode())
^ (this.rawType == null ? 0 : this.rawType.hashCode());
}
@Override
public String toString() {
StringBuilder localStringBuilder = new StringBuilder();
if (this.ownerType != null) {
if ((this.ownerType instanceof Class<?>))
localStringBuilder.append(((Class<?>) this.ownerType).getName());
else {
localStringBuilder.append(this.ownerType.toString());
}
localStringBuilder.append(".");
if ((this.ownerType instanceof ParameterizedTypeImpl)) {
localStringBuilder.append(this.rawType.getName()
.replace(((ParameterizedTypeImpl) this.ownerType).rawType.getName() + "$", ""));
} else {
localStringBuilder.append(this.rawType.getName());
}
} else {
localStringBuilder.append(this.rawType.getName());
}
if ((this.actualTypeArguments != null) && (this.actualTypeArguments.length > 0)) {
localStringBuilder.append("<");
int i = 1;
for (Type localType : this.actualTypeArguments) {
if (i == 0) {
localStringBuilder.append(", ");
}
if ((localType instanceof Class<?>)) {
localStringBuilder.append(((Class<?>) localType).getName());
} else {
// if(null!=localType){
localStringBuilder.append(localType.toString());
// }
}
i = 0;
}
localStringBuilder.append(">");
}
return localStringBuilder.toString();
}
} |
@SuppressWarnings("rawtypes")
TypeVariable[] arrayOfTypeVariable = this.rawType.getTypeParameters();
if (arrayOfTypeVariable.length != this.actualTypeArguments.length) {
throw new MalformedParameterizedTypeException();
}
// for(int i=0; i < this.actualTypeArguments.length; i++);
| 976 | 93 | 1,069 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/AutoLoadTO.java | AutoLoadTO | toString | class AutoLoadTO implements Serializable {
private static final long serialVersionUID = 1L;
private final CacheAopProxyChain joinPoint;
private final Object[] args;
/**
* 缓存注解
*/
private final Cache cache;
/**
* 缓存时长
*/
private int expire;
/**
* 缓存Key
*/
private final CacheKeyTO cacheKey;
/**
* 上次从DAO加载数据时间
*/
private long lastLoadTime = 0L;
/**
* 上次请求数据时间
*/
private long lastRequestTime = 0L;
/**
* 第一次请求数据时间
*/
private long firstRequestTime = 0L;
/**
* 请求数据次数
*/
private long requestTimes = 0L;
private volatile boolean loading = false;
/**
* 加载次数
*/
private long loadCnt = 0L;
/**
* 从DAO中加载数据,使用时间的总和
*/
private long useTotalTime = 0L;
public AutoLoadTO(CacheKeyTO cacheKey, CacheAopProxyChain joinPoint, Object args[], Cache cache, int expire) {
this.cacheKey = cacheKey;
this.joinPoint = joinPoint;
this.args = args;
this.cache = cache;
this.expire = expire;
}
public CacheAopProxyChain getJoinPoint() {
return joinPoint;
}
public long getLastRequestTime() {
return lastRequestTime;
}
public AutoLoadTO setLastRequestTime(long lastRequestTime) {
synchronized (this) {
this.lastRequestTime = lastRequestTime;
if (firstRequestTime == 0) {
firstRequestTime = lastRequestTime;
}
requestTimes++;
}
return this;
}
/**
* @param firstRequestTime System.currentTimeMillis()
*/
public void setFirstRequestTime(long firstRequestTime) {
this.firstRequestTime = firstRequestTime;
}
public long getFirstRequestTime() {
return firstRequestTime;
}
public long getRequestTimes() {
return requestTimes;
}
public Cache getCache() {
return cache;
}
public long getLastLoadTime() {
return lastLoadTime;
}
/**
* @param lastLoadTime last load time
* @return this
*/
public AutoLoadTO setLastLoadTime(long lastLoadTime) {
this.lastLoadTime = lastLoadTime;
return this;
}
public CacheKeyTO getCacheKey() {
return cacheKey;
}
public boolean isLoading() {
return loading;
}
/**
* @param loading 是否正在加载
* @return this
*/
public AutoLoadTO setLoading(boolean loading) {
this.loading = loading;
return this;
}
public Object[] getArgs() {
return args;
}
public long getLoadCnt() {
return loadCnt;
}
public long getUseTotalTime() {
return useTotalTime;
}
/**
* 记录用时
*
* @param useTime 用时
* @return this
*/
public AutoLoadTO addUseTotalTime(long useTime) {
synchronized (this) {
this.loadCnt++;
this.useTotalTime += useTime;
}
return this;
}
/**
* 平均耗时
*
* @return long 平均耗时
*/
public long getAverageUseTime() {
if (loadCnt == 0) {
return 0;
}
return this.useTotalTime / this.loadCnt;
}
public int getExpire() {
return expire;
}
/**
* @param expire expire
* @return this
*/
public AutoLoadTO setExpire(int expire) {
this.expire = expire;
return this;
}
public void flushRequestTime(CacheWrapper<Object> cacheWrapper) {
// 同步最后加载时间
this.setLastRequestTime(System.currentTimeMillis())
// 同步加载时间
.setLastLoadTime(cacheWrapper.getLastLoadTime())
// 同步过期时间
.setExpire(cacheWrapper.getExpire());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AutoLoadTO that = (AutoLoadTO) o;
return expire == that.expire &&
lastLoadTime == that.lastLoadTime &&
lastRequestTime == that.lastRequestTime &&
firstRequestTime == that.firstRequestTime &&
requestTimes == that.requestTimes &&
loading == that.loading &&
loadCnt == that.loadCnt &&
useTotalTime == that.useTotalTime &&
Objects.equals(joinPoint, that.joinPoint) &&
Arrays.equals(args, that.args) &&
Objects.equals(cache, that.cache) &&
Objects.equals(cacheKey, that.cacheKey);
}
@Override
public int hashCode() {
int result = Objects.hash(joinPoint, cache, expire, cacheKey, lastLoadTime, lastRequestTime, firstRequestTime, requestTimes, loading, loadCnt, useTotalTime);
result = 31 * result + Arrays.hashCode(args);
return result;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "AutoLoadTO{" +
"joinPoint=" + joinPoint +
", args=" + Arrays.toString(args) +
", cache=" + cache +
", expire=" + expire +
", cacheKey=" + cacheKey +
", lastLoadTime=" + lastLoadTime +
", lastRequestTime=" + lastRequestTime +
", firstRequestTime=" + firstRequestTime +
", requestTimes=" + requestTimes +
", loading=" + loading +
", loadCnt=" + loadCnt +
", useTotalTime=" + useTotalTime +
'}';
| 1,499 | 159 | 1,658 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheKeyTO.java | CacheKeyTO | getCacheKey | class CacheKeyTO implements Serializable {
private static final long serialVersionUID = 7229320497442357252L;
private final String namespace;
private final String key;// 缓存Key
private final String hfield;// 设置哈希表中的字段,如果设置此项,则用哈希表进行存储
public CacheKeyTO(String namespace, String key, String hfield) {
this.namespace = namespace;
this.key = key;
this.hfield = hfield;
}
public String getCacheKey() {<FILL_FUNCTION_BODY>}
public String getLockKey() {
StringBuilder key = new StringBuilder(getCacheKey());
if (null != hfield && hfield.length() > 0) {
key.append(":").append(hfield);
}
key.append(":lock");
return key.toString();
}
public String getNamespace() {
return namespace;
}
public String getHfield() {
return hfield;
}
public String getKey() {
return key;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKeyTO that = (CacheKeyTO) o;
return Objects.equals(namespace, that.namespace) &&
Objects.equals(key, that.key) &&
Objects.equals(hfield, that.hfield);
}
@Override
public int hashCode() {
return Objects.hash(namespace, key, hfield);
}
@Override
public String toString() {
return "CacheKeyTO{" +
"namespace='" + namespace + '\'' +
", key='" + key + '\'' +
", hfield='" + hfield + '\'' +
'}';
}
} |
if (null != this.namespace && this.namespace.length() > 0) {
return new StringBuilder(this.namespace).append(":").append(this.key).toString();
}
return this.key;
| 506 | 57 | 563 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/CacheWrapper.java | CacheWrapper | clone | class CacheWrapper<T> implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/**
* 缓存数据
*/
private T cacheObject;
/**
* 最后加载时间
*/
private long lastLoadTime;
/**
* 缓存时长
*/
private int expire;
public CacheWrapper() {
}
public CacheWrapper(T cacheObject, int expire) {
this.cacheObject = cacheObject;
this.lastLoadTime = System.currentTimeMillis();
this.expire = expire;
}
public CacheWrapper(T cacheObject, int expire, long lastLoadTime) {
this.cacheObject = cacheObject;
this.lastLoadTime = lastLoadTime;
this.expire = expire;
}
/**
* 判断缓存是否已经过期
*
* @return boolean
*/
public boolean isExpired() {
if (expire > 0) {
return (System.currentTimeMillis() - lastLoadTime) > expire * 1000;
}
return false;
}
public int getExpire() {
return expire;
}
public void setCacheObject(T cacheObject) {
this.cacheObject = cacheObject;
}
public long getLastLoadTime() {
return lastLoadTime;
}
public T getCacheObject() {
return cacheObject;
}
public void setLastLoadTime(long lastLoadTime) {
this.lastLoadTime = lastLoadTime;
}
public void setExpire(int expire) {
this.expire = expire;
}
@Override
public Object clone() throws CloneNotSupportedException {<FILL_FUNCTION_BODY>}
} |
@SuppressWarnings("unchecked")
CacheWrapper<T> tmp = (CacheWrapper<T>) super.clone();
tmp.setCacheObject(this.cacheObject);
return tmp;
| 479 | 53 | 532 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/cache/to/ProcessingTO.java | ProcessingTO | toString | class ProcessingTO {
private volatile long startTime;
private volatile CacheWrapper<Object> cache;
private volatile boolean firstFinished = false;
private volatile Throwable error;
public ProcessingTO() {
startTime = System.currentTimeMillis();
}
public CacheWrapper<Object> getCache() {
return cache;
}
public void setCache(CacheWrapper<Object> cache) {
this.cache = cache;
}
public void setFirstFinished(boolean firstFinished) {
this.firstFinished = firstFinished;
}
public boolean isFirstFinished() {
return this.firstFinished;
}
public long getStartTime() {
return startTime;
}
public void setError(Throwable error) {
this.error = error;
}
public Throwable getError() {
return this.error;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProcessingTO that = (ProcessingTO) o;
return startTime == that.startTime &&
firstFinished == that.firstFinished &&
Objects.equals(cache, that.cache) &&
Objects.equals(error, that.error);
}
@Override
public int hashCode() {
return Objects.hash(startTime, cache, firstFinished, error);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "ProcessingTO{" +
"startTime=" + startTime +
", cache=" + cache +
", firstFinished=" + firstFinished +
", error=" + error +
'}';
| 418 | 59 | 477 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/BeanUtil.java | BeanUtil | toString | class BeanUtil {
@SuppressWarnings("rawtypes")
private static final ConcurrentHashMap<Class, Field[]> FIELDS_CAHCE = new ConcurrentHashMap<Class, Field[]>();
/**
* 是否为基础数据类型
*
* @param obj Object
* @return boolean true or false
*/
public static boolean isPrimitive(Object obj) {
boolean rv = obj.getClass().isPrimitive() || obj instanceof String || obj instanceof Integer
|| obj instanceof Long || obj instanceof Byte || obj instanceof Character || obj instanceof Boolean
|| obj instanceof Short || obj instanceof Float || obj instanceof Double || obj instanceof BigDecimal
|| obj instanceof BigInteger;
return rv;
}
/**
* 把Bean转换为字符串
*
* @param obj Object
* @return String String
*/
@SuppressWarnings("rawtypes")
public static String toString(Object obj) {<FILL_FUNCTION_BODY>}
} |
if (obj == null) {
return "null";
}
Class cl = obj.getClass();
if (isPrimitive(obj)) {
return String.valueOf(obj);
} else if (obj instanceof Enum) {
return ((Enum) obj).name();
} else if (obj instanceof Date) {
return String.valueOf(((Date) obj).getTime());
} else if (obj instanceof Calendar) {
return String.valueOf(((Calendar) obj).getTime().getTime());
} else if (cl.isArray()) {
String r = "[";
int len = Array.getLength(obj);
for (int i = 0; i < len; i++) {
if (i > 0) {
r += ",";
}
Object val = Array.get(obj, i);
r += toString(val);
}
return r + "]";
} else if (obj instanceof Collection) {
Collection tempCol = (Collection) obj;
Iterator it = tempCol.iterator();
String r = "[";
for (int i = 0; it.hasNext(); i++) {
if (i > 0) {
r += ",";
}
Object val = it.next();
r += toString(val);
}
return r + "]";
} else if (obj instanceof Map) {
Map tempMap = (Map) obj;
String r = "{";
Iterator it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Entry) it.next();
Object key = entry.getKey();
r += toString(key);
r += "=";
Object val = entry.getValue();
r += toString(val);
if (it.hasNext()) {
r += ",";
}
}
return r + "}";
} else if (obj instanceof Class) {
Class tmpCls = (Class) obj;
return tmpCls.getName();
}
String r = cl.getName();
do {
Field[] fields = FIELDS_CAHCE.get(cl);
if (null == fields) {
fields = cl.getDeclaredFields();
if (null != fields) {
AccessibleObject.setAccessible(fields, true);
}
FIELDS_CAHCE.put(cl, fields);
}
if (null == fields || fields.length == 0) {
cl = cl.getSuperclass();
continue;
}
r += "[";
// get the names and values of all fields
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers())) {
continue;
}
if (f.isSynthetic() || f.getName().indexOf("this$") != -1) {
continue;
}
r += f.getName() + "=";
try {
Object val = f.get(obj);
r += toString(val);
} catch (Exception e) {
e.printStackTrace();
}
r += ",";
}
String comma = ",";
if (r.endsWith(comma)) {
r = r.substring(0, r.length() - 1);
}
r += "]";
cl = cl.getSuperclass();
} while (cl != null);
return r;
| 256 | 871 | 1,127 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-common/src/main/java/com/jarvis/lib/util/StringUtil.java | StringUtil | containsText | class StringUtil {
/**
* Check whether the given {@code CharSequence} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code CharSequence} is not {@code null}, its length is greater than
* 0, and it contains at least one non-whitespace character.
* <p><pre class="code">
* StringUtils.hasText(null) = false
* StringUtils.hasText("") = false
* StringUtils.hasText(" ") = false
* StringUtils.hasText("12345") = true
* StringUtils.hasText(" 12345 ") = true
* </pre>
* @param str the {@code CharSequence} to check (may be {@code null})
* @return {@code true} if the {@code CharSequence} is not {@code null},
* its length is greater than 0, and it does not contain whitespace only
* @see Character#isWhitespace
*/
public static boolean hasText(CharSequence str) {
return (str != null && str.length() > 0 && containsText(str));
}
/**
* Check whether the given {@code String} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code String} is not {@code null}, its length is greater than 0,
* and it contains at least one non-whitespace character.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null}, its
* length is greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText(String str) {
return (str != null && !str.isEmpty() && containsText(str));
}
private static boolean containsText(CharSequence str) {<FILL_FUNCTION_BODY>}
} |
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
| 511 | 66 | 577 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/CacheHelper.java | CacheHelper | initDeleteCacheKeysSet | class CacheHelper {
private static final ThreadLocal<CacheOpType> OP_TYPE = new ThreadLocal<CacheOpType>();
private static final ThreadLocal<Set<CacheKeyTO>> DELETE_CACHE_KEYS = new ThreadLocal<Set<CacheKeyTO>>();
/**
* 获取CacheOpType
*
* @return ThreadLocal中设置的CacheOpType
*/
public static CacheOpType getCacheOpType() {
return OP_TYPE.get();
}
/**
* 设置CacheOpType
*
* @param opType CacheOpType
*/
public static void setCacheOpType(CacheOpType opType) {
OP_TYPE.set(opType);
}
/**
* 移除CacheOpType
*/
public static void clearCacheOpType() {
OP_TYPE.remove();
}
public static void initDeleteCacheKeysSet() {<FILL_FUNCTION_BODY>}
public static Set<CacheKeyTO> getDeleteCacheKeysSet() {
return DELETE_CACHE_KEYS.get();
}
public static void addDeleteCacheKey(CacheKeyTO key) {
Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get();
if (null != set) {
set.add(key);
}
}
public static boolean isOnTransactional() {
Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get();
return null != set;
}
public static void clearDeleteCacheKeysSet() {
DELETE_CACHE_KEYS.remove();
}
} |
Set<CacheKeyTO> set = DELETE_CACHE_KEYS.get();
if (null == set) {
set = new HashSet<CacheKeyTO>();
DELETE_CACHE_KEYS.set(set);
}
| 421 | 66 | 487 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/ComboCacheManager.java | ComboCacheManager | mset | class ComboCacheManager implements ICacheManager {
/**
* 表达式解析器
*/
private final AbstractScriptParser scriptParser;
/**
* 本地缓存实现
*/
private ICacheManager localCache;
/**
* 远程缓存实现
*/
private ICacheManager remoteCache;
private static final Logger log = LoggerFactory.getLogger(ComboCacheManager.class);
public ComboCacheManager(ICacheManager localCache, ICacheManager remoteCache, AbstractScriptParser scriptParser) {
this.localCache = localCache;
this.remoteCache = remoteCache;
this.scriptParser = scriptParser;
}
@Override
public void setCache(CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method)
throws CacheCenterConnectionException {
if (method.isAnnotationPresent(LocalCache.class)) {
LocalCache lCache = method.getAnnotation(LocalCache.class);
setLocalCache(lCache, cacheKey, result, method);
// 只本地缓存
if (lCache.localOnly()) {
return;
}
}
remoteCache.setCache(cacheKey, result, method);
}
@Override
public void mset(Method method, Collection<MSetParam> params) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>}
private void setLocalCache(LocalCache lCache, CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) {
try {
LocalCacheWrapper<Object> localResult = new LocalCacheWrapper<Object>();
localResult.setLastLoadTime(System.currentTimeMillis());
int expire = scriptParser.getRealExpire(lCache.expire(), lCache.expireExpression(), null,
result.getCacheObject());
localResult.setExpire(expire);
localResult.setCacheObject(result.getCacheObject());
localResult.setRemoteExpire(result.getExpire());
localResult.setRemoteLastLoadTime(result.getLastLoadTime());
localCache.setCache(cacheKey, result, method);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@Override
public CacheWrapper<Object> get(CacheKeyTO key, Method method) throws CacheCenterConnectionException {
LocalCache lCache = null;
if (method.isAnnotationPresent(LocalCache.class)) {
lCache = method.getAnnotation(LocalCache.class);
}
String threadName = Thread.currentThread().getName();
// 如果是自动加载线程,则只从远程缓存获取。
if (null != lCache && !threadName.startsWith(AutoLoadHandler.THREAD_NAME_PREFIX)) {
CacheWrapper<Object> result = localCache.get(key, method);
if (null != result) {
if (result instanceof LocalCacheWrapper) {
LocalCacheWrapper<Object> localResult = (LocalCacheWrapper<Object>) result;
return new CacheWrapper<Object>(localResult.getCacheObject(), localResult.getRemoteExpire(), localResult.getRemoteLastLoadTime());
} else {
return result;
}
}
}
CacheWrapper<Object> result = remoteCache.get(key, method);
// 如果取到了则先放到本地缓存里
if (null != lCache && result != null) {
setLocalCache(lCache, key, result, method);
}
return result;
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) throws CacheCenterConnectionException {
LocalCache lCache = null;
if (method.isAnnotationPresent(LocalCache.class)) {
lCache = method.getAnnotation(LocalCache.class);
} else {
return remoteCache.mget(method, returnType, keys);
}
String threadName = Thread.currentThread().getName();
Map<CacheKeyTO, CacheWrapper<Object>> all;
Map<CacheKeyTO, CacheWrapper<Object>> remoteResults = null;
if (!threadName.startsWith(AutoLoadHandler.THREAD_NAME_PREFIX)) {
all = new HashMap<>(keys.size());
Map<CacheKeyTO, CacheWrapper<Object>> localResults = localCache.mget(method, returnType, keys);
if (null != localResults && !localResults.isEmpty()) {
Iterator<Map.Entry<CacheKeyTO, CacheWrapper<Object>>> iterator = localResults.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<CacheKeyTO, CacheWrapper<Object>> item = iterator.next();
CacheWrapper<Object> result = item.getValue();
if (result instanceof LocalCacheWrapper) {
LocalCacheWrapper<Object> localResult = (LocalCacheWrapper<Object>) result;
CacheWrapper<Object> result2 = new CacheWrapper<Object>(localResult.getCacheObject(), localResult.getRemoteExpire(), localResult.getRemoteLastLoadTime());
all.put(item.getKey(), result2);
} else {
all.put(item.getKey(), result);
}
}
}
if(all.size() < keys.size()) {
Set<CacheKeyTO> unCachekeys = new HashSet<>(keys.size() - all.size());
for(CacheKeyTO key : keys) {
if(!all.containsKey(key)) {
unCachekeys.add(key);
}
}
remoteResults = remoteCache.mget(method, returnType, keys);
if(null != remoteResults && !remoteResults.isEmpty()) {
all.putAll(remoteResults);
}
}
} else {
remoteResults = remoteCache.mget(method, returnType, keys);
all = remoteResults;
}
if(null != remoteResults && !remoteResults.isEmpty()) {
// 放到本地缓存里
Iterator<Map.Entry<CacheKeyTO, CacheWrapper<Object>>> iterator = remoteResults.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<CacheKeyTO, CacheWrapper<Object>> item = iterator.next();
setLocalCache(lCache, item.getKey(), item.getValue(), method);
}
}
return all;
}
@Override
public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException {
localCache.delete(keys);
remoteCache.delete(keys);
}
} |
if (method.isAnnotationPresent(LocalCache.class)) {
LocalCache lCache = method.getAnnotation(LocalCache.class);
for (MSetParam param : params) {
if (param == null) {
continue;
}
setLocalCache(lCache, param.getCacheKey(), param.getResult(), method);
}
// 只本地缓存
if (lCache.localOnly()) {
return;
}
}
remoteCache.mset(method, params);
| 1,647 | 131 | 1,778 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/DataLoaderFactory.java | DataLoaderFactory | getDataLoader | class DataLoaderFactory extends BasePooledObjectFactory<DataLoader> {
private static volatile DataLoaderFactory instance;
private final GenericObjectPool<DataLoader> factory;
private DataLoaderFactory() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1024);
config.setMaxIdle(50);
config.setMinIdle(8);
// 当Pool中没有对象时不等待,而是直接new个新的
config.setBlockWhenExhausted(false);
AbandonedConfig abandonConfig = new AbandonedConfig();
abandonConfig.setRemoveAbandonedTimeout(300);
abandonConfig.setRemoveAbandonedOnBorrow(true);
abandonConfig.setRemoveAbandonedOnMaintenance(true);
factory = new GenericObjectPool<DataLoader>(this, config, abandonConfig);
}
public static DataLoaderFactory getInstance() {
if (null == instance) {
synchronized (DataLoaderFactory.class) {
if (null == instance) {
instance = new DataLoaderFactory();
}
}
}
return instance;
}
public DataLoader getDataLoader() {<FILL_FUNCTION_BODY>}
public void returnObject(DataLoader loader) {
loader.reset();
factory.returnObject(loader);
}
@Override
public DataLoader create() throws Exception {
return new DataLoader();
}
@Override
public PooledObject<DataLoader> wrap(DataLoader obj) {
return new DefaultPooledObject<DataLoader>(obj);
}
} |
try {
return factory.borrowObject();
} catch (Exception e) {
e.printStackTrace();
}
return new DataLoader();
| 411 | 43 | 454 | <methods>public void <init>() ,public void activateObject(PooledObject<com.jarvis.cache.DataLoader>) throws java.lang.Exception,public abstract com.jarvis.cache.DataLoader create() throws java.lang.Exception,public void destroyObject(PooledObject<com.jarvis.cache.DataLoader>) throws java.lang.Exception,public PooledObject<com.jarvis.cache.DataLoader> makeObject() throws java.lang.Exception,public void passivateObject(PooledObject<com.jarvis.cache.DataLoader>) throws java.lang.Exception,public boolean validateObject(PooledObject<com.jarvis.cache.DataLoader>) ,public abstract PooledObject<com.jarvis.cache.DataLoader> wrap(com.jarvis.cache.DataLoader) <variables> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/DeleteCacheMagicHandler.java | DeleteCacheMagicHandler | getCacheKeyForMagic | class DeleteCacheMagicHandler {
private final CacheHandler cacheHandler;
private final DeleteCacheAopProxyChain jp;
private final CacheDeleteMagicKey[] cacheDeleteKeys;
private final Object[] arguments;
private final Method method;
private final Object retVal;
private final Object target;
private final String methodName;
private final Class<?>[] parameterTypes;
public DeleteCacheMagicHandler(CacheHandler cacheHandler, DeleteCacheAopProxyChain jp, CacheDeleteMagicKey[] cacheDeleteKeys, Object retVal) {
this.cacheHandler = cacheHandler;
this.jp = jp;
this.cacheDeleteKeys = cacheDeleteKeys;
this.arguments = jp.getArgs();
this.method = jp.getMethod();
this.retVal = retVal;
this.target = jp.getTarget();
this.methodName = jp.getMethod().getName();
this.parameterTypes = method.getParameterTypes();
}
/**
* @param cacheDeleteKey
* @return
* @throws Exception
*/
private void isMagic(CacheDeleteMagicKey cacheDeleteKey) throws Exception {
String key = cacheDeleteKey.value();
if (null == key || key.length() == 0) {
throw new Exception("value不允许为空");
}
int iterableArgIndex = cacheDeleteKey.iterableArgIndex();
if (parameterTypes.length > 0 && iterableArgIndex >= 0) {
if (iterableArgIndex >= parameterTypes.length) {
throw new Exception("iterableArgIndex必须小于参数长度:" + parameterTypes.length);
}
if (iterableArgIndex >= 0 && cacheDeleteKey.iterableReturnValue()) {
throw new Exception("不支持iterableArgIndex大于0且iterableReturnValue=true的情况");
}
Class<?> tmp = parameterTypes[iterableArgIndex];
if (tmp.isArray() || Collection.class.isAssignableFrom(tmp)) {
//rv = true;
} else {
throw new Exception("magic模式下,参数" + iterableArgIndex + "必须是数组或Collection的类型");
}
}
if (cacheDeleteKey.iterableReturnValue()) {
Class<?> returnType = method.getReturnType();
if (returnType.isArray() || Collection.class.isAssignableFrom(returnType)) {
// rv = true;
} else {
throw new Exception("当iterableReturnValue=true时,返回值必须是数组或Collection的类型");
}
}
}
public List<List<CacheKeyTO>> getCacheKeyForMagic() throws Exception {<FILL_FUNCTION_BODY>}
private List<CacheKeyTO> splitReturnValueOnly(CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception {
if (null == retVal) {
return Collections.emptyList();
}
List<CacheKeyTO> list;
if (retVal.getClass().isArray()) {
Object[] newValues = (Object[]) retVal;
list = new ArrayList<>(newValues.length);
for (Object value : newValues) {
if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, arguments, value)) {
continue;
}
list.add(this.cacheHandler.getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, value, true));
}
} else if (retVal instanceof Collection) {
Collection<Object> newValues = (Collection<Object>) retVal;
list = new ArrayList<>(newValues.size());
for (Object value : newValues) {
if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, arguments, value)) {
continue;
}
list.add(this.cacheHandler.getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, value, true));
}
} else {
return Collections.emptyList();
}
return list;
}
private List<CacheKeyTO> splitArgOnly(CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception {
int iterableArgIndex = cacheDeleteKey.iterableArgIndex();
Object tmpArg = arguments[iterableArgIndex];
List<CacheKeyTO> list = null;
if (tmpArg instanceof Collection) {
Collection<Object> iterableCollectionArg = (Collection<Object>) tmpArg;
list = new ArrayList<>(iterableCollectionArg.size());
for (Object arg : iterableCollectionArg) {
Optional<CacheKeyTO> tmp = getKey(arg, cacheDeleteKey, retVal, keyExpression, hfieldExpression);
if (tmp.isPresent()) {
list.add(tmp.get());
}
}
} else if (tmpArg.getClass().isArray()) {
Object[] iterableArrayArg = (Object[]) tmpArg;
list = new ArrayList<>(iterableArrayArg.length);
for (Object arg : iterableArrayArg) {
Optional<CacheKeyTO> tmp = getKey(arg, cacheDeleteKey, retVal, keyExpression, hfieldExpression);
if (tmp.isPresent()) {
list.add(tmp.get());
}
}
} else {
return Collections.emptyList();
}
return list;
}
private Optional<CacheKeyTO> getKey(Object arg, CacheDeleteMagicKey cacheDeleteKey, Object retVal, String keyExpression, String hfieldExpression) throws Exception {
Object[] tmpArgs = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (i == cacheDeleteKey.iterableArgIndex()) {
tmpArgs[i] = arg;
} else {
tmpArgs[i] = arguments[i];
}
}
if (!cacheHandler.getScriptParser().isCanDelete(cacheDeleteKey, tmpArgs, retVal)) {
return Optional.empty();
}
return Optional.of(this.cacheHandler.getCacheKey(target, methodName, tmpArgs, keyExpression, hfieldExpression, retVal, true));
}
} |
List<List<CacheKeyTO>> lists = new ArrayList<>(cacheDeleteKeys.length);
for (CacheDeleteMagicKey cacheDeleteKey : cacheDeleteKeys) {
isMagic(cacheDeleteKey);
String keyExpression = cacheDeleteKey.value();
String hfieldExpression = cacheDeleteKey.hfield();
// 只对返回值进行分割处理
if (parameterTypes.length == 0 || cacheDeleteKey.iterableArgIndex() < 0) {
if (cacheDeleteKey.iterableReturnValue()) {
lists.add(splitReturnValueOnly(cacheDeleteKey, retVal, keyExpression, hfieldExpression));
}
continue;
}
int iterableArgIndex = cacheDeleteKey.iterableArgIndex();
// 只对参数进行分割处理
if (iterableArgIndex >= 0 && !cacheDeleteKey.iterableReturnValue()) {
lists.add(splitArgOnly(cacheDeleteKey, retVal, keyExpression, hfieldExpression));
continue;
}
if (iterableArgIndex >= 0 && cacheDeleteKey.iterableReturnValue()) {
}
}
return lists;
| 1,559 | 280 | 1,839 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-core/src/main/java/com/jarvis/cache/RefreshHandler.java | RefreshHandler | doRefresh | class RefreshHandler {
private static final Logger log = LoggerFactory.getLogger(RefreshHandler.class);
private static final int REFRESH_MIN_EXPIRE = 120;
private static final int ONE_THOUSAND_MS = 1000;
/**
* 刷新缓存线程池
*/
private final ThreadPoolExecutor refreshThreadPool;
/**
* 正在刷新缓存队列
*/
private final ConcurrentHashMap<CacheKeyTO, Byte> refreshing;
private final CacheHandler cacheHandler;
public RefreshHandler(CacheHandler cacheHandler, AutoLoadConfig config) {
this.cacheHandler = cacheHandler;
int corePoolSize = config.getRefreshThreadPoolSize();// 线程池的基本大小
int maximumPoolSize = config.getRefreshThreadPoolMaxSize();// 线程池最大大小,线程池允许创建的最大线程数。如果队列满了,并且已创建的线程数小于最大线程数,则线程池会再创建新的线程执行任务。值得注意的是如果使用了无界的任务队列这个参数就没什么效果。
int keepAliveTime = config.getRefreshThreadPoolkeepAliveTime();
TimeUnit unit = TimeUnit.MINUTES;
int queueCapacity = config.getRefreshQueueCapacity();// 队列容量
refreshing = new ConcurrentHashMap<CacheKeyTO, Byte>(queueCapacity);
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(queueCapacity);
RejectedExecutionHandler rejectedHandler = new RefreshRejectedExecutionHandler();
refreshThreadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, queue,
new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix = "autoload-cache-RefreshHandler-";
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
t.setDaemon(true);
return t;
}
}, rejectedHandler);
}
public void removeTask(CacheKeyTO cacheKey) {
refreshing.remove(cacheKey);
}
public void doRefresh(CacheAopProxyChain pjp, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) {<FILL_FUNCTION_BODY>}
public void shutdown() {
refreshThreadPool.shutdownNow();
try {
refreshThreadPool.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class RefreshTask implements Runnable {
private final CacheAopProxyChain pjp;
private final Cache cache;
private final CacheKeyTO cacheKey;
private final CacheWrapper<Object> cacheWrapper;
private final Object[] arguments;
public RefreshTask(CacheAopProxyChain pjp, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper)
throws Exception {
this.pjp = pjp;
this.cache = cache;
this.cacheKey = cacheKey;
this.cacheWrapper = cacheWrapper;
if (cache.argumentsDeepCloneEnable()) {
// 进行深度复制(因为是异步执行,防止外部修改参数值)
this.arguments = (Object[]) cacheHandler.getCloner().deepCloneMethodArgs(pjp.getMethod(),
pjp.getArgs());
} else {
this.arguments = pjp.getArgs();
}
}
@Override
public void run() {
DataLoader dataLoader;
if(cacheHandler.getAutoLoadConfig().isDataLoaderPooled()) {
DataLoaderFactory factory = DataLoaderFactory.getInstance();
dataLoader = factory.getDataLoader();
} else {
dataLoader = new DataLoader();
}
CacheWrapper<Object> newCacheWrapper = null;
boolean isFirst = false;
try {
newCacheWrapper = dataLoader.init(pjp, cacheKey, cache, cacheHandler, arguments).loadData()
.getCacheWrapper();
} catch (Throwable ex) {
log.error(ex.getMessage(), ex);
} finally {
// dataLoader 的数据必须在放回对象池之前获取
isFirst = dataLoader.isFirst();
if(cacheHandler.getAutoLoadConfig().isDataLoaderPooled()) {
DataLoaderFactory factory = DataLoaderFactory.getInstance();
factory.returnObject(dataLoader);
}
}
if (isFirst) {
// 如果数据加载失败,则把旧数据进行续租
if (null == newCacheWrapper && null != cacheWrapper) {
int newExpire = cacheWrapper.getExpire() / 2;
if (newExpire < 120) {
newExpire = 120;
}
newCacheWrapper = new CacheWrapper<Object>(cacheWrapper.getCacheObject(), newExpire);
}
try {
if (null != newCacheWrapper) {
cacheHandler.writeCache(pjp, arguments, cache, cacheKey, newCacheWrapper);
}
} catch (Throwable e) {
log.error(e.getMessage(), e);
}
}
refreshing.remove(cacheKey);
}
public CacheKeyTO getCacheKey() {
return cacheKey;
}
}
class RefreshRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
Runnable last = e.getQueue().poll();
if (last instanceof RefreshTask) {
RefreshTask lastTask = (RefreshTask) last;
refreshing.remove(lastTask.getCacheKey());
}
e.execute(r);
}
}
}
} |
int expire = cacheWrapper.getExpire();
if (expire < REFRESH_MIN_EXPIRE) {// 如果过期时间太小了,就不允许自动加载,避免加载过于频繁,影响系统稳定性
return;
}
// 计算超时时间
int alarmTime = cache.alarmTime();
long timeout;
if (alarmTime > 0 && alarmTime < expire) {
timeout = expire - alarmTime;
} else {
if (expire >= 600) {
timeout = expire - REFRESH_MIN_EXPIRE;
} else {
timeout = expire - 60;
}
}
if ((System.currentTimeMillis() - cacheWrapper.getLastLoadTime()) < (timeout * ONE_THOUSAND_MS)) {
return;
}
Byte tmpByte = refreshing.get(cacheKey);
// 如果有正在刷新的请求,则不处理
if (null != tmpByte) {
return;
}
tmpByte = 1;
if (null == refreshing.putIfAbsent(cacheKey, tmpByte)) {
try {
refreshThreadPool.execute(new RefreshTask(pjp, cache, cacheKey, cacheWrapper));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
| 1,526 | 349 | 1,875 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-lock/autoload-cache-lock-jedis/src/main/java/com/jarvis/cache/lock/ShardedJedisLock.java | ShardedJedisLock | setnx | class ShardedJedisLock extends AbstractRedisLock {
private ShardedJedisPool shardedJedisPool;
public ShardedJedisLock(ShardedJedisPool shardedJedisPool) {
this.shardedJedisPool = shardedJedisPool;
}
private void returnResource(ShardedJedis shardedJedis) {
shardedJedis.close();
}
@Override
protected boolean setnx(String key, String val, int expire) {<FILL_FUNCTION_BODY>}
@Override
protected void del(String key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
Jedis jedis = shardedJedis.getShard(key);
jedis.del(key);
} finally {
returnResource(shardedJedis);
}
}
} |
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
Jedis jedis = shardedJedis.getShard(key);
return OK.equalsIgnoreCase(jedis.set(key, val, SetParams.setParams().nx().ex(expire)));
} finally {
returnResource(shardedJedis);
}
| 254 | 113 | 367 | <methods>public non-sealed void <init>() ,public boolean tryLock(java.lang.String, int) ,public void unlock(java.lang.String) <variables>protected static final java.lang.String EX,private static final ThreadLocal<Map<java.lang.String,com.jarvis.cache.to.RedisLockInfo>> LOCK_START_TIME,protected static final java.lang.String NX,protected static final java.lang.String OK,private static final org.slf4j.Logger logger |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-lock/autoload-cache-lock-redis/src/main/java/com/jarvis/cache/lock/AbstractRedisLock.java | AbstractRedisLock | unlock | class AbstractRedisLock implements ILock {
private static final Logger logger = LoggerFactory.getLogger(AbstractRedisLock.class);
private static final ThreadLocal<Map<String, RedisLockInfo>> LOCK_START_TIME = new ThreadLocal<Map<String, RedisLockInfo>>() {
@Override
protected Map<String, RedisLockInfo> initialValue() {
return new HashMap<>(4);
}
};
protected static final String OK = "OK";
protected static final String NX = "NX";
protected static final String EX = "EX";
/**
* SETNX
*
* @param key key
* @param val vale
* @param expire 过期时间
* @return 是否设置成功
*/
protected abstract boolean setnx(String key, String val, int expire);
/**
* DEL
*
* @param key key
*/
protected abstract void del(String key);
@Override
public boolean tryLock(String key, int lockExpire) {
boolean locked = setnx(key, OK, lockExpire);
if (locked) {
Map<String, RedisLockInfo> startTimeMap = LOCK_START_TIME.get();
RedisLockInfo info = new RedisLockInfo();
info.setLeaseTime(lockExpire * 1000);
info.setStartTime(System.currentTimeMillis());
startTimeMap.put(key, info);
}
return locked;
}
@Override
public void unlock(String key) {<FILL_FUNCTION_BODY>}
} |
Map<String, RedisLockInfo> startTimeMap = LOCK_START_TIME.get();
RedisLockInfo info = null;
if (null != startTimeMap) {
info = startTimeMap.remove(key);
}
// 如果实际执行时长超过租约时间则不需要主到释放锁
long useTime = System.currentTimeMillis() - info.getStartTime();
if (null != info && useTime >= info.getLeaseTime()) {
logger.warn("lock(" + key + ") run timeout, use time:" + useTime);
return;
}
try {
del(key);
} catch (Throwable e) {
}
| 423 | 175 | 598 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisClusterCacheManager.java | JedisClusterClient | mget | class JedisClusterClient implements IRedis {
private final JedisCluster jedisCluster;
private final AbstractRedisCacheManager cacheManager;
public JedisClusterClient(JedisCluster jedisCluster, AbstractRedisCacheManager cacheManager) {
this.jedisCluster = jedisCluster;
this.cacheManager = cacheManager;
}
@Override
public void close() throws IOException {
}
@Override
public void set(byte[] key, byte[] value) {
jedisCluster.set(key, value);
}
@Override
public void setex(byte[] key, int seconds, byte[] value) {
jedisCluster.setex(key, seconds, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value) {
jedisCluster.hset(key, field, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) {
@Override
public void execute(JedisClusterPipeline pipeline) {
pipeline.hset(key, field, value);
pipeline.expire(key, seconds);
}
};
try {
retryableJedisClusterPipeline.sync();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@Override
public void mset(Collection<MSetParam> params) {
RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) {
@Override
public void execute(JedisClusterPipeline pipeline) throws Exception {
JedisUtil.executeMSet(pipeline, cacheManager, params);
}
};
try {
retryableJedisClusterPipeline.sync();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
@Override
public byte[] get(byte[] key) {
return jedisCluster.get(key);
}
@Override
public byte[] hget(byte[] key, byte[] field) {
return jedisCluster.hget(key, field);
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void delete(Set<CacheKeyTO> keys) {
RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) {
@Override
public void execute(JedisClusterPipeline pipeline) {
JedisUtil.executeDelete(pipeline, keys);
}
};
try {
retryableJedisClusterPipeline.sync();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} |
RetryableJedisClusterPipeline retryableJedisClusterPipeline = new RetryableJedisClusterPipeline(jedisCluster) {
@Override
public void execute(JedisClusterPipeline pipeline) {
JedisUtil.executeMGet(pipeline, keys);
}
};
return cacheManager.deserialize(keys, retryableJedisClusterPipeline.syncAndReturnAll(), returnType);
| 813 | 112 | 925 | <methods>public void <init>(ISerializer<java.lang.Object>) ,public void delete(Set<com.jarvis.cache.to.CacheKeyTO>) throws com.jarvis.cache.exception.CacheCenterConnectionException,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> deserialize(Set<com.jarvis.cache.to.CacheKeyTO>, Collection<java.lang.Object>, java.lang.reflect.Type) throws java.lang.Exception,public CacheWrapper<java.lang.Object> get(com.jarvis.cache.to.CacheKeyTO, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public int getHashExpire() ,public ISerializer<java.lang.Object> getSerializer() ,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> mget(java.lang.reflect.Method, java.lang.reflect.Type, Set<com.jarvis.cache.to.CacheKeyTO>) ,public void mset(java.lang.reflect.Method, Collection<com.jarvis.cache.MSetParam>) ,public void setCache(com.jarvis.cache.to.CacheKeyTO, CacheWrapper<java.lang.Object>, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public void setHashExpire(int) <variables>public static final com.jarvis.cache.serializer.StringSerializer KEY_SERIALIZER,protected int hashExpire,private static final org.slf4j.Logger log,protected final non-sealed ISerializer<java.lang.Object> serializer |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisClusterPipeline.java | JedisClusterPipeline | innerSync | class JedisClusterPipeline extends PipelineBase implements Closeable {
private final JedisClusterInfoCache clusterInfoCache;
/**
* 根据顺序存储每个命令对应的Client
*/
private final Queue<Client> clients;
/**
* 用于缓存连接
*/
private final Map<JedisPool, Jedis> jedisMap;
public JedisClusterPipeline(JedisClusterInfoCache clusterInfoCache) {
this.clusterInfoCache = clusterInfoCache;
this.clients = new LinkedList<>();
this.jedisMap = new HashMap<>(3);
}
/**
* 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化
*/
protected void sync() {
innerSync(null);
}
/**
* 同步读取所有数据 并按命令顺序返回一个列表
*
* @return 按照命令的顺序返回所有的数据
*/
protected List<Object> syncAndReturnAll() {
List<Object> responseList = new ArrayList<>(clients.size());
innerSync(responseList);
return responseList;
}
private void innerSync(List<Object> formatted) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
clean();
clients.clear();
for (Jedis jedis : jedisMap.values()) {
flushCachedData(jedis);
jedis.close();
}
jedisMap.clear();
}
private void flushCachedData(Jedis jedis) {
try {
//FIXME 这个count怎么取值? 执行命令的个数??
jedis.getClient().getMany(jedisMap.size());
//jedis.getClient().getAll();
} catch (RuntimeException ex) {
// 其中一个client出问题,后面出问题的几率较大
}
}
@Override
protected Client getClient(String key) {
byte[] bKey = SafeEncoder.encode(key);
return getClient(bKey);
}
@Override
protected Client getClient(byte[] key) {
Client client = getClient(JedisClusterCRC16.getSlot(key));
clients.add(client);
return client;
}
private Client getClient(int slot) {
JedisPool pool = clusterInfoCache.getSlotPool(slot);
// 根据pool从缓存中获取Jedis
Jedis jedis = jedisMap.get(pool);
if (null == jedis) {
jedis = pool.getResource();
jedisMap.put(pool, jedis);
}
return jedis.getClient();
}
public JedisClusterInfoCache getClusterInfoCache() {
return clusterInfoCache;
}
public Queue<Client> getClients() {
return clients;
}
public Map<JedisPool, Jedis> getJedisMap() {
return jedisMap;
}
} |
try {
Response<?> response;
Object data;
for (Client client : clients) {
response = generateResponse(client.getOne());
if (null != formatted) {
data = response.get();
formatted.add(data);
}
}
} catch (JedisRedirectionException jre) {
throw jre;
} finally {
close();
}
| 824 | 107 | 931 | <methods>public void <init>() ,public Response<java.lang.Long> append(java.lang.String, java.lang.String) ,public Response<java.lang.Long> append(byte[], byte[]) ,public Response<java.lang.Long> bitcount(java.lang.String) ,public Response<java.lang.Long> bitcount(byte[]) ,public Response<java.lang.Long> bitcount(java.lang.String, long, long) ,public Response<java.lang.Long> bitcount(byte[], long, long) ,public transient Response<List<java.lang.Long>> bitfield(java.lang.String, java.lang.String[]) ,public transient Response<List<java.lang.Long>> bitfield(byte[], byte[][]) ,public transient Response<List<java.lang.Long>> bitfieldReadonly(byte[], byte[][]) ,public transient Response<List<java.lang.Long>> bitfieldReadonly(java.lang.String, java.lang.String[]) ,public Response<java.lang.Long> bitpos(java.lang.String, boolean) ,public Response<java.lang.Long> bitpos(byte[], boolean) ,public Response<java.lang.Long> bitpos(java.lang.String, boolean, redis.clients.jedis.BitPosParams) ,public Response<java.lang.Long> bitpos(byte[], boolean, redis.clients.jedis.BitPosParams) ,public Response<List<java.lang.String>> blpop(java.lang.String) ,public Response<List<byte[]>> blpop(byte[]) ,public Response<List<java.lang.String>> brpop(java.lang.String) ,public Response<List<byte[]>> brpop(byte[]) ,public Response<java.lang.Long> decr(java.lang.String) ,public Response<java.lang.Long> decr(byte[]) ,public Response<java.lang.Long> decrBy(java.lang.String, long) ,public Response<java.lang.Long> decrBy(byte[], long) ,public Response<java.lang.Long> del(java.lang.String) ,public Response<java.lang.Long> del(byte[]) ,public Response<byte[]> dump(java.lang.String) ,public Response<byte[]> dump(byte[]) ,public Response<java.lang.String> echo(java.lang.String) ,public Response<byte[]> echo(byte[]) ,public Response<java.lang.Boolean> exists(java.lang.String) ,public Response<java.lang.Boolean> exists(byte[]) ,public Response<java.lang.Long> expire(java.lang.String, int) ,public Response<java.lang.Long> expire(byte[], int) ,public Response<java.lang.Long> expireAt(java.lang.String, long) ,public Response<java.lang.Long> expireAt(byte[], long) ,public Response<java.lang.Long> geoadd(byte[], Map<byte[],redis.clients.jedis.GeoCoordinate>) ,public Response<java.lang.Long> geoadd(java.lang.String, Map<java.lang.String,redis.clients.jedis.GeoCoordinate>) ,public Response<java.lang.Long> geoadd(byte[], double, double, byte[]) ,public Response<java.lang.Long> geoadd(java.lang.String, double, double, java.lang.String) ,public Response<java.lang.Double> geodist(byte[], byte[], byte[]) ,public Response<java.lang.Double> geodist(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Double> geodist(byte[], byte[], byte[], redis.clients.jedis.GeoUnit) ,public Response<java.lang.Double> geodist(java.lang.String, java.lang.String, java.lang.String, redis.clients.jedis.GeoUnit) ,public transient Response<List<byte[]>> geohash(byte[], byte[][]) ,public transient Response<List<java.lang.String>> geohash(java.lang.String, java.lang.String[]) ,public transient Response<List<redis.clients.jedis.GeoCoordinate>> geopos(byte[], byte[][]) ,public transient Response<List<redis.clients.jedis.GeoCoordinate>> geopos(java.lang.String, java.lang.String[]) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadius(byte[], double, double, double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadius(java.lang.String, double, double, double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadius(byte[], double, double, double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadius(java.lang.String, double, double, double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMember(byte[], byte[], double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMember(java.lang.String, java.lang.String, double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMember(byte[], byte[], double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMember(java.lang.String, java.lang.String, double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMemberReadonly(byte[], byte[], double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMemberReadonly(java.lang.String, java.lang.String, double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMemberReadonly(byte[], byte[], double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusByMemberReadonly(java.lang.String, java.lang.String, double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusReadonly(byte[], double, double, double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusReadonly(java.lang.String, double, double, double, redis.clients.jedis.GeoUnit) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusReadonly(byte[], double, double, double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<List<redis.clients.jedis.GeoRadiusResponse>> georadiusReadonly(java.lang.String, double, double, double, redis.clients.jedis.GeoUnit, redis.clients.jedis.params.GeoRadiusParam) ,public Response<java.lang.String> get(java.lang.String) ,public Response<byte[]> get(byte[]) ,public Response<java.lang.String> getSet(java.lang.String, java.lang.String) ,public Response<byte[]> getSet(byte[], byte[]) ,public Response<java.lang.Boolean> getbit(java.lang.String, long) ,public Response<java.lang.Boolean> getbit(byte[], long) ,public Response<java.lang.String> getrange(java.lang.String, long, long) ,public Response<byte[]> getrange(byte[], long, long) ,public transient Response<java.lang.Long> hdel(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> hdel(byte[], byte[][]) ,public Response<java.lang.Boolean> hexists(java.lang.String, java.lang.String) ,public Response<java.lang.Boolean> hexists(byte[], byte[]) ,public Response<java.lang.String> hget(java.lang.String, java.lang.String) ,public Response<byte[]> hget(byte[], byte[]) ,public Response<Map<java.lang.String,java.lang.String>> hgetAll(java.lang.String) ,public Response<Map<byte[],byte[]>> hgetAll(byte[]) ,public Response<java.lang.Long> hincrBy(java.lang.String, java.lang.String, long) ,public Response<java.lang.Long> hincrBy(byte[], byte[], long) ,public Response<java.lang.Double> hincrByFloat(java.lang.String, java.lang.String, double) ,public Response<java.lang.Double> hincrByFloat(byte[], byte[], double) ,public Response<Set<java.lang.String>> hkeys(java.lang.String) ,public Response<Set<byte[]>> hkeys(byte[]) ,public Response<java.lang.Long> hlen(java.lang.String) ,public Response<java.lang.Long> hlen(byte[]) ,public transient Response<List<java.lang.String>> hmget(java.lang.String, java.lang.String[]) ,public transient Response<List<byte[]>> hmget(byte[], byte[][]) ,public Response<java.lang.String> hmset(java.lang.String, Map<java.lang.String,java.lang.String>) ,public Response<java.lang.String> hmset(byte[], Map<byte[],byte[]>) ,public Response<java.lang.Long> hset(java.lang.String, Map<java.lang.String,java.lang.String>) ,public Response<java.lang.Long> hset(byte[], Map<byte[],byte[]>) ,public Response<java.lang.Long> hset(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Long> hset(byte[], byte[], byte[]) ,public Response<java.lang.Long> hsetnx(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Long> hsetnx(byte[], byte[], byte[]) ,public Response<java.lang.Long> hstrlen(java.lang.String, java.lang.String) ,public Response<java.lang.Long> hstrlen(byte[], byte[]) ,public Response<List<java.lang.String>> hvals(java.lang.String) ,public Response<List<byte[]>> hvals(byte[]) ,public Response<java.lang.Long> incr(java.lang.String) ,public Response<java.lang.Long> incr(byte[]) ,public Response<java.lang.Long> incrBy(java.lang.String, long) ,public Response<java.lang.Long> incrBy(byte[], long) ,public Response<java.lang.Double> incrByFloat(java.lang.String, double) ,public Response<java.lang.Double> incrByFloat(byte[], double) ,public Response<java.lang.String> lindex(java.lang.String, long) ,public Response<byte[]> lindex(byte[], long) ,public Response<java.lang.Long> linsert(java.lang.String, redis.clients.jedis.ListPosition, java.lang.String, java.lang.String) ,public Response<java.lang.Long> linsert(byte[], redis.clients.jedis.ListPosition, byte[], byte[]) ,public Response<java.lang.Long> llen(java.lang.String) ,public Response<java.lang.Long> llen(byte[]) ,public Response<java.lang.String> lpop(java.lang.String) ,public Response<byte[]> lpop(byte[]) ,public transient Response<java.lang.Long> lpush(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> lpush(byte[], byte[][]) ,public transient Response<java.lang.Long> lpushx(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> lpushx(byte[], byte[][]) ,public Response<List<java.lang.String>> lrange(java.lang.String, long, long) ,public Response<List<byte[]>> lrange(byte[], long, long) ,public Response<java.lang.Long> lrem(java.lang.String, long, java.lang.String) ,public Response<java.lang.Long> lrem(byte[], long, byte[]) ,public Response<java.lang.String> lset(java.lang.String, long, java.lang.String) ,public Response<java.lang.String> lset(byte[], long, byte[]) ,public Response<java.lang.String> ltrim(java.lang.String, long, long) ,public Response<java.lang.String> ltrim(byte[], long, long) ,public Response<java.lang.String> migrate(java.lang.String, int, java.lang.String, int, int) ,public Response<java.lang.String> migrate(java.lang.String, int, byte[], int, int) ,public Response<java.lang.Long> move(java.lang.String, int) ,public Response<java.lang.Long> move(byte[], int) ,public Response<java.lang.String> objectEncoding(java.lang.String) ,public Response<byte[]> objectEncoding(byte[]) ,public Response<java.lang.Long> objectFreq(byte[]) ,public Response<java.lang.Long> objectFreq(java.lang.String) ,public Response<java.lang.Long> objectIdletime(java.lang.String) ,public Response<java.lang.Long> objectIdletime(byte[]) ,public Response<java.lang.Long> objectRefcount(java.lang.String) ,public Response<java.lang.Long> objectRefcount(byte[]) ,public Response<java.lang.Long> persist(java.lang.String) ,public Response<java.lang.Long> persist(byte[]) ,public Response<java.lang.Long> pexpire(java.lang.String, long) ,public Response<java.lang.Long> pexpire(byte[], long) ,public Response<java.lang.Long> pexpireAt(java.lang.String, long) ,public Response<java.lang.Long> pexpireAt(byte[], long) ,public transient Response<java.lang.Long> pfadd(byte[], byte[][]) ,public transient Response<java.lang.Long> pfadd(java.lang.String, java.lang.String[]) ,public Response<java.lang.Long> pfcount(byte[]) ,public Response<java.lang.Long> pfcount(java.lang.String) ,public Response<java.lang.String> psetex(java.lang.String, long, java.lang.String) ,public Response<java.lang.String> psetex(byte[], long, byte[]) ,public Response<java.lang.Long> pttl(java.lang.String) ,public Response<java.lang.Long> pttl(byte[]) ,public Response<java.lang.String> restore(java.lang.String, int, byte[]) ,public Response<java.lang.String> restore(byte[], int, byte[]) ,public Response<java.lang.String> restoreReplace(java.lang.String, int, byte[]) ,public Response<java.lang.String> restoreReplace(byte[], int, byte[]) ,public Response<java.lang.String> rpop(java.lang.String) ,public Response<byte[]> rpop(byte[]) ,public transient Response<java.lang.Long> rpush(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> rpush(byte[], byte[][]) ,public transient Response<java.lang.Long> rpushx(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> rpushx(byte[], byte[][]) ,public transient Response<java.lang.Long> sadd(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> sadd(byte[], byte[][]) ,public Response<java.lang.Long> scard(java.lang.String) ,public Response<java.lang.Long> scard(byte[]) ,public transient Response<java.lang.Object> sendCommand(java.lang.String, redis.clients.jedis.commands.ProtocolCommand, java.lang.String[]) ,public transient Response<java.lang.Object> sendCommand(byte[], redis.clients.jedis.commands.ProtocolCommand, byte[][]) ,public Response<java.lang.String> set(java.lang.String, java.lang.String) ,public Response<java.lang.String> set(byte[], byte[]) ,public Response<java.lang.String> set(java.lang.String, java.lang.String, redis.clients.jedis.params.SetParams) ,public Response<java.lang.String> set(byte[], byte[], redis.clients.jedis.params.SetParams) ,public Response<java.lang.Boolean> setbit(java.lang.String, long, boolean) ,public Response<java.lang.Boolean> setbit(byte[], long, byte[]) ,public Response<java.lang.String> setex(java.lang.String, int, java.lang.String) ,public Response<java.lang.String> setex(byte[], int, byte[]) ,public Response<java.lang.Long> setnx(java.lang.String, java.lang.String) ,public Response<java.lang.Long> setnx(byte[], byte[]) ,public Response<java.lang.Long> setrange(java.lang.String, long, java.lang.String) ,public Response<java.lang.Long> setrange(byte[], long, byte[]) ,public Response<java.lang.Boolean> sismember(java.lang.String, java.lang.String) ,public Response<java.lang.Boolean> sismember(byte[], byte[]) ,public Response<Set<java.lang.String>> smembers(java.lang.String) ,public Response<Set<byte[]>> smembers(byte[]) ,public Response<List<java.lang.String>> sort(java.lang.String) ,public Response<List<byte[]>> sort(byte[]) ,public Response<List<java.lang.String>> sort(java.lang.String, redis.clients.jedis.SortingParams) ,public Response<List<byte[]>> sort(byte[], redis.clients.jedis.SortingParams) ,public Response<java.lang.String> spop(java.lang.String) ,public Response<byte[]> spop(byte[]) ,public Response<Set<java.lang.String>> spop(java.lang.String, long) ,public Response<Set<byte[]>> spop(byte[], long) ,public Response<java.lang.String> srandmember(java.lang.String) ,public Response<byte[]> srandmember(byte[]) ,public Response<List<java.lang.String>> srandmember(java.lang.String, int) ,public Response<List<byte[]>> srandmember(byte[], int) ,public transient Response<java.lang.Long> srem(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> srem(byte[], byte[][]) ,public Response<java.lang.Long> strlen(java.lang.String) ,public Response<java.lang.Long> strlen(byte[]) ,public Response<java.lang.String> substr(java.lang.String, int, int) ,public Response<java.lang.String> substr(byte[], int, int) ,public Response<java.lang.Long> touch(java.lang.String) ,public Response<java.lang.Long> touch(byte[]) ,public Response<java.lang.Long> ttl(java.lang.String) ,public Response<java.lang.Long> ttl(byte[]) ,public Response<java.lang.String> type(java.lang.String) ,public Response<java.lang.String> type(byte[]) ,public Response<java.lang.Long> unlink(java.lang.String) ,public Response<java.lang.Long> unlink(byte[]) ,public transient Response<java.lang.Long> xack(java.lang.String, java.lang.String, redis.clients.jedis.StreamEntryID[]) ,public transient Response<java.lang.Long> xack(byte[], byte[], byte[][]) ,public Response<redis.clients.jedis.StreamEntryID> xadd(java.lang.String, redis.clients.jedis.StreamEntryID, Map<java.lang.String,java.lang.String>) ,public Response<byte[]> xadd(byte[], byte[], Map<byte[],byte[]>) ,public Response<redis.clients.jedis.StreamEntryID> xadd(java.lang.String, redis.clients.jedis.StreamEntryID, Map<java.lang.String,java.lang.String>, long, boolean) ,public Response<byte[]> xadd(byte[], byte[], Map<byte[],byte[]>, long, boolean) ,public transient Response<List<redis.clients.jedis.StreamEntry>> xclaim(java.lang.String, java.lang.String, java.lang.String, long, long, int, boolean, redis.clients.jedis.StreamEntryID[]) ,public transient Response<List<byte[]>> xclaim(byte[], byte[], byte[], long, long, int, boolean, byte[][]) ,public transient Response<java.lang.Long> xdel(java.lang.String, redis.clients.jedis.StreamEntryID[]) ,public transient Response<java.lang.Long> xdel(byte[], byte[][]) ,public Response<java.lang.String> xgroupCreate(java.lang.String, java.lang.String, redis.clients.jedis.StreamEntryID, boolean) ,public Response<java.lang.String> xgroupCreate(byte[], byte[], byte[], boolean) ,public Response<java.lang.Long> xgroupDelConsumer(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Long> xgroupDelConsumer(byte[], byte[], byte[]) ,public Response<java.lang.Long> xgroupDestroy(java.lang.String, java.lang.String) ,public Response<java.lang.Long> xgroupDestroy(byte[], byte[]) ,public Response<java.lang.String> xgroupSetID(java.lang.String, java.lang.String, redis.clients.jedis.StreamEntryID) ,public Response<java.lang.String> xgroupSetID(byte[], byte[], byte[]) ,public Response<java.lang.Long> xlen(java.lang.String) ,public Response<java.lang.Long> xlen(byte[]) ,public Response<List<redis.clients.jedis.StreamPendingEntry>> xpending(java.lang.String, java.lang.String, redis.clients.jedis.StreamEntryID, redis.clients.jedis.StreamEntryID, int, java.lang.String) ,public Response<List<redis.clients.jedis.StreamPendingEntry>> xpending(byte[], byte[], byte[], byte[], int, byte[]) ,public Response<List<redis.clients.jedis.StreamEntry>> xrange(java.lang.String, redis.clients.jedis.StreamEntryID, redis.clients.jedis.StreamEntryID, int) ,public Response<List<byte[]>> xrange(byte[], byte[], byte[], int) ,public Response<List<redis.clients.jedis.StreamEntry>> xrevrange(java.lang.String, redis.clients.jedis.StreamEntryID, redis.clients.jedis.StreamEntryID, int) ,public Response<List<byte[]>> xrevrange(byte[], byte[], byte[], int) ,public Response<java.lang.Long> xtrim(java.lang.String, long, boolean) ,public Response<java.lang.Long> xtrim(byte[], long, boolean) ,public Response<java.lang.Long> zadd(java.lang.String, Map<java.lang.String,java.lang.Double>) ,public Response<java.lang.Long> zadd(byte[], Map<byte[],java.lang.Double>) ,public Response<java.lang.Long> zadd(java.lang.String, double, java.lang.String) ,public Response<java.lang.Long> zadd(java.lang.String, Map<java.lang.String,java.lang.Double>, redis.clients.jedis.params.ZAddParams) ,public Response<java.lang.Long> zadd(byte[], double, byte[]) ,public Response<java.lang.Long> zadd(byte[], Map<byte[],java.lang.Double>, redis.clients.jedis.params.ZAddParams) ,public Response<java.lang.Long> zadd(java.lang.String, double, java.lang.String, redis.clients.jedis.params.ZAddParams) ,public Response<java.lang.Long> zadd(byte[], double, byte[], redis.clients.jedis.params.ZAddParams) ,public Response<java.lang.Long> zcard(java.lang.String) ,public Response<java.lang.Long> zcard(byte[]) ,public Response<java.lang.Long> zcount(java.lang.String, double, double) ,public Response<java.lang.Long> zcount(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Long> zcount(byte[], double, double) ,public Response<java.lang.Long> zcount(byte[], byte[], byte[]) ,public Response<java.lang.Double> zincrby(java.lang.String, double, java.lang.String) ,public Response<java.lang.Double> zincrby(byte[], double, byte[]) ,public Response<java.lang.Double> zincrby(java.lang.String, double, java.lang.String, redis.clients.jedis.params.ZIncrByParams) ,public Response<java.lang.Double> zincrby(byte[], double, byte[], redis.clients.jedis.params.ZIncrByParams) ,public Response<java.lang.Long> zlexcount(byte[], byte[], byte[]) ,public Response<java.lang.Long> zlexcount(java.lang.String, java.lang.String, java.lang.String) ,public Response<redis.clients.jedis.Tuple> zpopmax(java.lang.String) ,public Response<redis.clients.jedis.Tuple> zpopmax(byte[]) ,public Response<Set<redis.clients.jedis.Tuple>> zpopmax(java.lang.String, int) ,public Response<Set<redis.clients.jedis.Tuple>> zpopmax(byte[], int) ,public Response<redis.clients.jedis.Tuple> zpopmin(java.lang.String) ,public Response<redis.clients.jedis.Tuple> zpopmin(byte[]) ,public Response<Set<redis.clients.jedis.Tuple>> zpopmin(byte[], int) ,public Response<Set<redis.clients.jedis.Tuple>> zpopmin(java.lang.String, int) ,public Response<Set<java.lang.String>> zrange(java.lang.String, long, long) ,public Response<Set<byte[]>> zrange(byte[], long, long) ,public Response<Set<byte[]>> zrangeByLex(byte[], byte[], byte[]) ,public Response<Set<java.lang.String>> zrangeByLex(java.lang.String, java.lang.String, java.lang.String) ,public Response<Set<byte[]>> zrangeByLex(byte[], byte[], byte[], int, int) ,public Response<Set<java.lang.String>> zrangeByLex(java.lang.String, java.lang.String, java.lang.String, int, int) ,public Response<Set<java.lang.String>> zrangeByScore(java.lang.String, double, double) ,public Response<Set<byte[]>> zrangeByScore(byte[], double, double) ,public Response<Set<java.lang.String>> zrangeByScore(java.lang.String, java.lang.String, java.lang.String) ,public Response<Set<byte[]>> zrangeByScore(byte[], byte[], byte[]) ,public Response<Set<java.lang.String>> zrangeByScore(java.lang.String, double, double, int, int) ,public Response<Set<java.lang.String>> zrangeByScore(java.lang.String, java.lang.String, java.lang.String, int, int) ,public Response<Set<byte[]>> zrangeByScore(byte[], double, double, int, int) ,public Response<Set<byte[]>> zrangeByScore(byte[], byte[], byte[], int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(java.lang.String, double, double) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(java.lang.String, java.lang.String, java.lang.String) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(byte[], double, double) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(byte[], byte[], byte[]) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(java.lang.String, double, double, int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(java.lang.String, java.lang.String, java.lang.String, int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(byte[], double, double, int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeByScoreWithScores(byte[], byte[], byte[], int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeWithScores(java.lang.String, long, long) ,public Response<Set<redis.clients.jedis.Tuple>> zrangeWithScores(byte[], long, long) ,public Response<java.lang.Long> zrank(java.lang.String, java.lang.String) ,public Response<java.lang.Long> zrank(byte[], byte[]) ,public transient Response<java.lang.Long> zrem(java.lang.String, java.lang.String[]) ,public transient Response<java.lang.Long> zrem(byte[], byte[][]) ,public Response<java.lang.Long> zremrangeByLex(byte[], byte[], byte[]) ,public Response<java.lang.Long> zremrangeByLex(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Long> zremrangeByRank(java.lang.String, long, long) ,public Response<java.lang.Long> zremrangeByRank(byte[], long, long) ,public Response<java.lang.Long> zremrangeByScore(java.lang.String, double, double) ,public Response<java.lang.Long> zremrangeByScore(java.lang.String, java.lang.String, java.lang.String) ,public Response<java.lang.Long> zremrangeByScore(byte[], double, double) ,public Response<java.lang.Long> zremrangeByScore(byte[], byte[], byte[]) ,public Response<Set<java.lang.String>> zrevrange(java.lang.String, long, long) ,public Response<Set<byte[]>> zrevrange(byte[], long, long) ,public Response<Set<byte[]>> zrevrangeByLex(byte[], byte[], byte[]) ,public Response<Set<java.lang.String>> zrevrangeByLex(java.lang.String, java.lang.String, java.lang.String) ,public Response<Set<byte[]>> zrevrangeByLex(byte[], byte[], byte[], int, int) ,public Response<Set<java.lang.String>> zrevrangeByLex(java.lang.String, java.lang.String, java.lang.String, int, int) ,public Response<Set<java.lang.String>> zrevrangeByScore(java.lang.String, double, double) ,public Response<Set<byte[]>> zrevrangeByScore(byte[], double, double) ,public Response<Set<java.lang.String>> zrevrangeByScore(java.lang.String, java.lang.String, java.lang.String) ,public Response<Set<byte[]>> zrevrangeByScore(byte[], byte[], byte[]) ,public Response<Set<java.lang.String>> zrevrangeByScore(java.lang.String, double, double, int, int) ,public Response<Set<java.lang.String>> zrevrangeByScore(java.lang.String, java.lang.String, java.lang.String, int, int) ,public Response<Set<byte[]>> zrevrangeByScore(byte[], double, double, int, int) ,public Response<Set<byte[]>> zrevrangeByScore(byte[], byte[], byte[], int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(java.lang.String, double, double) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(java.lang.String, java.lang.String, java.lang.String) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(byte[], double, double) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(byte[], byte[], byte[]) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(java.lang.String, double, double, int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(java.lang.String, java.lang.String, java.lang.String, int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(byte[], double, double, int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeByScoreWithScores(byte[], byte[], byte[], int, int) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeWithScores(java.lang.String, long, long) ,public Response<Set<redis.clients.jedis.Tuple>> zrevrangeWithScores(byte[], long, long) ,public Response<java.lang.Long> zrevrank(java.lang.String, java.lang.String) ,public Response<java.lang.Long> zrevrank(byte[], byte[]) ,public Response<java.lang.Double> zscore(java.lang.String, java.lang.String) ,public Response<java.lang.Double> zscore(byte[], byte[]) <variables> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisUtil.java | JedisUtil | executeMSet | class JedisUtil {
private static final Logger log = LoggerFactory.getLogger(JedisUtil.class);
public static void executeMSet(PipelineBase pipeline, AbstractRedisCacheManager manager, Collection<MSetParam> params) throws Exception {<FILL_FUNCTION_BODY>}
public static void executeMGet(PipelineBase pipeline, Set<CacheKeyTO> keys) {
String hfield;
String cacheKey;
byte[] key;
for (CacheKeyTO cacheKeyTO : keys) {
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
if (null == hfield || hfield.isEmpty()) {
pipeline.get(key);
} else {
pipeline.hget(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield));
}
}
}
public static void executeDelete(PipelineBase pipeline, Set<CacheKeyTO> keys) {
String hfield;
String cacheKey;
byte[] key;
for (CacheKeyTO cacheKeyTO : keys) {
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("delete cache {}", cacheKey);
}
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
if (null == hfield || hfield.isEmpty()) {
pipeline.del(key);
} else {
pipeline.hdel(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield));
}
}
}
} |
CacheKeyTO cacheKeyTO;
String cacheKey;
String hfield;
CacheWrapper<Object> result;
byte[] key;
byte[] val;
for (MSetParam param : params) {
if(null == param){
continue;
}
cacheKeyTO = param.getCacheKey();
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
result = param.getResult();
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
val = manager.getSerializer().serialize(result);
if (null == hfield || hfield.isEmpty()) {
int expire = result.getExpire();
if (expire == AbstractRedisCacheManager.NEVER_EXPIRE) {
pipeline.set(key, val);
} else if (expire > 0) {
pipeline.setex(key, expire, val);
}
} else {
int hExpire = manager.getHashExpire() < 0 ? result.getExpire() : manager.getHashExpire();
pipeline.hset(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield), val);
if (hExpire > 0) {
pipeline.expire(key, hExpire);
}
}
}
| 490 | 364 | 854 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/RetryableJedisClusterPipeline.java | RetryableJedisClusterPipeline | syncAndReturnAll | class RetryableJedisClusterPipeline {
/**
* 部分字段没有对应的获取方法,只能采用反射来做
* 也可以去继承JedisCluster和JedisSlotBasedConnectionHandler来提供访问接口
**/
private static final Field FIELD_CONNECTION_HANDLER;
private static final Field FIELD_CACHE;
private static final Logger log = LoggerFactory.getLogger(JedisUtil.class);
static {
FIELD_CONNECTION_HANDLER = getField(BinaryJedisCluster.class, "connectionHandler");
FIELD_CACHE = getField(JedisClusterConnectionHandler.class, "cache");
}
private final JedisSlotBasedConnectionHandler connectionHandler;
private final JedisClusterInfoCache clusterInfoCache;
private int maxAttempts = 1;
public RetryableJedisClusterPipeline(JedisCluster jedisCluster) {
connectionHandler = getValue(jedisCluster, FIELD_CONNECTION_HANDLER);
clusterInfoCache = getValue(connectionHandler, FIELD_CACHE);
}
public abstract void execute(JedisClusterPipeline pipeline) throws Exception;
/**
* 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化
* @throws Exception redis 异常
*/
public void sync() throws Exception {
try {
JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache);
execute(pipeline);
pipeline.sync();
} catch (JedisMovedDataException jre) {
// if MOVED redirection occurred, rebuilds cluster's slot cache,
// recommended by Redis cluster specification
connectionHandler.renewSlotCache();
if (maxAttempts > 0) {
maxAttempts--;
sync();
return;
}
throw jre;
} catch (Exception e) {
throw e;
}
}
/**
* 同步读取所有数据 并按命令顺序返回一个列表
*
* @return 按照命令的顺序返回所有的数据
* @throws Exception redis 异常
*/
public List<Object> syncAndReturnAll() throws Exception {<FILL_FUNCTION_BODY>}
private static Field getField(Class<?> cls, String fieldName) {
try {
Field field = cls.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException | SecurityException e) {
throw new RuntimeException("cannot find or access field '" + fieldName + "' from " + cls.getName(), e);
}
}
@SuppressWarnings({"unchecked"})
private static <T> T getValue(Object obj, Field field) {
try {
return (T) field.get(obj);
} catch (IllegalArgumentException | IllegalAccessException e) {
log.error("get value fail", e);
throw new RuntimeException(e);
}
}
} |
try {
JedisClusterPipeline pipeline = new JedisClusterPipeline(clusterInfoCache);
execute(pipeline);
return pipeline.syncAndReturnAll();
} catch (JedisMovedDataException jre) {
// if MOVED redirection occurred, rebuilds cluster's slot cache,
// recommended by Redis cluster specification
connectionHandler.renewSlotCache();
if (maxAttempts > 0) {
maxAttempts--;
return syncAndReturnAll();
}
throw jre;
} catch (Exception ex) {
throw ex;
}
| 806 | 155 | 961 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/ShardedJedisCacheManager.java | ShardedJedisClient | delete | class ShardedJedisClient implements IRedis {
private static final Logger LOGGER = LoggerFactory.getLogger(ShardedJedisClient.class);
private final ShardedJedis shardedJedis;
private final AbstractRedisCacheManager cacheManager;
public ShardedJedisClient(ShardedJedis shardedJedis, AbstractRedisCacheManager cacheManager) {
this.shardedJedis = shardedJedis;
this.cacheManager = cacheManager;
}
@Override
public void close() throws IOException {
if (null != shardedJedis) {
shardedJedis.close();
}
}
@Override
public void set(byte[] key, byte[] value) {
Jedis jedis = shardedJedis.getShard(key);
jedis.set(key, value);
}
@Override
public void setex(byte[] key, int seconds, byte[] value) {
Jedis jedis = shardedJedis.getShard(key);
jedis.setex(key, seconds, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value) {
Jedis jedis = shardedJedis.getShard(key);
jedis.hset(key, field, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
Jedis jedis = shardedJedis.getShard(key);
Pipeline pipeline = jedis.pipelined();
pipeline.hset(key, field, value);
pipeline.expire(key, seconds);
pipeline.sync();
}
@Override
public void mset(Collection<MSetParam> params) {
ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(shardedJedis);
try {
JedisUtil.executeMSet(pipeline, this.cacheManager, params);
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
pipeline.sync();
}
@Override
public byte[] get(byte[] key) {
Jedis jedis = shardedJedis.getShard(key);
return jedis.get(key);
}
@Override
public byte[] hget(byte[] key, byte[] field) {
Jedis jedis = shardedJedis.getShard(key);
return jedis.hget(key, field);
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) throws Exception {
ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(shardedJedis);
JedisUtil.executeMGet(pipeline, keys);
Collection<Object> values = pipeline.syncAndReturnAll();
return cacheManager.deserialize(keys, values, returnType);
}
@Override
public void delete(Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>}
} |
ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(shardedJedis);
JedisUtil.executeDelete(pipeline, keys);
pipeline.sync();
| 842 | 61 | 903 | <methods>public void <init>(ISerializer<java.lang.Object>) ,public void delete(Set<com.jarvis.cache.to.CacheKeyTO>) throws com.jarvis.cache.exception.CacheCenterConnectionException,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> deserialize(Set<com.jarvis.cache.to.CacheKeyTO>, Collection<java.lang.Object>, java.lang.reflect.Type) throws java.lang.Exception,public CacheWrapper<java.lang.Object> get(com.jarvis.cache.to.CacheKeyTO, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public int getHashExpire() ,public ISerializer<java.lang.Object> getSerializer() ,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> mget(java.lang.reflect.Method, java.lang.reflect.Type, Set<com.jarvis.cache.to.CacheKeyTO>) ,public void mset(java.lang.reflect.Method, Collection<com.jarvis.cache.MSetParam>) ,public void setCache(com.jarvis.cache.to.CacheKeyTO, CacheWrapper<java.lang.Object>, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public void setHashExpire(int) <variables>public static final com.jarvis.cache.serializer.StringSerializer KEY_SERIALIZER,protected int hashExpire,private static final org.slf4j.Logger log,protected final non-sealed ISerializer<java.lang.Object> serializer |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisCacheManager.java | LettuceRedisClient | delete | class LettuceRedisClient implements IRedis {
private final StatefulRedisConnection<byte[], byte[]> connection;
private final AbstractRedisCacheManager cacheManager;
public LettuceRedisClient(StatefulRedisConnection<byte[], byte[]> connection, AbstractRedisCacheManager cacheManager) {
this.connection = connection;
this.cacheManager = cacheManager;
}
@Override
public void close() throws IOException {
this.connection.close();
}
@Override
public void set(byte[] key, byte[] value) {
connection.async().set(key, value);
}
@Override
public void setex(byte[] key, int seconds, byte[] value) {
connection.async().setex(key, seconds, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value) {
connection.async().hset(key, field, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
// 为了提升性能,开启pipeline
this.connection.setAutoFlushCommands(false);
RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
asyncCommands.hset(key, field, value);
asyncCommands.expire(key, seconds);
this.connection.flushCommands();
}
@Override
public void mset(Collection<MSetParam> params) {
// 为了提升性能,开启pipeline
this.connection.setAutoFlushCommands(false);
RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
try {
LettuceRedisUtil.executeMSet((AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, params);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
this.connection.flushCommands();
}
}
@Override
public byte[] get(byte[] key) {
try {
return connection.async().get(key).get();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public byte[] hget(byte[] key, byte[] field) {
try {
return connection.async().hget(key, field).get();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) {
RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
return LettuceRedisUtil.executeMGet(connection, (AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, returnType, keys);
}
@Override
public void delete(Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>}
} |
// 为了提升性能,开启pipeline
this.connection.setAutoFlushCommands(false);
RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
try {
for (CacheKeyTO cacheKeyTO : keys) {
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("delete cache {}", cacheKey);
}
String hfield = cacheKeyTO.getHfield();
if (null == hfield || hfield.isEmpty()) {
asyncCommands.del(KEY_SERIALIZER.serialize(cacheKey));
} else {
asyncCommands.hdel(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield));
}
}
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
this.connection.flushCommands();
}
| 791 | 264 | 1,055 | <methods>public void <init>(ISerializer<java.lang.Object>) ,public void delete(Set<com.jarvis.cache.to.CacheKeyTO>) throws com.jarvis.cache.exception.CacheCenterConnectionException,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> deserialize(Set<com.jarvis.cache.to.CacheKeyTO>, Collection<java.lang.Object>, java.lang.reflect.Type) throws java.lang.Exception,public CacheWrapper<java.lang.Object> get(com.jarvis.cache.to.CacheKeyTO, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public int getHashExpire() ,public ISerializer<java.lang.Object> getSerializer() ,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> mget(java.lang.reflect.Method, java.lang.reflect.Type, Set<com.jarvis.cache.to.CacheKeyTO>) ,public void mset(java.lang.reflect.Method, Collection<com.jarvis.cache.MSetParam>) ,public void setCache(com.jarvis.cache.to.CacheKeyTO, CacheWrapper<java.lang.Object>, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public void setHashExpire(int) <variables>public static final com.jarvis.cache.serializer.StringSerializer KEY_SERIALIZER,protected int hashExpire,private static final org.slf4j.Logger log,protected final non-sealed ISerializer<java.lang.Object> serializer |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisClusterCacheManager.java | LettuceRedisClusterClient | delete | class LettuceRedisClusterClient implements IRedis {
private final StatefulRedisClusterConnection<byte[], byte[]> connection;
private final AbstractRedisCacheManager cacheManager;
public LettuceRedisClusterClient(StatefulRedisClusterConnection<byte[], byte[]> connection, AbstractRedisCacheManager cacheManager) {
this.connection = connection;
this.cacheManager = cacheManager;
}
@Override
public void close() throws IOException {
this.connection.close();
}
@Override
public void set(byte[] key, byte[] value) {
connection.async().set(key, value);
}
@Override
public void setex(byte[] key, int seconds, byte[] value) {
connection.async().setex(key, seconds, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value) {
connection.async().hset(key, field, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
// 为了提升性能,开启pipeline
this.connection.setAutoFlushCommands(false);
RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
asyncCommands.hset(key, field, value);
asyncCommands.expire(key, seconds);
this.connection.flushCommands();
}
@Override
public void mset(Collection<MSetParam> params) {
// 为了提升性能,开启pipeline
this.connection.setAutoFlushCommands(false);
RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
try {
LettuceRedisUtil.executeMSet((AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, params);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
this.connection.flushCommands();
}
}
@Override
public byte[] get(byte[] key) {
try {
return connection.async().get(key).get();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public byte[] hget(byte[] key, byte[] field) {
try {
return connection.async().hget(key, field).get();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) {
RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
return LettuceRedisUtil.executeMGet(connection, (AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, returnType, keys);
}
@Override
public void delete(Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>}
} |
// 为了提升性能,开启pipeline
this.connection.setAutoFlushCommands(false);
RedisAdvancedClusterAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
try {
for (CacheKeyTO cacheKeyTO : keys) {
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.length() == 0) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("delete cache {}", cacheKey);
}
String hfield = cacheKeyTO.getHfield();
if (null == hfield || hfield.length() == 0) {
asyncCommands.del(KEY_SERIALIZER.serialize(cacheKey));
} else {
asyncCommands.hdel(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield));
}
}
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
this.connection.flushCommands();
}
| 805 | 273 | 1,078 | <methods>public void <init>(ISerializer<java.lang.Object>) ,public void delete(Set<com.jarvis.cache.to.CacheKeyTO>) throws com.jarvis.cache.exception.CacheCenterConnectionException,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> deserialize(Set<com.jarvis.cache.to.CacheKeyTO>, Collection<java.lang.Object>, java.lang.reflect.Type) throws java.lang.Exception,public CacheWrapper<java.lang.Object> get(com.jarvis.cache.to.CacheKeyTO, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public int getHashExpire() ,public ISerializer<java.lang.Object> getSerializer() ,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> mget(java.lang.reflect.Method, java.lang.reflect.Type, Set<com.jarvis.cache.to.CacheKeyTO>) ,public void mset(java.lang.reflect.Method, Collection<com.jarvis.cache.MSetParam>) ,public void setCache(com.jarvis.cache.to.CacheKeyTO, CacheWrapper<java.lang.Object>, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public void setHashExpire(int) <variables>public static final com.jarvis.cache.serializer.StringSerializer KEY_SERIALIZER,protected int hashExpire,private static final org.slf4j.Logger log,protected final non-sealed ISerializer<java.lang.Object> serializer |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisUtil.java | LettuceRedisUtil | executeMGet | class LettuceRedisUtil {
public static void executeMSet(AbstractRedisAsyncCommands<byte[], byte[]> pipeline, AbstractRedisCacheManager manager, Collection<MSetParam> params) throws Exception {
CacheKeyTO cacheKeyTO;
String cacheKey;
String hfield;
CacheWrapper<Object> result;
byte[] key;
byte[] val;
for (MSetParam param : params) {
if (null == param) {
continue;
}
cacheKeyTO = param.getCacheKey();
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
result = param.getResult();
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
val = manager.getSerializer().serialize(result);
if (null == hfield || hfield.isEmpty()) {
int expire = result.getExpire();
if (expire == AbstractRedisCacheManager.NEVER_EXPIRE) {
pipeline.set(key, val);
} else if (expire > 0) {
pipeline.setex(key, expire, val);
}
} else {
int hExpire = manager.getHashExpire() < 0 ? result.getExpire() : manager.getHashExpire();
pipeline.hset(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield), val);
if (hExpire > 0) {
pipeline.expire(key, hExpire);
}
}
}
}
public static Map<CacheKeyTO, CacheWrapper<Object>> executeMGet(StatefulConnection<byte[], byte[]> connection, AbstractRedisAsyncCommands<byte[], byte[]> asyncCommands, AbstractRedisCacheManager cacheManager, Type returnType, Set<CacheKeyTO> keys) {<FILL_FUNCTION_BODY>}
} |
String hfield;
String cacheKey;
byte[] key;
RedisFuture<byte[]>[] futures = new RedisFuture[keys.size()];
try {
// 为了提升性能,开启pipeline
connection.setAutoFlushCommands(false);
int i = 0;
for (CacheKeyTO cacheKeyTO : keys) {
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
if (null == hfield || hfield.isEmpty()) {
futures[i] = asyncCommands.get(key);
} else {
futures[i] = asyncCommands.hget(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield));
}
i++;
}
} finally {
connection.flushCommands();
}
Map<CacheKeyTO, CacheWrapper<Object>> res = new HashMap<>(keys.size());
int i = 0;
for (CacheKeyTO cacheKeyTO : keys) {
RedisFuture<byte[]> future = futures[i];
try {
byte[] data = future.get();
if (null == data || data.length == 0) {
continue;
}
CacheWrapper<Object> value = (CacheWrapper<Object>)cacheManager.getSerializer().deserialize(data, returnType);
if (null != value) {
res.put(cacheKeyTO, value);
}
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
return res;
| 501 | 449 | 950 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-memcache/src/main/java/com/jarvis/cache/memcache/MemcachedCacheManager.java | MemcachedCacheManager | get | class MemcachedCacheManager implements ICacheManager {
private MemcachedClient memcachedClient;
public MemcachedCacheManager() {
}
@Override
public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> result, final Method method) throws CacheCenterConnectionException {
if (null == cacheKeyTO) {
return;
}
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
return;
}
String hfield = cacheKeyTO.getHfield();
if (null != hfield && hfield.length() > 0) {
throw new RuntimeException("memcached does not support hash cache.");
}
if (result.getExpire() >= 0) {
memcachedClient.set(cacheKey, result.getExpire(), result);
}
}
@Override
public void mset(final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException {
if (null == params || params.isEmpty()) {
return;
}
for (MSetParam param : params) {
if (null == param) {
continue;
}
this.setCache(param.getCacheKey(), param.getResult(), method);
}
}
@SuppressWarnings("unchecked")
@Override
public CacheWrapper<Object> get(final CacheKeyTO cacheKeyTO, Method method) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) throws CacheCenterConnectionException {
if (null == keys || keys.isEmpty()) {
return Collections.emptyMap();
}
Map<String, CacheKeyTO> keyMap = new HashMap<>(keys.size());
for (CacheKeyTO key : keys) {
keyMap.put(key.getCacheKey(), key);
}
Map<String, Object> values = memcachedClient.getBulk(keyMap.keySet());
if (null == values || values.isEmpty()) {
return null;
}
Map<CacheKeyTO, CacheWrapper<Object>> res = new HashMap<>(values.size());
Iterator<Map.Entry<String, CacheKeyTO>> keyMapIt = keyMap.entrySet().iterator();
while (keyMapIt.hasNext()) {
Map.Entry<String, CacheKeyTO> item = keyMapIt.next();
CacheWrapper<Object> value = (CacheWrapper<Object>) values.get(item.getKey());
if (null != value) {
res.put(item.getValue(), value);
}
}
return res;
}
@Override
public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException {
if (null == memcachedClient || null == keys || keys.isEmpty()) {
return;
}
String hfield;
for (CacheKeyTO cacheKeyTO : keys) {
if (null == cacheKeyTO) {
continue;
}
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
hfield = cacheKeyTO.getHfield();
if (null != hfield && hfield.length() > 0) {
throw new RuntimeException("memcached does not support hash cache.");
}
try {
String allKeysPattern = "*";
if (allKeysPattern.equals(cacheKey)) {
memcachedClient.flush();
} else {
memcachedClient.delete(cacheKey);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public MemcachedClient getMemcachedClient() {
return memcachedClient;
}
public void setMemcachedClient(MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
} |
if (null == cacheKeyTO) {
return null;
}
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
return null;
}
String hfield = cacheKeyTO.getHfield();
if (null != hfield && hfield.length() > 0) {
throw new RuntimeException("memcached does not support hash cache.");
}
return (CacheWrapper<Object>) memcachedClient.get(cacheKey);
| 1,025 | 131 | 1,156 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-manager/autoload-cache-manager-redis/src/main/java/com/jarvis/cache/redis/AbstractRedisCacheManager.java | AbstractRedisCacheManager | setCache | class AbstractRedisCacheManager implements ICacheManager {
public static final StringSerializer KEY_SERIALIZER = new StringSerializer();
private static final Logger log = LoggerFactory.getLogger(AbstractRedisCacheManager.class);
/**
* Hash的缓存时长:等于0时永久缓存;大于0时,主要是为了防止一些已经不用的缓存占用内存;hashExpire小于0时,则使用@Cache中设置的expire值(默认值为-1)。
*/
protected int hashExpire = -1;
protected final ISerializer<Object> serializer;
public AbstractRedisCacheManager(ISerializer<Object> serializer) {
this.serializer = serializer;
}
protected abstract IRedis getRedis();
@Override
public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> result, final Method method) throws CacheCenterConnectionException {<FILL_FUNCTION_BODY>}
@Override
public void mset(final Method method, final Collection<MSetParam> params) {
if (null == params || params.isEmpty()) {
return;
}
try (IRedis redis = getRedis()) {
redis.mset(params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
@Override
public CacheWrapper<Object> get(final CacheKeyTO cacheKeyTO, final Method method) throws CacheCenterConnectionException {
if (null == cacheKeyTO) {
return null;
}
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
return null;
}
CacheWrapper<Object> res = null;
String hfield;
Type returnType = null;
try (IRedis redis = getRedis()) {
byte[] val;
hfield = cacheKeyTO.getHfield();
if (null == hfield || hfield.isEmpty()) {
val = redis.get(KEY_SERIALIZER.serialize(cacheKey));
} else {
val = redis.hget(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield));
}
if (null != method) {
returnType = method.getGenericReturnType();
}
res = (CacheWrapper<Object>) serializer.deserialize(val, returnType);
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(final Method method, final Type returnType, final Set<CacheKeyTO> keys) {
if (null == keys || keys.isEmpty()) {
return Collections.emptyMap();
}
try (IRedis redis = getRedis()) {
return redis.mget(returnType, keys);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public Map<CacheKeyTO, CacheWrapper<Object>> deserialize(Set<CacheKeyTO> keys, Collection<Object> values, Type returnType) throws Exception {
if (null == values || values.isEmpty()) {
return Collections.emptyMap();
}
CacheWrapper<Object> tmp;
Map<CacheKeyTO, CacheWrapper<Object>> res = new HashMap<>(keys.size());
Iterator<CacheKeyTO> keysIt = keys.iterator();
for (Object value : values) {
CacheKeyTO cacheKeyTO = keysIt.next();
if (null == value) {
continue;
}
if (!(value instanceof byte[])) {
log.warn("the data from redis is not byte[] but " + value.getClass().getName());
continue;
}
tmp = (CacheWrapper<Object>) serializer.deserialize((byte[]) value, returnType);
if (null != tmp) {
res.put(cacheKeyTO, tmp);
}
}
return res;
}
@Override
public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException {
if (null == keys || keys.isEmpty()) {
return;
}
try (IRedis redis = getRedis()) {
redis.delete(keys);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public int getHashExpire() {
return hashExpire;
}
public void setHashExpire(int hashExpire) {
if (hashExpire < 0) {
return;
}
this.hashExpire = hashExpire;
}
public ISerializer<Object> getSerializer() {
return serializer;
}
} |
if (null == cacheKeyTO) {
return;
}
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
return;
}
try (IRedis redis = getRedis()) {
String hfield = cacheKeyTO.getHfield();
byte[] key = KEY_SERIALIZER.serialize(cacheKey);
byte[] val = serializer.serialize(result);
if (null == hfield || hfield.isEmpty()) {
int expire = result.getExpire();
if (expire == NEVER_EXPIRE) {
redis.set(key, val);
} else if (expire > 0) {
redis.setex(key, expire, val);
}
} else {
byte[] field = KEY_SERIALIZER.serialize(hfield);
int hExpire = hashExpire < 0 ? result.getExpire() : hashExpire;
if (hExpire == NEVER_EXPIRE) {
redis.hset(key, field, val);
} else if (hExpire > 0) {
redis.hset(key, field, val, hExpire);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
| 1,232 | 337 | 1,569 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-script/autoload-cache-script-js/src/main/java/com/jarvis/cache/script/JavaScriptParser.java | JavaScriptParser | addFunction | class JavaScriptParser extends AbstractScriptParser {
private final ScriptEngineManager manager = new ScriptEngineManager();
private final ConcurrentHashMap<String, CompiledScript> expCache = new ConcurrentHashMap<String, CompiledScript>();
private final StringBuffer funcs = new StringBuffer();
private static int versionCode;
private final ScriptEngine engine;
public JavaScriptParser() {
engine = manager.getEngineByName("javascript");
try {
addFunction(HASH, CacheUtil.class.getDeclaredMethod("getUniqueHashStr", new Class[]{Object.class}));
addFunction(EMPTY, CacheUtil.class.getDeclaredMethod("isEmpty", new Class[]{Object.class}));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void addFunction(String name, Method method) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal,
Class<T> valueType) throws Exception {
Bindings bindings = new SimpleBindings();
bindings.put(TARGET, target);
bindings.put(ARGS, arguments);
if (hasRetVal) {
bindings.put(RET_VAL, retVal);
}
CompiledScript script = expCache.get(exp);
if (null != script) {
return (T) script.eval(bindings);
}
if (engine instanceof Compilable) {
Compilable compEngine = (Compilable) engine;
script = compEngine.compile(funcs + exp);
expCache.put(exp, script);
return (T) script.eval(bindings);
} else {
return (T) engine.eval(funcs + exp, bindings);
}
}
} |
try {
String clsName = method.getDeclaringClass().getName();
String methodName = method.getName();
funcs.append("function " + name + "(obj){return " + clsName + "." + methodName + "(obj);}");
} catch (Exception e) {
e.printStackTrace();
}
| 487 | 88 | 575 | <methods>public non-sealed void <init>() ,public abstract void addFunction(java.lang.String, java.lang.reflect.Method) ,public java.lang.String getDefinedCacheKey(java.lang.String, java.lang.Object, java.lang.Object[], java.lang.Object, boolean) throws java.lang.Exception,public abstract T getElValue(java.lang.String, java.lang.Object, java.lang.Object[], java.lang.Object, boolean, Class<T>) throws java.lang.Exception,public T getElValue(java.lang.String, java.lang.Object, java.lang.Object[], Class<T>) throws java.lang.Exception,public int getRealExpire(int, java.lang.String, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isAutoload(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[]) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.ExCache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCanDelete(com.jarvis.cache.annotation.CacheDeleteKey, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCanDelete(com.jarvis.cache.annotation.CacheDeleteMagicKey, java.lang.Object[], java.lang.Object) throws java.lang.Exception<variables>protected static final java.lang.String ARGS,protected static final java.lang.String EMPTY,protected static final java.lang.String HASH,protected static final java.lang.String RET_VAL,protected static final java.lang.String TARGET |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-script/autoload-cache-script-ognl/src/main/java/com/jarvis/cache/script/OgnlParser.java | OgnlParser | getElValue | class OgnlParser extends AbstractScriptParser {
private final ConcurrentHashMap<String, Object> EXPRESSION_CACHE = new ConcurrentHashMap<String, Object>();
private final ConcurrentHashMap<String, Class<?>> funcs = new ConcurrentHashMap<String, Class<?>>(8);
public OgnlParser() {
}
@Override
public void addFunction(String name, Method method) {
funcs.put(name, method.getDeclaringClass());
}
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String exp, Object target, Object[] arguments, Object retVal, boolean hasRetVal,
Class<T> valueType) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (valueType.equals(String.class)) {
if (exp.indexOf("#") == -1 && exp.indexOf("@") == -1 && exp.indexOf("'") == -1) {// 如果不是表达式,直接返回字符串
return (T) exp;
}
}
Object object = EXPRESSION_CACHE.get(exp);
if (null == object) {
String className = CacheUtil.class.getName();
String exp2 = exp.replaceAll("@@" + HASH + "\\(", "@" + className + "@getUniqueHashStr(");
exp2 = exp2.replaceAll("@@" + EMPTY + "\\(", "@" + className + "@isEmpty(");
Iterator<Map.Entry<String, Class<?>>> it = funcs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Class<?>> entry = it.next();
className = entry.getValue().getName();
exp2 = exp2.replaceAll("@@" + entry.getKey() + "\\(", "@" + className + "@" + entry.getKey() + "(");
}
object = Ognl.parseExpression(exp2);
EXPRESSION_CACHE.put(exp, object);
}
Map<String, Object> values = new HashMap<String, Object>(2);
values.put(TARGET, target);
values.put(ARGS, arguments);
if (hasRetVal) {
values.put(RET_VAL, retVal);
}
OgnlContext context = new OgnlContext(values);
context.setRoot(arguments);
Object res = Ognl.getValue(object, context, context.getRoot(), valueType);
return (T) res;
| 202 | 454 | 656 | <methods>public non-sealed void <init>() ,public abstract void addFunction(java.lang.String, java.lang.reflect.Method) ,public java.lang.String getDefinedCacheKey(java.lang.String, java.lang.Object, java.lang.Object[], java.lang.Object, boolean) throws java.lang.Exception,public abstract T getElValue(java.lang.String, java.lang.Object, java.lang.Object[], java.lang.Object, boolean, Class<T>) throws java.lang.Exception,public T getElValue(java.lang.String, java.lang.Object, java.lang.Object[], Class<T>) throws java.lang.Exception,public int getRealExpire(int, java.lang.String, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isAutoload(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[]) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.ExCache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCanDelete(com.jarvis.cache.annotation.CacheDeleteKey, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCanDelete(com.jarvis.cache.annotation.CacheDeleteMagicKey, java.lang.Object[], java.lang.Object) throws java.lang.Exception<variables>protected static final java.lang.String ARGS,protected static final java.lang.String EMPTY,protected static final java.lang.String HASH,protected static final java.lang.String RET_VAL,protected static final java.lang.String TARGET |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-script/autoload-cache-script-springel/src/main/java/com/jarvis/cache/script/SpringELParser.java | SpringELParser | getElValue | class SpringELParser extends AbstractScriptParser {
/**
* # 号
*/
private static final String POUND = "#";
/**
* 撇号
*/
private static final String apostrophe = "'";
private final ExpressionParser parser = new SpelExpressionParser();
private final ConcurrentHashMap<String, Expression> expCache = new ConcurrentHashMap<String, Expression>();
private static Method hash = null;
private static Method empty = null;
static {
try {
hash = CacheUtil.class.getDeclaredMethod("getUniqueHashStr", new Class[]{Object.class});
empty = CacheUtil.class.getDeclaredMethod("isEmpty", new Class[]{Object.class});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private final ConcurrentHashMap<String, Method> funcs = new ConcurrentHashMap<String, Method>(8);
/**
* @param name 方法名
* @param method 方法
*/
@Override
public void addFunction(String name, Method method) {
funcs.put(name, method);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String keySpEL, Object target, Object[] arguments, Object retVal, boolean hasRetVal,
Class<T> valueType) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (valueType.equals(String.class)) {
// 如果不是表达式,直接返回字符串
if (keySpEL.indexOf(POUND) == -1 && keySpEL.indexOf("'") == -1) {
return (T) keySpEL;
}
}
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction(HASH, hash);
context.registerFunction(EMPTY, empty);
Iterator<Map.Entry<String, Method>> it = funcs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Method> entry = it.next();
context.registerFunction(entry.getKey(), entry.getValue());
}
context.setVariable(TARGET, target);
context.setVariable(ARGS, arguments);
if (hasRetVal) {
context.setVariable(RET_VAL, retVal);
}
Expression expression = expCache.get(keySpEL);
if (null == expression) {
expression = parser.parseExpression(keySpEL);
expCache.put(keySpEL, expression);
}
return expression.getValue(context, valueType);
| 409 | 302 | 711 | <methods>public non-sealed void <init>() ,public abstract void addFunction(java.lang.String, java.lang.reflect.Method) ,public java.lang.String getDefinedCacheKey(java.lang.String, java.lang.Object, java.lang.Object[], java.lang.Object, boolean) throws java.lang.Exception,public abstract T getElValue(java.lang.String, java.lang.Object, java.lang.Object[], java.lang.Object, boolean, Class<T>) throws java.lang.Exception,public T getElValue(java.lang.String, java.lang.Object, java.lang.Object[], Class<T>) throws java.lang.Exception,public int getRealExpire(int, java.lang.String, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isAutoload(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[]) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.Cache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCacheable(com.jarvis.cache.annotation.ExCache, java.lang.Object, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCanDelete(com.jarvis.cache.annotation.CacheDeleteKey, java.lang.Object[], java.lang.Object) throws java.lang.Exception,public boolean isCanDelete(com.jarvis.cache.annotation.CacheDeleteMagicKey, java.lang.Object[], java.lang.Object) throws java.lang.Exception<variables>protected static final java.lang.String ARGS,protected static final java.lang.String EMPTY,protected static final java.lang.String HASH,protected static final java.lang.String RET_VAL,protected static final java.lang.String TARGET |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/clone/Cloning.java | Cloning | deepClone | class Cloning implements ICloner {
private final Cloner cloner = new Cloner();
@Override
public Object deepClone(Object obj, final Type type) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName()
+ " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
}
} |
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
if (clazz.isArray()) {
Object[] arr = (Object[]) obj;
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), arr.length);
for (int i = 0; i < arr.length; i++) {
res[i] = deepClone(arr[i], null);
}
return res;
}
return cloner.deepClone(obj);
| 254 | 301 | 555 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/compress/CommonsCompressor.java | CommonsCompressor | compress | class CommonsCompressor implements ICompressor {
private static final int BUFFER = 1024;
private static final CompressorStreamFactory FACTORY = new CompressorStreamFactory();
private String name;
public CommonsCompressor(String name) {
this.name = name;
}
@Override
public byte[] compress(ByteArrayInputStream bais) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public byte[] decompress(ByteArrayInputStream bais) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CompressorInputStream cis = FACTORY.createCompressorInputStream(name, bais);
int len;
byte buf[] = new byte[BUFFER];
while ((len = cis.read(buf, 0, BUFFER)) != -1) {
baos.write(buf, 0, len);
}
cis.close();
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
}
} |
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CompressorOutputStream cos = FACTORY.createCompressorOutputStream(name, baos);
int len;
byte buf[] = new byte[BUFFER];
while ((len = bais.read(buf, 0, BUFFER)) != -1) {
cos.write(buf, 0, len);
}
cos.flush();
cos.close();
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
| 284 | 148 | 432 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/serializer/CompressorSerializer.java | CompressorSerializer | serialize | class CompressorSerializer implements ISerializer<Object> {
private static final int DEFAULT_COMPRESSION_THRESHOLD = 16384;
private int compressionThreshold = DEFAULT_COMPRESSION_THRESHOLD;
private final ISerializer<Object> serializer;
private final ICompressor compressor;
public CompressorSerializer(ISerializer<Object> serializer) {
this.serializer = serializer;
this.compressor = new CommonsCompressor(CompressorStreamFactory.GZIP);
}
public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold) {
this.serializer = serializer;
this.compressionThreshold = compressionThreshold;
this.compressor = new CommonsCompressor(CompressorStreamFactory.GZIP);
}
public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold, String compressType) {
this.serializer = serializer;
this.compressionThreshold = compressionThreshold;
this.compressor = new CommonsCompressor(compressType);
}
public CompressorSerializer(ISerializer<Object> serializer, int compressionThreshold, ICompressor compressor) {
this.serializer = serializer;
this.compressionThreshold = compressionThreshold;
this.compressor = compressor;
}
@Override
public byte[] serialize(final Object obj) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public Object deserialize(final byte[] bytes, final Type returnType) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
byte flag = bytes[0];
byte[] data;
if (flag == 0) {
data = new byte[bytes.length - 1];
System.arraycopy(bytes, 1, data, 0, data.length);
} else {
data = compressor.decompress(new ByteArrayInputStream(bytes, 1, bytes.length - 1));
}
return serializer.deserialize(data, returnType);
}
@Override
public Object deepClone(Object obj, final Type type) throws Exception {
return serializer.deepClone(obj, type);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {
return serializer.deepCloneMethodArgs(method, args);
}
} |
if (null == obj) {
return null;
}
byte[] data = serializer.serialize(obj);
byte flag = 0;
if (data.length > compressionThreshold) {
data = compressor.compress(new ByteArrayInputStream(data));
flag = 1;
}
byte[] out = new byte[data.length + 1];
out[0] = flag;
System.arraycopy(data, 0, out, 1, data.length);
return out;
| 633 | 130 | 763 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-api/src/main/java/com/jarvis/cache/serializer/StringSerializer.java | StringSerializer | deepClone | class StringSerializer implements ISerializer<String> {
private final Charset charset;
public StringSerializer() {
this(StandardCharsets.UTF_8);
}
public StringSerializer(Charset charset) {
this.charset = charset;
}
@Override
public String deserialize(byte[] bytes, Type returnType) {
return (bytes == null ? null : new String(bytes, charset));
}
@Override
public byte[] serialize(String string) {
return (string == null ? null : string.getBytes(charset));
}
@Override
public Object deepClone(Object obj, final Type type) {<FILL_FUNCTION_BODY>}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) {
return (Object[]) deepClone(args, null);
}
} |
if (null == obj) {
return obj;
}
String str = (String) obj;
return String.copyValueOf(str.toCharArray());
| 224 | 45 | 269 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-fastjson/src/main/java/com/jarvis/cache/serializer/FastjsonSerializer.java | FastjsonSerializer | deepCloneMethodArgs | class FastjsonSerializer implements ISerializer<Object> {
private final Charset charset;
private static final SerializerFeature[] FEATURES = {SerializerFeature.DisableCircularReferenceDetect};
private static final Map<Type, ParameterizedTypeImpl> TYPE_CACHE = new ConcurrentHashMap<>(1024);
public FastjsonSerializer() {
this(StandardCharsets.UTF_8);
}
public FastjsonSerializer(Charset charset) {
this.charset = charset;
}
@Override
public byte[] serialize(final Object obj) throws Exception {
if (obj == null) {
return null;
}
String json = JSON.toJSONString(obj, FEATURES);
return json.getBytes(charset);
}
@Override
public Object deserialize(final byte[] bytes, final Type returnType) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
ParameterizedTypeImpl type = TYPE_CACHE.get(returnType);
if (null == type) {
Type[] agsType = new Type[]{returnType};
type = ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null);
TYPE_CACHE.put(returnType, type);
}
String json = new String(bytes, charset);
return JSON.parseObject(json, type);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Object deepClone(Object obj, final Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
// List/Map在编译时类型会被擦除,导致List<Object>反序列化后变为List<JSONObject>
if (null != type && !(obj instanceof Collection) && !(obj instanceof Map)) {
String json = JSON.toJSONString(obj, FEATURES);
return JSON.parseObject(json, type);
}
if (clazz.isArray()) {
Object[] arr = (Object[]) obj;
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), arr.length);
for (int i = 0; i < arr.length; i++) {
res[i] = deepClone(arr[i], null);
}
return res;
} else if (obj instanceof Collection) {
Collection<?> tempCol = (Collection<?>) obj;
Collection res = tempCol.getClass().newInstance();
Iterator<?> it = tempCol.iterator();
while (it.hasNext()) {
Object val = deepClone(it.next(), null);
res.add(val);
}
return res;
} else if (obj instanceof Map) {
Map tempMap = (Map) obj;
Map res = tempMap.getClass().newInstance();
Iterator it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Entry) it.next();
Object key = entry.getKey();
Object val = entry.getValue();
res.put(deepClone(key, null), deepClone(val, null));
}
return res;
} else if (obj instanceof CacheWrapper) {
CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj;
CacheWrapper<Object> res = new CacheWrapper<Object>();
res.setExpire(wrapper.getExpire());
res.setLastLoadTime(wrapper.getLastLoadTime());
res.setCacheObject(deepClone(wrapper.getCacheObject(), null));
return res;
} else {
String json = JSON.toJSONString(obj, FEATURES);
return JSON.parseObject(json, clazz);
}
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName()
+ " must " + genericParameterTypes.length);
}
Class<?> clazz = args.getClass();
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[args.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), args.length);
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
Type genericParameterType = genericParameterTypes[i];
Object obj = args[i];
if (genericParameterType instanceof ParameterizedType) {
String json = JSON.toJSONString(obj, FEATURES);
res[i] = JSON.parseObject(json, genericParameterType);
} else {
res[i] = deepClone(obj, null);
}
}
return res;
| 1,174 | 300 | 1,474 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/HessianSerializer.java | HessianSerializer | deepCloneMethodArgs | class HessianSerializer implements ISerializer<Object> {
private static final SerializerFactory SERIALIZER_FACTORY = new SerializerFactory();
static {
SERIALIZER_FACTORY.addFactory(new HessionBigDecimalSerializerFactory());
SERIALIZER_FACTORY.addFactory(new HessionSoftReferenceSerializerFactory());
}
/**
* 添加自定义SerializerFactory
*
* @param factory AbstractSerializerFactory
*/
public void addSerializerFactory(AbstractSerializerFactory factory) {
SERIALIZER_FACTORY.addFactory(factory);
}
@Override
public byte[] serialize(final Object obj) throws Exception {
if (obj == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
AbstractHessianOutput output = new Hessian2Output(outputStream);
output.setSerializerFactory(SERIALIZER_FACTORY);
// 将对象写到流里
output.writeObject(obj);
output.flush();
byte[] val = outputStream.toByteArray();
output.close();
return val;
}
@Override
public Object deserialize(final byte[] bytes, final Type returnType) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
AbstractHessianInput input = new Hessian2Input(inputStream);
input.setSerializerFactory(SERIALIZER_FACTORY);
Object obj = input.readObject();
input.close();
return obj;
}
@Override
public Object deepClone(Object obj, final Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
return deserialize(serialize(obj), null);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName()
+ " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
| 655 | 167 | 822 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/SoftReferenceDeserializer.java | SoftReferenceDeserializer | readObject | class SoftReferenceDeserializer extends AbstractMapDeserializer {
@Override
public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException {<FILL_FUNCTION_BODY>}
protected SoftReference<Object> instantiate() throws Exception {
Object obj = new Object();
return new SoftReference<Object>(obj);
}
} |
try {
SoftReference<Object> obj = instantiate();
in.addRef(obj);
Object value = in.readObject();
obj = null;
return new SoftReference<Object>(value);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
| 93 | 92 | 185 | <methods>public void <init>() ,public Class#RAW getType() ,public java.lang.Object readObject(com.caucho.hessian.io.AbstractHessianInput) throws java.io.IOException<variables> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/SoftReferenceSerializer.java | SoftReferenceSerializer | writeObject | class SoftReferenceSerializer extends AbstractSerializer implements ObjectSerializer {
@Override
public Serializer getObjectSerializer() {
return this;
}
@Override
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {<FILL_FUNCTION_BODY>}
} |
if (out.addRef(obj)) {
return;
}
@SuppressWarnings("unchecked")
SoftReference<Object> data = (SoftReference<Object>) obj;
int refV = out.writeObjectBegin(SoftReference.class.getName());
if (refV == -1) {
out.writeInt(1);
out.writeString("ref");
out.writeObjectBegin(SoftReference.class.getName());
}
if (data != null) {
Object ref = data.get();
if (null != ref) {
out.writeObject(ref);
} else {
out.writeNull();
}
} else {
out.writeNull();
}
| 74 | 188 | 262 | <methods>public void <init>() ,public void writeObject(java.lang.Object, com.caucho.hessian.io.AbstractHessianOutput) throws java.io.IOException<variables>public static final com.caucho.hessian.io.AbstractSerializer.NullSerializer NULL,protected static final java.util.logging.Logger log |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceDeserializer.java | WeakReferenceDeserializer | readObject | class WeakReferenceDeserializer extends AbstractMapDeserializer {
@Override
public Object readObject(AbstractHessianInput in, Object[] fields) throws IOException {<FILL_FUNCTION_BODY>}
protected WeakReference<Object> instantiate() throws Exception {
Object obj = new Object();
return new WeakReference<Object>(obj);
}
} |
try {
WeakReference<Object> obj = instantiate();
in.addRef(obj);
Object value = in.readObject();
obj = null;
return new WeakReference<Object>(value);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
| 96 | 94 | 190 | <methods>public void <init>() ,public Class#RAW getType() ,public java.lang.Object readObject(com.caucho.hessian.io.AbstractHessianInput) throws java.io.IOException<variables> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-hessian/src/main/java/com/jarvis/cache/serializer/hession/WeakReferenceSerializer.java | WeakReferenceSerializer | writeObject | class WeakReferenceSerializer extends AbstractSerializer implements ObjectSerializer {
@Override
public Serializer getObjectSerializer() {
return this;
}
@Override
public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {<FILL_FUNCTION_BODY>}
} |
if (out.addRef(obj)) {
return;
}
@SuppressWarnings("unchecked")
WeakReference<Object> data = (WeakReference<Object>) obj;
int refV = out.writeObjectBegin(WeakReference.class.getName());
if (refV == -1) {
out.writeInt(1);
out.writeString("ref");
out.writeObjectBegin(WeakReference.class.getName());
}
if (data != null) {
Object ref = data.get();
if (null != ref) {
out.writeObject(ref);
} else {
out.writeNull();
}
} else {
out.writeNull();
}
| 75 | 192 | 267 | <methods>public void <init>() ,public void writeObject(java.lang.Object, com.caucho.hessian.io.AbstractHessianOutput) throws java.io.IOException<variables>public static final com.caucho.hessian.io.AbstractSerializer.NullSerializer NULL,protected static final java.util.logging.Logger log |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jackson-msgpack/src/main/java/com/jarvis/cache/serializer/JacksonMsgpackSerializer.java | JacksonMsgpackSerializer | deepClone | class JacksonMsgpackSerializer implements ISerializer<Object> {
private static final ObjectMapper MAPPER = new ObjectMapper(new MessagePackFactory());
@Override
public byte[] serialize(Object obj) throws Exception {
if (obj == null) {
return null;
}
return MAPPER.writeValueAsBytes(obj);
}
@Override
public Object deserialize(byte[] bytes, Type returnType) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
Type[] agsType = new Type[]{returnType};
JavaType javaType = MAPPER.getTypeFactory()
.constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null));
return MAPPER.readValue(bytes, javaType);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Object deepClone(Object obj, final Type type) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName()
+ " must " + genericParameterTypes.length);
}
Class<?> clazz = args.getClass();
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[args.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), args.length);
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
Type genericParameterType = genericParameterTypes[i];
Object obj = args[i];
if (genericParameterType instanceof ParameterizedType) {
byte[] tmp = MAPPER.writeValueAsBytes(obj);
JavaType javaType = MAPPER.getTypeFactory().constructType(genericParameterType);
res[i] = MAPPER.readValue(tmp, javaType);
} else {
res[i] = deepClone(obj, null);
}
}
return res;
}
} |
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
if (null != type) {
byte[] tmp = MAPPER.writeValueAsBytes(obj);
JavaType javaType = MAPPER.getTypeFactory().constructType(type);
return MAPPER.readValue(tmp, javaType);
}
if (clazz.isArray()) {
Object[] arr = (Object[]) obj;
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), arr.length);
for (int i = 0; i < arr.length; i++) {
res[i] = deepClone(arr[i], null);
}
return res;
} else if (obj instanceof Collection) {
Collection<?> tempCol = (Collection<?>) obj;
Collection res = tempCol.getClass().newInstance();
Iterator<?> it = tempCol.iterator();
while (it.hasNext()) {
Object val = deepClone(it.next(), null);
res.add(val);
}
return res;
} else if (obj instanceof Map) {
Map tempMap = (Map) obj;
Map res = tempMap.getClass().newInstance();
Iterator it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Entry) it.next();
Object key = entry.getKey();
Object val = entry.getValue();
res.put(deepClone(key, null), deepClone(val, null));
}
return res;
} else if (obj instanceof CacheWrapper) {
CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj;
CacheWrapper<Object> res = new CacheWrapper<Object>();
res.setExpire(wrapper.getExpire());
res.setLastLoadTime(wrapper.getLastLoadTime());
res.setCacheObject(deepClone(wrapper.getCacheObject(), null));
return res;
} else {
byte[] tmp = MAPPER.writeValueAsBytes(obj);
return MAPPER.readValue(tmp, clazz);
}
| 610 | 714 | 1,324 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jackson/src/main/java/com/jarvis/cache/serializer/JacksonJsonSerializer.java | NullValueSerializer | deepCloneMethodArgs | class NullValueSerializer extends StdSerializer<NullValue> {
private static final long serialVersionUID = 1999052150548658808L;
private final String classIdentifier;
/**
* @param classIdentifier can be {@literal null} and will be defaulted
* to {@code @class}.
*/
NullValueSerializer(String classIdentifier) {
super(NullValue.class);
this.classIdentifier = StringUtil.hasText(classIdentifier) ? classIdentifier : "@class";
}
/*
* (non-Javadoc)
* @see
* com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.
* lang.Object, com.fasterxml.jackson.core.JsonGenerator,
* com.fasterxml.jackson.databind.SerializerProvider)
*/
@Override
public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField(classIdentifier, NullValue.class.getName());
jgen.writeEndObject();
}
}
@Override
public byte[] serialize(final Object obj) throws Exception {
if (obj == null) {
return null;
}
return MAPPER.writeValueAsBytes(obj);
}
@Override
public Object deserialize(final byte[] bytes, final Type returnType) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
Type[] agsType = new Type[]{returnType};
JavaType javaType = MAPPER.getTypeFactory()
.constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null));
return MAPPER.readValue(bytes, javaType);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Object deepClone(Object obj, final Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
if (null != type) {
String json = MAPPER.writeValueAsString(obj);
JavaType javaType = MAPPER.getTypeFactory().constructType(type);
return MAPPER.readValue(json, javaType);
}
if (clazz.isArray()) {
Object[] arr = (Object[]) obj;
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[arr.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), arr.length);
for (int i = 0; i < arr.length; i++) {
res[i] = deepClone(arr[i], null);
}
return res;
} else if (obj instanceof Collection) {
Collection<?> tempCol = (Collection<?>) obj;
Collection res = tempCol.getClass().newInstance();
Iterator<?> it = tempCol.iterator();
while (it.hasNext()) {
Object val = deepClone(it.next(), null);
res.add(val);
}
return res;
} else if (obj instanceof Map) {
Map tempMap = (Map) obj;
Map res = tempMap.getClass().newInstance();
Iterator it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Entry) it.next();
Object key = entry.getKey();
Object val = entry.getValue();
res.put(deepClone(key, null), deepClone(val, null));
}
return res;
} else if (obj instanceof CacheWrapper) {
CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj;
CacheWrapper<Object> res = new CacheWrapper<Object>();
res.setExpire(wrapper.getExpire());
res.setLastLoadTime(wrapper.getLastLoadTime());
res.setCacheObject(deepClone(wrapper.getCacheObject(), null));
return res;
} else {
String json = MAPPER.writeValueAsString(obj);
return MAPPER.readValue(json, clazz);
}
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY> |
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName()
+ " must " + genericParameterTypes.length);
}
Class<?> clazz = args.getClass();
Object[] res = ((Object) clazz == (Object) Object[].class) ? (Object[]) new Object[args.length]
: (Object[]) Array.newInstance(clazz.getComponentType(), args.length);
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
Type genericParameterType = genericParameterTypes[i];
Object obj = args[i];
if (genericParameterType instanceof ParameterizedType) {
String json = MAPPER.writeValueAsString(obj);
JavaType javaType = MAPPER.getTypeFactory().constructType(genericParameterType);
res[i] = MAPPER.readValue(json, javaType);
} else {
res[i] = deepClone(obj, null);
}
}
return res;
| 1,266 | 322 | 1,588 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jdk/src/main/java/com/jarvis/cache/serializer/JdkSerializer.java | JdkSerializer | deserialize | class JdkSerializer implements ISerializer<Object> {
@Override
public Object deserialize(byte[] bytes, Type returnType) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public byte[] serialize(Object obj) throws Exception {
if (obj == null) {
return new byte[0];
}
// 将对象写到流里
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream output = new ObjectOutputStream(outputStream);
output.writeObject(obj);
output.flush();
return outputStream.toByteArray();
}
@Override
public Object deepClone(Object obj, final Type type) throws Exception {
if (null == obj) {
return obj;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
return deserialize(serialize(obj), null);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName()
+ " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
}
} |
if (null == bytes || bytes.length == 0) {
return null;
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
ObjectInputStream input = new ObjectInputStream(inputStream);
return input.readObject();
| 546 | 62 | 608 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/KryoSerializer.java | KryoSerializer | serialize | class KryoSerializer implements ISerializer<Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(KryoSerializer.class);
private KryoContext kryoContext;
private static final Logger logger = LoggerFactory.getLogger(KryoSerializer.class);
public KryoSerializer() {
this.kryoContext = DefaultKryoContext.newKryoContextFactory(kryo -> {
kryo.register(CacheWrapper.class, new CacheWrapperSerializer());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("kryo register classes successfully.");
}
});
}
/**
* 添加Kryo类注册器
* @param registration see {@link KryoClassRegistration}
*/
public void addKryoClassRegistration(KryoClassRegistration registration) {
kryoContext.addKryoClassRegistration(registration);
}
@Override
public byte[] serialize(Object obj) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public Object deserialize(byte[] bytes, Type returnType) throws Exception {
if (null == bytes || bytes.length == 0) {
return null;
}
return kryoContext.deserialize(bytes);
}
@Override
public Object deepClone(Object obj, Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation() || clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
return deserialize(serialize(obj), null);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
}
} |
if (obj == null) {
return null;
}
return kryoContext.serialize(obj);
| 730 | 34 | 764 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/kryo/CacheWrapperSerializer.java | CacheWrapperSerializer | read | class CacheWrapperSerializer extends Serializer<CacheWrapper> {
@Override
@SuppressWarnings("unchecked")
public void write(Kryo kryo, Output output, CacheWrapper object) {
output.writeInt(object.getExpire(), true);
output.writeLong(object.getLastLoadTime(), true);
kryo.writeClassAndObject(output, object.getCacheObject());
}
@Override
@SuppressWarnings("unchecked")
public CacheWrapper read(Kryo kryo, Input input, Class<CacheWrapper> type) {<FILL_FUNCTION_BODY>}
} |
int expire = input.readInt(true);
long lastLoadTime = input.readLong(true);
Object o = kryo.readClassAndObject(input);
CacheWrapper cacheWrapper = new CacheWrapper();
cacheWrapper.setCacheObject(o);
cacheWrapper.setExpire(expire);
cacheWrapper.setLastLoadTime(lastLoadTime);
return cacheWrapper;
| 161 | 100 | 261 | <methods>public void <init>() ,public void <init>(boolean) ,public void <init>(boolean, boolean) ,public CacheWrapper#RAW copy(com.esotericsoftware.kryo.Kryo, CacheWrapper#RAW) ,public boolean getAcceptsNull() ,public boolean isImmutable() ,public abstract CacheWrapper#RAW read(com.esotericsoftware.kryo.Kryo, com.esotericsoftware.kryo.io.Input, Class<CacheWrapper#RAW>) ,public void setAcceptsNull(boolean) ,public void setGenerics(com.esotericsoftware.kryo.Kryo, Class#RAW[]) ,public void setImmutable(boolean) ,public abstract void write(com.esotericsoftware.kryo.Kryo, com.esotericsoftware.kryo.io.Output, CacheWrapper#RAW) <variables>private boolean acceptsNull,private boolean immutable |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-kryo/src/main/java/com/jarvis/cache/serializer/kryo/DefaultKryoContext.java | DefaultKryoContext | serialize | class DefaultKryoContext implements KryoContext {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 100;
private KryoPool pool;
private List<KryoClassRegistration> registrations;
public static KryoContext newKryoContextFactory(KryoClassRegistration registration) {
KryoContext kryoContext = new DefaultKryoContext();
kryoContext.addKryoClassRegistration(registration);
return kryoContext;
}
private DefaultKryoContext() {
registrations = new ArrayList<>();
//KryoFactory的create方法会延后调用
pool = new KryoPool.Builder(() -> {
Kryo kryo = new Kryo();
registrations.forEach(reg -> reg.register(kryo));
return kryo;
}).softReferences().build();
}
@Override
public byte[] serialize(Object obj) {
return serialize(obj, DEFAULT_BUFFER_SIZE);
}
@Override
public byte[] serialize(Object obj, int bufferSize) {<FILL_FUNCTION_BODY>}
@Override
public Object deserialize(byte[] serialized) {
Kryo kryo = pool.borrow();
try (Input input = new Input(new ByteArrayInputStream(serialized))) {
Object o = kryo.readClassAndObject(input);
return o;
} finally {
pool.release(kryo);
}
}
@Override
public void addKryoClassRegistration(KryoClassRegistration registration) {
if (null != registration) {
registrations.add(registration);
}
}
} |
Kryo kryo = pool.borrow();
try (Output output = new Output(new ByteArrayOutputStream(), bufferSize)) {
kryo.writeClassAndObject(output, obj);
return output.toBytes();
} finally {
pool.release(kryo);
}
| 451 | 77 | 528 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/HeapByteBufUtil.java | HeapByteBufUtil | setIntLE | class HeapByteBufUtil {
static byte getByte(byte[] memory, int index) {
return memory[index];
}
static short getShort(byte[] memory, int index) {
return (short) (memory[index] << 8 | memory[index + 1] & 0xFF);
}
static short getShortLE(byte[] memory, int index) {
return (short) (memory[index] & 0xff | memory[index + 1] << 8);
}
static int getUnsignedMedium(byte[] memory, int index) {
return (memory[index] & 0xff) << 16 |
(memory[index + 1] & 0xff) << 8 |
memory[index + 2] & 0xff;
}
static int getUnsignedMediumLE(byte[] memory, int index) {
return memory[index] & 0xff |
(memory[index + 1] & 0xff) << 8 |
(memory[index + 2] & 0xff) << 16;
}
static int getInt(byte[] memory, int index) {
return (memory[index] & 0xff) << 24 |
(memory[index + 1] & 0xff) << 16 |
(memory[index + 2] & 0xff) << 8 |
memory[index + 3] & 0xff;
}
static int getIntLE(byte[] memory, int index) {
return memory[index] & 0xff |
(memory[index + 1] & 0xff) << 8 |
(memory[index + 2] & 0xff) << 16 |
(memory[index + 3] & 0xff) << 24;
}
static long getLong(byte[] memory, int index) {
return ((long) memory[index] & 0xff) << 56 |
((long) memory[index + 1] & 0xff) << 48 |
((long) memory[index + 2] & 0xff) << 40 |
((long) memory[index + 3] & 0xff) << 32 |
((long) memory[index + 4] & 0xff) << 24 |
((long) memory[index + 5] & 0xff) << 16 |
((long) memory[index + 6] & 0xff) << 8 |
(long) memory[index + 7] & 0xff;
}
static long getLongLE(byte[] memory, int index) {
return (long) memory[index] & 0xff |
((long) memory[index + 1] & 0xff) << 8 |
((long) memory[index + 2] & 0xff) << 16 |
((long) memory[index + 3] & 0xff) << 24 |
((long) memory[index + 4] & 0xff) << 32 |
((long) memory[index + 5] & 0xff) << 40 |
((long) memory[index + 6] & 0xff) << 48 |
((long) memory[index + 7] & 0xff) << 56;
}
static void setByte(byte[] memory, int index, int value) {
memory[index] = (byte) value;
}
static void setShort(byte[] memory, int index, int value) {
memory[index] = (byte) (value >>> 8);
memory[index + 1] = (byte) value;
}
static void setShortLE(byte[] memory, int index, int value) {
memory[index] = (byte) value;
memory[index + 1] = (byte) (value >>> 8);
}
static void setMedium(byte[] memory, int index, int value) {
memory[index] = (byte) (value >>> 16);
memory[index + 1] = (byte) (value >>> 8);
memory[index + 2] = (byte) value;
}
static void setMediumLE(byte[] memory, int index, int value) {
memory[index] = (byte) value;
memory[index + 1] = (byte) (value >>> 8);
memory[index + 2] = (byte) (value >>> 16);
}
static void setInt(byte[] memory, int index, int value) {
memory[index] = (byte) (value >>> 24);
memory[index + 1] = (byte) (value >>> 16);
memory[index + 2] = (byte) (value >>> 8);
memory[index + 3] = (byte) value;
}
static void setIntLE(byte[] memory, int index, int value) {<FILL_FUNCTION_BODY>}
static void setLong(byte[] memory, int index, long value) {
memory[index] = (byte) (value >>> 56);
memory[index + 1] = (byte) (value >>> 48);
memory[index + 2] = (byte) (value >>> 40);
memory[index + 3] = (byte) (value >>> 32);
memory[index + 4] = (byte) (value >>> 24);
memory[index + 5] = (byte) (value >>> 16);
memory[index + 6] = (byte) (value >>> 8);
memory[index + 7] = (byte) value;
}
static void setLongLE(byte[] memory, int index, long value) {
memory[index] = (byte) value;
memory[index + 1] = (byte) (value >>> 8);
memory[index + 2] = (byte) (value >>> 16);
memory[index + 3] = (byte) (value >>> 24);
memory[index + 4] = (byte) (value >>> 32);
memory[index + 5] = (byte) (value >>> 40);
memory[index + 6] = (byte) (value >>> 48);
memory[index + 7] = (byte) (value >>> 56);
}
private HeapByteBufUtil() {
}
} |
memory[index] = (byte) value;
memory[index + 1] = (byte) (value >>> 8);
memory[index + 2] = (byte) (value >>> 16);
memory[index + 3] = (byte) (value >>> 24);
| 1,590 | 74 | 1,664 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ProtoBufSerializer.java | ProtoBufSerializer | deepCloneMethodArgs | class ProtoBufSerializer implements ISerializer<CacheWrapper<Object>> {
private ConcurrentHashMap<Class, Lambda> lambdaMap = new ConcurrentHashMap<>();
private static final ObjectMapper MAPPER = new ObjectMapper();
public ProtoBufSerializer() {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.registerModule(new SimpleModule().addSerializer(new NullValueSerializer(null)));
MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
}
@Override
public byte[] serialize(CacheWrapper<Object> obj) throws Exception {
WriteByteBuf byteBuf = new WriteByteBuf();
byteBuf.writeInt(obj.getExpire());
byteBuf.writeLong(obj.getLastLoadTime());
Object cacheObj = obj.getCacheObject();
if (cacheObj != null) {
if (cacheObj instanceof Message) {
byteBuf.writeBytes(((Message) cacheObj).toByteArray());
} else {
MAPPER.writeValue(byteBuf, cacheObj);
}
}
return byteBuf.toByteArray();
}
@Override
public CacheWrapper<Object> deserialize(final byte[] bytes, Type returnType) throws Exception {
if (bytes == null || bytes.length == 0) {
return null;
}
CacheWrapper<Object> cacheWrapper = new CacheWrapper<>();
ReadByteBuf byteBuf = new ReadByteBuf(bytes);
cacheWrapper.setExpire(byteBuf.readInt());
cacheWrapper.setLastLoadTime(byteBuf.readLong());
byte[] body = byteBuf.readableBytes();
if (body == null || body.length == 0) {
return cacheWrapper;
}
Class<?> clazz = TypeFactory.rawClass(returnType);
if (Message.class.isAssignableFrom(clazz)) {
Lambda lambda = getLambda(clazz);
Object obj = lambda.invoke_for_Object(new ByteArrayInputStream(body));
cacheWrapper.setCacheObject(obj);
} else {
Type[] agsType = new Type[]{returnType};
JavaType javaType = MAPPER.getTypeFactory().constructType(ParameterizedTypeImpl.make(CacheWrapper.class, agsType, null));
cacheWrapper.setCacheObject(MAPPER.readValue(body, clazz));
}
return cacheWrapper;
}
@SuppressWarnings("unchecked")
@Override
public Object deepClone(Object obj, Type type) throws Exception {
if (null == obj) {
return null;
}
Class<?> clazz = obj.getClass();
if (BeanUtil.isPrimitive(obj) || clazz.isEnum() || obj instanceof Class || clazz.isAnnotation()
|| clazz.isSynthetic()) {// 常见不会被修改的数据类型
return obj;
}
if (obj instanceof Date) {
return ((Date) obj).clone();
} else if (obj instanceof Calendar) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(((Calendar) obj).getTime().getTime());
return cal;
}
if (obj instanceof CacheWrapper) {
CacheWrapper<Object> wrapper = (CacheWrapper<Object>) obj;
CacheWrapper<Object> res = new CacheWrapper<>();
res.setExpire(wrapper.getExpire());
res.setLastLoadTime(wrapper.getLastLoadTime());
res.setCacheObject(deepClone(wrapper.getCacheObject(), null));
return res;
}
if (obj instanceof Message) {
return ((Message) obj).toBuilder().build();
}
return MAPPER.readValue(MAPPER.writeValueAsBytes(obj), clazz);
}
@Override
public Object[] deepCloneMethodArgs(Method method, Object[] args) throws Exception {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private Lambda getLambda(Class clazz) throws NoSuchMethodException {
Lambda lambda = lambdaMap.get(clazz);
if (lambda == null) {
Method method = clazz.getDeclaredMethod("parseFrom", InputStream.class);
try {
lambda = LambdaFactory.create(method);
lambdaMap.put(clazz, lambda);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
return lambda;
}
private class NullValueSerializer extends StdSerializer<NullValue> {
private static final long serialVersionUID = 1999052150548658808L;
private final String classIdentifier;
/**
* @param classIdentifier can be {@literal null} and will be defaulted
* to {@code @class}.
*/
NullValueSerializer(String classIdentifier) {
super(NullValue.class);
this.classIdentifier = StringUtil.hasText(classIdentifier) ? classIdentifier : "@class";
}
/*
* (non-Javadoc)
* @see
* com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.
* lang.Object, com.fasterxml.jackson.core.JsonGenerator,
* com.fasterxml.jackson.databind.SerializerProvider)
*/
@Override
public void serialize(NullValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField(classIdentifier, NullValue.class.getName());
jgen.writeEndObject();
}
}
} |
if (null == args || args.length == 0) {
return args;
}
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (args.length != genericParameterTypes.length) {
throw new Exception("the length of " + method.getDeclaringClass().getName() + "." + method.getName() + " must " + genericParameterTypes.length);
}
Object[] res = new Object[args.length];
int len = genericParameterTypes.length;
for (int i = 0; i < len; i++) {
res[i] = deepClone(args[i], null);
}
return res;
| 1,466 | 165 | 1,631 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/ReadByteBuf.java | ReadByteBuf | readableBytes | class ReadByteBuf {
private byte[] array;
private int readerIndex;
public ReadByteBuf(byte[] array) {
this.array = array;
this.readerIndex = 0;
}
public byte readByte() {
byte value = HeapByteBufUtil.getByte(array, readerIndex);
readerIndex += 1;
return value;
}
public int readInt() {
int value = HeapByteBufUtil.getInt(array, readerIndex);
readerIndex += 4;
return value;
}
public long readLong() {
long value = HeapByteBufUtil.getLong(array, readerIndex);
readerIndex += 8;
return value;
}
public byte[] readableBytes() {<FILL_FUNCTION_BODY>}
} |
byte[] newArray = new byte[array.length - readerIndex];
System.arraycopy(array, readerIndex, newArray, 0, newArray.length);
return newArray;
| 209 | 49 | 258 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-protobuf/src/main/java/com/jarvis/cache/serializer/protobuf/WriteByteBuf.java | WriteByteBuf | writeBytes | class WriteByteBuf extends OutputStream {
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private byte[] buf;
private int count;
public WriteByteBuf() {
this(32);
}
@Override
public void write(int b) throws IOException {
writeByte((byte) b);
}
public WriteByteBuf(int arrayLength) {
buf = new byte[arrayLength];
}
public void writeByte(byte value) {
int length = 1;
ensureCapacity(length + count);
HeapByteBufUtil.setByte(buf, count, value);
count += length;
}
public void writeInt(int value) {
int length = 4;
ensureCapacity(length + count);
HeapByteBufUtil.setInt(buf, count, value);
count += length;
}
public void writeLong(long value) {
int length = 8;
ensureCapacity(length + count);
HeapByteBufUtil.setLong(buf, count, value);
count += length;
}
public void writeBytes(byte[] bytes) {<FILL_FUNCTION_BODY>}
public byte[] toByteArray() {
byte[] newArray = new byte[count];
System.arraycopy(buf, 0, newArray, 0, count);
return newArray;
}
private void ensureCapacity(int minCapacity) {
// overflow-conscious code
if (minCapacity - buf.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = buf.length;
int newCapacity = oldCapacity << 1;
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
buf = Arrays.copyOf(buf, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
} |
int length = bytes.length;
ensureCapacity(bytes.length + count);
System.arraycopy(bytes, 0, buf, count, length);
count += bytes.length;
| 607 | 50 | 657 | <methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/admin/AutoloadCacheController.java | AutoloadCacheController | listAutoLoadVO | class AutoloadCacheController {
private static final Logger log = LoggerFactory.getLogger(AutoloadCacheController.class);
private final CacheHandler autoloadCacheHandler;
public AutoloadCacheController(CacheHandler autoloadCacheHandler) {
this.autoloadCacheHandler = autoloadCacheHandler;
}
@GetMapping
public AutoLoadVO[] listAutoLoadVO() {<FILL_FUNCTION_BODY>}
@GetMapping("/args")
public Object[] showArgs(String key, String hfield) {
CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield);
AutoLoadTO tmpTO = autoloadCacheHandler.getAutoLoadHandler().getAutoLoadTO(cacheKeyTO);
if (null != tmpTO && null != tmpTO.getArgs()) {
return tmpTO.getArgs();
}
return null;
}
@PostMapping("removeCache")
public boolean removeCache(String key, String hfield) {
CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield);
try {
Set<CacheKeyTO> keys=new HashSet<>();
keys.add(cacheKeyTO);
autoloadCacheHandler.delete(keys);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
@PostMapping("removeAutoloadTO")
public boolean removeAutoloadTO(String key, String hfield) {
CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield);
try {
autoloadCacheHandler.getAutoLoadHandler().removeAutoLoadTO(cacheKeyTO);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
@PostMapping("resetLastLoadTime")
public boolean resetLastLoadTime(String key, String hfield) {
CacheKeyTO cacheKeyTO = new CacheKeyTO(autoloadCacheHandler.getAutoLoadConfig().getNamespace(), key, hfield);
try {
autoloadCacheHandler.getAutoLoadHandler().resetAutoLoadLastLoadTime(cacheKeyTO);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
private static final ThreadLocal<SimpleDateFormat> FORMATER = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
private String formatDate(long time) {
if (time < 100000) {
return "";
}
Date date = new Date(time);
return FORMATER.get().format(date);
}
} |
AutoLoadTO queue[] = autoloadCacheHandler.getAutoLoadHandler().getAutoLoadQueue();
if (null == queue || queue.length == 0) {
return null;
}
AutoLoadVO[] autoLoadVOs = new AutoLoadVO[queue.length];
for (int i = 0; i < queue.length; i++) {
AutoLoadTO tmpTO = queue[i];
CacheAopProxyChain pjp = tmpTO.getJoinPoint();
String className = pjp.getTarget().getClass().getName();
String methodName = pjp.getMethod().getName();
CacheKeyTO cacheKeyTO = tmpTO.getCacheKey();
AutoLoadVO autoLoadVO = new AutoLoadVO();
autoLoadVO.setNamespace(cacheKeyTO.getNamespace());
autoLoadVO.setKey(cacheKeyTO.getKey());
autoLoadVO.setHfield(cacheKeyTO.getHfield());
autoLoadVO.setMethod(className + "." + methodName);
autoLoadVO.setLastRequestTime(formatDate(tmpTO.getLastRequestTime()));
autoLoadVO.setFirstRequestTime(formatDate(tmpTO.getFirstRequestTime()));
autoLoadVO.setRequestTimes(tmpTO.getRequestTimes());
autoLoadVO.setLastLoadTime(formatDate(tmpTO.getLastLoadTime()));
autoLoadVO.setExpire(tmpTO.getCache().expire());
// 缓存过期时间
autoLoadVO.setExpireTime(formatDate(tmpTO.getLastLoadTime() + tmpTO.getCache().expire() * 1000));
autoLoadVO.setRequestTimeout(tmpTO.getCache().requestTimeout());
autoLoadVO.setRequestTimeoutTime(
formatDate(tmpTO.getLastRequestTime() + tmpTO.getCache().requestTimeout() * 1000));
autoLoadVO.setLoadCount(tmpTO.getLoadCnt());
autoLoadVO.setAverageUseTime(tmpTO.getAverageUseTime());
autoLoadVOs[i] = autoLoadVO;
}
return autoLoadVOs;
| 765 | 523 | 1,288 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/admin/HTTPBasicAuthorizeAttribute.java | HTTPBasicAuthorizeAttribute | checkHeaderAuth | class HTTPBasicAuthorizeAttribute implements Filter {
private static final String SESSION_AUTH_ATTRIBUTE = "autoload-cache-auth";
private final AutoloadCacheProperties properties;
public HTTPBasicAuthorizeAttribute(AutoloadCacheProperties properties) {
this.properties = properties;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String sessionAuth = (String) (request).getSession().getAttribute(SESSION_AUTH_ATTRIBUTE);
if (sessionAuth == null) {
if (!checkHeaderAuth(request, response)) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("WWW-Authenticate", "Basic realm=\"input username and password\"");
return;
}
}
chain.doFilter(request, response);
}
private boolean checkHeaderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
private String getFromBASE64(String s) {
if (s == null) {
return null;
}
try {
byte[] b = Base64.getDecoder().decode(s);
return new String(b);
} catch (Exception e) {
return null;
}
}
@Override
public void destroy() {
}
} |
String userName = properties.getAdminUserName();
if (null == userName || userName.isEmpty()) {
return true;
}
String password = properties.getAdminPassword();
String auth = request.getHeader("Authorization");
if ((auth != null) && (auth.length() > 6)) {
auth = auth.substring(6, auth.length());
String decodedAuth = getFromBASE64(auth);
if (decodedAuth != null) {
String[] userArray = decodedAuth.split(":");
if (userArray != null && userArray.length == 2 && userName.equals(userArray[0])) {
if ((null == password || password.isEmpty())
|| (null != password && password.equals(userArray[1]))) {
request.getSession().setAttribute(SESSION_AUTH_ATTRIBUTE, decodedAuth);
return true;
}
}
}
}
return false;
| 448 | 244 | 692 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/AutoloadCacheAutoConfigure.java | AutoloadCacheAutoConfigure | filterRegistrationBean | class AutoloadCacheAutoConfigure {
private static final String VALIDATOR_BEAN_NAME = "autoloadCacheAutoConfigurationValidator";
@Autowired
private AutoloadCacheProperties config;
private final ILock lock;
public AutoloadCacheAutoConfigure(ObjectProvider<ILock> lockProvider) {
if (null != lockProvider) {
lock = lockProvider.getIfAvailable();
} else {
lock = null;
}
}
@Bean(name = VALIDATOR_BEAN_NAME)
public CacheManagerValidator autoloadCacheAutoConfigurationValidator() {
return new CacheManagerValidator();
}
@Bean(destroyMethod = "destroy")
@ConditionalOnMissingBean(CacheHandler.class)
@ConditionalOnBean({ ICacheManager.class, AbstractScriptParser.class, ICloner.class })
public CacheHandler autoloadCacheHandler(ICacheManager cacheManager, AbstractScriptParser scriptParser,
ICloner cloner) {
CacheHandler cacheHandler = new CacheHandler(cacheManager, scriptParser, config.getConfig(), cloner);
cacheHandler.setLock(lock);
return cacheHandler;
}
// 1. 创建通知 suixingpay.autoload.cache. 和
// suixingpay.autoload.cache.enable-delete
@Bean
@ConditionalOnBean(CacheHandler.class)
@ConditionalOnProperty(value = AutoloadCacheProperties.PREFIX + ".enable-read-and-write", matchIfMissing = true)
public CacheMethodInterceptor autoloadCacheMethodInterceptor(CacheHandler cacheHandler) {
return new CacheMethodInterceptor(cacheHandler, config);
}
@Bean
@ConditionalOnBean(CacheHandler.class)
@ConditionalOnProperty(value = AutoloadCacheProperties.PREFIX + ".enable-delete", matchIfMissing = true)
public CacheDeleteInterceptor autoloadCacheDeleteInterceptor(CacheHandler cacheHandler) {
return new CacheDeleteInterceptor(cacheHandler, config);
}
@Bean
@ConditionalOnBean(CacheHandler.class)
@ConditionalOnProperty(value = AutoloadCacheProperties.PREFIX + ".enable-delete", matchIfMissing = true)
public CacheDeleteTransactionalInterceptor autoloadCacheDeleteTransactionalInterceptor(CacheHandler cacheHandler) {
return new CacheDeleteTransactionalInterceptor(cacheHandler, config);
}
// 2.配置Advisor
@Bean("autoloadCacheAdvisor")
@ConditionalOnBean(CacheMethodInterceptor.class)
public AbstractPointcutAdvisor autoloadCacheAdvisor(CacheMethodInterceptor cacheMethodInterceptor) {
AbstractPointcutAdvisor cacheAdvisor = new MethodAnnotationPointcutAdvisor(Cache.class, cacheMethodInterceptor);
cacheAdvisor.setOrder(config.getCacheOrder());
return cacheAdvisor;
}
@Bean("autoloadCacheDeleteAdvisor")
@ConditionalOnBean(CacheDeleteInterceptor.class)
public AbstractPointcutAdvisor autoloadCacheDeleteAdvisor(CacheDeleteInterceptor cacheDeleteInterceptor) {
AbstractPointcutAdvisor cacheDeleteAdvisor = new MethodAnnotationPointcutAdvisor(CacheDelete.class,
cacheDeleteInterceptor);
cacheDeleteAdvisor.setOrder(config.getDeleteCacheOrder());
return cacheDeleteAdvisor;
}
@Bean("autoloadCacheDeleteTransactionalAdvisor")
@ConditionalOnBean(CacheDeleteTransactionalInterceptor.class)
public AbstractPointcutAdvisor autoloadCacheDeleteTransactionalAdvisor(
CacheDeleteTransactionalInterceptor cacheDeleteTransactionalInterceptor) {
AbstractPointcutAdvisor cacheDeleteTransactionalAdvisor = new MethodAnnotationPointcutAdvisor(
CacheDeleteTransactional.class, cacheDeleteTransactionalInterceptor);
cacheDeleteTransactionalAdvisor.setOrder(config.getDeleteCacheTransactionalOrder());
return cacheDeleteTransactionalAdvisor;
}
// 3.配置ProxyCreator
@Bean
@ConditionalOnBean(CacheHandler.class)
public AbstractAdvisorAutoProxyCreator autoloadCacheAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator proxy = new DefaultAdvisorAutoProxyCreator();
proxy.setAdvisorBeanNamePrefix("autoloadCache");
proxy.setProxyTargetClass(config.isProxyTargetClass());
// proxy.setInterceptorNames("cacheAdvisor","cacheDeleteAdvisor","cacheDeleteTransactionalAdvisor");//
// 注意此处不需要设置,否则会执行两次
return proxy;
}
@Bean
@ConditionalOnWebApplication
public FilterRegistrationBean filterRegistrationBean() {<FILL_FUNCTION_BODY>}
@Bean
@ConditionalOnWebApplication
@ConditionalOnMissingBean(AutoloadCacheController.class)
public AutoloadCacheController AutoloadCacheController(CacheHandler autoloadCacheHandler) {
return new AutoloadCacheController(autoloadCacheHandler);
}
static class CacheManagerValidator {
@Autowired(required = false)
private AbstractScriptParser scriptParser;
@Autowired(required = false)
private ISerializer<Object> serializer;
@Autowired(required = false)
private ICacheManager cacheManager;
@PostConstruct
public void checkHasCacheManager() {
Assert.notNull(this.scriptParser, "No script parser could be auto-configured");
Assert.notNull(this.serializer, "No serializer could be auto-configured");
Assert.notNull(this.cacheManager, "No cache manager could be auto-configured");
}
}
} |
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
HTTPBasicAuthorizeAttribute httpBasicFilter = new HTTPBasicAuthorizeAttribute(config);
registrationBean.setFilter(httpBasicFilter);
List<String> urlPatterns = new ArrayList<String>();
urlPatterns.add("/autoload-cache-ui.html");
urlPatterns.add("/autoload-cache/*");
registrationBean.setUrlPatterns(urlPatterns);
return registrationBean;
| 1,450 | 119 | 1,569 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/AutoloadCacheManageConfiguration.java | LettuceCacheCacheManagerConfiguration | createRedisCacheManager | class LettuceCacheCacheManagerConfiguration {
/**
* 默认只支持{@link LettuceRedisClusterCacheManager}<br>
*
* @param config
* @param serializer
* @param connectionFactory
* @return
*/
@Bean
@ConditionalOnMissingBean(ICacheManager.class)
@ConditionalOnBean(LettuceConnectionFactory.class)
public ICacheManager autoloadCacheCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer,
LettuceConnectionFactory connectionFactory) {
return createRedisCacheManager(config, serializer, connectionFactory);
}
private ICacheManager createRedisCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer, LettuceConnectionFactory connectionFactory) {<FILL_FUNCTION_BODY>}
} |
RedisConnection redisConnection = null;
try {
redisConnection = connectionFactory.getConnection();
AbstractRedisCacheManager cacheManager = null;
if (redisConnection instanceof LettuceClusterConnection) {
LettuceClusterConnection lettuceClusterConnection = (LettuceClusterConnection) redisConnection;
try {
Field clusterClientField = LettuceClusterConnection.class.getDeclaredField("clusterClient");
clusterClientField.setAccessible(true);
RedisClusterClient redisClusterClient = (RedisClusterClient) clusterClientField.get(lettuceClusterConnection);
cacheManager = new LettuceRedisClusterCacheManager(redisClusterClient, serializer);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
cacheManager = new SpringRedisCacheManager(connectionFactory, serializer);
}
// 根据需要自行配置
cacheManager.setHashExpire(config.getJedis().getHashExpire());
return cacheManager;
} catch (Throwable e) {
log.error(e.getMessage(), e);
throw e;
} finally {
RedisConnectionUtils.releaseConnection(redisConnection, connectionFactory);
}
| 214 | 309 | 523 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/AutoloadCacheProperties.java | AutoloadCacheProperties | init | class AutoloadCacheProperties {
public static final String PREFIX = "autoload.cache";
private AutoLoadConfig config = new AutoLoadConfig();
private JedisCacheManagerConfig jedis = new JedisCacheManagerConfig();
@Autowired
private Environment env;
private boolean namespaceEnable = true;
private boolean proxyTargetClass = true;
private boolean enable = true;
/**
* @Cache 注解是否生效, 默认值为true
*/
private boolean enableReadAndWrite = true;
/**
* @DeleteCache 和 @DeleteCacheTransactional 注解是否生效, 默认值为true
*/
private boolean enableDelete = true;
/**
* @Cache 注解AOP执行顺序
*/
private int cacheOrder = Integer.MAX_VALUE;
/**
* @DeleteCache 注解AOP执行顺序
*/
private int deleteCacheOrder = Integer.MAX_VALUE;
/**
* @DeleteCacheTransactionalAspect 注解AOP执行顺序
*/
private int deleteCacheTransactionalOrder = 0;
private String adminUserName = "admin";
private String adminPassword = "admin";
public AutoLoadConfig getConfig() {
return config;
}
public void setConfig(AutoLoadConfig config) {
this.config = config;
}
public JedisCacheManagerConfig getJedis() {
return jedis;
}
public void setJedis(JedisCacheManagerConfig jedis) {
this.jedis = jedis;
}
public Environment getEnv() {
return env;
}
public void setEnv(Environment env) {
this.env = env;
}
public boolean isNamespaceEnable() {
return namespaceEnable;
}
public void setNamespaceEnable(boolean namespaceEnable) {
this.namespaceEnable = namespaceEnable;
}
public boolean isProxyTargetClass() {
return proxyTargetClass;
}
public void setProxyTargetClass(boolean proxyTargetClass) {
this.proxyTargetClass = proxyTargetClass;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public boolean isEnableReadAndWrite() {
return enableReadAndWrite;
}
public void setEnableReadAndWrite(boolean enableReadAndWrite) {
this.enableReadAndWrite = enableReadAndWrite;
}
public boolean isEnableDelete() {
return enableDelete;
}
public void setEnableDelete(boolean enableDelete) {
this.enableDelete = enableDelete;
}
public int getCacheOrder() {
return cacheOrder;
}
public void setCacheOrder(int cacheOrder) {
this.cacheOrder = cacheOrder;
}
public int getDeleteCacheOrder() {
return deleteCacheOrder;
}
public void setDeleteCacheOrder(int deleteCacheOrder) {
this.deleteCacheOrder = deleteCacheOrder;
}
public int getDeleteCacheTransactionalOrder() {
return deleteCacheTransactionalOrder;
}
public void setDeleteCacheTransactionalOrder(int deleteCacheTransactionalOrder) {
this.deleteCacheTransactionalOrder = deleteCacheTransactionalOrder;
}
public String getAdminUserName() {
return adminUserName;
}
public void setAdminUserName(String adminUserName) {
this.adminUserName = adminUserName;
}
public String getAdminPassword() {
return adminPassword;
}
public void setAdminPassword(String adminPassword) {
this.adminPassword = adminPassword;
}
@PostConstruct
public void init() {<FILL_FUNCTION_BODY>}
/**
* 对JedisClusterCacheManager 进行配置
*
*
*/
static class JedisCacheManagerConfig {
/**
* Hash的缓存时长:等于0时永久缓存;大于0时,主要是为了防止一些已经不用的缓存占用内存;hashExpire小于0时,则使用@Cache中设置的expire值(默认值为-1)。
*/
private int hashExpire = -1;
public int getHashExpire() {
return hashExpire;
}
public void setHashExpire(int hashExpire) {
this.hashExpire = hashExpire;
}
}
} |
if (namespaceEnable && null != env) {
String namespace = config.getNamespace();
if (null == namespace || namespace.trim().length() == 0) {
String applicationName = env.getProperty("spring.application.name");
if (null != applicationName && applicationName.trim().length() > 0) {
config.setNamespace(applicationName);
}
}
}
| 1,165 | 103 | 1,268 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/DistributedLockConfiguration.java | DistributedLockConfiguration | autoLoadCacheDistributedLock | class DistributedLockConfiguration {
private static final Logger logger = LoggerFactory.getLogger(DistributedLockConfiguration.class);
@Bean
@ConditionalOnMissingBean({ILock.class})
@ConditionalOnClass(RedisConnectionFactory.class)
@ConditionalOnBean(RedisConnectionFactory.class)
public ILock autoLoadCacheDistributedLock(RedisConnectionFactory connectionFactory) {<FILL_FUNCTION_BODY>}
} |
if (null == connectionFactory) {
return null;
}
SpringRedisLock lock = new SpringRedisLock(connectionFactory);
if (logger.isDebugEnabled()) {
logger.debug("ILock with SpringJedisLock auto-configured");
}
return lock;
| 115 | 77 | 192 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/CacheDeleteInterceptor.java | CacheDeleteInterceptor | invoke | class CacheDeleteInterceptor implements MethodInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CacheDeleteInterceptor.class);
private final CacheHandler cacheHandler;
private final AutoloadCacheProperties config;
public CacheDeleteInterceptor(CacheHandler cacheHandler, AutoloadCacheProperties config) {
this.cacheHandler = cacheHandler;
this.config = config;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
} |
if (!this.config.isEnable()) {
return invocation.proceed();
}
Method method = invocation.getMethod();
// if (method.getDeclaringClass().isInterface()) {
Class<?> cls = AopUtil.getTargetClass(invocation.getThis());
if (!cls.equals(invocation.getThis().getClass())) {
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass() + "-->" + cls);
}
return invocation.proceed();
}
// }
Object result = invocation.proceed();
if (method.isAnnotationPresent(CacheDelete.class)) {
CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + method.getName() + "-->@CacheDelete");
}
cacheHandler.deleteCache(new DeleteCacheAopProxy(invocation), cacheDelete, result);
} else {
Method specificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis().getClass());
if (specificMethod.isAnnotationPresent(CacheDelete.class)) {
CacheDelete cacheDelete = specificMethod.getAnnotation(CacheDelete.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + specificMethod.getName()
+ "-->@CacheDelete");
}
cacheHandler.deleteCache(new DeleteCacheAopProxy(invocation), cacheDelete, result);
}
}
return result;
| 141 | 414 | 555 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/CacheDeleteTransactionalInterceptor.java | CacheDeleteTransactionalInterceptor | invoke | class CacheDeleteTransactionalInterceptor implements MethodInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CacheDeleteTransactionalInterceptor.class);
private final CacheHandler cacheHandler;
private final AutoloadCacheProperties config;
public CacheDeleteTransactionalInterceptor(CacheHandler cacheHandler, AutoloadCacheProperties config) {
this.cacheHandler = cacheHandler;
this.config = config;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
} |
if (!this.config.isEnable()) {
return invocation.proceed();
}
Method method = invocation.getMethod();
// if (method.getDeclaringClass().isInterface()) {
Class<?> cls = AopUtil.getTargetClass(invocation.getThis());
if (!cls.equals(invocation.getThis().getClass())) {
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass() + "-->" + cls);
}
return invocation.proceed();
}
// }
if (logger.isDebugEnabled()) {
logger.debug(invocation.toString());
}
if (method.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cacheDeleteTransactional = method.getAnnotation(CacheDeleteTransactional.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + method.getName()
+ "-->@CacheDeleteTransactional");
}
return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),
cacheDeleteTransactional);
} else {
Method specificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis().getClass());
if (specificMethod.isAnnotationPresent(CacheDeleteTransactional.class)) {
CacheDeleteTransactional cacheDeleteTransactional = specificMethod
.getAnnotation(CacheDeleteTransactional.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + specificMethod.getName()
+ "-->@CacheDeleteTransactional");
}
return cacheHandler.proceedDeleteCacheTransactional(new DeleteCacheTransactionalAopProxy(invocation),
cacheDeleteTransactional);
}
}
return invocation.proceed();
| 147 | 474 | 621 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/CacheMethodInterceptor.java | CacheMethodInterceptor | invoke | class CacheMethodInterceptor implements MethodInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CacheMethodInterceptor.class);
private final CacheHandler cacheHandler;
private final AutoloadCacheProperties config;
public CacheMethodInterceptor(CacheHandler cacheHandler, AutoloadCacheProperties config) {
this.cacheHandler = cacheHandler;
this.config = config;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
} |
if (!this.config.isEnable()) {
return invocation.proceed();
}
Method method = invocation.getMethod();
// if (method.getDeclaringClass().isInterface()) {
Class<?> cls = AopUtil.getTargetClass(invocation.getThis());
if (!cls.equals(invocation.getThis().getClass())) {
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass() + "-->" + cls);
}
return invocation.proceed();
}
// }
if (logger.isDebugEnabled()) {
logger.debug(invocation.toString());
}
if (method.isAnnotationPresent(Cache.class)) {
Cache cache = method.getAnnotation(Cache.class);
if (logger.isDebugEnabled()) {
logger.debug(invocation.getThis().getClass().getName() + "." + method.getName() + "-->@Cache");
}
return cacheHandler.proceed(new CacheAopProxy(invocation), cache);
} else {
Method specificMethod = AopUtils.getMostSpecificMethod(method, invocation.getThis().getClass());
if (specificMethod.isAnnotationPresent(Cache.class)) {
Cache cache = specificMethod.getAnnotation(Cache.class);
if (logger.isDebugEnabled()) {
logger.debug(
invocation.getThis().getClass().getName() + "." + specificMethod.getName() + "-->@Cache");
}
return cacheHandler.proceed(new CacheAopProxy(invocation), cache);
}
}
return invocation.proceed();
| 141 | 416 | 557 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/aopproxy/CacheAopProxy.java | CacheAopProxy | getMethod | class CacheAopProxy implements CacheAopProxyChain {
private final MethodInvocation invocation;
private Method method;
public CacheAopProxy(MethodInvocation invocation) {
this.invocation = invocation;
}
@Override
public Object[] getArgs() {
return invocation.getArguments();
}
@Override
public Object getTarget() {
return invocation.getThis();
}
@Override
public Method getMethod() {<FILL_FUNCTION_BODY>}
@Override
public Object doProxyChain(Object[] arguments) throws Throwable {
return getMethod().invoke(invocation.getThis(), arguments);
}
} |
if (null == method) {
this.method = invocation.getMethod();
}
return method;
| 181 | 32 | 213 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/interceptor/aopproxy/DeleteCacheAopProxy.java | DeleteCacheAopProxy | getMethod | class DeleteCacheAopProxy implements DeleteCacheAopProxyChain {
private final MethodInvocation invocation;
private Method method;
public DeleteCacheAopProxy(MethodInvocation invocation) {
this.invocation = invocation;
}
@Override
public Object[] getArgs() {
return invocation.getArguments();
}
@Override
public Object getTarget() {
return invocation.getThis();
}
@Override
public Method getMethod() {<FILL_FUNCTION_BODY>}
} |
if (null == method) {
this.method = invocation.getMethod();
}
return method;
| 142 | 32 | 174 | <no_super_class> |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/redis/SpringRedisCacheManager.java | RedisConnectionClient | mget | class RedisConnectionClient implements IRedis {
private final RedisConnectionFactory redisConnectionFactory;
private final RedisConnection redisConnection;
private final AbstractRedisCacheManager cacheManager;
public RedisConnectionClient(RedisConnectionFactory redisConnectionFactory, AbstractRedisCacheManager cacheManager) {
this.redisConnectionFactory = redisConnectionFactory;
this.redisConnection = RedisConnectionUtils.getConnection(redisConnectionFactory);
// TransactionSynchronizationManager.hasResource(redisConnectionFactory);
this.cacheManager = cacheManager;
}
@Override
public void close() {
RedisConnectionUtils.releaseConnection(redisConnection, redisConnectionFactory);
}
@Override
public void set(byte[] key, byte[] value) {
redisConnection.stringCommands().set(key, value);
}
@Override
public void setex(byte[] key, int seconds, byte[] value) {
redisConnection.stringCommands().setEx(key, seconds, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value) {
redisConnection.hashCommands().hSet(key, field, value);
}
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
try {
redisConnection.openPipeline();
redisConnection.hashCommands().hSet(key, field, value);
redisConnection.keyCommands().expire(key, seconds);
} finally {
redisConnection.closePipeline();
}
}
@Override
public void mset(Collection<MSetParam> params) throws Exception {
CacheKeyTO cacheKeyTO;
String cacheKey;
String hfield;
CacheWrapper<Object> result;
byte[] key;
byte[] val;
try {
redisConnection.openPipeline();
for (MSetParam param : params) {
if (null == param) {
continue;
}
cacheKeyTO = param.getCacheKey();
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
result = param.getResult();
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
val = cacheManager.getSerializer().serialize(result);
if (null == hfield || hfield.isEmpty()) {
int expire = result.getExpire();
if (expire == AbstractRedisCacheManager.NEVER_EXPIRE) {
redisConnection.stringCommands().set(key, val);
} else if (expire > 0) {
redisConnection.stringCommands().setEx(key, expire, val);
}
} else {
int hExpire = cacheManager.getHashExpire() < 0 ? result.getExpire() : cacheManager.getHashExpire();
redisConnection.hashCommands().hSet(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield), val);
if (hExpire > 0) {
redisConnection.keyCommands().expire(key, hExpire);
}
}
}
} finally {
redisConnection.closePipeline();
}
}
@Override
public byte[] get(byte[] key) {
return redisConnection.stringCommands().get(key);
}
@Override
public byte[] hget(byte[] key, byte[] field) {
return redisConnection.hashCommands().hGet(key, field);
}
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void delete(Set<CacheKeyTO> keys) {
try {
redisConnection.openPipeline();
for (CacheKeyTO cacheKeyTO : keys) {
String cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.length() == 0) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("delete cache {}", cacheKey);
}
String hfield = cacheKeyTO.getHfield();
if (null == hfield || hfield.length() == 0) {
redisConnection.keyCommands().del(KEY_SERIALIZER.serialize(cacheKey));
} else {
redisConnection.hashCommands().hDel(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield));
}
}
} finally {
redisConnection.closePipeline();
}
}
} |
String hfield;
String cacheKey;
byte[] key;
try {
redisConnection.openPipeline();
for (CacheKeyTO cacheKeyTO : keys) {
cacheKey = cacheKeyTO.getCacheKey();
if (null == cacheKey || cacheKey.isEmpty()) {
continue;
}
hfield = cacheKeyTO.getHfield();
key = AbstractRedisCacheManager.KEY_SERIALIZER.serialize(cacheKey);
if (null == hfield || hfield.isEmpty()) {
redisConnection.stringCommands().get(key);
} else {
redisConnection.hashCommands().hGet(key, AbstractRedisCacheManager.KEY_SERIALIZER.serialize(hfield));
}
}
} finally {
return cacheManager.deserialize(keys, redisConnection.closePipeline(), returnType);
}
| 1,228 | 225 | 1,453 | <methods>public void <init>(ISerializer<java.lang.Object>) ,public void delete(Set<com.jarvis.cache.to.CacheKeyTO>) throws com.jarvis.cache.exception.CacheCenterConnectionException,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> deserialize(Set<com.jarvis.cache.to.CacheKeyTO>, Collection<java.lang.Object>, java.lang.reflect.Type) throws java.lang.Exception,public CacheWrapper<java.lang.Object> get(com.jarvis.cache.to.CacheKeyTO, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public int getHashExpire() ,public ISerializer<java.lang.Object> getSerializer() ,public Map<com.jarvis.cache.to.CacheKeyTO,CacheWrapper<java.lang.Object>> mget(java.lang.reflect.Method, java.lang.reflect.Type, Set<com.jarvis.cache.to.CacheKeyTO>) ,public void mset(java.lang.reflect.Method, Collection<com.jarvis.cache.MSetParam>) ,public void setCache(com.jarvis.cache.to.CacheKeyTO, CacheWrapper<java.lang.Object>, java.lang.reflect.Method) throws com.jarvis.cache.exception.CacheCenterConnectionException,public void setHashExpire(int) <variables>public static final com.jarvis.cache.serializer.StringSerializer KEY_SERIALIZER,protected int hashExpire,private static final org.slf4j.Logger log,protected final non-sealed ISerializer<java.lang.Object> serializer |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/redis/SpringRedisLock.java | SpringRedisLock | setnx | class SpringRedisLock extends AbstractRedisLock {
private static final Logger logger = LoggerFactory.getLogger(SpringRedisLock.class);
private static final StringSerializer STRING_SERIALIZER = new StringSerializer();
private final RedisConnectionFactory redisConnectionFactory;
public SpringRedisLock(RedisConnectionFactory redisConnectionFactory) {
this.redisConnectionFactory = redisConnectionFactory;
}
private RedisConnection getConnection() {
return RedisConnectionUtils.getConnection(redisConnectionFactory);
}
@Override
protected boolean setnx(String key, String val, int expire) {<FILL_FUNCTION_BODY>}
@Override
protected void del(String key) {
if (null == redisConnectionFactory || null == key || key.length() == 0) {
return;
}
RedisConnection redisConnection = getConnection();
try {
redisConnection.keyCommands().del(STRING_SERIALIZER.serialize(key));
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
} finally {
RedisConnectionUtils.releaseConnection(redisConnection, redisConnectionFactory);
}
}
} |
if (null == redisConnectionFactory || null == key || key.isEmpty()) {
return false;
}
RedisConnection redisConnection = getConnection();
try {
Expiration expiration = Expiration.from(expire, TimeUnit.SECONDS);
// 采用redisson做客户端时,set key value [EX | PX] [NX | XX] 会因为条件不满足无法设值成功而返回null导致拆箱空指针
Boolean locked = redisConnection.stringCommands().set(STRING_SERIALIZER.serialize(key), STRING_SERIALIZER.serialize(val), expiration, RedisStringCommands.SetOption.SET_IF_ABSENT);
return locked == null ? false : locked;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
} finally {
RedisConnectionUtils.releaseConnection(redisConnection, redisConnectionFactory);
}
return false;
| 310 | 240 | 550 | <methods>public non-sealed void <init>() ,public boolean tryLock(java.lang.String, int) ,public void unlock(java.lang.String) <variables>protected static final java.lang.String EX,private static final ThreadLocal<Map<java.lang.String,com.jarvis.cache.to.RedisLockInfo>> LOCK_START_TIME,protected static final java.lang.String NX,protected static final java.lang.String OK,private static final org.slf4j.Logger logger |
qiujiayu_AutoLoadCache | AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/util/AopUtil.java | AopUtil | getTargetClass | class AopUtil {
/**
* @param target
* @return
*/
public static Class<?> getTargetClass(Object target) {<FILL_FUNCTION_BODY>}
} |
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
if (targetClass == null && target != null) {
targetClass = target.getClass();
}
return targetClass;
| 55 | 58 | 113 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/common/filter/AuthFilter.java | AuthFilter | doFilter | class AuthFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
/**
* doFilter determines if user is an administrator or redirect to login page
*
* @param req task request
* @param resp task response
* @param chain filter chain
* @throws ServletException
*/
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException {<FILL_FUNCTION_BODY>}
} |
HttpServletRequest servletRequest = (HttpServletRequest) req;
HttpServletResponse servletResponse = (HttpServletResponse) resp;
boolean isAdmin = false;
try {
//read auth token
String authToken = AuthUtil.getAuthToken(servletRequest.getSession());
//check if exists
if (authToken != null && !authToken.trim().equals("")) {
//check if valid admin auth token
String userType = AuthDB.isAuthorized(AuthUtil.getUserId(servletRequest.getSession()), authToken);
if (userType != null) {
String uri = servletRequest.getRequestURI();
if (Auth.MANAGER.equals(userType)) {
isAdmin = true;
} else if (!uri.contains("/manage/") && Auth.ADMINISTRATOR.equals(userType)) {
isAdmin = true;
}
AuthUtil.setUserType(servletRequest.getSession(), userType);
//check to see if user has timed out
String timeStr = AuthUtil.getTimeout(servletRequest.getSession());
if (timeStr != null && !timeStr.trim().equals("")) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyHHmmss");
Date sessionTimeout = sdf.parse(timeStr);
Date currentTime = new Date();
//if current time > timeout then redirect to login page
if (sessionTimeout == null || currentTime.after(sessionTimeout)) {
isAdmin = false;
} else {
AuthUtil.setTimeout(servletRequest.getSession());
}
} else {
isAdmin = false;
}
}
}
//if not admin redirect to login page
if (!isAdmin) {
AuthUtil.deleteAllSession(servletRequest.getSession());
servletResponse.sendRedirect(servletRequest.getContextPath() + "/");
} else {
chain.doFilter(req, resp);
}
} catch (SQLException | ParseException | IOException | GeneralSecurityException ex) {
AuthUtil.deleteAllSession(servletRequest.getSession());
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
| 159 | 566 | 725 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/common/util/AppConfig.java | AppConfig | decryptProperty | class AppConfig {
private static final Logger log = LoggerFactory.getLogger(AppConfig.class);
private static PropertiesConfiguration prop;
public static final String CONFIG_DIR = StringUtils.isNotEmpty(System.getProperty("CONFIG_DIR")) ? System.getProperty("CONFIG_DIR").trim() : AppConfig.class.getClassLoader().getResource(".").getPath();
static {
try {
//move configuration to specified dir
if (StringUtils.isNotEmpty(System.getProperty("CONFIG_DIR"))) {
File configFile = new File(CONFIG_DIR + "BastillionConfig.properties");
if (!configFile.exists()) {
File oldConfig = new File(AppConfig.class.getClassLoader().getResource(".").getPath() + "BastillionConfig.properties");
FileUtils.moveFile(oldConfig, configFile);
}
configFile = new File(CONFIG_DIR + "jaas.conf");
if (!configFile.exists()) {
File oldConfig = new File(AppConfig.class.getClassLoader().getResource(".").getPath() + "jaas.conf");
FileUtils.moveFile(oldConfig, configFile);
}
}
prop = new PropertiesConfiguration(CONFIG_DIR + "BastillionConfig.properties");
} catch (IOException | ConfigurationException ex) {
log.error(ex.toString(), ex);
}
}
private AppConfig() {
}
/**
* gets the property from config
*
* @param name property name
* @return configuration property
*/
public static String getProperty(String name) {
String property = null;
if (StringUtils.isNotEmpty(name)) {
if (StringUtils.isNotEmpty(System.getenv(name))) {
property = System.getenv(name);
} else if (StringUtils.isNotEmpty(System.getenv(name.toUpperCase()))) {
property = System.getenv(name.toUpperCase());
} else {
property = prop.getString(name);
}
}
return property;
}
/**
* gets the property from config
*
* @param name property name
* @param defaultValue default value if property is empty
* @return configuration property
*/
public static String getProperty(String name, String defaultValue) {
String value = getProperty(name);
if (StringUtils.isEmpty(value)) {
value = defaultValue;
}
return value;
}
/**
* gets the property from config and replaces placeholders
*
* @param name property name
* @param replacementMap name value pairs of place holders to replace
* @return configuration property
*/
public static String getProperty(String name, Map<String, String> replacementMap) {
String value = getProperty(name);
if (StringUtils.isNotEmpty(value)) {
//iterate through map to replace text
Set<String> keySet = replacementMap.keySet();
for (String key : keySet) {
//replace values in string
String rVal = replacementMap.get(key);
value = value.replace("${" + key + "}", rVal);
}
}
return value;
}
/**
* removes property from the config
*
* @param name property name
*/
public static void removeProperty(String name) throws ConfigurationException {
//remove property
prop.clearProperty(name);
prop.save();
}
/**
* updates the property in the config
*
* @param name property name
* @param value property value
*/
public static void updateProperty(String name, String value) throws ConfigurationException {
//remove property
if (StringUtils.isNotEmpty(value)) {
prop.setProperty(name, value);
prop.save();
}
}
/**
* checks if property is encrypted
*
* @param name property name
* @return true if property is encrypted
*/
public static boolean isPropertyEncrypted(String name) {
String property = prop.getString(name);
if (StringUtils.isNotEmpty(property)) {
return property.matches("^" + EncryptionUtil.CRYPT_ALGORITHM + "\\{.*\\}$");
} else {
return false;
}
}
/**
* decrypts and returns the property from config
*
* @param name property name
* @return configuration property
*/
public static String decryptProperty(String name) throws GeneralSecurityException {<FILL_FUNCTION_BODY>}
/**
* encrypts and updates the property in the config
*
* @param name property name
* @param value property value
*/
public static void encryptProperty(String name, String value) throws ConfigurationException, GeneralSecurityException {
//remove property
if (StringUtils.isNotEmpty(value)) {
prop.setProperty(name, EncryptionUtil.CRYPT_ALGORITHM + "{" + EncryptionUtil.encrypt(value) + "}");
prop.save();
}
}
} |
String retVal = prop.getString(name);
if (StringUtils.isNotEmpty(retVal)) {
retVal = retVal.replaceAll("^" + EncryptionUtil.CRYPT_ALGORITHM + "\\{", "").replaceAll("\\}$", "");
retVal = EncryptionUtil.decrypt(retVal);
}
return retVal;
| 1,308 | 97 | 1,405 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/common/util/AuthUtil.java | AuthUtil | getAuthToken | class AuthUtil {
public static final String SESSION_ID = "sessionId";
public static final String USER_ID = "userId";
public static final String USERNAME = "username";
public static final String AUTH_TOKEN = "authToken";
public static final String TIMEOUT = "timeout";
private AuthUtil() {
}
/**
* query session for OTP shared secret
*
* @param session http session
* @return shared secret
*/
public static String getOTPSecret(HttpSession session) throws GeneralSecurityException {
String secret = (String) session.getAttribute("otp_secret");
secret = EncryptionUtil.decrypt(secret);
return secret;
}
/**
* set authentication type
*
* @param session http session
* @param authType authentication type
*/
public static void setAuthType(HttpSession session, String authType) {
if (authType != null) {
session.setAttribute("authType", authType);
}
}
/**
* query authentication type
*
* @param session http session
* @return authentication type
*/
public static String getAuthType(HttpSession session) {
String authType = (String) session.getAttribute("authType");
return authType;
}
/**
* set user type
*
* @param session http session
* @param userType user type
*/
public static void setUserType(HttpSession session, String userType) {
if (userType != null) {
session.setAttribute("userType", userType);
}
}
/**
* query user type
*
* @param session http session
* @return user type
*/
public static String getUserType(HttpSession session) {
String userType = (String) session.getAttribute("userType");
return userType;
}
/**
* set session id
*
* @param session http session
* @param sessionId session id
*/
public static void setSessionId(HttpSession session, Long sessionId) throws GeneralSecurityException {
if (sessionId != null) {
session.setAttribute(SESSION_ID, EncryptionUtil.encrypt(sessionId.toString()));
}
}
/**
* query session id
*
* @param session http session
* @return session id
*/
public static Long getSessionId(HttpSession session) throws GeneralSecurityException {
Long sessionId = null;
String sessionIdStr = EncryptionUtil.decrypt((String) session.getAttribute(SESSION_ID));
if (sessionIdStr != null && !sessionIdStr.trim().equals("")) {
sessionId = Long.parseLong(sessionIdStr);
}
return sessionId;
}
/**
* query session for user id
*
* @param session http session
* @return user id
*/
public static Long getUserId(HttpSession session) throws GeneralSecurityException {
Long userId = null;
String userIdStr = EncryptionUtil.decrypt((String) session.getAttribute(USER_ID));
if (userIdStr != null && !userIdStr.trim().equals("")) {
userId = Long.parseLong(userIdStr);
}
return userId;
}
/**
* query session for the username
*
* @param session http session
* @return username
*/
public static String getUsername(HttpSession session) {
return (String) session.getAttribute(USERNAME);
}
/**
* query session for authentication token
*
* @param session http session
* @return authentication token
*/
public static String getAuthToken(HttpSession session) throws GeneralSecurityException {<FILL_FUNCTION_BODY>}
/**
* query session for timeout
*
* @param session http session
* @return timeout string
*/
public static String getTimeout(HttpSession session) {
String timeout = (String) session.getAttribute(TIMEOUT);
return timeout;
}
/**
* set session OTP shared secret
*
* @param session http session
* @param secret shared secret
*/
public static void setOTPSecret(HttpSession session, String secret) throws GeneralSecurityException {
if (secret != null && !secret.trim().equals("")) {
session.setAttribute("otp_secret", EncryptionUtil.encrypt(secret));
}
}
/**
* set session user id
*
* @param session http session
* @param userId user id
*/
public static void setUserId(HttpSession session, Long userId) throws GeneralSecurityException {
if (userId != null) {
session.setAttribute(USER_ID, EncryptionUtil.encrypt(userId.toString()));
}
}
/**
* set session username
*
* @param session http session
* @param username username
*/
public static void setUsername(HttpSession session, String username) {
if (username != null) {
session.setAttribute(USERNAME, username);
}
}
/**
* set session authentication token
*
* @param session http session
* @param authToken authentication token
*/
public static void setAuthToken(HttpSession session, String authToken) throws GeneralSecurityException {
if (authToken != null && !authToken.trim().equals("")) {
session.setAttribute(AUTH_TOKEN, EncryptionUtil.encrypt(authToken));
}
}
/**
* set session timeout
*
* @param session http session
*/
public static void setTimeout(HttpSession session) {
//set session timeout
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyHHmmss");
Calendar timeout = Calendar.getInstance();
timeout.add(Calendar.MINUTE, Integer.parseInt(AppConfig.getProperty("sessionTimeout", "15")));
session.setAttribute(TIMEOUT, sdf.format(timeout.getTime()));
}
/**
* delete all session information
*
* @param session
*/
public static void deleteAllSession(HttpSession session) {
session.setAttribute(TIMEOUT, null);
session.setAttribute(AUTH_TOKEN, null);
session.setAttribute(USER_ID, null);
session.setAttribute(SESSION_ID, null);
session.invalidate();
}
/**
* return client ip from servlet request
*
* @param servletRequest http servlet request
* @return client ip
*/
public static String getClientIPAddress(HttpServletRequest servletRequest) {
String clientIP = null;
if (StringUtils.isNotEmpty(AppConfig.getProperty("clientIPHeader"))) {
clientIP = servletRequest.getHeader(AppConfig.getProperty("clientIPHeader"));
}
if (StringUtils.isEmpty(clientIP)) {
clientIP = servletRequest.getRemoteAddr();
}
return clientIP;
}
} |
String authToken = (String) session.getAttribute(AUTH_TOKEN);
authToken = EncryptionUtil.decrypt(authToken);
return authToken;
| 1,815 | 45 | 1,860 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/LoginKtrl.java | LoginKtrl | loginSubmit | class LoginKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(LoginKtrl.class);
//check if otp is enabled
@Model(name = "otpEnabled")
static final Boolean otpEnabled = ("required".equals(AppConfig.getProperty("oneTimePassword")) || "optional".equals(AppConfig.getProperty("oneTimePassword")));
private static final Logger loginAuditLogger = LoggerFactory.getLogger("io.bastillion.manage.control.LoginAudit");
private final String AUTH_ERROR = "Authentication Failed : Login credentials are invalid";
private final String AUTH_ERROR_NO_PROFILE = "Authentication Failed : There are no profiles assigned to this account";
private final String AUTH_ERROR_EXPIRED_ACCOUNT = "Authentication Failed : Account has expired";
@Model(name = "auth")
Auth auth;
public LoginKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/login", method = MethodType.GET)
public String login() {
return "/login.html";
}
@Kontrol(path = "/loginSubmit", method = MethodType.POST)
public String loginSubmit() throws ServletException {<FILL_FUNCTION_BODY>}
@Kontrol(path = "/logout", method = MethodType.GET)
public String logout() {
AuthUtil.deleteAllSession(getRequest().getSession());
return "redirect:/";
}
/**
* Validates fields for auth submit
*/
@Validate(input = "/login.html")
public void validateLoginSubmit() {
if (auth.getUsername() == null ||
auth.getUsername().trim().equals("")) {
addFieldError("auth.username", "Required");
}
if (auth.getPassword() == null ||
auth.getPassword().trim().equals("")) {
addFieldError("auth.password", "Required");
}
}
} |
String retVal = "redirect:/admin/menu.html";
String authToken = null;
try {
authToken = AuthDB.login(auth);
//get client IP
String clientIP = AuthUtil.getClientIPAddress(getRequest());
if (authToken != null) {
User user = AuthDB.getUserByAuthToken(authToken);
if (user != null) {
String sharedSecret = null;
if (otpEnabled) {
sharedSecret = AuthDB.getSharedSecret(user.getId());
if (StringUtils.isNotEmpty(sharedSecret) && (auth.getOtpToken() == null || !OTPUtil.verifyToken(sharedSecret, auth.getOtpToken()))) {
loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR);
addError(AUTH_ERROR);
return "/login.html";
}
}
//check to see if admin has any assigned profiles
if (!User.MANAGER.equals(user.getUserType()) && (user.getProfileList() == null || user.getProfileList().size() <= 0)) {
loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR_NO_PROFILE);
addError(AUTH_ERROR_NO_PROFILE);
return "/login.html";
}
//check to see if account has expired
if (user.isExpired()) {
loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR_EXPIRED_ACCOUNT);
addError(AUTH_ERROR_EXPIRED_ACCOUNT);
return "/login.html";
}
AuthUtil.setAuthToken(getRequest().getSession(), authToken);
AuthUtil.setUserId(getRequest().getSession(), user.getId());
AuthUtil.setAuthType(getRequest().getSession(), user.getAuthType());
AuthUtil.setTimeout(getRequest().getSession());
AuthUtil.setUsername(getRequest().getSession(), user.getUsername());
AuthDB.updateLastLogin(user);
//for first time login redirect to set OTP
if (otpEnabled && StringUtils.isEmpty(sharedSecret)) {
retVal = "redirect:/admin/viewOTP.ktrl";
} else if ("changeme".equals(auth.getPassword()) && Auth.AUTH_BASIC.equals(user.getAuthType())) {
retVal = "redirect:/admin/userSettings.ktrl";
}
loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - Authentication Success");
}
} else {
loginAuditLogger.info(auth.getUsername() + " (" + clientIP + ") - " + AUTH_ERROR);
addError(AUTH_ERROR);
retVal = "/login.html";
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return retVal;
| 572 | 868 | 1,440 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/OTPKtrl.java | OTPKtrl | qrImage | class OTPKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(OTPKtrl.class);
public static final boolean requireOTP = "required".equals(AppConfig.getProperty("oneTimePassword"));
//QR image size
private static final int QR_IMAGE_WIDTH = 325;
private static final int QR_IMAGE_HEIGHT = 325;
@Model(name = "qrImage")
String qrImage;
@Model(name = "sharedSecret")
String sharedSecret;
public OTPKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/admin/viewOTP", method = MethodType.GET)
public String viewOTP() throws ServletException {
sharedSecret = OTPUtil.generateSecret();
try {
AuthUtil.setOTPSecret(getRequest().getSession(), sharedSecret);
} catch (GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
qrImage = new Date().getTime() + ".png";
return "/admin/two-factor_otp.html";
}
@Kontrol(path = "/admin/otpSubmit", method = MethodType.POST)
public String otpSubmit() throws ServletException {
try {
AuthDB.updateSharedSecret(sharedSecret, AuthUtil.getAuthToken(getRequest().getSession()));
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
if (requireOTP) {
AuthUtil.deleteAllSession(getRequest().getSession());
}
return "redirect:/logout.ktrl";
}
@Kontrol(path = "/admin/qrImage", method = MethodType.GET)
public String qrImage() throws ServletException {<FILL_FUNCTION_BODY>}
} |
String username;
String secret;
try {
username = UserDB.getUser(AuthUtil.getUserId(getRequest().getSession())).getUsername();
secret = AuthUtil.getOTPSecret(getRequest().getSession());
AuthUtil.setOTPSecret(getRequest().getSession(), null);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
try {
String qrCodeText = "otpauth://totp/Bastillion%20%28" + URLEncoder.encode(getRequest().getHeader("host").replaceAll("\\:.*$", ""), "utf-8") + "%29:" + username + "?secret=" + secret;
QRCodeWriter qrWriter = new QRCodeWriter();
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix matrix = qrWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, QR_IMAGE_WIDTH, QR_IMAGE_HEIGHT, hints);
getResponse().setContentType("image/png");
BufferedImage image = new BufferedImage(QR_IMAGE_WIDTH, QR_IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, QR_IMAGE_WIDTH, QR_IMAGE_HEIGHT);
graphics.setColor(Color.BLACK);
for (int x = 0; x < QR_IMAGE_WIDTH; x++) {
for (int y = 0; y < QR_IMAGE_HEIGHT; y++) {
if (matrix.get(x, y)) {
graphics.fillRect(x, y, 1, 1);
}
}
}
ImageIO.write(image, "png", getResponse().getOutputStream());
getResponse().getOutputStream().flush();
getResponse().getOutputStream().close();
} catch (IOException | WriterException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return null;
| 592 | 675 | 1,267 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/ProfileKtrl.java | ProfileKtrl | saveProfile | class ProfileKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(ProfileKtrl.class);
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "profile")
Profile profile = new Profile();
public ProfileKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/manage/viewProfiles", method = MethodType.GET)
public String viewSystems() throws ServletException {
try {
sortedSet = ProfileDB.getProfileSet(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/manage/view_profiles.html";
}
@Kontrol(path = "/manage/saveProfile", method = MethodType.POST)
public String saveProfile() throws ServletException {<FILL_FUNCTION_BODY>}
@Kontrol(path = "/manage/deleteProfile", method = MethodType.GET)
public String deleteProfile() throws ServletException {
if (profile.getId() != null) {
try {
ProfileDB.deleteProfile(profile.getId());
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
return "redirect:/manage/viewProfiles.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
}
/**
* validate save profile
*/
@Validate(input = "/manage/view_profiles.html")
public void validateSaveProfile() throws ServletException {
if (profile == null
|| profile.getNm() == null
|| profile.getNm().trim().equals("")) {
addFieldError("profile.nm", "Required");
}
if (!this.getFieldErrors().isEmpty()) {
try {
sortedSet = ProfileDB.getProfileSet(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
}
} |
try {
if (profile.getId() != null) {
ProfileDB.updateProfile(profile);
} else {
ProfileDB.insertProfile(profile);
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "redirect:/manage/viewProfiles.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
| 693 | 161 | 854 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/ProfileSystemsKtrl.java | ProfileSystemsKtrl | viewProfileSystems | class ProfileSystemsKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(ProfileSystemsKtrl.class);
@Model(name = "profile")
Profile profile;
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "systemSelectId")
List<Long> systemSelectId = new ArrayList<>();
public ProfileSystemsKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/manage/viewProfileSystems", method = MethodType.GET)
public String viewProfileSystems() throws ServletException {<FILL_FUNCTION_BODY>}
@Kontrol(path = "/manage/assignSystemsToProfile", method = MethodType.POST)
public String assignSystemsToProfile() throws ServletException {
if (systemSelectId != null) {
try {
ProfileSystemsDB.setSystemsForProfile(profile.getId(), systemSelectId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
RefreshAuthKeyUtil.refreshProfileSystems(profile.getId());
return "redirect:/manage/viewProfiles.ktrl";
}
} |
if (profile != null && profile.getId() != null) {
try {
profile = ProfileDB.getProfile(profile.getId());
sortedSet = SystemDB.getSystemSet(sortedSet, profile.getId());
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
return "/manage/view_profile_systems.html";
| 361 | 122 | 483 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/ProfileUsersKtrl.java | ProfileUsersKtrl | assignSystemsToProfile | class ProfileUsersKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(ProfileUsersKtrl.class);
@Model(name = "profile")
Profile profile;
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "userSelectId")
List<Long> userSelectId = new ArrayList<>();
public ProfileUsersKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/manage/viewProfileUsers", method = MethodType.GET)
public String viewProfileUsers() throws ServletException {
if (profile != null && profile.getId() != null) {
try {
profile = ProfileDB.getProfile(profile.getId());
sortedSet = UserDB.getAdminUserSet(sortedSet, profile.getId());
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
return "/manage/view_profile_users.html";
}
@Kontrol(path = "/manage/assignUsersToProfile", method = MethodType.POST)
public String assignSystemsToProfile() throws ServletException {<FILL_FUNCTION_BODY>}
} |
if (userSelectId != null) {
try {
UserProfileDB.setUsersForProfile(profile.getId(), userSelectId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
RefreshAuthKeyUtil.refreshProfileSystems(profile.getId());
return "redirect:/manage/viewProfiles.ktrl";
| 351 | 120 | 471 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/ScriptKtrl.java | ScriptKtrl | validateSaveScript | class ScriptKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(ScriptKtrl.class);
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "script")
Script script = new Script();
public ScriptKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/admin/viewScripts", method = MethodType.GET)
public String viewScripts() throws ServletException {
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
sortedSet = ScriptDB.getScriptSet(sortedSet, userId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/admin/view_scripts.html";
}
@Kontrol(path = "/admin/saveScript", method = MethodType.POST)
public String saveScript() throws ServletException {
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
if (script.getId() != null) {
ScriptDB.updateScript(script, userId);
} else {
ScriptDB.insertScript(script, userId);
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "redirect:/admin/viewScripts.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
}
@Kontrol(path = "/admin/deleteScript", method = MethodType.GET)
public String deleteScript() throws ServletException {
if (script.getId() != null) {
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
ScriptDB.deleteScript(script.getId(), userId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
return "redirect:/admin/viewScripts.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
}
/**
* Validates all fields for adding a user
*/
@Validate(input = "/admin/view_scripts.html")
public void validateSaveScript() throws ServletException {<FILL_FUNCTION_BODY>}
} |
if (script == null
|| script.getDisplayNm() == null
|| script.getDisplayNm().trim().equals("")) {
addFieldError("script.displayNm", "Required");
}
if (script == null
|| script.getScript() == null
|| script.getScript().trim().equals("")
|| (new Script()).getScript().trim().equals(script.getScript().trim())) {
addFieldError("script.script", "Required");
}
if (!this.getFieldErrors().isEmpty()) {
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
sortedSet = ScriptDB.getScriptSet(sortedSet, userId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
| 707 | 227 | 934 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/SessionAuditKtrl.java | SessionAuditKtrl | getJSONTermOutputForSession | class SessionAuditKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(SessionAuditKtrl.class);
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "sessionId")
Long sessionId;
@Model(name = "instanceId")
Integer instanceId;
@Model(name = "sessionAudit")
SessionAudit sessionAudit;
@Model(name = "systemList")
List<HostSystem> systemList;
@Model(name = "userList")
List<User> userList;
public SessionAuditKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/manage/viewSessions", method = MethodType.GET)
public String viewSessions() throws ServletException {
if (sortedSet.getOrderByField() == null || sortedSet.getOrderByField().trim().equals("")) {
sortedSet.setOrderByField(SessionAuditDB.SORT_BY_SESSION_TM);
sortedSet.setOrderByDirection("desc");
}
try {
systemList = SystemDB.getSystemSet(new SortedSet(SystemDB.SORT_BY_NAME)).getItemList();
userList = UserDB.getUserSet(new SortedSet(SessionAuditDB.SORT_BY_USERNAME)).getItemList();
sortedSet = SessionAuditDB.getSessions(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/manage/view_sessions.html";
}
@Kontrol(path = "/manage/getTermsForSession", method = MethodType.GET)
public String getTermsForSession() throws ServletException {
try {
sessionAudit = SessionAuditDB.getSessionsTerminals(sessionId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/manage/view_terms.html";
}
@Kontrol(path = "/manage/getJSONTermOutputForSession", method = MethodType.GET)
public String getJSONTermOutputForSession() throws ServletException {<FILL_FUNCTION_BODY>}
} |
try {
String json = new Gson().toJson(SessionAuditDB.getTerminalLogsForSession(sessionId, instanceId));
getResponse().getOutputStream().write(json.getBytes());
} catch (SQLException | GeneralSecurityException | IOException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return null;
| 644 | 106 | 750 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/SystemKtrl.java | SystemKtrl | validateSaveSystem | class SystemKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(SystemKtrl.class);
public static final String REQUIRED = "Required";
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "hostSystem")
HostSystem hostSystem = new HostSystem();
@Model(name = "script")
Script script = null;
@Model(name = "password")
String password;
@Model(name = "passphrase")
String passphrase;
@Model(name = "profileList")
List<Profile> profileList = new ArrayList<>();
public SystemKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/admin/viewSystems", method = MethodType.GET)
public String viewAdminSystems() throws ServletException {
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
if (Auth.MANAGER.equals(AuthUtil.getUserType(getRequest().getSession()))) {
sortedSet = SystemDB.getSystemSet(sortedSet);
profileList = ProfileDB.getAllProfiles();
} else {
sortedSet = SystemDB.getUserSystemSet(sortedSet, userId);
profileList = UserProfileDB.getProfilesByUser(userId);
}
if (script != null && script.getId() != null) {
script = ScriptDB.getScript(script.getId(), userId);
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/admin/view_systems.html";
}
@Kontrol(path = "/manage/viewSystems", method = MethodType.GET)
public String viewManageSystems() throws ServletException {
try {
sortedSet = SystemDB.getSystemSet(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/manage/view_systems.html";
}
@Kontrol(path = "/manage/saveSystem", method = MethodType.POST)
public String saveSystem() throws ServletException {
String retVal = "redirect:/manage/viewSystems.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
hostSystem = SSHUtil.authAndAddPubKey(hostSystem, passphrase, password);
try {
if (hostSystem.getId() != null) {
SystemDB.updateSystem(hostSystem);
} else {
hostSystem.setId(SystemDB.insertSystem(hostSystem));
}
sortedSet = SystemDB.getSystemSet(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
if (!HostSystem.SUCCESS_STATUS.equals(hostSystem.getStatusCd())) {
retVal = "/manage/view_systems.html";
}
return retVal;
}
@Kontrol(path = "/manage/deleteSystem", method = MethodType.GET)
public String deleteSystem() throws ServletException {
if (hostSystem.getId() != null) {
try {
SystemDB.deleteSystem(hostSystem.getId());
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
return "redirect:/manage/viewSystems.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
}
/**
* Validates all fields for adding a host system
*/
@Validate(input = "/manage/view_systems.html")
public void validateSaveSystem() throws ServletException {<FILL_FUNCTION_BODY>}
} |
if (hostSystem == null
|| hostSystem.getDisplayNm() == null
|| hostSystem.getDisplayNm().trim().equals("")) {
addFieldError("hostSystem.displayNm", REQUIRED);
}
if (hostSystem == null
|| hostSystem.getUser() == null
|| hostSystem.getUser().trim().equals("")) {
addFieldError("hostSystem.user", REQUIRED);
}
if (hostSystem == null
|| hostSystem.getHost() == null
|| hostSystem.getHost().trim().equals("")) {
addFieldError("hostSystem.host", REQUIRED);
}
if (hostSystem == null
|| hostSystem.getPort() == null) {
addFieldError("hostSystem.port", REQUIRED);
} else if (!(hostSystem.getPort() > 0)) {
addFieldError("hostSystem.port", "Invalid");
}
if (hostSystem == null
|| hostSystem.getAuthorizedKeys() == null
|| hostSystem.getAuthorizedKeys().trim().equals("") || hostSystem.getAuthorizedKeys().trim().equals("~")) {
addFieldError("hostSystem.authorizedKeys", REQUIRED);
}
if (!this.getFieldErrors().isEmpty()) {
try {
sortedSet = SystemDB.getSystemSet(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
| 1,208 | 432 | 1,640 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/UploadAndPushKtrl.java | UploadAndPushKtrl | push | class UploadAndPushKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(UploadAndPushKtrl.class);
public static final String UPLOAD_PATH = DBUtils.class.getClassLoader().getResource(".").getPath() + "../upload";
@Model(name = "upload")
File upload;
@Model(name = "uploadFileName")
String uploadFileName;
@Model(name = "idList")
List<Long> idList = new ArrayList<>();
@Model(name = "pushDir")
String pushDir = "~";
@Model(name = "hostSystemList")
List<HostSystem> hostSystemList;
@Model(name = "pendingSystemStatus")
HostSystem pendingSystemStatus;
@Model(name = "currentSystemStatus")
HostSystem currentSystemStatus;
public UploadAndPushKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/admin/setUpload", method = MethodType.GET)
public String setUpload() throws Exception {
Long userId = AuthUtil.getUserId(getRequest().getSession());
SystemStatusDB.setInitialSystemStatus(idList, userId, AuthUtil.getUserType(getRequest().getSession()));
return "/admin/upload.html";
}
@Kontrol(path = "/admin/uploadSubmit", method = MethodType.POST)
public String uploadSubmit() {
String retVal = "/admin/upload_result.html";
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(getRequest());
for (FileItem item : multiparts) {
if (!item.isFormField()) {
uploadFileName = new File(item.getName()).getName();
File path = new File(UPLOAD_PATH);
if (!path.exists()) {
path.mkdirs();
}
upload = new File(UPLOAD_PATH + File.separator + uploadFileName);
item.write(upload);
} else {
pushDir = item.getString();
}
}
pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
hostSystemList = SystemStatusDB.getAllSystemStatus(userId);
} catch (Exception ex) {
log.error(ex.toString(), ex);
retVal = "/admin/upload.html";
}
//reset csrf token back since it's already set on page load
getRequest().getSession().setAttribute(SecurityFilter._CSRF,
getRequest().getParameter(SecurityFilter._CSRF));
return retVal;
}
@Kontrol(path = "/admin/push", method = MethodType.POST)
public String push() throws ServletException {<FILL_FUNCTION_BODY>}
} |
try {
Long userId = AuthUtil.getUserId(getRequest().getSession());
Long sessionId = AuthUtil.getSessionId(getRequest().getSession());
//get next pending system
pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
if (pendingSystemStatus != null) {
//get session for system
SchSession session = null;
for (Integer instanceId : SecureShellKtrl.getUserSchSessionMap().get(sessionId).getSchSessionMap().keySet()) {
//if host system id matches pending system then upload
if (pendingSystemStatus.getId().equals(SecureShellKtrl.getUserSchSessionMap().get(sessionId).getSchSessionMap().get(instanceId).getHostSystem().getId())) {
session = SecureShellKtrl.getUserSchSessionMap().get(sessionId).getSchSessionMap().get(instanceId);
}
}
if (session != null) {
//push upload to system
currentSystemStatus = SSHUtil.pushUpload(pendingSystemStatus, session.getSession(), UPLOAD_PATH + "/" + uploadFileName, pushDir + "/" + uploadFileName);
//update system status
SystemStatusDB.updateSystemStatus(currentSystemStatus, userId);
pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);
}
}
//if push has finished to all servers then delete uploaded file
if (pendingSystemStatus == null) {
File delFile = new File(UPLOAD_PATH, uploadFileName);
FileUtils.deleteQuietly(delFile);
//delete all expired files in upload path
File delDir = new File(UPLOAD_PATH);
if (delDir.isDirectory()) {
//set expire time to delete all files older than 48 hrs
Calendar expireTime = Calendar.getInstance();
expireTime.add(Calendar.HOUR, -48);
Iterator<File> filesToDelete = FileUtils.iterateFiles(delDir, new AgeFileFilter(expireTime.getTime()), TrueFileFilter.TRUE);
while (filesToDelete.hasNext()) {
delFile = filesToDelete.next();
delFile.delete();
}
}
}
hostSystemList = SystemStatusDB.getAllSystemStatus(userId);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
//reset csrf token back since it's already set on page load
getRequest().getSession().setAttribute(SecurityFilter._CSRF,
getRequest().getParameter(SecurityFilter._CSRF));
return "/admin/upload_result.html";
| 750 | 689 | 1,439 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/UserSettingsKtrl.java | UserSettingsKtrl | passwordSubmit | class UserSettingsKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(UserSettingsKtrl.class);
public static final String REQUIRED = "Required";
@Model(name = "themeMap")
static Map<String, String> themeMap1 = new LinkedHashMap<>(Map.ofEntries(
entry("Tango", "#2e3436,#cc0000,#4e9a06,#c4a000,#3465a4,#75507b,#06989a,#d3d7cf,#555753,#ef2929,#8ae234,#fce94f,#729fcf,#ad7fa8,#34e2e2,#eeeeec"),
entry("XTerm", "#000000,#cd0000,#00cd00,#cdcd00,#0000ee,#cd00cd,#00cdcd,#e5e5e5,#7f7f7f,#ff0000,#00ff00,#ffff00,#5c5cff,#ff00ff,#00ffff,#ffffff")
));
@Model(name = "planeMap")
static Map<String, String> planeMap1 = new LinkedHashMap<>(Map.ofEntries(
entry("Black on light yellow", "#FFFFDD,#000000"),
entry("Black on white", "#FFFFFF,#000000"),
entry("Gray on black", "#000000,#AAAAAA"),
entry("Green on black", "#000000,#00FF00"),
entry("White on black", "#000000,#FFFFFF")
));
@Model(name = "publicKey")
static String publicKey;
@Model(name = "auth")
Auth auth;
@Model(name = "userSettings")
UserSettings userSettings;
static {
try {
publicKey = PrivateKeyDB.getApplicationKey().getPublicKey();
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
}
}
public UserSettingsKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/admin/userSettings", method = MethodType.GET)
public String userSettings() throws ServletException {
try {
userSettings = UserThemeDB.getTheme(AuthUtil.getUserId(getRequest().getSession()));
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/admin/user_settings.html";
}
@Kontrol(path = "/admin/passwordSubmit", method = MethodType.POST)
public String passwordSubmit() throws ServletException {<FILL_FUNCTION_BODY>}
@Kontrol(path = "/admin/themeSubmit", method = MethodType.POST)
public String themeSubmit() throws ServletException {
userSettings.setTheme(userSettings.getTheme());
userSettings.setPlane(userSettings.getPlane());
try {
UserThemeDB.saveTheme(AuthUtil.getUserId(getRequest().getSession()), userSettings);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "redirect:/admin/menu.html";
}
/**
* Validates fields for password submit
*/
@Validate(input = "/admin/user_settings.html")
public void validatePasswordSubmit() {
if (auth.getPassword() == null ||
auth.getPassword().trim().equals("")) {
addFieldError("auth.password", REQUIRED);
}
if (auth.getPasswordConfirm() == null ||
auth.getPasswordConfirm().trim().equals("")) {
addFieldError("auth.passwordConfirm", REQUIRED);
}
if (auth.getPrevPassword() == null ||
auth.getPrevPassword().trim().equals("")) {
addFieldError("auth.prevPassword", REQUIRED);
}
}
} |
String retVal = "/admin/user_settings.html";
if (!auth.getPassword().equals(auth.getPasswordConfirm())) {
addError("Passwords do not match");
} else if (!PasswordUtil.isValid(auth.getPassword())) {
addError(PasswordUtil.PASSWORD_REQ_ERROR_MSG);
} else {
try {
auth.setAuthToken(AuthUtil.getAuthToken(getRequest().getSession()));
if (AuthDB.updatePassword(auth)) {
retVal = "redirect:/admin/menu.html";
} else {
addError("Current password is invalid");
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
}
return retVal;
| 1,212 | 245 | 1,457 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/control/UsersKtrl.java | UsersKtrl | validateSaveUser | class UsersKtrl extends BaseKontroller {
private static final Logger log = LoggerFactory.getLogger(UsersKtrl.class);
public static final String REQUIRED = "Required";
@Model(name = "sortedSet")
SortedSet sortedSet = new SortedSet();
@Model(name = "user")
User user = new User();
@Model(name = "resetSharedSecret")
Boolean resetSharedSecret = false;
@Model(name = "userId")
Long userId;
public UsersKtrl(HttpServletRequest request, HttpServletResponse response) {
super(request, response);
}
@Kontrol(path = "/manage/viewUsers", method = MethodType.GET)
public String viewUsers() throws ServletException {
try {
userId = AuthUtil.getUserId(getRequest().getSession());
sortedSet = UserDB.getUserSet(sortedSet);
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "/manage/view_users.html";
}
@Kontrol(path = "/manage/saveUser", method = MethodType.POST)
public String saveUser() throws ServletException {
String retVal = "redirect:/manage/viewUsers.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
try {
if (user.getId() != null) {
if (user.getPassword() == null || user.getPassword().trim().equals("")) {
UserDB.updateUserNoCredentials(user);
} else {
UserDB.updateUserCredentials(user);
}
//check if reset is set
if (resetSharedSecret) {
UserDB.resetSharedSecret(user.getId());
}
} else {
UserDB.insertUser(user);
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return retVal;
}
@Kontrol(path = "/manage/deleteUser", method = MethodType.GET)
public String deleteUser() throws ServletException {
try {
if (user.getId() != null && !user.getId().equals(AuthUtil.getUserId(getRequest().getSession()))) {
UserDB.deleteUser(user.getId());
PublicKeyDB.deleteUserPublicKeys(user.getId());
RefreshAuthKeyUtil.refreshAllSystems();
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "redirect:/manage/viewUsers.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
}
@Kontrol(path = "/manage/unlockUser", method = MethodType.GET)
public String unlockUser() throws ServletException {
try {
if (user.getId() != null && !user.getId().equals(AuthUtil.getUserId(getRequest().getSession()))) {
UserDB.unlockAccount(user.getId());
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
return "redirect:/manage/viewUsers.ktrl?sortedSet.orderByDirection=" + sortedSet.getOrderByDirection() + "&sortedSet.orderByField=" + sortedSet.getOrderByField();
}
/**
* Validates all fields for adding a user
*/
@Validate(input = "/manage/view_users.html")
public void validateSaveUser() throws ServletException {<FILL_FUNCTION_BODY>}
} |
if (user == null
|| user.getUsername() == null
|| user.getUsername().trim().equals("")) {
addFieldError("user.username", REQUIRED);
}
if (user == null
|| user.getLastNm() == null
|| user.getLastNm().trim().equals("")) {
addFieldError("user.lastNm", REQUIRED);
}
if (user == null
|| user.getFirstNm() == null
|| user.getFirstNm().trim().equals("")) {
addFieldError("user.firstNm", REQUIRED);
}
if (user != null && user.getPassword() != null && !user.getPassword().trim().equals("")) {
if (!user.getPassword().equals(user.getPasswordConfirm())) {
addError("Passwords do not match");
} else if (!PasswordUtil.isValid(user.getPassword())) {
addError(PasswordUtil.PASSWORD_REQ_ERROR_MSG);
}
}
if (user != null && user.getId() == null && !Auth.AUTH_EXTERNAL.equals(user.getAuthType()) && (user.getPassword() == null || user.getPassword().trim().equals(""))) {
addError("Password is required");
}
try {
if (user != null && !UserDB.isUnique(user.getId(), user.getUsername())) {
addError("Username has been taken");
}
if (!this.getFieldErrors().isEmpty() || !this.getErrors().isEmpty()) {
userId = AuthUtil.getUserId(getRequest().getSession());
sortedSet = UserDB.getUserSet(sortedSet);
}
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
throw new ServletException(ex.toString(), ex);
}
| 1,133 | 528 | 1,661 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/PrivateKeyDB.java | PrivateKeyDB | getApplicationKey | class PrivateKeyDB {
private PrivateKeyDB() {
}
/**
* returns public private key for application
*
* @return app key values
*/
public static ApplicationKey getApplicationKey() throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>}
} |
ApplicationKey appKey = null;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("select * from application_key");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
appKey = new ApplicationKey();
appKey.setId(rs.getLong("id"));
appKey.setPassphrase(EncryptionUtil.decrypt(rs.getString("passphrase")));
appKey.setPrivateKey(EncryptionUtil.decrypt(rs.getString("private_key")));
appKey.setPublicKey(rs.getString("public_key"));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
return appKey;
| 77 | 207 | 284 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/ProfileDB.java | ProfileDB | getProfileSet | class ProfileDB {
public static final String FILTER_BY_SYSTEM = "system";
public static final String FILTER_BY_USER = "username";
public static final String SORT_BY_PROFILE_NM = "nm";
private ProfileDB() {
}
/**
* method to do order by based on the sorted set object for profiles
*
* @return list of profiles
*/
public static SortedSet getProfileSet(SortedSet sortedSet) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>}
/**
* returns all profile information
*
* @return list of profiles
*/
public static List<Profile> getAllProfiles() throws SQLException, GeneralSecurityException {
ArrayList<Profile> profileList = new ArrayList<>();
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("select * from profiles order by nm asc");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Profile profile = new Profile();
profile.setId(rs.getLong("id"));
profile.setNm(rs.getString("nm"));
profile.setDesc(rs.getString("desc"));
profileList.add(profile);
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
return profileList;
}
/**
* returns profile based on id
*
* @param profileId profile id
* @return profile
*/
public static Profile getProfile(Long profileId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
Profile profile = getProfile(con, profileId);
DBUtils.closeConn(con);
return profile;
}
/**
* returns profile based on id
*
* @param con db connection object
* @param profileId profile id
* @return profile
*/
public static Profile getProfile(Connection con, Long profileId) throws SQLException {
Profile profile = null;
PreparedStatement stmt = con.prepareStatement("select * from profiles where id=?");
stmt.setLong(1, profileId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
profile = new Profile();
profile.setId(rs.getLong("id"));
profile.setNm(rs.getString("nm"));
profile.setDesc(rs.getString("desc"));
profile.setHostSystemList(ProfileSystemsDB.getSystemsByProfile(con, profileId));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return profile;
}
/**
* inserts new profile
*
* @param profile profile object
*/
public static void insertProfile(Profile profile) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("insert into profiles (nm, desc) values (?,?)");
stmt.setString(1, profile.getNm());
stmt.setString(2, profile.getDesc());
stmt.execute();
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
}
/**
* updates profile
*
* @param profile profile object
*/
public static void updateProfile(Profile profile) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("update profiles set nm=?, desc=? where id=?");
stmt.setString(1, profile.getNm());
stmt.setString(2, profile.getDesc());
stmt.setLong(3, profile.getId());
stmt.execute();
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
}
/**
* deletes profile
*
* @param profileId profile id
*/
public static void deleteProfile(Long profileId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("delete from profiles where id=?");
stmt.setLong(1, profileId);
stmt.execute();
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
}
} |
ArrayList<Profile> profileList = new ArrayList<>();
String orderBy = "";
if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
}
String sql = "select distinct p.* from profiles p ";
if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) {
sql = sql + ", system_map m, system s where m.profile_id = p.id and m.system_id = s.id" +
" and (lower(s.display_nm) like ? or lower(s.host) like ?)";
} else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) {
sql = sql + ", user_map m, users u where m.profile_id = p.id and m.user_id = u.id" +
" and (lower(u.first_nm) like ? or lower(u.last_nm) like ?" +
" or lower(u.email) like ? or lower(u.username) like ?)";
}
sql = sql + orderBy;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement(sql);
if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) {
stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%");
stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%");
} else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) {
stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
stmt.setString(3, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
stmt.setString(4, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
}
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Profile profile = new Profile();
profile.setId(rs.getLong("id"));
profile.setNm(rs.getString("nm"));
profile.setDesc(rs.getString("desc"));
profileList.add(profile);
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
sortedSet.setItemList(profileList);
return sortedSet;
| 1,136 | 785 | 1,921 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/ProfileSystemsDB.java | ProfileSystemsDB | getSystemIdsByProfile | class ProfileSystemsDB {
private ProfileSystemsDB() {
}
/**
* sets host systems for profile
*
* @param profileId profile id
* @param systemIdList list of host system ids
*/
public static void setSystemsForProfile(Long profileId, List<Long> systemIdList) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("delete from system_map where profile_id=?");
stmt.setLong(1, profileId);
stmt.execute();
DBUtils.closeStmt(stmt);
for (Long systemId : systemIdList) {
stmt = con.prepareStatement("insert into system_map (profile_id, system_id) values (?,?)");
stmt.setLong(1, profileId);
stmt.setLong(2, systemId);
stmt.execute();
DBUtils.closeStmt(stmt);
}
DBUtils.closeConn(con);
}
/**
* returns a list of systems for a given profile
*
* @param con DB connection
* @param profileId profile id
* @return list of host systems
*/
public static List<HostSystem> getSystemsByProfile(Connection con, Long profileId) throws SQLException {
List<HostSystem> hostSystemList = new ArrayList<>();
PreparedStatement stmt = con.prepareStatement("select * from system s, system_map m where s.id=m.system_id and m.profile_id=? order by display_nm asc");
stmt.setLong(1, profileId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
HostSystem hostSystem = new HostSystem();
hostSystem.setId(rs.getLong("id"));
hostSystem.setDisplayNm(rs.getString("display_nm"));
hostSystem.setUser(rs.getString("username"));
hostSystem.setHost(rs.getString("host"));
hostSystem.setPort(rs.getInt("port"));
hostSystem.setAuthorizedKeys(rs.getString("authorized_keys"));
hostSystemList.add(hostSystem);
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return hostSystemList;
}
/**
* returns a list of systems for a given profile
*
* @param profileId profile id
* @return list of host systems
*/
public static List<HostSystem> getSystemsByProfile(Long profileId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
List<HostSystem> hostSystemList = getSystemsByProfile(con, profileId);
DBUtils.closeConn(con);
return hostSystemList;
}
/**
* returns a list of system ids for a given profile
*
* @param con DB con
* @param profileId profile id
* @return list of host systems
*/
public static List<Long> getSystemIdsByProfile(Connection con, Long profileId) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* returns a list of system ids for a given profile
*
* @param profileId profile id
* @return list of host systems
*/
public static List<Long> getSystemIdsByProfile(Long profileId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
List<Long> systemIdList = getSystemIdsByProfile(con, profileId);
DBUtils.closeConn(con);
return systemIdList;
}
/**
* returns a list of system ids for a given profile
*
* @param con DB con
* @param profileId profile id
* @param userId user id
* @return list of host systems
*/
public static List<Long> getSystemIdsByProfile(Connection con, Long profileId, Long userId) throws SQLException {
List<Long> systemIdList = new ArrayList<>();
PreparedStatement stmt = con.prepareStatement("select sm.system_id from system_map sm, user_map um where um.profile_id=sm.profile_id and sm.profile_id=? and um.user_id=?");
stmt.setLong(1, profileId);
stmt.setLong(2, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
systemIdList.add(rs.getLong("system_id"));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return systemIdList;
}
/**
* returns a list of system ids for a given profile
*
* @param profileId profile id
* @param userId user id
* @return list of host systems
*/
public static List<Long> getSystemIdsByProfile(Long profileId, Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
List<Long> systemIdList = getSystemIdsByProfile(con, profileId, userId);
DBUtils.closeConn(con);
return systemIdList;
}
} |
List<Long> systemIdList = new ArrayList<>();
PreparedStatement stmt = con.prepareStatement("select * from system s, system_map m where s.id=m.system_id and m.profile_id=? order by display_nm asc");
stmt.setLong(1, profileId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
systemIdList.add(rs.getLong("id"));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return systemIdList;
| 1,344 | 151 | 1,495 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/ScriptDB.java | ScriptDB | getScript | class ScriptDB {
public static final String DISPLAY_NM = "display_nm";
public static final String SORT_BY_DISPLAY_NM = DISPLAY_NM;
private ScriptDB() {
}
/**
* returns scripts based on sort order defined
*
* @param sortedSet object that defines sort order
* @param userId user id
* @return sorted script list
*/
public static SortedSet getScriptSet(SortedSet sortedSet, Long userId) throws SQLException, GeneralSecurityException {
ArrayList<Script> scriptList = new ArrayList<>();
String orderBy = "";
if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
}
String sql = "select * from scripts where user_id=? " + orderBy;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setLong(1, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Script script = new Script();
script.setId(rs.getLong("id"));
script.setDisplayNm(rs.getString(DISPLAY_NM));
script.setScript(rs.getString("script"));
scriptList.add(script);
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
sortedSet.setItemList(scriptList);
return sortedSet;
}
/**
* returns script base on id
*
* @param scriptId script id
* @param userId user id
* @return script object
*/
public static Script getScript(Long scriptId, Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
Script script = getScript(con, scriptId, userId);
DBUtils.closeConn(con);
return script;
}
/**
* returns script base on id
*
* @param con DB connection
* @param scriptId script id
* @param userId user id
* @return script object
*/
public static Script getScript(Connection con, Long scriptId, Long userId) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* inserts new script
*
* @param script script object
* @param userId user id
*/
public static void insertScript(Script script, Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("insert into scripts (display_nm, script, user_id) values (?,?,?)");
stmt.setString(1, script.getDisplayNm());
stmt.setString(2, script.getScript());
stmt.setLong(3, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
}
/**
* updates existing script
*
* @param script script object
* @param userId user id
*/
public static void updateScript(Script script, Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("update scripts set display_nm=?, script=? where id=? and user_id=?");
stmt.setString(1, script.getDisplayNm());
stmt.setString(2, script.getScript());
stmt.setLong(3, script.getId());
stmt.setLong(4, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
}
/**
* deletes script
*
* @param scriptId script id
* @param userId user id
*/
public static void deleteScript(Long scriptId, Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("delete from scripts where id=? and user_id=?");
stmt.setLong(1, scriptId);
stmt.setLong(2, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
}
} |
Script script = null;
PreparedStatement stmt = con.prepareStatement("select * from scripts where id=? and user_id=?");
stmt.setLong(1, scriptId);
stmt.setLong(2, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
script = new Script();
script.setId(rs.getLong("id"));
script.setDisplayNm(rs.getString(DISPLAY_NM));
script.setScript(rs.getString("script"));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return script;
| 1,177 | 175 | 1,352 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/SystemStatusDB.java | SystemStatusDB | getNextPendingSystem | class SystemStatusDB {
public static final String STATUS_CD = "status_cd";
private SystemStatusDB() {
}
/**
* set the initial status for selected systems
*
* @param systemSelectIds systems ids to set initial status
* @param userId user id
* @param userType user type
*/
public static void setInitialSystemStatus(List<Long> systemSelectIds, Long userId, String userType) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
//checks perms if to see if in assigned profiles
if (!Auth.MANAGER.equals(userType)) {
systemSelectIds = SystemDB.checkSystemPerms(con, systemSelectIds, userId);
}
//deletes all old systems
deleteAllSystemStatus(con, userId);
for (Long hostSystemId : systemSelectIds) {
HostSystem hostSystem = new HostSystem();
hostSystem.setId(hostSystemId);
hostSystem.setStatusCd(HostSystem.INITIAL_STATUS);
//insert new status
insertSystemStatus(con, hostSystem, userId);
}
DBUtils.closeConn(con);
}
/**
* deletes all records from status table for user
*
* @param con DB connection object
* @param userId user id
*/
private static void deleteAllSystemStatus(Connection con, Long userId) throws SQLException {
PreparedStatement stmt = con.prepareStatement("delete from status where user_id=?");
stmt.setLong(1, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
}
/**
* inserts into the status table to keep track of key placement status
*
* @param con DB connection object
* @param hostSystem systems for authorized_keys replacement
* @param userId user id
*/
private static void insertSystemStatus(Connection con, HostSystem hostSystem, Long userId) throws SQLException {
PreparedStatement stmt = con.prepareStatement("insert into status (id, status_cd, user_id) values (?,?,?)");
stmt.setLong(1, hostSystem.getId());
stmt.setString(2, hostSystem.getStatusCd());
stmt.setLong(3, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
}
/**
* updates the status table to keep track of key placement status
*
* @param hostSystem systems for authorized_keys replacement
* @param userId user id
*/
public static void updateSystemStatus(HostSystem hostSystem, Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
updateSystemStatus(con, hostSystem, userId);
DBUtils.closeConn(con);
}
/**
* updates the status table to keep track of key placement status
*
* @param con DB connection
* @param hostSystem systems for authorized_keys replacement
* @param userId user id
*/
public static void updateSystemStatus(Connection con, HostSystem hostSystem, Long userId) throws SQLException {
PreparedStatement stmt = con.prepareStatement("update status set status_cd=? where id=? and user_id=?");
stmt.setString(1, hostSystem.getStatusCd());
stmt.setLong(2, hostSystem.getId());
stmt.setLong(3, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
}
/**
* returns all key placement statuses
*
* @param userId user id
*/
public static SortedSet getSortedSetStatus(Long userId) throws SQLException, GeneralSecurityException {
SortedSet sortedSet = new SortedSet();
sortedSet.setItemList(getAllSystemStatus(userId));
return sortedSet;
}
/**
* returns all key placement statuses
*
* @param userId user id
*/
public static List<HostSystem> getAllSystemStatus(Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
List<HostSystem> hostSystemList = getAllSystemStatus(con, userId);
DBUtils.closeConn(con);
return hostSystemList;
}
/**
* returns all key placement statuses
*
* @param con DB connection object
* @param userId user id
*/
private static List<HostSystem> getAllSystemStatus(Connection con, Long userId) throws SQLException {
List<HostSystem> hostSystemList = new ArrayList<>();
PreparedStatement stmt = con.prepareStatement("select * from status where user_id=? order by id asc");
stmt.setLong(1, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
HostSystem hostSystem = SystemDB.getSystem(con, rs.getLong("id"));
hostSystem.setStatusCd(rs.getString(STATUS_CD));
hostSystemList.add(hostSystem);
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return hostSystemList;
}
/**
* returns key placement status of system
*
* @param systemId system id
* @param userId user id
*/
public static HostSystem getSystemStatus(Long systemId, Long userId) throws SQLException, GeneralSecurityException {
HostSystem hostSystem = null;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("select * from status where id=? and user_id=?");
stmt.setLong(1, systemId);
stmt.setLong(2, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
hostSystem = SystemDB.getSystem(con, rs.getLong("id"));
hostSystem.setStatusCd(rs.getString(STATUS_CD));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
return hostSystem;
}
/**
* returns the first system that authorized keys has not been tried
*
* @param userId user id
* @return hostSystem systems for authorized_keys replacement
*/
public static HostSystem getNextPendingSystem(Long userId) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>}
} |
HostSystem hostSystem = null;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("select * from status where (status_cd like ? or status_cd like ? or status_cd like ?) and user_id=? order by id asc");
stmt.setString(1, HostSystem.INITIAL_STATUS);
stmt.setString(2, HostSystem.AUTH_FAIL_STATUS);
stmt.setString(3, HostSystem.PUBLIC_KEY_FAIL_STATUS);
stmt.setLong(4, userId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
hostSystem = SystemDB.getSystem(con, rs.getLong("id"));
hostSystem.setStatusCd(rs.getString(STATUS_CD));
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
return hostSystem;
| 1,683 | 255 | 1,938 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/UserProfileDB.java | UserProfileDB | checkIsUsersProfile | class UserProfileDB {
private UserProfileDB() {
}
/**
* sets users for profile
*
* @param profileId profile id
* @param userIdList list of user ids
*/
public static void setUsersForProfile(Long profileId, List<Long> userIdList) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("delete from user_map where profile_id=?");
stmt.setLong(1, profileId);
stmt.execute();
DBUtils.closeStmt(stmt);
for (Long userId : userIdList) {
stmt = con.prepareStatement("insert into user_map (profile_id, user_id) values (?,?)");
stmt.setLong(1, profileId);
stmt.setLong(2, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
}
//delete all unassigned keys by profile
PublicKeyDB.deleteUnassignedKeysByProfile(con, profileId);
DBUtils.closeConn(con);
}
/**
* return a list of profiles for user
*
* @param userId user id
* @return profile list
*/
public static List<Profile> getProfilesByUser(Long userId) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
List<Profile> profileList = getProfilesByUser(con, userId);
DBUtils.closeConn(con);
return profileList;
}
/**
* return a list of profiles for user
*
* @param userId user id
* @return profile list
*/
public static List<Profile> getProfilesByUser(Connection con, Long userId) throws SQLException {
ArrayList<Profile> profileList = new ArrayList<>();
PreparedStatement stmt = con.prepareStatement("select * from profiles g, user_map m where g.id=m.profile_id and m.user_id=? order by nm asc");
stmt.setLong(1, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Profile profile = new Profile();
profile.setId(rs.getLong("id"));
profile.setNm(rs.getString("nm"));
profile.setDesc(rs.getString("desc"));
profileList.add(profile);
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
return profileList;
}
/**
* checks to determine if user belongs to profile
*
* @param userId user id
* @param profileId profile id
* @return true if user belongs to profile
*/
public static boolean checkIsUsersProfile(Long userId, Long profileId) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>}
/**
* assigns profiles to given user
*
* @param userId user id
* @param allProfilesNmList list of all profiles
* @param assignedProfilesNmList list of assigned profiles
*/
public static void assignProfilesToUser(Connection con, Long userId, List<String> allProfilesNmList, List<String> assignedProfilesNmList) throws SQLException {
for (String profileNm : allProfilesNmList) {
if (StringUtils.isNotEmpty(profileNm)) {
Long profileId = null;
PreparedStatement stmt = con.prepareStatement("select id from profiles p where lower(p.nm) like ?");
stmt.setString(1, profileNm.toLowerCase());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
profileId = rs.getLong("id");
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
if (profileId != null) {
stmt = con.prepareStatement("delete from user_map where profile_id=?");
stmt.setLong(1, profileId);
stmt.execute();
DBUtils.closeStmt(stmt);
if (assignedProfilesNmList.contains(profileNm)) {
stmt = con.prepareStatement("insert into user_map (profile_id, user_id) values (?,?)");
stmt.setLong(1, profileId);
stmt.setLong(2, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
}
//delete all unassigned keys by profile
PublicKeyDB.deleteUnassignedKeysByProfile(con, profileId);
}
}
}
}
/**
* assigns profiles to given user
*
* @param userId user id
* @param profileNm profile name
*/
public static void assignProfileToUser(Connection con, Long userId, String profileNm) throws SQLException {
if (StringUtils.isNotEmpty(profileNm)) {
Long profileId = null;
PreparedStatement stmt = con.prepareStatement("select id from profiles p where lower(p.nm) like ?");
stmt.setString(1, profileNm.toLowerCase());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
profileId = rs.getLong("id");
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
if (profileId != null) {
stmt = con.prepareStatement("delete from user_map where profile_id=?");
stmt.setLong(1, profileId);
stmt.execute();
DBUtils.closeStmt(stmt);
stmt = con.prepareStatement("insert into user_map (profile_id, user_id) values (?,?)");
stmt.setLong(1, profileId);
stmt.setLong(2, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
//delete all unassigned keys by profile
PublicKeyDB.deleteUnassignedKeysByProfile(con, profileId);
}
}
}
} |
boolean isUsersProfile = false;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("select * from user_map where profile_id=? and user_id=?");
stmt.setLong(1, profileId);
stmt.setLong(2, userId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
isUsersProfile = true;
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
return isUsersProfile;
| 1,593 | 159 | 1,752 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/db/UserThemeDB.java | UserThemeDB | getTheme | class UserThemeDB {
private UserThemeDB() {
}
/**
* get user theme
*
* @param userId object
* @return user theme object
*/
public static UserSettings getTheme(Long userId) throws SQLException, GeneralSecurityException {<FILL_FUNCTION_BODY>}
/**
* saves user theme
*
* @param userId object
*/
public static void saveTheme(Long userId, UserSettings theme) throws SQLException, GeneralSecurityException {
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("delete from user_theme where user_id=?");
stmt.setLong(1, userId);
stmt.execute();
DBUtils.closeStmt(stmt);
if (StringUtils.isNotEmpty(theme.getPlane()) || StringUtils.isNotEmpty(theme.getTheme())) {
stmt = con.prepareStatement("insert into user_theme(user_id, bg, fg, d1, d2, d3, d4, d5, d6, d7, d8, b1, b2, b3, b4, b5, b6, b7, b8) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
stmt.setLong(1, userId);
stmt.setString(2, theme.getBg());
stmt.setString(3, theme.getFg());
//if contains all 16 theme colors insert
if (theme.getColors() != null && theme.getColors().length == 16) {
for (int i = 0; i < 16; i++) {
stmt.setString(i + 4, theme.getColors()[i]);
}
//else set to null
} else {
for (int i = 0; i < 16; i++) {
stmt.setString(i + 4, null);
}
}
stmt.execute();
DBUtils.closeStmt(stmt);
}
DBUtils.closeConn(con);
}
} |
UserSettings theme = null;
Connection con = DBUtils.getConn();
PreparedStatement stmt = con.prepareStatement("select * from user_theme where user_id=?");
stmt.setLong(1, userId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
theme = new UserSettings();
theme.setBg(rs.getString("bg"));
theme.setFg(rs.getString("fg"));
if (StringUtils.isNotEmpty(rs.getString("d1"))) {
String[] colors = new String[16];
colors[0] = rs.getString("d1");
colors[1] = rs.getString("d2");
colors[2] = rs.getString("d3");
colors[3] = rs.getString("d4");
colors[4] = rs.getString("d5");
colors[5] = rs.getString("d6");
colors[6] = rs.getString("d7");
colors[7] = rs.getString("d8");
colors[8] = rs.getString("b1");
colors[9] = rs.getString("b2");
colors[10] = rs.getString("b3");
colors[11] = rs.getString("b4");
colors[12] = rs.getString("b5");
colors[13] = rs.getString("b6");
colors[14] = rs.getString("b7");
colors[15] = rs.getString("b8");
theme.setColors(colors);
}
}
DBUtils.closeRs(rs);
DBUtils.closeStmt(stmt);
DBUtils.closeConn(con);
return theme;
| 541 | 456 | 997 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/model/SortedSet.java | SortedSet | getOrderByField | class SortedSet {
private String orderByField = null;
private String orderByDirection = "asc";
private List itemList;
private Map<String, String> filterMap = new HashMap<>();
public SortedSet() {
}
public SortedSet(String orderByField) {
this.orderByField = orderByField;
}
public String getOrderByField() {<FILL_FUNCTION_BODY>}
public void setOrderByField(String orderByField) {
this.orderByField = orderByField;
}
public String getOrderByDirection() {
if ("asc".equalsIgnoreCase(orderByDirection)) {
return "asc";
} else {
return "desc";
}
}
public void setOrderByDirection(String orderByDirection) {
this.orderByDirection = orderByDirection;
}
public List getItemList() {
return itemList;
}
public void setItemList(List itemList) {
this.itemList = itemList;
}
public Map<String, String> getFilterMap() {
return filterMap;
}
public void setFilterMap(Map<String, String> filterMap) {
this.filterMap = filterMap;
}
} |
if (orderByField != null) {
return orderByField.replaceAll("[^0-9,a-z,A-Z,\\_,\\.]", "");
}
return null;
| 334 | 55 | 389 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/model/UserSettings.java | UserSettings | setPlane | class UserSettings {
String[] colors = null;
String bg;
String fg;
String plane;
String theme;
Integer ptyWidth;
Integer ptyHeight;
public String[] getColors() {
return colors;
}
public void setColors(String[] colors) {
this.colors = colors;
}
public String getBg() {
return bg;
}
public void setBg(String bg) {
this.bg = bg;
}
public String getFg() {
return fg;
}
public void setFg(String fg) {
this.fg = fg;
}
public String getPlane() {
if (StringUtils.isNotEmpty(bg) && StringUtils.isNotEmpty(fg)) {
plane = bg + "," + fg;
}
return plane;
}
public void setPlane(String plane) {<FILL_FUNCTION_BODY>}
public String getTheme() {
if (this.colors != null && this.colors.length == 16) {
theme = StringUtils.join(this.colors, ",");
}
return theme;
}
public void setTheme(String theme) {
if (StringUtils.isNotEmpty(theme) && theme.split(",").length == 16) {
this.setColors(theme.split(","));
}
this.theme = theme;
}
public Integer getPtyWidth() {
return ptyWidth;
}
public void setPtyWidth(Integer ptyWidth) {
this.ptyWidth = ptyWidth;
}
public Integer getPtyHeight() {
return ptyHeight;
}
public void setPtyHeight(Integer ptyHeight) {
this.ptyHeight = ptyHeight;
}
} |
if (StringUtils.isNotEmpty(plane) && plane.split(",").length == 2) {
this.setBg(plane.split(",")[0]);
this.setFg(plane.split(",")[1]);
}
this.plane = plane;
| 494 | 73 | 567 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/task/SecureShellTask.java | SecureShellTask | run | class SecureShellTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger(SecureShellTask.class);
InputStream outFromChannel;
SessionOutput sessionOutput;
public SecureShellTask(SessionOutput sessionOutput, InputStream outFromChannel) {
this.sessionOutput = sessionOutput;
this.outFromChannel = outFromChannel;
}
public void run() {<FILL_FUNCTION_BODY>}
} |
InputStreamReader isr = new InputStreamReader(outFromChannel);
BufferedReader br = new BufferedReader(isr);
SessionOutputUtil.addOutput(sessionOutput);
char[] buff = new char[1024];
int read;
try {
while ((read = br.read(buff)) != -1) {
SessionOutputUtil.addToOutput(sessionOutput.getSessionId(), sessionOutput.getInstanceId(), buff, 0, read);
Thread.sleep(50);
}
SessionOutputUtil.removeOutput(sessionOutput.getSessionId(), sessionOutput.getInstanceId());
} catch (IOException | InterruptedException ex) {
log.error(ex.toString(), ex);
}
| 121 | 183 | 304 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/task/SentOutputTask.java | SentOutputTask | run | class SentOutputTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger(SentOutputTask.class);
Session session;
Long sessionId;
User user;
public SentOutputTask(Long sessionId, Session session, User user) {
this.sessionId = sessionId;
this.session = session;
this.user = user;
}
public void run() {<FILL_FUNCTION_BODY>}
} |
Gson gson = new Gson();
while (session.isOpen()) {
try {
Connection con = DBUtils.getConn();
List<SessionOutput> outputList = SessionOutputUtil.getOutput(con, sessionId, user);
if (!outputList.isEmpty()) {
String json = gson.toJson(outputList);
//send json to session
this.session.getBasicRemote().sendText(json);
}
Thread.sleep(25);
DBUtils.closeConn(con);
} catch (SQLException | GeneralSecurityException | IOException | InterruptedException ex) {
log.error(ex.toString(), ex);
}
}
| 120 | 171 | 291 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/DSPool.java | DSPool | registerDataSource | class DSPool {
private static BasicDataSource dsPool = null;
private static final String BASE_DIR = AppConfig.CONFIG_DIR;
private static final String DB_DRIVER = AppConfig.getProperty("dbDriver");
private static final int MAX_ACTIVE = Integer.parseInt(AppConfig.getProperty("maxActive"));
private static final boolean TEST_ON_BORROW = Boolean.parseBoolean(AppConfig.getProperty("testOnBorrow"));
private static final int MIN_IDLE = Integer.parseInt(AppConfig.getProperty("minIdle"));
private static final int MAX_WAIT = Integer.parseInt(AppConfig.getProperty("maxWait"));
private DSPool() {
}
/**
* fetches the data source for H2 db
*
* @return data source pool
*/
public static BasicDataSource getDataSource() throws GeneralSecurityException {
if (dsPool == null) {
dsPool = registerDataSource();
}
return dsPool;
}
/**
* register the data source for H2 DB
*
* @return pooling database object
*/
private static BasicDataSource registerDataSource() throws GeneralSecurityException {<FILL_FUNCTION_BODY>}
} |
System.setProperty("h2.baseDir", BASE_DIR);
// create a database connection
String user = AppConfig.getProperty("dbUser");
String password = AppConfig.decryptProperty("dbPassword");
String connectionURL = AppConfig.getProperty("dbConnectionURL");
if (connectionURL != null && connectionURL.contains("CIPHER=")) {
password = "filepwd " + password;
}
String validationQuery = "select 1";
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setMaxTotal(MAX_ACTIVE);
dataSource.setTestOnBorrow(TEST_ON_BORROW);
dataSource.setMinIdle(MIN_IDLE);
dataSource.setMaxWaitMillis(MAX_WAIT);
dataSource.setValidationQuery(validationQuery);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(connectionURL);
return dataSource;
| 320 | 269 | 589 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/EncryptionUtil.java | EncryptionUtil | encrypt | class EncryptionUtil {
private static final Logger log = LoggerFactory.getLogger(EncryptionUtil.class);
//secret key
private static byte[] key = new byte[0];
static {
try {
key = KeyStoreUtil.getSecretBytes(KeyStoreUtil.ENCRYPTION_KEY_ALIAS);
} catch (GeneralSecurityException ex) {
log.error(ex.toString(), ex);
}
}
public static final String CRYPT_ALGORITHM = "AES";
public static final String HASH_ALGORITHM = "SHA-256";
private EncryptionUtil() {
}
/**
* generate salt for hash
*
* @return salt
*/
public static String generateSalt() {
byte[] salt = new byte[32];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(salt);
return new String(Base64.encodeBase64(salt));
}
/**
* return hash value of string
*
* @param str unhashed string
* @param salt salt for hash
* @return hash value of string
*/
public static String hash(String str, String salt) throws NoSuchAlgorithmException {
String hash = null;
MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
if (StringUtils.isNotEmpty(salt)) {
md.update(Base64.decodeBase64(salt.getBytes()));
}
md.update(str.getBytes(StandardCharsets.UTF_8));
hash = new String(Base64.encodeBase64(md.digest()));
return hash;
}
/**
* return hash value of string
*
* @param str unhashed string
* @return hash value of string
*/
public static String hash(String str) throws NoSuchAlgorithmException {
return hash(str, null);
}
/**
* return encrypted value of string
*
* @param key secret key
* @param str unencrypted string
* @return encrypted string
*/
public static String encrypt(byte[] key, String str) throws GeneralSecurityException {<FILL_FUNCTION_BODY>}
/**
* return decrypted value of encrypted string
*
* @param key secret key
* @param str encrypted string
* @return decrypted string
*/
public static String decrypt(byte[] key, String str) throws GeneralSecurityException {
String retVal = null;
if (str != null && str.length() > 0) {
Cipher c = Cipher.getInstance(CRYPT_ALGORITHM);
c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM));
byte[] decodedVal = Base64.decodeBase64(str.getBytes());
retVal = new String(c.doFinal(decodedVal));
}
return retVal;
}
/**
* return encrypted value of string
*
* @param str unencrypted string
* @return encrypted string
*/
public static String encrypt(String str) throws GeneralSecurityException {
return encrypt(key, str);
}
/**
* return decrypted value of encrypted string
*
* @param str encrypted string
* @return decrypted string
*/
public static String decrypt(String str) throws GeneralSecurityException {
return decrypt(key, str);
}
} |
String retVal = null;
if (str != null && str.length() > 0) {
Cipher c = Cipher.getInstance(CRYPT_ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM));
byte[] encVal = c.doFinal(str.getBytes());
retVal = new String(Base64.encodeBase64(encVal));
}
return retVal;
| 912 | 131 | 1,043 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/KeyStoreUtil.java | KeyStoreUtil | initializeKeyStore | class KeyStoreUtil {
private static final Logger log = LoggerFactory.getLogger(KeyStoreUtil.class);
private static KeyStore keyStore = null;
private static final String keyStoreFile = AppConfig.CONFIG_DIR
+ "/bastillion.jceks";
private static final char[] KEYSTORE_PASS = new char[]{
'G', '~', 'r', 'x', 'Z', 'E', 'w', 'f', 'a', '[', '!', 'f', 'Z', 'd', '*', 'L', '8', 'm', 'h', 'u', '#',
'j', '9', ':', '~', ';', 'U', '>', 'O', 'i', '8', 'r', 'C', '}', 'f', 't', '%', '[', 'H', 'h', 'M', '&',
'K', ':', 'l', '5', 'c', 'H', '6', 'r', 'A', 'E', '.', 'F', 'Y', 'W', '}', '{', '*', '8', 'd', 'E', 'C',
'A', '6', 'F', 'm', 'j', 'u', 'A', 'Q', '%', '{', '/', '@', 'm', '&', '5', 'S', 'q', '4', 'Q', '+', 'Y',
'|', 'X', 'W', 'z', '8', '<', 'j', 'd', 'a', '}', '`', '0', 'N', 'B', '3', 'i', 'v', '5', 'U', ' ', '2',
'd', 'd', '(', '&', 'J', '_', '9', 'o', '(', '2', 'I', '`', ';', '>', '#', '$', 'X', 'j', '&', '&', '%',
'>', '#', '7', 'q', '>', ')', 'L', 'A', 'v', 'h', 'j', 'i', '8', '~', ')', 'a', '~', 'W', '/', 'l', 'H',
'L', 'R', '+', '\\', 'i', 'R', '_', '+', 'y', 's', '0', 'n', '\'', '=', '{', 'B', ':', 'l', '1', '%', '^',
'd', 'n', 'H', 'X', 'B', '$', 'f', '"', '#', ')', '{', 'L', '/', 'q', '\'', 'O', '%', 's', 'M', 'Q', ']',
'D', 'v', ';', 'L', 'C', 'd', '?', 'D', 'l', 'h', 'd', 'i', 'N', '4', 'R', '>', 'O', ';', '$', '(', '4',
'-', '0', '^', 'Y', ')', '5', 'V', 'M', '7', 'S', 'a', 'c', 'D', 'C', 'w', 'A', 'o', 'n', 's', 'r', '*',
'G', '[', 'l', 'h', '$', 'U', 's', '_', 'D', 'f', 'X', '~', '.', '7', 'B', 'A', 'E', '(', '#', ']', ':',
'`', ',', 'k', 'y'};
private static final int KEYLENGTH = 256;
//Alias for encryption keystore
public static final String ENCRYPTION_KEY_ALIAS = "KEYBOX-ENCRYPTION_KEY";
static {
File f = new File(keyStoreFile);
//load or create keystore
try {
if (f.isFile() && f.canRead()) {
keyStore = KeyStore.getInstance("JCEKS");
FileInputStream keyStoreInputStream = new FileInputStream(f);
keyStore.load(keyStoreInputStream, KEYSTORE_PASS);
}
//create keystore
else {
initializeKeyStore();
}
} catch (IOException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
}
}
/**
* get secret entry for alias
*
* @param alias keystore secret alias
* @return secret byte array
*/
public static byte[] getSecretBytes(String alias) throws GeneralSecurityException {
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(KEYSTORE_PASS));
return entry.getSecretKey().getEncoded();
}
/**
* get secret entry for alias
*
* @param alias keystore secret alias
* @return secret string
*/
public static String getSecretString(String alias) throws GeneralSecurityException {
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(KEYSTORE_PASS));
return new String(entry.getSecretKey().getEncoded());
}
/**
* set secret in keystore
*
* @param alias keystore secret alias
* @param secret keystore entry
*/
public static void setSecret(String alias, byte[] secret) throws KeyStoreException {
KeyStore.ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(KEYSTORE_PASS);
SecretKeySpec secretKey = new SecretKeySpec(secret, 0, secret.length, "AES");
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
keyStore.setEntry(alias, secretKeyEntry, protectionParameter);
}
/**
* set secret in keystore
*
* @param alias keystore secret alias
* @param secret keystore entry
*/
public static void setSecret(String alias, String secret) throws KeyStoreException {
setSecret(alias, secret.getBytes());
}
/**
* delete existing and create new keystore
*/
public static void resetKeyStore() throws IOException, GeneralSecurityException {
File file = new File(keyStoreFile);
if (file.exists()) {
FileUtils.forceDelete(file);
}
//create new keystore
initializeKeyStore();
}
/**
* create new keystore
*/
private static void initializeKeyStore() throws GeneralSecurityException, IOException {<FILL_FUNCTION_BODY>}
} |
keyStore = KeyStore.getInstance("JCEKS");
//create keystore
keyStore.load(null, KEYSTORE_PASS);
//set encryption key
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(KEYLENGTH);
KeyStoreUtil.setSecret(KeyStoreUtil.ENCRYPTION_KEY_ALIAS, keyGenerator.generateKey().getEncoded());
//write keystore
FileOutputStream fos = new FileOutputStream(keyStoreFile);
keyStore.store(fos, KEYSTORE_PASS);
fos.close();
| 1,649 | 152 | 1,801 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/OTPUtil.java | OTPUtil | verifyToken | class OTPUtil {
private static final Logger log = LoggerFactory.getLogger(OTPUtil.class);
//sizes to generate OTP secret
private static final int SECRET_SIZE = 10;
private static final int NUM_SCRATCH_CODES = 5;
private static final int SCRATCH_CODE_SIZE = 4;
//token window in near future or past
private static final int TOKEN_WINDOW = 3;
//interval for validation token change
private static final int CHANGE_INTERVAL = 30;
private OTPUtil() {
}
/**
* generates OPT secret
*
* @return String shared secret
*/
public static String generateSecret() {
byte[] buffer = new byte[(NUM_SCRATCH_CODES * SCRATCH_CODE_SIZE) + SECRET_SIZE];
new SecureRandom().nextBytes(buffer);
byte[] secret = Arrays.copyOf(buffer, SECRET_SIZE);
return new String(new Base32().encode(secret));
}
/**
* verifies code for OTP secret
*
* @param secret shared secret
* @param token verification token
* @return true if success
*/
public static boolean verifyToken(String secret, long token) {
//check token in near future or past
int window = TOKEN_WINDOW;
for (int i = window; i >= -window; i--) {
long time = (new Date().getTime() / TimeUnit.SECONDS.toMillis(CHANGE_INTERVAL)) + i;
if (verifyToken(secret, token, time)) {
return true;
}
}
return false;
}
/**
* verifies code for OTP secret per time interval
*
* @param secret shared secret
* @param token verification token
* @param time time representation to calculate OTP
* @return true if success
*/
private static boolean verifyToken(String secret, long token, long time) {<FILL_FUNCTION_BODY>}
} |
long calculated = -1;
byte[] key = new Base32().decode(secret);
SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1");
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array());
int offset = hash[hash.length - 1] & 0xF;
for (int i = 0; i < 4; ++i) {
calculated <<= 8;
calculated |= (hash[offset + i] & 0xFF);
}
calculated &= 0x7FFFFFFF;
calculated %= 1000000;
} catch (Exception ex) {
log.error(ex.toString(), ex);
}
return (calculated != -1 && calculated == token);
| 540 | 240 | 780 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/RefreshAuthKeyUtil.java | RefreshAllSystemsTask | run | class RefreshAllSystemsTask implements Runnable {
private static final Logger log = LoggerFactory.getLogger(RefreshAllSystemsTask.class);
@Override
public void run() {<FILL_FUNCTION_BODY>}
} |
//distribute all public keys
try {
SSHUtil.distributePubKeysToAllSystems();
} catch (SQLException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
}
| 65 | 59 | 124 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/SessionOutputSerializer.java | SessionOutputSerializer | serialize | class SessionOutputSerializer implements JsonSerializer<Object> {
@Override
public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {<FILL_FUNCTION_BODY>}
} |
JsonObject object = new JsonObject();
if (typeOfSrc.equals(AuditWrapper.class)) {
AuditWrapper auditWrapper = (AuditWrapper) src;
object.addProperty("user_id", auditWrapper.getUser().getId());
object.addProperty("username", auditWrapper.getUser().getUsername());
object.addProperty("user_type", auditWrapper.getUser().getUserType());
object.addProperty("first_nm", auditWrapper.getUser().getFirstNm());
object.addProperty("last_nm", auditWrapper.getUser().getLastNm());
object.addProperty("email", auditWrapper.getUser().getEmail());
object.addProperty("session_id", auditWrapper.getSessionOutput().getSessionId());
object.addProperty("instance_id", auditWrapper.getSessionOutput().getInstanceId());
object.addProperty("host_id", auditWrapper.getSessionOutput().getId());
object.addProperty("host", auditWrapper.getSessionOutput().getDisplayLabel());
object.addProperty("output", auditWrapper.getSessionOutput().getOutput().toString());
object.addProperty("timestamp", new Date().getTime());
}
return object;
| 54 | 296 | 350 | <no_super_class> |
bastillion-io_Bastillion | Bastillion/src/main/java/io/bastillion/manage/util/SessionOutputUtil.java | SessionOutputUtil | getOutput | class SessionOutputUtil {
private static final Map<Long, UserSessionsOutput> userSessionsOutputMap = new ConcurrentHashMap<>();
public final static boolean enableInternalAudit = "true".equals(AppConfig.getProperty("enableInternalAudit"));
private static final Gson gson = new GsonBuilder().registerTypeAdapter(AuditWrapper.class, new SessionOutputSerializer()).create();
private static final Logger systemAuditLogger = LoggerFactory.getLogger("io.bastillion.manage.util.SystemAudit");
private SessionOutputUtil() {
}
/**
* removes session for user session
*
* @param sessionId session id
*/
public static void removeUserSession(Long sessionId) {
UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId);
if (userSessionsOutput != null) {
userSessionsOutput.getSessionOutputMap().clear();
}
userSessionsOutputMap.remove(sessionId);
}
/**
* removes session output for host system
*
* @param sessionId session id
* @param instanceId id of host system instance
*/
public static void removeOutput(Long sessionId, Integer instanceId) {
UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId);
if (userSessionsOutput != null) {
userSessionsOutput.getSessionOutputMap().remove(instanceId);
}
}
/**
* adds a new output
*
* @param sessionOutput session output object
*/
public static void addOutput(SessionOutput sessionOutput) {
UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionOutput.getSessionId());
if (userSessionsOutput == null) {
userSessionsOutputMap.put(sessionOutput.getSessionId(), new UserSessionsOutput());
userSessionsOutput = userSessionsOutputMap.get(sessionOutput.getSessionId());
}
userSessionsOutput.getSessionOutputMap().put(sessionOutput.getInstanceId(), sessionOutput);
}
/**
* adds a new output
*
* @param sessionId session id
* @param instanceId id of host system instance
* @param value Array that is the source of characters
* @param offset The initial offset
* @param count The length
*/
public static void addToOutput(Long sessionId, Integer instanceId, char[] value, int offset, int count) {
UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId);
if (userSessionsOutput != null) {
userSessionsOutput.getSessionOutputMap().get(instanceId).getOutput().append(value, offset, count);
}
}
/**
* returns list of output lines
*
* @param sessionId session id object
* @param user user auth object
* @return session output list
*/
public static List<SessionOutput> getOutput(Connection con, Long sessionId, User user) throws SQLException {<FILL_FUNCTION_BODY>}
} |
List<SessionOutput> outputList = new ArrayList<>();
UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(sessionId);
if (userSessionsOutput != null) {
for (Integer key : userSessionsOutput.getSessionOutputMap().keySet()) {
//get output chars and set to output
SessionOutput sessionOutput = userSessionsOutput.getSessionOutputMap().get(key);
if (sessionOutput != null && sessionOutput.getOutput() != null
&& StringUtils.isNotEmpty(sessionOutput.getOutput())) {
outputList.add(sessionOutput);
//send to audit logger
systemAuditLogger.info(gson.toJson(new AuditWrapper(user, sessionOutput)));
if (enableInternalAudit) {
SessionAuditDB.insertTerminalLog(con, sessionOutput);
}
userSessionsOutput.getSessionOutputMap().put(key, new SessionOutput(sessionId, sessionOutput));
}
}
}
return outputList;
| 787 | 267 | 1,054 | <no_super_class> |
OpenHFT_Chronicle-Map | Chronicle-Map/src/main/java/net/openhft/chronicle/hash/impl/ChronicleHashCloseOnExitHook.java | ChronicleHashCloseOnExitHook | closeAll | class ChronicleHashCloseOnExitHook {
private static WeakHashMap<VanillaChronicleHash<?, ?, ?, ?>.Identity, Long> maps = new WeakHashMap<>();
private static long order = 0;
static {
PriorityHook.add(80, ChronicleHashCloseOnExitHook::closeAll);
}
private ChronicleHashCloseOnExitHook() {
}
static synchronized void add(VanillaChronicleHash<?, ?, ?, ?> hash) {
if (maps == null)
throw new IllegalStateException("Shutdown in progress");
maps.put(hash.identity, order++);
}
static synchronized void remove(VanillaChronicleHash<?, ?, ?, ?> hash) {
if (maps == null)
return; // we are already in shutdown
maps.remove(hash.identity);
}
private static void closeAll() {<FILL_FUNCTION_BODY>}
} |
try {
WeakHashMap<VanillaChronicleHash<?, ?, ?, ?>.Identity, Long> maps;
synchronized (ChronicleHashCloseOnExitHook.class) {
maps = ChronicleHashCloseOnExitHook.maps;
ChronicleHashCloseOnExitHook.maps = null;
}
TreeMap<Long, VanillaChronicleHash<?, ?, ?, ?>> orderedMaps = new TreeMap<>();
maps.forEach((identity, order) -> orderedMaps.put(order, identity.hash()));
// close later added maps first
orderedMaps.descendingMap().values().forEach(h -> {
try {
Runnable preShutdownAction = h.getPreShutdownAction();
if (preShutdownAction != null) {
try {
preShutdownAction.run();
} catch (Throwable throwable) {
try {
Jvm.error().on(ChronicleHashCloseOnExitHook.class,
"Error running pre-shutdown action for " + h.toIdentityString() +
" :", throwable);
} catch (Throwable t2) {
throwable.addSuppressed(t2);
throwable.printStackTrace();
}
}
}
h.close();
} catch (Throwable throwable) {
try {
Jvm.error().on(ChronicleHashCloseOnExitHook.class,
"Error while closing " + h.toIdentityString() +
" during shutdown hook:", throwable);
} catch (Throwable t2) {
// This may occur if the log service has already been shut down. Try to fall
// back to printStackTrace().
throwable.addSuppressed(t2);
throwable.printStackTrace();
}
}
});
} catch (Throwable throwable) {
try {
Jvm.error().on(ChronicleHashCloseOnExitHook.class,
"Error while closing maps during shutdown hook:", throwable);
} catch (Throwable t2) {
throwable.addSuppressed(t2);
throwable.printStackTrace();
}
}
| 250 | 541 | 791 | <no_super_class> |