Skip to content

Commit

Permalink
fixes #2017 Update module config class to support the conversion of s…
Browse files Browse the repository at this point in the history
…tring to boolean and integer (#2018)
  • Loading branch information
stevehu authored Nov 25, 2023
1 parent 2e5cad4 commit b8f1158
Show file tree
Hide file tree
Showing 14 changed files with 298 additions and 107 deletions.
8 changes: 5 additions & 3 deletions audit/src/main/java/com/networknt/audit/AuditConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class AuditConfig {
private List<String> headerList;
private List<String> auditList;

private Config config;
private final Config config;
// A customized logger appender defined in default logback.xml
private Consumer<String> auditFunc;
private boolean statusCode;
Expand Down Expand Up @@ -151,8 +151,10 @@ Config getConfig() {

private void setLogLevel() {
Object object = getMappedConfig().get(LOG_LEVEL_IS_ERROR);
auditFunc = (object != null && (Boolean) object) ?
LoggerFactory.getLogger(Constants.AUDIT_LOGGER)::error : LoggerFactory.getLogger(Constants.AUDIT_LOGGER)::info;
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() {
Expand Down
2 changes: 1 addition & 1 deletion audit/src/main/resources/config/audit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ responseTime: ${audit.responseTime:true}
# log level is controlled by logLevel
auditOnError: ${audit.auditOnError:false}

# log level; by default it is set to info. If you want to change it to error, set to true.
# log level is error; by default the logging level is set to info. If you want to change it to error, set to true.
logLevelIsError: ${audit.logLevelIsError:false}

# the format for outputting the timestamp, if the format is not specified or invalid, will use a long value.
Expand Down
60 changes: 23 additions & 37 deletions client-config/src/main/java/com/networknt/client/ClientConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,42 +165,28 @@ private void setRequestConfig() {
return;
}
Map<String, Object> requestConfig = (Map<String, Object>) mappedConfig.get(REQUEST);

if (requestConfig.containsKey(ERROR_THRESHOLD)) {
errorThreshold = (int) requestConfig.get(ERROR_THRESHOLD);
}
if (requestConfig.containsKey(TIMEOUT)) {
timeout = (int) requestConfig.get(TIMEOUT);
}
if (requestConfig.containsKey(RESET_TIMEOUT)) {
resetTimeout = (int) requestConfig.get(RESET_TIMEOUT);
}
if(requestConfig.containsKey(INJECT_OPEN_TRACING)) {
injectOpenTracing = (Boolean) requestConfig.get(INJECT_OPEN_TRACING);
}
if(requestConfig.containsKey(INJECT_CALLER_ID)) {
injectCallerId = (Boolean) requestConfig.get(INJECT_CALLER_ID);
}
if (requestConfig.containsKey(ENABLE_HTTP2)) {
requestEnableHttp2 = Config.loadBooleanValue(ENABLE_HTTP2, requestConfig.get(ENABLE_HTTP2));;
} else {
requestEnableHttp2 = false;
}
if (requestConfig.containsKey(CONNECTION_POOL_SIZE)) {
connectionPoolSize = (int) requestConfig.get(CONNECTION_POOL_SIZE);
}
if (requestConfig.containsKey(CONNECTION_EXPIRE_TIME)) {
connectionExpireTime = Long.parseLong(requestConfig.get(CONNECTION_EXPIRE_TIME).toString());
}
if (requestConfig.containsKey(MAX_REQUEST_PER_CONNECTION)) {
maxReqPerConn = (int) requestConfig.get(MAX_REQUEST_PER_CONNECTION);
}
if (requestConfig.containsKey(MAX_CONNECTION_NUM_PER_HOST)) {
maxConnectionNumPerHost = (int) requestConfig.get(MAX_CONNECTION_NUM_PER_HOST);
}
if (requestConfig.containsKey(MIN_CONNECTION_NUM_PER_HOST)) {
minConnectionNumPerHost = (int) requestConfig.get(MIN_CONNECTION_NUM_PER_HOST);
}
Object object = requestConfig.get(ERROR_THRESHOLD);
if(object != null) errorThreshold = Config.loadIntegerValue(ERROR_THRESHOLD, object);
object = requestConfig.get(TIMEOUT);
if(object != null) timeout = Config.loadIntegerValue(TIMEOUT, object);
object = requestConfig.get(RESET_TIMEOUT);
if(object != null) resetTimeout = Config.loadIntegerValue(RESET_TIMEOUT, object);
object = requestConfig.get(INJECT_OPEN_TRACING);
if(object != null) injectOpenTracing = Config.loadBooleanValue(INJECT_OPEN_TRACING, object);
object = requestConfig.get(INJECT_CALLER_ID);
if(object != null) injectCallerId = Config.loadBooleanValue(INJECT_CALLER_ID, object);
object = requestConfig.get(ENABLE_HTTP2);
if(object != null) requestEnableHttp2 = Config.loadBooleanValue(ENABLE_HTTP2, object);
object = requestConfig.get(CONNECTION_POOL_SIZE);
if(object != null) connectionPoolSize = Config.loadIntegerValue(CONNECTION_POOL_SIZE, object);
object = requestConfig.get(CONNECTION_EXPIRE_TIME);
if(object != null) connectionExpireTime = Config.loadLongValue(CONNECTION_EXPIRE_TIME, object);
object = requestConfig.get(MAX_REQUEST_PER_CONNECTION);
if(object != null) maxReqPerConn = Config.loadIntegerValue(MAX_REQUEST_PER_CONNECTION, object);
object = requestConfig.get(MAX_CONNECTION_NUM_PER_HOST);
if(object != null) maxConnectionNumPerHost = Config.loadIntegerValue(MAX_CONNECTION_NUM_PER_HOST, object);
object = requestConfig.get(MIN_CONNECTION_NUM_PER_HOST);
if(object != null) minConnectionNumPerHost = Config.loadIntegerValue(MIN_CONNECTION_NUM_PER_HOST, object);
}

private void setPathPrefixServices() {
Expand All @@ -217,7 +203,7 @@ private void setOAuthConfig() {
derefConfig = (Map<String, Object>)oauthConfig.get(DEREF);
signConfig = (Map<String, Object>)oauthConfig.get(SIGN);
if(oauthConfig.get(MULTIPLE_AUTH_SERVERS) != null) {
multipleAuthServers = (Boolean)oauthConfig.get(MULTIPLE_AUTH_SERVERS);
multipleAuthServers = Config.loadBooleanValue(MULTIPLE_AUTH_SERVERS, oauthConfig.get(MULTIPLE_AUTH_SERVERS));
} else {
multipleAuthServers = false;
}
Expand Down
2 changes: 1 addition & 1 deletion client-config/src/main/resources/config/client.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ oauth:
multipleAuthServers: ${client.multipleAuthServers:false}
token:
cache:
#capacity of caching TOKENs
#capacity of caching tokens in the client for downstream API calls. The default value is 200.
capacity: ${client.tokenCacheCapacity:200}
# The scope token will be renewed automatically 1 minute before expiry
tokenRenewBeforeExpired: ${client.tokenRenewBeforeExpired:60000}
Expand Down
8 changes: 4 additions & 4 deletions client/src/main/java/com/networknt/client/Http2Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ protected Http2Client() {
private Http2Client(final ClassLoader classLoader) {
Map<String, Object> tlsMap = config.getTlsConfig();
// disable the hostname verification based on the config.
if(tlsMap != null && Boolean.FALSE.equals(tlsMap.get(TLSConfig.VERIFY_HOSTNAME))) {
if(tlsMap == null || tlsMap.get(TLSConfig.VERIFY_HOSTNAME) == null || Boolean.FALSE.equals(Config.loadBooleanValue(TLSConfig.VERIFY_HOSTNAME, tlsMap.get(TLSConfig.VERIFY_HOSTNAME)))) {
System.setProperty(DISABLE_HTTPS_ENDPOINT_IDENTIFICATION_PROPERTY, "true");
}
boolean injectCallerId = config.isInjectCallerId();
Expand Down Expand Up @@ -766,7 +766,7 @@ public static SSLContext createSSLContext() throws IOException {
if(tlsMap != null) {
try {
// load key store for client certificate if two way ssl is used.
Boolean loadKeyStore = (Boolean) tlsMap.get(LOAD_KEY_STORE);
Boolean loadKeyStore = tlsMap.get(LOAD_KEY_STORE) == null ? false : Config.loadBooleanValue(LOAD_KEY_STORE, tlsMap.get(LOAD_KEY_STORE));
if (loadKeyStore != null && loadKeyStore) {
String keyStoreName = System.getProperty(KEY_STORE_PROPERTY);
String keyStorePass = System.getProperty(KEY_STORE_PASSWORD_PROPERTY);
Expand Down Expand Up @@ -796,13 +796,13 @@ public static SSLContext createSSLContext() throws IOException {
}

TrustManager[] trustManagers = null;
Boolean loadDefaultTrust = (Boolean) tlsMap.get(LOAD_DEFAULT_TRUST);
Boolean loadDefaultTrust = tlsMap.get(LOAD_DEFAULT_TRUST) == null ? false : Config.loadBooleanValue(LOAD_DEFAULT_TRUST, tlsMap.get(LOAD_DEFAULT_TRUST));
List<TrustManager> trustManagerList = new ArrayList<>();
try {
// load trust store, this is the server public key certificate
// first check if javax.net.ssl.trustStore system properties is set. It is only necessary if the server
// certificate doesn't have the entire chain.
Boolean loadTrustStore = (Boolean) tlsMap.get(LOAD_TRUST_STORE);
Boolean loadTrustStore = tlsMap.get(LOAD_TRUST_STORE) == null ? false : Config.loadBooleanValue(LOAD_TRUST_STORE, tlsMap.get(LOAD_TRUST_STORE));
if (loadTrustStore != null && loadTrustStore) {

String trustStoreName = (String) tlsMap.get(TRUST_STORE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,11 @@ public Map<String, Object> getMappedConfig() {

private void setConfigData() {
Object object = mappedConfig.get(ENABLED);
if(object != null && (Boolean) object) {
enabled = true;
}
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(GET_METHOD_ENABLED);
if(object != null && (Boolean) object) {
getMethodEnabled = true;
}
if(object != null) getMethodEnabled = Config.loadBooleanValue(GET_METHOD_ENABLED, object);
object = mappedConfig.get(PASS_THROUGH);
if(object != null && (Boolean) object) {
passThrough = true;
}
if(object != null) passThrough = Config.loadBooleanValue(PASS_THROUGH, object);
tokenServiceId = (String)getMappedConfig().get(TOKEN_SERVICE_ID);
}

Expand Down
22 changes: 11 additions & 11 deletions handler/src/main/java/com/networknt/handler/BuffersUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ public class BuffersUtils {
private static final Logger LOG = LoggerFactory.getLogger(BuffersUtils.class);

/**
* @param srcs
* @return
* @throws IOException
* @param srcs PooledByteBuffer[]
* @return a ByteBuffer containing the content of the srcs
* @throws IOException If the content exceeds the MAX_CONTENT_SIZE
*/
public static ByteBuffer toByteBuffer(final PooledByteBuffer[] srcs) throws IOException {
if (srcs == null)
Expand Down Expand Up @@ -91,10 +91,10 @@ public static String toString(final byte[] src, Charset cs) throws IOException {
/**
* transfer the src data to the pooled buffers overwriting the exising data
*
* @param src
* @param dest
* @param exchange
* @return
* @param src ByteBuffer
* @param dest PooledByteBuffer[]
* @param exchange HttpServerExchange
* @return int
*/
public static int transfer(final ByteBuffer src, final PooledByteBuffer[] dest, HttpServerExchange exchange) {
int copied = 0;
Expand Down Expand Up @@ -158,10 +158,10 @@ public static void dump(String msg, PooledByteBuffer[] data) {
/**
* append the src data to the pooled buffers
*
* @param src
* @param dest
* @param exchange
* @return
* @param src ByteBuffer
* @param dest PooledByteBuffer[]
* @param exchange HttpServerExchange
* @return int
*/
public static int append(final ByteBuffer src, final PooledByteBuffer[] dest, HttpServerExchange exchange) {
int copied = 0;
Expand Down
30 changes: 10 additions & 20 deletions handler/src/main/java/com/networknt/handler/Handler.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,8 @@ public class Handler {
private static final AttachmentKey<Integer> CHAIN_SEQ = AttachmentKey.create(Integer.class);
private static final AttachmentKey<String> CHAIN_ID = AttachmentKey.create(String.class);
private static final Logger LOG = LoggerFactory.getLogger(Handler.class);
private static final String CONFIG_NAME = "handler";
private static String configName = CONFIG_NAME;

// Accessed directly.
public static HandlerConfig config = (HandlerConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME,
HandlerConfig.class);
public static HandlerConfig config = HandlerConfig.load();

// each handler keyed by a name.
static final Map<String, HttpHandler> handlers = new HashMap<>();
Expand All @@ -75,7 +71,7 @@ public static void init() {
initChains();
initPaths();
initDefaultHandlers();
ModuleRegistry.registerModule(HandlerConfig.CONFIG_NAME, Handler.class.getName(), Config.getInstance().getJsonMapConfigNoCache(CONFIG_NAME), null);
ModuleRegistry.registerModule(HandlerConfig.CONFIG_NAME, Handler.class.getName(), config.getMappedConfig(), null);
}

/**
Expand All @@ -88,14 +84,8 @@ static void initHandlers() {

// initialize handlers
for (var handler : config.getHandlers()) {

// If the handler is configured as just a string, it's a fully qualified class
// name with a default constructor.
if (handler instanceof String)
initStringDefinedHandler((String) handler);

else if (handler instanceof Map)
initMapDefinedHandler((Map<String, Object>) handler);
// handler is a fully qualified class name with a default constructor.
initStringDefinedHandler((String) handler);
}
}
}
Expand Down Expand Up @@ -134,7 +124,7 @@ static void initPaths() {
if (config != null && config.getPaths() != null) {

for (var pathChain : config.getPaths()) {
pathChain.validate(configName + " config"); // raises exception on misconfiguration
pathChain.validate(HandlerConfig.CONFIG_NAME + " config"); // raises exception on misconfiguration

if (pathChain.getPath() == null)
addSourceChain(pathChain);
Expand Down Expand Up @@ -461,13 +451,13 @@ else if (handlerOrProviderObject instanceof WebSocketConnectionCallback)
handlerListById.put(namedClass.first, Collections.singletonList(resolvedHandler));
}

/**
/*
* Helper method for generating the instance of a handler from its map
* definition in config. Ie. No mapped values for setters, or list of
* constructor fields.
*
* @param handler
*/
* @param handler handler map
* As all handlers have a default constructor with a configuration file, there is no need to pass any parameters.
private static void initMapDefinedHandler(Map<String, Object> handler) {
// If the handler is a map, the keys are the class name, values are the
// parameters.
Expand Down Expand Up @@ -506,6 +496,7 @@ private static void initMapDefinedHandler(Map<String, Object> handler) {
}
}
}
*/

/**
* To support multiple instances of the same class, support a naming
Expand Down Expand Up @@ -537,8 +528,7 @@ static Tuple<String, Class> splitClassAndName(String classLabel) {

// Exposed for testing only.
static void setConfig(String configName) throws Exception {
Handler.configName = configName;
config = (HandlerConfig) Config.getInstance().getJsonObjectConfig(configName, HandlerConfig.class);
config = HandlerConfig.load(configName);
initHandlers();
initChains();
initPaths();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ public interface LightHttpHandler extends HttpHandler {
String AUDIT_ON_ERROR = "auditOnError";
String AUDIT_STACK_TRACE = "auditStackTrace";

HandlerConfig config = (HandlerConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, HandlerConfig.class);
HandlerConfig config = HandlerConfig.load();
// the reason we are not using the AuditConfig is to avoid the dependency on audit module.
Map<String, Object> auditConfig = Config.getInstance().getDefaultJsonMapConfigNoCache(AUDIT_CONFIG_NAME);

boolean auditOnError = auditConfig == null ? false : auditConfig.get(AUDIT_ON_ERROR) != null ? (boolean)auditConfig.get(AUDIT_ON_ERROR) : false;
boolean auditStackTrace = auditConfig == null ? false : auditConfig.get(AUDIT_STACK_TRACE) != null ? (boolean)auditConfig.get(AUDIT_ON_ERROR) : false;
boolean auditOnError = auditConfig != null && auditConfig.get(AUDIT_ON_ERROR) != null ? Config.loadBooleanValue(AUDIT_ON_ERROR, auditConfig.get(AUDIT_ON_ERROR)) : false;
boolean auditStackTrace = auditConfig != null && auditConfig.get(AUDIT_STACK_TRACE) != null ? Config.loadBooleanValue(AUDIT_STACK_TRACE, auditConfig.get(AUDIT_STACK_TRACE)) : false;

/**
* This method is used to construct a standard error status in JSON format from an error code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,8 @@ private void forceIdentityEncodingForInterceptors(HttpServerExchange exchange) {
}

/**
* @param exchange
* @throws Exception
* @param exchange HttpServerExchange
* @throws Exception if any exception happens
*/
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public class ContentStreamSinkConduit extends AbstractStreamSinkConduit<StreamSi
/**
* Construct a new instance.
*
* @param next
* @param exchange
* @param next the delegate conduit to set
* @param exchange HttpServerExchange
*/
public ContentStreamSinkConduit(StreamSinkConduit next, HttpServerExchange exchange) {
super(next);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public class ModifiableContentSinkConduit extends AbstractStreamSinkConduit<Stre
* Construct a new instance.
*
* @param next the delegate conduit to set
* @param exchange
* @param exchange HttpServerExchange
*/
public ModifiableContentSinkConduit(StreamSinkConduit next, HttpServerExchange exchange) {
super(next);
Expand Down
Loading

0 comments on commit b8f1158

Please sign in to comment.