proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
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); } }
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); }
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) { }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/JedisClusterCacheManager.java
JedisClusterCacheManager
mget
class JedisClusterCacheManager extends AbstractRedisCacheManager { private static final Logger log = LoggerFactory.getLogger(JedisClusterCacheManager.class); private final JedisClusterClient redis; public JedisClusterCacheManager(JedisCluster jedisCluster, ISerializer<Object> serializer) { super(serializer); this.redis = new JedisClusterClient(jedisCluster, this); } @Override protected IRedis getRedis() { return redis; } public static 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);
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(); }
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); } } }
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; }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-jedis/src/main/java/com/jarvis/cache/redis/ShardedJedisCacheManager.java
ShardedJedisCacheManager
delete
class ShardedJedisCacheManager extends AbstractRedisCacheManager { private final ShardedJedisPool shardedJedisPool; public ShardedJedisCacheManager(ShardedJedisPool shardedJedisPool, ISerializer<Object> serializer) { super(serializer); this.shardedJedisPool = shardedJedisPool; } @Override protected IRedis getRedis() { return new ShardedJedisClient(shardedJedisPool.getResource(), this); } public static 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();
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisCacheManager.java
LettuceRedisCacheManager
delete
class LettuceRedisCacheManager extends AbstractRedisCacheManager { private final RedisClient redisClient; private static final Logger log = LoggerFactory.getLogger(LettuceRedisCacheManager.class); public LettuceRedisCacheManager(RedisClient redisClient, ISerializer<Object> serializer) { super(serializer); this.redisClient = redisClient; } @Override protected IRedis getRedis() { StatefulRedisConnection<byte[], byte[]> connection = redisClient.connect(ByteArrayCodec.INSTANCE); return new LettuceRedisClient(connection, this); } public static 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(); }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-manager/autoload-cache-manager-lettuce/src/main/java/com/jarvis/cache/redis/LettuceRedisClusterCacheManager.java
LettuceRedisClusterCacheManager
delete
class LettuceRedisClusterCacheManager extends AbstractRedisCacheManager { private final RedisClusterClient redisClusterClient; private static final Logger log = LoggerFactory.getLogger(LettuceRedisClusterCacheManager.class); public LettuceRedisClusterCacheManager(RedisClusterClient redisClusterClient, ISerializer<Object> serializer) { super(serializer); this.redisClusterClient = redisClusterClient; } @Override protected IRedis getRedis() { StatefulRedisClusterConnection<byte[], byte[]> connection = redisClusterClient.connect(ByteArrayCodec.INSTANCE); return new LettuceRedisClusterClient(connection, this); } public static 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(); }
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;
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);
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(); }
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(); }
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;
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);
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);
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;
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;
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());
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;
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;
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); }
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(); }
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); }
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(); }
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); }
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-serializer/autoload-cache-serializer-jackson/src/main/java/com/jarvis/cache/serializer/JacksonJsonSerializer.java
JacksonJsonSerializer
deepCloneMethodArgs
class JacksonJsonSerializer implements ISerializer<Object> { private static final ObjectMapper MAPPER = new ObjectMapper(); public JacksonJsonSerializer() { // mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.registerModule( new SimpleModule().addSerializer(new JacksonJsonSerializer.NullValueSerializer((String) null))); MAPPER.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); } 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(); } } @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;
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();
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);
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;
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); }
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);
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;
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;
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;
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;
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;
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;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/autoconfigure/AutoloadCacheManageConfiguration.java
AutoloadCacheManageConfiguration
createRedisCacheManager
class AutoloadCacheManageConfiguration { private static final Logger log = LoggerFactory.getLogger(AutoloadCacheManageConfiguration.class); private static final boolean hessianPresent = ClassUtils.isPresent( "com.caucho.hessian.io.AbstractSerializerFactory", AutoloadCacheManageConfiguration.class.getClassLoader()); private static final boolean kryoPresent = ClassUtils.isPresent( "com.esotericsoftware.kryo.Kryo", AutoloadCacheManageConfiguration.class.getClassLoader()); /** * 表达式解析器{@link AbstractScriptParser AbstractScriptParser} 注入规则:<br> * 如果导入了Ognl的jar包,优先 使用Ognl表达式:{@link OgnlParser * OgnlParser},否则使用{@link SpringELParser SpringELParser}<br> * * @return */ @Bean @ConditionalOnMissingBean(AbstractScriptParser.class) public AbstractScriptParser autoloadCacheScriptParser() { return new SpringELParser(); } /** * * 序列化工具{@link ISerializer ISerializer} 注入规则:<br> * 如果导入了Hessian的jar包,优先使用Hessian:{@link HessianSerializer * HessianSerializer},否则使用{@link JdkSerializer JdkSerializer}<br> * * @return */ @Bean @ConditionalOnMissingBean(ISerializer.class) public ISerializer<Object> autoloadCacheSerializer() { ISerializer<Object> res; // 推荐优先使用:Hessian if (hessianPresent) { res = new HessianSerializer(); log.debug("HessianSerializer auto-configured"); } else if (kryoPresent) { res = new KryoSerializer(); log.debug("KryoSerializer auto-configured"); } else { res = new JdkSerializer(); log.debug("JdkSerializer auto-configured"); } return res; } @Configuration @ConditionalOnClass(Jedis.class) static class JedisCacheCacheManagerConfiguration { /** * 默认只支持{@link JedisClusterCacheManager}<br> * * @param config * @param serializer * @param connectionFactory * @return */ @Bean @ConditionalOnMissingBean(ICacheManager.class) @ConditionalOnBean(JedisConnectionFactory.class) public ICacheManager autoloadCacheCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer, JedisConnectionFactory connectionFactory) { return createRedisCacheManager(config, serializer, connectionFactory); } private ICacheManager createRedisCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer, JedisConnectionFactory connectionFactory) { RedisConnection redisConnection = null; try { redisConnection = connectionFactory.getConnection(); AbstractRedisCacheManager cacheManager = null; if (redisConnection instanceof JedisClusterConnection) { JedisClusterConnection redisClusterConnection = (JedisClusterConnection) redisConnection; // 优先使用JedisCluster; 因为JedisClusterConnection 批量处理,需要使用JedisCluster JedisCluster jedisCluster = redisClusterConnection.getNativeConnection(); cacheManager = new JedisClusterCacheManager(jedisCluster, serializer); } 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); } } } @Configuration @ConditionalOnClass(RedisClient.class) static 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); }
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); } } }
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;
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;
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();
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();
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;
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;
qiujiayu_AutoLoadCache
AutoLoadCache/autoload-cache-spring-boot-starter/src/main/java/com/jarvis/cache/redis/SpringRedisCacheManager.java
SpringRedisCacheManager
mget
class SpringRedisCacheManager extends AbstractRedisCacheManager { private static final Logger log = LoggerFactory.getLogger(SpringRedisCacheManager.class); private final RedisConnectionFactory redisConnectionFactory; public SpringRedisCacheManager(RedisConnectionFactory redisConnectionFactory, ISerializer<Object> serializer) { super(serializer); this.redisConnectionFactory = redisConnectionFactory; } @Override protected IRedis getRedis() { return new RedisConnectionClient(redisConnectionFactory, this); } public static 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); }
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;
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;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Audio.java
Audio
init
class Audio { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化 */ public Audio init() {<FILL_FUNCTION_BODY>} public AudioResponse transcriptions(File audio,Transcriptions transcriptions){ RequestBody a = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), audio); MultipartBody.Part aPart = MultipartBody.Part.createFormData("image", audio.getName(), a); Single<AudioResponse> audioResponse = this.apiClient.audioTranscriptions(aPart,transcriptions); return audioResponse.blockingGet(); } public AudioResponse translations(File audio,Transcriptions transcriptions){ RequestBody a = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), audio); MultipartBody.Part aPart = MultipartBody.Part.createFormData("image", audio.getName(), a); Single<AudioResponse> audioResponse = this.apiClient.audioTranslations(aPart,transcriptions); return audioResponse.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPT.java
ChatGPT
init
class ChatGPT { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化:与服务端建立连接,成功后可直接与服务端进行对话 */ public ChatGPT init() {<FILL_FUNCTION_BODY>} /** * 最新版的GPT-3.5 chat completion 更加贴近官方网站的问答模型 * * @param chatCompletion 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public ChatCompletionResponse chatCompletion(ChatCompletion chatCompletion) { Single<ChatCompletionResponse> chatCompletionResponse = this.apiClient.chatCompletion(chatCompletion); return chatCompletionResponse.blockingGet(); } /** * 支持多个问答参数来与服务端进行对话 * * @param messages 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public ChatCompletionResponse chatCompletion(List<Message> messages) { ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).build(); return this.chatCompletion(chatCompletion); } /** * 与服务端进行对话 * @param message 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public String chat(String message) { ChatCompletion chatCompletion = ChatCompletion.builder() .messages(Arrays.asList(Message.of(message))) .build(); ChatCompletionResponse response = this.chatCompletion(chatCompletion); return response.getChoices().get(0).getMessage().getContent(); } /** * 余额查询 * * @return 余额总金额及明细 */ public CreditGrantsResponse creditGrants() { Single<CreditGrantsResponse> creditGrants = this.apiClient.creditGrants(); return creditGrants.blockingGet(); } /** * 余额查询 * * @return 余额总金额 */ public BigDecimal balance() { Single<SubscriptionData> subscription = apiClient.subscription(); SubscriptionData subscriptionData = subscription.blockingGet(); BigDecimal total = subscriptionData.getHardLimitUsd(); DateTime start = DateUtil.offsetDay(new Date(), -90); DateTime end = DateUtil.offsetDay(new Date(), 1); Single<UseageResponse> usage = apiClient.usage(formatDate(start), formatDate(end)); UseageResponse useageResponse = usage.blockingGet(); BigDecimal used = useageResponse.getTotalUsage().divide(BigDecimal.valueOf(100)); return total.subtract(used); } /** * 新建连接进行余额查询 * * @return 余额总金额 */ public static BigDecimal balance(String key) { ChatGPT chatGPT = ChatGPT.builder() .apiKey(key) .build() .init(); return chatGPT.balance(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("ChatGPT init error!"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPTStream.java
ChatGPTStream
streamChatCompletion
class ChatGPTStream { private String apiKey; private List<String> apiKeyList; private OkHttpClient okHttpClient; /** * 连接超时 */ @Builder.Default private long timeout = 90; /** * 网络代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 反向代理 */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; /** * 初始化 */ public ChatGPTStream init() { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } okHttpClient = client.build(); return this; } /** * 流式输出 */ public void streamChatCompletion(ChatCompletion chatCompletion, EventSourceListener eventSourceListener) {<FILL_FUNCTION_BODY>} /** * 流式输出 */ public void streamChatCompletion(List<Message> messages, EventSourceListener eventSourceListener) { ChatCompletion chatCompletion = ChatCompletion.builder() .messages(messages) .stream(true) .build(); streamChatCompletion(chatCompletion, eventSourceListener); } }
chatCompletion.setStream(true); try { EventSource.Factory factory = EventSources.createFactory(okHttpClient); ObjectMapper mapper = new ObjectMapper(); String requestBody = mapper.writeValueAsString(chatCompletion); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = new Request.Builder() .url(apiHost + "v1/chat/completions") .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody)) .header("Authorization", "Bearer " + key) .build(); factory.newEventSource(request, eventSourceListener); } catch (Exception e) { log.error("请求出错:{}", e); }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ConsoleChatGPT.java
ConsoleChatGPT
main
class ConsoleChatGPT { public static Proxy proxy = Proxy.NO_PROXY; public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static BigDecimal getBalance(String key) { ChatGPT chatGPT = ChatGPT.builder() .apiKey(key) .proxy(proxy) .build() .init(); return chatGPT.balance(); } private static void check(String key) { if (key == null || key.isEmpty()) { throw new RuntimeException("请输入正确的KEY"); } } @SneakyThrows public static String getInput(String prompt) { System.out.print(prompt); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); List<String> lines = new ArrayList<>(); String line; try { while ((line = reader.readLine()) != null && !line.isEmpty()) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines.stream().collect(Collectors.joining("\n")); } }
System.out.println("ChatGPT - Java command-line interface"); System.out.println("Press enter twice to submit your question."); System.out.println(); System.out.println("按两次回车以提交您的问题!!!"); System.out.println("按两次回车以提交您的问题!!!"); System.out.println("按两次回车以提交您的问题!!!"); System.out.println(); System.out.println("Please enter APIKEY, press Enter twice to submit:"); String key = getInput("请输入APIKEY,按两次回车以提交:\n"); check(key); // 询问用户是否使用代理 国内需要代理 System.out.println("是否使用代理?(y/n): "); System.out.println("use proxy?(y/n): "); String useProxy = getInput("按两次回车以提交:\n"); if (useProxy.equalsIgnoreCase("y")) { // 输入代理地址 System.out.println("请输入代理类型(http/socks): "); String type = getInput("按两次回车以提交:\n"); // 输入代理地址 System.out.println("请输入代理IP: "); String proxyHost = getInput("按两次回车以提交:\n"); // 输入代理端口 System.out.println("请输入代理端口: "); String portStr = getInput("按两次回车以提交:\n"); Integer proxyPort = Integer.parseInt(portStr); if (type.equals("http")) { proxy = Proxys.http(proxyHost, proxyPort); } else { proxy = Proxys.socks5(proxyHost, proxyPort); } } // System.out.println("Inquiry balance..."); // System.out.println("查询余额中..."); // BigDecimal balance = getBalance(key); // System.out.println("API KEY balance: " + balance.toPlainString()); // // if (!NumberUtil.isGreater(balance, BigDecimal.ZERO)) { // System.out.println("API KEY 余额不足: "); // return; // } while (true) { String prompt = getInput("\nYou:\n"); ChatGPTStream chatGPT = ChatGPTStream.builder() .apiKey(key) .proxy(proxy) .build() .init(); System.out.println("AI: "); //卡住 CountDownLatch countDownLatch = new CountDownLatch(1); Message message = Message.of(prompt); ConsoleStreamListener listener = new ConsoleStreamListener() { @Override public void onError(Throwable throwable, String response) { throwable.printStackTrace(); countDownLatch.countDown(); } }; listener.setOnComplate(msg -> { countDownLatch.countDown(); }); chatGPT.streamChatCompletion(Arrays.asList(message), listener); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Embedding.java
Embedding
init
class Embedding { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; public Embedding init() {<FILL_FUNCTION_BODY>} /** * 生成向量 */ public EmbeddingResult createEmbeddings(EmbeddingRequest request) { Single<EmbeddingResult> embeddingResultSingle = this.apiClient.createEmbeddings(request); return embeddingResultSingle.blockingGet(); } /** * 生成向量 */ public EmbeddingResult createEmbeddings(String input, String user) { EmbeddingRequest request = EmbeddingRequest.builder() .input(Collections.singletonList(input)) .model(EmbeddingRequest.EmbeddingModelEnum.TEXT_EMBEDDING_ADA_002.getModelName()) .user(user) .build(); Single<EmbeddingResult> embeddingResultSingle = this.apiClient.createEmbeddings(request); return embeddingResultSingle.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } this.okHttpClient = client.build(); this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Images.java
Images
init
class Images { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化 */ public Images init() {<FILL_FUNCTION_BODY>} public ImagesRensponse generations(Generations generations){ Single<ImagesRensponse> imagesRensponse = this.apiClient.imageGenerations(generations); return imagesRensponse.blockingGet(); } public ImagesRensponse edits(File image,File mask,Edits edits){ RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image); MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i); RequestBody m = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), mask); MultipartBody.Part mPart = MultipartBody.Part.createFormData("mask", mask.getName(), m); Single<ImagesRensponse> imagesRensponse = this.apiClient.imageEdits(iPart,mPart,edits); return imagesRensponse.blockingGet(); } public ImagesRensponse variations(File image,Variations variations){ RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image); MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i); Single<ImagesRensponse> imagesRensponse = this.apiClient.imageVariations(iPart,variations); return imagesRensponse.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Test.java
Test
main
class Test { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
Proxy proxys = Proxys.http("127.0.0.1",10809); Images images = Images.builder() .proxy(proxys) .apiKey("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") .apiHost("https://api.openai.com/") .timeout(900) .build() .init(); File file = new File("C:\\Users\\马同徽\\Pictures\\微信图片_20230606140621.png"); Variations variations = Variations.ofURL(1,"256x256"); Generations generations = Generations.ofURL("一只鲨鱼和一直蜜蜂结合成一种动物",1,"256x256"); ImagesRensponse imagesRensponse = images.variations(file,variations); System.out.println(imagesRensponse.getCreated()); System.out.println(imagesRensponse.getCode()); System.out.println(imagesRensponse.getMsg()); List<Object> data = imagesRensponse.getData(); for(Object o:data){ System.out.println(o.toString()); } /*Audio audio = Audio.builder() .proxy(proxys) .apiKey("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") .apiHost("https://api.openai.com/") .timeout(900) .build() .init(); File file = new File("D:\\Jenny.mp3"); Transcriptions transcriptions = Transcriptions.of(file, AudioModel.WHISPER1.getValue()); AudioResponse response = audio.transcriptions(transcriptions); System.out.println(response.getText());*/
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/listener/AbstractStreamListener.java
AbstractStreamListener
onEvent
class AbstractStreamListener extends EventSourceListener { protected String lastMessage = ""; /** * Called when all new message are received. * * @param message the new message */ @Setter @Getter protected Consumer<String> onComplate = s -> { }; /** * Called when a new message is received. * 收到消息 单个字 * * @param message the new message */ public abstract void onMsg(String message); /** * Called when an error occurs. * 出错时调用 * * @param throwable the throwable that caused the error * @param response the response associated with the error, if any */ public abstract void onError(Throwable throwable, String response); @Override public void onOpen(EventSource eventSource, Response response) { // do nothing } @Override public void onClosed(EventSource eventSource) { // do nothing } @Override public void onEvent(EventSource eventSource, String id, String type, String data) {<FILL_FUNCTION_BODY>} @SneakyThrows @Override public void onFailure(EventSource eventSource, Throwable throwable, Response response) { try { log.error("Stream connection error: {}", throwable); String responseText = ""; if (Objects.nonNull(response)) { responseText = response.body().string(); } log.error("response:{}", responseText); String forbiddenText = "Your access was terminated due to violation of our policies"; if (StrUtil.contains(responseText, forbiddenText)) { log.error("Chat session has been terminated due to policy violation"); log.error("检测到号被封了"); } String overloadedText = "That model is currently overloaded with other requests."; if (StrUtil.contains(responseText, overloadedText)) { log.error("检测到官方超载了,赶紧优化你的代码,做重试吧"); } this.onError(throwable, responseText); } catch (Exception e) { log.warn("onFailure error:{}", e); // do nothing } finally { eventSource.cancel(); } } }
if (data.equals("[DONE]")) { onComplate.accept(lastMessage); return; } ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class); // 读取Json List<ChatChoice> choices = response.getChoices(); if (choices == null || choices.isEmpty()) { return; } Message delta = choices.get(0).getDelta(); String text = delta.getContent(); if (text != null) { lastMessage += text; onMsg(text); }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/ChatContextHolder.java
ChatContextHolder
add
class ChatContextHolder { private static Map<String, List<Message>> context = new HashMap<>(); /** * 获取对话历史 * * @param id * @return */ public static List<Message> get(String id) { List<Message> messages = context.get(id); if (messages == null) { messages = new ArrayList<>(); context.put(id, messages); } return messages; } /** * 添加对话 * * @param id * @return */ public static void add(String id, String msg) { Message message = Message.builder().content(msg).build(); add(id, message); } /** * 添加对话 * * @param id * @return */ public static void add(String id, Message message) {<FILL_FUNCTION_BODY>} /** * 清除对话 * @param id */ public static void remove(String id) { context.remove(id); } }
List<Message> messages = context.get(id); if (messages == null) { messages = new ArrayList<>(); context.put(id, messages); } messages.add(message);
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/SseHelper.java
SseHelper
complete
class SseHelper { public void complete(SseEmitter sseEmitter) {<FILL_FUNCTION_BODY>} public void send(SseEmitter sseEmitter, Object data) { try { sseEmitter.send(data); } catch (Exception e) { } } }
try { sseEmitter.complete(); } catch (Exception e) { }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/TokensUtil.java
TokensUtil
tokens
class TokensUtil { private static final Map<String, Encoding> modelEncodingMap = new HashMap<>(); private static final EncodingRegistry encodingRegistry = Encodings.newDefaultEncodingRegistry(); static { for (ChatCompletion.Model model : ChatCompletion.Model.values()) { Optional<Encoding> encodingForModel = encodingRegistry.getEncodingForModel(model.getName()); encodingForModel.ifPresent(encoding -> modelEncodingMap.put(model.getName(), encoding)); } } /** * 计算tokens * @param modelName 模型名称 * @param messages 消息列表 * @return 计算出的tokens数量 */ public static int tokens(String modelName, List<Message> messages) {<FILL_FUNCTION_BODY>} }
Encoding encoding = modelEncodingMap.get(modelName); if (encoding == null) { throw new IllegalArgumentException("Unsupported model: " + modelName); } int tokensPerMessage = 0; int tokensPerName = 0; if (modelName.startsWith("gpt-4")) { tokensPerMessage = 3; tokensPerName = 1; } else if (modelName.startsWith("gpt-3.5-turbo")) { tokensPerMessage = 4; // every message follows <|start|>{role/name}\n{content}<|end|>\n tokensPerName = -1; // if there's a name, the role is omitted } int sum = 0; for (Message message : messages) { sum += tokensPerMessage; sum += encoding.countTokens(message.getContent()); sum += encoding.countTokens(message.getRole()); if (StrUtil.isNotBlank(message.getName())) { sum += encoding.countTokens(message.getName()); sum += tokensPerName; } } sum += 3; return sum;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/async/ResultCallbackTemplate.java
ResultCallbackTemplate
onError
class ResultCallbackTemplate<RC_T extends ResultCallback<A_RES_T>, A_RES_T> implements ResultCallback<A_RES_T> { private static final Logger LOGGER = LoggerFactory.getLogger(ResultCallbackTemplate.class); private final CountDownLatch started = new CountDownLatch(1); private final CountDownLatch completed = new CountDownLatch(1); private Closeable stream; private boolean closed = false; private Throwable firstError = null; @Override public void onStart(Closeable stream) { this.stream = stream; this.closed = false; started.countDown(); } @Override public void onError(Throwable throwable) {<FILL_FUNCTION_BODY>} @Override public void onComplete() { try { close(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void close() throws IOException { if (!closed) { closed = true; try { if (stream != null) { stream.close(); } } finally { completed.countDown(); } } } /** * Blocks until {@link ResultCallback#onComplete()} was called */ @SuppressWarnings("unchecked") public RC_T awaitCompletion() throws InterruptedException { try { completed.await(); // eventually (re)throws RuntimeException throwFirstError(); return (RC_T) this; } finally { try { close(); } catch (IOException e) { LOGGER.debug("Failed to close", e); } } } /** * Blocks until {@link ResultCallback#onComplete()} was called or the given timeout occurs * @return {@code true} if completed and {@code false} if the waiting time elapsed * before {@link ResultCallback#onComplete()} was called. */ public boolean awaitCompletion(long timeout, TimeUnit timeUnit) throws InterruptedException { try { boolean result = completed.await(timeout, timeUnit); throwFirstError(); return result; } finally { try { close(); } catch (IOException e) { LOGGER.debug("Failed to close", e); } } } /** * Blocks until {@link ResultCallback#onStart(Closeable)} was called. * {@link ResultCallback#onStart(Closeable)} is called when the request was processed on the server * side and the response is incoming. */ @SuppressWarnings("unchecked") public RC_T awaitStarted() throws InterruptedException { started.await(); return (RC_T) this; } /** * Blocks until {@link ResultCallback#onStart(Closeable)} was called or the given timeout occurs. * {@link ResultCallback#onStart(Closeable)} is called when the request was processed on the server side * and the response is incoming. * @return {@code true} if started and {@code false} if the waiting time elapsed * before {@link ResultCallback#onStart(Closeable)} was called. */ public boolean awaitStarted(long timeout, TimeUnit timeUnit) throws InterruptedException { return started.await(timeout, timeUnit); } /** * Throws the first occurred error as a runtime exception * @throws com.github.dockerjava.api.exception.DockerException The first docker based Error * @throws RuntimeException on any other occurred error */ protected void throwFirstError() { if (firstError != null) { if (firstError instanceof Error) { throw (Error) firstError; } if (firstError instanceof RuntimeException) { throw (RuntimeException) firstError; } throw new RuntimeException(firstError); } } }
if (closed) return; if (this.firstError == null) { this.firstError = throwable; } try { LOGGER.error("Error during callback", throwable); } finally { try { close(); } catch (IOException e) { throw new RuntimeException(e); } }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/command/BuildImageResultCallback.java
BuildImageResultCallback
onNext
class BuildImageResultCallback extends ResultCallbackTemplate<BuildImageResultCallback, BuildResponseItem> { private static final Logger LOGGER = LoggerFactory.getLogger(BuildImageResultCallback.class); private String imageId; private String error; @Override public void onNext(BuildResponseItem item) {<FILL_FUNCTION_BODY>} /** * Awaits the image id from the response stream. * * @throws DockerClientException * if the build fails. */ public String awaitImageId() { try { awaitCompletion(); } catch (InterruptedException e) { throw new DockerClientException("", e); } return getImageId(); } /** * Awaits the image id from the response stream. * * @throws DockerClientException * if the build fails or the timeout occurs. */ public String awaitImageId(long timeout, TimeUnit timeUnit) { try { awaitCompletion(timeout, timeUnit); } catch (InterruptedException e) { throw new DockerClientException("Awaiting image id interrupted: ", e); } return getImageId(); } private String getImageId() { if (error != null) { throw new DockerClientException("Could not build image: " + error); } if (imageId != null) { return imageId; } throw new DockerClientException("Could not build image"); } }
if (item.isBuildSuccessIndicated()) { this.imageId = item.getImageId(); } else if (item.isErrorIndicated()) { this.error = item.getError(); } LOGGER.debug("{}", item);
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/command/LoadImageCallback.java
LoadImageCallback
onNext
class LoadImageCallback extends ResultCallbackTemplate<LoadImageCallback, LoadResponseItem> { private static final Logger LOGGER = LoggerFactory.getLogger(LoadImageCallback.class); private String message; private String error; @Override public void onNext(LoadResponseItem item) {<FILL_FUNCTION_BODY>} public String awaitMessage() { try { awaitCompletion(); } catch (InterruptedException e) { throw new DockerClientException("", e); } return getMessage(); } private String getMessage() { if (this.message != null) { return this.message; } if (this.error == null) { throw new DockerClientException("Could not build image"); } throw new DockerClientException("Could not build image: " + this.error); } }
if (item.isBuildSuccessIndicated()) { this.message = item.getMessage(); } else if (item.isErrorIndicated()) { this.error = item.getError(); } LOGGER.debug("{}", item);
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/command/PullImageResultCallback.java
PullImageResultCallback
onNext
class PullImageResultCallback extends ResultCallback.Adapter<PullResponseItem> { private static final Logger LOGGER = LoggerFactory.getLogger(PullImageResultCallback.class); private boolean isSwarm = false; private Map<String, PullResponseItem> results = null; @CheckForNull private PullResponseItem latestItem = null; @Override public void onNext(PullResponseItem item) {<FILL_FUNCTION_BODY>} private void checkForDockerSwarmResponse(PullResponseItem item) { if (item.getStatus().matches("Pulling\\s.+\\.{3}$")) { isSwarm = true; LOGGER.debug("Communicating with Docker Swarm."); } } private void handleDockerSwarmResponse(final PullResponseItem item) { if (results == null) { results = new HashMap<>(); } // Swarm terminates a pull sometimes with an empty line. // Therefore keep first success message PullResponseItem currentItem = results.get(item.getId()); if (currentItem == null || !currentItem.isPullSuccessIndicated()) { results.put(item.getId(), item); } } private void handleDockerClientResponse(PullResponseItem item) { latestItem = item; } private void checkDockerSwarmPullSuccessful() { if (results.isEmpty()) { throw new DockerClientException("Could not pull image through Docker Swarm"); } else { boolean pullFailed = false; StringBuilder sb = new StringBuilder(); for (PullResponseItem pullResponseItem : results.values()) { if (!pullResponseItem.isPullSuccessIndicated()) { pullFailed = true; sb.append("[" + pullResponseItem.getId() + ":" + messageFromPullResult(pullResponseItem) + "]"); } } if (pullFailed) { throw new DockerClientException("Could not pull image: " + sb.toString()); } } } private void checkDockerClientPullSuccessful() { if (latestItem == null) { return; } if (!latestItem.isPullSuccessIndicated()) { throw new DockerClientException("Could not pull image: " + messageFromPullResult(latestItem)); } } private String messageFromPullResult(PullResponseItem pullResponseItem) { return (pullResponseItem.getError() != null) ? pullResponseItem.getError() : pullResponseItem.getStatus(); } @Override protected void throwFirstError() { super.throwFirstError(); if (isSwarm) { checkDockerSwarmPullSuccessful(); } else { checkDockerClientPullSuccessful(); } } }
// only do it once if (results == null && latestItem == null) { checkForDockerSwarmResponse(item); } if (isSwarm) { handleDockerSwarmResponse(item); } else { handleDockerClientResponse(item); } LOGGER.debug("{}", item);
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/command/WaitContainerResultCallback.java
WaitContainerResultCallback
awaitStatusCode
class WaitContainerResultCallback extends ResultCallbackTemplate<WaitContainerResultCallback, WaitResponse> { private static final Logger LOGGER = LoggerFactory.getLogger(WaitContainerResultCallback.class); @CheckForNull private WaitResponse waitResponse = null; @Override public void onNext(WaitResponse waitResponse) { this.waitResponse = waitResponse; LOGGER.debug("{}", waitResponse); } /** * Awaits the status code from the container. * * @throws DockerClientException * if the wait operation fails. */ public Integer awaitStatusCode() { try { awaitCompletion(); } catch (InterruptedException e) { throw new DockerClientException("", e); } return getStatusCode(); } /** * Awaits the status code from the container. * * @throws DockerClientException * if the wait operation fails. */ public Integer awaitStatusCode(long timeout, TimeUnit timeUnit) {<FILL_FUNCTION_BODY>} private Integer getStatusCode() { if (waitResponse == null) { throw new DockerClientException("Error while wait container"); } else { return waitResponse.getStatusCode(); } } }
try { if (!awaitCompletion(timeout, timeUnit)) { throw new DockerClientException("Awaiting status code timeout."); } } catch (InterruptedException e) { throw new DockerClientException("Awaiting status code interrupted: ", e); } return getStatusCode();
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Bind.java
Bind
parse
class Bind extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; private String path; private Volume volume; private AccessMode accessMode; /** * @since {@link com.github.dockerjava.core.RemoteApiVersion#VERSION_1_23} */ private Boolean noCopy; /** * @since {@link com.github.dockerjava.core.RemoteApiVersion#VERSION_1_17} */ private SELContext secMode; /** * @since {@link com.github.dockerjava.core.RemoteApiVersion#VERSION_1_22} */ private PropagationMode propagationMode; public Bind(String path, Volume volume) { this(path, volume, AccessMode.DEFAULT, SELContext.DEFAULT); } public Bind(String path, Volume volume, Boolean noCopy) { this(path, volume, AccessMode.DEFAULT, SELContext.DEFAULT, noCopy); } public Bind(String path, Volume volume, AccessMode accessMode) { this(path, volume, accessMode, SELContext.DEFAULT); } public Bind(String path, Volume volume, AccessMode accessMode, SELContext secMode) { this(path, volume, accessMode, secMode, null); } public Bind(String path, Volume volume, AccessMode accessMode, SELContext secMode, Boolean noCopy) { this(path, volume, accessMode, secMode, noCopy, PropagationMode.DEFAULT_MODE); } public Bind(String path, Volume volume, AccessMode accessMode, SELContext secMode, Boolean noCopy, PropagationMode propagationMode) { this.path = path; this.volume = volume; this.accessMode = accessMode; this.secMode = secMode; this.noCopy = noCopy; this.propagationMode = propagationMode; } public String getPath() { return path; } public Volume getVolume() { return volume; } public AccessMode getAccessMode() { return accessMode; } public SELContext getSecMode() { return secMode; } public Boolean getNoCopy() { return noCopy; } public PropagationMode getPropagationMode() { return propagationMode; } /** * Parses a bind mount specification to a {@link Bind}. * * @param serialized * the specification, e.g. <code>/host:/container:ro</code> * @return a {@link Bind} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ public static Bind parse(String serialized) {<FILL_FUNCTION_BODY>} /** * Returns a string representation of this {@link Bind} suitable for inclusion in a JSON message. * The format is <code>&lt;host path&gt;:&lt;container path&gt;:&lt;access mode&gt;</code>, * like the argument in {@link #parse(String)}. * * @return a string representation of this {@link Bind} */ @Override public String toString() { return String.format("%s:%s:%s%s%s%s", path, volume.getPath(), accessMode.toString(), secMode != SELContext.none ? "," + secMode.toString() : "", noCopy != null ? ",nocopy" : "", propagationMode != PropagationMode.DEFAULT_MODE ? "," + propagationMode.toString() : ""); } }
try { // Split by ':' but not ':\' (Windows-style path) String[] parts = serialized.split(":(?!\\\\)"); switch (parts.length) { case 2: { return new Bind(parts[0], new Volume(parts[1])); } case 3: { String[] flags = parts[2].split(","); AccessMode accessMode = AccessMode.DEFAULT; SELContext seMode = SELContext.DEFAULT; Boolean nocopy = null; PropagationMode propagationMode = PropagationMode.DEFAULT_MODE; for (String p : flags) { if (p.length() == 2) { accessMode = AccessMode.valueOf(p.toLowerCase()); } else if ("nocopy".equals(p)) { nocopy = true; } else if (PropagationMode.SHARED.toString().equals(p)) { propagationMode = PropagationMode.SHARED; } else if (PropagationMode.SLAVE.toString().equals(p)) { propagationMode = PropagationMode.SLAVE; } else if (PropagationMode.PRIVATE.toString().equals(p)) { propagationMode = PropagationMode.PRIVATE; } else { seMode = SELContext.fromString(p); } } return new Bind(parts[0], new Volume(parts[1]), accessMode, seMode, nocopy, propagationMode); } default: { throw new IllegalArgumentException(); } } } catch (Exception e) { throw new IllegalArgumentException("Error parsing Bind '" + serialized + "'", e); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/BuildResponseItem.java
BuildResponseItem
getImageId
class BuildResponseItem extends ResponseItem { private static final long serialVersionUID = -1252904184236343612L; private static final String BUILD_SUCCESS = "Successfully built"; private static final String SHA256 = "sha256:"; /** * Returns whether the stream field indicates a successful build operation */ @JsonIgnore public boolean isBuildSuccessIndicated() { if (isErrorIndicated() || getStream() == null) { return false; } return getStream().contains(BUILD_SUCCESS) || getStream().startsWith(SHA256); } @JsonIgnore public String getImageId() {<FILL_FUNCTION_BODY>} }
if (!isBuildSuccessIndicated()) { return null; } if (getStream().startsWith(SHA256)) { return getStream().replaceFirst(SHA256, "").trim(); } return getStream().replaceFirst(BUILD_SUCCESS, "").trim();
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Device.java
Device
parse
class Device extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("CgroupPermissions") private String cGroupPermissions = ""; @JsonProperty("PathOnHost") private String pathOnHost = null; @JsonProperty("PathInContainer") private String pathInContainer = null; public Device() { } public Device(String cGroupPermissions, String pathInContainer, String pathOnHost) { requireNonNull(cGroupPermissions, "cGroupPermissions is null"); requireNonNull(pathInContainer, "pathInContainer is null"); requireNonNull(pathOnHost, "pathOnHost is null"); this.cGroupPermissions = cGroupPermissions; this.pathInContainer = pathInContainer; this.pathOnHost = pathOnHost; } public String getcGroupPermissions() { return cGroupPermissions; } public String getPathInContainer() { return pathInContainer; } public String getPathOnHost() { return pathOnHost; } /** * @link https://github.com/docker/docker/blob/6b4a46f28266031ce1a1315f17fb69113a06efe1/runconfig/opts/parse_test.go#L468 */ @Nonnull public static Device parse(@Nonnull String deviceStr) {<FILL_FUNCTION_BODY>} /** * ValidDeviceMode checks if the mode for device is valid or not. * Valid mode is a composition of r (read), w (write), and m (mknod). * * @link https://github.com/docker/docker/blob/6b4a46f28266031ce1a1315f17fb69113a06efe1/runconfig/opts/parse.go#L796 */ private static boolean validDeviceMode(String deviceMode) { Map<String, Boolean> validModes = new HashMap<>(3); validModes.put("r", true); validModes.put("w", true); validModes.put("m", true); if (deviceMode == null || deviceMode.length() == 0) { return false; } for (char ch : deviceMode.toCharArray()) { final String mode = String.valueOf(ch); if (!Boolean.TRUE.equals(validModes.get(mode))) { return false; // wrong mode } validModes.put(mode, false); } return true; } }
String src = ""; String dst = ""; String permissions = "rwm"; final String[] arr = deviceStr.trim().split(":"); // java String.split() returns wrong length, use tokenizer instead switch (new StringTokenizer(deviceStr, ":").countTokens()) { case 3: { // Mismatches docker code logic. While there is no validations after parsing, checking heregit if (validDeviceMode(arr[2])) { permissions = arr[2]; } else { throw new IllegalArgumentException("Invalid device specification: " + deviceStr); } } case 2: { if (validDeviceMode(arr[1])) { permissions = arr[1]; } else { dst = arr[1]; } } case 1: { src = arr[0]; break; } default: { throw new IllegalArgumentException("Invalid device specification: " + deviceStr); } } if (dst == null || dst.length() == 0) { dst = src; } return new Device(permissions, dst, src);
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/DockerObjectAccessor.java
DockerObjectAccessor
overrideRawValues
class DockerObjectAccessor { /** * @deprecated not for public usage, unless you _really_ understand what you're doing */ @Deprecated public static void overrideRawValues(DockerObject o, HashMap<String, Object> rawValues) {<FILL_FUNCTION_BODY>} /** * This is an advanced method for setting raw values on the resulting object * that will fully overwrite any previously set value for given key. * * Make sure to check Docker's API before using it. */ public static void overrideRawValue(DockerObject o, String key, Object value) { o.rawValues.put(key, value); } private DockerObjectAccessor() { } }
o.rawValues = rawValues != null ? rawValues : new HashMap<>();
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/ExposedPort.java
ExposedPort
parse
class ExposedPort implements Serializable { private static final long serialVersionUID = 1L; private final InternetProtocol protocol; private final int port; /** * Creates an {@link ExposedPort} for the given parameters. * * @param port * the {@link #getPort() port number} * @param protocol * the {@link InternetProtocol} */ public ExposedPort(int port, InternetProtocol protocol) { this.port = port; this.protocol = protocol; } /** * Creates an {@link ExposedPort} for the given {@link #getPort() port number} and {@link InternetProtocol#DEFAULT}. * * @param port * the {@link #getPort() port number} */ public ExposedPort(int port) { this(port, InternetProtocol.DEFAULT); } /** * Creates an {@link ExposedPort} for the given parameters. * * @param scheme * the {@link #getScheme() scheme}, <code>tcp</code>, <code>udp</code> or <code>sctp</code> * @param port * the {@link #getPort() port number} * @deprecated use {@link #ExposedPort(int, InternetProtocol)} */ @Deprecated public ExposedPort(String scheme, int port) { this(port, InternetProtocol.valueOf(scheme)); } /** * @return the {@link InternetProtocol} of the {@link #getPort() port} that the container exposes */ public InternetProtocol getProtocol() { return protocol; } /** * @return the scheme (internet protocol), <code>tcp</code>, <code>udp</code> or <code>sctp</code> * @deprecated use {@link #getProtocol()} */ @Deprecated public String getScheme() { return protocol.toString(); } /** @return the port number that the container exposes */ public int getPort() { return port; } /** * Creates an {@link ExposedPort} for {@link InternetProtocol#TCP}. This is a shortcut for * <code>new ExposedPort(port, {@link InternetProtocol#TCP})</code> */ public static ExposedPort tcp(int port) { return new ExposedPort(port, TCP); } /** * Creates an {@link ExposedPort} for {@link InternetProtocol#UDP}. This is a shortcut for * <code>new ExposedPort(port, {@link InternetProtocol#UDP})</code> */ public static ExposedPort udp(int port) { return new ExposedPort(port, UDP); } /** * Creates an {@link ExposedPort} for {@link InternetProtocol#SCTP}. This is a shortcut for * <code>new ExposedPort(port, {@link InternetProtocol#SCTP})</code> */ public static ExposedPort sctp(int port) { return new ExposedPort(port, SCTP); } /** * Parses a textual port specification (as used by the Docker CLI) to an {@link ExposedPort}. * * @param serialized * the specification, e.g. <code>80/tcp</code> * @return an {@link ExposedPort} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ @JsonCreator public static ExposedPort parse(String serialized) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} /** * Returns a string representation of this {@link ExposedPort} suitable for inclusion in a JSON message. The format is * <code>port/protocol</code>, like the argument in {@link #parse(String)}. * * @return a string representation of this {@link ExposedPort} */ @Override @JsonValue public String toString() { return port + "/" + protocol.toString(); } }
try { String[] parts = serialized.split("/"); switch (parts.length) { case 1: return new ExposedPort(Integer.parseInt(parts[0])); case 2: return new ExposedPort(Integer.parseInt(parts[0]), InternetProtocol.parse(parts[1])); default: throw new IllegalArgumentException(); } } catch (Exception e) { throw new IllegalArgumentException("Error parsing ExposedPort '" + serialized + "'"); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/ExposedPorts.java
ExposedPorts
toPrimitive
class ExposedPorts implements Serializable { private static final long serialVersionUID = 1L; private ExposedPort[] exposedPorts; public ExposedPorts(ExposedPort... exposedPorts) { this.exposedPorts = exposedPorts; } public ExposedPorts(List<ExposedPort> exposedPorts) { this.exposedPorts = exposedPorts.toArray(new ExposedPort[exposedPorts.size()]); } public ExposedPort[] getExposedPorts() { return exposedPorts; } @JsonCreator public static ExposedPorts fromPrimitive(Map<String, Object> object) { return new ExposedPorts( object.keySet().stream().map(ExposedPort::parse).toArray(ExposedPort[]::new) ); } @JsonValue public Map<String, Object> toPrimitive() {<FILL_FUNCTION_BODY>} }
return Stream.of(exposedPorts).collect(Collectors.toMap( ExposedPort::toString, __ -> new Object(), (a, b) -> a ));
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Identifier.java
Identifier
fromCompoundString
class Identifier extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; public final Repository repository; public final Optional<String> tag; public Identifier(Repository repository, String tag) { this.repository = repository; this.tag = Optional.ofNullable(tag); } /** * Return an identifier that correctly splits up the repository and tag. There can be &gt; 1 ":" fred/jim --&gt; fred/jim, [] * fred/jim:123 --&gt; fred/jim, 123 fred:123/jim:123 --&gt; fred:123/jim, 123 * * * @param identifier * as a string * @return parsed identifier. */ public static Identifier fromCompoundString(String identifier) {<FILL_FUNCTION_BODY>} }
String[] parts = identifier.split("/"); if (parts.length != 2) { String[] rhs = identifier.split(":"); if (rhs.length != 2) { return new Identifier(new Repository(identifier), null); } else { return new Identifier(new Repository(rhs[0]), rhs[1]); } } String[] rhs = parts[1].split(":"); if (rhs.length != 2) { return new Identifier(new Repository(identifier), null); } return new Identifier(new Repository(parts[0] + "/" + rhs[0]), rhs[1]);
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Link.java
Link
parse
class Link extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; private final String name; private final String alias; /** * Creates a {@link Link} for the container with the given name and an aliased name for use in the target container. * * @param name * the name of the container that you want to link into the target container * @param alias * the aliased name under which the linked container will be available in the target container */ public Link(final String name, final String alias) { this.name = name; this.alias = alias; } /** * @return the name of the container that is linked into the target container */ public String getName() { return name; } /** * @return the aliased name under which the linked container will be available in the target container */ public String getAlias() { return alias; } /** * Parses a textual link specification (as used by the Docker CLI) to a {@link Link}. * * @param serialized * the specification, e.g. <code>name:alias</code> or <code>/name1:/name2/alias</code> * @return a {@link Link} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ public static Link parse(final String serialized) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} /** * Returns a string representation of this {@link Link} suitable for inclusion in a JSON message. The format is <code>name:alias</code>, * like the argument in {@link #parse(String)}. * * @return a string representation of this {@link Link} */ @Override public String toString() { return name + ":" + alias; } }
try { final String[] parts = serialized.split(":"); switch (parts.length) { case 2: { String[] nameSplit = parts[0].split("/"); String[] aliasSplit = parts[1].split("/"); return new Link(nameSplit[nameSplit.length - 1], aliasSplit[aliasSplit.length - 1]); } default: { throw new IllegalArgumentException(); } } } catch (final Exception e) { throw new IllegalArgumentException("Error parsing Link '" + serialized + "'"); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/LoadResponseItem.java
LoadResponseItem
getMessage
class LoadResponseItem extends ResponseItem { private static final long serialVersionUID = 1L; private static final String IMPORT_SUCCESS = "Loaded image:"; /** * Returns whether the stream field indicates a successful build operation */ @JsonIgnore public boolean isBuildSuccessIndicated() { if (isErrorIndicated() || getStream() == null) { return false; } return getStream().contains(IMPORT_SUCCESS); } @JsonIgnore public String getMessage() {<FILL_FUNCTION_BODY>} }
if (!isBuildSuccessIndicated()) { return null; } else if (getStream().contains(IMPORT_SUCCESS)) { return getStream(); } return null;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/LogConfig.java
LogConfig
fromValue
class LogConfig extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("Type") public LoggingType type = null; @JsonProperty("Config") public Map<String, String> config; public LogConfig(LoggingType type, Map<String, String> config) { this.type = type; this.config = config; } public LogConfig(LoggingType type) { this(type, null); } public LogConfig() { } public LoggingType getType() { return type; } public LogConfig setType(LoggingType type) { this.type = type; return this; } @JsonIgnore public Map<String, String> getConfig() { return config; } @JsonIgnore public LogConfig setConfig(Map<String, String> config) { this.config = config; return this; } public enum LoggingType { NONE("none"), DEFAULT("json-file"), LOCAL("local"), ETWLOGS("etwlogs"), JSON_FILE("json-file"), SYSLOG("syslog"), JOURNALD("journald"), GELF("gelf"), FLUENTD("fluentd"), AWSLOGS("awslogs"), DB("db"), // Synology specific driver SPLUNK("splunk"), GCPLOGS("gcplogs"), LOKI("loki"); private String type; LoggingType(String type) { this.type = type; } @JsonValue public String getType() { return type; } @JsonCreator @CheckForNull public static LoggingType fromValue(String text) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.valueOf(type); } } }
for (LoggingType b : LoggingType.values()) { if (String.valueOf(b.type).equals(text)) { return b; } } return null;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Mount.java
Mount
withBindOptions
class Mount extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; /** * @since 1.24 */ @JsonProperty("Type") private MountType type; /** * @since 1.24 */ @JsonProperty("Source") private String source; /** * @since 1.24 */ @JsonProperty("Target") private String target; /** * @since 1.24 */ @JsonProperty("ReadOnly") private Boolean readOnly; /** * @since 1.24 */ @JsonProperty("BindOptions") private BindOptions bindOptions; /** * @since 1.24 */ @JsonProperty("VolumeOptions") private VolumeOptions volumeOptions; /** * @since 1.29 */ @JsonProperty("TmpfsOptions") private TmpfsOptions tmpfsOptions; /** * @see #type */ @CheckForNull public MountType getType() { return type; } /** * @see #type */ public Mount withType(MountType type) { this.type = type; return this; } /** * @see #source */ @CheckForNull public String getSource() { return source; } /** * @see #source */ public Mount withSource(String source) { this.source = source; return this; } /** * @see #target */ @CheckForNull public String getTarget() { return target; } /** * @see #target */ public Mount withTarget(String target) { this.target = target; return this; } /** * @see #readOnly */ @CheckForNull public Boolean getReadOnly() { return readOnly; } /** * @see #readOnly */ public Mount withReadOnly(Boolean readOnly) { this.readOnly = readOnly; return this; } /** * @see #bindOptions */ @CheckForNull public BindOptions getBindOptions() { return bindOptions; } /** * @see #bindOptions */ public Mount withBindOptions(BindOptions bindOptions) {<FILL_FUNCTION_BODY>} /** * @see #volumeOptions */ @CheckForNull public VolumeOptions getVolumeOptions() { return volumeOptions; } /** * @see #volumeOptions */ public Mount withVolumeOptions(VolumeOptions volumeOptions) { this.volumeOptions = volumeOptions; if (volumeOptions != null) { this.type = MountType.VOLUME; } return this; } /** * @see #tmpfsOptions */ @CheckForNull public TmpfsOptions getTmpfsOptions() { return tmpfsOptions; } /** * @see #tmpfsOptions */ public Mount withTmpfsOptions(TmpfsOptions tmpfsOptions) { this.tmpfsOptions = tmpfsOptions; if (tmpfsOptions != null) { this.type = MountType.TMPFS; } return this; } }
this.bindOptions = bindOptions; if (bindOptions != null) { this.type = MountType.BIND; } return this;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/PortBinding.java
PortBinding
parse
class PortBinding extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; private final Binding binding; private final ExposedPort exposedPort; public PortBinding(Binding binding, ExposedPort exposedPort) { this.binding = binding; this.exposedPort = exposedPort; } public Binding getBinding() { return binding; } public ExposedPort getExposedPort() { return exposedPort; } public static PortBinding parse(String serialized) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} private static PortBinding createFromSubstrings(String binding, String exposedPort) throws IllegalArgumentException { return new PortBinding(Binding.parse(binding), ExposedPort.parse(exposedPort)); } }
try { String[] parts = serialized.split(":"); switch (parts.length) { case 3: // 127.0.0.1:80:8080/tcp return createFromSubstrings(parts[0] + ":" + parts[1], parts[2]); case 2: // 80:8080 // 127.0.0.1::8080 return createFromSubstrings(parts[0], parts[1]); case 1: // 8080 return createFromSubstrings("", parts[0]); default: throw new IllegalArgumentException(); } } catch (Exception e) { throw new IllegalArgumentException("Error parsing PortBinding '" + serialized + "'", e); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Ports.java
Ports
parse
class Ports implements Serializable { private static final long serialVersionUID = 1L; private final Map<ExposedPort, Binding[]> ports = new HashMap<>(); /** * Creates a {@link Ports} object with no {@link PortBinding}s. Use {@link #bind(ExposedPort, Binding)} or {@link #add(PortBinding...)} * to add {@link PortBinding}s. */ public Ports() { } /** * Creates a {@link Ports} object with an initial {@link PortBinding} for the specified {@link ExposedPort} and {@link Binding}. Use * {@link #bind(ExposedPort, Binding)} or {@link #add(PortBinding...)} to add more {@link PortBinding}s. */ public Ports(ExposedPort exposedPort, Binding host) { bind(exposedPort, host); } public Ports(PortBinding... portBindings) { add(portBindings); } /** * Adds a new {@link PortBinding} for the specified {@link ExposedPort} and {@link Binding} to the current bindings. */ public void bind(ExposedPort exposedPort, Binding binding) { if (ports.containsKey(exposedPort)) { Binding[] bindings = ports.get(exposedPort); Binding[] newBindings = new Binding[bindings.length + 1]; System.arraycopy(bindings, 0, newBindings, 0, bindings.length); newBindings[newBindings.length - 1] = binding; ports.put(exposedPort, newBindings); } else { if (binding == null) { ports.put(exposedPort, null); } else { ports.put(exposedPort, new Binding[] {binding}); } } } /** * Adds the specified {@link PortBinding}(s) to the list of {@link PortBinding}s. */ public void add(PortBinding... portBindings) { for (PortBinding binding : portBindings) { bind(binding.getExposedPort(), binding.getBinding()); } } @Override public String toString() { return ports.toString(); } /** * Returns the port bindings in the format used by the Docker remote API, i.e. the {@link Binding}s grouped by {@link ExposedPort}. * * @return the port bindings as a {@link Map} that contains one or more {@link Binding}s per {@link ExposedPort}. */ public Map<ExposedPort, Binding[]> getBindings() { return ports; } // public PortBinding[] getBindingsAsArray() { // List<PortBinding> bindings = new ArrayList<>(); // for(Map.Entry<ExposedPort, Ports.Binding[]> entry: ports.entrySet()) { // for(Ports.Binding binding : entry.getValue()) { // bindings.add(new PortBinding(binding, entry.getKey())); // } // } // return bindings.toArray(new PortBinding[bindings.size()]); // } /** * A {@link Binding} represents a socket on the Docker host that is used in a {@link PortBinding}. It is characterized by an * {@link #getHostIp() IP address} and a {@link #getHostPortSpec() port spec}. Both properties may be <code>null</code> in order to * let Docker assign them dynamically/using defaults. * * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort */ @EqualsAndHashCode public static class Binding extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; /** * Creates a {@link Binding} for the given {@link #getHostPortSpec() port spec}, leaving the {@link #getHostIp() IP address} * undefined. * * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort */ public static Binding bindPortSpec(String portSpec) { return new Binding(null, portSpec); } /** * Creates a {@link Binding} for the given {@link #getHostIp() IP address}, leaving the {@link #getHostPortSpec() port spec} * undefined. */ public static Binding bindIp(String hostIp) { return new Binding(hostIp, null); } /** * Creates a {@link Binding} for the given {@link #getHostIp() IP address} and port number. */ public static Binding bindIpAndPort(String hostIp, int port) { return new Binding(hostIp, "" + port); } /** * Creates a {@link Binding} for the given {@link #getHostIp() IP address} and port range. */ public static Binding bindIpAndPortRange(String hostIp, int lowPort, int highPort) { return new Binding(hostIp, lowPort + "-" + highPort); } /** * Creates a {@link Binding} for the given port range, leaving the {@link #getHostIp() IP address} * undefined. */ public static Binding bindPortRange(int lowPort, int highPort) { return bindIpAndPortRange(null, lowPort, highPort); } /** * Creates a {@link Binding} for the given port leaving the {@link #getHostIp() IP address} * undefined. */ public static Binding bindPort(int port) { return bindIpAndPort(null, port); } /** * Creates an empty {@link Binding}. */ public static Binding empty() { return new Binding(null, null); } private final String hostIp; private final String hostPortSpec; /** * Creates a {@link Binding} for the given {@link #getHostIp() host IP address} and {@link #getHostPortSpec() host port spec}. * * @see Ports#bind(ExposedPort, Binding) * @see ExposedPort */ public Binding(String hostIp, String hostPortSpec) { this.hostIp = hostIp == null || hostIp.length() == 0 ? null : hostIp; this.hostPortSpec = hostPortSpec; } /** * @return the IP address on the Docker host. May be <code>null</code>, in which case Docker will bind the port to all interfaces ( * <code>0.0.0.0</code>). */ public String getHostIp() { return hostIp; } /** * @return the port spec for the binding on the Docker host. May reference a single port ("1234"), a port range ("1234-2345") or * <code>null</code>, in which case Docker will dynamically assign a port. */ public String getHostPortSpec() { return hostPortSpec; } /** * Parses a textual host and port specification (as used by the Docker CLI) to a {@link Binding}. * <p> * Legal syntax: <code>IP|IP:portSpec|portSpec</code> where <code>portSpec</code> is either a single port or a port range * * @param serialized * serialized the specification, e.g. <code>127.0.0.1:80</code> * @return a {@link Binding} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ public static Binding parse(String serialized) throws IllegalArgumentException {<FILL_FUNCTION_BODY>} /** * Returns a string representation of this {@link Binding} suitable for inclusion in a JSON message. The format is * <code>[IP:]Port</code>, like the argument in {@link #parse(String)}. * * @return a string representation of this {@link Binding} */ @Override public String toString() { if (hostIp == null || hostIp.length() == 0) { return hostPortSpec; } else if (hostPortSpec == null) { return hostIp; } else { return hostIp + ":" + hostPortSpec; } } } @JsonCreator public static Ports fromPrimitive(Map<String, List<Map<String, String>>> map) { Ports out = new Ports(); for (Entry<String, List<Map<String, String>>> entry : map.entrySet()) { ExposedPort exposedPort = ExposedPort.parse(entry.getKey()); if (entry.getValue() == null) { out.bind(exposedPort, null); } else { for (Map<String, String> binding : entry.getValue()) { out.bind(exposedPort, new Binding(binding.get("HostIp"), binding.get("HostPort"))); } } } return out; } @JsonValue public Map<String, List<Map<String, String>>> toPrimitive() { // Use reduce-like collect to be able to put nulls into the values return ports.entrySet().stream().collect( HashMap::new, (map, entry) -> { List<Map<String, String>> value = entry.getValue() == null ? null : Stream.of(entry.getValue()) .map(binding -> { Map<String, String> result = new HashMap<>(); result.put("HostIp", binding.getHostIp() == null ? "" : binding.getHostIp()); result.put("HostPort", binding.getHostPortSpec() == null ? "" : binding.getHostPortSpec()); return result; }) .collect(Collectors.toList()); map.put(entry.getKey().toString(), value); }, HashMap::putAll ); } }
try { if (serialized.isEmpty()) { return Binding.empty(); } String[] parts = serialized.split(":"); switch (parts.length) { case 2: { return new Binding(parts[0], parts[1]); } case 1: { return parts[0].contains(".") ? Binding.bindIp(parts[0]) : Binding.bindPortSpec(parts[0]); } default: { throw new IllegalArgumentException(); } } } catch (Exception e) { throw new IllegalArgumentException("Error parsing Binding '" + serialized + "'"); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/PullResponseItem.java
PullResponseItem
isPullSuccessIndicated
class PullResponseItem extends ResponseItem { private static final long serialVersionUID = -2575482839766823293L; private static final String LEGACY_REGISTRY = "this image was pulled from a legacy registry"; private static final String DOWNLOADED_NEWER_IMAGE = "Downloaded newer image"; private static final String IMAGE_UP_TO_DATE = "Image is up to date"; private static final String DOWNLOAD_COMPLETE = "Download complete"; private static final String DOWNLOADED_SWARM = ": downloaded"; /** * Returns whether the status indicates a successful pull operation * * @returns true: status indicates that pull was successful, false: status doesn't indicate a successful pull */ @JsonIgnore public boolean isPullSuccessIndicated() {<FILL_FUNCTION_BODY>} }
if (isErrorIndicated() || getStatus() == null) { return false; } return (getStatus().contains(DOWNLOAD_COMPLETE) || getStatus().contains(IMAGE_UP_TO_DATE) || getStatus().contains(DOWNLOADED_NEWER_IMAGE) || getStatus().contains(LEGACY_REGISTRY) || getStatus().contains(DOWNLOADED_SWARM) );
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Repository.java
Repository
getPath
class Repository extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; public final String name; /** * Name may be eg. 'busybox' or '10.0.0.1:5000/fred' * * @param name * Repository name */ public Repository(String name) { this.name = name; } /** * Return the URL portion (repository). Note that this might not actually BE a repository location. * * @return * @throws java.net.MalformedURLException */ public URL getURL() throws MalformedURLException { return new URL("http://" + name); } public String getPath() {<FILL_FUNCTION_BODY>} }
if (!name.contains("/")) { return name; } return name.substring(name.indexOf("/") + 1);
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/ResponseItem.java
ResponseItem
isErrorIndicated
class ResponseItem extends DockerObject implements Serializable { private static final long serialVersionUID = -5187169652557467828L; @JsonProperty("stream") private String stream; @JsonProperty("status") private String status; @JsonProperty("progressDetail") private ProgressDetail progressDetail; @Deprecated @JsonProperty("progress") private String progress; @JsonProperty("id") private String id; @JsonProperty("from") private String from; @JsonProperty("time") private Long time; @JsonProperty("errorDetail") private ErrorDetail errorDetail; @Deprecated @JsonProperty("error") private String error; /** * @since {@link RemoteApiVersion#VERSION_1_22} */ @JsonProperty("aux") private AuxDetail aux; @CheckForNull public String getStream() { return stream; } @CheckForNull public String getStatus() { return status; } @CheckForNull public ProgressDetail getProgressDetail() { return progressDetail; } @CheckForNull @Deprecated public String getProgress() { return progress; } @CheckForNull public String getId() { return id; } @CheckForNull public String getFrom() { return from; } @CheckForNull public Long getTime() { return time; } @CheckForNull public ErrorDetail getErrorDetail() { return errorDetail; } @Deprecated public String getError() { return error; } /** * @see #aux */ @CheckForNull public AuxDetail getAux() { return aux; } /** * Returns whether the error field indicates an error * * @returns true: the error field indicates an error, false: the error field doesn't indicate an error */ @JsonIgnore public boolean isErrorIndicated() {<FILL_FUNCTION_BODY>} @EqualsAndHashCode @ToString public static class ProgressDetail extends DockerObject implements Serializable { private static final long serialVersionUID = -1954994695645715264L; @JsonProperty("current") Long current; @JsonProperty("total") Long total; @JsonProperty("start") Long start; @CheckForNull public Long getCurrent() { return current; } @CheckForNull public Long getTotal() { return total; } @CheckForNull public Long getStart() { return start; } } @EqualsAndHashCode @ToString public static class ErrorDetail extends DockerObject implements Serializable { private static final long serialVersionUID = -9136704865403084083L; @JsonProperty("code") Integer code; @JsonProperty("message") String message; @CheckForNull public Integer getCode() { return code; } @CheckForNull public String getMessage() { return message; } } @EqualsAndHashCode @ToString public static class AuxDetail extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("Size") private Integer size; @JsonProperty("Tag") private String tag; @JsonProperty("Digest") private String digest; @CheckForNull public Integer getSize() { return size; } @CheckForNull public String getTag() { return tag; } @CheckForNull public String getDigest() { return digest; } } }
// check both the deprecated and current error fields, just in case return getError() != null || getErrorDetail() != null;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/RestartPolicy.java
RestartPolicy
toString
class RestartPolicy extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("MaximumRetryCount") private Integer maximumRetryCount = 0; @JsonProperty("Name") private String name = ""; public RestartPolicy() { } private RestartPolicy(int maximumRetryCount, String name) { requireNonNull(name, "name is null"); this.maximumRetryCount = maximumRetryCount; this.name = name; } /** * Do not restart the container if it dies. (default) */ public static RestartPolicy noRestart() { return new RestartPolicy(); } /** * Always restart the container no matter what exit code is returned. */ public static RestartPolicy alwaysRestart() { return new RestartPolicy(0, "always"); } /** * Restart the container if it exits with a non-zero exit code. * * @param maximumRetryCount * the maximum number of restarts. Set to <code>0</code> for unlimited retries. */ public static RestartPolicy onFailureRestart(int maximumRetryCount) { return new RestartPolicy(maximumRetryCount, "on-failure"); } /** * Restart the container unless it has been stopped */ public static RestartPolicy unlessStoppedRestart() { return new RestartPolicy(0, "unless-stopped"); } public Integer getMaximumRetryCount() { return maximumRetryCount; } public String getName() { return name; } /** * Parses a textual restart polixy specification (as used by the Docker CLI) to a {@link RestartPolicy}. * * @param serialized * the specification, e.g. <code>on-failure:2</code> * @return a {@link RestartPolicy} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ public static RestartPolicy parse(String serialized) throws IllegalArgumentException { try { String[] parts = serialized.split(":"); String name = parts[0]; if ("no".equals(name)) { return noRestart(); } if ("always".equals(name)) { return alwaysRestart(); } if ("unless-stopped".equals(name)) { return unlessStoppedRestart(); } if ("on-failure".equals(name)) { int count = 0; if (parts.length == 2) { count = Integer.parseInt(parts[1]); } return onFailureRestart(count); } throw new IllegalArgumentException(); } catch (Exception e) { throw new IllegalArgumentException("Error parsing RestartPolicy '" + serialized + "'"); } } /** * Returns a string representation of this {@link RestartPolicy}. The format is <code>name[:count]</code>, like the argument in * {@link #parse(String)}. * * @return a string representation of this {@link RestartPolicy} */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
String result = name.isEmpty() ? "no" : name; return maximumRetryCount > 0 ? result + ":" + maximumRetryCount : result;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/ServiceModeConfig.java
ServiceModeConfig
withReplicated
class ServiceModeConfig extends DockerObject implements Serializable { public static final long serialVersionUID = 1L; /** * @since 1.24 */ @JsonProperty("Replicated") private ServiceReplicatedModeOptions replicated; /** * @since 1.24 */ @JsonProperty("Global") private ServiceGlobalModeOptions global; /** * @since 1.24 */ @CheckForNull public ServiceMode getMode() { if (replicated != null) { return ServiceMode.REPLICATED; } if (global != null) { return ServiceMode.GLOBAL; } return null; } /** * @since 1.24 */ @CheckForNull public ServiceReplicatedModeOptions getReplicated() { return replicated; } /** * @since 1.24 */ public ServiceModeConfig withReplicated(ServiceReplicatedModeOptions replicated) {<FILL_FUNCTION_BODY>} /** * @since 1.24 */ @CheckForNull public ServiceGlobalModeOptions getGlobal() { return global; } /** * @since 1.24 */ public ServiceModeConfig withGlobal(ServiceGlobalModeOptions global) { if (global != null && this.replicated != null) { throw new IllegalStateException("Cannot set both global and replicated mode"); } this.global = global; return this; } }
if (replicated != null && this.global != null) { throw new IllegalStateException("Cannot set both replicated and global mode"); } this.replicated = replicated; return this;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/ServicePlacement.java
ServicePlacement
withMaxReplicas
class ServicePlacement extends DockerObject implements Serializable { public static final long serialVersionUID = 1L; /** * @since 1.24 */ @JsonProperty("Constraints") private List<String> constraints; /** * @since 1.30 */ @JsonProperty("Platforms") private List<SwarmNodePlatform> platforms; /** * @since 1.40 */ @JsonProperty("MaxReplicas") private Integer maxReplicas; /** * @see #constraints */ @CheckForNull public List<String> getConstraints() { return constraints; } /** * @see #constraints */ public ServicePlacement withConstraints(List<String> constraints) { this.constraints = constraints; return this; } /** * @see #platforms */ public List<SwarmNodePlatform> getPlatforms() { return platforms; } public void setPlatforms(List<SwarmNodePlatform> platforms) { this.platforms = platforms; } /** * Specifies the maximum amount of replicas / tasks that can run on one node. * 0 means unlimited replicas per node. * * @param maxReplicas Max number of replicas * @return This instance of ServicePlacement * @throws IllegalArgumentException if maxReplicas is less than 0 */ public ServicePlacement withMaxReplicas(int maxReplicas) {<FILL_FUNCTION_BODY>} /** * Getter for maxReplicas * * @return The maximum amount of replicas / tasks that can run on one node. */ public Integer getMaxReplicas() { return this.maxReplicas; } }
if (maxReplicas < 0) { throw new IllegalArgumentException("The Value for MaxReplicas must be greater or equal to 0"); } this.maxReplicas = maxReplicas; return this;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/Task.java
Task
toIndentedString
class Task extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("ID") private String id = null; @JsonProperty("Version") private ObjectVersion version = null; @JsonProperty("CreatedAt") private String createdAt = null; @JsonProperty("UpdatedAt") private String updatedAt = null; @JsonProperty("Name") private String name = null; @JsonProperty("Labels") private Map<String, String> labels = null; @JsonProperty("Spec") private TaskSpec spec = null; @JsonProperty("ServiceID") private String serviceId = null; @JsonProperty("Slot") private Integer slot = null; @JsonProperty("NodeID") private String nodeId = null; @JsonProperty("AssignedGenericResources") private List<GenericResource> assignedGenericResources = null; @JsonProperty("Status") private TaskStatus status = null; @JsonProperty("DesiredState") private TaskState desiredState = null; /** * The ID of the task. * * @return ID **/ public String getId() { return id; } /** * Get version * * @return version **/ public ObjectVersion getVersion() { return version; } /** * Get createdAt * * @return createdAt **/ public String getCreatedAt() { return createdAt; } /** * Get updatedAt * * @return updatedAt **/ public String getUpdatedAt() { return updatedAt; } /** * Name of the task. * * @return name **/ public String getName() { return name; } /** * User-defined key/value metadata. * * @return labels **/ public Map<String, String> getLabels() { return labels; } /** * Get spec * * @return spec **/ public TaskSpec getSpec() { return spec; } /** * Get status * * @return status **/ public TaskStatus getStatus() { return status; } /** * Get desiredState * * @return desiredState **/ public TaskState getDesiredState() { return desiredState; } /** * The ID of the service this task is part of. * * @return serviceId **/ public String getServiceId() { return serviceId; } /** * Get slot * * @return slot **/ public Integer getSlot() { return slot; } /** * The ID of the node that this task is on. * * @return nodeId **/ public String getNodeId() { return nodeId; } public Task withId(String id) { this.id = id; return this; } public Task withVersion(ObjectVersion version) { this.version = version; return this; } public Task withCreatedAt(String createdAt) { this.createdAt = createdAt; return this; } public Task withUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; return this; } public Task withName(String name) { this.name = name; return this; } public Task withLabels(Map<String, String> labels) { this.labels = labels; return this; } public Task withSpec(TaskSpec spec) { this.spec = spec; return this; } public Task withServiceId(String serviceId) { this.serviceId = serviceId; return this; } public Task withSlot(Integer slot) { this.slot = slot; return this; } public Task withNodeId(String nodeId) { this.nodeId = nodeId; return this; } public Task withAssignedGenericResources(List<GenericResource> assignedGenericResources) { this.assignedGenericResources = assignedGenericResources; return this; } public Task withStatus(TaskStatus status) { this.status = status; return this; } public Task withDesiredState(TaskState desiredState) { this.desiredState = desiredState; return this; } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) {<FILL_FUNCTION_BODY>} }
if (o == null) { return "null"; } return o.toString().replace("\n", "\n ");
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/TaskStatusContainerStatus.java
TaskStatusContainerStatus
withPid
class TaskStatusContainerStatus extends DockerObject implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("ContainerID") private String containerID = null; @JsonProperty("PID") private Long pid = null; @JsonProperty("ExitCode") private Long exitCode = null; public String getContainerID() { return containerID; } /** * * @deprecated use {@link #getPidLong()} */ @Deprecated public Integer getPid() { return pid != null ? pid.intValue() : null; } public Long getPidLong() { return pid; } /** * @deprecated use {@link #getExitCodeLong()} */ @Deprecated public Integer getExitCode() { return exitCode != null ? exitCode.intValue() : null; } public Long getExitCodeLong() { return exitCode; } public TaskStatusContainerStatus withContainerID(String containerID) { this.containerID = containerID; return this; } public TaskStatusContainerStatus withPid(Long pid) { this.pid = pid; return this; } /** * * @deprecated use {@link #withPid(Long)} */ @Deprecated public TaskStatusContainerStatus withPid(Integer pid) {<FILL_FUNCTION_BODY>} public TaskStatusContainerStatus withExitCode(Long exitCode) { this.exitCode = exitCode; return this; } /** * * @deprecated use {@link #withExitCode(Long)} */ @Deprecated public TaskStatusContainerStatus withExitCode(Integer exitCode) { this.exitCode = exitCode != null ? exitCode.longValue() : null; return this; } }
this.pid = pid != null ? pid.longValue() : null; return this;
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumeBinds.java
VolumeBinds
fromPrimitive
class VolumeBinds implements Serializable { private static final long serialVersionUID = 1L; private final VolumeBind[] binds; public VolumeBinds(VolumeBind... binds) { this.binds = binds; } public VolumeBind[] getBinds() { return binds; } @JsonCreator public static VolumeBinds fromPrimitive(Map<String, String> primitive) {<FILL_FUNCTION_BODY>} @JsonValue public Map<String, String> toPrimitive() { return Stream.of(binds).collect(Collectors.toMap( VolumeBind::getContainerPath, VolumeBind::getHostPath )); } }
return new VolumeBinds( primitive.entrySet().stream() .map(it -> new VolumeBind(it.getValue(), it.getKey())) .toArray(VolumeBind[]::new) );
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumeRW.java
VolumeRW
fromPrimitive
class VolumeRW implements Serializable { private static final long serialVersionUID = 1L; private Volume volume; private AccessMode accessMode = AccessMode.rw; public VolumeRW(Volume volume) { this.volume = volume; } public VolumeRW(Volume volume, AccessMode accessMode) { this.volume = volume; this.accessMode = accessMode; } public Volume getVolume() { return volume; } public AccessMode getAccessMode() { return accessMode; } /** * Returns a string representation of this {@link VolumeRW} suitable for inclusion in a JSON message. The returned String is simply the * container path, {@link #getPath()}. * * @return a string representation of this {@link VolumeRW} */ @Override public String toString() { return getVolume() + ":" + getAccessMode(); } @JsonCreator public static VolumeRW fromPrimitive(Map<String, Boolean> map) {<FILL_FUNCTION_BODY>} @JsonValue public Map<String, Boolean> toPrimitive() { return Collections.singletonMap(volume.getPath(), accessMode.toBoolean()); } }
Entry<String, Boolean> entry = map.entrySet().iterator().next(); return new VolumeRW(new Volume(entry.getKey()), AccessMode.fromBoolean(entry.getValue()));
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumesFrom.java
VolumesFrom
parse
class VolumesFrom implements Serializable { private static final long serialVersionUID = 1L; private String container; private AccessMode accessMode; public VolumesFrom(String container) { this(container, AccessMode.DEFAULT); } public VolumesFrom(String container, AccessMode accessMode) { this.container = container; this.accessMode = accessMode; } public String getContainer() { return container; } public AccessMode getAccessMode() { return accessMode; } /** * Parses a volume from specification to a {@link VolumesFrom}. * * @param serialized * the specification, e.g. <code>container:ro</code> * @return a {@link VolumesFrom} matching the specification * @throws IllegalArgumentException * if the specification cannot be parsed */ @JsonCreator public static VolumesFrom parse(String serialized) {<FILL_FUNCTION_BODY>} /** * Returns a string representation of this {@link VolumesFrom} suitable for inclusion in a JSON message. The format is * <code>&lt;container&gt;:&lt;access mode&gt;</code>, like the argument in {@link #parse(String)}. * * @return a string representation of this {@link VolumesFrom} */ @Override @JsonValue public String toString() { return container + ":" + accessMode.toString(); } }
try { String[] parts = serialized.split(":"); switch (parts.length) { case 1: { return new VolumesFrom(parts[0]); } case 2: { return new VolumesFrom(parts[0], AccessMode.valueOf(parts[1])); } default: { throw new IllegalArgumentException(); } } } catch (Exception e) { throw new IllegalArgumentException("Error parsing Bind '" + serialized + "'"); }
docker-java_docker-java
docker-java/docker-java-api/src/main/java/com/github/dockerjava/api/model/VolumesRW.java
VolumesRW
toPrimitive
class VolumesRW implements Serializable { private static final long serialVersionUID = 1L; private final VolumeRW[] volumesRW; public VolumesRW(VolumeRW... binds) { this.volumesRW = binds; } public VolumeRW[] getVolumesRW() { return volumesRW; } @JsonCreator public static VolumesRW fromPrimitive(Map<String, Boolean> map) { return new VolumesRW( map.entrySet().stream() .map(entry -> new VolumeRW(new Volume(entry.getKey()), AccessMode.fromBoolean(entry.getValue()))) .toArray(VolumeRW[]::new) ); } @JsonValue public Map<String, Boolean> toPrimitive() {<FILL_FUNCTION_BODY>} }
return Stream.of(volumesRW).collect(Collectors.toMap( it -> it.getVolume().getPath(), it -> it.getAccessMode().toBoolean() ));
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/DefaultDockerCmdExecFactory.java
DefaultDockerCmdExecFactory
queryParam
class DefaultDockerCmdExecFactory extends AbstractDockerCmdExecFactory { private final DockerHttpClient dockerHttpClient; private final ObjectMapper objectMapper; public DefaultDockerCmdExecFactory( DockerHttpClient dockerHttpClient, ObjectMapper objectMapper ) { this.dockerHttpClient = dockerHttpClient; this.objectMapper = objectMapper; } public DockerHttpClient getDockerHttpClient() { return dockerHttpClient; } @Override protected WebTarget getBaseResource() { return new DefaultWebTarget(); } @Override public void close() throws IOException { dockerHttpClient.close(); } private class DefaultWebTarget implements WebTarget { final ImmutableList<String> path; final SetMultimap<String, String> queryParams; DefaultWebTarget() { this( ImmutableList.of(), MultimapBuilder.hashKeys().hashSetValues().build() ); } DefaultWebTarget( ImmutableList<String> path, SetMultimap<String, String> queryParams ) { this.path = path; this.queryParams = queryParams; } @Override public String toString() { return String.format("DefaultWebTarget{path=%s, queryParams=%s}", path, queryParams); } @Override public InvocationBuilder request() { String resource = StringUtils.join(path, "/"); if (!resource.startsWith("/")) { resource = "/" + resource; } RemoteApiVersion apiVersion = getDockerClientConfig().getApiVersion(); if (apiVersion != RemoteApiVersion.UNKNOWN_VERSION) { resource = "/" + apiVersion.asWebPathPart() + resource; } if (!queryParams.isEmpty()) { Escaper urlFormParameterEscaper = UrlEscapers.urlFormParameterEscaper(); resource = queryParams.asMap().entrySet().stream() .flatMap(entry -> { return entry.getValue().stream().map(s -> { return entry.getKey() + "=" + urlFormParameterEscaper.escape(s); }); }) .collect(Collectors.joining("&", resource + "?", "")); } return new DefaultInvocationBuilder( dockerHttpClient, objectMapper, resource ); } @Override public DefaultWebTarget path(String... components) { ImmutableList<String> newPath = ImmutableList.<String>builder() .addAll(path) .add(components) .build(); return new DefaultWebTarget(newPath, queryParams); } @Override public DefaultWebTarget resolveTemplate(String name, Object value) { ImmutableList.Builder<String> newPath = ImmutableList.builder(); for (String component : path) { component = component.replaceAll( "\\{" + name + "\\}", UrlEscapers.urlPathSegmentEscaper().escape(value.toString()) ); newPath.add(component); } return new DefaultWebTarget(newPath.build(), queryParams); } @Override public DefaultWebTarget queryParam(String name, Object value) {<FILL_FUNCTION_BODY>} @Override public DefaultWebTarget queryParamsSet(String name, Set<?> values) { SetMultimap<String, String> newQueryParams = HashMultimap.create(queryParams); newQueryParams.replaceValues(name, values.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.toSet())); return new DefaultWebTarget(path, newQueryParams); } @Override public DefaultWebTarget queryParamsJsonMap(String name, Map<String, String> values) { if (values == null || values.isEmpty()) { return this; } // when param value is JSON string try { return queryParam(name, objectMapper.writeValueAsString(values)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } }
if (value == null) { return this; } SetMultimap<String, String> newQueryParams = HashMultimap.create(queryParams); newQueryParams.put(name, value.toString()); return new DefaultWebTarget(path, newQueryParams);
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/DockerContextMetaFile.java
DockerContextMetaFile
parseContextMetaFile
class DockerContextMetaFile { private static HashFunction metaHashFunction = Hashing.sha256(); @JsonProperty("Name") String name; @JsonProperty("Endpoints") Endpoints endpoints; public static class Endpoints { @JsonProperty("docker") Docker docker; public static class Docker { @JsonProperty("Host") String host; @JsonProperty("SkipTLSVerify") boolean skipTLSVerify; } } public static Optional<DockerContextMetaFile> resolveContextMetaFile(ObjectMapper objectMapper, File dockerConfigPath, String context) { final File path = dockerConfigPath.toPath() .resolve("contexts") .resolve("meta") .resolve(metaHashFunction.hashString(context, StandardCharsets.UTF_8).toString()) .resolve("meta.json") .toFile(); return Optional.ofNullable(loadContextMetaFile(objectMapper, path)); } public static Optional<File> resolveContextTLSFile(File dockerConfigPath, String context) { final File path = dockerConfigPath.toPath() .resolve("contexts") .resolve("tls") .resolve(metaHashFunction.hashString(context, StandardCharsets.UTF_8).toString()) .resolve("docker") .toFile(); return Optional.ofNullable(path).filter(File::exists); } public static DockerContextMetaFile loadContextMetaFile(ObjectMapper objectMapper, File dockerContextMetaFile) { try { return parseContextMetaFile(objectMapper, dockerContextMetaFile); } catch (Exception exception) { return null; } } public static DockerContextMetaFile parseContextMetaFile(ObjectMapper objectMapper, File dockerContextMetaFile) throws IOException {<FILL_FUNCTION_BODY>} }
try { return objectMapper.readValue(dockerContextMetaFile, DockerContextMetaFile.class); } catch (IOException e) { throw new IOException("Failed to parse docker context meta file " + dockerContextMetaFile, e); }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/FramedInputStreamConsumer.java
FramedInputStreamConsumer
accept
class FramedInputStreamConsumer implements Consumer<DockerHttpClient.Response> { private final ResultCallback<Frame> resultCallback; FramedInputStreamConsumer(ResultCallback<Frame> resultCallback) { this.resultCallback = resultCallback; } @Override public void accept(DockerHttpClient.Response response) {<FILL_FUNCTION_BODY>} private static StreamType streamType(int streamType) { switch (streamType) { case 0: return StreamType.STDIN; case 1: return StreamType.STDOUT; case 2: return StreamType.STDERR; default: return StreamType.RAW; } } }
try { InputStream body = response.getBody(); byte[] buffer = new byte[1024]; while (true) { // See https://docs.docker.com/engine/api/v1.37/#operation/ContainerAttach // [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT} int streamTypeByte = body.read(); if (streamTypeByte < 0) { return; } StreamType streamType = streamType(streamTypeByte); if (streamType == StreamType.RAW) { resultCallback.onNext(new Frame(StreamType.RAW, new byte[]{(byte) streamTypeByte})); int readBytes; while ((readBytes = body.read(buffer)) >= 0) { if (readBytes == buffer.length) { resultCallback.onNext(new Frame(StreamType.RAW, buffer)); } else { resultCallback.onNext(new Frame(StreamType.RAW, Arrays.copyOf(buffer, readBytes))); } } return; } // Skip 3 bytes for (int i = 0; i < 3; i++) { if (body.read() < 0) { return; } } // uint32 encoded as big endian. int bytesToRead = 0; for (int i = 0; i < 4; i++) { int readByte = body.read(); if (readByte < 0) { return; } bytesToRead |= (readByte & 0xff) << (8 * (3 - i)); } do { int readBytes = body.read(buffer, 0, Math.min(buffer.length, bytesToRead)); if (readBytes < 0) { // TODO log? return; } if (readBytes == buffer.length) { resultCallback.onNext(new Frame(streamType, buffer)); } else { resultCallback.onNext(new Frame(streamType, Arrays.copyOf(buffer, readBytes))); } bytesToRead -= readBytes; } while (bytesToRead > 0); } } catch (Exception e) { resultCallback.onError(e); }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/GoLangFileMatch.java
GoLangFileMatch
appendChunkPattern
class GoLangFileMatch { private GoLangFileMatch() { } public static final boolean IS_WINDOWS = File.separatorChar == '\\'; private static final String PATTERN_CHARS_TO_ESCAPE = "\\.[]{}()*+-?^$|"; private static final LoadingCache<String, Pattern> PATTERN_CACHE = CacheBuilder.newBuilder() .expireAfterAccess(1, TimeUnit.HOURS) .maximumSize(10_000) .build(CacheLoader.from(GoLangFileMatch::buildPattern)); public static boolean match(List<String> patterns, File file) { return !match(patterns, file.getPath()).isEmpty(); } public static boolean match(String pattern, File file) { return match(pattern, file.getPath()); } /** * Returns the matching patterns for the given string */ public static List<String> match(List<String> patterns, String name) { List<String> matches = new ArrayList<>(); for (String pattern : patterns) { if (match(pattern, name)) { matches.add(pattern); } } return matches; } public static boolean match(String pattern, String name) { try { return PATTERN_CACHE.get(pattern).matcher(name).matches(); } catch (ExecutionException | UncheckedExecutionException e) { throw new GoLangFileMatchException(e.getCause().getMessage()); } } private static Pattern buildPattern(String pattern) { StringBuilder patternStringBuilder = new StringBuilder("^"); while (!pattern.isEmpty()) { pattern = appendChunkPattern(patternStringBuilder, pattern); if (!pattern.isEmpty()) { patternStringBuilder.append(quote(File.separatorChar)); } } patternStringBuilder.append("(").append(quote(File.separatorChar)).append(".*").append(")?"); return Pattern.compile(patternStringBuilder.toString()); } private static String quote(char separatorChar) { if (StringUtils.contains(PATTERN_CHARS_TO_ESCAPE, separatorChar)) { return "\\" + separatorChar; } else { return String.valueOf(separatorChar); } } private static String appendChunkPattern(StringBuilder patternStringBuilder, String pattern) {<FILL_FUNCTION_BODY>} private static RangeParseState nextStateAfterChar(RangeParseState currentState) { if (currentState == RangeParseState.CHAR_EXPECTED_AFTER_DASH) { return RangeParseState.CHAR_EXPECTED; } else { return RangeParseState.CHAR_OR_DASH_EXPECTED; } } private enum RangeParseState { CHAR_EXPECTED, CHAR_OR_DASH_EXPECTED, CHAR_EXPECTED_AFTER_DASH } }
if (pattern.equals("**") || pattern.startsWith("**" + File.separator)) { patternStringBuilder.append("(") .append("[^").append(quote(File.separatorChar)).append("]*") .append("(") .append(quote(File.separatorChar)).append("[^").append(quote(File.separatorChar)).append("]*") .append(")*").append(")?"); return pattern.substring(pattern.length() == 2 ? 2 : 3); } boolean inRange = false; int rangeFrom = 0; RangeParseState rangeParseState = RangeParseState.CHAR_EXPECTED; boolean isEsc = false; int i; for (i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); switch (c) { case '/': if (!inRange) { if (!IS_WINDOWS && !isEsc) { // end of chunk return pattern.substring(i + 1); } else { patternStringBuilder.append(quote(c)); } } else { rangeParseState = nextStateAfterChar(rangeParseState); } isEsc = false; break; case '\\': if (!inRange) { if (!IS_WINDOWS) { if (isEsc) { patternStringBuilder.append(quote(c)); isEsc = false; } else { isEsc = true; } } else { // end of chunk return pattern.substring(i + 1); } } else { if (IS_WINDOWS || isEsc) { rangeParseState = nextStateAfterChar(rangeParseState); isEsc = false; } else { isEsc = true; } } break; case '[': if (!isEsc) { if (inRange) { throw new GoLangFileMatchException("[ not expected, closing bracket ] not yet reached"); } rangeFrom = i; rangeParseState = RangeParseState.CHAR_EXPECTED; inRange = true; } else { if (!inRange) { patternStringBuilder.append(c); } else { rangeParseState = nextStateAfterChar(rangeParseState); } } isEsc = false; break; case ']': if (!isEsc) { if (!inRange) { throw new GoLangFileMatchException("] is not expected, [ was not met"); } if (rangeParseState == RangeParseState.CHAR_EXPECTED_AFTER_DASH) { throw new GoLangFileMatchException("Character range not finished"); } patternStringBuilder.append(pattern.substring(rangeFrom, i + 1)); inRange = false; } else { if (!inRange) { patternStringBuilder.append(c); } else { rangeParseState = nextStateAfterChar(rangeParseState); } } isEsc = false; break; case '*': if (!inRange) { if (!isEsc) { patternStringBuilder.append("[^").append(quote(File.separatorChar)).append("]*"); } else { patternStringBuilder.append(quote(c)); } } else { rangeParseState = nextStateAfterChar(rangeParseState); } isEsc = false; break; case '?': if (!inRange) { if (!isEsc) { patternStringBuilder.append("[^").append(quote(File.separatorChar)).append("]"); } else { patternStringBuilder.append(quote(c)); } } else { rangeParseState = nextStateAfterChar(rangeParseState); } isEsc = false; break; case '-': if (!inRange) { patternStringBuilder.append(quote(c)); } else { if (!isEsc) { if (rangeParseState != RangeParseState.CHAR_OR_DASH_EXPECTED) { throw new GoLangFileMatchException("- character not expected"); } rangeParseState = RangeParseState.CHAR_EXPECTED_AFTER_DASH; } else { rangeParseState = nextStateAfterChar(rangeParseState); } } isEsc = false; break; default: if (!inRange) { patternStringBuilder.append(quote(c)); } else { rangeParseState = nextStateAfterChar(rangeParseState); } isEsc = false; } } if (isEsc) { throw new GoLangFileMatchException("Escaped character missing"); } if (inRange) { throw new GoLangFileMatchException("Character range not finished"); } return "";
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/KeystoreSSLConfig.java
KeystoreSSLConfig
getSSLContext
class KeystoreSSLConfig implements SSLConfig, Serializable { private final KeyStore keystore; private final String keystorePassword; /** * @param keystore * a KeyStore * @param keystorePassword * key password */ public KeystoreSSLConfig(KeyStore keystore, String keystorePassword) { this.keystorePassword = keystorePassword; this.keystore = Objects.requireNonNull(keystore); } /** * * @param pfxFile * a PKCS12 file * @param password * Password for the keystore * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException */ public KeystoreSSLConfig(File pfxFile, String password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { Objects.requireNonNull(pfxFile); Objects.requireNonNull(password); keystore = KeyStore.getInstance("pkcs12"); try (FileInputStream fs = new FileInputStream(pfxFile)) { keystore.load(fs, password.toCharArray()); } keystorePassword = password; } /** * Get the SSL Context out of the keystore. * * @return java SSLContext * @throws KeyManagementException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ @Override public SSLContext getSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KeystoreSSLConfig that = (KeystoreSSLConfig) o; return keystore.equals(that.keystore); } @Override public int hashCode() { return keystore.hashCode(); } @Override public String toString() { return new StringBuilder().append(this.getClass().getSimpleName()).append("{").append("keystore=") .append(keystore).append("}").toString(); } }
final SSLContext context = SSLContext.getInstance("TLS"); String httpProtocols = System.getProperty("https.protocols"); System.setProperty("https.protocols", "TLSv1"); if (httpProtocols != null) { System.setProperty("https.protocols", httpProtocols); } final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); keyManagerFactory.init(keystore, keystorePassword.toCharArray()); context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } @Override public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) { } @Override public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) { } } }, new SecureRandom()); return context;
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/LocalDirectorySSLConfig.java
LocalDirectorySSLConfig
getSSLContext
class LocalDirectorySSLConfig implements SSLConfig, Serializable { private static final long serialVersionUID = -4736328026418377358L; private final String dockerCertPath; public LocalDirectorySSLConfig(String dockerCertPath) { this.dockerCertPath = Objects.requireNonNull(dockerCertPath); } public String getDockerCertPath() { return dockerCertPath; } @Override public SSLContext getSSLContext() {<FILL_FUNCTION_BODY>} private PrivilegedAction<String> getSystemProperty(final String name, final String def) { return () -> System.getProperty(name, def); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocalDirectorySSLConfig that = (LocalDirectorySSLConfig) o; if (!dockerCertPath.equals(that.dockerCertPath)) { return false; } return true; } @Override public int hashCode() { return dockerCertPath.hashCode(); } @Override public String toString() { return new StringBuilder().append(this.getClass().getSimpleName()).append("{").append("dockerCertPath=") .append(dockerCertPath).append("}").toString(); } }
boolean certificatesExist = CertificateUtils.verifyCertificatesExist(dockerCertPath); if (certificatesExist) { try { Security.addProvider(new BouncyCastleProvider()); String caPemPath = dockerCertPath + File.separator + "ca.pem"; String keyPemPath = dockerCertPath + File.separator + "key.pem"; String certPemPath = dockerCertPath + File.separator + "cert.pem"; String keypem = new String(Files.readAllBytes(Paths.get(keyPemPath))); String certpem = new String(Files.readAllBytes(Paths.get(certPemPath))); String capem = new String(Files.readAllBytes(Paths.get(caPemPath))); String kmfAlgorithm = AccessController.doPrivileged(getSystemProperty("ssl.keyManagerFactory.algorithm", KeyManagerFactory.getDefaultAlgorithm())); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(kmfAlgorithm); keyManagerFactory.init(CertificateUtils.createKeyStore(keypem, certpem), "docker".toCharArray()); String tmfAlgorithm = AccessController.doPrivileged(getSystemProperty("ssl.trustManagerFactory.algorithm", TrustManagerFactory.getDefaultAlgorithm())); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm); trustManagerFactory.init(CertificateUtils.createTrustStore(capem)); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return sslContext; } catch (Exception e) { throw new DockerClientException(e.getMessage(), e); } } return null;
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/NameParser.java
NameParser
resolveRepositoryName
class NameParser { private NameParser() { } // CHECKSTYLE:OFF private static final int RepositoryNameTotalLengthMax = 255; private static final String SHA256_SEPARATOR = "@sha256:"; private static final String COLON_SEPARATOR = ":"; private static final Pattern RepositoryNameComponentRegexp = Pattern.compile("[a-z0-9]+(?:[._-][a-z0-9]+)*"); private static final Pattern RepositoryNameComponentAnchoredRegexp = Pattern.compile("^" + RepositoryNameComponentRegexp.pattern() + "$"); // CHECKSTYLE:ON // private static final Pattern RepositoryNameRegexp = Pattern.compile("(?:" + // RepositoryNameComponentRegexp.pattern() // + "/)*" + RepositoryNameComponentRegexp.pattern()); public static ReposTag parseRepositoryTag(String name) { int n = name.lastIndexOf(':'); if (n < 0) { return new ReposTag(name, ""); } String tag = name.substring(n + 1); if (StringUtils.containsIgnoreCase(name, SHA256_SEPARATOR)) { return new ReposTag(name, ""); } if (!tag.contains("/")) { return new ReposTag(name.substring(0, n), tag); } return new ReposTag(name, ""); } public static class ReposTag { public final String repos; public final String tag; public ReposTag(String repos, String tag) { this.repos = repos; this.tag = tag; } @Override public boolean equals(Object obj) { if (obj instanceof ReposTag) { ReposTag other = (ReposTag) obj; return new EqualsBuilder().append(repos, other.repos).append(tag, other.tag).isEquals(); } else { return false; } } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE); } } /* * see https://github.com/docker/distribution/blob/master/registry/api/v2/names.go */ public static void validateRepoName(String name) { if (name.isEmpty()) { throw new InvalidRepositoryNameException(String.format("Invalid empty repository name \"%s\"", name)); } if (name.length() > RepositoryNameTotalLengthMax) { throw new InvalidRepositoryNameException(String.format("Repository name \"%s\" is longer than " + RepositoryNameTotalLengthMax, name)); } String[] components = name.split("/"); for (String component : components) { if (!RepositoryNameComponentAnchoredRegexp.matcher(component).matches()) { throw new InvalidRepositoryNameException(String.format( "Repository name \"%s\" is invalid. Component: %s", name, component)); } } } public static HostnameReposName resolveRepositoryName(String reposName) {<FILL_FUNCTION_BODY>} public static class HostnameReposName { public final String hostname; public final String reposName; public HostnameReposName(String hostname, String reposName) { this.hostname = hostname; this.reposName = reposName; } @Override public boolean equals(Object obj) { if (obj instanceof HostnameReposName) { HostnameReposName other = (HostnameReposName) obj; return new EqualsBuilder().append(hostname, other.hostname).append(reposName, other.reposName) .isEquals(); } else { return false; } } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE); } } }
if (reposName.contains("://")) { throw new InvalidRepositoryNameException("RepositoryName shouldn't contain a scheme"); } String[] nameParts = reposName.split("/", 2); if (nameParts.length == 1 || (!nameParts[0].contains(".") && !nameParts[0].contains(":") && !nameParts[0].equals("localhost"))) { if (StringUtils.containsIgnoreCase(reposName, SHA256_SEPARATOR)) { reposName = StringUtils.substringBeforeLast(reposName, SHA256_SEPARATOR); } if (StringUtils.contains(reposName, COLON_SEPARATOR)) { reposName = StringUtils.substringBeforeLast(reposName, COLON_SEPARATOR); } return new HostnameReposName(AuthConfig.DEFAULT_SERVER_ADDRESS, reposName); } String hostname = nameParts[0]; reposName = nameParts[1]; if (hostname.contains("index.docker.io")) { throw new InvalidRepositoryNameException(String.format("Invalid repository name, try \"%s\" instead", reposName)); } if (StringUtils.containsIgnoreCase(reposName, SHA256_SEPARATOR)) { reposName = StringUtils.substringBeforeLast(reposName, SHA256_SEPARATOR); } if (StringUtils.contains(reposName, COLON_SEPARATOR)) { reposName = StringUtils.substringBeforeLast(reposName, COLON_SEPARATOR); } validateRepoName(reposName); return new HostnameReposName(hostname, reposName);
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/async/FrameStreamProcessor.java
FrameStreamProcessor
processResponseStream
class FrameStreamProcessor implements ResponseStreamProcessor<Frame> { @Override public void processResponseStream(InputStream response, ResultCallback<Frame> resultCallback) {<FILL_FUNCTION_BODY>} }
resultCallback.onStart(response); FrameReader frameReader = new FrameReader(response); try { Frame frame = frameReader.readFrame(); while (frame != null) { try { resultCallback.onNext(frame); } catch (Exception e) { resultCallback.onError(e); } finally { frame = frameReader.readFrame(); } } } catch (Throwable t) { resultCallback.onError(t); } finally { try { frameReader.close(); response.close(); } catch (IOException e) { resultCallback.onError(e); } finally { resultCallback.onComplete(); } }
docker-java_docker-java
docker-java/docker-java-core/src/main/java/com/github/dockerjava/core/async/JsonStreamProcessor.java
JsonStreamProcessor
processResponseStream
class JsonStreamProcessor<T> implements ResponseStreamProcessor<T> { private static final JsonFactory JSON_FACTORY = new JsonFactory(); private final TypeReference<T> typeReference; private final ObjectMapper objectMapper; @Deprecated public JsonStreamProcessor(Class<T> clazz) { this( DockerClientConfig.getDefaultObjectMapper(), new TypeReference<T>() { } ); } public JsonStreamProcessor(ObjectMapper objectMapper, TypeReference<T> typeReference) { this.typeReference = typeReference; this.objectMapper = objectMapper.copy().enable(JsonParser.Feature.AUTO_CLOSE_SOURCE); } @Override public void processResponseStream(InputStream response, ResultCallback<T> resultCallback) {<FILL_FUNCTION_BODY>} }
resultCallback.onStart(response); try { JsonParser jp = JSON_FACTORY.createParser(response); Boolean closed = jp.isClosed(); JsonToken nextToken = jp.nextToken(); while (!closed && nextToken != null && nextToken != JsonToken.END_OBJECT) { try { ObjectNode objectNode = objectMapper.readTree(jp); // exclude empty item serialization into class #461 if (!objectNode.isEmpty(null)) { T next = objectMapper.convertValue(objectNode, typeReference); resultCallback.onNext(next); } } catch (Exception e) { resultCallback.onError(e); } closed = jp.isClosed(); nextToken = jp.nextToken(); } } catch (Throwable t) { resultCallback.onError(t); } finally { try { response.close(); } catch (IOException e) { resultCallback.onError(e); } finally { resultCallback.onComplete(); } }