proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/sentinel/RedisSentinelReactiveCommandsImpl.java
|
RedisSentinelReactiveCommandsImpl
|
dispatch
|
class RedisSentinelReactiveCommandsImpl<K, V> extends AbstractRedisReactiveCommands<K, V>
implements RedisSentinelReactiveCommands<K, V> {
private final SentinelCommandBuilder<K, V> commandBuilder;
public RedisSentinelReactiveCommandsImpl(StatefulConnection<K, V> connection, RedisCodec<K, V> codec) {
super(connection, codec);
commandBuilder = new SentinelCommandBuilder<K, V>(codec);
}
@Override
public Mono<SocketAddress> getMasterAddrByName(K key) {
return createMono(() -> commandBuilder.getMasterAddrByKey(key));
}
@Override
public Flux<Map<K, V>> masters() {
return createDissolvingFlux(commandBuilder::masters);
}
@Override
public Mono<Map<K, V>> master(K key) {
return createMono(() -> commandBuilder.master(key));
}
@Override
public Flux<Map<K, V>> slaves(K key) {
return createDissolvingFlux(() -> commandBuilder.slaves(key));
}
@Override
public Flux<Map<K, V>> replicas(K key) {
return createDissolvingFlux(() -> commandBuilder.replicas(key));
}
@Override
public Mono<Long> reset(K key) {
return createMono(() -> commandBuilder.reset(key));
}
@Override
public Mono<String> failover(K key) {
return createMono(() -> commandBuilder.failover(key));
}
@Override
public Mono<String> monitor(K key, String ip, int port, int quorum) {
return createMono(() -> commandBuilder.monitor(key, ip, port, quorum));
}
@Override
public Mono<String> set(K key, String option, V value) {
return createMono(() -> commandBuilder.set(key, option, value));
}
@Override
public Mono<String> remove(K key) {
return createMono(() -> commandBuilder.remove(key));
}
@Override
public Mono<String> ping() {
return createMono(commandBuilder::ping);
}
@Override
public Mono<K> clientGetname() {
return createMono(commandBuilder::clientGetname);
}
@Override
public Mono<String> clientSetname(K name) {
return createMono(() -> commandBuilder.clientSetname(name));
}
@Override
public Mono<String> clientSetinfo(String key, String value) {
return createMono(() -> commandBuilder.clientSetinfo(key, value));
}
@Override
public Mono<String> clientKill(String addr) {
return createMono(() -> commandBuilder.clientKill(addr));
}
@Override
public Mono<Long> clientKill(KillArgs killArgs) {
return createMono(() -> commandBuilder.clientKill(killArgs));
}
@Override
public Mono<String> clientPause(long timeout) {
return createMono(() -> commandBuilder.clientPause(timeout));
}
@Override
public Mono<String> clientList() {
return createMono(commandBuilder::clientList);
}
@Override
public Mono<String> clientList(ClientListArgs clientListArgs) {
return createMono(() -> commandBuilder.clientList(clientListArgs));
}
@Override
public Mono<String> clientInfo() {
return createMono(commandBuilder::clientInfo);
}
@Override
public Mono<String> info() {
return createMono(commandBuilder::info);
}
@Override
public Mono<String> info(String section) {
return createMono(() -> commandBuilder.info(section));
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public <T> Flux<T> dispatch(ProtocolKeyword type, CommandOutput<K, V, ?> output) {
LettuceAssert.notNull(type, "Command type must not be null");
LettuceAssert.notNull(output, "CommandOutput type must not be null");
return (Flux) createFlux(() -> new Command<>(type, output));
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public <T> Flux<T> dispatch(ProtocolKeyword type, CommandOutput<K, V, ?> output, CommandArgs<K, V> args) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
getStatefulConnection().close();
}
@Override
public boolean isOpen() {
return getStatefulConnection().isOpen();
}
@Override
public StatefulRedisSentinelConnection<K, V> getStatefulConnection() {
return (StatefulRedisSentinelConnection<K, V>) super.getConnection();
}
}
|
LettuceAssert.notNull(type, "Command type must not be null");
LettuceAssert.notNull(output, "CommandOutput type must not be null");
LettuceAssert.notNull(args, "CommandArgs type must not be null");
return (Flux) createFlux(() -> new Command<>(type, output, args));
| 1,346
| 90
| 1,436
|
<methods>public void <init>(StatefulConnection<K,V>, RedisCodec<K,V>) ,public Mono<Set<io.lettuce.core.AclCategory>> aclCat() ,public Mono<Set<io.lettuce.core.protocol.CommandType>> aclCat(io.lettuce.core.AclCategory) ,public transient Mono<java.lang.Long> aclDeluser(java.lang.String[]) ,public transient Mono<java.lang.String> aclDryRun(java.lang.String, java.lang.String, java.lang.String[]) ,public Mono<java.lang.String> aclDryRun(java.lang.String, RedisCommand<K,V,?>) ,public Mono<java.lang.String> aclGenpass() ,public Mono<java.lang.String> aclGenpass(int) ,public Mono<List<java.lang.Object>> aclGetuser(java.lang.String) ,public Flux<java.lang.String> aclList() ,public Mono<java.lang.String> aclLoad() ,public Flux<Map<java.lang.String,java.lang.Object>> aclLog() ,public Flux<Map<java.lang.String,java.lang.Object>> aclLog(int) ,public Mono<java.lang.String> aclLogReset() ,public Mono<java.lang.String> aclSave() ,public Mono<java.lang.String> aclSetuser(java.lang.String, io.lettuce.core.AclSetuserArgs) ,public Flux<java.lang.String> aclUsers() ,public Mono<java.lang.String> aclWhoami() ,public Mono<java.lang.Long> append(K, V) ,public Mono<java.lang.String> asking() ,public Mono<java.lang.String> auth(java.lang.CharSequence) ,public Mono<java.lang.String> auth(java.lang.String, java.lang.CharSequence) ,public Mono<java.lang.String> bgrewriteaof() ,public Mono<java.lang.String> bgsave() ,public Mono<java.lang.Long> bitcount(K) ,public Mono<java.lang.Long> bitcount(K, long, long) ,public Flux<Value<java.lang.Long>> bitfield(K, io.lettuce.core.BitFieldArgs) ,public transient Mono<java.lang.Long> bitopAnd(K, K[]) ,public Mono<java.lang.Long> bitopNot(K, K) ,public transient Mono<java.lang.Long> bitopOr(K, K[]) ,public transient Mono<java.lang.Long> bitopXor(K, K[]) ,public Mono<java.lang.Long> bitpos(K, boolean) ,public Mono<java.lang.Long> bitpos(K, boolean, long) ,public Mono<java.lang.Long> bitpos(K, boolean, long, long) ,public Mono<V> blmove(K, K, io.lettuce.core.LMoveArgs, long) ,public Mono<V> blmove(K, K, io.lettuce.core.LMoveArgs, double) ,public transient Mono<KeyValue<K,List<V>>> blmpop(long, io.lettuce.core.LMPopArgs, K[]) ,public transient Mono<KeyValue<K,List<V>>> blmpop(double, io.lettuce.core.LMPopArgs, K[]) ,public transient Mono<KeyValue<K,V>> blpop(long, K[]) ,public transient Mono<KeyValue<K,V>> blpop(double, K[]) ,public transient Mono<KeyValue<K,V>> brpop(long, K[]) ,public transient Mono<KeyValue<K,V>> brpop(double, K[]) ,public Mono<V> brpoplpush(long, K, K) ,public Mono<V> brpoplpush(double, K, K) ,public transient Mono<KeyValue<K,ScoredValue<V>>> bzmpop(long, io.lettuce.core.ZPopArgs, K[]) ,public transient Mono<KeyValue<K,List<ScoredValue<V>>>> bzmpop(long, long, io.lettuce.core.ZPopArgs, K[]) ,public transient Mono<KeyValue<K,ScoredValue<V>>> bzmpop(double, io.lettuce.core.ZPopArgs, K[]) ,public transient Mono<KeyValue<K,List<ScoredValue<V>>>> bzmpop(double, int, io.lettuce.core.ZPopArgs, K[]) ,public transient Mono<KeyValue<K,ScoredValue<V>>> bzpopmax(long, K[]) ,public transient Mono<KeyValue<K,ScoredValue<V>>> bzpopmax(double, K[]) ,public transient Mono<KeyValue<K,ScoredValue<V>>> bzpopmin(long, K[]) ,public transient Mono<KeyValue<K,ScoredValue<V>>> bzpopmin(double, K[]) ,public Mono<java.lang.String> clientCaching(boolean) ,public Mono<K> clientGetname() ,public Mono<java.lang.Long> clientGetredir() ,public Mono<java.lang.Long> clientId() ,public Mono<java.lang.String> clientInfo() ,public Mono<java.lang.String> clientKill(java.lang.String) ,public Mono<java.lang.Long> clientKill(io.lettuce.core.KillArgs) ,public Mono<java.lang.String> clientList() ,public Mono<java.lang.String> clientList(io.lettuce.core.ClientListArgs) ,public Mono<java.lang.String> clientNoEvict(boolean) ,public Mono<java.lang.String> clientPause(long) ,public Mono<java.lang.String> clientSetinfo(java.lang.String, java.lang.String) ,public Mono<java.lang.String> clientSetname(K) ,public Mono<java.lang.String> clientTracking(io.lettuce.core.TrackingArgs) ,public Mono<java.lang.Long> clientUnblock(long, io.lettuce.core.UnblockType) ,public void close() ,public transient Mono<java.lang.String> clusterAddSlots(int[]) ,public transient Mono<java.lang.String> clusterAddSlotsRange(Range<java.lang.Integer>[]) ,public Mono<java.lang.String> clusterBumpepoch() ,public Mono<java.lang.Long> clusterCountFailureReports(java.lang.String) ,public Mono<java.lang.Long> clusterCountKeysInSlot(int) ,public transient Mono<java.lang.String> clusterDelSlots(int[]) ,public transient Mono<java.lang.String> clusterDelSlotsRange(Range<java.lang.Integer>[]) ,public Mono<java.lang.String> clusterFailover(boolean) ,public Mono<java.lang.String> clusterFailover(boolean, boolean) ,public Mono<java.lang.String> clusterFlushslots() ,public Mono<java.lang.String> clusterForget(java.lang.String) ,public Flux<K> clusterGetKeysInSlot(int, int) ,public Mono<java.lang.String> clusterInfo() ,public Mono<java.lang.Long> clusterKeyslot(K) ,public Mono<java.lang.String> clusterMeet(java.lang.String, int) ,public Mono<java.lang.String> clusterMyId() ,public Mono<java.lang.String> clusterNodes() ,public Flux<java.lang.String> clusterReplicas(java.lang.String) ,public Mono<java.lang.String> clusterReplicate(java.lang.String) ,public Mono<java.lang.String> clusterReset(boolean) ,public Mono<java.lang.String> clusterSaveconfig() ,public Mono<java.lang.String> clusterSetConfigEpoch(long) ,public Mono<java.lang.String> clusterSetSlotImporting(int, java.lang.String) ,public Mono<java.lang.String> clusterSetSlotMigrating(int, java.lang.String) ,public Mono<java.lang.String> clusterSetSlotNode(int, java.lang.String) ,public Mono<java.lang.String> clusterSetSlotStable(int) ,public Mono<List<java.lang.Object>> clusterShards() ,public Flux<java.lang.String> clusterSlaves(java.lang.String) ,public Flux<java.lang.Object> clusterSlots() ,public Flux<java.lang.Object> command() ,public Mono<java.lang.Long> commandCount() ,public transient Flux<java.lang.Object> commandInfo(java.lang.String[]) ,public transient Flux<java.lang.Object> commandInfo(io.lettuce.core.protocol.CommandType[]) ,public Mono<Map<java.lang.String,java.lang.String>> configGet(java.lang.String) ,public transient Mono<Map<java.lang.String,java.lang.String>> configGet(java.lang.String[]) ,public Mono<java.lang.String> configResetstat() ,public Mono<java.lang.String> configRewrite() ,public Mono<java.lang.String> configSet(java.lang.String, java.lang.String) ,public Mono<java.lang.String> configSet(Map<java.lang.String,java.lang.String>) ,public Mono<java.lang.Boolean> copy(K, K) ,public Mono<java.lang.Boolean> copy(K, K, io.lettuce.core.CopyArgs) ,public Flux<R> createDissolvingFlux(Supplier<RedisCommand<K,V,T>>) ,public Flux<T> createFlux(Supplier<RedisCommand<K,V,T>>) ,public Mono<T> createMono(Supplier<RedisCommand<K,V,T>>) ,public Mono<java.lang.Long> dbsize() ,public Mono<java.lang.String> debugCrashAndRecover(java.lang.Long) ,public Mono<java.lang.String> debugHtstats(int) ,public Mono<java.lang.String> debugObject(K) ,public Mono<java.lang.Void> debugOom() ,public Mono<java.lang.String> debugReload() ,public Mono<java.lang.String> debugRestart(java.lang.Long) ,public Mono<java.lang.String> debugSdslen(K) ,public Mono<java.lang.Void> debugSegfault() ,public Mono<java.lang.Long> decr(K) ,public Mono<java.lang.Long> decrby(K, long) ,public transient Mono<java.lang.Long> del(K[]) ,public Mono<java.lang.Long> del(Iterable<K>) ,public java.lang.String digest(java.lang.String) ,public java.lang.String digest(byte[]) ,public Mono<java.lang.String> discard() ,public Flux<T> dispatch(io.lettuce.core.protocol.ProtocolKeyword, CommandOutput<K,V,?>) ,public Flux<T> dispatch(io.lettuce.core.protocol.ProtocolKeyword, CommandOutput<K,V,?>, CommandArgs<K,V>) ,public Mono<byte[]> dump(K) ,public Mono<V> echo(V) ,public transient Flux<T> eval(java.lang.String, io.lettuce.core.ScriptOutputType, K[]) ,public transient Flux<T> eval(byte[], io.lettuce.core.ScriptOutputType, K[]) ,public transient Flux<T> eval(java.lang.String, io.lettuce.core.ScriptOutputType, K[], V[]) ,public transient Flux<T> eval(byte[], io.lettuce.core.ScriptOutputType, K[], V[]) ,public transient Flux<T> evalReadOnly(byte[], io.lettuce.core.ScriptOutputType, K[], V[]) ,public transient Flux<T> evalsha(java.lang.String, io.lettuce.core.ScriptOutputType, K[]) ,public transient Flux<T> evalsha(java.lang.String, io.lettuce.core.ScriptOutputType, K[], V[]) ,public transient Flux<T> evalshaReadOnly(java.lang.String, io.lettuce.core.ScriptOutputType, K[], V[]) ,public Mono<io.lettuce.core.TransactionResult> exec() ,public Mono<java.lang.Boolean> exists(K) ,public transient Mono<java.lang.Long> exists(K[]) ,public Mono<java.lang.Long> exists(Iterable<K>) ,public Mono<java.lang.Boolean> expire(K, long) ,public Mono<java.lang.Boolean> expire(K, long, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> expire(K, java.time.Duration) ,public Mono<java.lang.Boolean> expire(K, java.time.Duration, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> expireat(K, long) ,public Mono<java.lang.Boolean> expireat(K, long, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> expireat(K, java.util.Date) ,public Mono<java.lang.Boolean> expireat(K, java.util.Date, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> expireat(K, java.time.Instant) ,public Mono<java.lang.Boolean> expireat(K, java.time.Instant, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Long> expiretime(K) ,public transient Flux<T> fcall(java.lang.String, io.lettuce.core.ScriptOutputType, K[]) ,public transient Flux<T> fcall(java.lang.String, io.lettuce.core.ScriptOutputType, K[], V[]) ,public transient Flux<T> fcallReadOnly(java.lang.String, io.lettuce.core.ScriptOutputType, K[]) ,public transient Flux<T> fcallReadOnly(java.lang.String, io.lettuce.core.ScriptOutputType, K[], V[]) ,public void flushCommands() ,public Mono<java.lang.String> flushall() ,public Mono<java.lang.String> flushall(io.lettuce.core.FlushMode) ,public Mono<java.lang.String> flushallAsync() ,public Mono<java.lang.String> flushdb() ,public Mono<java.lang.String> flushdb(io.lettuce.core.FlushMode) ,public Mono<java.lang.String> flushdbAsync() ,public Mono<byte[]> functionDump() ,public Mono<java.lang.String> functionFlush(io.lettuce.core.FlushMode) ,public Mono<java.lang.String> functionKill() ,public Flux<Map<java.lang.String,java.lang.Object>> functionList() ,public Flux<Map<java.lang.String,java.lang.Object>> functionList(java.lang.String) ,public Mono<java.lang.String> functionLoad(java.lang.String) ,public Mono<java.lang.String> functionLoad(java.lang.String, boolean) ,public Mono<java.lang.String> functionRestore(byte[]) ,public Mono<java.lang.String> functionRestore(byte[], io.lettuce.core.FunctionRestoreMode) ,public Mono<java.lang.Long> geoadd(K, double, double, V) ,public Mono<java.lang.Long> geoadd(K, double, double, V, io.lettuce.core.GeoAddArgs) ,public transient Mono<java.lang.Long> geoadd(K, java.lang.Object[]) ,public transient Mono<java.lang.Long> geoadd(K, GeoValue<V>[]) ,public transient Mono<java.lang.Long> geoadd(K, io.lettuce.core.GeoAddArgs, java.lang.Object[]) ,public transient Mono<java.lang.Long> geoadd(K, io.lettuce.core.GeoAddArgs, GeoValue<V>[]) ,public Mono<java.lang.Double> geodist(K, V, V, io.lettuce.core.GeoArgs.Unit) ,public transient Flux<Value<java.lang.String>> geohash(K, V[]) ,public transient Flux<Value<io.lettuce.core.GeoCoordinates>> geopos(K, V[]) ,public Flux<V> georadius(K, double, double, double, io.lettuce.core.GeoArgs.Unit) ,public Flux<GeoWithin<V>> georadius(K, double, double, double, io.lettuce.core.GeoArgs.Unit, io.lettuce.core.GeoArgs) ,public Mono<java.lang.Long> georadius(K, double, double, double, io.lettuce.core.GeoArgs.Unit, GeoRadiusStoreArgs<K>) ,public Flux<V> georadiusbymember(K, V, double, io.lettuce.core.GeoArgs.Unit) ,public Flux<GeoWithin<V>> georadiusbymember(K, V, double, io.lettuce.core.GeoArgs.Unit, io.lettuce.core.GeoArgs) ,public Mono<java.lang.Long> georadiusbymember(K, V, double, io.lettuce.core.GeoArgs.Unit, GeoRadiusStoreArgs<K>) ,public Flux<V> geosearch(K, GeoRef<K>, io.lettuce.core.GeoSearch.GeoPredicate) ,public Flux<GeoWithin<V>> geosearch(K, GeoRef<K>, io.lettuce.core.GeoSearch.GeoPredicate, io.lettuce.core.GeoArgs) ,public Mono<java.lang.Long> geosearchstore(K, K, GeoRef<K>, io.lettuce.core.GeoSearch.GeoPredicate, io.lettuce.core.GeoArgs, boolean) ,public Mono<V> get(K) ,public StatefulConnection<K,V> getConnection() ,public Mono<java.lang.Long> getbit(K, long) ,public Mono<V> getdel(K) ,public Mono<V> getex(K, io.lettuce.core.GetExArgs) ,public Mono<V> getrange(K, long, long) ,public Mono<V> getset(K, V) ,public transient Mono<java.lang.Long> hdel(K, K[]) ,public Mono<java.lang.Boolean> hexists(K, K) ,public Mono<V> hget(K, K) ,public Flux<KeyValue<K,V>> hgetall(K) ,public Mono<java.lang.Long> hgetall(KeyValueStreamingChannel<K,V>, K) ,public Mono<java.lang.Long> hincrby(K, K, long) ,public Mono<java.lang.Double> hincrbyfloat(K, K, double) ,public Flux<K> hkeys(K) ,public Mono<java.lang.Long> hkeys(KeyStreamingChannel<K>, K) ,public Mono<java.lang.Long> hlen(K) ,public transient Flux<KeyValue<K,V>> hmget(K, K[]) ,public transient Mono<java.lang.Long> hmget(KeyValueStreamingChannel<K,V>, K, K[]) ,public Mono<java.lang.String> hmset(K, Map<K,V>) ,public Mono<K> hrandfield(K) ,public Flux<K> hrandfield(K, long) ,public Mono<KeyValue<K,V>> hrandfieldWithvalues(K) ,public Flux<KeyValue<K,V>> hrandfieldWithvalues(K, long) ,public Mono<MapScanCursor<K,V>> hscan(K) ,public Mono<MapScanCursor<K,V>> hscan(K, io.lettuce.core.ScanArgs) ,public Mono<MapScanCursor<K,V>> hscan(K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<MapScanCursor<K,V>> hscan(K, io.lettuce.core.ScanCursor) ,public Mono<io.lettuce.core.StreamScanCursor> hscan(KeyValueStreamingChannel<K,V>, K) ,public Mono<io.lettuce.core.StreamScanCursor> hscan(KeyValueStreamingChannel<K,V>, K, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> hscan(KeyValueStreamingChannel<K,V>, K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> hscan(KeyValueStreamingChannel<K,V>, K, io.lettuce.core.ScanCursor) ,public Mono<KeyScanCursor<K>> hscanNovalues(K) ,public Mono<KeyScanCursor<K>> hscanNovalues(K, io.lettuce.core.ScanArgs) ,public Mono<KeyScanCursor<K>> hscanNovalues(K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<KeyScanCursor<K>> hscanNovalues(K, io.lettuce.core.ScanCursor) ,public Mono<io.lettuce.core.StreamScanCursor> hscanNovalues(KeyStreamingChannel<K>, K) ,public Mono<io.lettuce.core.StreamScanCursor> hscanNovalues(KeyStreamingChannel<K>, K, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> hscanNovalues(KeyStreamingChannel<K>, K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> hscanNovalues(KeyStreamingChannel<K>, K, io.lettuce.core.ScanCursor) ,public Mono<java.lang.Boolean> hset(K, K, V) ,public Mono<java.lang.Long> hset(K, Map<K,V>) ,public Mono<java.lang.Boolean> hsetnx(K, K, V) ,public Mono<java.lang.Long> hstrlen(K, K) ,public Flux<V> hvals(K) ,public Mono<java.lang.Long> hvals(ValueStreamingChannel<V>, K) ,public Mono<java.lang.Long> incr(K) ,public Mono<java.lang.Long> incrby(K, long) ,public Mono<java.lang.Double> incrbyfloat(K, double) ,public Mono<java.lang.String> info() ,public Mono<java.lang.String> info(java.lang.String) ,public boolean isOpen() ,public Flux<K> keys(K) ,public Mono<java.lang.Long> keys(KeyStreamingChannel<K>, K) ,public Mono<java.util.Date> lastsave() ,public Mono<V> lindex(K, long) ,public Mono<java.lang.Long> linsert(K, boolean, V, V) ,public Mono<java.lang.Long> llen(K) ,public Mono<V> lmove(K, K, io.lettuce.core.LMoveArgs) ,public transient Mono<KeyValue<K,List<V>>> lmpop(io.lettuce.core.LMPopArgs, K[]) ,public Mono<V> lpop(K) ,public Flux<V> lpop(K, long) ,public Mono<java.lang.Long> lpos(K, V) ,public Mono<java.lang.Long> lpos(K, V, io.lettuce.core.LPosArgs) ,public Flux<java.lang.Long> lpos(K, V, int) ,public Flux<java.lang.Long> lpos(K, V, int, io.lettuce.core.LPosArgs) ,public transient Mono<java.lang.Long> lpush(K, V[]) ,public transient Mono<java.lang.Long> lpushx(K, V[]) ,public Flux<V> lrange(K, long, long) ,public Mono<java.lang.Long> lrange(ValueStreamingChannel<V>, K, long, long) ,public Mono<java.lang.Long> lrem(K, long, V) ,public Mono<java.lang.String> lset(K, long, V) ,public Mono<java.lang.String> ltrim(K, long, long) ,public Mono<java.lang.Long> memoryUsage(K) ,public transient Flux<KeyValue<K,V>> mget(K[]) ,public Flux<KeyValue<K,V>> mget(Iterable<K>) ,public transient Mono<java.lang.Long> mget(KeyValueStreamingChannel<K,V>, K[]) ,public Mono<java.lang.Long> mget(ValueStreamingChannel<V>, Iterable<K>) ,public Mono<java.lang.Long> mget(KeyValueStreamingChannel<K,V>, Iterable<K>) ,public Mono<java.lang.String> migrate(java.lang.String, int, K, int, long) ,public Mono<java.lang.String> migrate(java.lang.String, int, int, long, MigrateArgs<K>) ,public Mono<java.lang.Boolean> move(K, int) ,public Mono<java.lang.String> mset(Map<K,V>) ,public Mono<java.lang.Boolean> msetnx(Map<K,V>) ,public Mono<java.lang.String> multi() ,public Mono<java.lang.String> objectEncoding(K) ,public Mono<java.lang.Long> objectFreq(K) ,public Mono<java.lang.Long> objectIdletime(K) ,public Mono<java.lang.Long> objectRefcount(K) ,public Mono<java.lang.Boolean> persist(K) ,public Mono<java.lang.Boolean> pexpire(K, long) ,public Mono<java.lang.Boolean> pexpire(K, long, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> pexpire(K, java.time.Duration) ,public Mono<java.lang.Boolean> pexpire(K, java.time.Duration, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> pexpireat(K, java.util.Date) ,public Mono<java.lang.Boolean> pexpireat(K, java.util.Date, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> pexpireat(K, java.time.Instant) ,public Mono<java.lang.Boolean> pexpireat(K, java.time.Instant, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Boolean> pexpireat(K, long) ,public Mono<java.lang.Boolean> pexpireat(K, long, io.lettuce.core.ExpireArgs) ,public Mono<java.lang.Long> pexpiretime(K) ,public transient Mono<java.lang.Long> pfadd(K, V[]) ,public transient Mono<java.lang.Long> pfadd(K, V, V[]) ,public transient Mono<java.lang.Long> pfcount(K[]) ,public transient Mono<java.lang.Long> pfcount(K, K[]) ,public transient Mono<java.lang.String> pfmerge(K, K[]) ,public transient Mono<java.lang.String> pfmerge(K, K, K[]) ,public Mono<java.lang.String> ping() ,public Mono<java.lang.String> psetex(K, long, V) ,public Mono<java.lang.Long> pttl(K) ,public Mono<java.lang.Long> publish(K, V) ,public Flux<K> pubsubChannels() ,public Flux<K> pubsubChannels(K) ,public Mono<java.lang.Long> pubsubNumpat() ,public transient Mono<Map<K,java.lang.Long>> pubsubNumsub(K[]) ,public Flux<K> pubsubShardChannels() ,public Flux<K> pubsubShardChannels(K) ,public transient Mono<Map<K,java.lang.Long>> pubsubShardNumsub(K[]) ,public Mono<java.lang.String> quit() ,public Mono<K> randomkey() ,public Mono<java.lang.String> readOnly() ,public Mono<java.lang.String> readWrite() ,public Mono<java.lang.String> rename(K, K) ,public Mono<java.lang.Boolean> renamenx(K, K) ,public Mono<java.lang.String> replicaof(java.lang.String, int) ,public Mono<java.lang.String> replicaofNoOne() ,public void reset() ,public Mono<java.lang.String> restore(K, long, byte[]) ,public Mono<java.lang.String> restore(K, byte[], io.lettuce.core.RestoreArgs) ,public Flux<java.lang.Object> role() ,public Mono<V> rpop(K) ,public Flux<V> rpop(K, long) ,public Mono<V> rpoplpush(K, K) ,public transient Mono<java.lang.Long> rpush(K, V[]) ,public transient Mono<java.lang.Long> rpushx(K, V[]) ,public transient Mono<java.lang.Long> sadd(K, V[]) ,public Mono<java.lang.String> save() ,public Mono<KeyScanCursor<K>> scan() ,public Mono<KeyScanCursor<K>> scan(io.lettuce.core.ScanArgs) ,public Mono<KeyScanCursor<K>> scan(io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<KeyScanCursor<K>> scan(io.lettuce.core.ScanCursor) ,public Mono<io.lettuce.core.StreamScanCursor> scan(KeyStreamingChannel<K>) ,public Mono<io.lettuce.core.StreamScanCursor> scan(KeyStreamingChannel<K>, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> scan(KeyStreamingChannel<K>, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> scan(KeyStreamingChannel<K>, io.lettuce.core.ScanCursor) ,public Mono<java.lang.Long> scard(K) ,public transient Flux<java.lang.Boolean> scriptExists(java.lang.String[]) ,public Mono<java.lang.String> scriptFlush() ,public Mono<java.lang.String> scriptFlush(io.lettuce.core.FlushMode) ,public Mono<java.lang.String> scriptKill() ,public Mono<java.lang.String> scriptLoad(java.lang.String) ,public Mono<java.lang.String> scriptLoad(byte[]) ,public transient Flux<V> sdiff(K[]) ,public transient Mono<java.lang.Long> sdiff(ValueStreamingChannel<V>, K[]) ,public transient Mono<java.lang.Long> sdiffstore(K, K[]) ,public Mono<java.lang.String> select(int) ,public Mono<java.lang.String> set(K, V) ,public Mono<java.lang.String> set(K, V, io.lettuce.core.SetArgs) ,public void setAutoFlushCommands(boolean) ,public Mono<V> setGet(K, V) ,public Mono<V> setGet(K, V, io.lettuce.core.SetArgs) ,public void setTimeout(java.time.Duration) ,public Mono<java.lang.Long> setbit(K, long, int) ,public Mono<java.lang.String> setex(K, long, V) ,public Mono<java.lang.Boolean> setnx(K, V) ,public Mono<java.lang.Long> setrange(K, long, V) ,public Mono<java.lang.Void> shutdown(boolean) ,public Mono<java.lang.Void> shutdown(io.lettuce.core.ShutdownArgs) ,public transient Flux<V> sinter(K[]) ,public transient Mono<java.lang.Long> sinter(ValueStreamingChannel<V>, K[]) ,public transient Mono<java.lang.Long> sintercard(K[]) ,public transient Mono<java.lang.Long> sintercard(long, K[]) ,public transient Mono<java.lang.Long> sinterstore(K, K[]) ,public Mono<java.lang.Boolean> sismember(K, V) ,public Mono<java.lang.String> slaveof(java.lang.String, int) ,public Mono<java.lang.String> slaveofNoOne() ,public Flux<java.lang.Object> slowlogGet() ,public Flux<java.lang.Object> slowlogGet(int) ,public Mono<java.lang.Long> slowlogLen() ,public Mono<java.lang.String> slowlogReset() ,public Flux<V> smembers(K) ,public Mono<java.lang.Long> smembers(ValueStreamingChannel<V>, K) ,public transient Flux<java.lang.Boolean> smismember(K, V[]) ,public Mono<java.lang.Boolean> smove(K, K, V) ,public Flux<V> sort(K) ,public Mono<java.lang.Long> sort(ValueStreamingChannel<V>, K) ,public Flux<V> sort(K, io.lettuce.core.SortArgs) ,public Mono<java.lang.Long> sort(ValueStreamingChannel<V>, K, io.lettuce.core.SortArgs) ,public Flux<V> sortReadOnly(K) ,public Mono<java.lang.Long> sortReadOnly(ValueStreamingChannel<V>, K) ,public Flux<V> sortReadOnly(K, io.lettuce.core.SortArgs) ,public Mono<java.lang.Long> sortReadOnly(ValueStreamingChannel<V>, K, io.lettuce.core.SortArgs) ,public Mono<java.lang.Long> sortStore(K, io.lettuce.core.SortArgs, K) ,public Mono<V> spop(K) ,public Flux<V> spop(K, long) ,public Mono<V> srandmember(K) ,public Flux<V> srandmember(K, long) ,public Mono<java.lang.Long> srandmember(ValueStreamingChannel<V>, K, long) ,public transient Mono<java.lang.Long> srem(K, V[]) ,public Mono<ValueScanCursor<V>> sscan(K) ,public Mono<ValueScanCursor<V>> sscan(K, io.lettuce.core.ScanArgs) ,public Mono<ValueScanCursor<V>> sscan(K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<ValueScanCursor<V>> sscan(K, io.lettuce.core.ScanCursor) ,public Mono<io.lettuce.core.StreamScanCursor> sscan(ValueStreamingChannel<V>, K) ,public Mono<io.lettuce.core.StreamScanCursor> sscan(ValueStreamingChannel<V>, K, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> sscan(ValueStreamingChannel<V>, K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> sscan(ValueStreamingChannel<V>, K, io.lettuce.core.ScanCursor) ,public Mono<io.lettuce.core.StringMatchResult> stralgoLcs(io.lettuce.core.StrAlgoArgs) ,public Mono<java.lang.Long> strlen(K) ,public transient Flux<V> sunion(K[]) ,public transient Mono<java.lang.Long> sunion(ValueStreamingChannel<V>, K[]) ,public transient Mono<java.lang.Long> sunionstore(K, K[]) ,public Mono<java.lang.String> swapdb(int, int) ,public Flux<V> time() ,public transient Mono<java.lang.Long> touch(K[]) ,public Mono<java.lang.Long> touch(Iterable<K>) ,public Mono<java.lang.Long> ttl(K) ,public Mono<java.lang.String> type(K) ,public transient Mono<java.lang.Long> unlink(K[]) ,public Mono<java.lang.Long> unlink(Iterable<K>) ,public Mono<java.lang.String> unwatch() ,public Mono<java.lang.Long> waitForReplication(int, long) ,public transient Mono<java.lang.String> watch(K[]) ,public transient Mono<java.lang.Long> xack(K, K, java.lang.String[]) ,public Mono<java.lang.String> xadd(K, Map<K,V>) ,public Mono<java.lang.String> xadd(K, io.lettuce.core.XAddArgs, Map<K,V>) ,public transient Mono<java.lang.String> xadd(K, java.lang.Object[]) ,public transient Mono<java.lang.String> xadd(K, io.lettuce.core.XAddArgs, java.lang.Object[]) ,public Mono<ClaimedMessages<K,V>> xautoclaim(K, XAutoClaimArgs<K>) ,public transient Flux<StreamMessage<K,V>> xclaim(K, Consumer<K>, long, java.lang.String[]) ,public transient Flux<StreamMessage<K,V>> xclaim(K, Consumer<K>, io.lettuce.core.XClaimArgs, java.lang.String[]) ,public transient Mono<java.lang.Long> xdel(K, java.lang.String[]) ,public Mono<java.lang.String> xgroupCreate(StreamOffset<K>, K) ,public Mono<java.lang.String> xgroupCreate(StreamOffset<K>, K, io.lettuce.core.XGroupCreateArgs) ,public Mono<java.lang.Boolean> xgroupCreateconsumer(K, Consumer<K>) ,public Mono<java.lang.Long> xgroupDelconsumer(K, Consumer<K>) ,public Mono<java.lang.Boolean> xgroupDestroy(K, K) ,public Mono<java.lang.String> xgroupSetid(StreamOffset<K>, K) ,public Flux<java.lang.Object> xinfoConsumers(K, K) ,public Flux<java.lang.Object> xinfoGroups(K) ,public Flux<java.lang.Object> xinfoStream(K) ,public Mono<java.lang.Long> xlen(K) ,public Mono<io.lettuce.core.models.stream.PendingMessages> xpending(K, K) ,public Flux<io.lettuce.core.models.stream.PendingMessage> xpending(K, K, Range<java.lang.String>, io.lettuce.core.Limit) ,public Flux<io.lettuce.core.models.stream.PendingMessage> xpending(K, Consumer<K>, Range<java.lang.String>, io.lettuce.core.Limit) ,public Flux<io.lettuce.core.models.stream.PendingMessage> xpending(K, XPendingArgs<K>) ,public Flux<StreamMessage<K,V>> xrange(K, Range<java.lang.String>) ,public Flux<StreamMessage<K,V>> xrange(K, Range<java.lang.String>, io.lettuce.core.Limit) ,public transient Flux<StreamMessage<K,V>> xread(StreamOffset<K>[]) ,public transient Flux<StreamMessage<K,V>> xread(io.lettuce.core.XReadArgs, StreamOffset<K>[]) ,public transient Flux<StreamMessage<K,V>> xreadgroup(Consumer<K>, StreamOffset<K>[]) ,public transient Flux<StreamMessage<K,V>> xreadgroup(Consumer<K>, io.lettuce.core.XReadArgs, StreamOffset<K>[]) ,public Flux<StreamMessage<K,V>> xrevrange(K, Range<java.lang.String>) ,public Flux<StreamMessage<K,V>> xrevrange(K, Range<java.lang.String>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> xtrim(K, long) ,public Mono<java.lang.Long> xtrim(K, boolean, long) ,public Mono<java.lang.Long> xtrim(K, io.lettuce.core.XTrimArgs) ,public Mono<java.lang.Long> zadd(K, double, V) ,public transient Mono<java.lang.Long> zadd(K, java.lang.Object[]) ,public transient Mono<java.lang.Long> zadd(K, ScoredValue<V>[]) ,public Mono<java.lang.Long> zadd(K, io.lettuce.core.ZAddArgs, double, V) ,public transient Mono<java.lang.Long> zadd(K, io.lettuce.core.ZAddArgs, java.lang.Object[]) ,public transient Mono<java.lang.Long> zadd(K, io.lettuce.core.ZAddArgs, ScoredValue<V>[]) ,public Mono<java.lang.Double> zaddincr(K, double, V) ,public Mono<java.lang.Double> zaddincr(K, io.lettuce.core.ZAddArgs, double, V) ,public Mono<java.lang.Long> zcard(K) ,public Mono<java.lang.Long> zcount(K, double, double) ,public Mono<java.lang.Long> zcount(K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zcount(K, Range<? extends java.lang.Number>) ,public transient Flux<V> zdiff(K[]) ,public transient Flux<ScoredValue<V>> zdiffWithScores(K[]) ,public transient Mono<java.lang.Long> zdiffstore(K, K[]) ,public Mono<java.lang.Double> zincrby(K, double, V) ,public transient Flux<V> zinter(K[]) ,public transient Flux<V> zinter(io.lettuce.core.ZAggregateArgs, K[]) ,public transient Flux<ScoredValue<V>> zinterWithScores(K[]) ,public transient Flux<ScoredValue<V>> zinterWithScores(io.lettuce.core.ZAggregateArgs, K[]) ,public transient Mono<java.lang.Long> zintercard(K[]) ,public transient Mono<java.lang.Long> zintercard(long, K[]) ,public transient Mono<java.lang.Long> zinterstore(K, K[]) ,public transient Mono<java.lang.Long> zinterstore(K, io.lettuce.core.ZStoreArgs, K[]) ,public Mono<java.lang.Long> zlexcount(K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zlexcount(K, Range<? extends V>) ,public transient Mono<KeyValue<K,ScoredValue<V>>> zmpop(io.lettuce.core.ZPopArgs, K[]) ,public transient Mono<KeyValue<K,List<ScoredValue<V>>>> zmpop(int, io.lettuce.core.ZPopArgs, K[]) ,public transient Mono<List<java.lang.Double>> zmscore(K, V[]) ,public Mono<ScoredValue<V>> zpopmax(K) ,public Flux<ScoredValue<V>> zpopmax(K, long) ,public Mono<ScoredValue<V>> zpopmin(K) ,public Flux<ScoredValue<V>> zpopmin(K, long) ,public Mono<V> zrandmember(K) ,public Flux<V> zrandmember(K, long) ,public Mono<ScoredValue<V>> zrandmemberWithScores(K) ,public Flux<ScoredValue<V>> zrandmemberWithScores(K, long) ,public Flux<V> zrange(K, long, long) ,public Mono<java.lang.Long> zrange(ValueStreamingChannel<V>, K, long, long) ,public Flux<ScoredValue<V>> zrangeWithScores(K, long, long) ,public Mono<java.lang.Long> zrangeWithScores(ScoredValueStreamingChannel<V>, K, long, long) ,public Flux<V> zrangebylex(K, java.lang.String, java.lang.String) ,public Flux<V> zrangebylex(K, Range<? extends V>) ,public Flux<V> zrangebylex(K, java.lang.String, java.lang.String, long, long) ,public Flux<V> zrangebylex(K, Range<? extends V>, io.lettuce.core.Limit) ,public Flux<V> zrangebyscore(K, double, double) ,public Flux<V> zrangebyscore(K, java.lang.String, java.lang.String) ,public Flux<V> zrangebyscore(K, double, double, long, long) ,public Flux<V> zrangebyscore(K, java.lang.String, java.lang.String, long, long) ,public Flux<V> zrangebyscore(K, Range<? extends java.lang.Number>) ,public Flux<V> zrangebyscore(K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrangebyscore(ValueStreamingChannel<V>, K, double, double) ,public Mono<java.lang.Long> zrangebyscore(ValueStreamingChannel<V>, K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zrangebyscore(ValueStreamingChannel<V>, K, double, double, long, long) ,public Mono<java.lang.Long> zrangebyscore(ValueStreamingChannel<V>, K, Range<? extends java.lang.Number>) ,public Mono<java.lang.Long> zrangebyscore(ValueStreamingChannel<V>, K, java.lang.String, java.lang.String, long, long) ,public Mono<java.lang.Long> zrangebyscore(ValueStreamingChannel<V>, K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Flux<ScoredValue<V>> zrangebyscoreWithScores(K, double, double) ,public Flux<ScoredValue<V>> zrangebyscoreWithScores(K, java.lang.String, java.lang.String) ,public Flux<ScoredValue<V>> zrangebyscoreWithScores(K, double, double, long, long) ,public Flux<ScoredValue<V>> zrangebyscoreWithScores(K, java.lang.String, java.lang.String, long, long) ,public Flux<ScoredValue<V>> zrangebyscoreWithScores(K, Range<? extends java.lang.Number>) ,public Flux<ScoredValue<V>> zrangebyscoreWithScores(K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, double, double) ,public Mono<java.lang.Long> zrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, Range<? extends java.lang.Number>) ,public Mono<java.lang.Long> zrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, double, double, long, long) ,public Mono<java.lang.Long> zrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, java.lang.String, java.lang.String, long, long) ,public Mono<java.lang.Long> zrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrangestore(K, K, Range<java.lang.Long>) ,public Mono<java.lang.Long> zrangestorebylex(K, K, Range<? extends V>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrangestorebyscore(K, K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrank(K, V) ,public Mono<ScoredValue<java.lang.Long>> zrankWithScore(K, V) ,public transient Mono<java.lang.Long> zrem(K, V[]) ,public Mono<java.lang.Long> zremrangebylex(K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zremrangebylex(K, Range<? extends V>) ,public Mono<java.lang.Long> zremrangebyrank(K, long, long) ,public Mono<java.lang.Long> zremrangebyscore(K, double, double) ,public Mono<java.lang.Long> zremrangebyscore(K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zremrangebyscore(K, Range<? extends java.lang.Number>) ,public Flux<V> zrevrange(K, long, long) ,public Mono<java.lang.Long> zrevrange(ValueStreamingChannel<V>, K, long, long) ,public Flux<ScoredValue<V>> zrevrangeWithScores(K, long, long) ,public Mono<java.lang.Long> zrevrangeWithScores(ScoredValueStreamingChannel<V>, K, long, long) ,public Flux<V> zrevrangebylex(K, Range<? extends V>) ,public Flux<V> zrevrangebylex(K, Range<? extends V>, io.lettuce.core.Limit) ,public Flux<V> zrevrangebyscore(K, double, double) ,public Flux<V> zrevrangebyscore(K, java.lang.String, java.lang.String) ,public Flux<V> zrevrangebyscore(K, Range<? extends java.lang.Number>) ,public Flux<V> zrevrangebyscore(K, double, double, long, long) ,public Flux<V> zrevrangebyscore(K, java.lang.String, java.lang.String, long, long) ,public Flux<V> zrevrangebyscore(K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrevrangebyscore(ValueStreamingChannel<V>, K, double, double) ,public Mono<java.lang.Long> zrevrangebyscore(ValueStreamingChannel<V>, K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zrevrangebyscore(ValueStreamingChannel<V>, K, Range<? extends java.lang.Number>) ,public Mono<java.lang.Long> zrevrangebyscore(ValueStreamingChannel<V>, K, double, double, long, long) ,public Mono<java.lang.Long> zrevrangebyscore(ValueStreamingChannel<V>, K, java.lang.String, java.lang.String, long, long) ,public Mono<java.lang.Long> zrevrangebyscore(ValueStreamingChannel<V>, K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Flux<ScoredValue<V>> zrevrangebyscoreWithScores(K, double, double) ,public Flux<ScoredValue<V>> zrevrangebyscoreWithScores(K, java.lang.String, java.lang.String) ,public Flux<ScoredValue<V>> zrevrangebyscoreWithScores(K, Range<? extends java.lang.Number>) ,public Flux<ScoredValue<V>> zrevrangebyscoreWithScores(K, double, double, long, long) ,public Flux<ScoredValue<V>> zrevrangebyscoreWithScores(K, java.lang.String, java.lang.String, long, long) ,public Flux<ScoredValue<V>> zrevrangebyscoreWithScores(K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrevrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, double, double) ,public Mono<java.lang.Long> zrevrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, java.lang.String, java.lang.String) ,public Mono<java.lang.Long> zrevrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, Range<? extends java.lang.Number>) ,public Mono<java.lang.Long> zrevrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, double, double, long, long) ,public Mono<java.lang.Long> zrevrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, java.lang.String, java.lang.String, long, long) ,public Mono<java.lang.Long> zrevrangebyscoreWithScores(ScoredValueStreamingChannel<V>, K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrevrangestore(K, K, Range<java.lang.Long>) ,public Mono<java.lang.Long> zrevrangestorebylex(K, K, Range<? extends V>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrevrangestorebyscore(K, K, Range<? extends java.lang.Number>, io.lettuce.core.Limit) ,public Mono<java.lang.Long> zrevrank(K, V) ,public Mono<ScoredValue<java.lang.Long>> zrevrankWithScore(K, V) ,public Mono<ScoredValueScanCursor<V>> zscan(K) ,public Mono<ScoredValueScanCursor<V>> zscan(K, io.lettuce.core.ScanArgs) ,public Mono<ScoredValueScanCursor<V>> zscan(K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<ScoredValueScanCursor<V>> zscan(K, io.lettuce.core.ScanCursor) ,public Mono<io.lettuce.core.StreamScanCursor> zscan(ScoredValueStreamingChannel<V>, K) ,public Mono<io.lettuce.core.StreamScanCursor> zscan(ScoredValueStreamingChannel<V>, K, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> zscan(ScoredValueStreamingChannel<V>, K, io.lettuce.core.ScanCursor, io.lettuce.core.ScanArgs) ,public Mono<io.lettuce.core.StreamScanCursor> zscan(ScoredValueStreamingChannel<V>, K, io.lettuce.core.ScanCursor) ,public Mono<java.lang.Double> zscore(K, V) ,public transient Flux<V> zunion(K[]) ,public transient Flux<V> zunion(io.lettuce.core.ZAggregateArgs, K[]) ,public transient Flux<ScoredValue<V>> zunionWithScores(K[]) ,public transient Flux<ScoredValue<V>> zunionWithScores(io.lettuce.core.ZAggregateArgs, K[]) ,public transient Mono<java.lang.Long> zunionstore(K, K[]) ,public transient Mono<java.lang.Long> zunionstore(K, io.lettuce.core.ZStoreArgs, K[]) <variables>private final non-sealed io.lettuce.core.resource.ClientResources clientResources,private final non-sealed RedisCommandBuilder<K,V> commandBuilder,private final non-sealed StatefulConnection<K,V> connection,private volatile EventExecutorGroup scheduler,private final non-sealed boolean tracingEnabled
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/sentinel/SentinelCommandBuilder.java
|
SentinelCommandBuilder
|
clientList
|
class SentinelCommandBuilder<K, V> extends BaseRedisCommandBuilder<K, V> {
public SentinelCommandBuilder(RedisCodec<K, V> codec) {
super(codec);
}
public Command<K, V, SocketAddress> getMasterAddrByKey(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add("get-master-addr-by-name").addKey(key);
return createCommand(SENTINEL, new SocketAddressOutput<>(codec), args);
}
public Command<K, V, List<Map<K, V>>> masters() {
CommandArgs<K, V> args = new CommandArgs<>(codec).add("masters");
return createCommand(SENTINEL, new ListOfMapsOutput<>(codec), args);
}
public Command<K, V, Map<K, V>> master(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add("master").addKey(key);
return createCommand(SENTINEL, new MapOutput<>(codec), args);
}
public Command<K, V, List<Map<K, V>>> slaves(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(SLAVES).addKey(key);
return createCommand(SENTINEL, new ListOfMapsOutput<>(codec), args);
}
public Command<K, V, List<Map<K, V>>> replicas(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(REPLICAS).addKey(key);
return createCommand(SENTINEL, new ListOfMapsOutput<>(codec), args);
}
public Command<K, V, Long> reset(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(RESET).addKey(key);
return createCommand(SENTINEL, new IntegerOutput<>(codec), args);
}
public Command<K, V, String> failover(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(FAILOVER).addKey(key);
return createCommand(SENTINEL, new StatusOutput<>(codec), args);
}
public Command<K, V, String> monitor(K key, String ip, int port, int quorum) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(MONITOR).addKey(key).add(ip).add(port).add(quorum);
return createCommand(SENTINEL, new StatusOutput<>(codec), args);
}
public Command<K, V, String> set(K key, String option, V value) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(SET).addKey(key).add(option).addValue(value);
return createCommand(SENTINEL, new StatusOutput<>(codec), args);
}
public Command<K, V, K> clientGetname() {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(GETNAME);
return createCommand(CLIENT, new KeyOutput<>(codec), args);
}
public Command<K, V, String> clientSetname(K name) {
LettuceAssert.notNull(name, "Name must not be null");
CommandArgs<K, V> args = new CommandArgs<>(codec).add(SETNAME).addKey(name);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
}
public Command<K, V, String> clientSetinfo(String key, String value) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(SETINFO).add(key).add(value);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
}
public Command<K, V, String> clientKill(String addr) {
LettuceAssert.notNull(addr, "Addr must not be null");
LettuceAssert.notEmpty(addr, "Addr must not be empty");
CommandArgs<K, V> args = new CommandArgs<>(codec).add(KILL).add(addr);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
}
public Command<K, V, Long> clientKill(KillArgs killArgs) {
LettuceAssert.notNull(killArgs, "KillArgs must not be null");
CommandArgs<K, V> args = new CommandArgs<>(codec).add(KILL);
killArgs.build(args);
return createCommand(CLIENT, new IntegerOutput<>(codec), args);
}
public Command<K, V, String> clientPause(long timeout) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(PAUSE).add(timeout);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
}
public Command<K, V, String> clientList() {<FILL_FUNCTION_BODY>}
public Command<K, V, String> clientList(ClientListArgs clientListArgs) {
LettuceAssert.notNull(clientListArgs, "ClientListArgs must not be null");
CommandArgs<K, V> args = new CommandArgs<>(codec).add(LIST);
clientListArgs.build(args);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
}
public Command<K, V, String> clientInfo() {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(CommandKeyword.INFO);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
}
public Command<K, V, String> info() {
return createCommand(CommandType.INFO, new StatusOutput<>(codec));
}
public Command<K, V, String> info(String section) {
LettuceAssert.notNull(section, "Section must not be null");
CommandArgs<K, V> args = new CommandArgs<>(codec).add(section);
return createCommand(CommandType.INFO, new StatusOutput<>(codec), args);
}
public Command<K, V, String> ping() {
return createCommand(PING, new StatusOutput<>(codec));
}
public Command<K, V, String> remove(K key) {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(CommandKeyword.REMOVE).addKey(key);
return createCommand(SENTINEL, new StatusOutput<>(codec), args);
}
}
|
CommandArgs<K, V> args = new CommandArgs<>(codec).add(LIST);
return createCommand(CLIENT, new StatusOutput<>(codec), args);
| 1,680
| 43
| 1,723
|
<methods>public void <init>(RedisCodec<K,V>) <variables>protected final non-sealed RedisCodec<K,V> codec
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/sentinel/StatefulRedisSentinelConnectionImpl.java
|
StatefulRedisSentinelConnectionImpl
|
setClientName
|
class StatefulRedisSentinelConnectionImpl<K, V> extends RedisChannelHandler<K, V>
implements StatefulRedisSentinelConnection<K, V> {
protected final RedisCodec<K, V> codec;
protected final RedisSentinelCommands<K, V> sync;
protected final RedisSentinelAsyncCommands<K, V> async;
protected final RedisSentinelReactiveCommands<K, V> reactive;
private final SentinelConnectionState connectionState = new SentinelConnectionState();
public StatefulRedisSentinelConnectionImpl(RedisChannelWriter writer, RedisCodec<K, V> codec, Duration timeout) {
super(writer, timeout);
this.codec = codec;
this.async = new RedisSentinelAsyncCommandsImpl<>(this, codec);
this.sync = syncHandler(async, RedisSentinelCommands.class);
this.reactive = new RedisSentinelReactiveCommandsImpl<>(this, codec);
}
@Override
public <T> RedisCommand<K, V, T> dispatch(RedisCommand<K, V, T> command) {
return super.dispatch(command);
}
@Override
public Collection<RedisCommand<K, V, ?>> dispatch(Collection<? extends RedisCommand<K, V, ?>> commands) {
return super.dispatch(commands);
}
@Override
public RedisSentinelCommands<K, V> sync() {
return sync;
}
@Override
public RedisSentinelAsyncCommands<K, V> async() {
return async;
}
@Override
public RedisSentinelReactiveCommands<K, V> reactive() {
return reactive;
}
/**
* @param clientName
* @deprecated since 6.0, use {@link RedisSentinelAsyncCommands#clientSetname(Object)}.
*/
@Deprecated
public void setClientName(String clientName) {<FILL_FUNCTION_BODY>}
public ConnectionState getConnectionState() {
return connectionState;
}
static class SentinelConnectionState extends ConnectionState {
@Override
protected void setClientName(String clientName) {
super.setClientName(clientName);
}
}
}
|
CommandArgs<String, String> args = new CommandArgs<>(StringCodec.UTF8).add(CommandKeyword.SETNAME).addValue(clientName);
AsyncCommand<String, String, String> async = new AsyncCommand<>(
new Command<>(CommandType.CLIENT, new StatusOutput<>(StringCodec.UTF8), args));
connectionState.setClientName(clientName);
dispatch((RedisCommand) async);
| 613
| 111
| 724
|
<methods>public void <init>(io.lettuce.core.RedisChannelWriter, java.time.Duration) ,public void activated() ,public void addListener(io.lettuce.core.RedisConnectionStateListener) ,public void close() ,public CompletableFuture<java.lang.Void> closeAsync() ,public void deactivated() ,public void flushCommands() ,public io.lettuce.core.RedisChannelWriter getChannelWriter() ,public io.lettuce.core.ConnectionEvents getConnectionEvents() ,public io.lettuce.core.ClientOptions getOptions() ,public io.lettuce.core.resource.ClientResources getResources() ,public java.time.Duration getTimeout() ,public boolean isClosed() ,public boolean isOpen() ,public transient void registerCloseables(Collection<java.io.Closeable>, java.io.Closeable[]) ,public void removeListener(io.lettuce.core.RedisConnectionStateListener) ,public void reset() ,public void setAutoFlushCommands(boolean) ,public void setOptions(io.lettuce.core.ClientOptions) ,public void setTimeout(java.time.Duration) <variables>private static final AtomicIntegerFieldUpdater<RedisChannelHandler#RAW> CLOSED,private static final int ST_CLOSED,private static final int ST_OPEN,private volatile boolean active,private final non-sealed io.lettuce.core.RedisChannelWriter channelWriter,private volatile io.lettuce.core.ClientOptions clientOptions,private final non-sealed io.lettuce.core.resource.ClientResources clientResources,private io.lettuce.core.CloseEvents closeEvents,private final CompletableFuture<java.lang.Void> closeFuture,private volatile int closed,private final io.lettuce.core.ConnectionEvents connectionEvents,private final boolean debugEnabled,private static final InternalLogger logger,private java.time.Duration timeout,private final non-sealed boolean tracingEnabled
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/AbstractCdiBean.java
|
AbstractCdiBean
|
getStereotypes
|
class AbstractCdiBean<T> implements Bean<T> {
protected final Bean<RedisURI> redisURIBean;
protected final Bean<ClientResources> clientResourcesBean;
protected final BeanManager beanManager;
protected final Set<Annotation> qualifiers;
protected final String name;
public AbstractCdiBean(Bean<RedisURI> redisURIBean, Bean<ClientResources> clientResourcesBean, BeanManager beanManager,
Set<Annotation> qualifiers, String name) {
this.redisURIBean = redisURIBean;
this.clientResourcesBean = clientResourcesBean;
this.beanManager = beanManager;
this.qualifiers = qualifiers;
this.name = name;
}
@Override
@SuppressWarnings("unchecked")
public Set<Type> getTypes() {
return Collections.singleton(getBeanClass());
}
@Override
public Set<Annotation> getQualifiers() {
return qualifiers;
}
@Override
public String getName() {
return name;
}
@Override
public Class<? extends Annotation> getScope() {
return ApplicationScoped.class;
}
@Override
public Set<Class<? extends Annotation>> getStereotypes() {<FILL_FUNCTION_BODY>}
@Override
public boolean isAlternative() {
return false;
}
@Override
public boolean isNullable() {
return false;
}
@Override
public Set<InjectionPoint> getInjectionPoints() {
return Collections.emptySet();
}
}
|
Set<Class<? extends Annotation>> stereotypes = new HashSet<>();
for (Annotation annotation : getQualifiers()) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.isAnnotationPresent(Stereotype.class)) {
stereotypes.add(annotationType);
}
}
return stereotypes;
| 422
| 98
| 520
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/AsyncConnectionPoolSupport.java
|
AsyncConnectionPoolSupport
|
doCreatePool
|
class AsyncConnectionPoolSupport {
private AsyncConnectionPoolSupport() {
}
/**
* Create and initialize asynchronously a new {@link BoundedAsyncPool} using the {@link Supplier}. Allocated instances are
* wrapped and must not be returned with {@link AsyncPool#release(Object)}.
* <p>
* Since Lettuce 6, this method is blocking as it awaits pool initialization (creation of idle connections).Use
* {@link #createBoundedObjectPoolAsync(Supplier, BoundedPoolConfig)} to obtain a {@link CompletionStage} for non-blocking
* synchronization.
*
* @param connectionSupplier must not be {@code null}.
* @param config must not be {@code null}.
* @param <T> connection type.
* @return the connection pool.
*/
public static <T extends StatefulConnection<?, ?>> BoundedAsyncPool<T> createBoundedObjectPool(
Supplier<CompletionStage<T>> connectionSupplier, BoundedPoolConfig config) {
return createBoundedObjectPool(connectionSupplier, config, true);
}
/**
* Create and initialize asynchronously a new {@link BoundedAsyncPool} using the {@link Supplier}.
* <p>
* Since Lettuce 6, this method is blocking as it awaits pool initialization (creation of idle connections).Use
* {@link #createBoundedObjectPoolAsync(Supplier, BoundedPoolConfig, boolean)} to obtain a {@link CompletionStage} for
* non-blocking synchronization.
*
* @param connectionSupplier must not be {@code null}.
* @param config must not be {@code null}.
* @param wrapConnections {@code false} to return direct connections that need to be returned to the pool using
* {@link AsyncPool#release(Object)}. {@code true} to return wrapped connection that are returned to the pool when
* invoking {@link StatefulConnection#close()}/{@link StatefulConnection#closeAsync()}.
* @param <T> connection type.
* @return the connection pool.
*/
public static <T extends StatefulConnection<?, ?>> BoundedAsyncPool<T> createBoundedObjectPool(
Supplier<CompletionStage<T>> connectionSupplier, BoundedPoolConfig config, boolean wrapConnections) {
try {
return createBoundedObjectPoolAsync(connectionSupplier, config, wrapConnections).toCompletableFuture().join();
} catch (Exception e) {
throw Exceptions.bubble(Exceptions.unwrap(e));
}
}
/**
* Create and initialize asynchronously a new {@link BoundedAsyncPool} using the {@link Supplier}. Allocated instances are
* wrapped and must not be returned with {@link AsyncPool#release(Object)}.
*
* @param connectionSupplier must not be {@code null}.
* @param config must not be {@code null}.
* @param <T> connection type.
* @return {@link CompletionStage} emitting the connection pool upon completion.
* @since 5.3.3
*/
public static <T extends StatefulConnection<?, ?>> CompletionStage<BoundedAsyncPool<T>> createBoundedObjectPoolAsync(
Supplier<CompletionStage<T>> connectionSupplier, BoundedPoolConfig config) {
return createBoundedObjectPoolAsync(connectionSupplier, config, true);
}
/**
* Create and initialize asynchronously a new {@link BoundedAsyncPool} using the {@link Supplier}.
*
* @param connectionSupplier must not be {@code null}.
* @param config must not be {@code null}.
* @param wrapConnections {@code false} to return direct connections that need to be returned to the pool using
* {@link AsyncPool#release(Object)}. {@code true} to return wrapped connection that are returned to the pool when
* invoking {@link StatefulConnection#close()}/{@link StatefulConnection#closeAsync()}.
* @param <T> connection type.
* @return {@link CompletionStage} emitting the connection pool upon completion.
* @since 5.3.3
*/
public static <T extends StatefulConnection<?, ?>> CompletionStage<BoundedAsyncPool<T>> createBoundedObjectPoolAsync(
Supplier<CompletionStage<T>> connectionSupplier, BoundedPoolConfig config, boolean wrapConnections) {
BoundedAsyncPool<T> pool = doCreatePool(connectionSupplier, config, wrapConnections);
CompletableFuture<BoundedAsyncPool<T>> future = new CompletableFuture<>();
pool.createIdle().whenComplete((v, throwable) -> {
if (throwable == null) {
future.complete(pool);
} else {
pool.closeAsync().whenComplete((v1, throwable1) -> {
future.completeExceptionally(new RedisConnectionException("Could not create pool", throwable));
});
}
});
return future;
}
protected static <T extends StatefulConnection<?, ?>> BoundedAsyncPool<T> doCreatePool(
Supplier<CompletionStage<T>> connectionSupplier, BoundedPoolConfig config, boolean wrapConnections) {<FILL_FUNCTION_BODY>}
/**
* @author Mark Paluch
* @since 5.1
*/
private static class RedisPooledObjectFactory<T extends StatefulConnection<?, ?>> implements AsyncObjectFactory<T> {
private final Supplier<CompletionStage<T>> connectionSupplier;
RedisPooledObjectFactory(Supplier<CompletionStage<T>> connectionSupplier) {
this.connectionSupplier = connectionSupplier;
}
@Override
public CompletableFuture<T> create() {
return connectionSupplier.get().toCompletableFuture();
}
@Override
public CompletableFuture<Void> destroy(T object) {
return object.closeAsync();
}
@Override
public CompletableFuture<Boolean> validate(T object) {
return CompletableFuture.completedFuture(object.isOpen());
}
}
private static class AsyncPoolWrapper<T> implements Origin<T> {
private final AsyncPool<T> pool;
AsyncPoolWrapper(AsyncPool<T> pool) {
this.pool = pool;
}
@Override
public void returnObject(T o) {
returnObjectAsync(o).join();
}
@Override
public CompletableFuture<Void> returnObjectAsync(T o) {
return pool.release(o);
}
}
}
|
LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
LettuceAssert.notNull(config, "BoundedPoolConfig must not be null");
AtomicReference<Origin<T>> poolRef = new AtomicReference<>();
BoundedAsyncPool<T> pool = new BoundedAsyncPool<T>(new RedisPooledObjectFactory<T>(connectionSupplier), config, false) {
@Override
public CompletableFuture<T> acquire() {
CompletableFuture<T> acquire = super.acquire();
if (wrapConnections) {
return acquire.thenApply(it -> ConnectionWrapping.wrapConnection(it, poolRef.get()));
}
return acquire;
}
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<Void> release(T object) {
if (wrapConnections && object instanceof HasTargetConnection) {
return super.release((T) ((HasTargetConnection) object).getTargetConnection());
}
return super.release(object);
}
};
poolRef.set(new AsyncPoolWrapper<>(pool));
return pool;
| 1,660
| 300
| 1,960
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/BasePool.java
|
BasePool
|
unknownStackTrace
|
class BasePool {
private final boolean testOnCreate;
private final boolean testOnAcquire;
private final boolean testOnRelease;
/**
* Create a new pool given {@link BasePoolConfig}.
*
* @param poolConfig must not be {@code null}.
*/
protected BasePool(BasePoolConfig poolConfig) {
LettuceAssert.notNull(poolConfig, "PoolConfig must not be null");
this.testOnCreate = poolConfig.isTestOnCreate();
this.testOnAcquire = poolConfig.isTestOnAcquire();
this.testOnRelease = poolConfig.isTestOnRelease();
}
/**
* Returns whether objects created for the pool will be validated before being returned from the acquire method. Validation
* is performed by the {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the pool. If the
* object fails to validate, then acquire will fail.
*
* @return {@code true} if newly created objects are validated before being returned from the acquire method.
*/
public boolean isTestOnCreate() {
return testOnCreate;
}
/**
* Returns whether objects acquired from the pool will be validated before being returned from the acquire method.
* Validation is performed by the {@link AsyncObjectFactory#validate(Object)} method of the factory associated with the
* pool. If the object fails to validate, it will be removed from the pool and destroyed, and a new attempt will be made to
* borrow an object from the pool.
*
* @return {@code true} if objects are validated before being returned from the acquire method.
*/
public boolean isTestOnAcquire() {
return testOnAcquire;
}
/**
* Returns whether objects borrowed from the pool will be validated when they are returned to the pool via the release
* method. Validation is performed by the {@link AsyncObjectFactory#validate(Object)} method of the factory associated with
* the pool. Returning objects that fail validation are destroyed rather then being returned the pool.
*
* @return {@code true} if objects are validated on return to the pool via the release method.
*/
public boolean isTestOnRelease() {
return testOnRelease;
}
/**
* Set the {@link StackTraceElement} for the given {@link Throwable}, using the {@link Class} and method name.
*/
static <T extends Throwable> T unknownStackTrace(T cause, Class<?> clazz, String method) {<FILL_FUNCTION_BODY>}
}
|
cause.setStackTrace(new StackTraceElement[] { new StackTraceElement(clazz.getName(), method, null, -1) });
return cause;
| 635
| 40
| 675
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/CommonsPool2ConfigConverter.java
|
CommonsPool2ConfigConverter
|
bounded
|
class CommonsPool2ConfigConverter {
private CommonsPool2ConfigConverter() {
}
/**
* Converts {@link GenericObjectPoolConfig} properties to an immutable {@link BoundedPoolConfig}. Applies max total, min/max
* idle and test on borrow/create/release configuration.
*
* @param config must not be {@code null}.
* @return the converted {@link BoundedPoolConfig}.
*/
public static BoundedPoolConfig bounded(GenericObjectPoolConfig<?> config) {<FILL_FUNCTION_BODY>}
}
|
LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");
return BoundedPoolConfig.builder() //
.maxTotal(config.getMaxTotal() > 0 ? config.getMaxTotal() : Integer.MAX_VALUE)
.maxIdle(config.getMaxIdle() > 0 ? config.getMaxIdle() : Integer.MAX_VALUE) //
.minIdle(config.getMinIdle()) //
.testOnAcquire(config.getTestOnBorrow()) //
.testOnCreate(config.getTestOnCreate()) //
.testOnRelease(config.getTestOnReturn()) //
.build();
| 142
| 165
| 307
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/ConnectionPoolSupport.java
|
ConnectionPoolSupport
|
createGenericObjectPool
|
class ConnectionPoolSupport {
private ConnectionPoolSupport() {
}
/**
* Creates a new {@link GenericObjectPool} using the {@link Supplier}. Allocated instances are wrapped and must not be
* returned with {@link ObjectPool#returnObject(Object)}.
*
* @param connectionSupplier must not be {@code null}.
* @param config must not be {@code null}.
* @param <T> connection type.
* @return the connection pool.
*/
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
Supplier<T> connectionSupplier, GenericObjectPoolConfig<T> config) {
return createGenericObjectPool(connectionSupplier, config, true);
}
/**
* Creates a new {@link GenericObjectPool} using the {@link Supplier}.
*
* @param connectionSupplier must not be {@code null}.
* @param config must not be {@code null}.
* @param wrapConnections {@code false} to return direct connections that need to be returned to the pool using
* {@link ObjectPool#returnObject(Object)}. {@code true} to return wrapped connection that are returned to the
* pool when invoking {@link StatefulConnection#close()}.
* @param <T> connection type.
* @return the connection pool.
*/
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
Supplier<T> connectionSupplier, GenericObjectPoolConfig<T> config, boolean wrapConnections) {<FILL_FUNCTION_BODY>}
/**
* Creates a new {@link SoftReferenceObjectPool} using the {@link Supplier}. Allocated instances are wrapped and must not be
* returned with {@link ObjectPool#returnObject(Object)}.
*
* @param connectionSupplier must not be {@code null}.
* @param <T> connection type.
* @return the connection pool.
*/
public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool(
Supplier<T> connectionSupplier) {
return createSoftReferenceObjectPool(connectionSupplier, true);
}
/**
* Creates a new {@link SoftReferenceObjectPool} using the {@link Supplier}.
*
* @param connectionSupplier must not be {@code null}.
* @param wrapConnections {@code false} to return direct connections that need to be returned to the pool using
* {@link ObjectPool#returnObject(Object)}. {@code true} to return wrapped connection that are returned to the
* pool when invoking {@link StatefulConnection#close()}.
* @param <T> connection type.
* @return the connection pool.
*/
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool(
Supplier<T> connectionSupplier, boolean wrapConnections) {
LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
AtomicReference<Origin<T>> poolRef = new AtomicReference<>();
SoftReferenceObjectPool<T> pool = new SoftReferenceObjectPool<T>(new RedisPooledObjectFactory<>(connectionSupplier)) {
@Override
public synchronized T borrowObject() throws Exception {
return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get())
: super.borrowObject();
}
@Override
public synchronized void returnObject(T obj) throws Exception {
if (wrapConnections && obj instanceof HasTargetConnection) {
super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
return;
}
super.returnObject(obj);
}
};
poolRef.set(new ObjectPoolWrapper<>(pool));
return pool;
}
/**
* @author Mark Paluch
* @since 4.3
*/
private static class RedisPooledObjectFactory<T extends StatefulConnection<?, ?>> extends BasePooledObjectFactory<T> {
private final Supplier<T> connectionSupplier;
RedisPooledObjectFactory(Supplier<T> connectionSupplier) {
this.connectionSupplier = connectionSupplier;
}
@Override
public T create() throws Exception {
return connectionSupplier.get();
}
@Override
public void destroyObject(PooledObject<T> p) throws Exception {
p.getObject().close();
}
@Override
public PooledObject<T> wrap(T obj) {
return new DefaultPooledObject<>(obj);
}
@Override
public boolean validateObject(PooledObject<T> p) {
return p.getObject().isOpen();
}
}
private static class ObjectPoolWrapper<T> implements Origin<T> {
private static final CompletableFuture<Void> COMPLETED = CompletableFuture.completedFuture(null);
private final ObjectPool<T> pool;
ObjectPoolWrapper(ObjectPool<T> pool) {
this.pool = pool;
}
@Override
public void returnObject(T o) throws Exception {
pool.returnObject(o);
}
@Override
public CompletableFuture<Void> returnObjectAsync(T o) throws Exception {
pool.returnObject(o);
return COMPLETED;
}
}
}
|
LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");
AtomicReference<Origin<T>> poolRef = new AtomicReference<>();
GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<T>(connectionSupplier), config) {
@Override
public T borrowObject() throws Exception {
return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get())
: super.borrowObject();
}
@Override
public void returnObject(T obj) {
if (wrapConnections && obj instanceof HasTargetConnection) {
super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
return;
}
super.returnObject(obj);
}
};
poolRef.set(new ObjectPoolWrapper<>(pool));
return pool;
| 1,394
| 256
| 1,650
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/ConnectionWrapping.java
|
ConnectionWrapping
|
wrapConnection
|
class ConnectionWrapping {
/**
* Unwrap a potentially {@link Wrapper} object. Recurses across {@link Wrapper wrappers}
*
* @param object the potentially wrapped object.
* @return the {@code object} if it is not wrapped or the {@link Wrapper#unwrap() unwrapped} object.
*/
public static Object unwrap(Object object) {
while (object instanceof Wrapper<?>) {
object = ((Wrapper<?>) object).unwrap();
}
return object;
}
/**
* Wrap a connection along its {@link Origin} reference.
*
* @param connection
* @param pool
* @param <T>
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
static <T> T wrapConnection(T connection, Origin<T> pool) {<FILL_FUNCTION_BODY>}
/**
* Invocation handler that takes care of connection.close(). Connections are returned to the pool on a close()-call.
*
* @author Mark Paluch
* @param <T> Connection type.
* @since 4.3
*/
static class ReturnObjectOnCloseInvocationHandler<T> extends AbstractInvocationHandler implements Wrapper<T> {
private T connection;
private T proxiedConnection;
private Map<Method, Object> connectionProxies = new ConcurrentHashMap<>(5, 1);
private final Origin<T> pool;
ReturnObjectOnCloseInvocationHandler(T connection, Origin<T> pool) {
this.connection = connection;
this.pool = pool;
}
void setProxiedConnection(T proxiedConnection) {
this.proxiedConnection = proxiedConnection;
}
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getStatefulConnection")) {
return proxiedConnection;
}
if (method.getName().equals("getTargetConnection")) {
return connection;
}
if (connection == null) {
throw new RedisException("Connection is deallocated and cannot be used anymore.");
}
if (method.getName().equals("close")) {
pool.returnObject(proxiedConnection);
connection = null;
proxiedConnection = null;
connectionProxies.clear();
return null;
}
if (method.getName().equals("closeAsync")) {
CompletableFuture<Void> future = pool.returnObjectAsync(proxiedConnection);
connection = null;
proxiedConnection = null;
connectionProxies.clear();
return future;
}
try {
if (method.getName().equals("sync") || method.getName().equals("async")
|| method.getName().equals("reactive")) {
return connectionProxies.computeIfAbsent(method, m -> getInnerProxy(method, args));
}
return method.invoke(connection, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getInnerProxy(Method method, Object[] args) {
try {
Object result = method.invoke(connection, args);
result = Proxy.newProxyInstance(getClass().getClassLoader(), result.getClass().getInterfaces(),
new DelegateCloseToConnectionInvocationHandler((AsyncCloseable) proxiedConnection, result));
return result;
} catch (IllegalAccessException e) {
throw new RedisException(e);
} catch (InvocationTargetException e) {
throw new RedisException(e.getTargetException());
}
}
public T getConnection() {
return connection;
}
@Override
public T unwrap() {
return getConnection();
}
}
/**
* Invocation handler that takes care of connection.close(). Connections are returned to the pool on a close()-call.
*
* @author Mark Paluch
* @param <T> Connection type.
* @since 4.3
*/
@SuppressWarnings("try")
static class DelegateCloseToConnectionInvocationHandler<T extends AsyncCloseable & AutoCloseable>
extends AbstractInvocationHandler implements Wrapper<Object> {
private final T proxiedConnection;
private final Object api;
DelegateCloseToConnectionInvocationHandler(T proxiedConnection, Object api) {
this.proxiedConnection = proxiedConnection;
this.api = api;
}
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getStatefulConnection")) {
return proxiedConnection;
}
try {
if (method.getName().equals("close")) {
proxiedConnection.close();
return null;
}
if (method.getName().equals("closeAsync")) {
return proxiedConnection.closeAsync();
}
return method.invoke(api, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
@Override
public Object unwrap() {
return api;
}
}
/**
* Interface to retrieve an underlying target connection from a proxy.
*/
interface HasTargetConnection {
StatefulConnection<?, ?> getTargetConnection();
}
/**
* Interface to return objects to their origin.
*/
interface Origin<T> {
/**
* Synchronously return the object.
*/
void returnObject(T o) throws Exception;
/**
* Return the object asynchronously.
*/
CompletableFuture<Void> returnObjectAsync(T o) throws Exception;
}
/**
* Marker interface to indicate a wrapper.
*
* @param <T> Type of the wrapped object.
* @since 5.2
*/
interface Wrapper<T> {
T unwrap();
}
}
|
ReturnObjectOnCloseInvocationHandler<T> handler = new ReturnObjectOnCloseInvocationHandler<T>(connection, pool);
Class<?>[] implementedInterfaces = connection.getClass().getInterfaces();
Class[] interfaces = new Class[implementedInterfaces.length + 1];
interfaces[0] = HasTargetConnection.class;
System.arraycopy(implementedInterfaces, 0, interfaces, 1, implementedInterfaces.length);
T proxiedConnection = (T) Proxy.newProxyInstance(connection.getClass().getClassLoader(), interfaces, handler);
handler.setProxiedConnection(proxiedConnection);
return proxiedConnection;
| 1,602
| 170
| 1,772
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/LettuceCdiExtension.java
|
LettuceCdiExtension
|
processBean
|
class LettuceCdiExtension implements Extension {
private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(LettuceCdiExtension.class);
private final Map<Set<Annotation>, Bean<RedisURI>> redisUris = new ConcurrentHashMap<>();
private final Map<Set<Annotation>, Bean<ClientResources>> clientResources = new ConcurrentHashMap<>();
public LettuceCdiExtension() {
LOGGER.info("Activating CDI extension for lettuce.");
}
/**
* Implementation of a an observer which checks for RedisURI beans and stores them in {@link #redisUris} for later
* association with corresponding repository beans.
*
* @param <T> The type.
* @param processBean The annotated type as defined by CDI.
*/
@SuppressWarnings("unchecked")
<T> void processBean(@Observes ProcessBean<T> processBean) {<FILL_FUNCTION_BODY>}
/**
* Implementation of a an observer which registers beans to the CDI container for the detected RedisURIs.
* <p>
* The repository beans are associated to the EntityManagers using their qualifiers.
*
* @param beanManager The BeanManager instance.
*/
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
int counter = 0;
for (Entry<Set<Annotation>, Bean<RedisURI>> entry : redisUris.entrySet()) {
Bean<RedisURI> redisUri = entry.getValue();
Set<Annotation> qualifiers = entry.getKey();
String clientBeanName = RedisClient.class.getSimpleName();
String clusterClientBeanName = RedisClusterClient.class.getSimpleName();
if (!containsDefault(qualifiers)) {
clientBeanName += counter;
clusterClientBeanName += counter;
counter++;
}
Bean<ClientResources> clientResources = this.clientResources.get(qualifiers);
RedisClientCdiBean clientBean = new RedisClientCdiBean(redisUri, clientResources, beanManager, qualifiers,
clientBeanName);
register(afterBeanDiscovery, qualifiers, clientBean);
RedisClusterClientCdiBean clusterClientBean = new RedisClusterClientCdiBean(redisUri, clientResources, beanManager,
qualifiers, clusterClientBeanName);
register(afterBeanDiscovery, qualifiers, clusterClientBean);
}
}
private boolean containsDefault(Set<Annotation> qualifiers) {
return qualifiers.stream().filter(input -> input instanceof Default).findFirst().isPresent();
}
private void register(AfterBeanDiscovery afterBeanDiscovery, Set<Annotation> qualifiers, Bean<?> bean) {
LOGGER.info(String.format("Registering bean '%s' with qualifiers %s.", bean.getBeanClass().getName(), qualifiers));
afterBeanDiscovery.addBean(bean);
}
}
|
Bean<T> bean = processBean.getBean();
for (Type type : bean.getTypes()) {
if (!(type instanceof Class<?>)) {
continue;
}
// Check if the bean is an RedisURI.
if (RedisURI.class.isAssignableFrom((Class<?>) type)) {
Set<Annotation> qualifiers = LettuceSets.newHashSet(bean.getQualifiers());
if (bean.isAlternative() || !redisUris.containsKey(qualifiers)) {
LOGGER.debug(String.format("Discovered '%s' with qualifiers %s.", RedisURI.class.getName(), qualifiers));
redisUris.put(qualifiers, (Bean<RedisURI>) bean);
}
}
if (ClientResources.class.isAssignableFrom((Class<?>) type)) {
Set<Annotation> qualifiers = LettuceSets.newHashSet(bean.getQualifiers());
if (bean.isAlternative() || !clientResources.containsKey(qualifiers)) {
LOGGER.debug(
String.format("Discovered '%s' with qualifiers %s.", ClientResources.class.getName(), qualifiers));
clientResources.put(qualifiers, (Bean<ClientResources>) bean);
}
}
}
| 756
| 334
| 1,090
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/RedisClientCdiBean.java
|
RedisClientCdiBean
|
create
|
class RedisClientCdiBean extends AbstractCdiBean<RedisClient> {
RedisClientCdiBean(Bean<RedisURI> redisURIBean, Bean<ClientResources> clientResourcesBean, BeanManager beanManager,
Set<Annotation> qualifiers, String name) {
super(redisURIBean, clientResourcesBean, beanManager, qualifiers, name);
}
@Override
public Class<?> getBeanClass() {
return RedisClient.class;
}
@Override
public RedisClient create(CreationalContext<RedisClient> creationalContext) {<FILL_FUNCTION_BODY>}
@Override
public void destroy(RedisClient instance, CreationalContext<RedisClient> creationalContext) {
instance.shutdown();
}
}
|
CreationalContext<RedisURI> uriCreationalContext = beanManager.createCreationalContext(redisURIBean);
RedisURI redisURI = (RedisURI) beanManager.getReference(redisURIBean, RedisURI.class, uriCreationalContext);
if (clientResourcesBean != null) {
ClientResources clientResources = (ClientResources) beanManager.getReference(clientResourcesBean,
ClientResources.class, uriCreationalContext);
return RedisClient.create(clientResources, redisURI);
}
return RedisClient.create(redisURI);
| 202
| 147
| 349
|
<methods>public void <init>(Bean<io.lettuce.core.RedisURI>, Bean<io.lettuce.core.resource.ClientResources>, BeanManager, Set<java.lang.annotation.Annotation>, java.lang.String) ,public Set<InjectionPoint> getInjectionPoints() ,public java.lang.String getName() ,public Set<java.lang.annotation.Annotation> getQualifiers() ,public Class<? extends java.lang.annotation.Annotation> getScope() ,public Set<Class<? extends java.lang.annotation.Annotation>> getStereotypes() ,public Set<java.lang.reflect.Type> getTypes() ,public boolean isAlternative() ,public boolean isNullable() <variables>protected final non-sealed BeanManager beanManager,protected final non-sealed Bean<io.lettuce.core.resource.ClientResources> clientResourcesBean,protected final non-sealed java.lang.String name,protected final non-sealed Set<java.lang.annotation.Annotation> qualifiers,protected final non-sealed Bean<io.lettuce.core.RedisURI> redisURIBean
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/RedisClusterClientCdiBean.java
|
RedisClusterClientCdiBean
|
create
|
class RedisClusterClientCdiBean extends AbstractCdiBean<RedisClusterClient> {
public RedisClusterClientCdiBean(Bean<RedisURI> redisURIBean, Bean<ClientResources> clientResourcesBean,
BeanManager beanManager, Set<Annotation> qualifiers, String name) {
super(redisURIBean, clientResourcesBean, beanManager, qualifiers, name);
}
@Override
public Class<?> getBeanClass() {
return RedisClusterClient.class;
}
@Override
public RedisClusterClient create(CreationalContext<RedisClusterClient> creationalContext) {<FILL_FUNCTION_BODY>}
@Override
public void destroy(RedisClusterClient instance, CreationalContext<RedisClusterClient> creationalContext) {
instance.shutdown();
}
}
|
CreationalContext<RedisURI> uriCreationalContext = beanManager.createCreationalContext(redisURIBean);
RedisURI redisURI = (RedisURI) beanManager.getReference(redisURIBean, RedisURI.class, uriCreationalContext);
if (clientResourcesBean != null) {
ClientResources clientResources = (ClientResources) beanManager.getReference(clientResourcesBean,
ClientResources.class, uriCreationalContext);
return RedisClusterClient.create(clientResources, redisURI);
}
return RedisClusterClient.create(redisURI);
| 211
| 149
| 360
|
<methods>public void <init>(Bean<io.lettuce.core.RedisURI>, Bean<io.lettuce.core.resource.ClientResources>, BeanManager, Set<java.lang.annotation.Annotation>, java.lang.String) ,public Set<InjectionPoint> getInjectionPoints() ,public java.lang.String getName() ,public Set<java.lang.annotation.Annotation> getQualifiers() ,public Class<? extends java.lang.annotation.Annotation> getScope() ,public Set<Class<? extends java.lang.annotation.Annotation>> getStereotypes() ,public Set<java.lang.reflect.Type> getTypes() ,public boolean isAlternative() ,public boolean isNullable() <variables>protected final non-sealed BeanManager beanManager,protected final non-sealed Bean<io.lettuce.core.resource.ClientResources> clientResourcesBean,protected final non-sealed java.lang.String name,protected final non-sealed Set<java.lang.annotation.Annotation> qualifiers,protected final non-sealed Bean<io.lettuce.core.RedisURI> redisURIBean
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/caching/ClientSideCaching.java
|
ClientSideCaching
|
get
|
class ClientSideCaching<K, V> implements CacheFrontend<K, V> {
private final CacheAccessor<K, V> cacheAccessor;
private final RedisCache<K, V> redisCache;
private final List<Consumer<K>> invalidationListeners = new CopyOnWriteArrayList<>();
private ClientSideCaching(CacheAccessor<K, V> cacheAccessor, RedisCache<K, V> redisCache) {
this.cacheAccessor = cacheAccessor;
this.redisCache = redisCache;
}
/**
* Enable server-assisted Client side caching for the given {@link CacheAccessor} and {@link StatefulRedisConnection}.
* <p>
* Note that the {@link CacheFrontend} is associated with a Redis connection. Make sure to {@link CacheFrontend#close()
* close} the frontend object to release the Redis connection after use.
*
* @param cacheAccessor the accessor used to interact with the client-side cache.
* @param connection the Redis connection to use. The connection will be associated with {@link CacheFrontend} and must be
* closed through {@link CacheFrontend#close()}.
* @param tracking the tracking parameters.
* @param <K> Key type.
* @param <V> Value type.
* @return the {@link CacheFrontend} for value retrieval.
*/
public static <K, V> CacheFrontend<K, V> enable(CacheAccessor<K, V> cacheAccessor, StatefulRedisConnection<K, V> connection,
TrackingArgs tracking) {
connection.sync().clientTracking(tracking);
return create(cacheAccessor, connection);
}
/**
* Create a server-assisted Client side caching for the given {@link CacheAccessor} and {@link StatefulRedisConnection}.
* This method expects that client key tracking is already configured.
* <p>
* Note that the {@link CacheFrontend} is associated with a Redis connection. Make sure to {@link CacheFrontend#close()
* close} the frontend object to release the Redis connection after use.
*
* @param cacheAccessor the accessor used to interact with the client-side cache.
* @param connection the Redis connection to use. The connection will be associated with {@link CacheFrontend} and must be
* closed through {@link CacheFrontend#close()}.
* @param <K> Key type.
* @param <V> Value type.
* @return the {@link CacheFrontend} for value retrieval.
*/
public static <K, V> CacheFrontend<K, V> create(CacheAccessor<K, V> cacheAccessor,
StatefulRedisConnection<K, V> connection) {
StatefulRedisConnectionImpl<K, V> connectionImpl = (StatefulRedisConnectionImpl) connection;
RedisCodec<K, V> codec = connectionImpl.getCodec();
RedisCache<K, V> redisCache = new DefaultRedisCache<>(connection, codec);
return create(cacheAccessor, redisCache);
}
private static <K, V> CacheFrontend<K, V> create(CacheAccessor<K, V> cacheAccessor, RedisCache<K, V> redisCache) {
ClientSideCaching<K, V> caching = new ClientSideCaching<>(cacheAccessor, redisCache);
redisCache.addInvalidationListener(caching::notifyInvalidate);
caching.addInvalidationListener(cacheAccessor::evict);
return caching;
}
private void notifyInvalidate(K key) {
for (java.util.function.Consumer<K> invalidationListener : invalidationListeners) {
invalidationListener.accept(key);
}
}
@Override
public void close() {
redisCache.close();
}
public void addInvalidationListener(java.util.function.Consumer<K> invalidationListener) {
invalidationListeners.add(invalidationListener);
}
@Override
public V get(K key) {
V value = cacheAccessor.get(key);
if (value == null) {
value = redisCache.get(key);
if (value != null) {
cacheAccessor.put(key, value);
}
}
return value;
}
@Override
public V get(K key, Callable<V> valueLoader) {<FILL_FUNCTION_BODY>}
}
|
V value = cacheAccessor.get(key);
if (value == null) {
value = redisCache.get(key);
if (value == null) {
try {
value = valueLoader.call();
} catch (Exception e) {
throw new ValueRetrievalException(
String.format("Value loader %s failed with an exception for key %s", valueLoader, key), e);
}
if (value == null) {
throw new ValueRetrievalException(
String.format("Value loader %s returned a null value for key %s", valueLoader, key));
}
redisCache.put(key, value);
// register interest in key
redisCache.get(key);
}
cacheAccessor.put(key, value);
}
return value;
| 1,157
| 213
| 1,370
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/support/caching/DefaultRedisCache.java
|
DefaultRedisCache
|
addInvalidationListener
|
class DefaultRedisCache<K, V> implements RedisCache<K, V> {
private final StatefulRedisConnection<K, V> connection;
private final RedisCodec<K, V> codec;
public DefaultRedisCache(StatefulRedisConnection<K, V> connection, RedisCodec<K, V> codec) {
this.connection = connection;
this.codec = codec;
}
@Override
public V get(K key) {
return connection.sync().get(key);
}
@Override
public void put(K key, V value) {
connection.sync().set(key, value);
}
@Override
public void addInvalidationListener(java.util.function.Consumer<? super K> listener) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
connection.close();
}
}
|
connection.addListener(message -> {
if (message.getType().equals("invalidate")) {
List<Object> content = message.getContent(codec::decodeKey);
List<K> keys = (List<K>) content.get(1);
keys.forEach(listener);
}
});
| 236
| 84
| 320
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/tracing/BraveTracing.java
|
Builder
|
createEndpoint
|
class Builder {
private brave.Tracing tracing;
private String serviceName = "redis";
private Consumer<zipkin2.Endpoint.Builder> endpointCustomizer = it -> {
};
private BiConsumer<RedisCommand<Object, Object, Object>, Span> spanCustomizer = (command, span) -> {
};
private boolean includeCommandArgsInSpanTags = true;
private Builder() {
}
/**
* Sets the {@link Tracing}.
*
* @param tracing the Brave {@link brave.Tracing} object, must not be {@code null}.
* @return {@code this} {@link Builder}.
*/
public Builder tracing(brave.Tracing tracing) {
LettuceAssert.notNull(tracing, "Tracing must not be null!");
this.tracing = tracing;
return this;
}
/**
* Sets the name used in the {@link zipkin2.Endpoint}.
*
* @param serviceName the name for the {@link zipkin2.Endpoint}, must not be {@code null}.
* @return {@code this} {@link Builder}.
*/
public Builder serviceName(String serviceName) {
LettuceAssert.notEmpty(serviceName, "Service name must not be null!");
this.serviceName = serviceName;
return this;
}
/**
* Excludes command arguments from {@link Span} tags. Enabled by default.
*
* @return {@code this} {@link Builder}.
*/
public Builder excludeCommandArgsFromSpanTags() {
return includeCommandArgsInSpanTags(false);
}
/**
* Controls the inclusion of command arguments in {@link Span} tags. Enabled by default.
*
* @param includeCommandArgsInSpanTags the flag to enable or disable the inclusion of command args in {@link Span} tags.
* @return {@code this} {@link Builder}.
*/
public Builder includeCommandArgsInSpanTags(boolean includeCommandArgsInSpanTags) {
this.includeCommandArgsInSpanTags = includeCommandArgsInSpanTags;
return this;
}
/**
* Sets an {@link zipkin2.Endpoint} customizer to customize the {@link zipkin2.Endpoint} through its
* {@link zipkin2.Endpoint.Builder}. The customizer is invoked before {@link zipkin2.Endpoint.Builder#build() building}
* the endpoint.
*
* @param endpointCustomizer must not be {@code null}.
* @return {@code this} {@link Builder}.
*/
public Builder endpointCustomizer(Consumer<zipkin2.Endpoint.Builder> endpointCustomizer) {
LettuceAssert.notNull(endpointCustomizer, "Endpoint customizer must not be null!");
this.endpointCustomizer = endpointCustomizer;
return this;
}
/**
* Sets an {@link brave.Span} customizer to customize the {@link brave.Span}. The customizer is invoked before
* {@link Span#finish()} finishing} the span.
*
* @param spanCustomizer must not be {@code null}.
* @return {@code this} {@link Builder}.
*/
public Builder spanCustomizer(Consumer<brave.Span> spanCustomizer) {
LettuceAssert.notNull(spanCustomizer, "Span customizer must not be null!");
this.spanCustomizer = (command, span) -> spanCustomizer.accept(span);
return this;
}
/**
* Sets an {@link brave.Span} customizer to customize the {@link brave.Span} based on the underlying
* {@link RedisCommand}. The customizer is invoked before {@link Span#finish()} finishing} the span.
*
* @param spanCustomizer must not be {@code null}.
* @return {@code this} {@link Builder}.
* @since 6.0
*/
public Builder spanCustomizer(BiConsumer<RedisCommand<Object, Object, Object>, brave.Span> spanCustomizer) {
LettuceAssert.notNull(spanCustomizer, "Span customizer must not be null!");
this.spanCustomizer = spanCustomizer;
return this;
}
/**
* @return a new instance of {@link BraveTracing}
*/
public BraveTracing build() {
LettuceAssert.notNull(this.tracing, "Brave Tracing must not be null!");
return new BraveTracing(this);
}
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean includeCommandArgsInSpanTags() {
return includeCommandArgsInSpanTags;
}
@Override
public TracerProvider getTracerProvider() {
return () -> tracer;
}
@Override
public TraceContextProvider initialTraceContextProvider() {
return BraveTraceContextProvider.INSTANCE;
}
@Override
public Endpoint createEndpoint(SocketAddress socketAddress) {<FILL_FUNCTION_BODY>
|
zipkin2.Endpoint.Builder builder = zipkin2.Endpoint.newBuilder().serviceName(tracingOptions.serviceName);
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
builder.ip(inetSocketAddress.getAddress()).port(inetSocketAddress.getPort());
tracingOptions.customizeEndpoint(builder);
return new BraveEndpoint(builder.build());
}
tracingOptions.customizeEndpoint(builder);
return new BraveEndpoint(builder.build());
| 1,284
| 144
| 1,428
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/tracing/DefaultLettuceObservationConvention.java
|
DefaultLettuceObservationConvention
|
getLowCardinalityKeyValues
|
class DefaultLettuceObservationConvention implements LettuceObservationConvention {
private final boolean includeCommandArgsInSpanTags;
/**
*
*/
DefaultLettuceObservationConvention(boolean includeCommandArgsInSpanTags) {
this.includeCommandArgsInSpanTags = includeCommandArgsInSpanTags;
}
@Override
public KeyValues getLowCardinalityKeyValues(LettuceObservationContext context) {<FILL_FUNCTION_BODY>}
@Override
public KeyValues getHighCardinalityKeyValues(LettuceObservationContext context) {
RedisCommand<?, ?, ?> command = context.getRequiredCommand();
if (includeCommandArgsInSpanTags) {
if (command.getArgs() != null) {
return KeyValues.of(HighCardinalityCommandKeyNames.STATEMENT
.withValue(command.getType().name() + " " + command.getArgs().toCommandString()));
}
}
return KeyValues.empty();
}
@Override
public String getContextualName(LettuceObservationContext context) {
return context.getRequiredCommand().getType().name().toLowerCase(Locale.ROOT);
}
public boolean includeCommandArgsInSpanTags() {
return includeCommandArgsInSpanTags;
}
}
|
Tracing.Endpoint ep = context.getRequiredEndpoint();
KeyValues keyValues = KeyValues.of(LowCardinalityCommandKeyNames.DATABASE_SYSTEM.withValue("redis"), //
LowCardinalityCommandKeyNames.REDIS_COMMAND.withValue(context.getRequiredCommand().getType().name()));
if (ep instanceof SocketAddressEndpoint) {
SocketAddressEndpoint endpoint = (SocketAddressEndpoint) ep;
if (endpoint.getSocketAddress() instanceof InetSocketAddress) {
InetSocketAddress inet = (InetSocketAddress) endpoint.getSocketAddress();
keyValues = keyValues
.and(KeyValues.of(LowCardinalityCommandKeyNames.NET_SOCK_PEER_ADDR.withValue(inet.getHostString()),
LowCardinalityCommandKeyNames.NET_SOCK_PEER_PORT.withValue("" + inet.getPort()),
LowCardinalityCommandKeyNames.NET_TRANSPORT.withValue("IP.TCP")));
} else {
keyValues = keyValues
.and(KeyValues.of(LowCardinalityCommandKeyNames.NET_PEER_NAME.withValue(endpoint.toString()),
LowCardinalityCommandKeyNames.NET_TRANSPORT.withValue("Unix")));
}
}
return keyValues;
| 338
| 334
| 672
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/tracing/LettuceObservationContext.java
|
LettuceObservationContext
|
toString
|
class LettuceObservationContext extends SenderContext<Object> {
private volatile RedisCommand<?, ?, ?> command;
private volatile Endpoint endpoint;
/**
* Create a new {@code LettuceObservationContext} given the {@code serviceName}.
*
* @param serviceName service name.
*/
public LettuceObservationContext(String serviceName) {
super((carrier, key, value) -> {
}, Kind.CLIENT);
setRemoteServiceName(serviceName);
}
/**
* Returns the required {@link RedisCommand} or throws {@link IllegalStateException} if no command is associated with the
* context. Use {@link #hasCommand()} to check if the command is available.
*
* @return the required {@link RedisCommand}.
* @throws IllegalStateException if no command is associated with the context.
*/
public RedisCommand<?, ?, ?> getRequiredCommand() {
RedisCommand<?, ?, ?> local = command;
if (local == null) {
throw new IllegalStateException("LettuceObservationContext is not associated with a Command");
}
return local;
}
/**
* Set the {@link RedisCommand}.
*
* @param command the traced command.
*/
public void setCommand(RedisCommand<?, ?, ?> command) {
this.command = command;
}
/**
* @return {@code true} if the command is available;{@code false} otherwise.
*/
public boolean hasCommand() {
return this.command != null;
}
/**
* Returns the required {@link Endpoint} or throws {@link IllegalStateException} if no endpoint is associated with the
* context.
*
* @return the required {@link Endpoint}.
* @throws IllegalStateException if no endpoint is associated with the context.
*/
public Endpoint getRequiredEndpoint() {
Endpoint local = endpoint;
if (local == null) {
throw new IllegalStateException("LettuceObservationContext is not associated with a Endpoint");
}
return local;
}
/**
* Set the {@link Endpoint}.
*
* @param endpoint the traced endpoint.
*/
public void setEndpoint(Endpoint endpoint) {
this.endpoint = endpoint;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuffer sb = new StringBuffer();
sb.append(getClass().getSimpleName());
sb.append(" [name=").append(getName());
sb.append(", contextualName=").append(getContextualName());
sb.append(", error=").append(getError());
sb.append(", lowCardinalityKeyValues=").append(getLowCardinalityKeyValues());
sb.append(", highCardinalityKeyValues=").append(getHighCardinalityKeyValues());
sb.append(", parentObservation=").append(getParentObservation());
sb.append(", command=").append(command);
sb.append(", endpoint=").append(endpoint);
sb.append(']');
return sb.toString();
| 626
| 187
| 813
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/tracing/MicrometerTracing.java
|
MicrometerSpan
|
start
|
class MicrometerSpan extends Span {
private final LettuceObservationContext context;
private final Function<LettuceObservationContext, Observation> observationFactory;
private Map<String, String> highCardinalityKeyValue;
private Observation observation;
public MicrometerSpan(String serviceName, Function<LettuceObservationContext, Observation> observationFactory) {
this.context = new LettuceObservationContext(serviceName);
this.observationFactory = observationFactory;
}
@Override
public Span start(RedisCommand<?, ?, ?> command) {<FILL_FUNCTION_BODY>}
@Override
public Span name(String name) {
return this;
}
@Override
public Span annotate(String annotation) {
return this;
}
@Override
public Span tag(String key, String value) {
if (this.highCardinalityKeyValue == null) {
this.highCardinalityKeyValue = new HashMap<>();
}
this.highCardinalityKeyValue.put(key, value);
return this;
}
@Override
public Span error(Throwable throwable) {
this.observation.error(throwable);
return this;
}
@Override
public Span remoteEndpoint(Endpoint endpoint) {
this.context.setEndpoint(endpoint);
return this;
}
@Override
public void finish() {
this.observation.stop();
}
}
|
this.context.setCommand(command);
this.observation = observationFactory.apply(context);
if (this.highCardinalityKeyValue != null) {
this.highCardinalityKeyValue.forEach(this.observation::highCardinalityKeyValue);
}
if (command instanceof CompleteableCommand<?>) {
CompleteableCommand<?> completeableCommand = (CompleteableCommand<?>) command;
completeableCommand.onComplete((o, throwable) -> {
if (command.getOutput() != null) {
String error = command.getOutput().getError();
if (error != null) {
this.observation.highCardinalityKeyValue(HighCardinalityCommandKeyNames.ERROR.withValue(error));
} else if (throwable != null) {
error(throwable);
}
}
finish();
});
} else {
throw new IllegalArgumentException("Command " + command
+ " must implement CompleteableCommand to attach Span completion to command completion");
}
this.observation.start();
return this;
| 398
| 284
| 682
|
<no_super_class>
|
redis_lettuce
|
lettuce/src/main/java/io/lettuce/core/tracing/SocketAddressEndpoint.java
|
SocketAddressEndpoint
|
toString
|
class SocketAddressEndpoint implements Tracing.Endpoint {
private final SocketAddress socketAddress;
public SocketAddressEndpoint(SocketAddress socketAddress) {
this.socketAddress = socketAddress;
}
public SocketAddress getSocketAddress() {
return socketAddress;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
if (socketAddress instanceof InetSocketAddress) {
InetSocketAddress inet = (InetSocketAddress) socketAddress;
return inet.getHostString() + ":" + inet.getPort();
}
return socketAddress.toString();
| 100
| 64
| 164
|
<no_super_class>
|
networknt_light-4j
|
light-4j/api-key/src/main/java/com/networknt/apikey/ApiKeyHandler.java
|
ApiKeyHandler
|
handleApiKey
|
class ApiKeyHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(ApiKeyHandler.class);
static final String API_KEY_MISMATCH = "ERR10075";
static ApiKeyConfig config;
private volatile HttpHandler next;
public ApiKeyHandler() {
if(logger.isTraceEnabled()) logger.trace("ApiKeyHandler is loaded.");
config = ApiKeyConfig.load();
}
/**
* This is a constructor for test cases only. Please don't use it.
* @param cfg BasicAuthConfig
*/
@Deprecated
public ApiKeyHandler(ApiKeyConfig cfg) {
config = cfg;
if(logger.isInfoEnabled()) logger.info("ApiKeyHandler is loaded.");
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
// As apiKeys are in the config file, we need to mask them.
List<String> masks = new ArrayList<>();
// if hashEnabled, there is no need to mask in the first place.
if(!config.hashEnabled) {
masks.add("apiKey");
}
ModuleRegistry.registerModule(ApiKeyConfig.CONFIG_NAME, ApiKeyHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ApiKeyConfig.CONFIG_NAME), masks);
}
@Override
public void reload() {
config.reload();
List<String> masks = new ArrayList<>();
if(!config.hashEnabled) {
masks.add("apiKey");
}
ModuleRegistry.registerModule(ApiKeyConfig.CONFIG_NAME, ApiKeyHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ApiKeyConfig.CONFIG_NAME), masks);
if(logger.isInfoEnabled()) logger.info("ApiKeyHandler is reloaded.");
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("ApiKeyHandler.handleRequest starts.");
String requestPath = exchange.getRequestPath();
if(handleApiKey(exchange, requestPath)) {
if(logger.isDebugEnabled()) logger.debug("ApiKeyHandler.handleRequest ends.");
// only goes to the next handler the APIKEY verification is passed successfully.
Handler.next(exchange, next);
}
}
public boolean handleApiKey(HttpServerExchange exchange, String requestPath) {<FILL_FUNCTION_BODY>}
}
|
if(logger.isTraceEnabled()) logger.trace("requestPath = " + requestPath);
if (config.getPathPrefixAuths() != null) {
boolean matched = false;
boolean found = false;
// iterate all the ApiKey entries to find if any of them matches the request path.
for(ApiKey apiKey: config.getPathPrefixAuths()) {
if(requestPath.startsWith(apiKey.getPathPrefix())) {
found = true;
// found the matched prefix, validate the apiKey by getting the header and compare.
String k = exchange.getRequestHeaders().getFirst(apiKey.getHeaderName());
if(config.hashEnabled) {
// hash the apiKey and compare with the one in the config.
try {
matched = HashUtil.validatePassword(k.toCharArray(), apiKey.getApiKey());
if(matched) {
if (logger.isTraceEnabled()) logger.trace("Found valid apiKey with prefix = " + apiKey.getPathPrefix() + " headerName = " + apiKey.getHeaderName());
break;
}
} catch (Exception e) {
// there is no way to get here as the validatePassword will not throw any exception.
logger.error("Exception:", e);
}
} else {
// if not hash enabled, then compare the apiKey directly.
if(apiKey.getApiKey().equals(k)) {
if (logger.isTraceEnabled()) logger.trace("Found matched apiKey with prefix = " + apiKey.getPathPrefix() + " headerName = " + apiKey.getHeaderName());
matched = true;
break;
}
}
}
}
if(!found) {
// the request path is no in the configuration, consider pass and go to the next handler.
return true;
}
if(!matched) {
// at this moment, if not matched, then return an error message.
logger.error("Could not find matched APIKEY for request path " + requestPath);
setExchangeStatus(exchange, API_KEY_MISMATCH, requestPath);
if(logger.isDebugEnabled()) logger.debug("ApiKeyHandler.handleRequest ends with an error.");
exchange.endExchange();
return false;
}
}
return true;
| 723
| 570
| 1,293
|
<no_super_class>
|
networknt_light-4j
|
light-4j/apikey-config/src/main/java/com/networknt/apikey/ApiKeyConfig.java
|
ApiKeyConfig
|
setConfigList
|
class ApiKeyConfig {
private static final Logger logger = LoggerFactory.getLogger(ApiKeyConfig.class);
public static final String CONFIG_NAME = "apikey";
public static final String ENABLED = "enabled";
public static final String HASH_ENABLED = "hashEnabled";
public static final String PATH_PREFIX = "pathPrefix";
public static final String HEADER_NAME = "headerName";
public static final String API_KEY = "apiKey";
public static final String PATH_PREFIX_AUTHS = "pathPrefixAuths";
boolean enabled;
boolean hashEnabled;
List<ApiKey> pathPrefixAuths;
private final Config config;
private Map<String, Object> mappedConfig;
private ApiKeyConfig() {
this(CONFIG_NAME);
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
* @param configName String
*/
private ApiKeyConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
public static ApiKeyConfig load() {
return new ApiKeyConfig();
}
public static ApiKeyConfig load(String configName) {
return new ApiKeyConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isHashEnabled() {
return hashEnabled;
}
public void setHashEnabled(boolean hashEnabled) {
this.hashEnabled = hashEnabled;
}
public List<ApiKey> getPathPrefixAuths() {
return pathPrefixAuths;
}
public void setPathPrefixAuths(List<ApiKey> pathPrefixAuths) {
this.pathPrefixAuths = pathPrefixAuths;
}
private void setConfigData() {
Object object = mappedConfig.get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(HASH_ENABLED);
if(object != null) hashEnabled = Config.loadBooleanValue(HASH_ENABLED, object);
}
private void setConfigList() {<FILL_FUNCTION_BODY>}
public static List<ApiKey> populatePathPrefixAuths(List<Map<String, Object>> values) {
List<ApiKey> pathPrefixAuths = new ArrayList<>();
for(Map<String, Object> value: values) {
ApiKey apiKey = new ApiKey();
apiKey.setPathPrefix((String)value.get(PATH_PREFIX));
apiKey.setHeaderName((String)value.get(HEADER_NAME));
apiKey.setApiKey((String)value.get(API_KEY));
pathPrefixAuths.add(apiKey);
}
return pathPrefixAuths;
}
}
|
// path prefix auth mapping
if (mappedConfig.get(PATH_PREFIX_AUTHS) != null) {
Object object = mappedConfig.get(PATH_PREFIX_AUTHS);
pathPrefixAuths = new ArrayList<>();
if(object instanceof String) {
String s = (String)object;
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("pathPrefixAuth s = " + s);
if(s.startsWith("[")) {
// json format
try {
List<Map<String, Object>> values = Config.getInstance().getMapper().readValue(s, new TypeReference<>() {});
pathPrefixAuths = populatePathPrefixAuths(values);
} catch (Exception e) {
logger.error("Exception:", e);
throw new ConfigException("could not parse the pathPrefixAuth json with a list of string and object.");
}
} else {
throw new ConfigException("pathPrefixAuth must be a list of string object map.");
}
} else if (object instanceof List) {
// the object is a list of map, we need convert it to PathPrefixAuth object.
pathPrefixAuths = populatePathPrefixAuths((List<Map<String, Object>>)object);
} else {
throw new ConfigException("pathPrefixAuth must be a list of string object map.");
}
}
| 814
| 343
| 1,157
|
<no_super_class>
|
networknt_light-4j
|
light-4j/audit-config/src/main/java/com/networknt/audit/AuditConfig.java
|
AuditConfig
|
setConfigData
|
class AuditConfig {
private static final Logger logger = LoggerFactory.getLogger(AuditConfig.class);
public static final String REQUEST_BODY = "requestBody";
public static final String RESPONSE_BODY = "responseBody";
private static final String HEADERS = "headers";
private static final String AUDIT = "audit";
private static final String STATUS_CODE = "statusCode";
private static final String RESPONSE_TIME = "responseTime";
private static final String AUDIT_ON_ERROR = "auditOnError";
private static final String LOG_LEVEL_IS_ERROR = "logLevelIsError";
private static final String MASK = "mask";
private static final String TIMESTAMP_FORMAT = "timestampFormat";
private static final String ENABLED = "enabled";
private static final String REQUEST_BODY_MAX_SIZE = "requestBodyMaxSize";
private static final String RESPONSE_BODY_MAX_SIZE = "responseBodyMaxSize";
private Map<String, Object> mappedConfig;
public static final String CONFIG_NAME = "audit";
private List<String> headerList;
private List<String> auditList;
private final Config config;
// A customized logger appender defined in default logback.xml
private Consumer<String> auditFunc;
private boolean statusCode;
private boolean responseTime;
private boolean auditOnError;
private boolean mask;
private String timestampFormat;
private int requestBodyMaxSize;
private int responseBodyMaxSize;
private boolean enabled;
private AuditConfig() {
this(CONFIG_NAME);
}
private AuditConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setLists();
setLogLevel();
setConfigData();
}
public static AuditConfig load() {
return new AuditConfig();
}
public static AuditConfig load(String configName) {
return new AuditConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setLists();
setLogLevel();
setConfigData();
}
public List<String> getHeaderList() {
return headerList;
}
public List<String> getAuditList() {
return auditList;
}
public Consumer<String> getAuditFunc() {
return auditFunc;
}
public boolean isAuditOnError() {
return auditOnError;
}
public boolean isMask() {
return mask;
}
public boolean isEnabled() { return enabled; }
public boolean isResponseTime() {
return responseTime;
}
public boolean isStatusCode() {
return statusCode;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public boolean hasHeaderList() {
return getHeaderList() != null && getHeaderList().size() > 0;
}
public boolean hasAuditList() {
return getAuditList() != null && getAuditList().size() > 0;
}
public String getTimestampFormat() {
return timestampFormat;
}
public int getRequestBodyMaxSize() { return requestBodyMaxSize; }
public int getResponseBodyMaxSize() { return responseBodyMaxSize; }
Config getConfig() {
return config;
}
private void setLogLevel() {
Object object = getMappedConfig().get(LOG_LEVEL_IS_ERROR);
if(object != null) {
auditOnError = Config.loadBooleanValue(LOG_LEVEL_IS_ERROR, object);
auditFunc = auditOnError ? LoggerFactory.getLogger(Constants.AUDIT_LOGGER)::error : LoggerFactory.getLogger(Constants.AUDIT_LOGGER)::info;
}
}
private void setLists() {
if(getMappedConfig().get(HEADERS) instanceof String) {
String s = (String)getMappedConfig().get(HEADERS);
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
if(s.startsWith("[")) {
// this is a JSON string, and we need to parse it.
try {
headerList = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the headers json with a list of strings.");
}
} else {
// this is a comma separated string.
headerList = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (getMappedConfig().get(HEADERS) instanceof List) {
headerList = (List<String>) getMappedConfig().get(HEADERS);
} else {
throw new ConfigException("headers list is missing or wrong type.");
}
if(getMappedConfig().get(AUDIT) instanceof String) {
String s = (String)getMappedConfig().get(AUDIT);
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
if(s.startsWith("[")) {
// this is a JSON string, and we need to parse it.
try {
auditList = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the audit json with a list of strings.");
}
} else {
// this is a comma separated string.
auditList = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (getMappedConfig().get(AUDIT) instanceof List) {
auditList = (List<String>) getMappedConfig().get(AUDIT);
} else {
throw new ConfigException("audit list is missing or wrong type.");
}
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = getMappedConfig().get(STATUS_CODE);
if(object != null) statusCode = Config.loadBooleanValue(STATUS_CODE, object);
object = getMappedConfig().get(RESPONSE_TIME);
if(object != null) responseTime = Config.loadBooleanValue(RESPONSE_TIME, object);
object = getMappedConfig().get(AUDIT_ON_ERROR);
if(object != null) auditOnError = Config.loadBooleanValue(AUDIT_ON_ERROR, object);
object = getMappedConfig().get(MASK);
if(object != null) mask = Config.loadBooleanValue(MASK, object);
object = mappedConfig.get(REQUEST_BODY_MAX_SIZE);
if(object != null) requestBodyMaxSize = Config.loadIntegerValue(REQUEST_BODY_MAX_SIZE, object);
object = mappedConfig.get(RESPONSE_BODY_MAX_SIZE);
if(object != null) responseBodyMaxSize = Config.loadIntegerValue(RESPONSE_BODY_MAX_SIZE, object);
object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
timestampFormat = (String)getMappedConfig().get(TIMESTAMP_FORMAT);
| 1,590
| 337
| 1,927
|
<no_super_class>
|
networknt_light-4j
|
light-4j/balance/src/main/java/com/networknt/balance/ConsistentHashLoadBalance.java
|
ConsistentHashLoadBalance
|
doSelect
|
class ConsistentHashLoadBalance implements LoadBalance {
static Logger logger = LoggerFactory.getLogger(ConsistentHashLoadBalance.class);
// TODO need to keep a lookup table to map the hash to host:ip, using index in the
// urls is not reliable as the sequence will be changed after service restart.
// maybe we need somehow to have an instanceId for each service instance. UUID will
// do the job. It will be registered as extra parameter like public key and public
// key certificate of the service.
public ConsistentHashLoadBalance() {
if(logger.isInfoEnabled()) logger.info("A ConsistentHashLoadBalance instance is started");
}
@Override
public URL select(List<URL> urls, String serviceId, String tag, String requestKey) {
URL url = null;
if (urls.size() > 1) {
url = doSelect(urls, requestKey);
} else if (urls.size() == 1) {
url = urls.get(0);
}
return url;
}
private URL doSelect(List<URL> urls, String requestKey) {<FILL_FUNCTION_BODY>}
private int getHash(String hashKey) {
int hashcode;
if(hashKey != null) {
hashcode = hashKey.hashCode();
} else {
hashcode = 0;
}
return getPositive(hashcode);
}
}
|
int hash = getHash(requestKey);
// convert hash to an index in urls. This assumes there are the same number
// This will be changed later on.
return urls.get(hash % urls.size());
| 369
| 58
| 427
|
<no_super_class>
|
networknt_light-4j
|
light-4j/balance/src/main/java/com/networknt/balance/LocalFirstLoadBalance.java
|
LocalFirstLoadBalance
|
ipToLong
|
class LocalFirstLoadBalance extends RoundRobinLoadBalance {
static Logger logger = LoggerFactory.getLogger(LocalFirstLoadBalance.class);
static String ip = "0.0.0.0";
static{
// get the address of the localhost
InetAddress inetAddress = Util.getInetAddress();
// get ip address for this host.
ip = inetAddress.getHostAddress();
}
public LocalFirstLoadBalance() {
if(logger.isInfoEnabled()) logger.info("A LocalFirstLoadBalance instance is started");
}
/**
* Local first requestKey is not used as it is ip on the localhost. It first needs to
* find a list of urls on the localhost for the service, and then round robin in the
* list to pick up one.
*
* Currently, this load balance is only used if you deploy the service as standalone
* java process on data center hosts. We need to find a way to identify two VMs or two
* docker containers sitting on the same physical machine in the future to improve it.
*
* It is also suitable if your services are built on top of light-hybrid-4j and want
* to use the remote interface for service to service communication.
*
* @param urls List
* @param serviceId String
* @param tag String
* @param requestKey String
* @return URL
*/
@Override
public URL select(List<URL> urls, String serviceId, String tag, String requestKey) {
String key = tag == null ? serviceId : serviceId + "|" + tag;
// search for a URL in the same ip first
List<URL> localUrls = searchLocalUrls(urls, ip);
if(localUrls.size() > 0) {
if(localUrls.size() == 1) {
return localUrls.get(0);
} else {
// round robin within localUrls
return doSelect(localUrls, key);
}
} else {
// round robin within urls
return doSelect(urls, key);
}
}
private List<URL> searchLocalUrls(List<URL> urls, String ip) {
List<URL> localUrls = new ArrayList<URL>();
long local = ipToLong(ip);
for (URL url : urls) {
long tmp = ipToLong(url.getHost());
if (local != 0 && local == tmp) {
localUrls.add(url);
}
}
return localUrls;
}
public static long ipToLong(final String address) {<FILL_FUNCTION_BODY>}
}
|
final String[] addressBytes = address.split("\\.");
int length = addressBytes.length;
if (length < 3) {
return 0;
}
long ip = 0;
try {
for (int i = 0; i < 4; i++) {
ip <<= 8;
ip |= Integer.parseInt(addressBytes[i]);
}
} catch (Exception e) {
logger.warn("Warn ipToLong address is wrong: address =" + address);
}
return ip;
| 676
| 135
| 811
|
<methods>public void <init>() ,public com.networknt.registry.URL select(List<com.networknt.registry.URL>, java.lang.String, java.lang.String, java.lang.String) <variables>static Logger logger,Map<java.lang.String,java.util.concurrent.atomic.AtomicInteger> serviceIdx
|
networknt_light-4j
|
light-4j/balance/src/main/java/com/networknt/balance/RoundRobinLoadBalance.java
|
RoundRobinLoadBalance
|
select
|
class RoundRobinLoadBalance implements LoadBalance {
static Logger logger = LoggerFactory.getLogger(RoundRobinLoadBalance.class);
// cache the idx for each service so that the index is per service for the round robin.
Map<String, AtomicInteger> serviceIdx = new ConcurrentHashMap<>();
public RoundRobinLoadBalance() {
if(logger.isInfoEnabled()) logger.info("A RoundRobinLoadBalance instance is started");
}
/**
* Round robin requestKey is not used as it should be null, the url will
* be selected from the list base on an instance idx so every url has the
* same priority.
*
* @param urls List
* @param serviceId String
* @param tag String
* @param requestKey String
* @return Url
*/
@Override
public URL select(List<URL> urls, String serviceId, String tag, String requestKey) {<FILL_FUNCTION_BODY>}
protected URL doSelect(List<URL> urls, String key) {
int index = getNextPositive(key);
for (int i = 0; i < urls.size(); i++) {
URL url = urls.get((i + index) % urls.size());
if (url != null) {
return url;
}
}
return null;
}
// get positive int
private int getNextPositive(String key) {
AtomicInteger idx = serviceIdx.get(key);
if(idx == null) {
idx = new AtomicInteger((int)(Math.random()*10));
serviceIdx.put(key, idx);
}
return getPositive(idx.incrementAndGet());
}
}
|
URL url = null;
if (urls.size() > 1) {
String key = tag == null ? serviceId : serviceId + "|" + tag;
url = doSelect(urls, key);
} else if (urls.size() == 1) {
url = urls.get(0);
}
return url;
| 450
| 90
| 540
|
<no_super_class>
|
networknt_light-4j
|
light-4j/basic-config/src/main/java/com/networknt/basicauth/BasicAuthConfig.java
|
BasicAuthConfig
|
setConfigData
|
class BasicAuthConfig {
public static final String CONFIG_NAME = "basic-auth";
private static final String ENABLED = "enabled";
private static final String ENABLE_AD = "enableAD";
private static final String ALLOW_ANONYMOUS = "allowAnonymous";
private static final String ALLOW_BEARER_TOKEN = "allowBearerToken";
private static final String USERS = "users";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String PATHS = "paths";
public static final String ANONYMOUS = "anonymous";
public static final String BEARER = "bearer";
boolean enabled;
boolean enableAD;
boolean allowAnonymous;
boolean allowBearerToken;
Map<String, UserAuth> users; // the key is the username to locate the object
private final Config config;
private Map<String, Object> mappedConfig;
public BasicAuthConfig() {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigUser();
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
* @param configName String
*/
public BasicAuthConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigUser();
}
public static BasicAuthConfig load() {
return new BasicAuthConfig();
}
public static BasicAuthConfig load(String configName) {
return new BasicAuthConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigUser();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnableAD() {
return enabled;
}
public void setEnableAD(boolean enabled) {
this.enableAD = enabled;
}
public boolean isAllowAnonymous() {
return allowAnonymous;
}
public void setAllowAnonymous(boolean allowAnonymous) {
this.allowAnonymous = allowAnonymous;
}
public boolean isAllowBearerToken() {
return allowBearerToken;
}
public void setAllowBearerToken(boolean allowBearerToken) {
this.allowBearerToken = allowBearerToken;
}
public Map<String, UserAuth> getUsers() { return users; }
private void setConfigData() {<FILL_FUNCTION_BODY>}
private void setConfigUser() {
if (mappedConfig.get(USERS) instanceof List) {
List<Map<String, Object>> userList = (List) mappedConfig.get(USERS);
populateUsers(userList);
} else if (mappedConfig.get(USERS) instanceof String) {
// The value can be a string from the config server or in values.yml
// It must start with '[' in the beginning.
String s = (String)mappedConfig.get(USERS);
s = s.trim();
if(!s.startsWith("[")) {
throw new ConfigException("The string value must be start with [ as a JSON list");
}
List<Map<String, Object>> userList = JsonMapper.string2List(s);
populateUsers(userList);
} else {
// if the basic auth is enabled and users is empty, we throw the ConfigException.
if(enabled) {
throw new ConfigException("Basic Auth is enabled but there is no users definition.");
}
}
}
private void populateUsers(List<Map<String, Object>> userList) {
users = new HashMap<>();
userList.forEach(user -> {
if (user instanceof Map) {
// the password might be encrypted.
UserAuth userAuth = new UserAuth();
user.forEach((k, v) -> {
if (USERNAME.equals(k)) {
userAuth.setUsername((String) v);
}
if (PASSWORD.equals(k)) {
userAuth.setPassword((String) v);
}
if (PATHS.equals(k)) {
if (v instanceof List) {
userAuth.setPaths((List) v);
} else {
throw new ConfigException("Paths must be an array of strings.");
}
}
});
users.put(userAuth.getUsername(), userAuth);
}
});
}
}
|
Object object = mappedConfig.get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(ENABLE_AD);
if(object != null) enableAD = Config.loadBooleanValue(ENABLE_AD, object);
object = mappedConfig.get(ALLOW_ANONYMOUS);
if(object != null) allowAnonymous = Config.loadBooleanValue(ALLOW_ANONYMOUS, object);
object = mappedConfig.get(ALLOW_BEARER_TOKEN);
if(object != null) allowBearerToken = Config.loadBooleanValue(ALLOW_BEARER_TOKEN, object);
| 1,199
| 176
| 1,375
|
<no_super_class>
|
networknt_light-4j
|
light-4j/body-config/src/main/java/com/networknt/body/BodyConfig.java
|
BodyConfig
|
setConfigData
|
class BodyConfig {
private static final Logger logger = LoggerFactory.getLogger(BodyConfig.class);
public static final String CONFIG_NAME = "body";
private static final String ENABLED = "enabled";
private static final String CACHE_REQUEST_BODY = "cacheRequestBody";
private static final String CACHE_RESPONSE_BODY = "cacheResponseBody";
private static final String LOG_FULL_REQUEST_BODY = "logFullRequestBody";
private static final String LOG_FULL_RESPONSE_BODY = "logFullResponseBody";
boolean enabled;
boolean cacheRequestBody;
boolean cacheResponseBody;
boolean logFullRequestBody;
boolean logFullResponseBody;
private final Config config;
private Map<String, Object> mappedConfig;
public BodyConfig() {
this(CONFIG_NAME);
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
* @param configName String
*/
private BodyConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static BodyConfig load() {
return new BodyConfig();
}
public static BodyConfig load(String configName) {
return new BodyConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public boolean isEnabled() {
return enabled;
}
public boolean isCacheRequestBody() {
return cacheRequestBody;
}
public boolean isCacheResponseBody() {
return cacheResponseBody;
}
public boolean isLogFullRequestBody() { return logFullRequestBody; }
public boolean isLogFullResponseBody() { return logFullResponseBody; }
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = mappedConfig.get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(CACHE_REQUEST_BODY);
if(object != null) cacheRequestBody = Config.loadBooleanValue(CACHE_REQUEST_BODY, object);
object = mappedConfig.get(CACHE_RESPONSE_BODY);
if(object != null) cacheResponseBody = Config.loadBooleanValue(CACHE_RESPONSE_BODY, object);
object = mappedConfig.get(LOG_FULL_REQUEST_BODY);
if(object != null) logFullRequestBody = Config.loadBooleanValue(LOG_FULL_REQUEST_BODY, object);
object = mappedConfig.get(LOG_FULL_RESPONSE_BODY);
if(object != null) logFullResponseBody = Config.loadBooleanValue(LOG_FULL_RESPONSE_BODY, object);
| 534
| 256
| 790
|
<no_super_class>
|
networknt_light-4j
|
light-4j/body/src/main/java/com/networknt/body/BodyConverter.java
|
BodyConverter
|
convert
|
class BodyConverter {
public static Map<String, Object> convert(FormData data) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> map = new HashMap<>();
for (String key : data) {
if (data.get(key).size() == 1) {
// If the form data is file, read it as FileItem, else read as String.
if (data.getFirst(key).getFileName() == null) {
String value = data.getFirst(key).getValue();
map.put(key, value);
} else {
FormData.FileItem value = data.getFirst(key).getFileItem();
map.put(key, value);
}
} else if (data.get(key).size() > 1) {
List<Object> list = new ArrayList<>();
for (FormData.FormValue value : data.get(key)) {
// If the form data is file, read it as FileItem, else read as String.
if (value.getFileName() == null) {
list.add(value.getValue());
} else {
list.add(value.getFileItem());
}
}
map.put(key, list);
}
// ignore size == 0
}
return map;
| 36
| 289
| 325
|
<no_super_class>
|
networknt_light-4j
|
light-4j/body/src/main/java/com/networknt/body/BodyHandler.java
|
BodyHandler
|
handleRequest
|
class BodyHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(BodyHandler.class);
static final String CONTENT_TYPE_MISMATCH = "ERR10015";
// request body will be parsed during validation and it is attached to the exchange, in JSON,
// it could be a map or list. So treat it as Object in the attachment.
public static final AttachmentKey<Object> REQUEST_BODY = AttachmentConstants.REQUEST_BODY;
public static final AttachmentKey<String> REQUEST_BODY_STRING = AttachmentConstants.REQUEST_BODY_STRING;
public static BodyConfig config;
private volatile HttpHandler next;
public BodyHandler() {
if (logger.isInfoEnabled()) logger.info("BodyHandler is loaded.");
config = BodyConfig.load();
}
/**
* Please don't use this constructor as it is designed for testing only.
* @param configName String
* @deprecated
*/
public BodyHandler(String configName) {
if (logger.isInfoEnabled()) logger.info("BodyHandler is loaded.");
config = BodyConfig.load(configName);
}
/**
* Check the header starts with application/json and parse it into map or list
* based on the first character "{" or "[". Otherwise, check the header starts
* with application/x-www-form-urlencoded or multipart/form-data and parse it
* into formdata
*
* @param exchange HttpServerExchange
* @throws Exception Exception
*/
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Method used to parse the body into FormData and attach it into exchange
*
* @param exchange exchange to be attached
* @throws IOException
*/
private void attachFormDataBody(final HttpServerExchange exchange) throws IOException {
Object data;
FormParserFactory formParserFactory = FormParserFactory.builder().build();
FormDataParser parser = formParserFactory.createParser(exchange);
if (parser != null) {
FormData formData = parser.parseBlocking();
data = BodyConverter.convert(formData);
exchange.putAttachment(AttachmentConstants.REQUEST_BODY, data);
} else {
InputStream inputStream = exchange.getInputStream();
exchange.putAttachment(AttachmentConstants.REQUEST_BODY, inputStream);
}
}
/**
* Method used to parse the body into a Map or a List and attach it into exchange
*
* @param exchange exchange to be attached
* @param string unparsed request body
* @throws IOException IO Exception
* @return boolean
*/
private boolean attachJsonBody(final HttpServerExchange exchange, String string) throws IOException {
Object body;
if (string != null) {
string = string.trim();
if (string.startsWith("{")) {
body = Config.getInstance().getMapper().readValue(string, new TypeReference<Map<String, Object>>() {
});
} else if (string.startsWith("[")) {
body = Config.getInstance().getMapper().readValue(string, new TypeReference<List<Object>>() {
});
} else {
// error here. The content type in head doesn't match the body.
setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, "application/json");
return false;
}
exchange.putAttachment(AttachmentConstants.REQUEST_BODY, body);
}
// if this is the get or delete request, the body wil be null, but we still need to go to the next handler.
return true;
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(BodyConfig.CONFIG_NAME, BodyHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(BodyConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(BodyConfig.CONFIG_NAME, BodyHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(BodyConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("BodyHandler is reloaded.");
}
}
|
if(logger.isDebugEnabled()) logger.debug("BodyHandler.handleRequest starts.");
// parse the body to map or list if content type is application/json
String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if (contentType != null) {
if (exchange.isInIoThread()) {
exchange.dispatch(this);
return;
}
exchange.startBlocking();
try {
if (contentType.startsWith("application/json")) {
InputStream inputStream = exchange.getInputStream();
String unparsedRequestBody = StringUtils.inputStreamToString(inputStream, StandardCharsets.UTF_8);
// attach the unparsed request body into exchange if the cacheRequestBody is enabled in body.yml
if (config.isCacheRequestBody()) {
exchange.putAttachment(AttachmentConstants.REQUEST_BODY_STRING, unparsedRequestBody);
}
// attach the parsed request body into exchange if the body parser is enabled
boolean res = attachJsonBody(exchange, unparsedRequestBody);
// this will ensure that the next handler won't be called.
if (!res) {
if(logger.isDebugEnabled()) logger.debug("BodyHandler.handleRequest ends with an error.");
return;
}
} else if (contentType.startsWith("text/plain")) {
InputStream inputStream = exchange.getInputStream();
String unparsedRequestBody = StringUtils.inputStreamToString(inputStream, StandardCharsets.UTF_8);
exchange.putAttachment(AttachmentConstants.REQUEST_BODY, unparsedRequestBody);
} else if (contentType.startsWith("multipart/form-data") || contentType.startsWith("application/x-www-form-urlencoded")) {
// attach the parsed request body into exchange if the body parser is enabled
attachFormDataBody(exchange);
} else {
InputStream inputStream = exchange.getInputStream();
exchange.putAttachment(AttachmentConstants.REQUEST_BODY, inputStream);
}
} catch (IOException e) {
logger.error("IOException: ", e);
setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, contentType);
if(logger.isDebugEnabled()) logger.debug("BodyHandler.handleRequest ends with an error.");
return;
}
}
if(logger.isDebugEnabled()) logger.debug("BodyHandler.handleRequest ends.");
Handler.next(exchange, next);
| 1,182
| 622
| 1,804
|
<no_super_class>
|
networknt_light-4j
|
light-4j/body/src/main/java/com/networknt/body/RequestBodyInterceptor.java
|
RequestBodyInterceptor
|
handleRequest
|
class RequestBodyInterceptor implements RequestInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(RequestBodyInterceptor.class);
public BodyConfig config;
private volatile HttpHandler next;
public RequestBodyInterceptor() {
if (LOG.isInfoEnabled())
LOG.info("RequestBodyInterceptor is loaded.");
config = BodyConfig.load();
}
/**
* Check the header starts with application/json and parse it into map or list
* based on the first character "{" or "[".
*
* @param exchange HttpServerExchange
* @throws Exception Exception
*/
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
private boolean handleBody(final HttpServerExchange ex, String body, String contentType) {
if (this.isJsonData(contentType))
return this.attachJsonBody(ex, body);
else if (this.isXmlData(contentType))
return this.attachXmlBody(ex, body);
else if (this.isFormData(contentType))
return this.attachFormDataBody(ex, body);
else
return false;
}
/**
* Method used to parse the body into a Map or a List and attach it into exchange.
*
* @param ex - current exchange
* @param str - byte buffer body as a string
* @return - true if successful
*/
public boolean attachJsonBody(final HttpServerExchange ex, String str) {
str = str.trim();
if (str.charAt(0) == JSON_MAP_OBJECT_STARTING_CHAR) {
this.cacheRequestBody(ex, str);
return this.parseJsonMapObject(ex, AttachmentConstants.REQUEST_BODY, str);
} else if (str.charAt(0) == JSON_ARRAY_OBJECT_STARTING_CHAR) {
this.cacheRequestBody(ex, str);
return this.parseJsonArrayObject(ex, AttachmentConstants.REQUEST_BODY, str);
}
setExchangeStatus(ex, CONTENT_TYPE_MISMATCH, ContentType.APPLICATION_JSON.value());
return false;
}
public boolean attachXmlBody(HttpServerExchange exchange, String s) {
// TODO
this.cacheRequestBody(exchange, s);
return true;
}
/**
* Method used to parse the body into FormData and attach it into exchange
*
* @param exchange exchange to be attached
* @param s the string of the request body
* @return boolean to indicate if attached.
*/
public boolean attachFormDataBody(final HttpServerExchange exchange, String s) {
// TODO
this.cacheRequestBody(exchange, s);
return true;
}
private void cacheRequestBody(HttpServerExchange exchange, String s) {
if (this.config.isCacheRequestBody())
exchange.putAttachment(AttachmentConstants.REQUEST_BODY_STRING, s);
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(BodyConfig.CONFIG_NAME, RequestBodyInterceptor.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(BodyConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(BodyConfig.CONFIG_NAME, RequestBodyInterceptor.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(BodyConfig.CONFIG_NAME), null);
if (LOG.isInfoEnabled())
LOG.info("RequestBodyInterceptor is reloaded.");
}
@Override
public boolean isRequiredContent() {
return true;
}
}
|
if (LOG.isDebugEnabled())
LOG.debug("RequestBodyInterceptor.handleRequest starts.");
if (this.shouldAttachBody(exchange.getRequestHeaders())) {
var existing = (PooledByteBuffer[]) exchange.getAttachment(AttachmentConstants.BUFFERED_REQUEST_DATA_KEY);
if(LOG.isTraceEnabled())
LOG.trace("request body exists in exchange attachment = {}", existing != null);
if (existing != null) {
if (LOG.isTraceEnabled())
LOG.trace("Attach request body requirement is met and the byte buffer pool exists.");
var completeBody = BuffersUtils.toString(existing, StandardCharsets.UTF_8);
var contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if (LOG.isTraceEnabled()) {
// this config flag should only be enabled on non-production environment for troubleshooting purpose.
if(config.isLogFullRequestBody())
LOG.trace("contentType = " + contentType + " request body = " + completeBody);
else
LOG.trace("contentType = " + contentType + " request body = " + (completeBody.length() > 16384 ? completeBody.substring(0, 16384) : completeBody));
}
boolean attached = this.handleBody(exchange, completeBody, contentType);
if (!attached && LOG.isErrorEnabled())
LOG.error("Failed to attach the request body to the exchange!");
else if (LOG.isTraceEnabled())
LOG.trace("Request body was attached to exchange");
} else if (LOG.isTraceEnabled())
LOG.trace("Request body interceptor is skipped due to the request path is not in request-injection.appliedBodyInjectionPathPrefixes configuration");
}
if (LOG.isDebugEnabled())
LOG.debug("RequestBodyInterceptor.handleRequest ends.");
| 1,059
| 484
| 1,543
|
<no_super_class>
|
networknt_light-4j
|
light-4j/body/src/main/java/com/networknt/body/ResponseBodyInterceptor.java
|
ResponseBodyInterceptor
|
handleRequest
|
class ResponseBodyInterceptor implements ResponseInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(ResponseBodyInterceptor.class);
private final BodyConfig config;
private volatile HttpHandler next;
public ResponseBodyInterceptor() {
if (LOG.isInfoEnabled())
LOG.info("ResponseBodyInterceptor is loaded");
this.config = BodyConfig.load();
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(BodyConfig.CONFIG_NAME, ResponseBodyInterceptor.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(BodyConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(BodyConfig.CONFIG_NAME, ResponseBodyInterceptor.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(BodyConfig.CONFIG_NAME), null);
if (LOG.isInfoEnabled())
LOG.info("ResponseBodyInterceptor is reloaded.");
}
@Override
public boolean isRequiredContent() {
return true;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
private boolean handleBody(final HttpServerExchange ex, String body, String contentType) {
if (this.isJsonData(contentType))
return this.attachJsonBody(ex, body);
else if (this.isXmlData(contentType))
return this.attachXmlBody(ex, body);
else if (this.isFormData(contentType))
return this.attachFormDataBody(ex, body);
else
return false;
}
/**
* Method used to parse the body into a Map or a List and attach it into exchange.
*
* @param ex - current exchange
* @param str - byte buffer body as a string
* @return - true if successful
*/
private boolean attachJsonBody(final HttpServerExchange ex, String str) {
str = str.trim();
if(str.isEmpty()) {
// if an empty string is passed in, we should not try to parse it. Just cache it.
this.cacheResponseBody(ex, str);
return true;
}
if (str.charAt(0) == JSON_MAP_OBJECT_STARTING_CHAR) {
this.cacheResponseBody(ex, str);
return this.parseJsonMapObject(ex, AttachmentConstants.REQUEST_BODY, str);
} else if (str.charAt(0) == JSON_ARRAY_OBJECT_STARTING_CHAR) {
this.cacheResponseBody(ex, str);
return this.parseJsonArrayObject(ex, AttachmentConstants.REQUEST_BODY, str);
}
setExchangeStatus(ex, CONTENT_TYPE_MISMATCH, ContentType.APPLICATION_JSON.value());
return false;
}
public boolean attachXmlBody(HttpServerExchange ex, String str) {
this.cacheResponseBody(ex, str);
return true;
}
public boolean attachFormDataBody(HttpServerExchange ex, String str) {
this.cacheResponseBody(ex, str);
return true;
}
private void cacheResponseBody(HttpServerExchange exchange, String s) {
if (this.config.isCacheRequestBody())
exchange.putAttachment(AttachmentConstants.RESPONSE_BODY_STRING, s);
}
}
|
if (LOG.isDebugEnabled())
LOG.debug("ResponseBodyInterceptor.handleRequest starts.");
if (this.shouldAttachBody(exchange.getResponseHeaders())) {
var existing = this.getBuffer(exchange);
if (existing != null) {
if (LOG.isTraceEnabled())
LOG.trace("Attach response body requirement is met and the byte buffer pool exists.");
var completeBody = BuffersUtils.toString(existing, StandardCharsets.UTF_8);
var contentType = exchange.getResponseHeaders().getFirst(Headers.CONTENT_TYPE);
if (LOG.isTraceEnabled()) {
if(config.isLogFullResponseBody())
LOG.trace("contentType = " + contentType + " response body = " + completeBody);
else
LOG.trace("contentType = " + contentType + " response body = " + (completeBody.length() > 16384 ? completeBody.substring(0, 16384) : completeBody));
}
boolean attached = this.handleBody(exchange, completeBody, contentType);
if (!attached && LOG.isErrorEnabled())
LOG.error("Failed to attach the request body to the exchange!");
}
}
if (LOG.isDebugEnabled())
LOG.debug("ResponseBodyInterceptor.handleRequest ends.");
| 982
| 341
| 1,323
|
<no_super_class>
|
networknt_light-4j
|
light-4j/cache-manager/src/main/java/com/networknt/cache/CacheConfig.java
|
CacheConfig
|
setConfigList
|
class CacheConfig {
private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);
public static final String CONFIG_NAME = "cache";
public static final String CACHES = "caches";
public static final String CACHE_NAME = "cacheName";
public static final String EXPIRY_IN_MINUTES = "expiryInMinutes";
public static final String MAX_SIZE = "maxSize";
List<CacheItem> caches;
private final Config config;
private Map<String, Object> mappedConfig;
private CacheConfig() {
this(CONFIG_NAME);
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
* @param configName String
*/
private CacheConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigList();
}
public static CacheConfig load() {
return new CacheConfig();
}
public static CacheConfig load(String configName) {
return new CacheConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigList();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public List<CacheItem> getCaches() {
return caches;
}
public void setCaches(List<CacheItem> caches) {
this.caches = caches;
}
public void setConfigList() {<FILL_FUNCTION_BODY>}
}
|
if (mappedConfig.get(CACHES) != null) {
Object object = mappedConfig.get(CACHES);
caches = new ArrayList<>();
if(object instanceof String) {
String s = (String)object;
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("caches s = " + s);
if(s.startsWith("[")) {
// json format
try {
caches = Config.getInstance().getMapper().readValue(s, new TypeReference<List<CacheItem>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the caches json with a list of string and object.");
}
} else {
throw new ConfigException("caches must be a list of string object map.");
}
} else if (object instanceof List) {
// the object is a list of map, we need convert it to CacheItem object.
List<Map<String, Object>> values = (List<Map<String, Object>>)object;
for(Map<String, Object> value: values) {
CacheItem cacheItem = new CacheItem();
cacheItem.setCacheName((String)value.get(CACHE_NAME));
cacheItem.setMaxSize((Integer)value.get(MAX_SIZE));
cacheItem.setExpiryInMinutes((Integer)value.get(EXPIRY_IN_MINUTES));
caches.add(cacheItem);
}
} else {
throw new ConfigException("caches must be a list of string object map.");
}
}
| 428
| 398
| 826
|
<no_super_class>
|
networknt_light-4j
|
light-4j/caffeine-cache/src/main/java/com/networknt/cache/CaffeineCacheManager.java
|
CaffeineCacheManager
|
getSize
|
class CaffeineCacheManager implements CacheManager {
private final Map<String, Cache<Object, Object>> caches = new ConcurrentHashMap<>();
public CaffeineCacheManager() {
if(logger.isInfoEnabled()) logger.info("CaffeineCacheManager is constructed.");
}
@Override
public void addCache(String cacheName, long maximumSize, long expiryInMinutes) {
Cache<Object, Object> cache = Caffeine.newBuilder()
.maximumSize(maximumSize)
.expireAfterWrite(expiryInMinutes, TimeUnit.MINUTES)
.build();
caches.put(cacheName, cache);
}
@Override
public void put(String cacheName, String key, Object value) {
Cache<Object, Object> cache = caches.get(cacheName);
if (cache != null) {
cache.put(key, value);
}
}
@Override
public Object get(String cacheName, String key) {
Cache<Object, Object> cache = caches.get(cacheName);
if (cache != null) {
return cache.getIfPresent(key);
}
return null;
}
@Override
public void delete(String cacheName, String key) {
Cache<Object, Object> cache = caches.get(cacheName);
if (cache != null) {
cache.invalidate(key);
}
}
@Override
public void removeCache(String cacheName) {
Cache<Object, Object> cache = caches.get(cacheName);
if (cache != null) {
cache.invalidateAll();
caches.remove(cacheName);
}
}
@Override
public int getSize(String cacheName) {<FILL_FUNCTION_BODY>}
}
|
Cache<Object, Object> cache = caches.get(cacheName);
if (cache != null) {
return (int) cache.estimatedSize();
} else {
return 0;
}
| 467
| 57
| 524
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/DefaultAsyncResult.java
|
DefaultAsyncResult
|
fail
|
class DefaultAsyncResult<T> implements AsyncResult<T> {
private Throwable cause;
private T result;
/**
* @deprecated should be created use {@link #succeed(Object)} or {@link #fail(Throwable)}
* @param cause Throwable throwable exceptions
* @param result result
*/
@Deprecated
public DefaultAsyncResult(Throwable cause, T result) {
this.cause = cause;
this.result = result;
}
public static <T> AsyncResult<T> succeed(T result) {
return new DefaultAsyncResult<>(null, result);
}
public static AsyncResult<Void> succeed() {
return succeed(null);
}
public static <T> AsyncResult<T> fail(Throwable cause) {<FILL_FUNCTION_BODY>}
public static <T> AsyncResult<T> fail(AsyncResult<?> result) {
return fail(result.cause());
}
@Override
public T result() {
return result;
}
@Override
public Throwable cause() {
return cause;
}
@Override
public boolean succeeded() {
return cause == null;
}
@Override
public boolean failed() {
return cause != null;
}
}
|
if (cause == null) {
throw new IllegalArgumentException("cause argument cannot be null");
}
return new DefaultAsyncResult<>(cause, null);
| 342
| 42
| 384
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/circuitbreaker/CircuitBreaker.java
|
CircuitBreaker
|
call
|
class CircuitBreaker {
private Supplier<CompletableFuture<ClientResponse>> supplier;
private static AtomicInteger timeoutCount;
private long lastErrorTime;
public CircuitBreaker(Supplier<CompletableFuture<ClientResponse>> supplier) {
this.supplier = supplier;
this.timeoutCount = new AtomicInteger(0);
}
public ClientResponse call() throws TimeoutException, ExecutionException, InterruptedException {<FILL_FUNCTION_BODY>}
private State checkState() {
ClientConfig clientConfig = ClientConfig.get();
boolean isExtrapolatedResetTimeout = Instant.now().toEpochMilli() - lastErrorTime > clientConfig.getResetTimeout();
boolean isExtrapolatedErrorThreshold = timeoutCount.get() >= clientConfig.getErrorThreshold();
if (isExtrapolatedErrorThreshold && isExtrapolatedResetTimeout) {
return State.HALF_OPEN;
}
if (timeoutCount.get() >= clientConfig.getErrorThreshold()) {
return State.OPEN;
}
return State.CLOSE;
}
private void recordTimeout() {
timeoutCount.getAndIncrement();
lastErrorTime = Instant.now().toEpochMilli();
}
}
|
State state = checkState();
try {
if (State.OPEN == state) {
throw new IllegalStateException("circuit is opened.");
}
ClientResponse clientResponse = supplier.get().get(ClientConfig.get().getTimeout(), TimeUnit.MILLISECONDS);
timeoutCount = new AtomicInteger(0);
return clientResponse;
} catch (InterruptedException | ExecutionException e) {
throw e;
} catch (TimeoutException e) {
recordTimeout();
throw e;
}
| 323
| 137
| 460
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/http/Http2ClientCompletableFutureNoRequest.java
|
Http2ClientCompletableFutureNoRequest
|
completed
|
class Http2ClientCompletableFutureNoRequest extends CompletableFuture<ClientResponse> implements ClientCallback<ClientExchange> {
private Logger logger = LoggerFactory.getLogger(Http2ClientCompletableFutureNoRequest.class);
@Override
public void completed(ClientExchange result) {<FILL_FUNCTION_BODY>}
@Override
public void failed(IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
}
|
result.setResponseListener(new ClientCallback<ClientExchange>() {
@Override
public void completed(final ClientExchange result) {
new StringReadChannelListener(result.getConnection().getBufferPool()) {
@Override
protected void stringDone(String string) {
if (logger.isDebugEnabled()) {
logger.debug("Service call response = {}", string);
}
result.getResponse().putAttachment(com.networknt.client.Http2Client.RESPONSE_BODY, string);
Http2ClientCompletableFutureNoRequest.super.complete(result.getResponse());
}
@Override
protected void error(IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
}.setup(result.getResponseChannel());
}
@Override
public void failed(IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
});
try {
result.getRequestChannel().shutdownWrites();
if(!result.getRequestChannel().flush()) {
result.getRequestChannel().getWriteSetter().set(ChannelListeners.<StreamSinkChannel>flushingChannelListener(null, null));
result.getRequestChannel().resumeWrites();
}
} catch (IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
| 122
| 359
| 481
|
<methods>public void <init>() ,public CompletableFuture<java.lang.Void> acceptEither(CompletionStage<? extends ClientResponse>, Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends ClientResponse>, Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends ClientResponse>, Consumer<? super ClientResponse>, java.util.concurrent.Executor) ,public static transient CompletableFuture<java.lang.Void> allOf(CompletableFuture<?>[]) ,public static transient CompletableFuture<java.lang.Object> anyOf(CompletableFuture<?>[]) ,public CompletableFuture<U> applyToEither(CompletionStage<? extends ClientResponse>, Function<? super ClientResponse,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends ClientResponse>, Function<? super ClientResponse,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends ClientResponse>, Function<? super ClientResponse,U>, java.util.concurrent.Executor) ,public boolean cancel(boolean) ,public boolean complete(ClientResponse) ,public CompletableFuture<ClientResponse> completeAsync(Supplier<? extends ClientResponse>) ,public CompletableFuture<ClientResponse> completeAsync(Supplier<? extends ClientResponse>, java.util.concurrent.Executor) ,public boolean completeExceptionally(java.lang.Throwable) ,public CompletableFuture<ClientResponse> completeOnTimeout(ClientResponse, long, java.util.concurrent.TimeUnit) ,public static CompletableFuture<U> completedFuture(U) ,public static CompletionStage<U> completedStage(U) ,public CompletableFuture<ClientResponse> copy() ,public java.util.concurrent.Executor defaultExecutor() ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit) ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit, java.util.concurrent.Executor) ,public CompletableFuture<ClientResponse> exceptionally(Function<java.lang.Throwable,? extends ClientResponse>) ,public CompletableFuture<ClientResponse> exceptionallyAsync(Function<java.lang.Throwable,? extends ClientResponse>) ,public CompletableFuture<ClientResponse> exceptionallyAsync(Function<java.lang.Throwable,? extends ClientResponse>, java.util.concurrent.Executor) ,public CompletableFuture<ClientResponse> exceptionallyCompose(Function<java.lang.Throwable,? extends CompletionStage<ClientResponse>>) ,public CompletableFuture<ClientResponse> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<ClientResponse>>) ,public CompletableFuture<ClientResponse> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<ClientResponse>>, java.util.concurrent.Executor) ,public static CompletableFuture<U> failedFuture(java.lang.Throwable) ,public static CompletionStage<U> failedStage(java.lang.Throwable) ,public ClientResponse get() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException,public ClientResponse get(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException,public ClientResponse getNow(ClientResponse) ,public int getNumberOfDependents() ,public CompletableFuture<U> handle(BiFunction<? super ClientResponse,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super ClientResponse,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super ClientResponse,java.lang.Throwable,? extends U>, java.util.concurrent.Executor) ,public boolean isCancelled() ,public boolean isCompletedExceptionally() ,public boolean isDone() ,public ClientResponse join() ,public CompletionStage<ClientResponse> minimalCompletionStage() ,public CompletableFuture<U> newIncompleteFuture() ,public void obtrudeException(java.lang.Throwable) ,public void obtrudeValue(ClientResponse) ,public CompletableFuture<ClientResponse> orTimeout(long, java.util.concurrent.TimeUnit) ,public CompletableFuture<java.lang.Void> runAfterBoth(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> runAfterEither(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<U> supplyAsync(Supplier<U>) ,public static CompletableFuture<U> supplyAsync(Supplier<U>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAccept(Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super ClientResponse>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAcceptBoth(CompletionStage<? extends U>, BiConsumer<? super ClientResponse,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super ClientResponse,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super ClientResponse,? super U>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenApply(Function<? super ClientResponse,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super ClientResponse,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super ClientResponse,? extends U>, java.util.concurrent.Executor) ,public CompletableFuture<V> thenCombine(CompletionStage<? extends U>, BiFunction<? super ClientResponse,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super ClientResponse,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super ClientResponse,? super U,? extends V>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenCompose(Function<? super ClientResponse,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super ClientResponse,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super ClientResponse,? extends CompletionStage<U>>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenRun(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<ClientResponse> toCompletableFuture() ,public java.lang.String toString() ,public CompletableFuture<ClientResponse> whenComplete(BiConsumer<? super ClientResponse,? super java.lang.Throwable>) ,public CompletableFuture<ClientResponse> whenCompleteAsync(BiConsumer<? super ClientResponse,? super java.lang.Throwable>) ,public CompletableFuture<ClientResponse> whenCompleteAsync(BiConsumer<? super ClientResponse,? super java.lang.Throwable>, java.util.concurrent.Executor) <variables>static final int ASYNC,private static final java.util.concurrent.Executor ASYNC_POOL,static final int NESTED,private static final java.lang.invoke.VarHandle NEXT,static final java.util.concurrent.CompletableFuture.AltResult NIL,private static final java.lang.invoke.VarHandle RESULT,private static final java.lang.invoke.VarHandle STACK,static final int SYNC,private static final boolean USE_COMMON_POOL,volatile java.lang.Object result,volatile java.util.concurrent.CompletableFuture.Completion stack
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/http/Http2ClientCompletableFutureWithRequest.java
|
Http2ClientCompletableFutureWithRequest
|
completed
|
class Http2ClientCompletableFutureWithRequest extends CompletableFuture<ClientResponse> implements ClientCallback<ClientExchange> {
private Logger logger = LoggerFactory.getLogger(Http2ClientCompletableFutureWithRequest.class);
private String requestBody;
public Http2ClientCompletableFutureWithRequest(String requestBody) {
this.requestBody = requestBody;
}
@Override
public void completed(ClientExchange result) {<FILL_FUNCTION_BODY>}
@Override
public void failed(IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
}
|
new StringWriteChannelListener(requestBody).setup(result.getRequestChannel());
result.setResponseListener(new ClientCallback<ClientExchange>() {
@Override
public void completed(ClientExchange result) {
new StringReadChannelListener(com.networknt.client.Http2Client.BUFFER_POOL) {
@Override
protected void stringDone(String string) {
if (logger.isDebugEnabled()) {
logger.debug("Service call response = {}", string);
}
result.getResponse().putAttachment(com.networknt.client.Http2Client.RESPONSE_BODY, string);
complete(result.getResponse());
}
@Override
protected void error(IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
}.setup(result.getResponseChannel());
}
@Override
public void failed(IOException e) {
logger.error("IOException:", e);
completeExceptionally(e);
}
});
| 160
| 262
| 422
|
<methods>public void <init>() ,public CompletableFuture<java.lang.Void> acceptEither(CompletionStage<? extends ClientResponse>, Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends ClientResponse>, Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> acceptEitherAsync(CompletionStage<? extends ClientResponse>, Consumer<? super ClientResponse>, java.util.concurrent.Executor) ,public static transient CompletableFuture<java.lang.Void> allOf(CompletableFuture<?>[]) ,public static transient CompletableFuture<java.lang.Object> anyOf(CompletableFuture<?>[]) ,public CompletableFuture<U> applyToEither(CompletionStage<? extends ClientResponse>, Function<? super ClientResponse,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends ClientResponse>, Function<? super ClientResponse,U>) ,public CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends ClientResponse>, Function<? super ClientResponse,U>, java.util.concurrent.Executor) ,public boolean cancel(boolean) ,public boolean complete(ClientResponse) ,public CompletableFuture<ClientResponse> completeAsync(Supplier<? extends ClientResponse>) ,public CompletableFuture<ClientResponse> completeAsync(Supplier<? extends ClientResponse>, java.util.concurrent.Executor) ,public boolean completeExceptionally(java.lang.Throwable) ,public CompletableFuture<ClientResponse> completeOnTimeout(ClientResponse, long, java.util.concurrent.TimeUnit) ,public static CompletableFuture<U> completedFuture(U) ,public static CompletionStage<U> completedStage(U) ,public CompletableFuture<ClientResponse> copy() ,public java.util.concurrent.Executor defaultExecutor() ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit) ,public static java.util.concurrent.Executor delayedExecutor(long, java.util.concurrent.TimeUnit, java.util.concurrent.Executor) ,public CompletableFuture<ClientResponse> exceptionally(Function<java.lang.Throwable,? extends ClientResponse>) ,public CompletableFuture<ClientResponse> exceptionallyAsync(Function<java.lang.Throwable,? extends ClientResponse>) ,public CompletableFuture<ClientResponse> exceptionallyAsync(Function<java.lang.Throwable,? extends ClientResponse>, java.util.concurrent.Executor) ,public CompletableFuture<ClientResponse> exceptionallyCompose(Function<java.lang.Throwable,? extends CompletionStage<ClientResponse>>) ,public CompletableFuture<ClientResponse> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<ClientResponse>>) ,public CompletableFuture<ClientResponse> exceptionallyComposeAsync(Function<java.lang.Throwable,? extends CompletionStage<ClientResponse>>, java.util.concurrent.Executor) ,public static CompletableFuture<U> failedFuture(java.lang.Throwable) ,public static CompletionStage<U> failedStage(java.lang.Throwable) ,public ClientResponse get() throws java.lang.InterruptedException, java.util.concurrent.ExecutionException,public ClientResponse get(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException, java.util.concurrent.TimeoutException,public ClientResponse getNow(ClientResponse) ,public int getNumberOfDependents() ,public CompletableFuture<U> handle(BiFunction<? super ClientResponse,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super ClientResponse,java.lang.Throwable,? extends U>) ,public CompletableFuture<U> handleAsync(BiFunction<? super ClientResponse,java.lang.Throwable,? extends U>, java.util.concurrent.Executor) ,public boolean isCancelled() ,public boolean isCompletedExceptionally() ,public boolean isDone() ,public ClientResponse join() ,public CompletionStage<ClientResponse> minimalCompletionStage() ,public CompletableFuture<U> newIncompleteFuture() ,public void obtrudeException(java.lang.Throwable) ,public void obtrudeValue(ClientResponse) ,public CompletableFuture<ClientResponse> orTimeout(long, java.util.concurrent.TimeUnit) ,public CompletableFuture<java.lang.Void> runAfterBoth(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterBothAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> runAfterEither(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable) ,public CompletableFuture<java.lang.Void> runAfterEitherAsync(CompletionStage<?>, java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable) ,public static CompletableFuture<java.lang.Void> runAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public static CompletableFuture<U> supplyAsync(Supplier<U>) ,public static CompletableFuture<U> supplyAsync(Supplier<U>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAccept(Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super ClientResponse>) ,public CompletableFuture<java.lang.Void> thenAcceptAsync(Consumer<? super ClientResponse>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenAcceptBoth(CompletionStage<? extends U>, BiConsumer<? super ClientResponse,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super ClientResponse,? super U>) ,public CompletableFuture<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U>, BiConsumer<? super ClientResponse,? super U>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenApply(Function<? super ClientResponse,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super ClientResponse,? extends U>) ,public CompletableFuture<U> thenApplyAsync(Function<? super ClientResponse,? extends U>, java.util.concurrent.Executor) ,public CompletableFuture<V> thenCombine(CompletionStage<? extends U>, BiFunction<? super ClientResponse,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super ClientResponse,? super U,? extends V>) ,public CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U>, BiFunction<? super ClientResponse,? super U,? extends V>, java.util.concurrent.Executor) ,public CompletableFuture<U> thenCompose(Function<? super ClientResponse,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super ClientResponse,? extends CompletionStage<U>>) ,public CompletableFuture<U> thenComposeAsync(Function<? super ClientResponse,? extends CompletionStage<U>>, java.util.concurrent.Executor) ,public CompletableFuture<java.lang.Void> thenRun(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable) ,public CompletableFuture<java.lang.Void> thenRunAsync(java.lang.Runnable, java.util.concurrent.Executor) ,public CompletableFuture<ClientResponse> toCompletableFuture() ,public java.lang.String toString() ,public CompletableFuture<ClientResponse> whenComplete(BiConsumer<? super ClientResponse,? super java.lang.Throwable>) ,public CompletableFuture<ClientResponse> whenCompleteAsync(BiConsumer<? super ClientResponse,? super java.lang.Throwable>) ,public CompletableFuture<ClientResponse> whenCompleteAsync(BiConsumer<? super ClientResponse,? super java.lang.Throwable>, java.util.concurrent.Executor) <variables>static final int ASYNC,private static final java.util.concurrent.Executor ASYNC_POOL,static final int NESTED,private static final java.lang.invoke.VarHandle NEXT,static final java.util.concurrent.CompletableFuture.AltResult NIL,private static final java.lang.invoke.VarHandle RESULT,private static final java.lang.invoke.VarHandle STACK,static final int SYNC,private static final boolean USE_COMMON_POOL,volatile java.lang.Object result,volatile java.util.concurrent.CompletableFuture.Completion stack
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/http/Http2ServiceResponse.java
|
Http2ServiceResponse
|
isClientResponseStatusOK
|
class Http2ServiceResponse {
ClientResponse clientResponse;
ObjectMapper objectMapper = Config.getInstance().getMapper();
public Http2ServiceResponse(ClientResponse clientResponse) {
this.clientResponse = clientResponse;
}
public String getClientResponseBody() {
return clientResponse.getAttachment(Http2Client.RESPONSE_BODY);
}
public int getClientResponseStatusCode() {
return clientResponse.getResponseCode();
}
public boolean isClientResponseStatusOK() {<FILL_FUNCTION_BODY>}
public <ResponseType> ResponseType getTypedClientResponse(Class<? extends ResponseType> clazz) throws Exception {
return this.objectMapper.readValue(this.getClientResponseBody(), clazz);
}
public <ResponseType> List<ResponseType> getTypedListClientResponse(Class<? extends ResponseType> clazz) throws Exception {
return this.objectMapper.readValue(this.getClientResponseBody(), objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
}
}
|
int statusCode = getClientResponseStatusCode();
return statusCode >= 200 && statusCode < 300;
| 270
| 32
| 302
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/http/HttpRequestValue.java
|
HttpRequestValue
|
toString
|
class HttpRequestValue implements Serializable {
private Map<String, BodyPart> bodyPartMap;
//request overall content type
private ContentType contentType;
public HttpRequestValue() {
this(null);
}
public HttpRequestValue(ContentType contentType) {
this(contentType, null);
}
public HttpRequestValue(ContentType contentType, Map<String, BodyPart> bodyPartMap) {
this.bodyPartMap = bodyPartMap;
}
public void setBody(Map<String, BodyPart> bodyPartMap) {
this.bodyPartMap = bodyPartMap;
}
public Map<String, BodyPart> getBody() {
return this.bodyPartMap;
}
public BodyPart getBody(String key) {
return (this.bodyPartMap==null? null : this.bodyPartMap.get(key) );
}
/**
* Indicates whether this entity has a body part by the key.
* @param key the key
* @return true if has body
*/
public boolean hasBody(String key) {
return (this.bodyPartMap==null? false : this.bodyPartMap.containsKey(key) );
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public static HttpRequestValue.DefaultRequestValueBuilder builder() {
return new HttpRequestValue.DefaultRequestValueBuilder();
}
public static HttpRequestValue.DefaultRequestValueBuilder builder(ContentType contentType) {
return new HttpRequestValue.DefaultRequestValueBuilder(contentType);
}
public static class DefaultRequestValueBuilder {
private Map<String, BodyPart> mappings = new HashMap();
private ContentType contentType;
public DefaultRequestValueBuilder() {
}
public DefaultRequestValueBuilder(ContentType contentType) {
this.contentType = contentType;
}
public HttpRequestValue.DefaultRequestValueBuilder with(String name, ContentType type, Object body) {
this.mappings.put(name, new BodyPart(type, body));
return this;
}
public HttpRequestValue build() {
return new HttpRequestValue(contentType, mappings);
}
}
}
|
StringBuilder builder = new StringBuilder("<");
builder.append(',');
Map<String, BodyPart> body = getBody();
if (body != null) {
builder.append(body);
builder.append(',');
}
builder.append('>');
return builder.toString();
| 567
| 82
| 649
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/http/Light4jHttp2ClientProvider.java
|
Light4jHttp2ClientProvider
|
createNotifier
|
class Light4jHttp2ClientProvider implements ClientProvider {
public static final String HTTP2 = "h2";
public static final String HTTP_1_1 = "http/1.1";
private static final ChannelListener<SslConnection> FAILED = new ChannelListener<SslConnection>() {
@Override
public void handleEvent(SslConnection connection) {
UndertowLogger.ROOT_LOGGER.alpnConnectionFailed(connection);
IoUtils.safeClose(connection);
}
};
@Override
public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioWorker worker, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
connect(listener, null, uri, worker, ssl, bufferPool, options);
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
connect(listener, null, uri, ioThread, ssl, bufferPool, options);
}
@Override
public Set<String> handlesSchemes() {
return new HashSet<>(Arrays.asList(new String[]{HTTP2}));
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, final URI uri, final XnioWorker worker, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
if (ssl == null) {
listener.failed(UndertowMessages.MESSAGES.sslWasNull());
return;
}
OptionMap tlsOptions = OptionMap.builder().addAll(options).set(Options.SSL_STARTTLS, true).getMap();
if(bindAddress == null) {
ssl.openSslConnection(worker, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, tlsOptions), tlsOptions).addNotifier(createNotifier(listener), null);
} else {
ssl.openSslConnection(worker, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, tlsOptions), tlsOptions).addNotifier(createNotifier(listener), null);
}
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
if (ssl == null) {
listener.failed(UndertowMessages.MESSAGES.sslWasNull());
return;
}
if(bindAddress == null) {
OptionMap tlsOptions = OptionMap.builder().addAll(options).set(Options.SSL_STARTTLS, true).getMap();
ssl.openSslConnection(ioThread, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, tlsOptions), options).addNotifier(createNotifier(listener), null);
} else {
ssl.openSslConnection(ioThread, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null);
}
}
protected IoFuture.Notifier<StreamConnection, Object> createNotifier(final ClientCallback<ClientConnection> listener) {<FILL_FUNCTION_BODY>}
protected ChannelListener<StreamConnection> createOpenListener(final ClientCallback<ClientConnection> listener, final URI uri, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
return new ChannelListener<StreamConnection>() {
@Override
public void handleEvent(StreamConnection connection) {
handleConnected(connection, listener, uri, bufferPool, options);
}
};
}
/**
* @deprecated will be change to protected in future TODO: not sure if this should be public
* @param listener {@link ClientCallback}
* @param uri URI
* @param bufferPool ByteBufferPool
* @param options OptionMap
* @return ALPNClientSelector.ALPNProtocol
*/
@Deprecated
public static ALPNClientSelector.ALPNProtocol alpnProtocol(final ClientCallback<ClientConnection> listener, URI uri, ByteBufferPool bufferPool, OptionMap options) {
return new ALPNClientSelector.ALPNProtocol(new ChannelListener<SslConnection>() {
@Override
public void handleEvent(SslConnection connection) {
listener.completed(createHttp2Channel(connection, bufferPool, options, uri.getHost()));
}
}, HTTP2);
};
protected void handleConnected(StreamConnection connection, final ClientCallback<ClientConnection> listener, URI uri,ByteBufferPool bufferPool, OptionMap options) {
Light4jALPNClientSelector.runAlpn((SslConnection) connection, FAILED, listener, alpnProtocol(listener, uri, bufferPool, options));
}
protected static Http2ClientConnection createHttp2Channel(StreamConnection connection, ByteBufferPool bufferPool, OptionMap options, String defaultHost) {
final ClientStatisticsImpl clientStatistics;
//first we set up statistics, if required
if (options.get(UndertowOptions.ENABLE_STATISTICS, false)) {
clientStatistics = new ClientStatisticsImpl();
connection.getSinkChannel().setConduit(new BytesSentStreamSinkConduit(connection.getSinkChannel().getConduit(), new ByteActivityCallback() {
@Override
public void activity(long bytes) {
clientStatistics.written += bytes;
}
}));
connection.getSourceChannel().setConduit(new BytesReceivedStreamSourceConduit(connection.getSourceChannel().getConduit(), new ByteActivityCallback() {
@Override
public void activity(long bytes) {
clientStatistics.read += bytes;
}
}));
} else {
clientStatistics = null;
}
Http2Channel http2Channel = new Http2Channel(connection, null, bufferPool, null, true, false, options);
return new Http2ClientConnection(http2Channel, false, defaultHost, clientStatistics, true);
}
protected static class ClientStatisticsImpl implements ClientStatistics {
private long requestCount, read, written;
@Override
public long getRequests() {
return requestCount;
}
@Override
public long getRead() {
return read;
}
@Override
public long getWritten() {
return written;
}
@Override
public void reset() {
read = 0;
written = 0;
requestCount = 0;
}
}
}
|
return new IoFuture.Notifier<StreamConnection, Object>() {
@Override
public void notify(IoFuture<? extends StreamConnection> ioFuture, Object o) {
if (ioFuture.getStatus() == IoFuture.Status.FAILED) {
listener.failed(ioFuture.getException());
}
}
};
| 1,808
| 88
| 1,896
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/http/Light4jHttpClientProvider.java
|
Light4jHttpClientProvider
|
connect
|
class Light4jHttpClientProvider implements ClientProvider {
private static final Logger logger = LoggerFactory.getLogger(Light4jHttpClientProvider.class);
public static final String HTTP = "http";
public static final String HTTPS = "https";
@Override
public Set<String> handlesSchemes() {
return new HashSet<>(Arrays.asList(new String[]{HTTP, HTTPS}));
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioWorker worker, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
connect(listener, null, uri, worker, ssl, bufferPool, options);
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final ByteBufferPool bufferPool, final OptionMap options) {
connect(listener, null, uri, ioThread, ssl, bufferPool, options);
}
@Override
public void connect(ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, URI uri, XnioWorker worker, XnioSsl ssl, ByteBufferPool bufferPool, OptionMap options) {
if (uri.getScheme().equals(HTTPS)) {
if (ssl == null) {
listener.failed(UndertowMessages.MESSAGES.sslWasNull());
return;
}
OptionMap tlsOptions = OptionMap.builder().addAll(options).set(Options.SSL_STARTTLS, true).getMap();
if (bindAddress == null) {
ssl.openSslConnection(worker, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, bufferPool, tlsOptions, uri), tlsOptions).addNotifier(createNotifier(listener), null);
} else {
ssl.openSslConnection(worker, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, bufferPool, tlsOptions, uri), tlsOptions).addNotifier(createNotifier(listener), null);
}
} else {
if (bindAddress == null) {
worker.openStreamConnection(new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 80 : uri.getPort()), createOpenListener(listener, bufferPool, options, uri), options).addNotifier(createNotifier(listener), null);
} else {
worker.openStreamConnection(bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 80 : uri.getPort()), createOpenListener(listener, bufferPool, options, uri), null, options).addNotifier(createNotifier(listener), null);
}
}
}
@Override
public void connect(ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, URI uri, XnioIoThread ioThread, XnioSsl ssl, ByteBufferPool bufferPool, OptionMap options) {<FILL_FUNCTION_BODY>}
private IoFuture.Notifier<StreamConnection, Object> createNotifier(final ClientCallback<ClientConnection> listener) {
return new IoFuture.Notifier<StreamConnection, Object>() {
@Override
public void notify(IoFuture<? extends StreamConnection> ioFuture, Object o) {
if (ioFuture.getStatus() == IoFuture.Status.FAILED) {
listener.failed(ioFuture.getException());
}
}
};
}
private ChannelListener<StreamConnection> createOpenListener(final ClientCallback<ClientConnection> listener, final ByteBufferPool bufferPool, final OptionMap options, final URI uri) {
return new ChannelListener<StreamConnection>() {
@Override
public void handleEvent(StreamConnection connection) {
handleConnected(connection, listener, bufferPool, options, uri);
}
};
}
private void handleConnected(final StreamConnection connection, final ClientCallback<ClientConnection> listener, final ByteBufferPool bufferPool, final OptionMap options, URI uri) {
boolean h2 = options.get(UndertowOptions.ENABLE_HTTP2, false);
if(connection instanceof SslConnection && (h2)) {
List<ALPNClientSelector.ALPNProtocol> protocolList = new ArrayList<>();
if(h2) {
protocolList.add(Http2ClientProvider.alpnProtocol(listener, uri, bufferPool, options));
}
Light4jALPNClientSelector.runAlpn((SslConnection) connection, new ChannelListener<SslConnection>() {
@Override
public void handleEvent(SslConnection connection) {
listener.completed(createHttpClientConnection(connection, options, bufferPool));
}
}, listener, protocolList.toArray(new ALPNClientSelector.ALPNProtocol[protocolList.size()]));
} else {
if(connection instanceof SslConnection) {
try {
((SslConnection) connection).startHandshake();
} catch (Throwable t) {
listener.failed((t instanceof IOException) ? (IOException) t : new IOException(t));
}
}
listener.completed(createHttpClientConnection(connection, options, bufferPool));
}
}
/*
* Create instances of "io.undertow.client.http.HttpClientConnection" using reflections
*/
private ClientConnection createHttpClientConnection(final StreamConnection connection, final OptionMap options, final ByteBufferPool bufferPool) {
try {
Class<?> cls = Class.forName("io.undertow.client.http.HttpClientConnection");
Constructor<?> o = cls.getDeclaredConstructor(StreamConnection.class, OptionMap.class, ByteBufferPool.class);
o.setAccessible(true);
return (ClientConnection) o.newInstance(connection, options, bufferPool);
}catch(Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
|
if (uri.getScheme().equals(HTTPS)) {
if (ssl == null) {
listener.failed(UndertowMessages.MESSAGES.sslWasNull());
return;
}
OptionMap tlsOptions = OptionMap.builder().addAll(options).set(Options.SSL_STARTTLS, true).getMap();
if (bindAddress == null) {
ssl.openSslConnection(ioThread, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, bufferPool, tlsOptions, uri), tlsOptions).addNotifier(createNotifier(listener), null);
} else {
ssl.openSslConnection(ioThread, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, bufferPool, tlsOptions, uri), tlsOptions).addNotifier(createNotifier(listener), null);
}
} else {
if (bindAddress == null) {
ioThread.openStreamConnection(new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 80 : uri.getPort()), createOpenListener(listener, bufferPool, options, uri), options).addNotifier(createNotifier(listener), null);
} else {
ioThread.openStreamConnection(bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 80 : uri.getPort()), createOpenListener(listener, bufferPool, options, uri), null, options).addNotifier(createNotifier(listener), null);
}
}
| 1,540
| 428
| 1,968
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/listener/ByteBufferReadChannelListener.java
|
ByteBufferReadChannelListener
|
handleEvent
|
class ByteBufferReadChannelListener implements ChannelListener<StreamSourceChannel> {
private final ByteBufferPool bufferPool;
private List<Byte> result = new ArrayList<>();
public ByteBufferReadChannelListener(ByteBufferPool bufferPool) {
this.bufferPool = bufferPool;
}
public void setup(StreamSourceChannel channel) {
PooledByteBuffer resource = this.bufferPool.allocate();
ByteBuffer buffer = resource.getBuffer();
try {
int r;
do {
r = channel.read(buffer);
if (r == 0) {
channel.getReadSetter().set(this);
channel.resumeReads();
} else if (r == -1) {
this.bufferDone(this.result);
IoUtils.safeClose(channel);
} else {
buffer.flip();
ByteBuffer[] buffs = new ByteBuffer[]{buffer};
for(int i = 0; i < buffs.length; ++i) {
ByteBuffer buf = buffs[i];
while(buf.hasRemaining()) {
result.add(buf.get());
}
}
}
} while(r > 0);
} catch (IOException var8) {
this.error(var8);
} finally {
resource.close();
}
}
public void handleEvent(StreamSourceChannel channel) {<FILL_FUNCTION_BODY>}
protected abstract void bufferDone(List<Byte> out);
protected abstract void error(IOException var1);
}
|
PooledByteBuffer resource = this.bufferPool.allocate();
ByteBuffer buffer = resource.getBuffer();
try {
int r;
do {
r = channel.read(buffer);
if (r == 0) {
return;
}
if (r == -1) {
this.bufferDone(this.result);
IoUtils.safeClose(channel);
} else {
buffer.flip();
ByteBuffer[] buffs = new ByteBuffer[]{buffer};;
for(int i = 0; i < buffs.length; ++i) {
ByteBuffer buf = buffs[i];
while(buf.hasRemaining()) {
result.add(buf.get());
}
}
}
} while(r > 0);
} catch (IOException var8) {
this.error(var8);
} finally {
resource.close();
}
| 384
| 232
| 616
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/listener/ByteBufferWriteChannelListener.java
|
ByteBufferWriteChannelListener
|
handleEvent
|
class ByteBufferWriteChannelListener implements ChannelListener<StreamSinkChannel>{
private final ByteBuffer buffer;
public ByteBufferWriteChannelListener(ByteBuffer body) {
this.buffer =body;
}
public void setup(StreamSinkChannel channel) {
while(true) {
try {
int c = channel.write(this.buffer);
if (this.buffer.hasRemaining() && c > 0) {
continue;
}
if (this.buffer.hasRemaining()) {
channel.getWriteSetter().set(this);
channel.resumeWrites();
} else {
this.writeDone(channel);
}
} catch (IOException var3) {
this.handleError(channel, var3);
}
return;
}
}
protected void handleError(StreamSinkChannel channel, IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
IoUtils.safeClose(channel);
}
public void handleEvent(StreamSinkChannel channel) {<FILL_FUNCTION_BODY>}
public boolean hasRemaining() {
return this.buffer.hasRemaining();
}
protected void writeDone(final StreamSinkChannel channel) {
try {
channel.shutdownWrites();
if (!channel.flush()) {
channel.getWriteSetter().set(ChannelListeners.flushingChannelListener(new ChannelListener<StreamSinkChannel>() {
public void handleEvent(StreamSinkChannel o) {
IoUtils.safeClose(channel);
}
}, ChannelListeners.closingChannelExceptionHandler()));
channel.resumeWrites();
}
} catch (IOException var3) {
this.handleError(channel, var3);
}
}
}
|
while(true) {
try {
int c = channel.write(this.buffer);
if (this.buffer.hasRemaining() && c > 0) {
continue;
}
if (this.buffer.hasRemaining()) {
channel.resumeWrites();
return;
}
this.writeDone(channel);
} catch (IOException var3) {
this.handleError(channel, var3);
}
return;
}
| 458
| 125
| 583
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/rest/RestClientTemplate.java
|
RestClientTemplate
|
execute
|
class RestClientTemplate implements RestClient {
private static Logger logger = LoggerFactory.getLogger(RestClientTemplate.class);
private OptionMap restOptions;
Optional<List<HttpStatus>> statusCodesValid = Optional.empty();
/**
* Instantiate a new LightRestClient with default RestClientOptions
*/
public RestClientTemplate() {
this.restOptions = OptionMap.EMPTY;
}
public void setStatusCodesValid(List<HttpStatus> statusCodesValid) {
this.statusCodesValid = Optional.of(statusCodesValid);
}
/**
* Instantiate a new LightRestClient with configurable RestClientOptions
* @param restOptions org.xnio.OptionMap of RestClientOptions
*/
public RestClientTemplate(OptionMap restOptions) {
this.restOptions = restOptions != null ? restOptions : OptionMap.EMPTY;
}
@Override
public String get(String url, String path) throws RestClientException {
return get(url, path, String.class);
}
@Override
public <T> T get(String url, String path, Class<T> responseType) throws RestClientException {
return get(url, path, responseType, null);
}
@Override
public <T> T get(ServiceDef serviceDef, String path, Class<T> responseType) throws RestClientException {
return execute(serviceDef, path, responseType, null, Methods.GET, null);
}
@Override
public <T> T get(ServiceDef serviceDef, String path, Class<T> responseType, Map<String, ?> headerMap) throws RestClientException {
return execute(serviceDef, path, responseType, headerMap, Methods.GET, null);
}
@Override
public String get(ServiceDef serviceDef, String path) throws RestClientException {
return get(serviceDef, path, String.class);
}
@Override
public <T> T get(String url, String path, Class<T> responseType, Map<String, ?> headerMap) throws RestClientException {
return execute(url, path, responseType, headerMap, Methods.GET, null);
}
@Override
public <T> T post(String url, String path, Class<T> responseType, String requestBody) throws RestClientException {
return post(url, path, responseType, null, requestBody);
}
@Override
public String post(String url, String path, String requestBody) throws RestClientException {
return post(url, path, String.class, requestBody);
}
@Override
public <T> T post(String url, String path, Class<T> responseType, Map<String, ?> headerMap, String requestBody) throws RestClientException {
return execute(url, path, responseType, headerMap, Methods.POST, requestBody);
}
@Override
public String post(ServiceDef serviceDef, String path, String requestBody) throws RestClientException {
return post(serviceDef, path, String.class, requestBody);
}
@Override
public <T> T post(ServiceDef serviceDef, String path, Class<T> responseType, String requestBody) throws RestClientException {
return post(serviceDef, path, responseType, null, requestBody);
}
@Override
public <T> T post(ServiceDef serviceDef, String path, Class<T> responseType, Map<String, ?> headerMap, String requestBody) throws RestClientException {
return execute(serviceDef, path, responseType, headerMap, Methods.POST, requestBody);
}
@Override
public String put(String url, String path, String requestBody) throws RestClientException {
return put(url, path, null, requestBody);
}
@Override
public String put(String url, String path, Map<String, ?> headerMap, String requestBody) throws RestClientException {
return execute(url, path, String.class, headerMap, Methods.PUT, requestBody);
}
@Override
public String put(ServiceDef serviceDef, String path, String requestBody) throws RestClientException {
return execute(serviceDef, path, String.class, null, Methods.PUT, requestBody);
}
@Override
public String put(ServiceDef serviceDef, String path, Map<String, ?> headerMap, String requestBody) throws RestClientException {
return execute(serviceDef, path, String.class, headerMap, Methods.PUT, requestBody);
}
@Override
public String delete(String url, String path) throws RestClientException {
return delete(url, path, null, null);
}
@Override
public String delete(String url, String path, Map<String, ?> headerMap, String requestBody) throws RestClientException {
return execute(url, path, String.class, headerMap, Methods.DELETE, requestBody);
}
@Override
public String delete(ServiceDef serviceDef, String path) throws RestClientException {
return execute(serviceDef, path, String.class, null, Methods.DELETE, null);
}
protected <T> T execute(String url, String path, Class<T> responseType, Map<String, ?> headerMap, HttpString method, String requestBody) throws RestClientException {<FILL_FUNCTION_BODY>}
protected <T> T execute(ServiceDef serviceDef, String path, Class<T> responseType, Map<String, ?> headerMap, HttpString method, String requestBody) throws RestClientException {
try {
Http2ServiceRequest http2ServiceRequest = new Http2ServiceRequest(serviceDef, path, method);
if (statusCodesValid.isPresent()) http2ServiceRequest.setStatusCodesValid(statusCodesValid.get());
http2ServiceRequest.setRequestHeaders(headerMap);
if (requestBody!=null) http2ServiceRequest.setRequestBody(requestBody);
return http2ServiceRequest.callForTypedObject(responseType).get();
} catch (Exception e) {
String errorStr = "execute the restful API call error:";
logger.error(errorStr + e);
throw new RestClientException(errorStr, e);
}
}
}
|
try {
Http2ServiceRequest http2ServiceRequest = new Http2ServiceRequest(new URI(url), path, method);
if (statusCodesValid.isPresent()) http2ServiceRequest.setStatusCodesValid(statusCodesValid.get());
http2ServiceRequest.setRequestHeaders(headerMap);
if (requestBody!=null) http2ServiceRequest.setRequestBody(requestBody);
return http2ServiceRequest.callForTypedObject(responseType).get();
} catch (Exception e) {
String errorStr = "execute the restful API call error:";
logger.error(errorStr + e);
throw new RestClientException(errorStr, e);
}
| 1,550
| 171
| 1,721
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/simplepool/SimpleConnectionPool.java
|
SimpleConnectionPool
|
borrow
|
class SimpleConnectionPool {
private final Map<URI, SimpleURIConnectionPool> pools = new ConcurrentHashMap<>();
private final SimpleConnectionMaker connectionMaker;
private final long expireTime;
private final int poolSize;
public SimpleConnectionPool(long expireTime, int poolSize, SimpleConnectionMaker connectionMaker) {
this.expireTime = expireTime;
this.poolSize = poolSize;
this.connectionMaker = connectionMaker;
}
public SimpleConnectionHolder.ConnectionToken borrow(long createConnectionTimeout, boolean isHttp2, URI uri)
throws RuntimeException
{<FILL_FUNCTION_BODY>}
public void restore(SimpleConnectionHolder.ConnectionToken connectionToken) {
if(pools.containsKey(connectionToken.uri()))
pools.get(connectionToken.uri()).restore(connectionToken);
}
}
|
if(!pools.containsKey(uri)) {
synchronized (pools) {
if (!pools.containsKey(uri))
pools.put(uri, new SimpleURIConnectionPool(uri, expireTime, poolSize, connectionMaker));
}
}
return pools.get(uri).borrow(createConnectionTimeout);
| 219
| 86
| 305
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/simplepool/undertow/SimpleClientConnectionMaker.java
|
SimpleClientConnectionMaker
|
makeConnection
|
class SimpleClientConnectionMaker implements SimpleConnectionMaker
{
private static final Logger logger = LoggerFactory.getLogger(SimpleClientConnectionMaker.class);
private static final ByteBufferPool BUFFER_POOL = new DefaultByteBufferPool(true, ClientConfig.get().getBufferSize() * 1024);
private static SimpleClientConnectionMaker simpleClientConnectionMaker = null;
public static SimpleConnectionMaker instance() {
if(simpleClientConnectionMaker == null)
simpleClientConnectionMaker = new SimpleClientConnectionMaker();
return simpleClientConnectionMaker;
}
@Override
public SimpleConnection makeConnection(
long createConnectionTimeout,
boolean isHttp2,
final URI uri,
final Set<SimpleConnection> allCreatedConnections) throws RuntimeException
{
boolean isHttps = uri.getScheme().equalsIgnoreCase("https");
XnioSsl ssl = getSSL(isHttps, isHttp2);
XnioWorker worker = getWorker(isHttp2);
OptionMap connectionOptions = getConnectionOptions(isHttp2);
InetSocketAddress bindAddress = null;
final FutureResult<SimpleConnection> result = new FutureResult<>();
ClientCallback<ClientConnection> connectionCallback = new ClientCallback<ClientConnection>() {
@Override
public void completed(ClientConnection connection) {
logger.debug("New connection {} established with {}", port(connection), uri);
SimpleConnection simpleConnection = new SimpleClientConnection(connection);
// note: its vital that allCreatedConnections and result contain the same SimpleConnection reference
allCreatedConnections.add(simpleConnection);
result.setResult(simpleConnection);
}
@Override
public void failed(IOException e) {
logger.debug("Failed to establish new connection for uri: {}", uri);
result.setException(e);
}
};
UndertowClient undertowClient = UndertowClient.getInstance();
undertowClient.connect(connectionCallback, bindAddress, uri, worker, ssl, BUFFER_POOL, connectionOptions);
IoFuture<SimpleConnection> future = result.getIoFuture();
return safeConnect(createConnectionTimeout, future);
}
@Override
public SimpleConnection makeConnection(long createConnectionTimeout, InetSocketAddress bindAddress, final URI uri, final XnioWorker worker, XnioSsl ssl, ByteBufferPool bufferPool, OptionMap options, final Set<SimpleConnection> allCreatedConnections) {<FILL_FUNCTION_BODY>}
public SimpleConnection reuseConnection(long createConnectionTimeout, SimpleConnection connection) throws RuntimeException
{
if(connection == null)
return null;
if(!(connection.getRawConnection() instanceof ClientConnection))
throw new IllegalArgumentException("Attempt to reuse wrong connection type. Must be of type ClientConnection");
if(!connection.isOpen())
throw new RuntimeException("Reused-connection has been unexpectedly closed");
return connection;
}
// PRIVATE METHODS
private static OptionMap getConnectionOptions(boolean isHttp2) {
return isHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY;
}
// TODO: Should worker be re-used? Note: Light-4J Http2Client re-uses it
private static AtomicReference<XnioWorker> WORKER = new AtomicReference<>(null);
private static XnioWorker getWorker(boolean isHttp2)
{
if(WORKER.get() != null) return WORKER.get();
Xnio xnio = Xnio.getInstance(Undertow.class.getClassLoader());
try {
// if WORKER is null, then set new WORKER otherwise leave existing WORKER
WORKER.compareAndSet(null, xnio.createWorker(null, getWorkerOptionMap(isHttp2)));
} catch (IOException e) {
throw new RuntimeException(e);
}
return WORKER.get();
}
private static OptionMap getWorkerOptionMap(boolean isHttp2)
{
OptionMap.Builder optionBuild = OptionMap.builder()
.set(Options.WORKER_IO_THREADS, 8)
.set(Options.TCP_NODELAY, true)
.set(Options.KEEP_ALIVE, true)
.set(Options.WORKER_NAME, isHttp2 ? "Callback-HTTP2" : "Callback-HTTP11");
return optionBuild.getMap();
}
// TODO: Should SSL be re-used? Note: Light-4J Http2Client re-uses it
private static AtomicReference<UndertowXnioSsl> SSL = new AtomicReference<>(null);
private static XnioSsl getSSL(boolean isHttps, boolean isHttp2)
{
if(!isHttps)
return null;
if(SSL.get() != null)
return SSL.get();
try {
// TODO: Should this be OptionMap.EMPTY ??
// if SSL is null, then set new SSL otherwise leave existing SSL
SSL.compareAndSet(
null,
new UndertowXnioSsl(getWorker(isHttp2).getXnio(), OptionMap.EMPTY, BUFFER_POOL, Http2Client.createSSLContext()));
} catch (Exception e) {
logger.error("Exception while creating new shared UndertowXnioSsl used to create connections", e);
throw new RuntimeException(e);
}
return SSL.get();
}
/***
* Never returns null
*
* @param timeoutSeconds
* @param future
* @return
*/
private static SimpleConnection safeConnect(long timeoutSeconds, IoFuture<SimpleConnection> future)
{
SimpleConnection connection = null;
if(future.await(timeoutSeconds, TimeUnit.SECONDS) != org.xnio.IoFuture.Status.DONE)
throw new RuntimeException("Connection establishment timed out");
try {
connection = future.get();
} catch (IOException e) {
throw new RuntimeException("Connection establishment generated I/O exception", e);
}
if(connection == null)
throw new RuntimeException("Connection establishment failed (null) - Full connection terminated");
return connection;
}
public static String port(ClientConnection connection) {
if(connection == null) return "NULL";
String url = connection.getLocalAddress().toString();
int semiColon = url.lastIndexOf(":");
if(semiColon == - 1) return "PORT?";
return url.substring(url.lastIndexOf(":")+1);
}
}
|
final FutureResult<SimpleConnection> result = new FutureResult<>();
ClientCallback<ClientConnection> connectionCallback = new ClientCallback<ClientConnection>() {
@Override
public void completed(ClientConnection connection) {
logger.debug("New connection {} established with {}", port(connection), uri);
SimpleConnection simpleConnection = new SimpleClientConnection(connection);
// note: its vital that allCreatedConnections and result contain the same SimpleConnection reference
allCreatedConnections.add(simpleConnection);
result.setResult(simpleConnection);
}
@Override
public void failed(IOException e) {
logger.debug("Failed to establish new connection for uri: {}", uri);
result.setException(e);
}
};
Http2Client http2Client = Http2Client.getInstance();
http2Client.connect(connectionCallback, bindAddress, uri, worker, ssl, bufferPool, options);
IoFuture<SimpleConnection> future = result.getIoFuture();
return safeConnect(createConnectionTimeout, future);
| 1,698
| 254
| 1,952
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/ssl/ClientX509ExtendedTrustManager.java
|
ClientX509ExtendedTrustManager
|
checkClientTrusted
|
class ClientX509ExtendedTrustManager implements X509TrustManager {
private final X509TrustManager trustManager;
public ClientX509ExtendedTrustManager(List<TrustManager> trustManagers) {
if(trustManagers == null || trustManagers.size() == 0) {
throw new IllegalArgumentException("TrustManagers must not be null or empty");
}
this.trustManager = (X509TrustManager)trustManagers.get(0);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {<FILL_FUNCTION_BODY>}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
trustManager.checkServerTrusted(chain, authType);
return; // someone trusts them. success!
} catch (CertificateException e) {
throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
List<X509Certificate> certificates = new ArrayList<>(Arrays.asList(trustManager.getAcceptedIssuers()));
return certificates.toArray(new X509Certificate[0]);
}
}
|
try {
trustManager.checkClientTrusted(chain, authType);
} catch (CertificateException e) {
throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
| 353
| 55
| 408
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/ssl/CompositeX509TrustManager.java
|
CompositeX509TrustManager
|
getAcceptedIssuers
|
class CompositeX509TrustManager implements X509TrustManager {
private final List<X509TrustManager> trustManagers;
public CompositeX509TrustManager(List<X509TrustManager> trustManagers) {
this.trustManagers = trustManagers;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509TrustManager trustManager : trustManagers) {
try {
trustManager.checkClientTrusted(chain, authType);
return; // someone trusts them. success!
} catch (CertificateException e) {
// maybe someone else will trust them
}
}
throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509TrustManager trustManager : trustManagers) {
try {
trustManager.checkServerTrusted(chain, authType);
return; // someone trusts them. success!
} catch (CertificateException e) {
// maybe someone else will trust them
}
}
throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
@Override
public X509Certificate[] getAcceptedIssuers() {<FILL_FUNCTION_BODY>}
}
|
List<X509Certificate> certificates = new ArrayList<>();
for (X509TrustManager trustManager : trustManagers) {
certificates.addAll(Arrays.asList(trustManager.getAcceptedIssuers()));
}
return certificates.toArray(new X509Certificate[0]);
| 381
| 86
| 467
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/com/networknt/client/ssl/Light4jALPNClientSelector.java
|
Light4jALPNClientSelector
|
runAlpn
|
class Light4jALPNClientSelector {
/**
* A connection is first created by org.xnio.nio.WorkerThread.openTcpStreamConnection(). Once the connection is established, it is passed to io.undertow.protocols.ssl.UndertowXnioSsl.StreamConnectionChannelListener.
* StreamConnectionChannelListener creates an io.undertow.protocols.ssl.UndertowSslConnection instance and passes it to this method.
*
* This method uses the provided sslConnection to perform Application-Layer Protocol Negotiation (ALPN). More specifically, this method negotiates with the server side about which protocol should be used.
* - If the negotiation succeeds, the selected protocol is passed to the corresponding channel listeners defined in the 'details' argument.
* For example, if HttpClientProvider is used and http2 is selected in the negotiation result, Http2ClientConnection will be created.
* - If the negotiation fails (i.e., selectedProtocol is null), the fallback listener is used to continue the communication if possible or simply close the connection.
* For the example above, if http2 is not supported on the server side, HttpClientConnection will be created in the fallback listener.
*
* @param sslConnection - an UndertowSslConnection instance
* @param fallback - the callback used if the ALPN negotiation fails or no APLN provider can be found
* @param failedListener - the callback for handling failures happened in the negotiations
* @param details - callbacks used to create client connections when the negotiation succeeds. Ideally, one callback should be provided for each protocol in {@link javax.net.ssl.SSLEngine#getSupportedProtocols()}.
*/
public static void runAlpn(final SslConnection sslConnection, final ChannelListener<SslConnection> fallback, final ClientCallback<ClientConnection> failedListener, final ALPNProtocol... details) {<FILL_FUNCTION_BODY>}
}
|
SslConduit conduit = UndertowXnioSsl.getSslConduit(sslConnection);
final ALPNProvider provider = ALPNManager.INSTANCE.getProvider(conduit.getSSLEngine());
if (provider == null) {
fallback.handleEvent(sslConnection);
return;
}
String[] protocols = new String[details.length];
final Map<String, ALPNProtocol> protocolMap = new HashMap<>();
for (int i = 0; i < protocols.length; ++i) {
protocols[i] = details[i].getProtocol();
protocolMap.put(details[i].getProtocol(), details[i]);
}
final SSLEngine sslEngine = provider.setProtocols(conduit.getSSLEngine(), protocols);
conduit.setSslEngine(sslEngine);
final AtomicReference<Boolean> handshakeDone = new AtomicReference<>(false);
final AtomicReference<Boolean> connClosed = new AtomicReference<>(false);
try {
sslConnection.getHandshakeSetter().set(new ChannelListener<SslConnection>() {
@Override
public void handleEvent(SslConnection channel) {
if(handshakeDone.get()) {
return;
}
handshakeDone.set(true);
}
});
sslConnection.getCloseSetter().set(new ChannelListener<SslConnection>() {
@Override
public void handleEvent(SslConnection channel) {
if(connClosed.get()) {
return;
}
connClosed.set(true);
}
});
sslConnection.startHandshake();
sslConnection.getSourceChannel().getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
@Override
public void handleEvent(StreamSourceChannel channel) {
String selectedProtocol = provider.getSelectedProtocol(sslEngine);
if (selectedProtocol != null) {
handleSelected(selectedProtocol);
} else {
ByteBuffer buf = ByteBuffer.allocate(100);
try {
int read = channel.read(buf);
if (read > 0) {
buf.flip();
PushBackStreamSourceConduit pb = new PushBackStreamSourceConduit(sslConnection.getSourceChannel().getConduit());
pb.pushBack(new ImmediatePooled<>(buf));
sslConnection.getSourceChannel().setConduit(pb);
} else if (read == -1) {
failedListener.failed(new ClosedChannelException());
}
selectedProtocol = provider.getSelectedProtocol(sslEngine);
if (selectedProtocol != null) {
handleSelected(selectedProtocol);
} else if (read > 0 || handshakeDone.get()) {
sslConnection.getSourceChannel().suspendReads();
fallback.handleEvent(sslConnection);
return;
}
} catch (Throwable t) {
IOException e = t instanceof IOException ? (IOException) t : new IOException(t);
failedListener.failed(e);
}
}
}
private void handleSelected(String selected) {
if (selected.isEmpty()) {
sslConnection.getSourceChannel().suspendReads();
fallback.handleEvent(sslConnection);
return;
} else {
ALPNClientSelector.ALPNProtocol details = protocolMap.get(selected);
if (details == null) {
//should never happen
sslConnection.getSourceChannel().suspendReads();
fallback.handleEvent(sslConnection);
return;
} else {// modification of ALPNClientSelector for JDK8. need to check handshake results.
if (handshakeDone.get()) {
sslConnection.getSourceChannel().suspendReads();
details.getSelected().handleEvent(sslConnection);
}else if (connClosed.get()) {
failedListener.failed(new ClosedChannelException());
}
}
}
}
});
sslConnection.getSourceChannel().resumeReads();
} catch (IOException e) {
failedListener.failed(e);
} catch (Throwable e) {
failedListener.failed(new IOException(e));
}
| 472
| 1,077
| 1,549
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/client5/http/psl/copied/PublicSuffixMatcher.java
|
PublicSuffixMatcher
|
getDomainRoot
|
class PublicSuffixMatcher {
private final Map<String, DomainType> rules;
private final Map<String, DomainType> exceptions;
public PublicSuffixMatcher(final Collection<String> rules, final Collection<String> exceptions) {
this(DomainType.UNKNOWN, rules, exceptions);
}
/*
* @since 4.5
*/
public PublicSuffixMatcher(
final DomainType domainType, final Collection<String> rules, final Collection<String> exceptions) {
Args.notNull(domainType, "Domain type");
Args.notNull(rules, "Domain suffix rules");
this.rules = new ConcurrentHashMap<>(rules.size());
for (final String rule: rules) {
this.rules.put(rule, domainType);
}
this.exceptions = new ConcurrentHashMap<>();
if (exceptions != null) {
for (final String exception: exceptions) {
this.exceptions.put(exception, domainType);
}
}
}
/*
* @since 4.5
*/
public PublicSuffixMatcher(final Collection<PublicSuffixList> lists) {
Args.notNull(lists, "Domain suffix lists");
this.rules = new ConcurrentHashMap<>();
this.exceptions = new ConcurrentHashMap<>();
for (final PublicSuffixList list: lists) {
final DomainType domainType = list.getType();
final List<String> rules = list.getRules();
for (final String rule: rules) {
this.rules.put(rule, domainType);
}
final List<String> exceptions = list.getExceptions();
if (exceptions != null) {
for (final String exception: exceptions) {
this.exceptions.put(exception, domainType);
}
}
}
}
private static boolean hasEntry(final Map<String, DomainType> map, final String rule, final DomainType expectedType) {
if (map == null) {
return false;
}
final DomainType domainType = map.get(rule);
if (domainType == null) {
return false;
} else {
return expectedType == null || domainType.equals(expectedType);
}
}
private boolean hasRule(final String rule, final DomainType expectedType) {
return hasEntry(this.rules, rule, expectedType);
}
private boolean hasException(final String exception, final DomainType expectedType) {
return hasEntry(this.exceptions, exception, expectedType);
}
public String getDomainRoot(final String domain) {
return getDomainRoot(domain, null);
}
public String getDomainRoot(final String domain, final DomainType expectedType) {<FILL_FUNCTION_BODY>}
/*
* Tests whether the given domain matches any of entry from the public suffix list.
*/
public boolean matches(final String domain) {
return matches(domain, null);
}
public boolean matches(final String domain, final DomainType expectedType) {
if (domain == null) {
return false;
}
final String domainRoot = getDomainRoot(
domain.startsWith(".") ? domain.substring(1) : domain, expectedType);
return domainRoot == null;
}
}
|
if (domain == null) {
return null;
}
if (domain.startsWith(".")) {
return null;
}
String domainName = null;
String segment = domain.toLowerCase(Locale.ROOT);
while (segment != null) {
// An exception rule takes priority over any other matching rule.
if (hasException(IDN.toUnicode(segment), expectedType)) {
return segment;
}
if (hasRule(IDN.toUnicode(segment), expectedType)) {
break;
}
final int nextdot = segment.indexOf('.');
final String nextSegment = nextdot != -1 ? segment.substring(nextdot + 1) : null;
if (nextSegment != null) {
if (hasRule("*." + IDN.toUnicode(nextSegment), expectedType)) {
break;
}
}
if (nextdot != -1) {
domainName = segment;
}
segment = nextSegment;
}
return domainName;
| 860
| 274
| 1,134
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/client5/http/ssl/copied/DistinguishedNameParser.java
|
DistinguishedNameParser
|
parseParameter
|
class DistinguishedNameParser {
public final static DistinguishedNameParser INSTANCE = new DistinguishedNameParser();
private static final BitSet EQUAL_OR_COMMA_OR_PLUS = TokenParser.INIT_BITSET('=', ',', '+');
private static final BitSet COMMA_OR_PLUS = TokenParser.INIT_BITSET(',', '+');
private final TokenParser tokenParser;
DistinguishedNameParser() {
this.tokenParser = new InternalTokenParser();
}
private String parseToken(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) {
return tokenParser.parseToken(buf, cursor, delimiters);
}
private String parseValue(final CharArrayBuffer buf, final ParserCursor cursor, final BitSet delimiters) {
return tokenParser.parseValue(buf, cursor, delimiters);
}
private NameValuePair parseParameter(final CharArrayBuffer buf, final ParserCursor cursor) {<FILL_FUNCTION_BODY>}
List<NameValuePair> parse(final CharArrayBuffer buf, final ParserCursor cursor) {
final List<NameValuePair> params = new ArrayList<>();
tokenParser.skipWhiteSpace(buf, cursor);
while (!cursor.atEnd()) {
final NameValuePair param = parseParameter(buf, cursor);
params.add(param);
}
return params;
}
List<NameValuePair> parse(final String s) {
if (s == null) {
return null;
}
final CharArrayBuffer buffer = new CharArrayBuffer(s.length());
buffer.append(s);
final ParserCursor cursor = new ParserCursor(0, s.length());
return parse(buffer, cursor);
}
static class InternalTokenParser extends TokenParser {
@Override
public void copyUnquotedContent(
final CharSequence buf,
final ParserCursor cursor,
final BitSet delimiters,
final StringBuilder dst) {
int pos = cursor.getPos();
final int indexFrom = cursor.getPos();
final int indexTo = cursor.getUpperBound();
boolean escaped = false;
for (int i = indexFrom; i < indexTo; i++, pos++) {
final char current = buf.charAt(i);
if (escaped) {
dst.append(current);
escaped = false;
} else {
if ((delimiters != null && delimiters.get(current))
|| TokenParser.isWhitespace(current) || current == '\"') {
break;
} else if (current == '\\') {
escaped = true;
} else {
dst.append(current);
}
}
}
cursor.updatePos(pos);
}
}
}
|
final String name = parseToken(buf, cursor, EQUAL_OR_COMMA_OR_PLUS);
if (cursor.atEnd()) {
return new BasicNameValuePair(name, null);
}
final int delim = buf.charAt(cursor.getPos());
cursor.updatePos(cursor.getPos() + 1);
if (delim == ',') {
return new BasicNameValuePair(name, null);
}
final String value = parseValue(buf, cursor, COMMA_OR_PLUS);
if (!cursor.atEnd()) {
cursor.updatePos(cursor.getPos() + 1);
}
return new BasicNameValuePair(name, value);
| 723
| 176
| 899
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/core5/http/message/copied/BasicNameValuePair.java
|
BasicNameValuePair
|
hashCode
|
class BasicNameValuePair implements NameValuePair, Serializable {
private static final long serialVersionUID = -6437800749411518984L;
private final String name;
private final String value;
/**
* Default Constructor taking a name and a value. The value may be null.
*
* @param name The name.
* @param value The value.
*/
public BasicNameValuePair(final String name, final String value) {
super();
this.name = Args.notNull(name, "Name");
this.value = value;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getValue() {
return this.value;
}
@Override
public String toString() {
// don't call complex default formatting for a simple toString
if (this.value == null) {
return name;
}
final int len = this.name.length() + 1 + this.value.length();
final StringBuilder buffer = new StringBuilder(len);
buffer.append(this.name);
buffer.append("=");
buffer.append(this.value);
return buffer.toString();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof BasicNameValuePair) {
final BasicNameValuePair that = (BasicNameValuePair) obj;
return this.name.equalsIgnoreCase(that.name) && LangUtils.equals(this.value, that.value);
}
return false;
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.name.toLowerCase(Locale.ROOT));
hash = LangUtils.hashCode(hash, this.value);
return hash;
| 455
| 64
| 519
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/core5/http/message/copied/ParserCursor.java
|
ParserCursor
|
updatePos
|
class ParserCursor {
private final int lowerBound;
private final int upperBound;
private int pos;
public ParserCursor(final int lowerBound, final int upperBound) {
super();
if (lowerBound < 0) {
throw new IndexOutOfBoundsException("Lower bound cannot be negative");
}
if (lowerBound > upperBound) {
throw new IndexOutOfBoundsException("Lower bound cannot be greater then upper bound");
}
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.pos = lowerBound;
}
public int getLowerBound() {
return this.lowerBound;
}
public int getUpperBound() {
return this.upperBound;
}
public int getPos() {
return this.pos;
}
public void updatePos(final int pos) {<FILL_FUNCTION_BODY>}
public boolean atEnd() {
return this.pos >= this.upperBound;
}
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append('[');
buffer.append(Integer.toString(this.lowerBound));
buffer.append('>');
buffer.append(Integer.toString(this.pos));
buffer.append('>');
buffer.append(Integer.toString(this.upperBound));
buffer.append(']');
return buffer.toString();
}
}
|
if (pos < this.lowerBound) {
throw new IndexOutOfBoundsException("pos: "+pos+" < lowerBound: "+this.lowerBound);
}
if (pos > this.upperBound) {
throw new IndexOutOfBoundsException("pos: "+pos+" > upperBound: "+this.upperBound);
}
this.pos = pos;
| 370
| 97
| 467
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/core5/net/copied/InetAddressUtils.java
|
InetAddressUtils
|
isIPv6HexCompressedAddress
|
class InetAddressUtils {
private InetAddressUtils() {
}
private static final String IPV4_BASIC_PATTERN_STRING =
"(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}" + // initial first field, 1-255
"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}" + // following 2 fields, 0-255 followed by .
"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255
private static final Pattern IPV4_PATTERN =
Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");
private static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros
Pattern.compile("^::[fF]{4}:" + IPV4_BASIC_PATTERN_STRING + "$");
private static final Pattern IPV6_STD_PATTERN =
Pattern.compile(
"^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$");
private static final Pattern IPV6_HEX_COMPRESSED_PATTERN =
Pattern.compile(
"^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)" + // 0-6 hex fields
"::" +
"(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$"); // 0-6 hex fields
/*
* The above pattern is not totally rigorous as it allows for more than 7 hex fields in total
*/
private static final char COLON_CHAR = ':';
// Must not have more than 7 colons (i.e. 8 fields)
private static final int MAX_COLON_COUNT = 7;
/**
* Checks whether the parameter is a valid IPv4 address
*
* @param input the address string to check for validity
* @return true if the input parameter is a valid IPv4 address
*/
public static boolean isIPv4Address(final String input) {
return IPV4_PATTERN.matcher(input).matches();
}
public static boolean isIPv4MappedIPv64Address(final String input) {
return IPV4_MAPPED_IPV6_PATTERN.matcher(input).matches();
}
/**
* Checks whether the parameter is a valid standard (non-compressed) IPv6 address
*
* @param input the address string to check for validity
* @return true if the input parameter is a valid standard (non-compressed) IPv6 address
*/
public static boolean isIPv6StdAddress(final String input) {
return IPV6_STD_PATTERN.matcher(input).matches();
}
/**
* Checks whether the parameter is a valid compressed IPv6 address
*
* @param input the address string to check for validity
* @return true if the input parameter is a valid compressed IPv6 address
*/
public static boolean isIPv6HexCompressedAddress(final String input) {<FILL_FUNCTION_BODY>}
/**
* Checks whether the parameter is a valid IPv6 address (including compressed).
*
* @param input the address string to check for validity
* @return true if the input parameter is a valid standard or compressed IPv6 address
*/
public static boolean isIPv6Address(final String input) {
return isIPv6StdAddress(input) || isIPv6HexCompressedAddress(input);
}
public static void formatAddress(
final StringBuilder buffer,
final SocketAddress socketAddress) {
Args.notNull(buffer, "buffer");
if (socketAddress instanceof InetSocketAddress) {
final InetSocketAddress socketaddr = (InetSocketAddress) socketAddress;
final InetAddress inetaddr = socketaddr.getAddress();
if (inetaddr != null) {
buffer.append(inetaddr.getHostAddress()).append(':').append(socketaddr.getPort());
} else {
buffer.append(socketAddress);
}
} else {
buffer.append(socketAddress);
}
}
public static String getCanonicalLocalHostName() {
try {
final InetAddress localHost = InetAddress.getLocalHost();
return localHost.getCanonicalHostName();
} catch (final UnknownHostException ex) {
return "localhost";
}
}
}
|
int colonCount = 0;
for(int i = 0; i < input.length(); i++) {
if (input.charAt(i) == COLON_CHAR) {
colonCount++;
}
}
return colonCount <= MAX_COLON_COUNT && IPV6_HEX_COMPRESSED_PATTERN.matcher(input).matches();
| 1,302
| 97
| 1,399
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/core5/util/copied/Args.java
|
Args
|
positive
|
class Args {
public static void check(final boolean expression, final String message) {
if (!expression) {
throw new IllegalArgumentException(message);
}
}
public static void check(final boolean expression, final String message, final Object... args) {
if (!expression) {
throw new IllegalArgumentException(String.format(message, args));
}
}
public static void check(final boolean expression, final String message, final Object arg) {
if (!expression) {
throw new IllegalArgumentException(String.format(message, arg));
}
}
public static long checkContentLength(final EntityDetails entityDetails) {
// -1 is a special value
// 0 is allowed as well
return checkRange(entityDetails.getContentLength(), -1, Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory)");
}
public static int checkRange(final int value, final int lowInclusive, final int highInclusive,
final String message) {
if (value < lowInclusive || value > highInclusive) {
throw illegalArgumentException("%s: %,d is out of range [%,d, %,d]", message, Integer.valueOf(value),
Integer.valueOf(lowInclusive), Integer.valueOf(highInclusive));
}
return value;
}
public static long checkRange(final long value, final long lowInclusive, final long highInclusive,
final String message) {
if (value < lowInclusive || value > highInclusive) {
throw illegalArgumentException("%s: %,d is out of range [%,d, %,d]", message, Long.valueOf(value),
Long.valueOf(lowInclusive), Long.valueOf(highInclusive));
}
return value;
}
public static <T extends CharSequence> T containsNoBlanks(final T argument, final String name) {
if (argument == null) {
throw illegalArgumentExceptionNotNull(name);
}
if (argument.length() == 0) {
throw illegalArgumentExceptionNotEmpty(name);
}
if (TextUtils.containsBlanks(argument)) {
throw new IllegalArgumentException(name + " must not contain blanks");
}
return argument;
}
private static IllegalArgumentException illegalArgumentException(final String format, final Object... args) {
return new IllegalArgumentException(String.format(format, args));
}
private static IllegalArgumentException illegalArgumentExceptionNotEmpty(final String name) {
return new IllegalArgumentException(name + " must not be empty");
}
private static IllegalArgumentException illegalArgumentExceptionNotNull(final String name) {
return new IllegalArgumentException(name + " must not be null");
}
public static <T extends CharSequence> T notBlank(final T argument, final String name) {
if (argument == null) {
throw illegalArgumentExceptionNotNull(name);
}
if (TextUtils.isBlank(argument)) {
throw new IllegalArgumentException(name + " must not be blank");
}
return argument;
}
public static <T extends CharSequence> T notEmpty(final T argument, final String name) {
if (argument == null) {
throw illegalArgumentExceptionNotNull(name);
}
if (TextUtils.isEmpty(argument)) {
throw illegalArgumentExceptionNotEmpty(name);
}
return argument;
}
public static <E, T extends Collection<E>> T notEmpty(final T argument, final String name) {
if (argument == null) {
throw illegalArgumentExceptionNotNull(name);
}
if (argument.isEmpty()) {
throw illegalArgumentExceptionNotEmpty(name);
}
return argument;
}
public static int notNegative(final int n, final String name) {
if (n < 0) {
throw illegalArgumentException("%s must not be negative: %,d", name, n);
}
return n;
}
public static long notNegative(final long n, final String name) {
if (n < 0) {
throw illegalArgumentException("%s must not be negative: %,d", name, n);
}
return n;
}
public static <T> T notNull(final T argument, final String name) {
if (argument == null) {
throw illegalArgumentExceptionNotNull(name);
}
return argument;
}
public static int positive(final int n, final String name) {
if (n <= 0) {
throw illegalArgumentException("%s must not be negative or zero: %,d", name, n);
}
return n;
}
public static long positive(final long n, final String name) {<FILL_FUNCTION_BODY>}
private Args() {
// Do not allow utility class to be instantiated.
}
}
|
if (n <= 0) {
throw illegalArgumentException("%s must not be negative or zero: %,d", name, n);
}
return n;
| 1,190
| 42
| 1,232
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/core5/util/copied/LangUtils.java
|
LangUtils
|
equals
|
class LangUtils {
public static final int HASH_SEED = 17;
public static final int HASH_OFFSET = 37;
/** Disabled default constructor. */
private LangUtils() {
}
public static int hashCode(final int seed, final int hashcode) {
return seed * HASH_OFFSET + hashcode;
}
public static int hashCode(final int seed, final boolean b) {
return hashCode(seed, b ? 1 : 0);
}
public static int hashCode(final int seed, final Object obj) {
return hashCode(seed, obj != null ? obj.hashCode() : 0);
}
/**
* Check if two objects are equal.
*
* @param obj1 first object to compare, may be {@code null}
* @param obj2 second object to compare, may be {@code null}
* @return {@code true} if the objects are equal or both null
*/
public static boolean equals(final Object obj1, final Object obj2) {<FILL_FUNCTION_BODY>}
/**
* Check if two object arrays are equal.
* <ul>
* <li>If both parameters are null, return {@code true}</li>
* <li>If one parameter is null, return {@code false}</li>
* <li>If the array lengths are different, return {@code false}</li>
* <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li>
* <li>Return {@code true}</li>
* </ul>
*
* @param a1 first array to compare, may be {@code null}
* @param a2 second array to compare, may be {@code null}
* @return {@code true} if the arrays are equal or both null
*/
public static boolean equals(final Object[] a1, final Object[] a2) {
if (a1 == null) {
return a2 == null;
}
if (a2 != null && a1.length == a2.length) {
for (int i = 0; i < a1.length; i++) {
if (!equals(a1[i], a2[i])) {
return false;
}
}
return true;
}
return false;
}
}
|
return obj1 == null ? obj2 == null : obj1.equals(obj2);
| 598
| 24
| 622
|
<no_super_class>
|
networknt_light-4j
|
light-4j/client/src/main/java/org/apache/hc/core5/util/copied/TextUtils.java
|
TextUtils
|
toHexString
|
class TextUtils {
private TextUtils() {
// Do not allow utility class to be instantiated.
}
public static boolean isEmpty(final CharSequence s) {
if (s == null) {
return true;
}
return s.length() == 0;
}
public static boolean isBlank(final CharSequence s) {
if (s == null) {
return true;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
public static boolean containsBlanks(final CharSequence s) {
if (s == null) {
return false;
}
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
return true;
}
}
return false;
}
public static String toHexString(final byte[] bytes) {<FILL_FUNCTION_BODY>}
}
|
if (bytes == null) {
return null;
}
final StringBuffer buffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
final byte b = bytes[i];
if (b < 16) {
buffer.append('0');
}
buffer.append(Integer.toHexString(b & 0xff));
}
return buffer.toString();
| 286
| 111
| 397
|
<no_super_class>
|
networknt_light-4j
|
light-4j/cluster/src/main/java/com/networknt/cluster/LightCluster.java
|
LightCluster
|
serviceToUrl
|
class LightCluster implements Cluster {
private static Logger logger = LoggerFactory.getLogger(LightCluster.class);
private static Registry registry = SingletonServiceFactory.getBean(Registry.class);
private static LoadBalance loadBalance = SingletonServiceFactory.getBean(LoadBalance.class);
public LightCluster() {
if(logger.isInfoEnabled()) logger.info("A LightCluster instance is started");
}
/**
* Implement serviceToUrl with client side service discovery.
*
* @param protocol either http or https
* @param serviceId unique service identifier - cannot be blank
* @param requestKey String
* @return Url discovered after the load balancing. Return null if the corresponding service cannot be found
*/
@Override
public String serviceToUrl(String protocol, String serviceId, String tag, String requestKey) {<FILL_FUNCTION_BODY>}
/**
*
* @param protocol either http or https
* @param serviceId unique service identifier - cannot be blank
* @param tag an environment tag use along with serviceId for discovery
* @return List of URI objects
*/
@Override
public List<URI> services(String protocol, String serviceId, String tag) {
if(StringUtils.isBlank(serviceId)) {
logger.debug("The serviceId cannot be blank");
return new ArrayList<>();
}
// transform to a list of URIs
return discovery(protocol, serviceId, tag).stream()
.map(this::toUri)
.collect(Collectors.toList());
}
private List<URL> discovery(String protocol, String serviceId, String tag) {
if(logger.isDebugEnabled()) logger.debug("protocol = " + protocol + " serviceId = " + serviceId + " tag = " + tag);
URL subscribeUrl = URLImpl.valueOf(protocol + "://localhost/" + serviceId);
if(tag != null) {
subscribeUrl.addParameter(Constants.TAG_ENVIRONMENT, tag);
}
if(logger.isDebugEnabled()) logger.debug("subscribeUrl = " + subscribeUrl);
// subscribe is async and the result won't come back immediately.
registry.subscribe(subscribeUrl, null);
// do a lookup for the quick response from either cache or registry service.
List<URL> urls = registry.discover(subscribeUrl);
if(logger.isDebugEnabled()) logger.debug("discovered urls = " + urls);
return urls;
}
private URI toUri(URL url) {
URI uri = null;
try {
uri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), null, null, null);
} catch (URISyntaxException e) {
logger.error("URISyntaxExcpetion", e);
}
return uri;
}
}
|
if(StringUtils.isBlank(serviceId)) {
logger.debug("The serviceId cannot be blank");
return null;
}
URL url = loadBalance.select(discovery(protocol, serviceId, tag), serviceId, tag, requestKey);
if (url != null) {
logger.debug("Final url after load balance = {}.", url);
// construct a url in string
return protocol + "://" + url.getHost() + ":" + url.getPort();
} else {
logger.debug("The service: {} cannot be found from service discovery.", serviceId);
return null;
}
| 715
| 158
| 873
|
<no_super_class>
|
networknt_light-4j
|
light-4j/common/src/main/java/com/networknt/common/DecryptUtil.java
|
DecryptUtil
|
decryptObject
|
class DecryptUtil {
public static Map<String, Object> decryptMap(Map<String, Object> map) {
decryptNode(map);
return map;
}
private static void decryptNode(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String)
map.put(key, decryptObject(value));
else if (value instanceof Map)
decryptNode((Map) value);
else if (value instanceof List) {
decryptList((List)value);
}
}
}
private static void decryptList(List list) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) instanceof String) {
list.set(i, decryptObject((list.get(i))));
} else if(list.get(i) instanceof Map) {
decryptNode((Map<String, Object>)list.get(i));
} else if(list.get(i) instanceof List) {
decryptList((List)list.get(i));
}
}
}
private static Object decryptObject(Object object) {<FILL_FUNCTION_BODY>}
}
|
if(object instanceof String) {
if(((String)object).startsWith(Decryptor.CRYPT_PREFIX)) {
Decryptor decryptor = SingletonServiceFactory.getBean(Decryptor.class);
if(decryptor == null) throw new RuntimeException("No implementation of Decryptor is defined in service.yml");
object = decryptor.decrypt((String)object);
}
}
return object;
| 341
| 116
| 457
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config-reload/src/main/java/com/networknt/config/reload/handler/ConfigReloadHandler.java
|
ConfigReloadHandler
|
processReloadMethod
|
class ConfigReloadHandler implements LightHttpHandler {
public static final String STARTUP_CONFIG_NAME = "startup";
public static final String CONFIG_LOADER_CLASS = "configLoaderClass";
private static final ObjectMapper mapper = Config.getInstance().getMapper();
private static final String STATUS_CONFIG_RELOAD_DISABLED = "ERR12217";
private static final String MODULE_DEFAULT = "ALL";
private static final String RELOAD_METHOD = "reload";
private static ConfigReloadConfig config;
public ConfigReloadHandler() {
if(logger.isDebugEnabled()) logger.debug("ConfigReloadHandler is constructed");
config = ConfigReloadConfig.load();
ModuleRegistry.registerModule(ConfigReloadConfig.CONFIG_NAME, ConfigReloadHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ConfigReloadConfig.CONFIG_NAME),null);
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if (config.isEnabled()) {
// this modulePlugins list contains both modules and plugins.
List<String> modulePlugins = (List)exchange.getAttachment(AttachmentConstants.REQUEST_BODY);
// the list that contains all the reloaded modules.
List<String> reloaded = new ArrayList<>();
// reload the config values.yml from the config server or local filesystem.
reLoadConfigs();
if (modulePlugins==null || modulePlugins.isEmpty() || modulePlugins.contains(MODULE_DEFAULT)) {
if (modulePlugins == null) modulePlugins = new ArrayList<>();
if (!modulePlugins.isEmpty()) modulePlugins.clear();
modulePlugins.addAll(ModuleRegistry.getModuleClasses());
modulePlugins.addAll(ModuleRegistry.getPluginClasses());
}
for (String module: modulePlugins) {
if (ModuleRegistry.getModuleClasses().contains(module)) {
String s = reloadModule(module);
if(s != null) reloaded.add(s);
} else if (ModuleRegistry.getPluginClasses().contains(module)) {
String s = reloadPlugin(module);
if(s != null) reloaded.add(s);
} else {
logger.error("Module or plugin " + module + " is not found in the registry");
}
}
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.setStatusCode(HttpStatus.OK.value());
exchange.getResponseSender().send(mapper.writeValueAsString(reloaded));
} else {
logger.error("Config reload is disabled in configReload.yml");
setExchangeStatus(exchange, STATUS_CONFIG_RELOAD_DISABLED);
}
}
private boolean processReloadMethod(Class<?> handler) {<FILL_FUNCTION_BODY>}
private String reloadModule(String module) {
try {
Class handler = Class.forName(module);
if (processReloadMethod(handler)) {
logger.info("Reload module " + module);
return module;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Handler class: " + module + " has not been found");
}
return null;
}
private String reloadPlugin(String plugin) {
// remove from the RuleLoaderStartupHook.ruleEngine.actionClassCache
Object object = RuleLoaderStartupHook.ruleEngine.actionClassCache.remove(plugin);
if (object != null) {
// recreate the module and put it into the cache.
try {
IAction ia = (IAction)Class.forName(plugin).getDeclaredConstructor().newInstance();
RuleLoaderStartupHook.ruleEngine.actionClassCache.put(plugin, ia);
} catch (Exception e) {
throw new RuntimeException("Handler class: " + plugin + " has not been found");
}
logger.info("Reload plugin " + plugin);
return plugin;
}
return null;
}
private void reLoadConfigs(){
IConfigLoader configLoader;
Map<String, Object> startupConfig = Config.getInstance().getJsonMapConfig(STARTUP_CONFIG_NAME);
if(startupConfig ==null || startupConfig.get(CONFIG_LOADER_CLASS) ==null){
configLoader = new DefaultConfigLoader();
}else{
try {
Class clazz = Class.forName((String) startupConfig.get(CONFIG_LOADER_CLASS));
configLoader = (IConfigLoader) clazz.getConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("configLoaderClass mentioned in startup.yml could not be found or constructed", e);
}
}
configLoader.reloadConfig();
}
}
|
try {
Method reload = handler.getDeclaredMethod(RELOAD_METHOD);
if(Modifier.isStatic(reload.getModifiers())) {
Object result = reload.invoke(null, null);
logger.info("Invoke static reload method " + result);
} else {
Object processorObject = handler.getDeclaredConstructor().newInstance();
Object result = reload.invoke(processorObject);
logger.info("Invoke reload method " + result);
}
return true;
} catch (Exception e) {
logger.error("Cannot invoke reload method for :" + handler.getName());
}
return false;
| 1,224
| 166
| 1,390
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config-reload/src/main/java/com/networknt/config/reload/handler/ModuleRegistryGetHandler.java
|
ModuleRegistryGetHandler
|
handleRequest
|
class ModuleRegistryGetHandler implements LightHttpHandler {
private static final ObjectMapper mapper = Config.getInstance().getMapper();
private static final String STATUS_CONFIG_RELOAD_DISABLED = "ERR12217";
public ModuleRegistryGetHandler() {
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ConfigReloadConfig config = (ConfigReloadConfig) Config.getInstance().getJsonObjectConfig(ConfigReloadConfig.CONFIG_NAME, ConfigReloadConfig.class);
if (config.isEnabled()) {
List<String> modulePlugins = new ArrayList<>();
modulePlugins.addAll(ModuleRegistry.getModuleClasses());
modulePlugins.addAll(ModuleRegistry.getPluginClasses());
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
exchange.setStatusCode(HttpStatus.OK.value());
exchange.getResponseSender().send(mapper.writeValueAsString(modulePlugins));
} else {
logger.error("Config reload is disabled in configReload.yml");
setExchangeStatus(exchange, STATUS_CONFIG_RELOAD_DISABLED);
}
| 105
| 214
| 319
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config-reload/src/main/java/com/networknt/config/reload/model/ConfigReloadConfig.java
|
ConfigReloadConfig
|
setConfigData
|
class ConfigReloadConfig {
private static final Logger logger = LoggerFactory.getLogger(ConfigReloadConfig.class);
public static final String CONFIG_NAME = "configReload";
private static final String ENABLED = "enabled";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
private ConfigReloadConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
private ConfigReloadConfig() {
this(CONFIG_NAME);
}
public static ConfigReloadConfig load(String configName) {
return new ConfigReloadConfig(configName);
}
public static ConfigReloadConfig load() {
return new ConfigReloadConfig();
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public void reload(String configName) {
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
if(getMappedConfig() != null) {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
}
| 390
| 57
| 447
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config/src/main/java/com/networknt/config/CentralizedManagement.java
|
CentralizedManagement
|
validateInjectedFieldName
|
class CentralizedManagement {
// Merge map config with values generated by ConfigInjection.class and return map
public static void mergeMap(boolean decrypt, Map<String, Object> config) {
merge(decrypt, config);
}
// Merge map config with values generated by ConfigInjection.class and return mapping object
public static Object mergeObject(boolean decrypt, Object config, Class clazz) {
merge(decrypt, config);
return convertMapToObj((Map<String, Object>) config, clazz);
}
// Search the config map recursively, expand List and Map level by level util no further expand
private static void merge(boolean decrypt, Object m1) {
if (m1 instanceof Map) {
Iterator<Object> fieldNames = ((Map<Object, Object>) m1).keySet().iterator();
String fieldName = null;
Map<String, Object> mapWithInjectedKey = new HashMap<>();
while (fieldNames.hasNext()) {
fieldName = String.valueOf(fieldNames.next());
Object field1 = ((Map<String, Object>) m1).get(fieldName);
if (field1 != null) {
if (field1 instanceof Map || field1 instanceof List) {
merge(decrypt, field1);
// Overwrite previous value when the field1 can not be expanded further
} else if (field1 instanceof String) {
// Retrieve values from ConfigInjection.class
Object injectValue = ConfigInjection.getInjectValue((String) field1, decrypt);
((Map<String, Object>) m1).put(fieldName, injectValue);
}
}
// post order, in case the key of configuration can also be injected.
Object injectedFieldName = ConfigInjection.getInjectValue(fieldName, decrypt);
// only inject when key has been changed
if (!fieldName.equals(injectedFieldName)) {
validateInjectedFieldName(fieldName, injectedFieldName);
// the map is unmodifiable during iterator, so put in another map and put it back after iteration.
mapWithInjectedKey.put((String)ConfigInjection.getInjectValue(fieldName, decrypt), field1);
fieldNames.remove();
}
}
// put back those updated keys
((Map<String, Object>) m1).putAll(mapWithInjectedKey);
} else if (m1 instanceof List) {
for (int i = 0; i < ((List<Object>) m1).size(); i++) {
Object field1 = ((List<Object>) m1).get(i);
if (field1 instanceof Map || field1 instanceof List) {
merge(decrypt, field1);
// Overwrite previous value when the field1 can not be expanded further
} else if (field1 instanceof String) {
// Retrieve values from ConfigInjection.class
Object injectValue = ConfigInjection.getInjectValue((String) field1, decrypt);
((List<Object>) m1).set(i, injectValue);
}
}
}
}
private static void validateInjectedFieldName(String fieldName, Object injectedFieldName) {<FILL_FUNCTION_BODY>}
// Method used to convert map to object based on the reference class provided
private static Object convertMapToObj(Map<String, Object> map, Class clazz) {
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.convertValue(map, clazz);
return obj;
}
}
|
if (injectedFieldName == null) {
throw new RuntimeException("the overwritten value cannot be null for key:" + fieldName);
}
if (!(injectedFieldName instanceof String)) {
throw new RuntimeException("the overwritten value for key has to be a String" + fieldName);
}
if(((String) injectedFieldName).isBlank()) {
throw new RuntimeException("the overwritten value cannot be empty for key:" + fieldName);
}
| 871
| 119
| 990
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config/src/main/java/com/networknt/config/JsonMapper.java
|
JsonMapper
|
fromJson
|
class JsonMapper {
public static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.configure(com.fasterxml.jackson.core.JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.registerModule(new JavaTimeModule());
objectMapper.registerModule(new Jdk8Module());
}
public static String toJson(Object x) {
try {
return objectMapper.writeValueAsString(x);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T fromJson(String json, Class<T> targetType) {<FILL_FUNCTION_BODY>}
public static Map<String, Object> string2Map(String s) {
try {
return objectMapper.readValue(s, new TypeReference<Map<String, Object>>(){});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static List<Map<String, Object>> string2List(String s) {
try {
return objectMapper.readValue(s, new TypeReference<List<Map<String, Object>>>(){});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
try {
return objectMapper.readValue(json, targetType);
} catch (IOException e) {
throw new RuntimeException(e);
}
| 410
| 42
| 452
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config/src/main/java/com/networknt/config/TlsUtil.java
|
TlsUtil
|
loadKeyStore
|
class TlsUtil {
static final Logger logger = LoggerFactory.getLogger(TlsUtil.class);
public static KeyStore loadKeyStore(final String name, final char[] password) {<FILL_FUNCTION_BODY>}
}
|
InputStream stream = null;
try {
stream = Config.getInstance().getInputStreamFromFile(name);
if (stream == null) {
String message = "Unable to load keystore '" + name + "', please provide the keystore matching the configuration in client.yml/server.yml to enable TLS connection.";
if (logger.isErrorEnabled()) {
logger.error(message);
}
throw new RuntimeException(message);
}
// try to load keystore as JKS
try {
KeyStore loadedKeystore = KeyStore.getInstance("JKS");
loadedKeystore.load(stream, password);
return loadedKeystore;
} catch (Exception e) {
// if JKS fails, attempt to load as PKCS12
try {
stream.close();
stream = Config.getInstance().getInputStreamFromFile(name);
KeyStore loadedKeystore = KeyStore.getInstance("PKCS12");
loadedKeystore.load(stream, password);
return loadedKeystore;
} catch (Exception e2) {
logger.error("Unable to load keystore " + name, e2);
throw new RuntimeException("Unable to load keystore " + name, e2);
}
}
} catch (Exception e) {
logger.error("Unable to load stream for keystore " + name, e);
throw new RuntimeException("Unable to load stream for keystore " + name, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
logger.error("Unable to close stream for keystore " + name, e);
}
}
}
| 62
| 435
| 497
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config/src/main/java/com/networknt/config/yml/ConfigLoaderConstructor.java
|
ConfigLoaderConstructor
|
createConfigLoader
|
class ConfigLoaderConstructor extends Constructor {
private static final Logger logger = LoggerFactory.getLogger(ConfigLoaderConstructor.class);
public static final String CONFIG_LOADER_CLASS = "configLoaderClass";
private final ConfigLoader configLoader;
public static ConfigLoaderConstructor getInstance(String configLoaderClass) {
return new ConfigLoaderConstructor(configLoaderClass);
}
private ConfigLoaderConstructor(String configLoaderClass) {
super(new LoaderOptions());
configLoader = createConfigLoader(configLoaderClass);
}
public ConfigLoader getConfigLoader() {
return configLoader;
}
private ConfigLoader createConfigLoader(String configLoaderClass) {<FILL_FUNCTION_BODY>}
}
|
if (configLoaderClass == null || configLoaderClass.equals("")) {
return null;
}
logger.debug("creating config loader {}.", configLoaderClass);
try {
Class<?> typeClass = Class.forName(configLoaderClass);
if (!typeClass.isInterface()) {
return (ConfigLoader) typeClass.getConstructor().newInstance();
} else {
logger.error("Please specify an implementing class of com.networknt.config.ConfigLoader.");
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException("Unable to construct the class loader.", e);
}
return null;
| 180
| 168
| 348
|
<no_super_class>
|
networknt_light-4j
|
light-4j/config/src/main/java/com/networknt/config/yml/DecryptConstructor.java
|
DecryptConstructor
|
createDecryptor
|
class DecryptConstructor extends Constructor {
private static final Logger logger = LoggerFactory.getLogger(DecryptConstructor.class);
private final Decryptor decryptor;
public static final String CONFIG_ITEM_DECRYPTOR_CLASS = "decryptorClass";
public static final String DEFAULT_DECRYPTOR_CLASS = AutoAESSaltDecryptor.class.getCanonicalName();
private DecryptConstructor() {
this(DEFAULT_DECRYPTOR_CLASS);
}
private DecryptConstructor(String decryptorClass) {
super(new LoaderOptions());
decryptor= createDecryptor(decryptorClass);
this.yamlConstructors.put(YmlConstants.CRYPT_TAG, new ConstructYamlDecryptedStr());
}
public static DecryptConstructor getInstance() {
return new DecryptConstructor();
}
public static DecryptConstructor getInstance(String decryptorClass) {
return new DecryptConstructor(decryptorClass);
}
private Decryptor createDecryptor(String decryptorClass) {<FILL_FUNCTION_BODY>}
public Decryptor getDecryptor() {
return decryptor;
}
public class ConstructYamlDecryptedStr extends AbstractConstruct {
@Override
public Object construct(Node node) {
return constructDecryptedScalar((ScalarNode) node);
}
private Object constructDecryptedScalar(ScalarNode node) {
return decryptor.decrypt(node.getValue());
}
}
}
|
// do not create a new decryptor if it is already created.
if(decryptor != null) {
return decryptor;
}
if (logger.isTraceEnabled()) {
logger.trace("creating decryptor {}", decryptorClass);
}
try {
Class<?> typeClass = Class.forName(decryptorClass);
if (!typeClass.isInterface()) {
return (Decryptor) typeClass.getConstructor().newInstance();
}else {
logger.error("Please specify an implementing class of com.networknt.decrypt.Decryptor.");
}
} catch (Exception e) {
logger.error(e.getMessage());
throw new RuntimeException("Unable to construct the decryptor due to lack of decryption password.", e);
}
return null;
| 384
| 219
| 603
|
<no_super_class>
|
networknt_light-4j
|
light-4j/consul/src/main/java/com/networknt/consul/ConsulHeartbeatManager.java
|
ConsulHeartbeatManager
|
run
|
class ConsulHeartbeatManager {
private static final Logger logger = LoggerFactory.getLogger(ConsulHeartbeatManager.class);
private ConsulClient client;
private String token;
// all serviceIds that need heart beats.
private ConcurrentHashSet<String> serviceIds = new ConcurrentHashSet<String>();
private ThreadPoolExecutor jobExecutor;
private ScheduledExecutorService heartbeatExecutor;
// last heart beat switcher status
private boolean lastHeartBeatSwitcherStatus = false;
private volatile boolean currentHeartBeatSwitcherStatus = false;
// switcher check times
private int switcherCheckTimes = 0;
public ConsulHeartbeatManager(ConsulClient client, String token) {
this.client = client;
this.token = token;
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(
10000);
jobExecutor = new ThreadPoolExecutor(5, 30, 30 * 1000,
TimeUnit.MILLISECONDS, workQueue);
}
public void start() {
heartbeatExecutor.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {<FILL_FUNCTION_BODY>}
}, ConsulConstants.SWITCHER_CHECK_CIRCLE,
ConsulConstants.SWITCHER_CHECK_CIRCLE, TimeUnit.MILLISECONDS);
}
/**
* check heart beat switcher status, if switcher is changed, then change lastHeartBeatSwitcherStatus
* to the latest status.
*
* @param switcherStatus
* @return
*/
private boolean isSwitcherChange(boolean switcherStatus) {
boolean ret = false;
if (switcherStatus != lastHeartBeatSwitcherStatus) {
ret = true;
lastHeartBeatSwitcherStatus = switcherStatus;
logger.info("heartbeat switcher change to " + switcherStatus);
}
return ret;
}
protected void processHeartbeat(boolean isPass) {
for (String serviceId : serviceIds) {
try {
jobExecutor.execute(new HeartbeatJob(serviceId, isPass));
} catch (RejectedExecutionException ree) {
logger.error("execute heartbeat job fail! serviceId:"
+ serviceId + " is rejected");
}
}
}
public void close() {
heartbeatExecutor.shutdown();
jobExecutor.shutdown();
logger.info("Consul heartbeatManager closed.");
}
/**
* Add consul serviceId,added serviceId will set passing status to keep sending heart beat.
*
* @param serviceId service Id
*/
public void addHeartbeatServcieId(String serviceId) {
serviceIds.add(serviceId);
}
/**
* remove serviceId,corresponding serviceId won't send heart beat
*
* @param serviceId service Id
*/
public void removeHeartbeatServiceId(String serviceId) {
serviceIds.remove(serviceId);
}
// check if heart beat switcher is on
private boolean isHeartbeatOpen() {
return currentHeartBeatSwitcherStatus;
}
public void setHeartbeatOpen(boolean open) {
currentHeartBeatSwitcherStatus = open;
}
class HeartbeatJob implements Runnable {
private String serviceId;
private boolean isPass;
public HeartbeatJob(String serviceId, boolean isPass) {
super();
this.serviceId = serviceId;
this.isPass = isPass;
}
@Override
public void run() {
try {
if (isPass) {
client.checkPass(serviceId, token);
} else {
client.checkFail(serviceId, token);
}
} catch (Exception e) {
logger.error(
"consul heartbeat-set check pass error!serviceId:"
+ serviceId, e);
}
}
}
public void setClient(ConsulClient client) {
this.client = client;
}
}
|
// Because consul check set pass triggers consul
// server write operation,frequently heart beat will impact consul
// performance,so heart beat takes long cycle and switcher check takes short cycle.
// multiple check on switcher and then send one heart beat to consul server.
// TODO change to switcher listener approach.
try {
boolean switcherStatus = isHeartbeatOpen();
if (isSwitcherChange(switcherStatus)) { // heart beat switcher status changed
processHeartbeat(switcherStatus);
} else {// heart beat switcher status not changed.
if (switcherStatus) {// switcher is on, check MAX_SWITCHER_CHECK_TIMES and then send a heart beat
switcherCheckTimes++;
if (switcherCheckTimes >= ConsulConstants.MAX_SWITCHER_CHECK_TIMES) {
processHeartbeat(true);
switcherCheckTimes = 0;
}
}
}
} catch (Exception e) {
logger.error("consul heartbeat executor err:",
e);
}
| 1,075
| 280
| 1,355
|
<no_super_class>
|
networknt_light-4j
|
light-4j/consul/src/main/java/com/networknt/consul/ConsulRecoveryManager.java
|
ConsulRecoveryManager
|
newFailedAttempt
|
class ConsulRecoveryManager {
private static final Logger logger = LoggerFactory.getLogger(ConsulRecoveryManager.class);
private static final ConsulConfig config =
(ConsulConfig) Config.getInstance().getJsonObjectConfig(ConsulConstants.CONFIG_NAME, ConsulConfig.class);
private static final AtomicBoolean shutdown = new AtomicBoolean(false);
private static final AtomicBoolean monitorThreadStarted = new AtomicBoolean(false);
private static final ConcurrentHashMap<String,Long> heartbeats = new ConcurrentHashMap<>();
private static final ConsulThreadMonitor consulThreadMonitor = new ConsulThreadMonitor(heartbeats);
private boolean isRecoveryMode;
private long recoveryAttempts = 0;
private String serviceName;
public ConsulRecoveryManager(String serviceName) {
this.serviceName = serviceName;
startConsulThreadMonitor();
}
private static void startConsulThreadMonitor() {
if(monitorThreadStarted.get()) return;
if(monitorThreadStarted.compareAndSet(false, true)) {
logger.debug("Starting Consul Thread Monitor...");
consulThreadMonitor.start();
}
}
/**
* Exit Consul connection recovery mode
*
* @return the previous recovery mode state
*/
public boolean exitRecoveryMode() {
recoveryAttempts = 0;
boolean oldMode = isRecoveryMode;
isRecoveryMode = false;
return oldMode;
}
/**
* Record a new failed attempt to recover the Consul connection
*
* @return true if additional failed attempts are permitted
* false if this new failed attempt was the last permitted attempt
*/
public boolean newFailedAttempt() {<FILL_FUNCTION_BODY>}
/**
* Gracefully shuts down the host application
*/
public static synchronized void gracefulShutdown() {
if(shutdown.get()) return;
logger.error("System shutdown initiated - Consul connection could not be reestablished");
shutdown.set(true);
System.exit(1);
}
public void checkin() {
logger.debug("Service {} checking in", serviceName);
heartbeats.put(serviceName, System.currentTimeMillis());
}
public boolean isRecoveryMode() { return isRecoveryMode; }
public long getRecoveryAttempts() { return recoveryAttempts; }
public String getServiceName() { return serviceName; }
public void setServiceName(String serviceName) { this.serviceName = serviceName; }
}
|
isRecoveryMode = true;
++recoveryAttempts;
logger.error("Recovery mode: Fixing Consul Connection for service {} - attempt {}...", serviceName, recoveryAttempts);
if(config.getMaxAttemptsBeforeShutdown() == -1) return true;
return config.getMaxAttemptsBeforeShutdown() >= recoveryAttempts;
| 648
| 94
| 742
|
<no_super_class>
|
networknt_light-4j
|
light-4j/consul/src/main/java/com/networknt/consul/ConsulService.java
|
ConsulService
|
toString
|
class ConsulService {
static ConsulConfig config = (ConsulConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ConsulConfig.class);
private String id;
private String name;
private List<String> tags;
private String address;
private Integer port;
private String checkString;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) { this.port = port; }
public ConsulService() {
if(config.tcpCheck) {
checkString = ",\"Check\":{\"CheckID\":\"check-%s\",\"DeregisterCriticalServiceAfter\":\"" + config.deregisterAfter + "\",\"TCP\":\"%s:%s\",\"Interval\":\"" + config.checkInterval + "\"}}";
} else if(config.httpCheck) {
checkString = ",\"Check\":{\"CheckID\":\"check-%s\",\"DeregisterCriticalServiceAfter\":\"" + config.deregisterAfter + "\",\"HTTP\":\"" + "https://%s:%s/health/%s" + "\",\"TLSSkipVerify\":true,\"Interval\":\"" + config.checkInterval + "\"}}";
} else {
checkString = ",\"Check\":{\"CheckID\":\"check-%s\",\"DeregisterCriticalServiceAfter\":\"" + config.deregisterAfter + "\",\"TTL\":\"" + config.checkInterval + "\"}}";
}
}
/**
* Construct a register json payload. Note that deregister internal minimum is 1m.
*
* @return String
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String s = tags.stream().map(Object::toString).collect(Collectors.joining("\",\""));
return "{\"ID\":\"" + id +
"\",\"Name\":\"" + name
+ "\",\"Tags\":[\"" + s
+ "\"],\"Address\":\"" + address
+ "\",\"Port\":" + port
+ String.format(checkString, id, address, port, name);
| 597
| 112
| 709
|
<no_super_class>
|
networknt_light-4j
|
light-4j/consul/src/main/java/com/networknt/consul/ConsulThreadMonitor.java
|
ConsulThreadMonitor
|
run
|
class ConsulThreadMonitor extends Thread {
private static final Logger logger = LoggerFactory.getLogger(ConsulThreadMonitor.class);
private static final ConsulConfig config =
(ConsulConfig) Config.getInstance().getJsonObjectConfig(ConsulConstants.CONFIG_NAME, ConsulConfig.class);
private final ConcurrentHashMap<String,Long> checkins;
private boolean shutdownIfThreadFrozen = config.isShutdownIfThreadFrozen();
private static final long WAIT_S = ConsulUtils.getWaitInSecond(config.getWait());
private static final long TIMEOUT_BUFFER_S = ConsulUtils.getTimeoutBufferInSecond(config.getTimeoutBuffer());
private static final long LOOKUP_INTERVAL_S = config.getLookupInterval();
// MIN_TIME_BETWEEN_CHECKINS_MS accounts for queue-wait time to enter connection pool synchronized methods (for up to 12 queued threads)
private static final long MIN_TIME_BETWEEN_CHECKINS_MS = 12 * 10 * 1000;
private static final long MAX_TIME_BETWEEN_CHECKINS_MS = Math.max(2 * 1000 * ( LOOKUP_INTERVAL_S + WAIT_S + TIMEOUT_BUFFER_S ), MIN_TIME_BETWEEN_CHECKINS_MS);
public ConsulThreadMonitor(final ConcurrentHashMap<String,Long> checkins) {
this.checkins = checkins;
}
public void run() {<FILL_FUNCTION_BODY>}
}
|
long now;
while(true) {
try {
Thread.sleep(MAX_TIME_BETWEEN_CHECKINS_MS);
now = System.currentTimeMillis();
for(Map.Entry<String,Long> checkin : checkins.entrySet()) {
if(now - checkin.getValue().longValue() > MAX_TIME_BETWEEN_CHECKINS_MS) {
if(shutdownIfThreadFrozen) {
logger.error("Service {} has missed its check in... Shutting down host...", checkin.getKey());
ConsulRecoveryManager.gracefulShutdown();
} else
logger.error("Service {} has missed its check in - Please restart host", checkin.getKey());
} else
logger.debug("Service {} checked in on time", checkin.getKey());
}
} catch (InterruptedException i) { logger.error("Consul Monitor Thread Interrupted", i);
} catch (Exception e) { logger.error("Consul Monitor Thread Exception", e); }
}
| 390
| 258
| 648
|
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
|
networknt_light-4j
|
light-4j/consul/src/main/java/com/networknt/consul/ConsulUtils.java
|
ConsulUtils
|
isSame
|
class ConsulUtils {
/**
* Check if two lists have the same urls.
*
* @param urls1 first url list
* @param urls2 second url list
* @return boolean true when they are the same
*/
public static boolean isSame(List<URL> urls1, List<URL> urls2) {<FILL_FUNCTION_BODY>}
/**
* build consul service from url
*
* @param url a URL object
* @return ConsulService consul service
*/
public static ConsulService buildService(URL url) {
ConsulService service = new ConsulService();
service.setAddress(url.getHost());
service.setId(ConsulUtils.convertConsulSerivceId(url));
service.setName(url.getPath());
service.setPort(url.getPort());
List<String> tags = new ArrayList<String>();
String env = url.getParameter(Constants.TAG_ENVIRONMENT);
if(env != null) tags.add(env);
service.setTags(tags);
return service;
}
/**
* build url from service
* @param protocol the protocol of the service
* @param service consul service
* @return URL object
*/
public static URL buildUrl(String protocol, ConsulService service) {
URL url = null;
if (url == null) {
Map<String, String> params = new HashMap<String, String>();
//String group = service.getName();
//params.put(URLParamType.group.getName(), group);
//params.put(URLParamType.nodeType.getName(), Constants.NODE_TYPE_SERVICE);
if (!service.getTags().isEmpty()) {
params.put(URLParamType.environment.getName(), service.getTags().get(0));
}
url = new URLImpl(protocol, service.getAddress(), service.getPort(),
ConsulUtils.getPathFromServiceId(service.getId()), params);
}
return url;
}
/**
* get cluster info from url, cluster info (protocol, path)
*
* @param url a URL object
* @return String url cluster info
*/
public static String getUrlClusterInfo(URL url) {
return url.getPath();
}
/**
* convert group to service name
*
* @param group group
* @return String service name
*/
public static String convertGroupToServiceName(String group) {
return group;
}
/**
* get group from consul service
*
* @param group group
* @return group
*/
public static String getGroupFromServiceName(String group) {
return group;
}
/**
* convert url to consul service id. serviceid includes ip+port+service
*
* @param url a URL object
* @return service id
*/
public static String convertConsulSerivceId(URL url) {
if (url == null) {
return null;
}
return convertServiceId(url.getHost(), url.getPort(), url.getPath());
}
/**
* get path of url from service id in consul
*
* @param serviceId service id
* @return path
*/
public static String getPathFromServiceId(String serviceId) {
return serviceId.substring(serviceId.indexOf(":") + 1, serviceId.lastIndexOf(":"));
}
/**
* get protocol from consul tag
*
* @param tag tag
* @return protocol
*/
public static String getProtocolFromTag(String tag) {
return tag.substring(ConsulConstants.CONSUL_TAG_LIGHT_PROTOCOL.length());
}
public static String convertServiceId(String host, int port, String path) {
return host + ":" + path + ":" + port;
}
/**
* convert the string wait to integer seconds from the config file. The possible format might be
* 600s or 10m etc. And the result will be 600 after the conversion.
*
* @param wait String format of wait from the config
* @return int of the wait seconds
*/
public static int getWaitInSecond(String wait) {
int w = 600;
if(wait.endsWith("s")) {
w = Integer.valueOf(wait.substring(0, wait.length() - 1));
} else if (wait.endsWith("m")) {
w = Integer.valueOf(wait.substring(0, wait.length() - 1)) * 60;
}
return w;
}
/**
* convert the string timeoutBuffer to integer seconds from the config file. The possible format might be
* 600s or 10m etc. And the result will be 600 after the conversion.
*
* Default timeoutBuffer value is 5s
*
* @param timeoutBuffer String format of timeoutBuffer from the config
* @return int of the timeoutBuffer in seconds
*/
public static int getTimeoutBufferInSecond(String timeoutBuffer) {
int w = 5;
if(timeoutBuffer.endsWith("s")) {
w = Integer.valueOf(timeoutBuffer.substring(0, timeoutBuffer.length() - 1));
} else if (timeoutBuffer.endsWith("m")) {
w = Integer.valueOf(timeoutBuffer.substring(0, timeoutBuffer.length() - 1)) * 60;
}
return w;
}
}
|
if(urls1 == null && urls2 == null) {
return true;
}
if (urls1 == null || urls2 == null) {
return false;
}
if (urls1.size() != urls2.size()) {
return false;
}
return urls1.containsAll(urls2);
| 1,422
| 94
| 1,516
|
<no_super_class>
|
networknt_light-4j
|
light-4j/content/src/main/java/com/networknt/content/ContentConfig.java
|
ContentConfig
|
setConfigData
|
class ContentConfig {
public static final String CONFIG_NAME = "content";
private static final String ENABLED = "enabled";
private static final String CONTENT_TYPE = "contentType";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
String contentType;
private ContentConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
private ContentConfig() {
this(CONFIG_NAME);
}
public static ContentConfig load(String configName) {
return new ContentConfig(configName);
}
public static ContentConfig load() {
return new ContentConfig();
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public void reload(String configName) {
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
if(getMappedConfig() != null) {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = getMappedConfig().get(CONTENT_TYPE);
if(object != null) contentType = (String)object;
}
| 415
| 90
| 505
|
<no_super_class>
|
networknt_light-4j
|
light-4j/content/src/main/java/com/networknt/content/ContentHandler.java
|
ContentHandler
|
reload
|
class ContentHandler implements MiddlewareHandler {
public static ContentConfig config;
private volatile HttpHandler next;
public ContentHandler() {
config = ContentConfig.load();
}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(ContentConfig.CONFIG_NAME, ContentConfig.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ContentConfig.CONFIG_NAME), null);
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if (exchange.getRequestHeaders().contains(Headers.CONTENT_TYPE)) {
exchange
.getResponseHeaders()
.put(Headers.CONTENT_TYPE, exchange.getRequestHeaders().get(Headers.CONTENT_TYPE).element());
} else {
exchange
.getResponseHeaders()
.put(Headers.CONTENT_TYPE, config.getContentType());
}
Handler.next(exchange, next);
}
@Override
public void reload() {<FILL_FUNCTION_BODY>}
}
|
config.reload();
ModuleRegistry.registerModule(ContentConfig.CONFIG_NAME, ContentConfig.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ContentConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) {
logger.info("ContentHandler is enabled.");
}
| 360
| 81
| 441
|
<no_super_class>
|
networknt_light-4j
|
light-4j/correlation-config/src/main/java/com/networknt/correlation/CorrelationConfig.java
|
CorrelationConfig
|
setConfigData
|
class CorrelationConfig {
public static final String CONFIG_NAME = "correlation";
private static final String ENABLED = "enabled";
private static final String AUTOGEN_CORRELATION_ID = "autogenCorrelationID";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
boolean autogenCorrelationID;
private CorrelationConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
private CorrelationConfig() {
this(CONFIG_NAME);
}
public static CorrelationConfig load(String configName) {
return new CorrelationConfig(configName);
}
public static CorrelationConfig load() {
return new CorrelationConfig();
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public void reload(String configName) {
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAutogenCorrelationID() {
return autogenCorrelationID;
}
public void setAutogenCorrelationID(boolean autogenCorrelationID) {
this.autogenCorrelationID = autogenCorrelationID;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
if(getMappedConfig() != null) {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = getMappedConfig().get(AUTOGEN_CORRELATION_ID);
if(object != null) autogenCorrelationID = Config.loadBooleanValue(AUTOGEN_CORRELATION_ID, object);
}
| 452
| 115
| 567
|
<no_super_class>
|
networknt_light-4j
|
light-4j/correlation/src/main/java/com/networknt/correlation/CorrelationHandler.java
|
CorrelationHandler
|
handleRequest
|
class CorrelationHandler implements MiddlewareHandler {
private static final Logger logger = LoggerFactory.getLogger(CorrelationHandler.class);
private static final String CID = "cId";
public static CorrelationConfig config;
private volatile HttpHandler next;
public CorrelationHandler() {
config = CorrelationConfig.load();
if(logger.isInfoEnabled()) logger.info("CorrelationHandler is loaded.");
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(CorrelationConfig.CONFIG_NAME, CorrelationHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CorrelationConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(CorrelationConfig.CONFIG_NAME, CorrelationHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CorrelationConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) {
logger.info("CorrelationHandler is enabled.");
}
}
}
|
if(logger.isDebugEnabled()) logger.debug("CorrelationHandler.handleRequest starts.");
// check if the cid is in the request header
String cId = exchange.getRequestHeaders().getFirst(HttpStringConstants.CORRELATION_ID);
if(cId == null) {
// if not set, check the autogen flag and generate if set to true
if(config.isAutogenCorrelationID()) {
// generate a UUID and put it into the request header
cId = Util.getUUID();
exchange.getRequestHeaders().put(HttpStringConstants.CORRELATION_ID, cId);
String tId = exchange.getRequestHeaders().getFirst(HttpStringConstants.TRACEABILITY_ID);
if(tId != null && logger.isInfoEnabled()) {
logger.info("Associate traceability Id " + tId + " with correlation Id " + cId);
}
}
}
// Add the cId into MDC so that all log statement will have cId as part of it.
MDC.put(CID, cId);
if (cId != null) {
this.addHandlerMDCContext(exchange, CID, cId);
}
// This is usually the first handler in the request/response chain, log all the request headers here for diagnostic purpose.
if(logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder();
for (HeaderValues header : exchange.getRequestHeaders()) {
for (String value : header) {
sb.append(header.getHeaderName()).append("=").append(value).append("\n");
}
}
logger.trace("Request Headers: " + sb);
}
if(logger.isDebugEnabled()) logger.debug("CorrelationHandler.handleRequest ends.");
Handler.next(exchange, next);
| 396
| 464
| 860
|
<no_super_class>
|
networknt_light-4j
|
light-4j/cors/src/main/java/com/networknt/cors/CorsConfig.java
|
CorsConfig
|
setConfigList
|
class CorsConfig {
private static final Logger logger = LoggerFactory.getLogger(CorsConfig.class);
public static final String CONFIG_NAME = "cors";
private static final String ENABLED = "enabled";
private static final String ALLOWED_ORIGINS = "allowedOrigins";
private static final String ALLOWED_METHODS = "allowedMethods";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
List<String> allowedOrigins;
List<String> allowedMethods;
private CorsConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
private CorsConfig() {
this(CONFIG_NAME);
}
public static CorsConfig load(String configName) {
return new CorsConfig(configName);
}
public static CorsConfig load() {
return new CorsConfig();
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
public void reload(String configName) {
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public List getAllowedOrigins() {
return allowedOrigins;
}
public void setAllowedOrigins(List allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public List getAllowedMethods() {
return allowedMethods;
}
public void setAllowedMethods(List allowedMethods) {
this.allowedMethods = allowedMethods;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setConfigData() {
if(getMappedConfig() != null) {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
}
}
private void setConfigList() {<FILL_FUNCTION_BODY>}
}
|
if (mappedConfig != null && mappedConfig.get(ALLOWED_ORIGINS) != null) {
Object object = mappedConfig.get(ALLOWED_ORIGINS);
allowedOrigins = new ArrayList<>();
if(object instanceof String) {
String s = (String)object;
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
if(s.startsWith("[")) {
// json format
try {
allowedOrigins = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the skipPathPrefixes json with a list of strings.");
}
} else {
// comma separated
allowedOrigins = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (object instanceof List) {
List prefixes = (List)object;
prefixes.forEach(item -> {
allowedOrigins.add((String)item);
});
} else {
throw new ConfigException("allowedOrigins must be a string or a list of strings.");
}
}
if (mappedConfig != null && mappedConfig.get(ALLOWED_METHODS) != null) {
Object object = mappedConfig.get(ALLOWED_METHODS);
allowedMethods = new ArrayList<>();
if(object instanceof String) {
String s = (String)object;
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
if(s.startsWith("[")) {
// json format
try {
allowedMethods = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the skipPathPrefixes json with a list of strings.");
}
} else {
// comma separated
allowedMethods = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (object instanceof List) {
List<String> prefixes = (List)object;
allowedMethods.addAll(prefixes);
} else {
throw new ConfigException("allowedMethods must be a string or a list of strings.");
}
}
| 622
| 594
| 1,216
|
<no_super_class>
|
networknt_light-4j
|
light-4j/cors/src/main/java/com/networknt/cors/CorsHttpHandler.java
|
CorsHttpHandler
|
setCorsResponseHeaders
|
class CorsHttpHandler implements MiddlewareHandler {
public static CorsConfig config;
private static Collection<String> allowedOrigins;
private static Collection<String> allowedMethods;
private volatile HttpHandler next;
/** Default max age **/
private static final long ONE_HOUR_IN_SECONDS = 60 * 60;
public CorsHttpHandler() {
config = CorsConfig.load();
allowedOrigins = config.getAllowedOrigins();
allowedMethods = config.getAllowedMethods();
if(logger.isInfoEnabled()) logger.info("CorsHttpHandler is loaded.");
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("CorsHttpHandler.handleRequest starts.");
HeaderMap headers = exchange.getRequestHeaders();
if (CorsUtil.isCoreRequest(headers)) {
if (isPreflightedRequest(exchange)) {
handlePreflightRequest(exchange);
return;
}
setCorsResponseHeaders(exchange);
}
if(logger.isDebugEnabled()) logger.debug("CorsHttpHandler.handleRequest ends.");
Handler.next(exchange, next);
}
private void handlePreflightRequest(HttpServerExchange exchange) throws Exception {
setCorsResponseHeaders(exchange);
HANDLE_200.handleRequest(exchange);
}
private void setCorsResponseHeaders(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(CorsConfig.CONFIG_NAME, CorsHttpHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CorsConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(CorsConfig.CONFIG_NAME, CorsHttpHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CorsConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) {
logger.info("CorsHttpHandler is enabled.");
}
}
}
|
HeaderMap headers = exchange.getRequestHeaders();
if (headers.contains(Headers.ORIGIN)) {
if(matchOrigin(exchange, allowedOrigins) != null) {
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_ORIGIN, headers.get(Headers.ORIGIN));
exchange.getResponseHeaders().add(Headers.VARY, Headers.ORIGIN_STRING);
}
}
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_METHODS, allowedMethods);
HeaderValues requestedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS);
if (requestedHeaders != null && !requestedHeaders.isEmpty()) {
exchange.getResponseHeaders().addAll(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders);
} else {
exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.CONTENT_TYPE_STRING);
exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.WWW_AUTHENTICATE_STRING);
exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, Headers.AUTHORIZATION_STRING);
}
exchange.getResponseHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
exchange.getResponseHeaders().add(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS);
| 651
| 386
| 1,037
|
<no_super_class>
|
networknt_light-4j
|
light-4j/cors/src/main/java/com/networknt/cors/CorsUtil.java
|
CorsUtil
|
matchOrigin
|
class CorsUtil {
private static final Logger logger = LoggerFactory.getLogger(CorsUtil.class);
public static boolean isCoreRequest(HeaderMap headers) {
return headers.contains(ORIGIN)
|| headers.contains(ACCESS_CONTROL_REQUEST_HEADERS)
|| headers.contains(ACCESS_CONTROL_REQUEST_METHOD);
}
/**
* Match the Origin header with the allowed origins.
* If it doesn't match then a 403 response code is set on the response and it returns null.
* @param exchange the current HttpExchange.
* @param allowedOrigins list of sanitized allowed origins.
* @return the first matching origin, null otherwise.
* @throws Exception the checked exception
*/
public static String matchOrigin(HttpServerExchange exchange, Collection<String> allowedOrigins) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Determine the default origin, to allow for local access.
* @param exchange the current HttpExchange.
* @return the default origin (aka current server).
*/
public static String defaultOrigin(HttpServerExchange exchange) {
String host = NetworkUtils.formatPossibleIpv6Address(exchange.getHostName());
String protocol = exchange.getRequestScheme();
int port = exchange.getHostPort();
//This browser set header should not need IPv6 escaping
StringBuilder allowedOrigin = new StringBuilder(256);
allowedOrigin.append(protocol).append("://").append(host);
if (!isDefaultPort(port, protocol)) {
allowedOrigin.append(':').append(port);
}
return allowedOrigin.toString();
}
private static boolean isDefaultPort(int port, String protocol) {
return (("http".equals(protocol) && 80 == port) || ("https".equals(protocol) && 443 == port));
}
/**
* Removes the port from a URL if this port is the default one for the URL's scheme.
* @param url the url to be sanitized.
* @return the sanitized url.
*/
public static String sanitizeDefaultPort(String url) {
int afterSchemeIndex = url.indexOf("://");
if(afterSchemeIndex < 0) {
return url;
}
String scheme = url.substring(0, afterSchemeIndex);
int fromIndex = scheme.length() + 3;
//Let's see if it is an IPv6 Address
int ipv6StartIndex = url.indexOf('[', fromIndex);
if (ipv6StartIndex > 0) {
fromIndex = url.indexOf(']', ipv6StartIndex);
}
int portIndex = url.indexOf(':', fromIndex);
if(portIndex >= 0) {
int port = Integer.parseInt(url.substring(portIndex + 1));
if(isDefaultPort(port, scheme)) {
return url.substring(0, portIndex);
}
}
return url;
}
public static boolean isPreflightedRequest(HttpServerExchange exchange) {
return Methods.OPTIONS.equals(exchange.getRequestMethod()) && isCoreRequest(exchange.getRequestHeaders());
}
}
|
HeaderMap headers = exchange.getRequestHeaders();
String[] origins = headers.get(Headers.ORIGIN).toArray();
if(logger.isTraceEnabled()) logger.trace("origins from the request header = " + Arrays.toString(origins) + " allowedOrigins = " + allowedOrigins);
if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
for (String allowedOrigin : allowedOrigins) {
for (String origin : origins) {
if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {
return allowedOrigin;
}
}
}
}
String allowedOrigin = defaultOrigin(exchange);
if(logger.isTraceEnabled()) logger.trace("allowedOrigin from the exchange = " + allowedOrigin);
for (String origin : origins) {
if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) {
return allowedOrigin;
}
}
logger.debug("Request rejected due to HOST/ORIGIN mis-match.");
ResponseCodeHandler.HANDLE_403.handleRequest(exchange);
return null;
| 818
| 287
| 1,105
|
<no_super_class>
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/GenericDataSource.java
|
GenericDataSource
|
createDataSource
|
class GenericDataSource {
public static final String DATASOURCE = "datasource";
public static final String DB_PASSWORD = "password";
public static final String DS_NAME = "H2DataSource";
public static final String PARAMETERS = "parameters";
public static final String SETTINGS = "settings";
public static final String JDBC_URL = "jdbcUrl";
public static final String USERNAME = "username";
public static final String MAXIMUM_POOL_SIZE = "maximumPoolSize";
public static final String CONNECTION_TIMEOUT = "connectionTimeout";
private static final Logger logger = LoggerFactory.getLogger(GenericDataSource.class);
// the HikariDataSource
private HikariDataSource ds;
// the data source name
protected String dsName;
protected Map<String, Object> dataSourceMap;
public String getDsName() {
return dsName;
}
public String getDbPassKey() {
return DB_PASSWORD;
}
public GenericDataSource() {
this.dsName = DS_NAME;
this.ds = createDataSource();
}
public GenericDataSource(String dsName) {
this.dsName = dsName;
this.ds = createDataSource();
}
protected HikariDataSource createDataSource() {<FILL_FUNCTION_BODY>}
private String convertFirstLetterUpper(String field) {
return field.substring(0,1).toUpperCase() + field.substring(1);
}
/**
* Get an instance of the datasource
*
* @return the HikariDataSource object
*/
public HikariDataSource getDataSource() {
return ds;
}
public Method findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
try {
return clazz.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException ex) {
}
// Then loop through all available methods, checking them one by one.
for (Method method : clazz.getMethods()) {
String name = method.getName();
if (!methodName.equals(name)) { // The method must have right name.
continue;
}
Class<?>[] acceptedParameterTypes = method.getParameterTypes();
if (acceptedParameterTypes.length != parameterTypes.length) { // Must have right number of parameters.
continue;
}
//For some special cases, we may need add type cast or class isAssignableFrom here to verify method
return method;
}
// None of our trials was successful!
throw new NoSuchMethodException();
}
}
|
// get the configured datasources
dataSourceMap = Config.getInstance().getJsonMapConfig(DATASOURCE);
// get the requested datasource
Map<String, Object> mainParams = (Map<String, Object>) dataSourceMap.get(getDsName());
Map<String, String> configParams = (Map<String, String>)mainParams.get(PARAMETERS);
Map<String, Object> settings = (Map<String, Object>)mainParams.get(SETTINGS);
// create the DataSource
ds = new HikariDataSource();
ds.setJdbcUrl((String)mainParams.get(JDBC_URL));
ds.setUsername((String)mainParams.get(USERNAME));
// use encrypted password
String password = (String)mainParams.get(DB_PASSWORD);
ds.setPassword(password);
// set datasource paramters
ds.setMaximumPoolSize(Config.loadIntegerValue(MAXIMUM_POOL_SIZE, mainParams.get(MAXIMUM_POOL_SIZE)));
ds.setConnectionTimeout(Config.loadIntegerValue(CONNECTION_TIMEOUT, mainParams.get(CONNECTION_TIMEOUT)));
if (settings != null && settings.size()>0) {
for (Map.Entry<String, Object> entry: settings.entrySet()) {
String fieldName = entry.getKey();
try {
Method method = findMethod(ds.getClass(), "set" + convertFirstLetterUpper(fieldName), entry.getValue().getClass());
method.invoke(ds, entry.getValue());
} catch (Exception e) {
logger.error("no such set method on datasource for setting value:" + fieldName);
}
}
}
// add datasource specific connection parameters
if(configParams != null) configParams.forEach((k, v) -> ds.addDataSourceProperty(k, v));
return ds;
| 702
| 485
| 1,187
|
<no_super_class>
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/H2DataSource.java
|
H2DataSource
|
getDsName
|
class H2DataSource extends GenericDataSource {
private static final String H2_DS = "H2DataSource";
@Override
public String getDsName() {<FILL_FUNCTION_BODY>}
public H2DataSource(String dsName) {
super(dsName);
}
public H2DataSource() {
super();
}
}
|
if(dsName != null) {
return dsName;
} else {
return H2_DS;
}
| 99
| 36
| 135
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) throws java.lang.NoSuchMethodException,public HikariDataSource getDataSource() ,public java.lang.String getDbPassKey() ,public java.lang.String getDsName() <variables>public static final java.lang.String CONNECTION_TIMEOUT,public static final java.lang.String DATASOURCE,public static final java.lang.String DB_PASSWORD,public static final java.lang.String DS_NAME,public static final java.lang.String JDBC_URL,public static final java.lang.String MAXIMUM_POOL_SIZE,public static final java.lang.String PARAMETERS,public static final java.lang.String SETTINGS,public static final java.lang.String USERNAME,protected Map<java.lang.String,java.lang.Object> dataSourceMap,private HikariDataSource ds,protected java.lang.String dsName,private static final Logger logger
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/MariaDataSource.java
|
MariaDataSource
|
getDsName
|
class MariaDataSource extends GenericDataSource {
private static final String MARIA_DS = "MariaDataSource";
@Override
public String getDsName() {<FILL_FUNCTION_BODY>}
public MariaDataSource(String dsName) {
super(dsName);
}
public MariaDataSource() {
super();
}
}
|
if(dsName != null) {
return dsName;
} else {
return MARIA_DS;
}
| 97
| 36
| 133
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) throws java.lang.NoSuchMethodException,public HikariDataSource getDataSource() ,public java.lang.String getDbPassKey() ,public java.lang.String getDsName() <variables>public static final java.lang.String CONNECTION_TIMEOUT,public static final java.lang.String DATASOURCE,public static final java.lang.String DB_PASSWORD,public static final java.lang.String DS_NAME,public static final java.lang.String JDBC_URL,public static final java.lang.String MAXIMUM_POOL_SIZE,public static final java.lang.String PARAMETERS,public static final java.lang.String SETTINGS,public static final java.lang.String USERNAME,protected Map<java.lang.String,java.lang.Object> dataSourceMap,private HikariDataSource ds,protected java.lang.String dsName,private static final Logger logger
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/MysqlDataSource.java
|
MysqlDataSource
|
getDsName
|
class MysqlDataSource extends GenericDataSource {
private static final String MYSQL_DS = "MysqlDataSource";
@Override
public String getDsName() {<FILL_FUNCTION_BODY>}
public MysqlDataSource(String dsName) {
super(dsName);
}
public MysqlDataSource() {
super();
}
}
|
if(dsName != null) {
return dsName;
} else {
return MYSQL_DS;
}
| 104
| 36
| 140
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) throws java.lang.NoSuchMethodException,public HikariDataSource getDataSource() ,public java.lang.String getDbPassKey() ,public java.lang.String getDsName() <variables>public static final java.lang.String CONNECTION_TIMEOUT,public static final java.lang.String DATASOURCE,public static final java.lang.String DB_PASSWORD,public static final java.lang.String DS_NAME,public static final java.lang.String JDBC_URL,public static final java.lang.String MAXIMUM_POOL_SIZE,public static final java.lang.String PARAMETERS,public static final java.lang.String SETTINGS,public static final java.lang.String USERNAME,protected Map<java.lang.String,java.lang.Object> dataSourceMap,private HikariDataSource ds,protected java.lang.String dsName,private static final Logger logger
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/OracleDataSource.java
|
OracleDataSource
|
getDsName
|
class OracleDataSource extends GenericDataSource {
private static final String ORACLE_DS = "OracleDataSource";
@Override
public String getDsName() {<FILL_FUNCTION_BODY>}
public OracleDataSource(String dsName) {
super(dsName);
}
public OracleDataSource() {
super();
}
}
|
if(dsName != null) {
return dsName;
} else {
return ORACLE_DS;
}
| 98
| 37
| 135
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) throws java.lang.NoSuchMethodException,public HikariDataSource getDataSource() ,public java.lang.String getDbPassKey() ,public java.lang.String getDsName() <variables>public static final java.lang.String CONNECTION_TIMEOUT,public static final java.lang.String DATASOURCE,public static final java.lang.String DB_PASSWORD,public static final java.lang.String DS_NAME,public static final java.lang.String JDBC_URL,public static final java.lang.String MAXIMUM_POOL_SIZE,public static final java.lang.String PARAMETERS,public static final java.lang.String SETTINGS,public static final java.lang.String USERNAME,protected Map<java.lang.String,java.lang.Object> dataSourceMap,private HikariDataSource ds,protected java.lang.String dsName,private static final Logger logger
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/PostgresDataSource.java
|
PostgresDataSource
|
getDsName
|
class PostgresDataSource extends GenericDataSource {
private static final String POSTGRES_DS = "PostgresDataSource";
@Override
public String getDsName() {<FILL_FUNCTION_BODY>}
public PostgresDataSource(String dsName) {
super(dsName);
}
public PostgresDataSource() {
super();
}
}
|
if(dsName != null) {
return dsName;
} else {
return POSTGRES_DS;
}
| 101
| 37
| 138
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) throws java.lang.NoSuchMethodException,public HikariDataSource getDataSource() ,public java.lang.String getDbPassKey() ,public java.lang.String getDsName() <variables>public static final java.lang.String CONNECTION_TIMEOUT,public static final java.lang.String DATASOURCE,public static final java.lang.String DB_PASSWORD,public static final java.lang.String DS_NAME,public static final java.lang.String JDBC_URL,public static final java.lang.String MAXIMUM_POOL_SIZE,public static final java.lang.String PARAMETERS,public static final java.lang.String SETTINGS,public static final java.lang.String USERNAME,protected Map<java.lang.String,java.lang.Object> dataSourceMap,private HikariDataSource ds,protected java.lang.String dsName,private static final Logger logger
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/SqlServerDataSource.java
|
SqlServerDataSource
|
getDsName
|
class SqlServerDataSource extends GenericDataSource {
private static final String SQLSERVER_DS = "SqlServerDataSource";
@Override
public String getDsName() {<FILL_FUNCTION_BODY>}
public SqlServerDataSource(String dsName) {
super(dsName);
}
public SqlServerDataSource() {
super();
}
}
|
if(dsName != null) {
return dsName;
} else {
return SQLSERVER_DS;
}
| 100
| 36
| 136
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) throws java.lang.NoSuchMethodException,public HikariDataSource getDataSource() ,public java.lang.String getDbPassKey() ,public java.lang.String getDsName() <variables>public static final java.lang.String CONNECTION_TIMEOUT,public static final java.lang.String DATASOURCE,public static final java.lang.String DB_PASSWORD,public static final java.lang.String DS_NAME,public static final java.lang.String JDBC_URL,public static final java.lang.String MAXIMUM_POOL_SIZE,public static final java.lang.String PARAMETERS,public static final java.lang.String SETTINGS,public static final java.lang.String USERNAME,protected Map<java.lang.String,java.lang.Object> dataSourceMap,private HikariDataSource ds,protected java.lang.String dsName,private static final Logger logger
|
networknt_light-4j
|
light-4j/data-source/src/main/java/com/networknt/db/factory/DefaultDataSourceFactory.java
|
DefaultDataSourceFactory
|
getDataSource
|
class DefaultDataSourceFactory implements DataSourceFactory{
// use light4j datasource config
public static final String DATASOURCE = "datasource";
public static final Map<String, DataSource> dataSources = Collections.synchronizedMap(new HashMap<>());
public static final Map<String, Object> dataSourceMap = Config.getInstance().getJsonMapConfig(DATASOURCE);
@Override
public DataSource getDataSource(String name) {<FILL_FUNCTION_BODY>}
}
|
if (dataSources.containsKey(name)) {
return dataSources.get(name);
}
GenericDataSource genericDataSource = new GenericDataSource(name);
HikariDataSource hkDs = genericDataSource.getDataSource();
DataSource result = hkDs;
//Map<String, Object> mainParams = (Map<String, Object>) dataSourceMap.get(name);
//String dsClazz = StringUtils.trimToEmpty((String)mainParams.getOrDefault("dataSourceClassName", mainParams.get("DataSourceClassName")));
//TODO add XA datasource build
dataSources.put(name, result);
return result;
| 134
| 176
| 310
|
<no_super_class>
|
networknt_light-4j
|
light-4j/db-provider/src/main/java/com/networknt/db/provider/DbProviderConfig.java
|
DbProviderConfig
|
setConfigData
|
class DbProviderConfig {
public static final String CONFIG_NAME = "db-provider";
public static final String DRIVER_CLASS_NAME = "driverClassName";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String JDBC_URL = "jdbcUrl";
public static final String MAXIMUM_POOL_SIZE = "maximumPoolSize";
String driverClassName;
String username;
String password;
String jdbcUrl;
int maximumPoolSize;
private final Config config;
private Map<String, Object> mappedConfig;
private DbProviderConfig() {
this(CONFIG_NAME);
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
* @param configName String
*/
private DbProviderConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static DbProviderConfig load() {
return new DbProviderConfig();
}
public static DbProviderConfig load(String configName) {
return new DbProviderConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getJdbcUrl() {
return jdbcUrl;
}
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
public int getMaximumPoolSize() {
return maximumPoolSize;
}
public void setMaximumPoolSize(int maximumPoolSize) {
this.maximumPoolSize = maximumPoolSize;
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = mappedConfig.get(DRIVER_CLASS_NAME);
if(object != null) driverClassName = (String)object;
object = mappedConfig.get(USERNAME);
if(object != null) username = (String)object;
object = mappedConfig.get(PASSWORD);
if(object != null) password = (String)object;
object = mappedConfig.get(JDBC_URL);
if(object != null) jdbcUrl = (String)object;
object = mappedConfig.get(MAXIMUM_POOL_SIZE);
if(object != null) Config.loadIntegerValue(MAXIMUM_POOL_SIZE, object);
| 643
| 172
| 815
|
<no_super_class>
|
networknt_light-4j
|
light-4j/db-provider/src/main/java/com/networknt/db/provider/SqlDbStartupHook.java
|
SqlDbStartupHook
|
onStartup
|
class SqlDbStartupHook implements StartupHookProvider {
private static final Logger logger = LoggerFactory.getLogger(SqlDbStartupHook.class);
static DbProviderConfig config = (DbProviderConfig) Config.getInstance().getJsonObjectConfig(DbProviderConfig.CONFIG_NAME, DbProviderConfig.class);
public static HikariDataSource ds;
// key and json cache for the dropdowns.
public static CacheManager cacheManager;
@Override
public void onStartup() {<FILL_FUNCTION_BODY>}
}
|
logger.info("SqlDbStartupHook begins");
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName(config.getDriverClassName());
hikariConfig.setUsername(config.getUsername());
hikariConfig.setPassword(config.getPassword());
hikariConfig.setJdbcUrl(config.getJdbcUrl());
if(logger.isTraceEnabled()) logger.trace("jdbcUrl = " + config.getJdbcUrl());
hikariConfig.setMaximumPoolSize(config.getMaximumPoolSize());
ds = new HikariDataSource(hikariConfig);
cacheManager = CacheManager.getInstance();
List<String> masks = new ArrayList<>();
masks.add("password");
ModuleRegistry.registerModule(DbProviderConfig.CONFIG_NAME, SqlDbStartupHook.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(DbProviderConfig.CONFIG_NAME), masks);
logger.info("SqlDbStartupHook ends");
| 137
| 264
| 401
|
<no_super_class>
|
networknt_light-4j
|
light-4j/decryptor/src/main/java/com/networknt/decrypt/AESSaltDecryptor.java
|
AESSaltDecryptor
|
decrypt
|
class AESSaltDecryptor implements Decryptor {
private static final Logger logger = LoggerFactory.getLogger(AESSaltDecryptor.class);
private static final int ITERATIONS = 65536;
private static final int KEY_SIZE = 256;
private static final String STRING_ENCODING = "UTF-8";
private static final byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// cache the secret to void recreating instances for each decrypt call as all config files
// will use the same salt per application.
private Map<String, SecretKeySpec> secretMap = new ConcurrentHashMap<>();
private Cipher cipher;
IvParameterSpec ivSpec;
public AESSaltDecryptor() {
try {
// CBC = Cipher Block chaining
// PKCS5Padding Indicates that the keys are padded
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ivSpec = new IvParameterSpec(iv);
} catch (Exception e) {
logger.error("Failed to get the Cipher instance:", e);
throw new RuntimeException("Unable to initialize", e);
}
}
@Override
public String decrypt(String input) {<FILL_FUNCTION_BODY>}
protected char[] getPassword() {
return "light".toCharArray();
}
private static byte[] fromHex(String hex) throws NoSuchAlgorithmException
{
byte[] bytes = new byte[hex.length() / 2];
for(int i = 0; i < bytes.length ;i++)
{
bytes[i] = (byte)Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
}
|
if (!input.startsWith(CRYPT_PREFIX)) {
logger.error("The secret text is not started with prefix " + CRYPT_PREFIX);
throw new RuntimeException("Unable to decrypt, input string does not start with 'CRYPT'.");
}
String[] parts = input.split(":");
// need to make sure that the salt is in the secret text.
if(parts.length != 3) {
logger.error("The secret text is not formatted correctly with CRYPT:salt:hash");
throw new RuntimeException("Unable to decrypt, input string is not formatted correctly with CRYPT:salt:hash");
}
try {
byte[] salt = fromHex(parts[1]);
byte[] hash = fromHex(parts[2]);
// try to get the secret from the cache first.
SecretKeySpec secret = secretMap.get(parts[1]);
if(secret == null) {
KeySpec spec = new PBEKeySpec(getPassword(), salt, ITERATIONS, KEY_SIZE);
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey tmp = factory.generateSecret(spec);
secret = new SecretKeySpec(tmp.getEncoded(), "AES");
secretMap.put(parts[1], secret);
}
cipher.init(Cipher.DECRYPT_MODE, secret, ivSpec);
return new String(cipher.doFinal(hash), STRING_ENCODING);
} catch (Exception e) {
throw new RuntimeException("Unable to decrypt because the decrypted password is incorrect.", e);
}
| 504
| 430
| 934
|
<no_super_class>
|
networknt_light-4j
|
light-4j/decryptor/src/main/java/com/networknt/decrypt/AutoAESSaltDecryptor.java
|
AutoAESSaltDecryptor
|
isJUnitTest
|
class AutoAESSaltDecryptor extends AESSaltDecryptor {
private final static String LIGHT_4J_CONFIG_PASSWORD = "light_4j_config_password";
// All junit tests configuration are using this password to encrypt sensitive info in config files. This Decryptor
// can detect if the current thread is started by the JUnit test case so that default password is going to be used.
// In this way, all other developers can run the build locally without providing the light_4j_config_password as an
// environment variable in the .profile or .bashrc file.
private final static String DEFAULT_JUNIT_TEST_PASSWORD = "light";
static char[] password = null;
@Override
protected char[] getPassword() {
if(password != null) {
// password is cached at the class level as a static variable. Once it is resolve, it won't be retrieved again.
return password;
} else {
// The environment variable name can be in lower or upper case to be suitable for all operating systems.
String passwordStr = System.getenv(LIGHT_4J_CONFIG_PASSWORD);
if(passwordStr == null || passwordStr.trim().equals("")) {
passwordStr = System.getenv(LIGHT_4J_CONFIG_PASSWORD.toUpperCase());
}
if (passwordStr == null || passwordStr.trim().equals("")) {
// we cannot get the password from the environment, check if we are in the JUnit tests. If it is we can use the default password "light"
// as all test cases are using it to encrypt secret in config files.
if(isJUnitTest()) {
passwordStr = DEFAULT_JUNIT_TEST_PASSWORD;
} else {
throw new RuntimeException("Unable to retrieve decrypted password of configuration files from environment variables.");
}
}
password = passwordStr.toCharArray();
return password;
}
}
public static boolean isJUnitTest() {<FILL_FUNCTION_BODY>}
}
|
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getClassName().startsWith("org.junit.")) {
return true;
}
}
return false;
| 500
| 58
| 558
|
<methods>public void <init>() ,public java.lang.String decrypt(java.lang.String) <variables>private static final int ITERATIONS,private static final int KEY_SIZE,private static final java.lang.String STRING_ENCODING,private javax.crypto.Cipher cipher,private static final byte[] iv,javax.crypto.spec.IvParameterSpec ivSpec,private static final Logger logger,private Map<java.lang.String,javax.crypto.spec.SecretKeySpec> secretMap
|
networknt_light-4j
|
light-4j/decryptor/src/main/java/com/networknt/decrypt/DummyDecryptor.java
|
DummyDecryptor
|
decrypt
|
class DummyDecryptor implements Decryptor {
private static final Logger logger = LoggerFactory.getLogger(DummyDecryptor.class);
public DummyDecryptor() {
if(logger.isInfoEnabled()) logger.info("DummyDecryptor is constructed.");
}
public String decrypt(String input) {<FILL_FUNCTION_BODY>}
}
|
if (!input.startsWith(CRYPT_PREFIX)) {
logger.error("The secret text is not started with prefix " + CRYPT_PREFIX);
throw new RuntimeException("Unable to decrypt, input string does not start with 'CRYPT'.");
}
String[] parts = input.split(":");
if(parts.length != 2) {
logger.error("The secret text is not formatted correctly with CRYPT:text");
throw new RuntimeException("Unable to decrypt, input string is not formatted correctly with CRYPT:text");
}
return parts[1];
| 97
| 152
| 249
|
<no_super_class>
|
networknt_light-4j
|
light-4j/decryptor/src/main/java/com/networknt/decrypt/ManualAESSaltDescryptor.java
|
ManualAESSaltDescryptor
|
getPassword
|
class ManualAESSaltDescryptor extends AESSaltDecryptor {
@Override
protected char[] getPassword() {<FILL_FUNCTION_BODY>}
}
|
char[] password = null;
Console console = System.console();
if (console != null) {
password = console.readPassword("Password for config decryption: ");
} else {
// for IDE testing
System.out.print("Password for config decryption: ");
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
password = sc.next().toCharArray();
}
sc.close();
}
if (password == null || password.length == 0) {
throw new RuntimeException("The decrypted password of configuration files should not be empty.");
}
return password;
| 46
| 162
| 208
|
<methods>public void <init>() ,public java.lang.String decrypt(java.lang.String) <variables>private static final int ITERATIONS,private static final int KEY_SIZE,private static final java.lang.String STRING_ENCODING,private javax.crypto.Cipher cipher,private static final byte[] iv,javax.crypto.spec.IvParameterSpec ivSpec,private static final Logger logger,private Map<java.lang.String,javax.crypto.spec.SecretKeySpec> secretMap
|
networknt_light-4j
|
light-4j/deref-token/src/main/java/com/networknt/deref/DerefMiddlewareHandler.java
|
DerefMiddlewareHandler
|
handleRequest
|
class DerefMiddlewareHandler implements MiddlewareHandler {
private static final Logger logger = LoggerFactory.getLogger(DerefMiddlewareHandler.class);
private static final String CONFIG_NAME = "deref";
private static final String MISSING_AUTH_TOKEN = "ERR10002";
private static final String EMPTY_TOKEN_DEREFERENCE_RESPONSE = "ERR10044";
private static final String TOKEN_DEREFERENCE_ERROR = "ERR10045";
public static DerefConfig config =
(DerefConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, DerefConfig.class);
private volatile HttpHandler next;
public DerefMiddlewareHandler() {
if(logger.isInfoEnabled()) logger.info("DerefMiddlewareHandler is constructed.");
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(DerefConfig.CONFIG_NAME, DerefMiddlewareHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(DerefConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config = (DerefConfig)Config.getInstance().getJsonObjectConfigNoCache(DerefConfig.CONFIG_NAME, DerefConfig.class);
ModuleRegistry.registerModule(DerefConfig.CONFIG_NAME, DerefMiddlewareHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("DerefMiddlewareHandler is reloaded.");
}
}
|
// check if the token is in the request Authorization header
String token = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
if(token == null) {
setExchangeStatus(exchange, MISSING_AUTH_TOKEN);
return;
} else {
// ignore it and let it go if the token format is JWT
if(token.indexOf('.') < 0) {
// this is a by reference token
DerefRequest request = new DerefRequest(token);
String response = OauthHelper.derefToken(request);
if(response == null || response.trim().length() == 0) {
setExchangeStatus(exchange, EMPTY_TOKEN_DEREFERENCE_RESPONSE, token);
return;
}
if(response.startsWith("{")) {
// an error status returned from OAuth 2.0 provider. We cannot assume that light-oauth2
// is used but still need to convert the error message to a status to wrap the error.
setExchangeStatus(exchange, TOKEN_DEREFERENCE_ERROR, response);
return;
} else {
// now consider the response it jwt
exchange.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer " + response);
}
}
}
Handler.next(exchange, next);
| 536
| 348
| 884
|
<no_super_class>
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/BodyDumper.java
|
BodyDumper
|
dumpInputStream
|
class BodyDumper extends AbstractDumper implements IRequestDumpable, IResponseDumpable{
private static final Logger logger = LoggerFactory.getLogger(BodyDumper.class);
private String bodyContent = "";
BodyDumper(DumpConfig config, HttpServerExchange exchange) {
super(config, exchange);
}
/**
* put bodyContent to result
* @param result a Map<String, Object> you want to put dumping info to.
*/
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(StringUtils.isNotBlank(this.bodyContent)) {
result.put(DumpConstants.BODY, this.bodyContent);
}
}
/**
* impl of dumping request body to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpRequest(Map<String, Object> result) {
String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
//only dump json info
if (contentType != null && contentType.startsWith("application/json")) {
//if body info already grab by body handler, get it from attachment directly
Object requestBodyAttachment = exchange.getAttachment(AttachmentConstants.REQUEST_BODY);
if(requestBodyAttachment != null) {
dumpBodyAttachment(requestBodyAttachment);
} else {
//otherwise get it from input stream directly
dumpInputStream();
}
} else {
logger.info("unsupported contentType: {}", contentType);
}
this.putDumpInfoTo(result);
}
/**
* impl of dumping response body to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpResponse(Map<String, Object> result) {
byte[] responseBodyAttachment = exchange.getAttachment(StoreResponseStreamSinkConduit.RESPONSE);
if(responseBodyAttachment != null) {
this.bodyContent = config.isMaskEnabled() ? Mask.maskJson(new ByteArrayInputStream(responseBodyAttachment), "responseBody") : new String(responseBodyAttachment, UTF_8);
}
this.putDumpInfoTo(result);
}
/**
* read from input stream, convert it to string, put into this.bodyContent
*/
private void dumpInputStream(){<FILL_FUNCTION_BODY>}
/**
* read from body attachment from Body Handler, convert it to string, put into this.bodyContent
*/
private void dumpBodyAttachment(Object requestBodyAttachment) {
this.bodyContent = config.isMaskEnabled() ? Mask.maskJson(requestBodyAttachment, "requestBody") : requestBodyAttachment.toString();
}
@Override
public boolean isApplicableForRequest() {
return config.isRequestBodyEnabled();
}
@Override
public boolean isApplicableForResponse() {
return config.isResponseBodyEnabled();
}
}
|
//dump request body
exchange.startBlocking();
InputStream inputStream = exchange.getInputStream();
try {
if(config.isMaskEnabled() && inputStream.available() != -1) {
this.bodyContent = Mask.maskJson(inputStream, "requestBody");
} else {
try {
this.bodyContent = StringUtils.inputStreamToString(inputStream, UTF_8);
} catch (IOException e) {
logger.error(e.toString());
}
}
} catch (IOException e) {
logger.error("undertow inputstream error:" + e.getMessage());
}
| 772
| 160
| 932
|
<methods><variables>protected final non-sealed com.networknt.dump.DumpConfig config,protected final non-sealed HttpServerExchange exchange
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/CookiesDumper.java
|
CookiesDumper
|
dumpCookies
|
class CookiesDumper extends AbstractDumper implements IRequestDumpable, IResponseDumpable{
private Map<String, Object> cookieMap = new LinkedHashMap<>();
CookiesDumper(DumpConfig config, HttpServerExchange exchange) {
super(config, exchange);
}
/**
* impl of dumping request cookies to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpRequest(Map<String, Object> result) {
Iterable<Cookie> iterable = exchange.requestCookies();
dumpCookies(iterable, "requestCookies");
this.putDumpInfoTo(result);
}
/**
* impl of dumping response cookies to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpResponse(Map<String, Object> result) {
Iterable<Cookie> iterable = exchange.responseCookies();
dumpCookies(iterable, "responseCookies");
this.putDumpInfoTo(result);
}
/**
* put cookies info to cookieMap
* @param iterable Iterable of cookies
*/
private void dumpCookies(Iterable<Cookie> iterable, String maskKey) {<FILL_FUNCTION_BODY>}
/**
* put cookieMap to result
* @param result a Map you want to put dumping info to.
*/
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(this.cookieMap.size() > 0) {
result.put(DumpConstants.COOKIES, cookieMap);
}
}
@Override
public boolean isApplicableForRequest() {
return config.isRequestCookieEnabled();
}
@Override
public boolean isApplicableForResponse() {
return config.isResponseCookieEnabled();
}
}
|
Iterator<Cookie> iterator = iterable.iterator();
while(iterator.hasNext()) {
Cookie cookie = iterator.next();
if(!config.getRequestFilteredCookies().contains(cookie.getName())) {
List<Map<String, String>> cookieInfoList = new ArrayList<>();
//mask cookieValue
String cookieValue = config.isMaskEnabled() ? Mask.maskRegex(cookie.getValue(), maskKey, cookie.getName()) : cookie.getValue();
cookieInfoList.add(new HashMap<String, String>(){{put(DumpConstants.COOKIE_VALUE, cookieValue);}});
cookieInfoList.add(new HashMap<String, String>(){{put(DumpConstants.COOKIE_DOMAIN, cookie.getDomain());}});
cookieInfoList.add(new HashMap<String, String>(){{put(DumpConstants.COOKIE_PATH, cookie.getPath());}});
cookieInfoList.add(new HashMap<String, String>(){{put(DumpConstants.COOKIE_EXPIRES, cookie.getExpires() == null ? "" : cookie.getExpires().toString());}});
this.cookieMap.put(cookie.getName(), cookieInfoList);
}
}
| 490
| 311
| 801
|
<methods><variables>protected final non-sealed com.networknt.dump.DumpConfig config,protected final non-sealed HttpServerExchange exchange
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/DumpConfig.java
|
DumpConfig
|
loadResponseConfig
|
class DumpConfig {
public static final String CONFIG_NAME = "dump";
private boolean enabled = false;
private boolean mask = false;
private String logLevel = "INFO";
private int indentSize = 4;
private boolean useJson = false;
private Map<String, Object> request;
private Map<String, Object> response;
private static Boolean DEFAULT = false;
//request settings:
private boolean requestUrlEnabled ;
private boolean requestHeaderEnabled ;
private List<String> requestFilteredHeaders;
private boolean requestCookieEnabled;
private List<String> requestFilteredCookies;
private boolean requestQueryParametersEnabled;
private List<String> requestFilteredQueryParameters;
private boolean requestBodyEnabled;
//response settings:
private boolean responseHeaderEnabled;
private List<String> responseFilteredHeaders;
private boolean responseCookieEnabled;
private List<String> responseFilteredCookies;
private boolean responseStatusCodeEnabled;
private boolean responseBodyEnabled;
public void setResponse(Map<String, Object> response) {
this.response = response == null ? new HashMap<>() : response;
loadResponseConfig(this.response);
}
public void setRequest(Map<String, Object> request) {
this.request = request == null ? new HashMap<>() : request;
loadRequestConfig(this.request);
}
private void loadRequestConfig(Map<String, Object> request) {
this.requestBodyEnabled = loadEnableConfig(request, DumpConstants.BODY);
this.requestCookieEnabled = loadEnableConfig(request, DumpConstants.COOKIES);
this.requestHeaderEnabled = loadEnableConfig(request, DumpConstants.HEADERS);
this.requestQueryParametersEnabled = loadEnableConfig(request, DumpConstants.QUERY_PARAMETERS);
this.requestUrlEnabled = loadEnableConfig(request, DumpConstants.URL);
this.requestFilteredCookies = loadFilterConfig(request, DumpConstants.FILTERED_COOKIES);
this.requestFilteredHeaders = loadFilterConfig(request, DumpConstants.FILTERED_HEADERS);
this.requestFilteredQueryParameters = loadFilterConfig(request, DumpConstants.FILTERED_QUERY_PARAMETERS);
}
private void loadResponseConfig(Map<String, Object> response) {<FILL_FUNCTION_BODY>}
private boolean loadEnableConfig(Map<String, Object> config, String optionName) {
return config.get(optionName) instanceof Boolean ? (Boolean)config.get(optionName) : DEFAULT;
}
private List<String> loadFilterConfig(Map<String, Object> config, String filterOptionName) {
return config.get(filterOptionName) instanceof List ? (List<String>)config.get(filterOptionName) : new ArrayList();
}
public boolean isEnabled() {
return enabled;
}
public boolean isRequestEnabled() {
return isEnabled() && !request.isEmpty();
}
public boolean isResponseEnabled() {
return isEnabled() && !response.isEmpty();
}
//auto-generated
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isMaskEnabled() {
return mask;
}
public void setMask(boolean mask) {
this.mask = mask;
}
public String getLogLevel() {
return logLevel;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
public int getIndentSize() { return indentSize; }
public void setIndentSize(int indentSize) {
this.indentSize = indentSize;
}
public boolean isUseJson() {
return useJson;
}
public void setUseJson(boolean useJson) {
this.useJson = useJson;
}
public Map<String, Object> getRequest() {
return request;
}
public Map<String, Object> getResponse() {
return response;
}
public boolean isRequestUrlEnabled() {
return requestUrlEnabled;
}
public boolean isRequestHeaderEnabled() {
return requestHeaderEnabled;
}
public List<String> getRequestFilteredHeaders() {
return requestFilteredHeaders;
}
public boolean isRequestCookieEnabled() {
return requestCookieEnabled;
}
public List<String> getRequestFilteredCookies() {
return requestFilteredCookies;
}
public boolean isRequestQueryParametersEnabled() {
return requestQueryParametersEnabled;
}
public List<String> getRequestFilteredQueryParameters() {
return requestFilteredQueryParameters;
}
public boolean isRequestBodyEnabled() {
return requestBodyEnabled;
}
public boolean isResponseHeaderEnabled() {
return responseHeaderEnabled;
}
public List<String> getResponseFilteredHeaders() {
return responseFilteredHeaders;
}
public boolean isResponseCookieEnabled() {
return responseCookieEnabled;
}
public List<String> getResponseFilteredCookies() {
return responseFilteredCookies;
}
public boolean isResponseStatusCodeEnabled() {
return responseStatusCodeEnabled;
}
public boolean isResponseBodyEnabled() {
return responseBodyEnabled;
}
}
|
this.responseBodyEnabled = loadEnableConfig(response, DumpConstants.BODY);
this.responseCookieEnabled = loadEnableConfig(response, DumpConstants.COOKIES);
this.responseHeaderEnabled = loadEnableConfig(response, DumpConstants.HEADERS);
this.responseStatusCodeEnabled = loadEnableConfig(response, DumpConstants.STATUS_CODE);
this.responseFilteredCookies = loadFilterConfig(response, DumpConstants.FILTERED_COOKIES);
this.responseFilteredHeaders = loadFilterConfig(response, DumpConstants.HEADERS);
| 1,364
| 143
| 1,507
|
<no_super_class>
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/DumpHandler.java
|
DumpHandler
|
handleRequest
|
class DumpHandler implements MiddlewareHandler {
private static DumpConfig config = (DumpConfig) Config.getInstance().getJsonObjectConfig(DumpConfig.CONFIG_NAME, DumpConfig.class);
private volatile HttpHandler next;
public DumpHandler() { }
@Override
public HttpHandler getNext() {
return next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(DumpConfig.CONFIG_NAME, DumpHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(DumpConfig.CONFIG_NAME), null);
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void reload() {
config = (DumpConfig)Config.getInstance().getJsonObjectConfigNoCache(DumpConfig.CONFIG_NAME, DumpConfig.class);
ModuleRegistry.registerModule(DumpConfig.CONFIG_NAME, DumpHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(DumpConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("DumpHandler is reloaded.");
}
}
|
if (exchange.isInIoThread()) {
exchange.dispatch(this);
return;
}
if(isEnabled()) {
Map<String, Object> result = new LinkedHashMap<>();
//create rootDumper which will do dumping.
RootDumper rootDumper = new RootDumper(config, exchange);
//dump request info into result right away
rootDumper.dumpRequest(result);
//only add response wrapper when response config is not set to "false"
if(config.isResponseEnabled()) {
//set Conduit to the conduit chain to store response body
exchange.addResponseWrapper((factory, exchange12) -> new StoreResponseStreamSinkConduit(factory.create(), exchange12));
}
//when complete exchange, dump response info to result, and log the result.
exchange.addExchangeCompleteListener((exchange1, nextListener) ->{
try {
rootDumper.dumpResponse(result);
//log the result
DumpHelper.logResult(result, config);
} catch (Throwable e) {
logger.error("ExchangeListener throwable", e);
} finally {
nextListener.proceed();
}
});
}
Handler.next(exchange, next);
| 379
| 319
| 698
|
<no_super_class>
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/DumpHelper.java
|
DumpHelper
|
getLoggerFuncBasedOnLevel
|
class DumpHelper {
private static Logger logger = LoggerFactory.getLogger(DumpHandler.class);
/**
* A help method to log result pojo
* @param result the map contains info that needs to be logged
*/
static void logResult(Map<String, Object> result, DumpConfig config) {
Consumer<String> loggerFunc = getLoggerFuncBasedOnLevel(config.getLogLevel());
if(config.isUseJson()) {
logResultUsingJson(result, loggerFunc);
} else {
int startLevel = -1;
StringBuilder sb = new StringBuilder("Http request/response information:");
_logResult(result, startLevel, config.getIndentSize(), sb);
loggerFunc.accept(sb.toString());
}
}
/**
* this method actually append result to result string
*/
private static <T> void _logResult(T result, int level, int indentSize, StringBuilder info) {
if(result instanceof Map) {
level += 1;
int finalLevel = level;
((Map)result).forEach((k, v) -> {
info.append("\n");
info.append(getTabBasedOnLevel(finalLevel, indentSize))
.append(k.toString())
.append(":");
_logResult(v, finalLevel, indentSize, info);
});
} else if(result instanceof List) {
int finalLevel = level;
((List)result).forEach(element -> _logResult(element, finalLevel, indentSize, info));
} else if(result instanceof String) {
info.append(" ").append(result);
} else if(result != null) {
try {
logger.warn(getTabBasedOnLevel(level, indentSize) + "{}", result);
} catch (Exception e) {
logger.error("Cannot handle this type: {}", result.getClass().getTypeName());
}
}
}
/**
*
* @param result a Map<String, Object> contains http request/response info which needs to be logged.
* @param loggerFunc Consuer<T> getLoggerFuncBasedOnLevel(config.getLogLevel())
*/
private static void logResultUsingJson(Map<String, Object> result, Consumer<String> loggerFunc) {
ObjectMapper mapper = new ObjectMapper();
String resultJson = "";
try {
resultJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
} catch (JsonProcessingException e) {
logger.error(e.toString());
}
if(StringUtils.isNotBlank(resultJson)){
loggerFunc.accept("Dump Info:\n" + resultJson);
}
}
/**
* calculate indent for formatting
* @return " " string of empty spaces
*/
private static String getTabBasedOnLevel(int level, int indentSize) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < level; i ++) {
for(int j = 0; j < indentSize; j++) {
sb.append(" ");
}
}
return sb.toString();
}
/**
* @param level type: String, the level the logger will log to
* @return Consumer<String>
*/
private static Consumer<String> getLoggerFuncBasedOnLevel(String level) {<FILL_FUNCTION_BODY>}
}
|
switch(level.toUpperCase()) {
case "ERROR":
return logger::error;
case "INFO":
return logger::info;
case "DEBUG":
return logger::debug;
case "WARN":
return logger::warn;
default:
return logger::info;
}
| 873
| 82
| 955
|
<no_super_class>
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/DumperFactory.java
|
RequestDumperFactory
|
create
|
class RequestDumperFactory{
/**
* create IRequestDumpable dumper.
* @param dumperName dumper name, need it to identify which dumper will be created
* @param config type: DumpConfig, needed by dumper constructor
* @param exchange type: HttpServerExchange, needed by dumper constructor
* @return IRequestDumpable dumper
*/
IRequestDumpable create(String dumperName, DumpConfig config, HttpServerExchange exchange) {<FILL_FUNCTION_BODY>}
}
|
switch (dumperName) {
case DumpConstants.BODY:
return new BodyDumper(config, exchange);
case DumpConstants.COOKIES:
return new CookiesDumper(config, exchange);
case DumpConstants.HEADERS:
return new HeadersDumper(config, exchange);
case DumpConstants.QUERY_PARAMETERS:
return new QueryParametersDumper(config, exchange);
case DumpConstants.URL:
return new UrlDumper(config, exchange);
default:
logger.error("unsupported dump type: {}", dumperName);
return null;
}
| 135
| 161
| 296
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.