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
|
|---|---|---|---|---|---|---|---|---|---|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/HeadersDumper.java
|
HeadersDumper
|
dumpRequest
|
class HeadersDumper extends AbstractDumper implements IRequestDumpable, IResponseDumpable {
private Map<String, Object> headerMap = new LinkedHashMap<>();
public HeadersDumper(DumpConfig config, HttpServerExchange exchange) {
super(config, exchange);
}
/**
* put headerMap to result.
* @param result a Map you want to put dumping info to.
*/
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(this.headerMap.size() > 0) {
result.put(DumpConstants.HEADERS, this.headerMap);
}
}
/**
* impl of dumping request headers to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpRequest(Map<String, Object> result) {<FILL_FUNCTION_BODY>}
/**
* impl of dumping response headers to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpResponse(Map<String, Object> result) {
HeaderMap headers = exchange.getResponseHeaders();
dumpHeaders(headers);
if(config.isMaskEnabled()) {
this.headerMap.forEach((s, o) -> headerMap.put(s, Mask.maskRegex((String) o, "responseHeader", s)));
}
this.putDumpInfoTo(result);
}
/**
* put headers info to headerMap
* @param headers types: HeaderMap, get from response or request
*/
private void dumpHeaders(HeaderMap headers) {
headers.forEach((headerValues) -> headerValues.forEach((headerValue) -> {
String headerName = headerValues.getHeaderName().toString();
if(!config.getRequestFilteredHeaders().contains(headerName)) {
headerMap.put(headerName, headerValue);
}
}));
}
@Override
public boolean isApplicableForRequest() {
return config.isRequestHeaderEnabled();
}
@Override
public boolean isApplicableForResponse() {
return config.isResponseHeaderEnabled();
}
}
|
HeaderMap headers = exchange.getRequestHeaders();
dumpHeaders(headers);
if(config.isMaskEnabled()) {
this.headerMap.forEach((s, o) -> headerMap.put(s, Mask.maskRegex((String) o, "requestHeader", s)));
}
this.putDumpInfoTo(result);
| 558
| 88
| 646
|
<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/QueryParametersDumper.java
|
QueryParametersDumper
|
dumpRequest
|
class QueryParametersDumper extends AbstractDumper implements IRequestDumpable {
private Map<String, Object> queryParametersMap = new LinkedHashMap<>();
public QueryParametersDumper(DumpConfig config, HttpServerExchange exchange) {
super(config, exchange);
}
/**
* impl of dumping request query parameter to result
* @param result A map you want to put dump information to
*/
@Override
public void dumpRequest(Map<String, Object> result) {<FILL_FUNCTION_BODY>}
/**
* put queryParametersMap to result.
* @param result a Map you want to put dumping info to.
*/
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(this.queryParametersMap.size() > 0) {
result.put(DumpConstants.QUERY_PARAMETERS, queryParametersMap);
}
}
@Override
public boolean isApplicableForRequest() {
return config.isRequestQueryParametersEnabled();
}
}
|
exchange.getQueryParameters().forEach((k, v) -> {
if (config.getRequestFilteredQueryParameters().contains(k)) {
//mask query parameter value
String queryParameterValue = config.isMaskEnabled() ? Mask.maskRegex( v.getFirst(), "queryParameter", k) : v.getFirst();
queryParametersMap.put(k, queryParameterValue);
}
});
this.putDumpInfoTo(result);
| 267
| 115
| 382
|
<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/RootDumper.java
|
RootDumper
|
dumpResponse
|
class RootDumper {
private DumperFactory dumperFactory;
private DumpConfig dumpConfig;
private HttpServerExchange exchange;
public RootDumper(DumpConfig dumpConfig, HttpServerExchange exchange) {
this.dumpConfig = dumpConfig;
this.exchange = exchange;
dumperFactory = new DumperFactory();
}
/**
* create dumpers that can dump http request info, and put http request info into Map<String, Object> result
* @param result a Map<String, Object> to put http request info to
*/
public void dumpRequest(Map<String, Object> result) {
if(!dumpConfig.isRequestEnabled()) { return; }
Map<String, Object> requestResult = new LinkedHashMap<>();
for(IRequestDumpable dumper: dumperFactory.createRequestDumpers(dumpConfig, exchange)) {
if(dumper.isApplicableForRequest()){
dumper.dumpRequest(requestResult);
}
}
result.put(DumpConstants.REQUEST, requestResult);
}
/**
* create dumpers that can dump http response info, and put http response info into Map<String, Object> result
* @param result a Map<String, Object> to put http response info to
*/
public void dumpResponse(Map<String, Object> result) {<FILL_FUNCTION_BODY>}
}
|
if(!dumpConfig.isResponseEnabled()) { return; }
Map<String, Object> responseResult = new LinkedHashMap<>();
for(IResponseDumpable dumper: dumperFactory.createResponseDumpers(dumpConfig, exchange)) {
if (dumper.isApplicableForResponse()) {
dumper.dumpResponse(responseResult);
}
}
result.put(DumpConstants.RESPONSE, responseResult);
| 349
| 114
| 463
|
<no_super_class>
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/StoreResponseStreamSinkConduit.java
|
StoreResponseStreamSinkConduit
|
write
|
class StoreResponseStreamSinkConduit extends AbstractStreamSinkConduit<StreamSinkConduit> {
public static final AttachmentKey<byte[]> RESPONSE = AttachmentKey.create(byte[].class);
private ByteArrayOutputStream outputStream;
private final HttpServerExchange exchange;
public StoreResponseStreamSinkConduit(StreamSinkConduit next, HttpServerExchange exchange) {
super(next);
this.exchange = exchange;
long length = exchange.getResponseContentLength();
if (length <= 0L) {
outputStream = new ByteArrayOutputStream();
} else {
if (length > Integer.MAX_VALUE) {
throw UndertowMessages.MESSAGES.responseTooLargeToBuffer(length);
}
outputStream = new ByteArrayOutputStream((int) length);
}
}
@Override
public int write(ByteBuffer src) throws IOException {
int start = src.position();
int ret = super.write(src);
for (int i = start; i < start + ret; ++i) {
outputStream.write(src.get(i));
}
return ret;
}
@Override
public long write(ByteBuffer[] srcs, int offs, int len) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public int writeFinal(ByteBuffer src) throws IOException {
int start = src.position();
int ret = super.writeFinal(src);
//without changing ByteBuffer remaining, copy to outputStream
for (int i = start; i < start + ret; ++i) {
outputStream.write(src.get(i));
}
return ret;
}
@Override
public long writeFinal(ByteBuffer[] srcs, int offs, int len) throws IOException {
int[] starts = new int[len];
long toWrite = 0;
for (int i = 0; i < len; ++i) {
starts[i] = srcs[i + offs].position();
toWrite += srcs[i + offs].remaining();
}
long ret = super.write(srcs, offs, len);
long rem = ret;
for (int i = 0; i < len; ++i) {
ByteBuffer buf = srcs[i + offs];
int pos = starts[i];
int limit = buf.limit();
//buf.position() could be later than buf.limit() due to after read the last byte, position will still move to next, but it's now larger than limit.
while (rem > 0 && pos <= buf.position() && pos < limit) {
outputStream.write(buf.get(pos));
pos++;
rem--;
}
}
return ret;
}
@Override
public void terminateWrites() throws IOException {
//after finish writes all through conduit, it will reach here, at this time, we put response info
exchange.putAttachment(RESPONSE, outputStream.toByteArray());
outputStream = null;
super.terminateWrites();
}
}
|
int[] starts = new int[len];
for (int i = 0; i < len; ++i) {
starts[i] = srcs[i + offs].position();
}
long ret = super.write(srcs, offs, len);
long rem = ret;
for (int i = 0; i < len; ++i) {
ByteBuffer buf = srcs[i + offs];
int pos = starts[i];
int limit = buf.limit();
//buf.position() could be later than buf.limit() due to after read the last byte, position will still move to next, but it's now larger than limit.
while (rem > 0 && pos <= buf.position() && pos < limit) {
outputStream.write(buf.get(pos));
pos++;
rem--;
}
}
return ret;
| 781
| 218
| 999
|
<no_super_class>
|
networknt_light-4j
|
light-4j/dump/src/main/java/com/networknt/dump/UrlDumper.java
|
UrlDumper
|
dumpRequest
|
class UrlDumper extends AbstractDumper implements IRequestDumpable{
private String url = "";
public UrlDumper(DumpConfig config, HttpServerExchange exchange) {
super(config, exchange);
}
@Override
public void dumpRequest(Map<String, Object> result) {<FILL_FUNCTION_BODY>}
/**
* put this.url to result
* @param result a Map you want to put dumping info to.
*/
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
if(StringUtils.isNotBlank(this.url)) {
result.put(DumpConstants.URL, this.url);
}
}
@Override
public boolean isApplicableForRequest() {
return config.isRequestUrlEnabled();
}
}
|
this.url = exchange.getRequestURL();
if(config.isMaskEnabled()) {
Mask.maskString(url, "uri");
}
this.putDumpInfoTo(result);
| 216
| 54
| 270
|
<methods><variables>protected final non-sealed com.networknt.dump.DumpConfig config,protected final non-sealed HttpServerExchange exchange
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/HostWhitelist.java
|
HostWhitelist
|
isHostAllowed
|
class HostWhitelist {
private RouterConfig config;
public HostWhitelist() {
config = RouterConfig.load();
}
public boolean isHostAllowed(URI serviceUri) {<FILL_FUNCTION_BODY>}
}
|
if (serviceUri != null) {
List<String> hostWhitelist = config.getHostWhitelist();
if (hostWhitelist == null || hostWhitelist.size() == 0) {
throw new ConfigException("No whitelist defined to allow the route to " + serviceUri);
}
String host = serviceUri.getHost();
return hostWhitelist.stream().anyMatch(
hostRegEx -> host != null && host.matches(hostRegEx));
} else {
return false;
}
| 72
| 143
| 215
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/OAuthServerConfig.java
|
OAuthServerConfig
|
setConfigList
|
class OAuthServerConfig {
private static final Logger logger = LoggerFactory.getLogger(OAuthServerConfig.class);
public static final String CONFIG_NAME = "oauthServer";
private static final String ENABLED = "enabled";
private static final String GET_METHOD_ENABLED = "getMethodEnabled";
private static final String CLIENT_CREDENTIALS = "client_credentials";
private static final String PASS_THROUGH = "passThrough";
private static final String TOKEN_SERVICE_ID = "tokenServiceId";
private Map<String, Object> mappedConfig;
private final Config config;
private boolean enabled;
private boolean getMethodEnabled;
private boolean passThrough;
private String tokenServiceId;
List<String> clientCredentials;
private OAuthServerConfig() {
this(CONFIG_NAME);
}
private OAuthServerConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
public static OAuthServerConfig load() {
return new OAuthServerConfig();
}
public static OAuthServerConfig load(String configName) {
return new OAuthServerConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
public boolean isEnabled() {
return enabled;
}
public boolean isGetMethodEnabled() {
return getMethodEnabled;
}
public List<String> getClientCredentials() {
return clientCredentials;
}
public boolean isPassThrough() {
return passThrough;
}
public void setPassThrough(boolean passThrough) {
this.passThrough = passThrough;
}
public String getTokenServiceId() {
return tokenServiceId;
}
public void setTokenServiceId(String tokenServiceId) {
this.tokenServiceId = tokenServiceId;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
private void setConfigData() {
Object object = mappedConfig.get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(GET_METHOD_ENABLED);
if(object != null) getMethodEnabled = Config.loadBooleanValue(GET_METHOD_ENABLED, object);
object = mappedConfig.get(PASS_THROUGH);
if(object != null) passThrough = Config.loadBooleanValue(PASS_THROUGH, object);
tokenServiceId = (String)getMappedConfig().get(TOKEN_SERVICE_ID);
}
private void setConfigList() {<FILL_FUNCTION_BODY>}
}
|
if (mappedConfig.get(CLIENT_CREDENTIALS) != null) {
Object object = mappedConfig.get(CLIENT_CREDENTIALS);
clientCredentials = 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 {
clientCredentials = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the clientCredentials json with a list of strings.");
}
} else {
// comma separated
clientCredentials = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (object instanceof List) {
List prefixes = (List)object;
prefixes.forEach(item -> {
clientCredentials.add((String)item);
});
} else {
throw new ConfigException("clientCredentials must be a string or a list of strings.");
}
}
| 736
| 302
| 1,038
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/OAuthServerGetHandler.java
|
OAuthServerGetHandler
|
handleRequest
|
class OAuthServerGetHandler implements LightHttpHandler {
static final Logger logger = LoggerFactory.getLogger(OAuthServerGetHandler.class);
private static final String METHOD_NOT_ALLOWED = "ERR10008";
private static final String UNSUPPORTED_GRANT_TYPE = "ERR12001";
private static final String INVALID_BASIC_CREDENTIALS = "ERR12004";
private static final String CONTENT_TYPE_MISSING = "ERR10076";
private static final String INVALID_CONTENT_TYPE = "ERR10077";
private static final String MISSING_AUTHORIZATION_HEADER = "ERR12002";
private static final String INVALID_AUTHORIZATION_HEADER = "ERR12003";
OAuthServerConfig config;
public OAuthServerGetHandler() {
config = OAuthServerConfig.load();
if(logger.isInfoEnabled()) logger.info("OAuthServerGetHandler is loaded and it is not secure!!!");
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// check the config to see if this handler is enabled.
if(!config.isGetMethodEnabled()) {
setExchangeStatus(exchange, METHOD_NOT_ALLOWED, exchange.getRequestMethod().toString(), exchange.getRequestURI());
return;
}
// response is always application/json.
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
// get the query parameters from the exchange.
Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();
String clientId = null;
String clientSecret = null;
String grantType = null;
if(queryParameters != null) {
clientId = queryParameters.get("client_id") != null?queryParameters.get("client_id").getFirst():null;
clientSecret = queryParameters.get("client_secret") != null?queryParameters.get("client_secret").getFirst():null;
grantType = queryParameters.get("grant_type") != null?queryParameters.get("grant_type").getFirst():null;
}
if("client_credentials".equals(grantType)) {
// check if client credentials in the list.
String credentials = null;
if(clientId != null && clientSecret != null) {
credentials = clientId + ":" + clientSecret;
} else {
// clientId and clientSecret are not in the body but in the authorization header.
String auth = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
if(auth != null) {
if("BASIC".equalsIgnoreCase(auth.substring(0, 5))) {
credentials = auth.substring(6);
int pos = credentials.indexOf(':');
if (pos == -1) {
credentials = new String(org.apache.commons.codec.binary.Base64.decodeBase64(credentials), UTF_8);
}
} else {
logger.error("Invalid authorization header " + auth.substring(0, 10));
setExchangeStatus(exchange, INVALID_AUTHORIZATION_HEADER, auth.substring(0, 10));
return;
}
} else {
// missing credentials.
logger.error("Missing authorization header.");
setExchangeStatus(exchange, MISSING_AUTHORIZATION_HEADER);
return;
}
}
if(config.getClientCredentials() != null && config.getClientCredentials().stream().anyMatch(credentials::equals)) {
Map<String, Object> resMap = new HashMap<>();
if(config.isPassThrough()) {
// get a jwt token from the real OAuth 2.0 provider.
Result<Jwt> result = TokenHandler.getJwtToken(config.getTokenServiceId());
if(result.isFailure()) {
logger.error("Cannot populate or renew jwt for client credential grant type: " + result.getError().toString());
setExchangeStatus(exchange, result.getError());
return;
} else {
Jwt jwt = result.getResult();
resMap.put("access_token", jwt.getJwt());
resMap.put("token_type", "bearer");
resMap.put("expires_in", (jwt.getExpire() - System.currentTimeMillis()) / 1000); // milliseconds to seconds.
}
} else {
// generate a dummy token just to complete the consumer workflow without code change.
resMap.put("access_token", HashUtil.generateUUID());
resMap.put("token_type", "bearer");
resMap.put("expires_in", 600);
}
if(logger.isTraceEnabled()) logger.trace("matched credential, sending response.");
exchange.getResponseSender().send(JsonMapper.toJson(resMap));
} else {
logger.error("invalid credentials");
setExchangeStatus(exchange, INVALID_BASIC_CREDENTIALS, credentials);
}
} else {
logger.error("not supported grant type " + grantType);
setExchangeStatus(exchange, UNSUPPORTED_GRANT_TYPE, grantType);
}
| 302
| 1,068
| 1,370
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/OAuthServerHandler.java
|
OAuthServerHandler
|
handleRequest
|
class OAuthServerHandler implements LightHttpHandler {
static final Logger logger = LoggerFactory.getLogger(OAuthServerHandler.class);
private static final String UNSUPPORTED_GRANT_TYPE = "ERR12001";
private static final String INVALID_BASIC_CREDENTIALS = "ERR12004";
private static final String CONTENT_TYPE_MISSING = "ERR10076";
private static final String INVALID_CONTENT_TYPE = "ERR10077";
private static final String MISSING_AUTHORIZATION_HEADER = "ERR12002";
private static final String INVALID_AUTHORIZATION_HEADER = "ERR12003";
OAuthServerConfig config;
public OAuthServerHandler() {
config = OAuthServerConfig.load();
if(logger.isInfoEnabled()) logger.info("OAuthServerHandler is constructed.");
ModuleRegistry.registerModule(OAuthServerConfig.CONFIG_NAME, OAuthServerHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(OAuthServerConfig.CONFIG_NAME),null);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// response is always application/json.
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
// application/json and x-www-form-urlencoded and form-data are supported.
String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if(contentType != null) {
// only the following three content types are supported.
if (contentType.startsWith("application/json") || contentType.startsWith("multipart/form-data") || contentType.startsWith("application/x-www-form-urlencoded")) {
Map<String, Object> formMap = (Map<String, Object>)exchange.getAttachment(REQUEST_BODY);
String clientId = (String)formMap.get("client_id");
String clientSecret = (String)formMap.get("client_secret");
String grantType = (String)formMap.get("grant_type");
if("client_credentials".equals(grantType)) {
// check if client credentials in the list.
String credentials = null;
if(clientId != null && clientSecret != null) {
credentials = clientId + ":" + clientSecret;
} else {
// clientId and clientSecret are not in the body but in the authorization header.
String auth = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
if(auth != null) {
if("BASIC".equalsIgnoreCase(auth.substring(0, 5))) {
credentials = auth.substring(6);
int pos = credentials.indexOf(':');
if (pos == -1) {
credentials = new String(org.apache.commons.codec.binary.Base64.decodeBase64(credentials), UTF_8);
}
} else {
logger.error("Invalid authorization header " + auth.substring(0, 10));
setExchangeStatus(exchange, INVALID_AUTHORIZATION_HEADER, auth.substring(0, 10));
return;
}
} else {
// missing credentials.
logger.error("Missing authorization header.");
setExchangeStatus(exchange, MISSING_AUTHORIZATION_HEADER);
return;
}
}
if(config.getClientCredentials() != null && config.getClientCredentials().stream().anyMatch(credentials::equals)) {
Map<String, Object> resMap = new HashMap<>();
if(config.isPassThrough()) {
// get a jwt token from the real OAuth 2.0 provider.
Result<Jwt> result = TokenHandler.getJwtToken(config.getTokenServiceId());
if(result.isFailure()) {
logger.error("Cannot populate or renew jwt for client credential grant type: " + result.getError().toString());
setExchangeStatus(exchange, result.getError());
return;
} else {
Jwt jwt = result.getResult();
resMap.put("access_token", jwt.getJwt());
resMap.put("token_type", "bearer");
resMap.put("expires_in", (jwt.getExpire() - System.currentTimeMillis()) / 1000); // milliseconds to seconds.
}
} else {
// generate a dummy token just to complete the consumer workflow without code change.
resMap.put("access_token", HashUtil.generateUUID());
resMap.put("token_type", "bearer");
resMap.put("expires_in", 600);
}
if(logger.isTraceEnabled()) logger.trace("matched credential, sending response.");
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(JsonMapper.toJson(resMap));
} else {
logger.error("invalid credentials");
setExchangeStatus(exchange, INVALID_BASIC_CREDENTIALS, credentials);
}
} else {
logger.error("not supported grant type " + grantType);
setExchangeStatus(exchange, UNSUPPORTED_GRANT_TYPE, grantType);
}
} else {
logger.error("invalid content type " + contentType);
setExchangeStatus(exchange, INVALID_CONTENT_TYPE, contentType);
}
} else {
logger.error("content type is missing and it is required.");
setExchangeStatus(exchange, CONTENT_TYPE_MISSING);
}
| 322
| 1,147
| 1,469
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/RouterHandler.java
|
RouterHandler
|
reload
|
class RouterHandler implements HttpHandler {
private static final Logger logger = LoggerFactory.getLogger(RouterHandler.class);
private static RouterConfig config;
protected static ProxyHandler proxyHandler;
protected static AbstractMetricsHandler metricsHandler;
public RouterHandler() {
config = RouterConfig.load();
ModuleRegistry.registerModule(RouterConfig.CONFIG_NAME, RouterHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(RouterConfig.CONFIG_NAME), null);
ClientConfig clientConfig = ClientConfig.get();
Map<String, Object> tlsMap = clientConfig.getTlsConfig();
// disable the hostname verification based on the config. We need to do it here as the LoadBalancingRouterProxyClient uses the Undertow HttpClient.
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");
}
// As we are building a client side router for the light platform, the assumption is the server will
// be on HTTP 2.0 TSL always. No need to handle HTTP 1.1 case here.
LoadBalancingRouterProxyClient client = new LoadBalancingRouterProxyClient();
if(config.httpsEnabled) client.setSsl(Http2Client.getInstance().getDefaultXnioSsl());
if(config.http2Enabled) {
client.setOptionMap(OptionMap.create(UndertowOptions.ENABLE_HTTP2, true));
} else {
client.setOptionMap(OptionMap.EMPTY);
}
proxyHandler = ProxyHandler.builder()
.setProxyClient(client)
.setMaxConnectionRetries(config.maxConnectionRetries)
.setMaxQueueSize(config.maxQueueSize)
.setMaxRequestTime(config.maxRequestTime)
.setPathPrefixMaxRequestTime(config.pathPrefixMaxRequestTime)
.setReuseXForwarded(config.reuseXForwarded)
.setRewriteHostHeader(config.rewriteHostHeader)
.setUrlRewriteRules(config.urlRewriteRules)
.setMethodRewriteRules(config.methodRewriteRules)
.setQueryParamRewriteRules(config.queryParamRewriteRules)
.setHeaderRewriteRules(config.headerRewriteRules)
.setNext(ResponseCodeHandler.HANDLE_404)
.build();
if(config.isMetricsInjection()) {
// get the metrics handler from the handler chain for metrics registration. If we cannot get the
// metrics handler, then an error message will be logged.
Map<String, HttpHandler> handlers = Handler.getHandlers();
metricsHandler = (AbstractMetricsHandler) handlers.get(MetricsConfig.CONFIG_NAME);
if(metricsHandler == null) {
logger.error("An instance of MetricsHandler is not configured in the handler.yml.");
}
}
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("RouterHandler.handleRequest starts.");
if(metricsHandler != null) {
exchange.putAttachment(AttachmentConstants.METRICS_HANDLER, metricsHandler);
exchange.putAttachment(AttachmentConstants.DOWNSTREAM_METRICS_NAME, config.getMetricsName());
exchange.putAttachment(AttachmentConstants.DOWNSTREAM_METRICS_START, System.nanoTime());
}
proxyHandler.handleRequest(exchange);
if(logger.isDebugEnabled()) logger.debug("RouterHandler.handleRequest ends.");
}
public void reload() {<FILL_FUNCTION_BODY>}
}
|
config.reload();
ModuleRegistry.registerModule(RouterConfig.CONFIG_NAME, RouterHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(RouterConfig.CONFIG_NAME), null);
LoadBalancingRouterProxyClient client = new LoadBalancingRouterProxyClient();
if(config.httpsEnabled) client.setSsl(Http2Client.getInstance().getDefaultXnioSsl());
if(config.http2Enabled) {
client.setOptionMap(OptionMap.create(UndertowOptions.ENABLE_HTTP2, true));
} else {
client.setOptionMap(OptionMap.EMPTY);
}
proxyHandler = ProxyHandler.builder()
.setProxyClient(client)
.setMaxConnectionRetries(config.maxConnectionRetries)
.setMaxQueueSize(config.maxQueueSize)
.setMaxRequestTime(config.maxRequestTime)
.setPathPrefixMaxRequestTime(config.pathPrefixMaxRequestTime)
.setReuseXForwarded(config.reuseXForwarded)
.setRewriteHostHeader(config.rewriteHostHeader)
.setUrlRewriteRules(config.urlRewriteRules)
.setMethodRewriteRules(config.methodRewriteRules)
.setQueryParamRewriteRules(config.queryParamRewriteRules)
.setHeaderRewriteRules(config.headerRewriteRules)
.setNext(ResponseCodeHandler.HANDLE_404)
.build();
if(config.isMetricsInjection()) {
// get the metrics handler from the handler chain for metrics registration. If we cannot get the
// metrics handler, then an error message will be logged.
Map<String, HttpHandler> handlers = Handler.getHandlers();
metricsHandler = (AbstractMetricsHandler) handlers.get(MetricsConfig.CONFIG_NAME);
if(metricsHandler == null) {
logger.error("An instance of MetricsHandler is not configured in the handler.yml.");
}
}
if(logger.isInfoEnabled()) logger.info("RouterHandler is reloaded.");
| 1,018
| 539
| 1,557
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/PathPrefixServiceConfig.java
|
PathPrefixServiceConfig
|
setMap
|
class PathPrefixServiceConfig {
private static final Logger logger = LoggerFactory.getLogger(PathPrefixServiceConfig.class);
public static final String CONFIG_NAME = "pathPrefixService";
// keys in the config file
private static final String ENABLED = "enabled";
private static final String MAPPING = "mapping";
// variables
private Map<String, Object> mappedConfig;
private Map<String, String> mapping;
private boolean enabled;
// the config object
private Config config;
private PathPrefixServiceConfig() {
this(CONFIG_NAME);
}
private PathPrefixServiceConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setMap();
setConfigData();
}
public static PathPrefixServiceConfig load() {
return new PathPrefixServiceConfig();
}
public static PathPrefixServiceConfig load(String configName) {
return new PathPrefixServiceConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setMap();
setConfigData();
}
public Map<String, String> getMapping() {
return mapping;
}
public boolean isEnabled() {
return enabled;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setMap() {<FILL_FUNCTION_BODY>}
private void setConfigData() {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
}
}
|
if(mappedConfig.get(MAPPING) != null) {
if(mappedConfig.get(MAPPING) instanceof String) {
String s = (String)mappedConfig.get(MAPPING);
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
// check if the mapping is in JSON format.
if(s.startsWith("{")) {
// json map
try {
mapping = Config.getInstance().getMapper().readValue(s, Map.class);
} catch (IOException e) {
logger.error("IOException:", e);
}
} else {
// key/value pair separated by &.
Map<String, String> map = new LinkedHashMap<>();
for (String keyValue : s.split(" *& *")) {
String[] pairs = keyValue.split(" *= *", 2);
map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}
mapping = map;
}
} else if (mappedConfig.get(MAPPING) instanceof Map) {
mapping = (Map<String, String>) mappedConfig.get(MAPPING);
} else {
logger.error("Mapping is the wrong type. Only JSON string and YAML map are supported.");
}
}
| 452
| 340
| 792
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/PathPrefixServiceHandler.java
|
PathPrefixServiceHandler
|
pathPrefixService
|
class PathPrefixServiceHandler implements MiddlewareHandler {
static Logger logger = LoggerFactory.getLogger(PathPrefixServiceHandler.class);
protected volatile HttpHandler next;
protected static PathPrefixServiceConfig config;
public PathPrefixServiceHandler() {
logger.info("PathServiceHandler is constructed");
config = PathPrefixServiceConfig.load();
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
logger.debug("PathPrefixServiceHandler.handleRequest starts.");
pathPrefixService(exchange);
logger.debug("PathPrefixServiceHandler.handleRequest ends.");
Handler.next(exchange, next);
}
protected void pathPrefixService(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(PathPrefixServiceConfig.CONFIG_NAME, PathPrefixServiceHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(PathPrefixServiceConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(PathPrefixServiceConfig.CONFIG_NAME, PathPrefixServiceHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(PathPrefixServiceConfig.CONFIG_NAME), null);
if (logger.isInfoEnabled()) logger.info("PathPrefixServiceHandler is reloaded.");
}
}
|
String requestPath = exchange.getRequestURI();
String[] serviceEntry = HandlerUtils.findServiceEntry(HandlerUtils.normalisePath(requestPath), config.getMapping());
// if service URL is in the header, we don't need to do the service discovery with serviceId.
HeaderValues serviceIdHeader = exchange.getRequestHeaders().get(HttpStringConstants.SERVICE_ID);
String serviceId = serviceIdHeader != null ? serviceIdHeader.peekFirst() : null;
if (serviceId == null && serviceEntry != null) {
if (logger.isTraceEnabled())
logger.trace("serviceEntry found and header is set for service_id = '{}'", serviceEntry[1]);
exchange.getRequestHeaders().put(HttpStringConstants.SERVICE_ID, serviceEntry[1]);
}
if (serviceEntry != null) {
if (logger.isTraceEnabled())
logger.trace("serviceEntry found and endpoint is set to = '{}@{}'", serviceEntry[0], exchange.getRequestMethod().toString().toLowerCase());
HandlerUtils.populateAuditAttachmentField(exchange, Constants.ENDPOINT_STRING, serviceEntry[0] + "@" + exchange.getRequestMethod().toString().toLowerCase());
} else {
if (logger.isTraceEnabled())
logger.trace("serviceEntry is null and endpoint is set to = '{}@{}'", Constants.UNKOWN_STRING, exchange.getRequestMethod().toString().toLowerCase());
// at this moment, we don't have a way to reliably determine the endpoint.
HandlerUtils.populateAuditAttachmentField(exchange, Constants.ENDPOINT_STRING, Constants.UNKOWN_STRING + "@" + exchange.getRequestMethod().toString().toLowerCase());
}
| 450
| 447
| 897
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/PathServiceConfig.java
|
PathServiceConfig
|
setMap
|
class PathServiceConfig {
private static final Logger logger = LoggerFactory.getLogger(PathServiceConfig.class);
public static final String CONFIG_NAME = "pathService";
// keys in the config file
private static final String ENABLED = "enabled";
private static final String MAPPING = "mapping";
// variables
private Map<String, Object> mappedConfig;
private Map<String, String> mapping;
private boolean enabled;
// the config object
private Config config;
private PathServiceConfig() {
this(CONFIG_NAME);
}
private PathServiceConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setMap();
setConfigData();
}
public static PathServiceConfig load() {
return new PathServiceConfig();
}
public static PathServiceConfig load(String configName) {
return new PathServiceConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setMap();
setConfigData();
}
public Map<String, String> getMapping() {
return mapping;
}
public boolean isEnabled() {
return enabled;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setMap() {<FILL_FUNCTION_BODY>}
private void setConfigData() {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
}
}
|
if(mappedConfig.get(MAPPING) != null) {
if(mappedConfig.get(MAPPING) instanceof String) {
String s = (String)mappedConfig.get(MAPPING);
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
if(s.startsWith("{")) {
// json map
try {
mapping = Config.getInstance().getMapper().readValue(s, Map.class);
} catch (IOException e) {
logger.error("IOException:", e);
}
} else {
Map<String, String> map = new LinkedHashMap<>();
for(String keyValue : s.split(" *& *")) {
String[] pairs = keyValue.split(" *= *", 2);
map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}
mapping = map;
}
} else if (mappedConfig.get(MAPPING) instanceof Map) {
mapping = (Map<String, String>) mappedConfig.get(MAPPING);
} else {
logger.error("mapping is the wrong type. Only JSON string and YAML map are supported.");
}
}
| 442
| 317
| 759
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/PathServiceHandler.java
|
PathServiceHandler
|
handleRequest
|
class PathServiceHandler implements MiddlewareHandler {
static Logger logger = LoggerFactory.getLogger(PathServiceHandler.class);
private volatile HttpHandler next;
private static PathServiceConfig config;
public PathServiceHandler() {
logger.info("PathServiceHandler is constructed");
config = PathServiceConfig.load();
}
@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(PathServiceConfig.CONFIG_NAME, PathServiceHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(PathServiceConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(PathServiceConfig.CONFIG_NAME, PathServiceHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(PathServiceConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("PathServiceHandler is reloaded.");
}
}
|
if(logger.isDebugEnabled()) logger.debug("PathServiceConfig.handleRequest starts.");
// if service URL is in the header, we don't need to do the service discovery with serviceId.
HeaderValues serviceIdHeader = exchange.getRequestHeaders().get(HttpStringConstants.SERVICE_ID);
String serviceId = serviceIdHeader != null ? serviceIdHeader.peekFirst() : null;
if(serviceId == null) {
Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
if (auditInfo != null) {
String endpoint = (String) auditInfo.get(Constants.ENDPOINT_STRING);
if (logger.isDebugEnabled()) logger.debug("endpoint = " + endpoint);
// now find the mapped serviceId from the mapping.
if (endpoint != null) {
serviceId = config.getMapping() == null ? null : config.getMapping().get(endpoint);
if(serviceId != null) {
if(logger.isTraceEnabled()) logger.trace("Put into the service_id header for serviceId = " + serviceId);
exchange.getRequestHeaders().put(HttpStringConstants.SERVICE_ID, serviceId);
} else {
if(logger.isDebugEnabled()) logger.debug("The endpoint is not in the mapping config");
}
} else {
logger.error("could not get endpoint from the auditInfo.");
}
} else {
// couldn't find auditInfo object in exchange attachment.
logger.error("could not find auditInfo object in exchange attachment.");
}
}
if(logger.isDebugEnabled()) logger.debug("PathServiceConfig.handleRequest ends.");
Handler.next(exchange, next);
| 365
| 432
| 797
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/SAMLTokenHandler.java
|
SAMLTokenHandler
|
handleRequest
|
class SAMLTokenHandler implements MiddlewareHandler {
public static final String CLIENT_CONFIG_NAME = "client";
public static final String CONFIG_SECURITY = "security";
static final TokenConfig config = TokenConfig.load();
static Logger logger = LoggerFactory.getLogger(SAMLTokenHandler.class);
protected volatile HttpHandler next;
static final String OAUTH = "oauth";
static final String TOKEN = "token";
static final String OAUTH_HTTP2_SUPPORT = "oauthHttp2Support";
static final String SAMLAssertionHeader = "assertion";
static final String JWTAssertionHeader = "client_assertion";
static Map<String, Object> clientConfig;
static Map<String, Object> tokenConfig;
static boolean oauthHttp2Support;
private final Object lock = new Object();
public SAMLTokenHandler() {
clientConfig = Config.getInstance().getJsonMapConfig(CLIENT_CONFIG_NAME);
if(clientConfig != null) {
Map<String, Object> oauthConfig = (Map<String, Object>)clientConfig.get(OAUTH);
if(oauthConfig != null) {
tokenConfig = (Map<String, Object>)oauthConfig.get(TOKEN);
}
}
Map<String, Object> securityConfig = Config.getInstance().getJsonMapConfig(CONFIG_SECURITY);
if(securityConfig != null) {
Boolean b = (Boolean)securityConfig.get(OAUTH_HTTP2_SUPPORT);
oauthHttp2Support = (b == null ? false : b.booleanValue());
}
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
public static void sendStatusToResponse(HttpServerExchange exchange, Status status) {
exchange.setStatusCode(status.getStatusCode());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(status.toString());
logger.error(status.toString());
// in case to trace where the status is created, enable the trace level logging to diagnose.
if (logger.isTraceEnabled()) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String stackTrace = Arrays.stream(elements)
.map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
logger.trace(stackTrace);
}
}
@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(TokenConfig.CONFIG_NAME, SAMLTokenHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(TokenConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(TokenConfig.CONFIG_NAME, SAMLTokenHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(TokenConfig.CONFIG_NAME), null);
}
private Result<String> getSAMLBearerToken(String samlAssertion , String jwtAssertion) {
SAMLBearerRequest tokenRequest = new SAMLBearerRequest(samlAssertion , jwtAssertion);
Result<TokenResponse> tokenResponse = OauthHelper.getTokenFromSamlResult(tokenRequest);
if(tokenResponse.isSuccess()) {
String jwt = tokenResponse.getResult().getAccessToken();
logger.debug("SAMLBearer Grant Type jwt: ", jwt);
return Success.of(jwt);
} else {
return Failure.of(tokenResponse.getError());
}
}
}
|
// check if there is a bear token in the authorization header in the request. If this
// is one, then this must be the subject token that is linked to the original user.
// We will keep this token in the Authorization header but create a new token with
// client credentials grant type with scopes for the particular client. (Can we just
// assume that the subject token has the scope already?)
logger.debug(exchange.toString());
Result<String> result = getSAMLBearerToken(exchange.getRequestHeaders().getFirst(SAMLAssertionHeader), exchange.getRequestHeaders().getFirst(JWTAssertionHeader));
if(result.isFailure()) {
sendStatusToResponse(exchange, result.getError());
return;
}
exchange.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer " + result.getResult());
exchange.getRequestHeaders().remove(SAMLAssertionHeader);
exchange.getRequestHeaders().remove(JWTAssertionHeader);
Handler.next(exchange, next);
| 1,032
| 264
| 1,296
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/ServiceDictConfig.java
|
ServiceDictConfig
|
setMap
|
class ServiceDictConfig {
private static final Logger logger = LoggerFactory.getLogger(ServiceDictConfig.class);
public static final String CONFIG_NAME = "serviceDict";
// keys in the config file
private static final String ENABLED = "enabled";
private static final String MAPPING = "mapping";
// variables
private Map<String, Object> mappedConfig;
private Map<String, String> mapping;
private boolean enabled;
// the config object
private Config config;
private ServiceDictConfig() {
this(CONFIG_NAME);
}
private ServiceDictConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setMap();
setConfigData();
}
public static ServiceDictConfig load() {
return new ServiceDictConfig();
}
public static ServiceDictConfig load(String configName) {
return new ServiceDictConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setMap();
setConfigData();
}
public Map<String, String> getMapping() {
return mapping;
}
public boolean isEnabled() {
return enabled;
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
Config getConfig() {
return config;
}
private void setMap() {<FILL_FUNCTION_BODY>}
private void setConfigData() {
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
}
}
|
Map<String, String> rawMapping = null;
if(mappedConfig.get(MAPPING) != null) {
if(mappedConfig.get(MAPPING) instanceof String) {
String s = (String)mappedConfig.get(MAPPING);
s = s.trim();
if(logger.isTraceEnabled()) logger.trace("s = " + s);
if(s.startsWith("{")) {
// json map
try {
mapping = Config.getInstance().getMapper().readValue(s, Map.class);
} catch (IOException e) {
logger.error("IOException:", e);
}
} else {
Map<String, String> map = new LinkedHashMap<>();
for(String keyValue : s.split(" *& *")) {
String[] pairs = keyValue.split(" *= *", 2);
map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
}
rawMapping = map;
}
} else if (mappedConfig.get(MAPPING) instanceof Map) {
rawMapping = (Map<String, String>) mappedConfig.get(MAPPING);
} else {
logger.error("mapping is the wrong type. Only JSON string and YAML map are supported.");
}
// convert the mapping to internal format.
mapping = new HashMap<>();
for (Map.Entry<String, String> entry : rawMapping.entrySet()) {
mapping.put(HandlerUtils.toInternalKey(entry.getKey()), entry.getValue());
}
mapping = Collections.unmodifiableMap(mapping);
}
| 451
| 411
| 862
|
<no_super_class>
|
networknt_light-4j
|
light-4j/egress-router/src/main/java/com/networknt/router/middleware/ServiceDictHandler.java
|
ServiceDictHandler
|
serviceDict
|
class ServiceDictHandler implements MiddlewareHandler {
private static final Logger logger = LoggerFactory.getLogger(ServiceDictHandler.class);
protected volatile HttpHandler next;
protected static ServiceDictConfig config;
public ServiceDictHandler() {
logger.info("ServiceDictHandler is constructed");
config = ServiceDictConfig.load();
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("ServiceDictHandler.handleRequest starts.");
serviceDict(exchange);
if(logger.isDebugEnabled()) logger.debug("ServiceDictHandler.handleRequest ends.");
Handler.next(exchange, next);
}
protected void serviceDict(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(ServiceDictConfig.CONFIG_NAME, ServiceDictHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ServiceDictConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(ServiceDictConfig.CONFIG_NAME, ServiceDictHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ServiceDictConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("ServiceDictHandler is reloaded.");
}
}
|
String requestPath = exchange.getRequestURI();
String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
String[] serviceEntry = HandlerUtils.findServiceEntry(HandlerUtils.toInternalKey(httpMethod, requestPath), config.getMapping());
HeaderValues serviceIdHeader = exchange.getRequestHeaders().get(HttpStringConstants.SERVICE_ID);
String serviceId = serviceIdHeader != null ? serviceIdHeader.peekFirst() : null;
if(serviceId == null && serviceEntry != null) {
if(logger.isTraceEnabled()) logger.trace("serviceEntry found and header is set for service_id = " + serviceEntry[1]);
exchange.getRequestHeaders().put(HttpStringConstants.SERVICE_ID, serviceEntry[1]);
}
if (serviceEntry != null) {
if (logger.isTraceEnabled())
logger.trace("serviceEntry found and endpoint is set to = '{}'", serviceEntry[0]);
HandlerUtils.populateAuditAttachmentField(exchange, Constants.ENDPOINT_STRING, serviceEntry[0]);
} else {
if (logger.isTraceEnabled())
logger.trace("serviceEntry is null and endpoint is set to = '{}@{}'", Constants.UNKOWN_STRING, exchange.getRequestMethod().toString().toLowerCase());
// at this moment, we don't have a way to reliably determine the endpoint.
HandlerUtils.populateAuditAttachmentField(exchange, Constants.ENDPOINT_STRING, Constants.UNKOWN_STRING + "@" + exchange.getRequestMethod().toString().toLowerCase());
}
| 463
| 405
| 868
|
<no_super_class>
|
networknt_light-4j
|
light-4j/email-sender/src/main/java/com/networknt/email/EmailSender.java
|
EmailSender
|
sendMailWithAttachment
|
class EmailSender {
private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);
public static final String CONFIG_EMAIL = "email";
public static final String CONFIG_SECRET = "secret";
static final EmailConfig emailConfg = (EmailConfig)Config.getInstance().getJsonObjectConfig(CONFIG_EMAIL, EmailConfig.class);
public EmailSender() {
}
/**
* Send email with a string content.
*
* @param to destination email address
* @param subject email subject
* @param content email content
* @throws MessagingException message exception
*/
public void sendMail (String to, String subject, String content) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.user", emailConfg.getUser());
props.put("mail.smtp.host", emailConfg.getHost());
props.put("mail.smtp.port", emailConfg.getPort());
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", emailConfg.getDebug());
props.put("mail.smtp.auth", emailConfg.getAuth());
props.put("mail.smtp.ssl.trust", emailConfg.host);
String pass = emailConfg.getPass();
if(pass == null) {
Map<String, Object> secret = Config.getInstance().getJsonMapConfig(CONFIG_SECRET);
pass = (String)secret.get(SecretConstants.EMAIL_PASSWORD);
}
SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), pass);
Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailConfg.getUser()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setContent(content, "text/html");
// Send message
Transport.send(message);
if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
}
/**
* Send email with a string content and attachment
*
* @param to destination eamil address
* @param subject email subject
* @param content email content
* @param filename attachment filename
* @throws MessagingException messaging exception
*/
public void sendMailWithAttachment (String to, String subject, String content, String filename) throws MessagingException{<FILL_FUNCTION_BODY>}
private static class SMTPAuthenticator extends Authenticator {
public String user;
public String password;
public SMTPAuthenticator(String user, String password) {
this.user = user;
this.password = password ;
}
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(this.user, this.password);
}
}
/**
* This is the template variable replacement utility to replace [name] with a key
* name in the map with the value in the template to generate the final email body.
*
* @param text The template in html format
* @param replacements A map that contains key/value pair for variables
* @return String of processed template
*/
public static String replaceTokens(String text,
Map<String, String> replacements) {
Pattern pattern = Pattern.compile("\\[(.+?)\\]");
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
if (replacement != null) {
matcher.appendReplacement(buffer, "");
buffer.append(replacement);
}
}
matcher.appendTail(buffer);
return buffer.toString();
}
}
|
Properties props = new Properties();
props.put("mail.smtp.user", emailConfg.getUser());
props.put("mail.smtp.host", emailConfg.getHost());
props.put("mail.smtp.port", emailConfg.getPort());
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", emailConfg.getDebug());
props.put("mail.smtp.auth", emailConfg.getAuth());
props.put("mail.smtp.ssl.trust", emailConfg.host);
String pass = emailConfg.getPass();
if(pass == null) {
Map<String, Object> secret = Config.getInstance().getJsonMapConfig(CONFIG_SECRET);
pass = (String)secret.get(SecretConstants.EMAIL_PASSWORD);
}
SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), pass);
Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailConfg.getUser()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText(content);
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
| 1,028
| 549
| 1,577
|
<no_super_class>
|
networknt_light-4j
|
light-4j/encode-decode/src/main/java/com/networknt/decode/RequestDecodeConfig.java
|
RequestDecodeConfig
|
setConfigList
|
class RequestDecodeConfig {
private static final Logger logger = LoggerFactory.getLogger(RequestDecodeConfig.class);
public static final String CONFIG_NAME = "request-decode";
public static final String ENABLED = "enabled";
public static final String DECODERS = "decoders";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
List<String> decoders;
private RequestDecodeConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
private RequestDecodeConfig() {
this(CONFIG_NAME);
}
public static RequestDecodeConfig load(String configName) {
return new RequestDecodeConfig(configName);
}
public static RequestDecodeConfig load() {
return new RequestDecodeConfig();
}
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<String> getDecoders() {
return decoders;
}
public void setDecoders(List<String> decoders) {
this.decoders = decoders;
}
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(DECODERS) != null) {
Object object = mappedConfig.get(DECODERS);
decoders = 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 {
decoders = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the decoders json with a list of strings.");
}
} else {
// comma separated
decoders = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (object instanceof List) {
List prefixes = (List)object;
prefixes.forEach(item -> {
decoders.add((String)item);
});
} else {
throw new ConfigException("decoders must be a string or a list of strings.");
}
}
| 557
| 300
| 857
|
<no_super_class>
|
networknt_light-4j
|
light-4j/encode-decode/src/main/java/com/networknt/decode/RequestDecodeHandler.java
|
RequestDecodeHandler
|
handleRequest
|
class RequestDecodeHandler implements MiddlewareHandler {
public static RequestDecodeConfig config =
(RequestDecodeConfig)Config.getInstance().getJsonObjectConfig(RequestDecodeConfig.CONFIG_NAME, RequestDecodeConfig.class);
private final Map<String, ConduitWrapper<StreamSourceConduit>> requestEncodings = new CopyOnWriteMap<>();
private volatile HttpHandler next;
public RequestDecodeHandler() {
List<String> decoders = config.getDecoders();
for(int i = 0; i < decoders.size(); i++) {
String decoder = decoders.get(i);
if(Constants.ENCODE_DEFLATE.equals(decoder)) {
requestEncodings.put(decoder, InflatingStreamSourceConduit.WRAPPER);
} else if(Constants.ENCODE_GZIP.equals(decoder)) {
requestEncodings.put(decoder, GzipStreamSourceConduit.WRAPPER);
} else {
throw new RuntimeException("Invalid decoder " + decoder + " for RequestDecodeHandler.");
}
}
}
@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(RequestDecodeConfig.CONFIG_NAME, RequestDecodeHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(RequestDecodeConfig.CONFIG_NAME), null);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(RequestDecodeConfig.CONFIG_NAME, RequestDecodeHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(RequestDecodeConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("RequestDecodeHandler is reloaded.");
}
}
|
ConduitWrapper<StreamSourceConduit> encodings = requestEncodings.get(exchange.getRequestHeaders().getFirst(Headers.CONTENT_ENCODING));
if (encodings != null && exchange.isRequestChannelAvailable()) {
exchange.addRequestWrapper(encodings);
// Nested handlers or even servlet filters may implement logic to decode encoded request data.
// Since the data is no longer encoded, we remove the encoding header.
exchange.getRequestHeaders().remove(Headers.CONTENT_ENCODING);
}
Handler.next(exchange, next);
| 573
| 152
| 725
|
<no_super_class>
|
networknt_light-4j
|
light-4j/encode-decode/src/main/java/com/networknt/encode/ResponseEncodeConfig.java
|
ResponseEncodeConfig
|
setConfigList
|
class ResponseEncodeConfig {
private static final Logger logger = LoggerFactory.getLogger(ResponseEncodeConfig.class);
public static final String CONFIG_NAME = "response-encode";
public static final String ENABLED = "enabled";
public static final String ENCODERS = "encoders";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
List<String> encoders;
private ResponseEncodeConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
private ResponseEncodeConfig() {
this(CONFIG_NAME);
}
public static ResponseEncodeConfig load(String configName) {
return new ResponseEncodeConfig(configName);
}
public static ResponseEncodeConfig load() {
return new ResponseEncodeConfig();
}
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<String> getEncoders() {
return encoders;
}
public void setEncoders(List<String> encoders) {
this.encoders = encoders;
}
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(ENCODERS) != null) {
Object object = mappedConfig.get(ENCODERS);
encoders = 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 {
encoders = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the encoders json with a list of strings.");
}
} else {
// comma separated
encoders = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (object instanceof List) {
List prefixes = (List)object;
prefixes.forEach(item -> {
encoders.add((String)item);
});
} else {
throw new ConfigException("encoders must be a string or a list of strings.");
}
}
| 558
| 300
| 858
|
<no_super_class>
|
networknt_light-4j
|
light-4j/encode-decode/src/main/java/com/networknt/encode/ResponseEncodeHandler.java
|
ResponseEncodeHandler
|
handleRequest
|
class ResponseEncodeHandler implements MiddlewareHandler {
public static ResponseEncodeConfig config =
(ResponseEncodeConfig)Config.getInstance().getJsonObjectConfig(ResponseEncodeConfig.CONFIG_NAME, ResponseEncodeConfig.class);
static final String NO_ENCODING_HANDLER = "ERR10050";
private final ContentEncodingRepository contentEncodingRepository;
private volatile HttpHandler next;
public ResponseEncodeHandler() {
contentEncodingRepository = new ContentEncodingRepository();
List<String> encoders = config.getEncoders();
for(int i = 0; i < encoders.size(); i++) {
String encoder = encoders.get(i);
if(Constants.ENCODE_GZIP.equals(encoder)) {
contentEncodingRepository.addEncodingHandler(encoder, new GzipEncodingProvider(), 100);
} else if(Constants.ENCODE_DEFLATE.equals(encoder)) {
contentEncodingRepository.addEncodingHandler(encoder, new DeflateEncodingProvider(), 10);
} else {
throw new RuntimeException("Invalid encoder " + encoder + " for ResponseEncodeHandler.");
}
}
}
@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(ResponseEncodeConfig.CONFIG_NAME, ResponseEncodeHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ResponseEncodeConfig.CONFIG_NAME), null);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(ResponseEncodeConfig.CONFIG_NAME, ResponseEncodeHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ResponseEncodeConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("ResponseEncodeHandler is reloaded.");
}
}
|
AllowedContentEncodings encodings = contentEncodingRepository.getContentEncodings(exchange);
if (encodings == null || !exchange.isResponseChannelAvailable()) {
Handler.next(exchange, next);
} else if (encodings.isNoEncodingsAllowed()) {
setExchangeStatus(exchange, NO_ENCODING_HANDLER);
return;
} else {
exchange.addResponseWrapper(encodings);
exchange.putAttachment(AllowedContentEncodings.ATTACHMENT_KEY, encodings);
Handler.next(exchange, next);
}
| 584
| 163
| 747
|
<no_super_class>
|
networknt_light-4j
|
light-4j/exception/src/main/java/com/networknt/exception/ExceptionHandler.java
|
ExceptionHandler
|
handleRequest
|
class ExceptionHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
public static final String CONFIG_NAME = "exception";
static ExceptionConfig config = (ExceptionConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ExceptionConfig.class);
static final String STATUS_RUNTIME_EXCEPTION = "ERR10010";
static final String STATUS_UNCAUGHT_EXCEPTION = "ERR10011";
private volatile HttpHandler next;
public ExceptionHandler() {
}
@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(ExceptionConfig.CONFIG_NAME, ExceptionHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ExceptionConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config = (ExceptionConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ExceptionConfig.class);
ModuleRegistry.registerModule(ExceptionConfig.CONFIG_NAME, ExceptionHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ExceptionConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("ExceptionHandler is reloaded.");
}
}
|
if(logger.isDebugEnabled()) logger.debug("ExceptionHandler.handleRequest starts.");
// dispatch here to make sure that all exceptions will be capture in this handler
// otherwise, some of the exceptions will be captured in Connectors class in Undertow
// As we've updated Server.java to redirect the logs to slf4j but still it make sense
// to handle the exception on our ExcpetionHandler.
if (exchange.isInIoThread()) {
exchange.dispatch(this);
return;
}
try {
if(logger.isDebugEnabled()) logger.debug("ExceptionHandler.handleRequest ends.");
Handler.next(exchange, next);
} catch (Throwable e) {
logger.error("Exception:", e);
if(exchange.isResponseChannelAvailable()) {
//handle exceptions
if(e instanceof RuntimeException) {
// check if it is FrameworkException which is subclass of RuntimeException.
if(e instanceof FrameworkException) {
FrameworkException fe = (FrameworkException)e;
exchange.setStatusCode(fe.getStatus().getStatusCode());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(fe.getStatus().toString());
logger.error(fe.getStatus().toString(), e);
} else {
setExchangeStatus(exchange, STATUS_RUNTIME_EXCEPTION);
}
} else {
if(e instanceof ApiException) {
ApiException ae = (ApiException)e;
exchange.setStatusCode(ae.getStatus().getStatusCode());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(ae.getStatus().toString());
logger.error(ae.getStatus().toString(), e);
} else if(e instanceof ClientException){
ClientException ce = (ClientException)e;
if(ce.getStatus().getStatusCode() == 0){
setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION);
} else {
exchange.setStatusCode(ce.getStatus().getStatusCode());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(ce.getStatus().toString());
}
} else {
setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION);
}
}
}
} finally {
// at last, clean the MDC. Most likely, correlationId in side.
//logger.debug("Clear MDC");
MDC.clear();
}
| 443
| 672
| 1,115
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler-config/src/main/java/com/networknt/handler/config/PathChain.java
|
PathChain
|
toString
|
class PathChain {
private String source;
private String path;
private String method;
private List<String> exec;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<String> getExec() {
return exec;
}
public void setExec(List<String> exec) {
this.exec = exec;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
/**
* Validate the settings and raise Exception on error.
* The origin is used to help locate problems.
*
* @param origin the origin
*/
public void validate(String origin) {
List<String> problems = new ArrayList<>();
if (source == null) {
if (path == null) {
problems.add("You must specify either path or source");
problems.add("It is possible that serviceId is missing from the values.yml and it is mandatory.");
} else if (method == null)
problems.add("You must specify method along with path: " + path);
} else {
if (path != null)
problems.add("Conflicting source: " + source + " and path: " + path);
if (method != null)
problems.add("Conflicting source: " + source + " and method: " + method);
}
if (method != null && !Util.METHODS.contains(method.toUpperCase()))
problems.add("Invalid HTTP method: " + method);
if (!problems.isEmpty())
throw new RuntimeException("Bad paths element in " + origin + " [ " + String.join(" | ", problems) + " ]");
}
}
|
if (path != null)
return path + "@" + method + " → " + exec;
else return source + "() → " + exec;
| 538
| 46
| 584
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler/src/main/java/com/networknt/handler/BuffersUtils.java
|
BuffersUtils
|
transfer
|
class BuffersUtils {
public static final RequestInjectionConfig config = RequestInjectionConfig.load();
public static final int MAX_CONTENT_SIZE = 16 * 1024 * config.getMaxBuffers(); // 16KB * maxBuffers
private static final Logger LOG = LoggerFactory.getLogger(BuffersUtils.class);
/**
* @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)
return null;
var dst = ByteBuffer.allocate(MAX_CONTENT_SIZE);
for (PooledByteBuffer src : srcs) {
if (src != null) {
final var srcBuffer = src.getBuffer();
if (srcBuffer.remaining() > dst.remaining()) {
if (LOG.isErrorEnabled())
LOG.error("Request content exceeeded {} bytes limit", MAX_CONTENT_SIZE);
throw new IOException("Request content exceeded " + MAX_CONTENT_SIZE + " bytes limit");
}
if (srcBuffer.hasRemaining()) {
Buffers.copy(dst, srcBuffer);
srcBuffer.flip();
}
}
}
return dst.flip();
}
public static byte[] toByteArray(final PooledByteBuffer[] src) throws IOException {
ByteBuffer content = toByteBuffer(src);
if (content == null)
return new byte[]{};
byte[] ret = new byte[content.remaining()];
content.rewind();
/* 'get' actually copies the bytes from the ByteBuffer to our destination 'ret' byte array. */
content.get(ret);
return ret;
}
/**
* Returns the actual byte array of the PooledByteBuffer
*
* @param src
* @return
* @throws IOException
*/
public static byte[] getByteArray(final PooledByteBuffer[] src) throws IOException {
ByteBuffer content = toByteBuffer(src);
if (content != null && content.hasArray())
return content.array();
return new byte[]{};
}
public static String toString(final PooledByteBuffer[] srcs, Charset cs) throws IOException {
return new String(toByteArray(srcs), cs);
}
public static String toString(final byte[] src, Charset cs) throws IOException {
return new String(src, cs);
}
/**
* transfer the src data to the pooled buffers overwriting the exising data
*
* @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;
int pidx = 0;
//src.rewind();
while (src.hasRemaining() && pidx < dest.length) {
ByteBuffer _dest;
if (dest[pidx] == null) {
dest[pidx] = exchange.getConnection().getByteBufferPool().allocate();
_dest = dest[pidx].getBuffer();
} else {
_dest = dest[pidx].getBuffer();
_dest.clear();
}
copied += Buffers.copy(_dest, src);
// very important, I lost a day for this!
_dest.flip();
pidx++;
}
// clean up remaining destination buffers
while (pidx < dest.length) {
dest[pidx] = null;
pidx++;
}
return copied;
}
public static void dump(String msg, PooledByteBuffer[] data) {
int nbuf = 0;
for (PooledByteBuffer dest : data) {
if (dest != null) {
var src = dest.getBuffer();
var sb = new StringBuilder();
try {
Buffers.dump(src, sb, 2, 2);
if (LOG.isDebugEnabled())
LOG.debug("{} buffer #{}:\n{}", msg, nbuf, sb);
} catch (IOException ie) {
if (LOG.isErrorEnabled())
LOG.error("failed to dump buffered content", ie);
}
}
nbuf++;
}
}
/**
* append the src data to the pooled buffers
*
* @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;
int pidx = 0;
src.rewind();
while (src.hasRemaining() && pidx < dest.length) {
ByteBuffer _dest;
if (dest[pidx] == null) {
dest[pidx] = exchange.getConnection().getByteBufferPool().allocate();
_dest = dest[pidx].getBuffer();
} else {
_dest = dest[pidx].getBuffer();
_dest.position(_dest.limit());
}
copied += Buffers.copy(_dest, src);
_dest.flip();
pidx++;
}
// clean up remaining destination buffers
while (pidx < dest.length) {
dest[pidx] = null;
pidx++;
}
return copied;
}
public static int transfer(final PooledByteBuffer[] src, final PooledByteBuffer[] dest, final HttpServerExchange exchange) {<FILL_FUNCTION_BODY>}
}
|
int copied = 0;
int idx = 0;
while (idx < src.length && idx < dest.length) {
if (src[idx] != null) {
if (dest[idx] == null)
dest[idx] = exchange.getConnection().getByteBufferPool().allocate();
var _dest = dest[idx].getBuffer();
var _src = src[idx].getBuffer();
copied += Buffers.copy(_dest, _src);
_dest.flip();
_src.flip();
}
idx++;
}
// clean up remaining destination buffers
while (idx < dest.length) {
dest[idx] = null;
idx++;
}
return copied;
| 1,504
| 196
| 1,700
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler/src/main/java/com/networknt/handler/HandlerUtils.java
|
HandlerUtils
|
findServiceEntry
|
class HandlerUtils {
private static final Logger logger = LoggerFactory.getLogger(HandlerUtils.class);
public static final String DELIMITOR = "@";
protected static final String INTERNAL_KEY_FORMAT = "%s %s";
/**
* Looks up the appropriate serviceId for a given requestPath taken directly from exchange.
* Returns null if the path does not map to a configured service, otherwise, an array will
* be returned with the first element the path prefix and the second element the serviceId.
*
* @param searchKey search key
* @param mapping a map of prefix and service id
* @return pathPrefix and serviceId in an array that is found
*/
public static String[] findServiceEntry(String searchKey, Map<String, String> mapping) {<FILL_FUNCTION_BODY>}
public static String normalisePath(String requestPath) {
if(!requestPath.startsWith("/")) {
return "/" + requestPath;
}
return requestPath;
}
public static String toInternalKey(String key) {
String[] tokens = StringUtils.trimToEmpty(key).split(DELIMITOR);
if (tokens.length ==2) {
return toInternalKey(tokens[1], tokens[0]);
}
logger.warn("Invalid key {}", key);
return key;
}
public static String toInternalKey(String method, String path) {
return String.format(INTERNAL_KEY_FORMAT, method, HandlerUtils.normalisePath(path));
}
public static void populateAuditAttachmentField(final HttpServerExchange exchange, String fieldName, String fieldValue) {
Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
if(auditInfo == null) {
logger.trace("AuditInfo is null, creating a new one and inserting the key-value pair '{}:{}'", fieldName, fieldValue);
auditInfo = new HashMap<>();
auditInfo.put(fieldName, fieldValue);
} else {
logger.trace("AuditInfo is not null, inserting the key-value pair '{}:{}'", fieldName, fieldValue);
if (auditInfo.containsKey(fieldName))
logger.debug("AuditInfo already contains the field '{}'! Replacing the value '{}' with '{}'.", fieldName, auditInfo.get(fieldName), fieldValue);
auditInfo.put(fieldName, fieldValue);
}
exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);
}
}
|
if(logger.isDebugEnabled()) logger.debug("findServiceEntry for " + searchKey);
String[] result = null;
if(mapping == null) {
if(logger.isDebugEnabled()) logger.debug("mapping is empty in the configuration.");
return null;
}
for (Map.Entry<String, String> entry : mapping.entrySet()) {
String prefix = entry.getKey();
if(searchKey.startsWith(prefix)) {
if((searchKey.length() == prefix.length() || searchKey.charAt(prefix.length()) == '/')) {
result = new String[2];
result[0] = entry.getKey();
result[1] = entry.getValue();
break;
}
}
}
if(result == null) {
if(logger.isDebugEnabled()) logger.debug("serviceEntry not found!");
} else {
if(logger.isDebugEnabled()) logger.debug("prefix = " + result[0] + " serviceId = " + result[1]);
}
return result;
| 661
| 265
| 926
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler/src/main/java/com/networknt/handler/OrchestrationHandler.java
|
OrchestrationHandler
|
handleRequest
|
class OrchestrationHandler implements LightHttpHandler {
static final String MISSING_HANDlER = "ERR10048";
public OrchestrationHandler() {
}
public OrchestrationHandler(HttpHandler lastHandler) {
Handler.setLastHandler(lastHandler);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (Handler.start(exchange))
Handler.next(exchange);
else {
// There is no matching path/method combination. Check if there are defaultHandlers defined.
if(Handler.startDefaultHandlers(exchange))
Handler.next(exchange);
else setExchangeStatus(exchange, MISSING_HANDlER, exchange.getRequestPath(), exchange.getRequestMethod().toString());
}
| 116
| 114
| 230
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler/src/main/java/com/networknt/handler/RequestInjectionConfig.java
|
RequestInjectionConfig
|
setConfigList
|
class RequestInjectionConfig {
private static final Logger LOG = LoggerFactory.getLogger(RequestInjectionConfig.class);
public static final String CONFIG_NAME = "request-injection";
private static final String ENABLED = "enabled";
private static final String APPLIED_BODY_INJECTION_PATH_PREFIXES = "appliedBodyInjectionPathPrefixes";
private static final String MAX_BUFFERS = "maxBuffers";
private boolean enabled;
private List<String> appliedBodyInjectionPathPrefixes;
private int maxBuffers;
private Map<String, Object> mappedConfig;
private final Config config;
public RequestInjectionConfig() {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
*
* @param configName String
*/
public RequestInjectionConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
static RequestInjectionConfig load() {
return new RequestInjectionConfig();
}
static RequestInjectionConfig load(String configName) {
return new RequestInjectionConfig(configName);
}
void reload() {
this.mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
public boolean isEnabled() {
return enabled;
}
public int getMaxBuffers() {
return maxBuffers;
}
public List<String> getAppliedBodyInjectionPathPrefixes() {
return appliedBodyInjectionPathPrefixes;
}
Map<String, Object> getMappedConfig() {
return mappedConfig;
}
private void setConfigData() {
var object = getMappedConfig().get(ENABLED);
if (object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = getMappedConfig().get(MAX_BUFFERS);
if (object != null) maxBuffers = Config.loadIntegerValue(MAX_BUFFERS, object);
}
private void setConfigList() {<FILL_FUNCTION_BODY>}
}
|
if (this.mappedConfig != null && this.mappedConfig.get(APPLIED_BODY_INJECTION_PATH_PREFIXES) != null) {
var object = this.mappedConfig.get(APPLIED_BODY_INJECTION_PATH_PREFIXES);
this.appliedBodyInjectionPathPrefixes = new ArrayList<>();
if (object instanceof String) {
var s = (String) object;
s = s.trim();
if (LOG.isTraceEnabled())
LOG.trace("s = " + s);
if (s.startsWith("[")) {
// json format
try {
this.appliedBodyInjectionPathPrefixes = Config.getInstance().getMapper().readValue(s, new TypeReference<>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the appliedBodyInjectionPathPrefixes json with a list of strings.");
}
// comma separated
} else this.appliedBodyInjectionPathPrefixes = Arrays.asList(s.split("\\s*,\\s*"));
} else if (object instanceof List) {
var prefixes = (List) object;
prefixes.forEach(item -> {
this.appliedBodyInjectionPathPrefixes.add((String) item);
});
} else throw new ConfigException("appliedBodyInjectionPathPrefixes must be a string or a list of strings.");
}
| 617
| 367
| 984
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler/src/main/java/com/networknt/handler/ResponseInjectionConfig.java
|
ResponseInjectionConfig
|
setConfigList
|
class ResponseInjectionConfig {
private static final Logger logger = LoggerFactory.getLogger(ResponseInjectionConfig.class);
public static final String CONFIG_NAME = "response-injection";
private static final String ENABLED = "enabled";
private static final String APPLIED_BODY_INJECTION_PATH_PREFIXES = "appliedBodyInjectionPathPrefixes";
private boolean enabled;
private List<String> appliedBodyInjectionPathPrefixes;
private Map<String, Object> mappedConfig;
private final Config config;
public ResponseInjectionConfig() {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
/**
* Please note that this constructor is only for testing to load different config files
* to test different configurations.
*
* @param configName String
*/
public ResponseInjectionConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setConfigList();
}
static ResponseInjectionConfig load() {
return new ResponseInjectionConfig();
}
static ResponseInjectionConfig load(String configName) {
return new ResponseInjectionConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setConfigList();
}
public boolean isEnabled() {
return enabled;
}
public List<String> getAppliedBodyInjectionPathPrefixes() {
return appliedBodyInjectionPathPrefixes;
}
Map<String, Object> getMappedConfig() {
return mappedConfig;
}
private void setConfigData() {
Object object = getMappedConfig().get(ENABLED);
if (object != null) enabled = Config.loadBooleanValue(ENABLED, object);
}
private void setConfigList() {<FILL_FUNCTION_BODY>}
}
|
if (mappedConfig != null && mappedConfig.get(APPLIED_BODY_INJECTION_PATH_PREFIXES) != null) {
var object = mappedConfig.get(APPLIED_BODY_INJECTION_PATH_PREFIXES);
appliedBodyInjectionPathPrefixes = new ArrayList<>();
if (object instanceof String) {
var s = (String) object;
s = s.trim();
if (logger.isTraceEnabled())
logger.trace("s = " + s);
if (s.startsWith("["))
try {
appliedBodyInjectionPathPrefixes = Config.getInstance().getMapper().readValue(s, new TypeReference<>() {
});
} catch (Exception e) {
throw new ConfigException("could not parse the appliedBodyInjectionPathPrefixes json with a list of strings.");
}
else
// comma separated
appliedBodyInjectionPathPrefixes = Arrays.asList(s.split("\\s*,\\s*"));
} else if (object instanceof List) {
var prefixes = (List) object;
prefixes.forEach(item -> {
appliedBodyInjectionPathPrefixes.add((String) item);
});
} else throw new ConfigException("appliedBodyInjectionPathPrefixes must be a string or a list of strings.");
}
| 528
| 344
| 872
|
<no_super_class>
|
networknt_light-4j
|
light-4j/handler/src/main/java/com/networknt/handler/ResponseInterceptorInjectionHandler.java
|
ResponseInterceptorInjectionHandler
|
handleRequest
|
class ResponseInterceptorInjectionHandler implements MiddlewareHandler {
private static final Logger LOG = LoggerFactory.getLogger(ResponseInterceptorInjectionHandler.class);
public static final AttachmentKey<HeaderMap> ORIGINAL_ACCEPT_ENCODINGS_KEY = AttachmentKey.create(HeaderMap.class);
private ResponseInterceptor[] interceptors = null;
private volatile HttpHandler next;
private static ResponseInjectionConfig config;
public ResponseInterceptorInjectionHandler() throws Exception {
config = ResponseInjectionConfig.load();
interceptors = SingletonServiceFactory.getBeans(ResponseInterceptor.class);
LOG.info("SinkConduitInjectorHandler is loaded!");
}
/**
* This is a constructor for test cases only. Please don't use it.
*
* @param cfg limit config
* @throws Exception thrown when config is wrong.
*/
@Deprecated
public ResponseInterceptorInjectionHandler(ResponseInjectionConfig cfg) throws Exception {
config = cfg;
LOG.info("SinkConduitInjectorHandler 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() {
ModuleRegistry.registerModule(ResponseInjectionConfig.CONFIG_NAME, ResponseInterceptorInjectionHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ResponseInjectionConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
if (LOG.isTraceEnabled())
LOG.trace("response-injection.yml is reloaded");
ModuleRegistry.registerModule(ResponseInjectionConfig.CONFIG_NAME, ResponseInterceptorInjectionHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ResponseInjectionConfig.CONFIG_NAME), null);
}
/**
* if the ModifiableContentSinkConduit is set, set the Accept-Encoding
* header to identity this is required to avoid response interceptors
* dealing with compressed data
*
* @param exchange the exchange
*/
private void forceIdentityEncodingForInterceptors(HttpServerExchange exchange) {
if (this.interceptorsRequireContent()) {
var before = new HeaderMap();
if (exchange.getRequestHeaders().contains(Headers.ACCEPT_ENCODING))
exchange.getRequestHeaders().get(Headers.ACCEPT_ENCODING).forEach((value) -> {
before.add(Headers.ACCEPT_ENCODING, value);
});
exchange.putAttachment(ORIGINAL_ACCEPT_ENCODINGS_KEY, before);
if (LOG.isDebugEnabled())
LOG.debug("{} setting encoding to identity because request involves response interceptors.", before);
exchange.getRequestHeaders().put(Headers.ACCEPT_ENCODING, "identity");
}
}
/**
* @param exchange HttpServerExchange
* @throws Exception if any exception happens
*/
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
private boolean isCompressed(HttpServerExchange exchange) {
// check if the request has a header accept encoding with gzip and deflate.
var contentEncodings = exchange.getResponseHeaders().get(Headers.CONTENT_ENCODING_STRING);
if (contentEncodings != null)
for (var values : contentEncodings)
if (this.hasCompressionFormat(values))
return true;
return false;
}
private boolean requiresContentSinkConduit(final HttpServerExchange exchange) {
return this.interceptorsRequireContent()
&& isAppliedBodyInjectionPathPrefix(exchange.getRequestPath())
&& !isCompressed(exchange);
}
private boolean isAppliedBodyInjectionPathPrefix(String requestPath) {
return config.getAppliedBodyInjectionPathPrefixes() != null
&& config.getAppliedBodyInjectionPathPrefixes().stream().anyMatch(requestPath::startsWith);
}
private boolean hasCompressionFormat(String values) {
return Arrays.stream(values.split(",")).anyMatch(
(v) -> Headers.GZIP.toString().equals(v)
|| Headers.COMPRESS.toString().equals(v)
|| Headers.DEFLATE.toString().equals(v)
);
}
private boolean interceptorsRequireContent() {
return interceptors != null && Arrays.stream(interceptors).anyMatch(ri -> ri.isRequiredContent());
}
}
|
// of the response buffering it if any interceptor resolvers the request
// and requires the content from the backend
exchange.addResponseWrapper((ConduitFactory<StreamSinkConduit> factory, HttpServerExchange currentExchange) -> {
if (this.requiresContentSinkConduit(exchange)) {
var mcsc = new ModifiableContentSinkConduit(factory.create(), currentExchange);
if (LOG.isTraceEnabled())
LOG.trace("created a ModifiableContentSinkConduit instance " + mcsc);
return mcsc;
} else return new ContentStreamSinkConduit(factory.create(), currentExchange);
});
Handler.next(exchange, next);
| 1,262
| 190
| 1,452
|
<no_super_class>
|
networknt_light-4j
|
light-4j/header/src/main/java/com/networknt/header/HeaderHandler.java
|
HeaderHandler
|
handleRequest
|
class HeaderHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(HeaderHandler.class);
private static HeaderConfig config;
private volatile HttpHandler next;
public HeaderHandler() {
config = HeaderConfig.load();
}
/**
* Please don't use this constructor. It is used by test case only to inject config object.
* @param cfg HeaderConfig
* @deprecated
*/
public HeaderHandler(HeaderConfig cfg) {
config = cfg;
}
/**
* Check iterate the configuration on both request and response section and update
* headers accordingly.
*
* @param exchange HttpServerExchange
* @throws Exception Exception
*/
@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(HeaderConfig.CONFIG_NAME, HeaderHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HeaderConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(HeaderConfig.CONFIG_NAME, HeaderHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HeaderConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("HeaderHandler is reloaded.");
}
}
|
if(logger.isDebugEnabled()) logger.debug("HeaderHandler.handleRequest starts.");
// handle all request header
List<String> requestHeaderRemove = config.getRequestRemoveList();
if(requestHeaderRemove != null) {
requestHeaderRemove.forEach(s -> exchange.getRequestHeaders().remove(s));
}
Map<String, Object> requestHeaderUpdate = config.getRequestUpdateMap();
if(requestHeaderUpdate != null) {
requestHeaderUpdate.forEach((k, v) -> exchange.getRequestHeaders().put(new HttpString(k), (String)v));
}
// handle all response header
List<String> responseHeaderRemove = config.getResponseRemoveList();
if(responseHeaderRemove != null) {
responseHeaderRemove.forEach(s -> exchange.getResponseHeaders().remove(s));
}
Map<String, Object> responseHeaderUpdate = config.getResponseUpdateMap();
if(responseHeaderUpdate != null) {
responseHeaderUpdate.forEach((k, v) -> exchange.getResponseHeaders().put(new HttpString(k), (String)v));
}
// handler per path prefix header if configured.
Map<String, Object> pathPrefixHeader = config.getPathPrefixHeader();
if(pathPrefixHeader != null) {
String requestPath = exchange.getRequestPath();
for(Map.Entry<String, Object> entry: config.getPathPrefixHeader().entrySet()) {
if(requestPath.startsWith(entry.getKey())) {
if(logger.isTraceEnabled()) logger.trace("found with requestPath = " + requestPath + " prefix = " + entry.getKey());
Map<String, Object> valueMap = (Map<String, Object>)entry.getValue();
// handle the request header for the request path
Map<String, Object> requestHeaderMap = (Map<String, Object>)valueMap.get(HeaderConfig.REQUEST);
if(requestHeaderMap != null) {
List<String> requestHeaderRemoveList = (List<String>)requestHeaderMap.get(HeaderConfig.REMOVE);
if(requestHeaderRemoveList != null) {
requestHeaderRemoveList.forEach(s -> {
exchange.getRequestHeaders().remove(s);
if(logger.isTraceEnabled()) logger.trace("remove request header " + s);
});
}
Map<String, Object> requestHeaderUpdateMap = (Map<String, Object>)requestHeaderMap.get(HeaderConfig.UPDATE);
if(requestHeaderUpdateMap != null) {
requestHeaderUpdateMap.forEach((k, v) -> {
exchange.getRequestHeaders().put(new HttpString(k), (String)v);
if(logger.isTraceEnabled()) logger.trace("update request header " + k + " with value " + v);
});
}
}
// handle the response header for the request path
Map<String, Object> responseHeaderMap = (Map<String, Object>)valueMap.get(HeaderConfig.RESPONSE);
if(responseHeaderMap != null) {
List<String> responseHeaderRemoveList = (List<String>)responseHeaderMap.get(HeaderConfig.REMOVE);
if(responseHeaderRemoveList != null) {
responseHeaderRemoveList.forEach(s -> {
exchange.getResponseHeaders().remove(s);
if(logger.isTraceEnabled()) logger.trace("remove response header " + s);
});
}
Map<String, Object> responseHeaderUpdateMap = (Map<String, Object>)responseHeaderMap.get(HeaderConfig.UPDATE);
if(responseHeaderUpdateMap != null) {
responseHeaderUpdateMap.forEach((k, v) -> {
exchange.getResponseHeaders().put(new HttpString(k), (String)v);
if(logger.isTraceEnabled()) logger.trace("update response header " + k + " with value " + v);
});
}
}
}
}
}
if(logger.isDebugEnabled()) logger.debug("HeaderHandler.handleRequest ends.");
Handler.next(exchange, next);
| 466
| 1,011
| 1,477
|
<no_super_class>
|
networknt_light-4j
|
light-4j/health-config/src/main/java/com/networknt/health/HealthConfig.java
|
HealthConfig
|
setConfigData
|
class HealthConfig {
public static final String CONFIG_NAME = "health";
private static final String ENABLED = "enabled";
private static final String USE_JSON = "useJson";
private static final String TIMEOUT = "timeout";
private static final String DOWNSTREAM_ENABLED = "downstreamEnabled";
private static final String DOWNSTREAM_HOST = "downstreamHost";
private static final String DOWNSTREAM_PATH = "downstreamPath";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enabled;
boolean useJson;
int timeout;
boolean downstreamEnabled;
String downstreamHost;
String downstreamPath;
private HealthConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
private HealthConfig() {
this(CONFIG_NAME);
}
public static HealthConfig load(String configName) {
return new HealthConfig(configName);
}
public static HealthConfig load() {
return new HealthConfig();
}
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 isUseJson() {
return useJson;
}
public void setUseJson(boolean useJson) {
this.useJson = useJson;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public boolean isDownstreamEnabled() {
return downstreamEnabled;
}
public void setDownstreamEnabled(boolean downstreamEnabled) {
this.downstreamEnabled = downstreamEnabled;
}
public String getDownstreamHost() {
return downstreamHost;
}
public void setDownstreamHost(String downstreamHost) {
this.downstreamHost = downstreamHost;
}
public String getDownstreamPath() {
return downstreamPath;
}
public void setDownstreamPath(String downstreamPath) {
this.downstreamPath = downstreamPath;
}
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(USE_JSON);
if(object != null) useJson = Config.loadBooleanValue(USE_JSON, object);
object = getMappedConfig().get(TIMEOUT);
if(object != null) timeout = Config.loadIntegerValue(TIMEOUT, object);
object = getMappedConfig().get(DOWNSTREAM_ENABLED);
if(object != null) downstreamEnabled = Config.loadBooleanValue(DOWNSTREAM_ENABLED, object);
object = getMappedConfig().get(DOWNSTREAM_HOST);
if(object != null) downstreamHost = (String)object;
object = getMappedConfig().get(DOWNSTREAM_PATH);
if(object != null) downstreamPath = (String)object;
}
| 710
| 257
| 967
|
<no_super_class>
|
networknt_light-4j
|
light-4j/health/src/main/java/com/networknt/health/HealthGetHandler.java
|
HealthGetHandler
|
handleRequest
|
class HealthGetHandler implements LightHttpHandler {
public static final String HEALTH_RESULT_OK = "OK";
public static final String HEALTH_RESULT_OK_JSON = JsonMapper.toJson(new HealthResult("OK"));
static final Logger logger = LoggerFactory.getLogger(HealthGetHandler.class);
static HealthConfig config;
public HealthGetHandler(){
config = HealthConfig.load();
ModuleRegistry.registerModule(HealthConfig.CONFIG_NAME, HealthGetHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HealthConfig.CONFIG_NAME), null);
if(logger.isTraceEnabled()) logger.trace("HealthGetHandler is constructed.");
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
static class HealthResult {
private String result;
private HealthResult(String result) {
setResult(result);
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
public static void reload() {
config = HealthConfig.load();
ModuleRegistry.registerModule(HealthConfig.CONFIG_NAME, HealthGetHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HealthConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("HealthGetHandler is reloaded.");
}
}
|
if (config != null && config.isUseJson()) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(HEALTH_RESULT_OK_JSON);
} else {
exchange.getResponseSender().send(HEALTH_RESULT_OK);
}
| 377
| 89
| 466
|
<no_super_class>
|
networknt_light-4j
|
light-4j/http-entity/src/main/java/com/networknt/http/ConcurrentLruCache.java
|
ConcurrentLruCache
|
get
|
class ConcurrentLruCache<K, V> {
private final int sizeLimit;
private final Function<K, V> generator;
private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();
private final ConcurrentLinkedDeque<K> queue = new ConcurrentLinkedDeque<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private volatile int size;
/**
* Create a new cache instance with the given limit and generator function.
* @param sizeLimit the maximum number of entries in the cache
* (0 indicates no caching, always generating a new value)
* @param generator a function to generate a new value for a given key
*/
public ConcurrentLruCache(int sizeLimit, Function<K, V> generator) {
this.sizeLimit = sizeLimit;
this.generator = generator;
}
/**
* Retrieve an entry from the cache, potentially triggering generation
* of the value.
* @param key the key to retrieve the entry for
* @return the cached or newly generated value
*/
public V get(K key) {<FILL_FUNCTION_BODY>}
/**
* Determine whether the given key is present in this cache.
* @param key the key to check for
* @return {@code true} if the key is present,
* {@code false} if there was no matching key
*/
public boolean contains(K key) {
return this.cache.containsKey(key);
}
/**
* Immediately remove the given key and any associated value.
* @param key the key to evict the entry for
* @return {@code true} if the key was present before,
* {@code false} if there was no matching key
*/
public boolean remove(K key) {
this.lock.writeLock().lock();
try {
boolean wasPresent = (this.cache.remove(key) != null);
this.queue.remove(key);
this.size = this.cache.size();
return wasPresent;
}
finally {
this.lock.writeLock().unlock();
}
}
/**
* Immediately remove all entries from this cache.
*/
public void clear() {
this.lock.writeLock().lock();
try {
this.cache.clear();
this.queue.clear();
this.size = 0;
}
finally {
this.lock.writeLock().unlock();
}
}
/**
* Return the current size of the cache.
* @see #sizeLimit()
* @return int Size of the cache.
*/
public int size() {
return this.size;
}
/**
* Return the the maximum number of entries in the cache
* (0 indicates no caching, always generating a new value).
* @see #size()
* @return int Size limit of the cache
*/
public int sizeLimit() {
return this.sizeLimit;
}
}
|
if (this.sizeLimit == 0) {
return this.generator.apply(key);
}
V cached = this.cache.get(key);
if (cached != null) {
if (this.size < this.sizeLimit) {
return cached;
}
this.lock.readLock().lock();
try {
if (this.queue.removeLastOccurrence(key)) {
this.queue.offer(key);
}
return cached;
}
finally {
this.lock.readLock().unlock();
}
}
this.lock.writeLock().lock();
try {
// Retrying in case of concurrent reads on the same key
cached = this.cache.get(key);
if (cached != null) {
if (this.queue.removeLastOccurrence(key)) {
this.queue.offer(key);
}
return cached;
}
// Generate value first, to prevent size inconsistency
V value = this.generator.apply(key);
if (this.size == this.sizeLimit) {
K leastUsed = this.queue.poll();
if (leastUsed != null) {
this.cache.remove(leastUsed);
}
}
this.queue.offer(key);
this.cache.put(key, value);
this.size = this.cache.size();
return value;
}
finally {
this.lock.writeLock().unlock();
}
| 750
| 397
| 1,147
|
<no_super_class>
|
networknt_light-4j
|
light-4j/http-entity/src/main/java/com/networknt/http/HttpEntity.java
|
HttpEntity
|
equals
|
class HttpEntity<T> {
/**
* The empty {@code HttpEntity}, with no body or headers.
*/
public static final HttpEntity<?> EMPTY = new HttpEntity<>();
private final HeaderMap headers;
private final T body;
/**
* Create a new, empty {@code HttpEntity}.
*/
protected HttpEntity() {
this(null, null);
}
/**
* Create a new {@code HttpEntity} with the given body and no headers.
* @param body the entity body
*/
public HttpEntity(T body) {
this(body, null);
}
/**
* Create a new {@code HttpEntity} with the given headers and no body.
* @param headers the entity headers
*/
public HttpEntity(HeaderMap headers) {
this(null, headers);
}
/**
* Create a new {@code HttpEntity} with the given body and headers.
* @param body the entity body
* @param headers the entity headers
*/
public HttpEntity(T body, HeaderMap headers) {
this.body = body;
this.headers = headers;
}
/**
* Returns the headers of this entity.
* @return HttpHeaders
*/
public HeaderMap getHeaders() {
return this.headers;
}
/**
* Returns the body of this entity.
* @return T body
*/
public T getBody() {
return this.body;
}
/**
* Indicates whether this entity has a body.
* @return boolean true if has body
*/
public boolean hasBody() {
return (this.body != null);
}
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return (ObjectUtils.nullSafeHashCode(this.headers) * 29 + ObjectUtils.nullSafeHashCode(this.body));
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("<");
if (this.body != null) {
builder.append(this.body);
builder.append(',');
}
builder.append(this.headers);
builder.append('>');
return builder.toString();
}
}
|
if (this == other) {
return true;
}
if (other == null || other.getClass() != getClass()) {
return false;
}
HttpEntity<?> otherEntity = (HttpEntity<?>) other;
return (ObjectUtils.nullSafeEquals(this.headers, otherEntity.headers) &&
ObjectUtils.nullSafeEquals(this.body, otherEntity.body));
| 575
| 107
| 682
|
<no_super_class>
|
networknt_light-4j
|
light-4j/http-entity/src/main/java/com/networknt/http/ResponseEntity.java
|
DefaultBuilder
|
contentType
|
class DefaultBuilder implements BodyBuilder {
private final Object statusCode;
private final HeaderMap headers;
public DefaultBuilder(Object statusCode) {
this(statusCode, new HeaderMap());
}
public DefaultBuilder(Object statusCode, HeaderMap headers) {
this.statusCode = statusCode;
this.headers = headers;
}
@Override
public BodyBuilder contentType(MediaType contentType) {<FILL_FUNCTION_BODY>}
@Override
public <T> ResponseEntity<T> body(T body) {
return new ResponseEntity<>(body, this.headers, this.statusCode);
}
}
|
if(contentType != null) {
this.headers.put(Headers.CONTENT_TYPE, contentType.toString());
} else {
this.headers.remove(Headers.CONTENT_TYPE);
}
return this;
| 169
| 62
| 231
|
<methods>public void <init>(T) ,public void <init>(HeaderMap) ,public void <init>(T, HeaderMap) ,public boolean equals(java.lang.Object) ,public T getBody() ,public HeaderMap getHeaders() ,public boolean hasBody() ,public int hashCode() ,public java.lang.String toString() <variables>public static final HttpEntity<?> EMPTY,private final non-sealed T body,private final non-sealed HeaderMap headers
|
networknt_light-4j
|
light-4j/http-url/src/main/java/com/networknt/url/QueryString.java
|
QueryString
|
addString
|
class QueryString {
private static final long serialVersionUID = 1744232652147275170L;
private final String encoding;
private Map<String, List<String>> parameters = new HashMap<>();
/**
* Constructor.
*/
public QueryString() {
this(StringUtils.EMPTY, StandardCharsets.UTF_8.toString());
}
/**
* Default URL character encoding is UTF-8.
* @param urlWithQueryString a URL from which to extract a query string.
*/
public QueryString(URL urlWithQueryString) {
this(urlWithQueryString.toString(), null);
}
/**
* Constructor.
* @param urlWithQueryString a URL from which to extract a query string.
* @param encoding character encoding
*/
public QueryString(URL urlWithQueryString, String encoding) {
this(urlWithQueryString.toString(), encoding);
}
/**
* Constructor. Default URL character encoding is UTF-8.
* It is possible to only supply a query string as opposed to an
* entire URL.
* Key and values making up a query string are assumed to be URL-encoded.
* Will throw a {@link RuntimeException} if UTF-8 encoding is not supported.
* @param urlWithQueryString a URL from which to extract a query string.
*/
public QueryString(String urlWithQueryString) {
this(urlWithQueryString, null);
}
/**
* Constructor.
* It is possible to only supply a query string as opposed to an
* entire URL.
* Key and values making up a query string are assumed to be URL-encoded.
* Will throw a {@link RuntimeException} if the supplied encoding is
* unsupported or invalid.
* @param urlWithQueryString a URL from which to extract a query string.
* @param encoding character encoding
*/
public QueryString(String urlWithQueryString, String encoding) {
if (StringUtils.isBlank(encoding)) {
this.encoding = StandardCharsets.UTF_8.toString();
} else {
this.encoding = encoding;
}
String paramString = urlWithQueryString;
if (paramString.contains("?")) {
paramString = StringUtils.substringBefore(paramString, "#");
paramString = paramString.replaceAll("(.*?)(\\?)(.*)", "$3");
}
String[] paramParts = paramString.split("\\&");
for (int i = 0; i < paramParts.length; i++) {
String paramPart = paramParts[i];
if (StringUtils.isBlank(paramPart)) {
continue;
}
String key;
String value;
if (paramPart.contains("=")) {
key = StringUtils.substringBefore(paramPart, "=");
value = StringUtils.substringAfter(paramPart, "=");
} else {
key = paramPart;
value = StringUtils.EMPTY;
}
try {
addString(URLDecoder.decode(key, this.encoding),
URLDecoder.decode(value, this.encoding));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(
"Cannot URL-decode query string (key="
+ key + "; value=" + value + ").", e);
}
}
}
/**
* Gets the character encoding. Default is UTF-8.
* @return character encoding
* @since 1.7.0
*/
public String getEncoding() {
return encoding;
}
/**
* Convert this <code>QueryString</code> to a URL-encoded string
* representation that can be appended as is to a URL with no query string.
*/
@Override
public synchronized String toString() {
if (parameters.isEmpty()) {
return "";
}
StringBuilder b = new StringBuilder();
char sep = '?';
for (String key : parameters.keySet()) {
for (String value : parameters.get(key)) {
b.append(sep);
sep = '&';
try {
b.append(URLEncoder.encode(key, encoding));
b.append('=');
b.append(URLEncoder.encode(value, encoding));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(
"Cannot URL-encode query string (key="
+ key + "; value=" + value + ").", e);
}
}
}
return b.toString();
}
/**
* Apply this url QueryString on the given URL. If a query string already
* exists, it is replaced by this one.
* @param url the URL to apply this query string.
* @return url with query string added
*/
public String applyOnURL(String url) {
if (StringUtils.isBlank(url)) {
return url;
}
return StringUtils.substringBefore(url, "?") + toString();
}
/**
* Apply this url QueryString on the given URL. If a query string already
* exists, it is replaced by this one.
* @param url the URL to apply this query string.
* @return url with query string added
*/
public URL applyOnURL(URL url) {
if (url == null) {
return url;
}
try {
return new URL(applyOnURL(url.toString()));
} catch (MalformedURLException e) {
throw new RuntimeException("Cannot applyl query string to: " + url, e);
}
}
/**
* Adds one or multiple string values.
* Adding a single <code>null</code> value has no effect.
* When adding multiple values, <code>null</code> values are converted
* to blank strings.
* @param key the key of the value to set
* @param values the values to set
*/
public final void addString(String key, String... values) {<FILL_FUNCTION_BODY>}
public boolean isEmpty() {
return parameters.isEmpty();
}
}
|
if (values == null || Array.getLength(values) == 0) {
return;
}
List<String> list = parameters.get(key);
if (list == null) {
list = new ArrayList<>();
}
list.addAll(Arrays.asList(values));
parameters.put(key, list);
| 1,564
| 88
| 1,652
|
<no_super_class>
|
networknt_light-4j
|
light-4j/info-config/src/main/java/com/networknt/info/ServerInfoConfig.java
|
ServerInfoConfig
|
setList
|
class ServerInfoConfig {
private static final Logger logger = LoggerFactory.getLogger(ServerInfoConfig.class);
public static final String CONFIG_NAME = "info";
public static final String ENABLE_SERVER_INFO = "enableServerInfo";
public static final String KEYS_TO_NOT_SORT = "keysToNotSort";
private static final String DOWNSTREAM_ENABLED = "downstreamEnabled";
private static final String DOWNSTREAM_HOST = "downstreamHost";
private static final String DOWNSTREAM_PATH = "downstreamPath";
private Map<String, Object> mappedConfig;
private final Config config;
boolean enableServerInfo;
List<String> keysToNotSort;
boolean downstreamEnabled;
String downstreamHost;
String downstreamPath;
private ServerInfoConfig() {
this(CONFIG_NAME);
}
private ServerInfoConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setData();
setList();
}
public static ServerInfoConfig load() {
return new ServerInfoConfig();
}
public static ServerInfoConfig load(String configName) {
return new ServerInfoConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setData();
setList();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public Config getConfig() {
return config;
}
public List<String> getKeysToNotSort() {
return keysToNotSort;
}
public boolean isEnableServerInfo() {
return enableServerInfo;
}
public void setEnableServerInfo(boolean enableServerInfo) {
this.enableServerInfo = enableServerInfo;
}
public boolean isDownstreamEnabled() {
return downstreamEnabled;
}
public void setDownstreamEnabled(boolean downstreamEnabled) {
this.downstreamEnabled = downstreamEnabled;
}
public String getDownstreamHost() {
return downstreamHost;
}
public void setDownstreamHost(String downstreamHost) {
this.downstreamHost = downstreamHost;
}
public String getDownstreamPath() {
return downstreamPath;
}
public void setDownstreamPath(String downstreamPath) {
this.downstreamPath = downstreamPath;
}
private void setData() {
Object object = mappedConfig.get(ENABLE_SERVER_INFO);
if(object != null) enableServerInfo = Config.loadBooleanValue(ENABLE_SERVER_INFO, object);
object = getMappedConfig().get(DOWNSTREAM_ENABLED);
if(object != null) downstreamEnabled = Config.loadBooleanValue(DOWNSTREAM_ENABLED, object);
object = getMappedConfig().get(DOWNSTREAM_HOST);
if(object != null) downstreamHost = (String)object;
object = getMappedConfig().get(DOWNSTREAM_PATH);
if(object != null) downstreamPath = (String)object;
}
private void setList() {<FILL_FUNCTION_BODY>}
}
|
if(mappedConfig.get(KEYS_TO_NOT_SORT) instanceof String) {
String s = (String)mappedConfig.get(KEYS_TO_NOT_SORT);
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 {
keysToNotSort = Config.getInstance().getMapper().readValue(s, new TypeReference<List<String>>() {});
} catch (Exception e) {
throw new ConfigException("could not parse the keysToNotSort json with a list of strings.");
}
} else {
// this is a comma separated string.
keysToNotSort = Arrays.asList(s.split("\\s*,\\s*"));
}
} else if (getMappedConfig().get(KEYS_TO_NOT_SORT) instanceof List) {
keysToNotSort = (List<String>) mappedConfig.get(KEYS_TO_NOT_SORT);
} else {
keysToNotSort = Arrays.asList("admin","default","defaultHandlers");
}
| 841
| 302
| 1,143
|
<no_super_class>
|
networknt_light-4j
|
light-4j/info-config/src/main/java/com/networknt/info/ServerInfoUtil.java
|
ServerInfoUtil
|
getServerTlsFingerPrint
|
class ServerInfoUtil {
static final Logger logger = LoggerFactory.getLogger(ServerInfoUtil.class);
public static Map<String, Object> updateNormalizeKey(Map<String, Object> moduleRegistry, ServerInfoConfig config) {
Map<String, Object> newModuleRegistry = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : moduleRegistry.entrySet()) {
String key = entry.getKey();
if (key.contains(":")) {
key = key.substring(0, key.indexOf(":"));
}
newModuleRegistry.put(key, entry.getValue());
}
// normalized the key and value for comparison.
newModuleRegistry = ConfigUtils.normalizeMap(newModuleRegistry, config.getKeysToNotSort());
return newModuleRegistry;
}
public static Map<String, Object> getDeployment() {
Map<String, Object> deploymentMap = new LinkedHashMap<>();
deploymentMap.put("apiVersion", Util.getJarVersion());
deploymentMap.put("frameworkVersion", getFrameworkVersion());
return deploymentMap;
}
public static Map<String, Object> getEnvironment() {
Map<String, Object> envMap = new LinkedHashMap<>();
envMap.put("host", getHost());
envMap.put("runtime", getRuntime());
envMap.put("system", getSystem());
return envMap;
}
public static Map<String, Object> getRuntime() {
Map<String, Object> runtimeMap = new LinkedHashMap<>();
Runtime runtime = Runtime.getRuntime();
runtimeMap.put("availableProcessors", runtime.availableProcessors());
runtimeMap.put("freeMemory", runtime.freeMemory());
runtimeMap.put("totalMemory", runtime.totalMemory());
runtimeMap.put("maxMemory", runtime.maxMemory());
return runtimeMap;
}
public static Map<String, Object> getSystem() {
Map<String, Object> systemMap = new LinkedHashMap<>();
Properties properties = System.getProperties();
systemMap.put("javaVendor", properties.getProperty("java.vendor"));
systemMap.put("javaVersion", properties.getProperty("java.version"));
systemMap.put("osName", properties.getProperty("os.name"));
systemMap.put("osVersion", properties.getProperty("os.version"));
systemMap.put("userTimezone", properties.getProperty("user.timezone"));
return systemMap;
}
public static String getFrameworkVersion() {
String version = null;
String path = "META-INF/maven/com.networknt/info/pom.properties";
InputStream in = ClassLoader.getSystemResourceAsStream(path);
try {
Properties prop = new Properties();
prop.load(in);
version = prop.getProperty("version");
} catch (Exception e) {
//logger.error("Exception:", e);
} finally {
try { in.close(); }
catch (Exception ignored){}
}
return version;
}
/**
* We can get it from server module but we don't want mutual dependency. So
* get it from config and keystore directly
*
* @return String TLS server certificate finger print
*/
public static String getServerTlsFingerPrint() {<FILL_FUNCTION_BODY>}
public static Map<String, Object> getHost() {
Map<String, Object> hostMap = new LinkedHashMap<>();
String ip = "unknown";
String hostname = "unknown";
InetAddress inetAddress = Util.getInetAddress();
ip = inetAddress.getHostAddress();
hostname = inetAddress.getHostName();
hostMap.put("ip", ip);
hostMap.put("hostname", hostname);
return hostMap;
}
public static Map<String, Object> getSecurity() {
Map<String, Object> secMap = new LinkedHashMap<>();
secMap.put("serverFingerPrint", getServerTlsFingerPrint());
return secMap;
}
public static Map<String, Object> getServerInfo(ServerInfoConfig config) {
Map<String, Object> infoMap = new LinkedHashMap<>();
infoMap.put("deployment", getDeployment());
infoMap.put("environment", getEnvironment());
infoMap.put("security", getSecurity());
// remove this as it is a rest specific. The specification is loaded in the specific handler.
// infoMap.put("specification", Config.getInstance().getJsonMapConfigNoCache("openapi"));
infoMap.put("component", updateNormalizeKey(ModuleRegistry.getModuleRegistry(), config));
infoMap.put("plugin", updateNormalizeKey(ModuleRegistry.getPluginRegistry(), config));
infoMap.put("plugins", ModuleRegistry.getPlugins());
return infoMap;
}
}
|
String fingerPrint = null;
ServerConfig serverConfig = ServerConfig.getInstance();
// load keystore here based on server config and secret config
String keystoreName = serverConfig.getKeystoreName();
String keystorePass = serverConfig.getKeystorePass();
if(keystoreName != null) {
try (InputStream stream = Config.getInstance().getInputStreamFromFile(keystoreName)) {
KeyStore loadedKeystore = KeyStore.getInstance("JKS");
loadedKeystore.load(stream, keystorePass.toCharArray());
X509Certificate cert = (X509Certificate)loadedKeystore.getCertificate(ServerConfig.CONFIG_NAME);
if(cert != null) {
fingerPrint = FingerPrintUtil.getCertFingerPrint(cert);
} else {
logger.error("Unable to find the certificate with alias name as server in the keystore");
}
} catch (Exception e) {
logger.error("Unable to load server keystore ", e);
}
}
return fingerPrint;
| 1,217
| 275
| 1,492
|
<no_super_class>
|
networknt_light-4j
|
light-4j/info/src/main/java/com/networknt/info/ServerInfoGetHandler.java
|
ServerInfoGetHandler
|
handleRequest
|
class ServerInfoGetHandler implements LightHttpHandler {
static final String STATUS_SERVER_INFO_DISABLED = "ERR10013";
static final Logger logger = LoggerFactory.getLogger(ServerInfoGetHandler.class);
static ServerInfoConfig config;
public ServerInfoGetHandler() {
if(logger.isDebugEnabled()) logger.debug("ServerInfoGetHandler is constructed");
config = ServerInfoConfig.load();
ModuleRegistry.registerModule(ServerInfoConfig.CONFIG_NAME, ServerInfoConfig.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(ServerInfoConfig.CONFIG_NAME),null);
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if(config.isEnableServerInfo()) {
Map<String,Object> infoMap = ServerInfoUtil.getServerInfo(config);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(infoMap));
} else {
setExchangeStatus(exchange, STATUS_SERVER_INFO_DISABLED);
}
| 196
| 113
| 309
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/ExternalServiceConfig.java
|
ExternalServiceConfig
|
setUrlRewriteRules
|
class ExternalServiceConfig {
public static final String CONFIG_NAME = "external-service";
private static final String ENABLED = "enabled";
private static final String PROXY_HOST = "proxyHost";
private static final String PROXY_PORT = "proxyPort";
private static final String ENABLE_HTTP2 = "enableHttp2";
private static final String PATH_HOST_MAPPINGS = "pathHostMappings";
private static final String METRICS_INJECTION = "metricsInjection";
private static final String METRICS_NAME = "metricsName";
boolean enabled;
String proxyHost;
int proxyPort;
boolean enableHttp2;
boolean metricsInjection;
String metricsName;
List<String[]> pathHostMappings;
List<UrlRewriteRule> urlRewriteRules;
private Config config;
private Map<String, Object> mappedConfig;
public ExternalServiceConfig() {
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 ExternalServiceConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
setUrlRewriteRules();
setConfigList();
}
public static ExternalServiceConfig load() {
return new ExternalServiceConfig();
}
public static ExternalServiceConfig load(String configName) {
return new ExternalServiceConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
setUrlRewriteRules();
setConfigList();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public int getProxyPort() {
return proxyPort;
}
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public boolean isEnableHttp2() {
return enableHttp2;
}
public void setEnableHttp2(boolean enableHttp2) {
this.enableHttp2 = enableHttp2;
}
public boolean isMetricsInjection() { return metricsInjection; }
public String getMetricsName() { return metricsName; }
private void setConfigData() {
Object object = mappedConfig.get(ENABLED);
if (object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(PROXY_HOST);
if (object != null) setProxyHost((String) object);
object = mappedConfig.get(PROXY_PORT);
if (object != null) proxyPort = Config.loadIntegerValue(PROXY_PORT, object);
object = mappedConfig.get(ENABLE_HTTP2);
if (object != null) enableHttp2 = Config.loadBooleanValue(ENABLE_HTTP2, object);
object = getMappedConfig().get(METRICS_INJECTION);
if(object != null) metricsInjection = Config.loadBooleanValue(METRICS_INJECTION, object);
object = getMappedConfig().get(METRICS_NAME);
if(object != null ) metricsName = (String)object;
}
public List<String[]> getPathHostMappings() {
return pathHostMappings;
}
public void setPathHostMappings(List<String[]> pathHostMappings) {
this.pathHostMappings = pathHostMappings;
}
public List<UrlRewriteRule> getUrlRewriteRules() {
return urlRewriteRules;
}
public void setUrlRewriteRules() {<FILL_FUNCTION_BODY>}
public void setUrlRewriteRules(List<UrlRewriteRule> urlRewriteRules) {
this.urlRewriteRules = urlRewriteRules;
}
private void setConfigList() {
if (mappedConfig.get(PATH_HOST_MAPPINGS) != null) {
Object object = mappedConfig.get(PATH_HOST_MAPPINGS);
pathHostMappings = new ArrayList<>();
if(object instanceof String) {
String s = (String)object;
s = s.trim();
if(s.startsWith("[")) {
// multiple path to host mappings
List<String> mappings = (List<String>) JsonMapper.fromJson(s, List.class);
for (String mapping : mappings) {
String[] parts = mapping.split(" ");
if(parts.length != 2) {
throw new ConfigException("path host entry must have two elements separated by a space.");
}
pathHostMappings.add(parts);
}
} else {
// there is only one path to host available, split the string for path and host.
String[] parts = s.split(" ");
if(parts.length != 2) {
throw new ConfigException("path host entry must have two elements separated by a space.");
}
pathHostMappings.add(parts);
}
} else if (object instanceof List) {
List<String> maps = (List<String>)object;
for(String s: maps) {
String[] parts = s.split(" ");
if(parts.length != 2) {
throw new ConfigException("path host entry must have two elements separated by a space.");
}
pathHostMappings.add(parts);
}
} else {
throw new ConfigException("pathHostMappings must be a string or a list of strings.");
}
}
}
}
|
this.urlRewriteRules = new ArrayList<>();
if(mappedConfig.get("urlRewriteRules") != null) {
if (mappedConfig.get("urlRewriteRules") instanceof String) {
String s = (String)mappedConfig.get("urlRewriteRules");
s = s.trim();
// There are two formats for the urlRewriteRules. One is a string separated by a space
// and the other is a list of strings separated by a space in JSON list format.
if(s.startsWith("[")) {
// multiple rules
List<String> rules = (List<String>) JsonMapper.fromJson(s, List.class);
for (String rule : rules) {
urlRewriteRules.add(UrlRewriteRule.convertToUrlRewriteRule(rule));
}
} else {
// single rule
urlRewriteRules.add(UrlRewriteRule.convertToUrlRewriteRule(s));
}
} else if (mappedConfig.get("urlRewriteRules") instanceof List) {
List<String> rules = (List)mappedConfig.get("urlRewriteRules");
for (String s : rules) {
urlRewriteRules.add(UrlRewriteRule.convertToUrlRewriteRule(s));
}
}
}
| 1,550
| 352
| 1,902
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/MultiPartBodyPublisher.java
|
MultiPartBodyPublisher
|
addPart
|
class MultiPartBodyPublisher {
private List<PartsSpecification> partsSpecificationList = new ArrayList<>();
private String boundary = UUID.randomUUID().toString();
public HttpRequest.BodyPublisher build() {
if (partsSpecificationList.size() == 0) {
throw new IllegalStateException("Must have at least one part to build multipart message.");
}
addFinalBoundaryPart();
return HttpRequest.BodyPublishers.ofByteArrays(PartsIterator::new);
}
public String getBoundary() {
return boundary;
}
public MultiPartBodyPublisher addPart(String name, String value) {<FILL_FUNCTION_BODY>}
public MultiPartBodyPublisher addPart(String name, Path value) {
PartsSpecification newPart = new PartsSpecification();
newPart.type = PartsSpecification.TYPE.FILE;
newPart.name = name;
newPart.path = value;
partsSpecificationList.add(newPart);
return this;
}
public MultiPartBodyPublisher addPart(String name, Supplier<InputStream> value, String filename, String contentType) {
PartsSpecification newPart = new PartsSpecification();
newPart.type = PartsSpecification.TYPE.STREAM;
newPart.name = name;
newPart.stream = value;
newPart.filename = filename;
newPart.contentType = contentType;
partsSpecificationList.add(newPart);
return this;
}
private void addFinalBoundaryPart() {
PartsSpecification newPart = new PartsSpecification();
newPart.type = PartsSpecification.TYPE.FINAL_BOUNDARY;
newPart.value = "--" + boundary + "--";
partsSpecificationList.add(newPart);
}
static class PartsSpecification {
public enum TYPE {
STRING, FILE, STREAM, FINAL_BOUNDARY
}
PartsSpecification.TYPE type;
String name;
String value;
Path path;
Supplier<InputStream> stream;
String filename;
String contentType;
}
class PartsIterator implements Iterator<byte[]> {
private Iterator<PartsSpecification> iter;
private InputStream currentFileInput;
private boolean done;
private byte[] next;
PartsIterator() {
iter = partsSpecificationList.iterator();
}
@Override
public boolean hasNext() {
if (done) return false;
if (next != null) return true;
try {
next = computeNext();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (next == null) {
done = true;
return false;
}
return true;
}
@Override
public byte[] next() {
if (!hasNext()) throw new NoSuchElementException();
byte[] res = next;
next = null;
return res;
}
private byte[] computeNext() throws IOException {
if (currentFileInput == null) {
if (!iter.hasNext()) return null;
PartsSpecification nextPart = iter.next();
if (PartsSpecification.TYPE.STRING.equals(nextPart.type)) {
String part =
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=" + nextPart.name + "\r\n" +
"Content-Type: text/plain; charset=UTF-8\r\n\r\n" +
nextPart.value + "\r\n";
return part.getBytes(StandardCharsets.UTF_8);
}
if (PartsSpecification.TYPE.FINAL_BOUNDARY.equals(nextPart.type)) {
return nextPart.value.getBytes(StandardCharsets.UTF_8);
}
String filename;
String contentType;
if (PartsSpecification.TYPE.FILE.equals(nextPart.type)) {
Path path = nextPart.path;
filename = path.getFileName().toString();
contentType = Files.probeContentType(path);
if (contentType == null) contentType = "application/octet-stream";
currentFileInput = Files.newInputStream(path);
} else {
filename = nextPart.filename;
contentType = nextPart.contentType;
if (contentType == null) contentType = "application/octet-stream";
currentFileInput = nextPart.stream.get();
}
String partHeader =
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=" + nextPart.name + "; filename=" + filename + "\r\n" +
"Content-Type: " + contentType + "\r\n\r\n";
return partHeader.getBytes(StandardCharsets.UTF_8);
} else {
byte[] buf = new byte[8192];
int r = currentFileInput.read(buf);
if (r > 0) {
byte[] actualBytes = new byte[r];
System.arraycopy(buf, 0, actualBytes, 0, r);
return actualBytes;
} else {
currentFileInput.close();
currentFileInput = null;
return "\r\n".getBytes(StandardCharsets.UTF_8);
}
}
}
}
}
|
PartsSpecification newPart = new PartsSpecification();
newPart.type = PartsSpecification.TYPE.STRING;
newPart.name = name;
newPart.value = value;
partsSpecificationList.add(newPart);
return this;
| 1,374
| 69
| 1,443
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/ProxyConfig.java
|
ProxyConfig
|
setConfigData
|
class ProxyConfig {
public static final String CONFIG_NAME = "proxy";
private static final String ENABLED = "enabled";
private static final String HTTP2_ENABLED = "http2Enabled";
private static final String HOSTS = "hosts";
private static final String CONNECTIONS_PER_THREAD = "connectionsPerThread";
private static final String MAX_REQUEST_TIME = "maxRequestTime";
private static final String REWRITE_HOST_HEADER = "rewriteHostHeader";
private static final String REUSE_X_FORWARDED = "reuseXForwarded";
private static final String MAX_CONNECTION_RETRIES = "maxConnectionRetries";
private static final String MAX_QUEUE_SIZE = "maxQueueSize";
private static final String FORWARD_JWT_CLAIMS = "forwardJwtClaims";
private static final String METRICS_INJECTION = "metricsInjection";
private static final String METRICS_NAME = "metricsName";
boolean enabled;
boolean http2Enabled;
String hosts;
int connectionsPerThread;
int maxRequestTime;
boolean rewriteHostHeader;
boolean reuseXForwarded;
int maxConnectionRetries;
int maxQueueSize;
private boolean forwardJwtClaims;
boolean metricsInjection;
String metricsName;
private Config config;
private Map<String, Object> mappedConfig;
private ProxyConfig() {
this(CONFIG_NAME);
}
private ProxyConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static ProxyConfig load() {
return new ProxyConfig();
}
public static ProxyConfig load(String configName) {
return new ProxyConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public boolean isEnabled() {
return enabled;
}
public boolean isHttp2Enabled() {
return http2Enabled;
}
public String getHosts() {
return hosts;
}
public int getConnectionsPerThread() {
return connectionsPerThread;
}
public int getMaxRequestTime() {
return maxRequestTime;
}
public boolean isRewriteHostHeader() { return rewriteHostHeader; }
public boolean isReuseXForwarded() { return reuseXForwarded; }
public int getMaxConnectionRetries() { return maxConnectionRetries; }
public int getMaxQueueSize() { return maxQueueSize; }
public boolean isForwardJwtClaims() {
return forwardJwtClaims;
}
public boolean isMetricsInjection() { return metricsInjection; }
public String getMetricsName() { return metricsName; }
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = getMappedConfig().get(HTTP2_ENABLED);
if(object != null) http2Enabled = Config.loadBooleanValue(HTTP2_ENABLED, object);
object = getMappedConfig().get(REWRITE_HOST_HEADER);
if(object != null) rewriteHostHeader = Config.loadBooleanValue(REWRITE_HOST_HEADER, object);
object = getMappedConfig().get(REUSE_X_FORWARDED);
if(object != null) reuseXForwarded = Config.loadBooleanValue(REUSE_X_FORWARDED, object);
object = getMappedConfig().get(FORWARD_JWT_CLAIMS);
if(object != null) forwardJwtClaims = Config.loadBooleanValue(FORWARD_JWT_CLAIMS, object);
object = getMappedConfig().get(HOSTS);
if(object != null) hosts = (String)object;
object = getMappedConfig().get(CONNECTIONS_PER_THREAD);
if(object != null) connectionsPerThread = Config.loadIntegerValue(CONNECTIONS_PER_THREAD, object);
object = getMappedConfig().get(MAX_REQUEST_TIME);
if(object != null) maxRequestTime = Config.loadIntegerValue(MAX_REQUEST_TIME, object);
object = getMappedConfig().get(MAX_CONNECTION_RETRIES);
if(object != null) maxConnectionRetries = Config.loadIntegerValue(MAX_CONNECTION_RETRIES, object);
object = getMappedConfig().get(MAX_QUEUE_SIZE);
if(object != null) maxQueueSize = Config.loadIntegerValue(MAX_QUEUE_SIZE, object);
object = getMappedConfig().get(METRICS_INJECTION);
if(object != null) metricsInjection = Config.loadBooleanValue(METRICS_INJECTION, object);
object = getMappedConfig().get(METRICS_NAME);
if(object != null ) metricsName = (String)object;
| 796
| 526
| 1,322
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/ProxyHealthGetHandler.java
|
ProxyHealthGetHandler
|
backendHealth
|
class ProxyHealthGetHandler implements LightHttpHandler {
public static final String HEALTH_RESULT_OK = "OK";
public static final String HEALTH_RESULT_ERROR = "ERROR";
static final Logger logger = LoggerFactory.getLogger(ProxyHealthGetHandler.class);
static final HealthConfig config = HealthConfig.load();
static final Http2Client client = Http2Client.getInstance();
// cached connection to the backend API to speed up the downstream check.
static ClientConnection connection = null;
public ProxyHealthGetHandler() {
if(logger.isTraceEnabled()) logger.trace("ProxyHealthGetHandler is constructed.");
ModuleRegistry.registerModule(HealthConfig.CONFIG_NAME, ProxyHealthGetHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(HealthConfig.CONFIG_NAME), null);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("ProxyHealthGetHandler.handleRequest starts.");
String result = HEALTH_RESULT_OK;
// if backend is not connected, then error. Check the configuration to see if it is enabled.
if(config.isDownstreamEnabled()) {
result = backendHealth();
}
// for security reason, we don't output the details about the error. Users can check the log for the failure.
if(HEALTH_RESULT_ERROR.equals(result)) {
exchange.setStatusCode(400);
if(logger.isDebugEnabled()) logger.debug("ProxyHealthGetHandler.handleRequest ends with an error.");
exchange.getResponseSender().send(HEALTH_RESULT_ERROR);
} else {
exchange.setStatusCode(200);
if(logger.isDebugEnabled()) logger.debug("ProxyHealthGetHandler.handleRequest ends.");
exchange.getResponseSender().send(HEALTH_RESULT_OK);
}
}
/**
* Try to access the configurable /health endpoint on the backend API. return OK if a success response is returned.
* Otherwise, ERROR is returned.
*
* @return result String of OK or ERROR.
*/
private String backendHealth() {<FILL_FUNCTION_BODY>}
}
|
String result = HEALTH_RESULT_OK;
long start = System.currentTimeMillis();
if(connection == null || !connection.isOpen()) {
try {
if(config.getDownstreamHost().startsWith("https")) {
connection = client.borrowConnection(new URI(config.getDownstreamHost()), Http2Client.WORKER, client.getDefaultXnioSsl(), Http2Client.BUFFER_POOL, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
} else {
connection = client.borrowConnection(new URI(config.getDownstreamHost()), Http2Client.WORKER, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
}
} catch (Exception ex) {
logger.error("Could not create connection to the backend:", ex);
result = HEALTH_RESULT_ERROR;
// if connection cannot be established, return error. The backend is not started yet.
return result;
}
}
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(config.getDownstreamPath());
request.getRequestHeaders().put(Headers.HOST, "localhost");
connection.sendRequest(request, client.createClientCallback(reference, latch));
latch.await(config.getTimeout(), TimeUnit.MILLISECONDS);
int statusCode = reference.get().getResponseCode();
String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
if(logger.isDebugEnabled()) logger.debug("statusCode = " + statusCode + " body = " + body);
if(statusCode >= 400) {
// something happens on the backend and the health check is not respond.
logger.error("Error due to error response from backend with status code = " + statusCode + " body = " + body);
result = HEALTH_RESULT_ERROR;
}
} catch (Exception exception) {
logger.error("Error while sending a health check request to the backend with exception: ", exception);
// for Java EE backend like spring boot, the connection created and opened but might not ready. So we need to close
// the connection if there are any exception here to work around the spring boot backend.
if(connection != null && connection.isOpen()) {
try { connection.close(); } catch (Exception e) { logger.error("Exception:", e); }
}
result = HEALTH_RESULT_ERROR;
}
long responseTime = System.currentTimeMillis() - start;
if(logger.isDebugEnabled()) logger.debug("Downstream health check response time = " + responseTime);
return result;
| 551
| 706
| 1,257
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/ProxyServerInfoHandler.java
|
ProxyServerInfoHandler
|
getServerInfo
|
class ProxyServerInfoHandler implements LightHttpHandler {
private static final Http2Client client = Http2Client.getInstance();
private static final int UNUSUAL_STATUS_CODE = 300;
private static OptionMap optionMap = OptionMap.create(UndertowOptions.ENABLE_HTTP2, true);
private static final String PROXY_INFO_KEY = "proxy_info";
static ProxyConfig proxyConfig;
static ServerInfoConfig serverInfoConfig;
public ProxyServerInfoHandler() {
proxyConfig = ProxyConfig.load();
serverInfoConfig = ServerInfoConfig.load();
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("ProxyServerInfoHandler.handleRequest starts.");
Map<String, Object> result = new HashMap<>();
Map<String, Object> proxyInfo = ServerInfoUtil.getServerInfo(serverInfoConfig);
result.put(PROXY_INFO_KEY, proxyInfo);
HeaderValues authVal = exchange.getRequestHeaders().get(Headers.AUTHORIZATION_STRING);
String token = authVal == null ? "" : authVal.get(0);
List<String> urls = Arrays.asList(proxyConfig.getHosts().split(","));
for (String url : urls) {
Map<String, Object> serverInfo;
try {
String serverInfoStr = getServerInfo(url, token);
serverInfo = Config.getInstance().getMapper().readValue(serverInfoStr, Map.class);
} catch (Exception e) {
logger.error("cannot get server info for " + url, e);
serverInfo = null;
}
result.put(url, serverInfo);
}
if(logger.isDebugEnabled()) logger.debug("ProxyServerInfoHandler.handleRequest ends.");
exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(result));
}
/**
* get server info from url with token
* @param url the url of the target server
* @param token auth token
* @return server info JSON string
*/
public static String getServerInfo(String url, String token) {<FILL_FUNCTION_BODY>}
/**
* send to service from controller with the health check and server info
*
* @param connection ClientConnection
* @param path path to send to controller
* @param token token to put in header
* @return AtomicReference<ClientResponse> response
*/
private static AtomicReference<ClientResponse> send(ClientConnection connection, HttpString method, String path, String token, String json) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
ClientRequest request = new ClientRequest().setMethod(method).setPath(path);
// add host header for HTTP/1.1 server when HTTP is used.
request.getRequestHeaders().put(Headers.HOST, "localhost");
if (token != null) request.getRequestHeaders().put(Headers.AUTHORIZATION, "Bearer " + token);
if(StringUtils.isBlank(json)) {
connection.sendRequest(request, client.createClientCallback(reference, latch));
} else {
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
connection.sendRequest(request, client.createClientCallback(reference, latch, json));
}
latch.await(1000, TimeUnit.MILLISECONDS);
return reference;
}
}
|
String res = "{}";
ClientConnection connection = null;
try {
URI uri = new URI(url);
switch(uri.getScheme()) {
case "http":
connection = client.borrowConnection(uri, Http2Client.WORKER, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
break;
case "https":
connection = client.borrowConnection(uri, Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, optionMap).get();
break;
}
AtomicReference<ClientResponse> reference = send(connection, Methods.GET, "/server/info", token, null);
if(reference != null && reference.get() != null) {
int statusCode = reference.get().getResponseCode();
if (statusCode >= UNUSUAL_STATUS_CODE) {
logger.error("Server Info error: {} : {}", statusCode, reference.get().getAttachment(Http2Client.RESPONSE_BODY));
throw new RuntimeException();
} else {
res = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
}
}
} catch (Exception e) {
logger.error("Server info request exception", e);
throw new RuntimeException("exception when getting server info", e);
} finally {
client.returnConnection(connection);
}
return res;
| 930
| 366
| 1,296
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/tableau/TableauConfig.java
|
TableauConfig
|
setConfigData
|
class TableauConfig {
public static final String CONFIG_NAME = "tableau";
public static final String ENABLED = "enabled";
public static final String SERVER_URL = "serverUrl";
public static final String SERVER_PATH = "serverPath";
public static final String TABLEAU_USERNAME = "tableauUsername";
boolean enabled;
String serverUrl;
String serverPath;
String tableauUsername;
private final Config config;
private Map<String, Object> mappedConfig;
private TableauConfig() {
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 TableauConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static TableauConfig load() {
return new TableauConfig();
}
public static TableauConfig load(String configName) {
return new TableauConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getServerUrl() {
return serverUrl;
}
public void setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public String getServerPath() {
return serverPath;
}
public void setServerPath(String serverPath) {
this.serverPath = serverPath;
}
public String getTableauUsername() {
return tableauUsername;
}
public void setTableauUsername(String tableauUsername) {
this.tableauUsername = tableauUsername;
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = mappedConfig.get(ENABLED);
if (object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = mappedConfig.get(SERVER_URL);
if (object != null) serverUrl = (String)object;
object = mappedConfig.get(SERVER_PATH);
if (object != null) serverPath = (String)object;
object = mappedConfig.get(TABLEAU_USERNAME);
if (object != null) tableauUsername = (String)object;
| 560
| 132
| 692
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ingress-proxy/src/main/java/com/networknt/proxy/tableau/TableauSimpleAuthHandler.java
|
TableauSimpleAuthHandler
|
getToken
|
class TableauSimpleAuthHandler implements MiddlewareHandler {
private static final Logger logger = LoggerFactory.getLogger(TableauSimpleAuthHandler.class);
private static final String TABLEAU_CONFIG_NAME = "tableau";
private static final String SECRET_CONFIG_NAME = "secret";
private static final String MISSING_TABLEAU_CONTENT_URL = "ERR11301";
private static final String FAIL_TO_GET_TABLEAU_TOKEN = "ERR11300";
private static final HttpString TABLEAU_TOKEN = new HttpString("X-Tableau-Auth");
private static final HttpString TABLEAU_CONTENT_URL = new HttpString("tableauContentUrl");
private static final TableauConfig config = TableauConfig.load();
private static final Map<String, Object> secretConfig;
private volatile HttpHandler next;
static {
Map<String, Object> secretMap = Config.getInstance().getJsonMapConfig(SECRET_CONFIG_NAME);
if(secretMap != null) {
secretConfig = DecryptUtil.decryptMap(secretMap);
} else {
throw new ExceptionInInitializerError("Could not locate secret.yml");
}
}
public TableauSimpleAuthHandler() {
}
/**
* Get the credentials from tableau config and send a request to Tableau server to get the token.
* The token will be saved into exchange attachment so that the next handler in the chain can use
* it to access to the target server.
*
* @param exchange http exchange
* @throws Exception exception
*/
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
String contentUrl = exchange.getRequestHeaders().getFirst(TABLEAU_CONTENT_URL);
if(contentUrl == null || contentUrl.length() == 0) {
setExchangeStatus(exchange, MISSING_TABLEAU_CONTENT_URL);
return;
}
String token = getToken(contentUrl);
if(token == null) {
setExchangeStatus(exchange, FAIL_TO_GET_TABLEAU_TOKEN);
return;
}
exchange.getRequestHeaders().put(TABLEAU_TOKEN, token);
exchange.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
Handler.next(exchange, next);
}
private String getToken(String contentUrl) throws ClientException {<FILL_FUNCTION_BODY>}
private String getRequestBody(String contentUrl) throws IOException {
Map<String, Object> site = new HashMap<>();
site.put("contentUrl", contentUrl);
Map<String, Object> credentials = new HashMap<>();
credentials.put("name", config.getTableauUsername());
credentials.put("password", secretConfig.get("tableauPassword"));
credentials.put("site", site);
Map<String, Object> request = new HashMap<>();
request.put("credentials", credentials);
return Config.getInstance().getMapper().writeValueAsString(request);
}
@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(TableauConfig.CONFIG_NAME, TableauSimpleAuthHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(TableauConfig.CONFIG_NAME), null);
}
}
|
String token = null;
final Http2Client client = Http2Client.getInstance();
final CountDownLatch latch = new CountDownLatch(1);
final ClientConnection connection;
try {
// use HTTP 1.1 connection as I don't think Tableau supports HTTP 2.0
connection = client.connect(new URI(config.getServerUrl()), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
} catch (Exception e) {
throw new ClientException(e);
}
final AtomicReference<ClientResponse> reference = new AtomicReference<>();
try {
final String requestBody = getRequestBody(contentUrl);
ClientRequest request = new ClientRequest().setPath(config.getServerPath()).setMethod(Methods.POST);
request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
request.getRequestHeaders().put(Headers.HOST, "localhost");
request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
connection.sendRequest(request, client.createClientCallback(reference, latch, requestBody));
latch.await();
int statusCode = reference.get().getResponseCode();
if(logger.isDebugEnabled()) logger.debug("statusCode = " + statusCode);
if(statusCode == StatusCodes.OK) {
String responseBody = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
if(logger.isDebugEnabled()) logger.debug("responseBody = " + responseBody);
Map<String, Object> responseMap = Config.getInstance().getMapper().readValue(responseBody, new TypeReference<Map<String, Object>>() {});
Map<String, Object> credentials = (Map<String, Object>)responseMap.get("credentials");
token = (String)credentials.get("token");
}
} catch (Exception e) {
logger.error("Exception: ", e);
throw new ClientException(e);
} finally {
IoUtils.safeClose(connection);
}
return token;
| 930
| 538
| 1,468
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ldap-util/src/main/java/com/networknt/ldap/LdapConfig.java
|
LdapConfig
|
setConfigData
|
class LdapConfig {
public static final String CONFIG_NAME = "ldap";
public static final String URI = "uri";
public static final String DOMAIN = "domain";
public static final String PRINCIPAL = "principal";
public static final String CREDENTIAL = "credential";
public static final String SEARCH_FILTER = "searchFilter";
public static final String SEARCH_BASE = "searchBase";
String uri;
String domain;
String principal;
String credential;
String searchFilter;
String searchBase;
private final Config config;
private Map<String, Object> mappedConfig;
private LdapConfig() {
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 LdapConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static LdapConfig load() {
return new LdapConfig();
}
public static LdapConfig load(String configName) {
return new LdapConfig(configName);
}
void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getDomain() { return domain; }
public void setDomain(String domain) {
this.domain = domain;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public String getSearchFilter() { return searchFilter; }
public void setSearchFilter(String searchFilter) { this.searchFilter = searchFilter; }
public String getSearchBase() { return searchBase; }
public void setSearchBase(String searchBase) { this.searchBase = searchBase; }
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = mappedConfig.get(URI);
if (object != null) uri = (String)object;
object = mappedConfig.get(DOMAIN);
if (object != null) domain = (String)object;
object = mappedConfig.get(PRINCIPAL);
if (object != null) principal = (String)object;
object = mappedConfig.get(CREDENTIAL);
if (object != null) credential = (String)object;
object = mappedConfig.get(SEARCH_FILTER);
if (object != null) searchFilter = (String)object;
object = mappedConfig.get(SEARCH_BASE);
if (object != null) searchBase = (String)object;
| 651
| 185
| 836
|
<no_super_class>
|
networknt_light-4j
|
light-4j/ldap-util/src/main/java/com/networknt/ldap/LdapUtil.java
|
LdapUtil
|
authorize
|
class LdapUtil {
private final static Logger logger = LoggerFactory.getLogger(LdapUtil.class);
private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
private final static String CONFIG_LDAP = "ldap";
private final static LdapConfig config;
static {
config = LdapConfig.load();
ModuleRegistry.registerModule(CONFIG_LDAP, LdapUtil.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CONFIG_LDAP), null);
}
/**
*
* Bind the username and password with LDAP context to verify the password. Return true
* if there is no NamingException. No further activity to retrieve group or memberOf
* from LDAP server.
*
* @param username String
* @param password String
* @return boolean true if authenticated
*/
public static boolean authenticate(String username, String password) {
try {
String dn = getUid(username);
if (dn != null) {
/* Found user - test password */
if ( testBind( dn, password ) ) {
if(logger.isDebugEnabled()) logger.debug("user '" + username + "' authentication succeeded");
return true;
} else {
if(logger.isDebugEnabled()) logger.debug("user '" + username + "' authentication failed");
return false;
}
} else {
if(logger.isDebugEnabled()) logger.debug("user '" + username + "' not found");
return false;
}
} catch (Exception e) {
logger.error("Exception:", e);
return false;
}
}
/**
*
* @param username String
* @return A set of memberOf attributes for the username on LDAP server. You can only call
* this method if the username has been authenticated with SPNEGO/Kerberos
*/
public static Set<String> authorize(String username) {<FILL_FUNCTION_BODY>}
/**
* First authenticate with the username and password on LDAP server and then retrieve groups
* or memberOf attributes from LDAP server. return null if authentication is failed. return
* an empty set if there is no group available for the current user. This method combines both
* authentication and authorization together.
*
* @param username String
* @param password String
* @return A set of memberOf attributes for the username after authentication.
*/
public static Set<String> auth(String username, String password) {
return null;
}
private static DirContext ldapContext () throws Exception {
Hashtable<String,String> env = new Hashtable <String,String>();
return ldapContext(env);
}
private static DirContext ldapContext (Hashtable<String,String> env) throws Exception {
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, config.getUri());
if(config.getUri().toUpperCase().startsWith("LDAPS://")) {
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put("java.naming.ldap.factory.socket", "com.networknt.ldap.LdapSSLSocketFactory");
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, config.getPrincipal());
env.put(Context.SECURITY_CREDENTIALS, config.getCredential());
DirContext ctx = new InitialDirContext(env);
return ctx;
}
private static String getUid (String username) throws Exception {
DirContext ctx = ldapContext();
String filter = String.format(config.searchFilter, username);
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration answer = ctx.search(config.searchBase, filter, ctrl);
String dn;
if (answer.hasMore()) {
SearchResult result = (SearchResult) answer.next();
dn = result.getNameInNamespace();
}
else {
dn = null;
}
answer.close();
return dn;
}
private static boolean testBind (String dn, String password) throws Exception {
Hashtable<String,String> env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, config.getUri());
if(config.getUri().toUpperCase().startsWith("LDAPS://")) {
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put("java.naming.ldap.factory.socket", "com.networknt.ldap.LdapSSLSocketFactory");
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, dn);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx = null;
try {
ctx = new InitialDirContext(env);
}
catch (javax.naming.AuthenticationException e) {
return false;
} finally {
try {
if(ctx != null) ctx.close();
} catch(Exception e) {}
}
return true;
}
}
|
Set<String> groups = new HashSet();
DirContext ctx = null;
try {
ctx = ldapContext();
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = String.format(config.searchFilter, username);
NamingEnumeration<SearchResult> results = ctx.search(config.searchBase, filter, ctrls);
if(!results.hasMore()) {
logger.error("Principal name '" + username + "' not found");
return null;
}
SearchResult result = results.next();
if(logger.isDebugEnabled()) logger.debug("distinguisedName: " + result.getNameInNamespace());
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {
for(int idx=0; idx<memberOf.size(); idx++) {
groups.add(memberOf.get(idx).toString());
}
}
} catch (Exception e) {
logger.error("Failed to authorize user " + username, e);
return null;
} finally {
try {
if(ctx != null) ctx.close();
} catch(Exception e) {}
}
return groups;
| 1,430
| 328
| 1,758
|
<no_super_class>
|
networknt_light-4j
|
light-4j/logger-config/src/main/java/com/networknt/logging/model/LoggerConfig.java
|
LoggerConfig
|
setConfigData
|
class LoggerConfig {
public static final String CONFIG_NAME = "logging";
private static final String ENABLED = "enabled";
private static final String LOG_START = "logStart";
private static final String DOWNSTREAM_ENABLED = "downstreamEnabled";
private static final String DOWNSTREAM_HOST = "downstreamHost";
private static final String DOWNSTREAM_FRAMEWORK = "downstreamFramework";
boolean enabled;
long logStart;
boolean downstreamEnabled;
String downstreamHost;
String downstreamFramework;
private final Config config;
private Map<String, Object> mappedConfig;
private LoggerConfig() {
this(CONFIG_NAME);
}
private LoggerConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static LoggerConfig load() {
return new LoggerConfig();
}
public static LoggerConfig load(String configName) {
return new LoggerConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public void setConfigData() {<FILL_FUNCTION_BODY>}
public Map<String, Object> getMappedConfig() {
return mappedConfig;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public long getLogStart() {
return logStart;
}
public void setLogStart(long logStart) {
this.logStart = logStart;
}
public boolean isDownstreamEnabled() {
return downstreamEnabled;
}
public void setDownstreamEnabled(boolean downstreamEnabled) {
this.downstreamEnabled = downstreamEnabled;
}
public String getDownstreamHost() {
return downstreamHost;
}
public void setDownstreamHost(String downstreamHost) {
this.downstreamHost = downstreamHost;
}
public String getDownstreamFramework() {
return downstreamFramework;
}
public void setDownstreamFramework(String downstreamFramework) {
this.downstreamFramework = downstreamFramework;
}
}
|
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = getMappedConfig().get(DOWNSTREAM_ENABLED);
if(object != null) downstreamEnabled = Config.loadBooleanValue(DOWNSTREAM_ENABLED, object);
object = getMappedConfig().get(LOG_START);
if(object != null) logStart = Config.loadLongValue(LOG_START, object);
object = getMappedConfig().get(DOWNSTREAM_HOST);
if(object != null ) downstreamHost = (String)object;
object = getMappedConfig().get(DOWNSTREAM_FRAMEWORK);
if(object != null ) downstreamFramework = (String)object;
| 606
| 209
| 815
|
<no_super_class>
|
networknt_light-4j
|
light-4j/logger-handler/src/main/java/com/networknt/logging/handler/LoggerGetNameHandler.java
|
LoggerGetNameHandler
|
handleRequest
|
class LoggerGetNameHandler implements LightHttpHandler {
public static final String CONFIG_NAME = "logging";
private static final String LOGGER_NAME = "loggerName";
static final String STATUS_LOGGER_INFO_DISABLED = "ERR12108";
private static final ObjectMapper mapper = Config.getInstance().getMapper();
public LoggerGetNameHandler() {
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Map<String, Deque<String>> parameters = exchange.getQueryParameters();
String loggerName = parameters.get(LOGGER_NAME).getFirst();
LoggerConfig config = (LoggerConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, LoggerConfig.class);
if (config.isEnabled()) {
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(loggerName);
LoggerInfo loggerInfo = new LoggerInfo();
loggerInfo.setName(logger.getName());
loggerInfo.setLevel(logger.getLevel().toString());
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
exchange.getResponseSender().send(mapper.writeValueAsString(loggerInfo));
} else {
logger.error("Logging is disabled in logging.yml");
setExchangeStatus(exchange, STATUS_LOGGER_INFO_DISABLED);
}
| 134
| 260
| 394
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/com/networknt/metrics/APMAgentReporter.java
|
Builder
|
reportCounter
|
class Builder {
private final MetricRegistry registry;
private Map<String, String> tags;
private TimeUnit rateUnit;
private TimeUnit durationUnit;
private MetricFilter filter;
private boolean skipIdleMetrics;
private Builder(MetricRegistry registry) {
this.registry = registry;
this.tags = null;
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
}
/**
* Add these tags to all metrics.
*
* @param tags a map containing tags common to all metrics
* @return {@code this}
*/
public Builder withTags(Map<String, String> tags) {
this.tags = Collections.unmodifiableMap(tags);
return this;
}
/**
* Convert rates to the given time unit.
*
* @param rateUnit a unit of time
* @return {@code this}
*/
public Builder convertRatesTo(TimeUnit rateUnit) {
this.rateUnit = rateUnit;
return this;
}
/**
* Convert durations to the given time unit.
*
* @param durationUnit a unit of time
* @return {@code this}
*/
public Builder convertDurationsTo(TimeUnit durationUnit) {
this.durationUnit = durationUnit;
return this;
}
/**
* Only report metrics which match the given filter.
*
* @param filter a {@link MetricFilter}
* @return {@code this}
*/
public Builder filter(MetricFilter filter) {
this.filter = filter;
return this;
}
/**
* Only report metrics that have changed.
*
* @param skipIdleMetrics true/false for skipping metrics not reported
* @return {@code this}
*/
public Builder skipIdleMetrics(boolean skipIdleMetrics) {
this.skipIdleMetrics = skipIdleMetrics;
return this;
}
public APMAgentReporter build(final TimeSeriesDbSender influxDb) {
return new APMAgentReporter(registry, influxDb, tags, rateUnit, durationUnit, filter, skipIdleMetrics);
}
}
private static final Logger logger = LoggerFactory.getLogger(APMAgentReporter.class);
private static final String COUNT = ".count";
private final TimeSeriesDbSender influxDb;
private final boolean skipIdleMetrics;
private final Map<MetricName, Long> previousValues;
private APMAgentReporter(final MetricRegistry registry, final TimeSeriesDbSender influxDb, final Map<String, String> tags,
final TimeUnit rateUnit, final TimeUnit durationUnit, final MetricFilter filter, final boolean skipIdleMetrics) {
super(registry, "apm-reporter", filter, rateUnit, durationUnit);
this.influxDb = influxDb;
influxDb.setTags(tags);
this.skipIdleMetrics = skipIdleMetrics;
this.previousValues = new TreeMap<>();
}
public static Builder forRegistry(MetricRegistry registry) {
return new Builder(registry);
}
@Override
public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters,
final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) {
final long now = System.currentTimeMillis();
if(logger.isDebugEnabled()) logger.debug("APMAgentReporter report is called with counter size {}", counters.size());
try {
influxDb.flush();
for (Map.Entry<MetricName, Gauge> entry : gauges.entrySet()) {
reportGauge(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Counter> entry : counters.entrySet()) {
reportCounter(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Histogram> entry : histograms.entrySet()) {
reportHistogram(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Meter> entry : meters.entrySet()) {
reportMeter(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Timer> entry : timers.entrySet()) {
reportTimer(entry.getKey(), entry.getValue(), now);
}
if (influxDb.hasSeriesData()) {
influxDb.writeData();
}
// reset counters
for (Map.Entry<MetricName, Counter> entry : counters.entrySet()) {
Counter counter = entry.getValue();
long count = counter.getCount();
counter.dec(count);
}
} catch (Exception e) {
logger.error("Unable to report to APM Agent. Discarding data.", e);
}
}
private void reportTimer(MetricName name, Timer timer, long now) {
if (canSkipMetric(name, timer)) {
return;
}
final Snapshot snapshot = timer.getSnapshot();
Map<String, String> apiTags = new HashMap<>(name.getTags());
String apiName = apiTags.remove("api");
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + ".min", apiTags, now, format(convertDuration(snapshot.getMin()))));
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + ".max", apiTags, now, format(convertDuration(snapshot.getMax()))));
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + ".mean", apiTags, now, format(convertDuration(snapshot.getMean()))));
}
private void reportHistogram(MetricName name, Histogram histogram, long now) {
if (canSkipMetric(name, histogram)) {
return;
}
final Snapshot snapshot = histogram.getSnapshot();
Map<String, String> apiTags = new HashMap<>(name.getTags());
String apiName = apiTags.remove("api");
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + COUNT, apiTags, now, format(histogram.getCount())));
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + ".min", apiTags, now, format(snapshot.getMin())));
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + ".max", apiTags, now, format(snapshot.getMax())));
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + ".mean", apiTags, now, format(snapshot.getMean())));
}
private void reportCounter(MetricName name, Counter counter, long now) {<FILL_FUNCTION_BODY>
|
Map<String, String> apiTags = new HashMap<>(name.getTags());
String apiName = apiTags.remove("api");
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey() + COUNT, apiTags, now, format(counter.getCount())));
| 1,860
| 81
| 1,941
|
<methods>public void close() ,public void report() ,public abstract void report(SortedMap<io.dropwizard.metrics.MetricName,Gauge#RAW>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Counter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Histogram>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Meter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Timer>) ,public void start(long, java.util.concurrent.TimeUnit) ,public void stop() <variables>private static final java.util.concurrent.atomic.AtomicInteger FACTORY_ID,private static final Logger LOG,private final non-sealed double durationFactor,private final non-sealed java.lang.String durationUnit,private final non-sealed java.util.concurrent.ScheduledExecutorService executor,private final non-sealed io.dropwizard.metrics.MetricFilter filter,private final non-sealed double rateFactor,private final non-sealed java.lang.String rateUnit,private final non-sealed io.dropwizard.metrics.MetricRegistry registry
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/com/networknt/metrics/JVMMetricsDbReporter.java
|
JVMMetricsDbReporter
|
report
|
class JVMMetricsDbReporter extends ScheduledReporter {
private static final Logger logger = LoggerFactory.getLogger(JVMMetricsDbReporter.class);
private final TimeSeriesDbSender influxDb;
private final MetricRegistry registry;
private final Map<String, String> tags;
public JVMMetricsDbReporter(final MetricRegistry registry, final TimeSeriesDbSender influxDb, String name, MetricFilter filter, TimeUnit rateUnit,
TimeUnit durationUnit, Map<String, String> tags) {
super(registry, name, filter, rateUnit, durationUnit);
this.influxDb = influxDb;
this.registry = registry;
this.tags = tags;
}
@Override
public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters,
final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) {<FILL_FUNCTION_BODY>}
private void reportGauge(MetricName name, Gauge<?> gauge, long now) {
final String value = format(gauge.getValue());
if(value != null) {
Map<String, String> apiTags = new HashMap<>(name.getTags());
String apiName = apiTags.remove("api");
Map<String, String> clientTags = new HashMap<>(name.getTags());
String clientId = clientTags.remove("clientId");
influxDb.appendPoints(new InfluxDbPoint(apiName + "." + name.getKey(), apiTags, now, value));
if(clientId != null) {
influxDb.appendPoints(new InfluxDbPoint(clientId + "." + name.getKey(), clientTags, now, value));
}
}
}
private String format(Object o) {
if (o instanceof Float) {
return format(((Float) o).doubleValue());
} else if (o instanceof Double) {
return format(((Double) o).doubleValue());
} else if (o instanceof Byte) {
return format(((Byte) o).longValue());
} else if (o instanceof Short) {
return format(((Short) o).longValue());
} else if (o instanceof Integer) {
return format(((Integer) o).longValue());
} else if (o instanceof Long) {
return format(((Long) o).longValue());
}
return null;
}
private String format(long n) {
return Long.toString(n);
}
private String format(double v) {
// the Carbon plaintext format is pretty underspecified, but it seems like it just wants
// US-formatted digits
return String.format(Locale.US, "%2.4f", v);
}
}
|
final long now = System.currentTimeMillis();
JVMMetricsUtil.trackAllJVMMetrics(registry, tags);
if(logger.isDebugEnabled()) logger.debug("JVMMetricsDbReporter report is called with counter size " + counters.size());
try {
influxDb.flush();
//Get gauges again from registry, since the gauges provided in the argument is OUTDATED (Previous collection)
for (Map.Entry<MetricName, Gauge> entry : registry.getGauges().entrySet()) {
reportGauge(entry.getKey(), entry.getValue(), now);
}
if (influxDb.hasSeriesData()) {
influxDb.writeData();
}
} catch (Exception e) {
logger.error("Unable to report to the time series database. Discarding data.", e);
}
| 741
| 224
| 965
|
<methods>public void close() ,public void report() ,public abstract void report(SortedMap<io.dropwizard.metrics.MetricName,Gauge#RAW>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Counter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Histogram>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Meter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Timer>) ,public void start(long, java.util.concurrent.TimeUnit) ,public void stop() <variables>private static final java.util.concurrent.atomic.AtomicInteger FACTORY_ID,private static final Logger LOG,private final non-sealed double durationFactor,private final non-sealed java.lang.String durationUnit,private final non-sealed java.util.concurrent.ScheduledExecutorService executor,private final non-sealed io.dropwizard.metrics.MetricFilter filter,private final non-sealed double rateFactor,private final non-sealed java.lang.String rateUnit,private final non-sealed io.dropwizard.metrics.MetricRegistry registry
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/com/networknt/metrics/JVMMetricsUtil.java
|
JVMMetricsUtil
|
trackAllJVMMetrics
|
class JVMMetricsUtil {
public static void trackAllJVMMetrics(final MetricRegistry registry, final Map<String, String> commonTags) {<FILL_FUNCTION_BODY>}
private static void track(String name, MemoryUsage m, final MetricRegistry registry, final Map<String, String> commonTags) {
MetricName mName = MetricRegistry.name("jvm", name).tagged(commonTags);
registry.remove(mName.resolve("used"));
registry.getOrAdd(mName.resolve("used"), createGaugeMetricBuilder(m.getUsed()));
registry.remove(mName.resolve("init"));
registry.getOrAdd(mName.resolve("init"), createGaugeMetricBuilder(m.getInit()));
registry.remove(mName.resolve("max"));
registry.getOrAdd(mName.resolve("max"), createGaugeMetricBuilder(m.getMax()));
registry.remove(mName.resolve("committed"));
registry.getOrAdd(mName.resolve("committed"), createGaugeMetricBuilder(m.getCommitted()));
}
private static void track(String name, Long value, final MetricRegistry registry, final Map<String, String> commonTags) {
MetricName mName = MetricRegistry.name("jvm", name).tagged(commonTags);
registry.remove(mName);
registry.getOrAdd(mName, createGaugeMetricBuilder(value));
}
private static void track(String name, Double value, final MetricRegistry registry, final Map<String, String> commonTags) {
MetricName mName = MetricRegistry.name("jvm", name).tagged(commonTags);
registry.remove(mName);
registry.getOrAdd(mName, createGaugeMetricBuilder(value));
}
private static void track(String name, int value, final MetricRegistry registry, final Map<String, String> commonTags) {
MetricName mName = MetricRegistry.name("jvm", name).tagged(commonTags);
registry.remove(mName);
registry.getOrAdd(mName, createGaugeMetricBuilder(value));
}
private static MetricBuilder<Gauge<Long>> createGaugeMetricBuilder(long value){
return new MetricBuilder<Gauge<Long>>() {
@Override
public Gauge<Long> newMetric() {
return () -> Long.valueOf(value);
}
@Override
public boolean isInstance(Metric metric) {
return Gauge.class.isInstance(metric);
}
};
}
private static MetricBuilder<Gauge<Double>> createGaugeMetricBuilder(Double value){
return new MetricBuilder<Gauge<Double>>() {
@Override
public Gauge<Double> newMetric() {
return () -> value;
}
@Override
public boolean isInstance(Metric metric) {
return Gauge.class.isInstance(metric);
}
};
}
private static MetricBuilder<Gauge<Integer>> createGaugeMetricBuilder(int value){
return new MetricBuilder<Gauge<Integer>>() {
@Override
public Gauge<Integer> newMetric() {
return () -> Integer.valueOf(value);
}
@Override
public boolean isInstance(Metric metric) {
return Gauge.class.isInstance(metric);
}
};
}
}
|
//JVM Metrics
MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
track("mem.heap_mem", memBean.getHeapMemoryUsage(), registry, commonTags);
track("mem.nonheap_mem", memBean.getNonHeapMemoryUsage(), registry, commonTags);
double hmu = ((Long)memBean.getHeapMemoryUsage().getUsed()).doubleValue();
double hmc = ((Long)memBean.getHeapMemoryUsage().getMax()).doubleValue();
if (hmc == -1) {
hmc = ((Long)memBean.getHeapMemoryUsage().getCommitted()).doubleValue();
}
double nhmu = ((Long)memBean.getNonHeapMemoryUsage().getUsed()).doubleValue();
double nhmc = ((Long)memBean.getNonHeapMemoryUsage().getMax()).doubleValue();
if (nhmc == -1) {
nhmc = ((Long)memBean.getNonHeapMemoryUsage().getCommitted()).doubleValue();
}
track("mem.heap_usage", hmu / hmc, registry, commonTags);
track("mem.nonheap_usage", nhmu / nhmc, registry, commonTags);
MBeanServer beans = ManagementFactory.getPlatformMBeanServer();
try {
ObjectName os = new ObjectName("java.lang:type=OperatingSystem");
Double sysCpuLoad = (Double)beans.getAttribute(os, "SystemCpuLoad");
Double processCpuLoad = (Double)beans.getAttribute(os, "ProcessCpuLoad");
double totalPMemory = ((Long)beans.getAttribute(os, "TotalPhysicalMemorySize")).doubleValue();
double freePMemory = ((Long)beans.getAttribute(os, "FreePhysicalMemorySize")).doubleValue();
track("os.sys_cpu_load", sysCpuLoad, registry, commonTags);
track("os.process_cpu_load", processCpuLoad, registry, commonTags);
track("os.mem_usage", (totalPMemory-freePMemory)/totalPMemory, registry, commonTags);
} catch (InstanceNotFoundException | AttributeNotFoundException | MalformedObjectNameException
| ReflectionException | MBeanException e) {
e.printStackTrace();
}
track("thread.count", ManagementFactory.getThreadMXBean().getThreadCount(), registry, commonTags);
| 891
| 621
| 1,512
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/com/networknt/metrics/MetricsConfig.java
|
MetricsConfig
|
setConfigData
|
class MetricsConfig {
public static final String CONFIG_NAME = "metrics";
private static final String ENABLED = "enabled";
private static final String ENABLED_JVM_MONITOR = "enableJVMMonitor";
private static final String SERVER_PROTOCOL = "serverProtocol";
private static final String SERVER_HOST = "serverHost";
private static final String SERVER_PORT = "serverPort";
private static final String SERVER_PATH = "serverPath";
private static final String SERVER_NAME = "serverName";
private static final String SERVER_USER = "serverUser";
private static final String SERVER_PASS = "serverPass";
private static final String REPORT_IN_MINUTES = "reportInMinutes";
private static final String PRODUCT_NAME = "productName";
private static final String SEND_SCOPE_CLIENT_ID = "sendScopeClientId";
private static final String SEND_CALLER_ID = "sendCallerId";
private static final String SEND_ISSUER = "sendIssuer";
private static final String ISSUER_REGEX = "issuerRegex";
boolean enabled;
boolean enableJVMMonitor;
String serverProtocol;
String serverHost;
int serverPort;
String serverPath;
String serverName;
String serverUser;
String serverPass;
int reportInMinutes;
String productName;
boolean sendScopeClientId;
boolean sendCallerId;
boolean sendIssuer;
String issuerRegex;
private Map<String, Object> mappedConfig;
private final Config config;
private MetricsConfig() {
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 MetricsConfig(String configName) {
config = Config.getInstance();
mappedConfig = config.getJsonMapConfigNoCache(configName);
setConfigData();
}
public static MetricsConfig load() {
return new MetricsConfig();
}
public static MetricsConfig load(String configName) {
return new MetricsConfig(configName);
}
public void reload() {
mappedConfig = config.getJsonMapConfigNoCache(CONFIG_NAME);
setConfigData();
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnableJVMMonitor() {
return enableJVMMonitor;
}
public void setEnableJVMMonitor(boolean enableJVMMonitor) {
this.enableJVMMonitor = enableJVMMonitor;
}
public String getServerHost() {
return serverHost;
}
public String getServerProtocol() {
return serverProtocol;
}
public void setServerProtocol(String serverProtocol) {
this.serverProtocol = serverProtocol;
}
public void setServerHost(String serverHost) {
this.serverHost = serverHost;
}
public int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
public int getReportInMinutes() {
return reportInMinutes;
}
public void setReportInMinutes(int reportInMinutes) {
this.reportInMinutes = reportInMinutes;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getServerName() { return serverName; }
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getServerUser() {
return serverUser;
}
public void setServerUser(String serverUser) {
this.serverUser = serverUser;
}
public String getServerPass() {
return serverPass;
}
public void setServerPass(String serverPass) {
this.serverPass = serverPass;
}
public String getServerPath() {
return serverPath;
}
public void setServerPath(String serverPath) {
this.serverPath = serverPath;
}
public boolean isSendScopeClientId() {
return sendScopeClientId;
}
public void setSendScopeClientId(boolean sendScopeClientId) {
this.sendScopeClientId = sendScopeClientId;
}
public boolean isSendCallerId() {
return sendCallerId;
}
public void setSendCallerId(boolean sendCallerId) {
this.sendCallerId = sendCallerId;
}
public boolean isSendIssuer() {
return sendIssuer;
}
public void setSendIssuer(boolean sendIssuer) {
this.sendIssuer = sendIssuer;
}
public String getIssuerRegex() {
return issuerRegex;
}
public void setIssuerRegex(String issuerRegex) {
this.issuerRegex = issuerRegex;
}
Map<String, Object> getMappedConfig() {
return mappedConfig;
}
private void setConfigData() {<FILL_FUNCTION_BODY>}
}
|
Object object = getMappedConfig().get(ENABLED);
if(object != null) enabled = Config.loadBooleanValue(ENABLED, object);
object = getMappedConfig().get(ENABLED_JVM_MONITOR);
if(object != null) enableJVMMonitor = Config.loadBooleanValue(ENABLED_JVM_MONITOR, object);
object = mappedConfig.get(SERVER_PROTOCOL);
if (object != null) setServerProtocol((String) object);;
object = mappedConfig.get(SERVER_HOST);
if (object != null) serverHost = (String) object;
object = mappedConfig.get(SERVER_PORT);
if (object != null) serverPort = Config.loadIntegerValue(SERVER_PORT, object);
object = getMappedConfig().get(SERVER_PATH);
if(object != null) serverPath = (String) object;
object = getMappedConfig().get(SERVER_NAME);
if(object != null) serverName = (String) object;
object = getMappedConfig().get(SERVER_USER);
if(object != null) serverUser = (String) object;
object = getMappedConfig().get(SERVER_PASS);
if(object != null) serverPass = (String) object;
object = getMappedConfig().get(REPORT_IN_MINUTES);
if(object != null) reportInMinutes = Config.loadIntegerValue(REPORT_IN_MINUTES, object);
object = getMappedConfig().get(PRODUCT_NAME);
if(object != null) productName = (String) object;
object = getMappedConfig().get(SEND_SCOPE_CLIENT_ID);
if(object != null) sendScopeClientId = Config.loadBooleanValue(SEND_SCOPE_CLIENT_ID, object);
object = getMappedConfig().get(SEND_CALLER_ID);
if(object != null) sendCallerId = Config.loadBooleanValue(SEND_CALLER_ID, object);
object = getMappedConfig().get(SEND_ISSUER);
if(object != null) sendIssuer = Config.loadBooleanValue(SEND_ISSUER, object);
object = getMappedConfig().get(ISSUER_REGEX);
if(object != null) issuerRegex = (String) object;
| 1,409
| 601
| 2,010
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/CachedGauge.java
|
CachedGauge
|
getValue
|
class CachedGauge<T> implements Gauge<T> {
private final Clock clock;
private final AtomicLong reloadAt;
private final long timeoutNS;
private volatile T value;
/**
* Creates a new cached gauge with the given timeout period.
*
* @param timeout the timeout
* @param timeoutUnit the unit of {@code timeout}
*/
protected CachedGauge(long timeout, TimeUnit timeoutUnit) {
this(Clock.defaultClock(), timeout, timeoutUnit);
}
/**
* Creates a new cached gauge with the given clock and timeout period.
*
* @param clock the clock used to calculate the timeout
* @param timeout the timeout
* @param timeoutUnit the unit of {@code timeout}
*/
protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) {
this.clock = clock;
this.reloadAt = new AtomicLong(0);
this.timeoutNS = timeoutUnit.toNanos(timeout);
}
/**
* Loads the value and returns it.
*
* @return the new value
*/
protected abstract T loadValue();
@Override
public T getValue() {<FILL_FUNCTION_BODY>}
private boolean shouldLoad() {
for (; ; ) {
final long time = clock.getTick();
final long current = reloadAt.get();
if (current > time) {
return false;
}
if (reloadAt.compareAndSet(current, time + timeoutNS)) {
return true;
}
}
}
@Override
public String toString() {
return String.valueOf(this.getValue());
}
}
|
if (shouldLoad()) {
this.value = loadValue();
}
return value;
| 448
| 28
| 476
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/DefaultObjectNameFactory.java
|
DefaultObjectNameFactory
|
createName
|
class DefaultObjectNameFactory implements ObjectNameFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultObjectNameFactory.class);
@Override
public ObjectName createName(String type, String domain, MetricName metricName) {<FILL_FUNCTION_BODY>}
}
|
String name = metricName.getKey();
try {
ObjectName objectName = new ObjectName(domain, "name", name);
if (objectName.isPattern()) {
objectName = new ObjectName(domain, "name", ObjectName.quote(name));
}
return objectName;
} catch (MalformedObjectNameException e) {
try {
return new ObjectName(domain, "name", ObjectName.quote(name));
} catch (MalformedObjectNameException e1) {
LOGGER.warn("Unable to register {} {}", type, name, e1);
throw new RuntimeException(e1);
}
}
| 74
| 170
| 244
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/EWMA.java
|
EWMA
|
tick
|
class EWMA {
private static final int INTERVAL = 5;
private static final double SECONDS_PER_MINUTE = 60.0;
private static final int ONE_MINUTE = 1;
private static final int FIVE_MINUTES = 5;
private static final int FIFTEEN_MINUTES = 15;
private static final double M1_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / ONE_MINUTE);
private static final double M5_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIVE_MINUTES);
private static final double M15_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIFTEEN_MINUTES);
private volatile boolean initialized = false;
private volatile double rate = 0.0;
private final LongAdder uncounted = new LongAdder();
private final double alpha, interval;
/**
* Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects
* to be ticked every 5 seconds.
*
* @return a one-minute EWMA
*/
public static EWMA oneMinuteEWMA() {
return new EWMA(M1_ALPHA, INTERVAL, TimeUnit.SECONDS);
}
/**
* Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects
* to be ticked every 5 seconds.
*
* @return a five-minute EWMA
*/
public static EWMA fiveMinuteEWMA() {
return new EWMA(M5_ALPHA, INTERVAL, TimeUnit.SECONDS);
}
/**
* Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which
* expects to be ticked every 5 seconds.
*
* @return a fifteen-minute EWMA
*/
public static EWMA fifteenMinuteEWMA() {
return new EWMA(M15_ALPHA, INTERVAL, TimeUnit.SECONDS);
}
/**
* Create a new EWMA with a specific smoothing constant.
*
* @param alpha the smoothing constant
* @param interval the expected tick interval
* @param intervalUnit the time unit of the tick interval
*/
public EWMA(double alpha, long interval, TimeUnit intervalUnit) {
this.interval = intervalUnit.toNanos(interval);
this.alpha = alpha;
}
/**
* Update the moving average with a new value.
*
* @param n the new value
*/
public void update(long n) {
uncounted.add(n);
}
/**
* Mark the passage of time and decay the current rate accordingly.
*/
public synchronized void tick() {<FILL_FUNCTION_BODY>}
/**
* Returns the rate in the given units of time.
*
* @param rateUnit the unit of time
* @return the rate
*/
public double getRate(TimeUnit rateUnit) {
return rate * rateUnit.toNanos(1);
}
}
|
final long count = uncounted.sumThenReset();
final double instantRate = count / interval;
if (initialized) {
rate += (alpha * (instantRate - rate));
} else {
rate = instantRate;
initialized = true;
}
| 828
| 71
| 899
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/ExponentiallyDecayingReservoir.java
|
ExponentiallyDecayingReservoir
|
getSnapshot
|
class ExponentiallyDecayingReservoir implements Reservoir {
private static final int DEFAULT_SIZE = 1028;
private static final double DEFAULT_ALPHA = 0.015;
private static final long RESCALE_THRESHOLD = TimeUnit.HOURS.toNanos(1);
private final ConcurrentSkipListMap<Double, WeightedSample> values;
private final ReentrantReadWriteLock lock;
private final double alpha;
private final int size;
private final AtomicLong count;
private volatile long startTime;
private final AtomicLong nextScaleTime;
private final Clock clock;
/**
* Creates a new {@link ExponentiallyDecayingReservoir} of 1028 elements, which offers a 99.9%
* confidence level with a 5% margin of error assuming a normal distribution, and an alpha
* factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements.
*/
public ExponentiallyDecayingReservoir() {
this(DEFAULT_SIZE, DEFAULT_ALPHA);
}
/**
* Creates a new {@link ExponentiallyDecayingReservoir}.
*
* @param size the number of samples to keep in the sampling reservoir
* @param alpha the exponential decay factor; the higher this is, the more biased the reservoir
* will be towards newer values
*/
public ExponentiallyDecayingReservoir(int size, double alpha) {
this(size, alpha, Clock.defaultClock());
}
/**
* Creates a new {@link ExponentiallyDecayingReservoir}.
*
* @param size the number of samples to keep in the sampling reservoir
* @param alpha the exponential decay factor; the higher this is, the more biased the reservoir
* will be towards newer values
* @param clock the clock used to timestamp samples and track rescaling
*/
public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) {
this.values = new ConcurrentSkipListMap<>();
this.lock = new ReentrantReadWriteLock();
this.alpha = alpha;
this.size = size;
this.clock = clock;
this.count = new AtomicLong(0);
this.startTime = currentTimeInSeconds();
this.nextScaleTime = new AtomicLong(clock.getTick() + RESCALE_THRESHOLD);
}
@Override
public int size() {
return (int) min(size, count.get());
}
@Override
public void update(long value) {
update(value, currentTimeInSeconds());
}
/**
* Adds an old value with a fixed timestamp to the reservoir.
*
* @param value the value to be added
* @param timestamp the epoch timestamp of {@code value} in seconds
*/
public void update(long value, long timestamp) {
rescaleIfNeeded();
lockForRegularUsage();
try {
final double itemWeight = weight(timestamp - startTime);
final WeightedSample sample = new WeightedSample(value, itemWeight);
final double priority = itemWeight / (1.0d - ThreadLocalRandom.current().nextDouble());
final long newCount = count.incrementAndGet();
if (newCount <= size) {
values.put(priority, sample);
} else {
Double first = values.firstKey();
if (first < priority && values.putIfAbsent(priority, sample) == null) {
// ensure we always remove an item
while (values.remove(first) == null) {
first = values.firstKey();
}
}
}
} finally {
unlockForRegularUsage();
}
}
private void rescaleIfNeeded() {
final long now = clock.getTick();
final long next = nextScaleTime.get();
if (now >= next) {
rescale(now, next);
}
}
@Override
public Snapshot getSnapshot() {<FILL_FUNCTION_BODY>}
private long currentTimeInSeconds() {
return TimeUnit.MILLISECONDS.toSeconds(clock.getTime());
}
private double weight(long t) {
return exp(alpha * t);
}
/* "A common feature of the above techniques—indeed, the key technique that
* allows us to track the decayed weights efficiently—is that they maintain
* counts and other quantities based on g(ti − L), and only scale by g(t − L)
* at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero
* and one, the intermediate values of g(ti − L) could become very large. For
* polynomial functions, these values should not grow too large, and should be
* effectively represented in practice by floating point values without loss of
* precision. For exponential functions, these values could grow quite large as
* new values of (ti − L) become large, and potentially exceed the capacity of
* common floating point types. However, since the values stored by the
* algorithms are linear combinations of g values (scaled sums), they can be
* rescaled relative to a new landmark. That is, by the analysis of exponential
* decay in Section III-A, the choice of L does not affect the final result. We
* can therefore multiply each value based on L by a factor of exp(−α(L′ − L)),
* and obtain the correct value as if we had instead computed relative to a new
* landmark L′ (and then use this new L′ at query time). This can be done with
* a linear pass over whatever data structure is being used."
*/
private void rescale(long now, long next) {
if (nextScaleTime.compareAndSet(next, now + RESCALE_THRESHOLD)) {
lockForRescale();
try {
final long oldStartTime = startTime;
this.startTime = currentTimeInSeconds();
final double scalingFactor = exp(-alpha * (startTime - oldStartTime));
final ArrayList<Double> keys = new ArrayList<>(values.keySet());
for (Double key : keys) {
final WeightedSample sample = values.remove(key);
final WeightedSample newSample = new WeightedSample(sample.value, sample.weight * scalingFactor);
values.put(key * scalingFactor, newSample);
}
// make sure the counter is in sync with the number of stored samples.
count.set(values.size());
} finally {
unlockForRescale();
}
}
}
private void unlockForRescale() {
lock.writeLock().unlock();
}
private void lockForRescale() {
lock.writeLock().lock();
}
private void lockForRegularUsage() {
lock.readLock().lock();
}
private void unlockForRegularUsage() {
lock.readLock().unlock();
}
}
|
lockForRegularUsage();
try {
return new WeightedSnapshot(values.values());
} finally {
unlockForRegularUsage();
}
| 1,788
| 43
| 1,831
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/HdrHistogramReservoir.java
|
HdrHistogramReservoir
|
size
|
class HdrHistogramReservoir implements Reservoir {
private final Recorder recorder;
@GuardedBy("this")
private final Histogram runningTotals;
@GuardedBy("this")
@Nonnull
private Histogram intervalHistogram;
/**
* Create a reservoir with a default recorder. This recorder should be suitable for most usage.
*/
public HdrHistogramReservoir() {
this(new Recorder(2));
}
/**
* Create a reservoir with a user-specified recorder.
*
* @param recorder Recorder to use
*/
public HdrHistogramReservoir(Recorder recorder) {
this.recorder = recorder;
/*
* Start by flipping the recorder's interval histogram.
* - it starts our counting at zero. Arguably this might be a bad thing if you wanted to feed in
* a recorder that already had some measurements? But that seems crazy.
* - intervalHistogram can be nonnull.
* - it lets us figure out the number of significant digits to use in runningTotals.
*/
intervalHistogram = recorder.getIntervalHistogram();
runningTotals = new Histogram(intervalHistogram.getNumberOfSignificantValueDigits());
}
@Override
public int size() {<FILL_FUNCTION_BODY>}
@Override
public void update(long value) {
recorder.recordValue(value);
}
/**
* @return the data accumulated since the reservoir was created
*/
@Override
public Snapshot getSnapshot() {
return new HistogramSnapshot(updateRunningTotals());
}
/**
* @return a copy of the accumulated state since the reservoir was created
*/
@Nonnull
private synchronized Histogram updateRunningTotals() {
intervalHistogram = recorder.getIntervalHistogram(intervalHistogram);
runningTotals.add(intervalHistogram);
return runningTotals.copy();
}
}
|
// This appears to be infrequently called, so not keeping a separate counter just for this.
return getSnapshot().size();
| 518
| 33
| 551
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/HdrHistogramResetOnSnapshotReservoir.java
|
HdrHistogramResetOnSnapshotReservoir
|
size
|
class HdrHistogramResetOnSnapshotReservoir implements Reservoir {
private final Recorder recorder;
@GuardedBy("this")
@Nonnull
private Histogram intervalHistogram;
/**
* Create a reservoir with a default recorder. This recorder should be suitable for most usage.
*/
public HdrHistogramResetOnSnapshotReservoir() {
this(new Recorder(2));
}
/**
* Create a reservoir with a user-specified recorder.
*
* @param recorder Recorder to use
*/
public HdrHistogramResetOnSnapshotReservoir(Recorder recorder) {
this.recorder = recorder;
/*
* Start by flipping the recorder's interval histogram.
* - it starts our counting at zero. Arguably this might be a bad thing if you wanted to feed in
* a recorder that already had some measurements? But that seems crazy.
* - intervalHistogram can be nonnull.
*/
intervalHistogram = recorder.getIntervalHistogram();
}
@Override
public int size() {<FILL_FUNCTION_BODY>}
@Override
public void update(long value) {
recorder.recordValue(value);
}
/**
* @return the data since the last snapshot was taken
*/
@Override
public Snapshot getSnapshot() {
return new HistogramSnapshot(getDataSinceLastSnapshotAndReset());
}
/**
* @return a copy of the accumulated state since the reservoir last had a snapshot
*/
@Nonnull
private synchronized Histogram getDataSinceLastSnapshotAndReset() {
intervalHistogram = recorder.getIntervalHistogram(intervalHistogram);
return intervalHistogram.copy();
}
}
|
// This appears to be infrequently called, so not keeping a separate counter just for this.
return getSnapshot().size();
| 456
| 33
| 489
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/Histogram.java
|
Histogram
|
toString
|
class Histogram implements Metric, Sampling, Counting {
private final Reservoir reservoir;
private final LongAdder count;
/**
* Creates a new {@link Histogram} with the given reservoir.
*
* @param reservoir the reservoir to create a histogram from
*/
public Histogram(Reservoir reservoir) {
this.reservoir = reservoir;
this.count = new LongAdder();
}
/**
* Adds a recorded value.
*
* @param value the length of the value
*/
public void update(int value) {
update((long) value);
}
/**
* Adds a recorded value.
*
* @param value the length of the value
*/
public void update(long value) {
count.increment();
reservoir.update(value);
}
/**
* Returns the number of values recorded.
*
* @return the number of values recorded
*/
@Override
public long getCount() {
return count.sum();
}
@Override
public Snapshot getSnapshot() {
return reservoir.getSnapshot();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final ByteArrayOutputStream out = new ByteArrayOutputStream();
this.getSnapshot().dump(out);
try {
return out.toString(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
return super.toString();
}
| 331
| 70
| 401
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/HistogramSnapshot.java
|
HistogramSnapshot
|
getValues
|
class HistogramSnapshot extends Snapshot {
private static final Logger logger = LoggerFactory.getLogger(HistogramSnapshot.class);
private final Histogram histogram;
HistogramSnapshot(@Nonnull Histogram histogram) {
this.histogram = histogram;
}
@Override
public double getValue(double quantile) {
return histogram.getValueAtPercentile(quantile * 100.0);
}
@Override
public long[] getValues() {<FILL_FUNCTION_BODY>}
@Override
public int size() {
return (int) histogram.getTotalCount();
}
@Override
public long getMax() {
return histogram.getMaxValue();
}
@Override
public double getMean() {
return histogram.getMean();
}
@Override
public long getMin() {
return histogram.getMinValue();
}
@Override
public double getStdDev() {
return histogram.getStdDeviation();
}
@Override
public void dump(OutputStream output) {
PrintWriter p = null;
try {
p = new PrintWriter(new OutputStreamWriter(output, UTF_8));
for (HistogramIterationValue value : histogram.recordedValues()) {
for (int j = 0; j < value.getCountAddedInThisIterationStep(); j++) {
p.printf("%d%n", value.getValueIteratedTo());
}
}
} catch (Exception e) {
if(p != null) p.close();
logger.error("Exception:", e);
}
}
}
|
long[] vals = new long[(int) histogram.getTotalCount()];
int i = 0;
for (HistogramIterationValue value : histogram.recordedValues()) {
long val = value.getValueIteratedTo();
for (int j = 0; j < value.getCountAddedInThisIterationStep(); j++) {
vals[i] = val;
i++;
}
}
if (i != vals.length) {
throw new IllegalStateException(
"Total count was " + histogram.getTotalCount() + " but iterating values produced " + vals.length);
}
return vals;
| 430
| 172
| 602
|
<methods>public non-sealed void <init>() ,public abstract void dump(java.io.OutputStream) ,public double get75thPercentile() ,public double get95thPercentile() ,public double get98thPercentile() ,public double get999thPercentile() ,public double get99thPercentile() ,public abstract long getMax() ,public abstract double getMean() ,public double getMedian() ,public abstract long getMin() ,public abstract double getStdDev() ,public abstract double getValue(double) ,public abstract long[] getValues() ,public abstract int size() <variables>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/InstrumentedExecutorService.java
|
InstrumentedExecutorService
|
submit
|
class InstrumentedExecutorService implements ExecutorService {
private static final AtomicLong nameCounter = new AtomicLong();
private final ExecutorService delegate;
private final Meter submitted;
private final Counter running;
private final Meter completed;
private final Timer duration;
private final Meter rejected;
/**
* Wraps an {@link ExecutorService} uses an auto-generated default name.
*
* @param delegate {@link ExecutorService} to wrap.
* @param registry {@link MetricRegistry} that will contain the metrics.
*/
public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) {
this(delegate, registry, "instrumented-delegate-" + nameCounter.incrementAndGet());
}
/**
* Wraps an {@link ExecutorService} with an explicit name.
*
* @param delegate {@link ExecutorService} to wrap.
* @param registry {@link MetricRegistry} that will contain the metrics.
* @param name name for this executor service.
*/
public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name) {
this.delegate = delegate;
this.submitted = registry.meter(MetricRegistry.name(name, "submitted"));
this.running = registry.counter(MetricRegistry.name(name, "running"));
this.completed = registry.meter(MetricRegistry.name(name, "completed"));
this.duration = registry.timer(MetricRegistry.name(name, "duration"));
this.rejected = registry.meter(MetricRegistry.name(name, "rejected"));
}
/**
* {@inheritDoc}
*/
@Override
public void execute(@Nonnull Runnable runnable) {
submitted.mark();
try {
delegate.execute(new InstrumentedRunnable(runnable));
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public Future<?> submit(@Nonnull Runnable runnable) {
submitted.mark();
try {
return delegate.submit(new InstrumentedRunnable(runnable));
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> Future<T> submit(@Nonnull Runnable runnable, T result) {
submitted.mark();
try {
return delegate.submit(new InstrumentedRunnable(runnable), result);
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> Future<T> submit(@Nonnull Callable<T> task) {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks) throws InterruptedException {
submitted.mark(tasks.size());
Collection<? extends Callable<T>> instrumented = instrument(tasks);
try {
return delegate.invokeAll(instrumented);
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> List<Future<T>> invokeAll(@Nonnull Collection<? extends Callable<T>> tasks, long timeout, @Nonnull TimeUnit unit) throws InterruptedException {
submitted.mark(tasks.size());
Collection<? extends Callable<T>> instrumented = instrument(tasks);
try {
return delegate.invokeAll(instrumented, timeout, unit);
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks) throws ExecutionException, InterruptedException {
submitted.mark(tasks.size());
Collection<? extends Callable<T>> instrumented = instrument(tasks);
try {
return delegate.invokeAny(instrumented);
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks, long timeout, @Nonnull TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
submitted.mark(tasks.size());
Collection<? extends Callable<T>> instrumented = instrument(tasks);
try {
return delegate.invokeAny(instrumented, timeout, unit);
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
}
private <T> Collection<? extends Callable<T>> instrument(Collection<? extends Callable<T>> tasks) {
final List<InstrumentedCallable<T>> instrumented = new ArrayList<>(tasks.size());
instrumented.addAll(tasks.stream().map((Function<Callable<T>, InstrumentedCallable<T>>) InstrumentedCallable::new).collect(Collectors.toList()));
return instrumented;
}
@Override
public void shutdown() {
delegate.shutdown();
}
@Nonnull
@Override
public List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
@Override
public boolean isShutdown() {
return delegate.isShutdown();
}
@Override
public boolean isTerminated() {
return delegate.isTerminated();
}
@Override
public boolean awaitTermination(long l, @Nonnull TimeUnit timeUnit) throws InterruptedException {
return delegate.awaitTermination(l, timeUnit);
}
private class InstrumentedRunnable implements Runnable {
private final Runnable task;
InstrumentedRunnable(Runnable task) {
this.task = task;
}
@Override
public void run() {
running.inc();
final Timer.Context context = duration.time();
try {
task.run();
} finally {
context.stop();
running.dec();
completed.mark();
}
}
}
private class InstrumentedCallable<T> implements Callable<T> {
private final Callable<T> callable;
InstrumentedCallable(Callable<T> callable) {
this.callable = callable;
}
@Override
public T call() throws Exception {
running.inc();
final Timer.Context context = duration.time();
try {
return callable.call();
} finally {
context.stop();
running.dec();
completed.mark();
}
}
}
}
|
submitted.mark();
try {
return delegate.submit(new InstrumentedCallable<>(task));
} catch (RejectedExecutionException e) {
rejected.mark();
throw e;
}
| 1,853
| 56
| 1,909
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/InstrumentedThreadFactory.java
|
InstrumentedThreadFactory
|
newThread
|
class InstrumentedThreadFactory implements ThreadFactory {
private static final AtomicLong nameCounter = new AtomicLong();
private final ThreadFactory delegate;
private final Meter created;
private final Counter running;
private final Meter terminated;
/**
* Wraps a {@link ThreadFactory}, uses a default auto-generated name.
*
* @param delegate {@link ThreadFactory} to wrap.
* @param registry {@link MetricRegistry} that will contain the metrics.
*/
public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) {
this(delegate, registry, "instrumented-thread-delegate-" + nameCounter.incrementAndGet());
}
/**
* Wraps a {@link ThreadFactory} with an explicit name.
*
* @param delegate {@link ThreadFactory} to wrap.
* @param registry {@link MetricRegistry} that will contain the metrics.
* @param name name for this delegate.
*/
public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) {
this.delegate = delegate;
this.created = registry.meter(MetricRegistry.name(name, "created"));
this.running = registry.counter(MetricRegistry.name(name, "running"));
this.terminated = registry.meter(MetricRegistry.name(name, "terminated"));
}
/**
* {@inheritDoc}
*/
@Override
public Thread newThread(@Nonnull Runnable runnable) {<FILL_FUNCTION_BODY>}
private class InstrumentedRunnable implements Runnable {
private final Runnable task;
InstrumentedRunnable(Runnable task) {
this.task = task;
}
@Override
public void run() {
running.inc();
try {
task.run();
} finally {
running.dec();
terminated.mark();
}
}
}
}
|
Runnable wrappedRunnable = new InstrumentedRunnable(runnable);
Thread thread = delegate.newThread(wrappedRunnable);
created.mark();
return thread;
| 502
| 52
| 554
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/JmxAttributeGauge.java
|
JmxAttributeGauge
|
getValue
|
class JmxAttributeGauge implements Gauge<Object> {
private final MBeanServerConnection mBeanServerConn;
private final ObjectName objectName;
private final String attributeName;
/**
* Creates a new JmxAttributeGauge.
*
* @param objectName the name of the object
* @param attributeName the name of the object's attribute
*/
public JmxAttributeGauge(ObjectName objectName, String attributeName) {
this(ManagementFactory.getPlatformMBeanServer(), objectName, attributeName);
}
/**
* Creates a new JmxAttributeGauge.
*
* @param mBeanServerConn the {@link MBeanServerConnection}
* @param objectName the name of the object
* @param attributeName the name of the object's attribute
*/
public JmxAttributeGauge(MBeanServerConnection mBeanServerConn, ObjectName objectName, String attributeName) {
this.mBeanServerConn = mBeanServerConn;
this.objectName = objectName;
this.attributeName = attributeName;
}
@Override
public Object getValue() {<FILL_FUNCTION_BODY>}
private ObjectName getObjectName() throws IOException {
if (objectName.isPattern()) {
Set<ObjectName> foundNames = mBeanServerConn.queryNames(objectName, null);
if (foundNames.size() == 1) {
return foundNames.iterator().next();
}
}
return objectName;
}
}
|
try {
return mBeanServerConn.getAttribute(getObjectName(), attributeName);
} catch (IOException e) {
return null;
} catch (JMException e) {
return null;
}
| 389
| 59
| 448
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/JmxReporter.java
|
JmxListener
|
registerMBean
|
class JmxListener implements MetricRegistryListener {
private final String name;
private final MBeanServer mBeanServer;
private final MetricFilter filter;
private final MetricTimeUnits timeUnits;
private final Map<ObjectName, ObjectName> registered;
private final ObjectNameFactory objectNameFactory;
private JmxListener(MBeanServer mBeanServer, String name, MetricFilter filter, MetricTimeUnits timeUnits, ObjectNameFactory objectNameFactory) {
this.mBeanServer = mBeanServer;
this.name = name;
this.filter = filter;
this.timeUnits = timeUnits;
this.registered = new ConcurrentHashMap<>();
this.objectNameFactory = objectNameFactory;
}
private void registerMBean(Object mBean, ObjectName objectName) throws JMException {<FILL_FUNCTION_BODY>}
private void unregisterMBean(ObjectName originalObjectName) throws InstanceNotFoundException, MBeanRegistrationException {
ObjectName storedObjectName = registered.remove(originalObjectName);
if (storedObjectName != null) {
mBeanServer.unregisterMBean(storedObjectName);
} else {
mBeanServer.unregisterMBean(originalObjectName);
}
}
@Override
public void onGaugeAdded(MetricName name, Gauge<?> gauge) {
try {
if (filter.matches(name, gauge)) {
final ObjectName objectName = createName("gauges", name);
registerMBean(new JmxGauge(gauge, objectName), objectName);
}
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Unable to register gauge", e);
} catch (JMException e) {
LOGGER.warn("Unable to register gauge", e);
}
}
@Override
public void onGaugeRemoved(MetricName name) {
try {
final ObjectName objectName = createName("gauges", name);
unregisterMBean(objectName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("Unable to unregister gauge", e);
} catch (MBeanRegistrationException e) {
LOGGER.warn("Unable to unregister gauge", e);
}
}
@Override
public void onCounterAdded(MetricName name, Counter counter) {
try {
if (filter.matches(name, counter)) {
final ObjectName objectName = createName("counters", name);
registerMBean(new JmxCounter(counter, objectName), objectName);
}
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Unable to register counter", e);
} catch (JMException e) {
LOGGER.warn("Unable to register counter", e);
}
}
@Override
public void onCounterRemoved(MetricName name) {
try {
final ObjectName objectName = createName("counters", name);
unregisterMBean(objectName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("Unable to unregister counter", e);
} catch (MBeanRegistrationException e) {
LOGGER.warn("Unable to unregister counter", e);
}
}
@Override
public void onHistogramAdded(MetricName name, Histogram histogram) {
try {
if (filter.matches(name, histogram)) {
final ObjectName objectName = createName("histograms", name);
registerMBean(new JmxHistogram(histogram, objectName), objectName);
}
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Unable to register histogram", e);
} catch (JMException e) {
LOGGER.warn("Unable to register histogram", e);
}
}
@Override
public void onHistogramRemoved(MetricName name) {
try {
final ObjectName objectName = createName("histograms", name);
unregisterMBean(objectName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("Unable to unregister histogram", e);
} catch (MBeanRegistrationException e) {
LOGGER.warn("Unable to unregister histogram", e);
}
}
@Override
public void onMeterAdded(MetricName name, Meter meter) {
try {
if (filter.matches(name, meter)) {
final ObjectName objectName = createName("meters", name);
registerMBean(new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName);
}
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Unable to register meter", e);
} catch (JMException e) {
LOGGER.warn("Unable to register meter", e);
}
}
@Override
public void onMeterRemoved(MetricName name) {
try {
final ObjectName objectName = createName("meters", name);
unregisterMBean(objectName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("Unable to unregister meter", e);
} catch (MBeanRegistrationException e) {
LOGGER.warn("Unable to unregister meter", e);
}
}
@Override
public void onTimerAdded(MetricName name, Timer timer) {
try {
if (filter.matches(name, timer)) {
final ObjectName objectName = createName("timers", name);
registerMBean(new JmxTimer(timer, objectName, timeUnits.rateFor(name.getKey()), timeUnits.durationFor(name.getKey())), objectName);
}
} catch (InstanceAlreadyExistsException e) {
LOGGER.debug("Unable to register timer", e);
} catch (JMException e) {
LOGGER.warn("Unable to register timer", e);
}
}
@Override
public void onTimerRemoved(MetricName name) {
try {
final ObjectName objectName = createName("timers", name);
unregisterMBean(objectName);
} catch (InstanceNotFoundException e) {
LOGGER.debug("Unable to unregister timer", e);
} catch (MBeanRegistrationException e) {
LOGGER.warn("Unable to unregister timer", e);
}
}
private ObjectName createName(String type, MetricName name) {
return objectNameFactory.createName(type, this.name, name);
}
void unregisterAll() {
for (ObjectName name : registered.keySet()) {
try {
unregisterMBean(name);
} catch (InstanceNotFoundException e) {
LOGGER.debug("Unable to unregister metric", e);
} catch (MBeanRegistrationException e) {
LOGGER.warn("Unable to unregister metric", e);
}
}
registered.clear();
}
}
|
ObjectInstance objectInstance = mBeanServer.registerMBean(mBean, objectName);
if (objectInstance != null) {
// the websphere mbeanserver rewrites the objectname to include
// cell, node & server info
// make sure we capture the new objectName for unregistration
registered.put(objectName, objectInstance.getObjectName());
} else {
registered.put(objectName, objectName);
}
| 1,785
| 113
| 1,898
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/JvmAttributeGaugeSet.java
|
JvmAttributeGaugeSet
|
getMetrics
|
class JvmAttributeGaugeSet implements MetricSet {
private final RuntimeMXBean runtime;
/**
* Creates a new set of gauges.
*/
public JvmAttributeGaugeSet() {
this(ManagementFactory.getRuntimeMXBean());
}
/**
* Creates a new set of gauges with the given {@link RuntimeMXBean}.
* @param runtime JVM management interface with access to system properties
*/
public JvmAttributeGaugeSet(RuntimeMXBean runtime) {
this.runtime = runtime;
}
@Override
public Map<MetricName, Metric> getMetrics() {<FILL_FUNCTION_BODY>}
}
|
final Map<MetricName, Metric> gauges = new HashMap<>();
gauges.put(MetricName.build("name"), (Gauge<String>) runtime::getName);
gauges.put(MetricName.build("vendor"), (Gauge<String>) () -> String.format(Locale.US,
"%s %s %s (%s)",
runtime.getVmVendor(),
runtime.getVmName(),
runtime.getVmVersion(),
runtime.getSpecVersion()));
gauges.put(MetricName.build("uptime"), (Gauge<Long>) runtime::getUptime);
return Collections.unmodifiableMap(gauges);
| 177
| 184
| 361
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/Meter.java
|
Meter
|
tickIfNecessary
|
class Meter implements Metered {
private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5);
private final EWMA m1Rate = EWMA.oneMinuteEWMA();
private final EWMA m5Rate = EWMA.fiveMinuteEWMA();
private final EWMA m15Rate = EWMA.fifteenMinuteEWMA();
private final LongAdder count = new LongAdder();
private final long startTime;
private final AtomicLong lastTick;
private final Clock clock;
/**
* Creates a new {@link Meter}.
*/
public Meter() {
this(Clock.defaultClock());
}
/**
* Creates a new {@link Meter}.
*
* @param clock the clock to use for the meter ticks
*/
public Meter(Clock clock) {
this.clock = clock;
this.startTime = this.clock.getTick();
this.lastTick = new AtomicLong(startTime);
}
/**
* Mark the occurrence of an event.
*/
public void mark() {
mark(1);
}
/**
* Mark the occurrence of a given number of events.
*
* @param n the number of events
*/
public void mark(long n) {
tickIfNecessary();
count.add(n);
m1Rate.update(n);
m5Rate.update(n);
m15Rate.update(n);
}
private void tickIfNecessary() {<FILL_FUNCTION_BODY>}
@Override
public long getCount() {
return count.sum();
}
@Override
public double getFifteenMinuteRate() {
tickIfNecessary();
return m15Rate.getRate(TimeUnit.SECONDS);
}
@Override
public double getFiveMinuteRate() {
tickIfNecessary();
return m5Rate.getRate(TimeUnit.SECONDS);
}
@Override
public double getMeanRate() {
if (getCount() == 0) {
return 0.0;
} else {
final double elapsed = (clock.getTick() - startTime);
return getCount() / elapsed * TimeUnit.SECONDS.toNanos(1);
}
}
@Override
public double getOneMinuteRate() {
tickIfNecessary();
return m1Rate.getRate(TimeUnit.SECONDS);
}
@Override
public String toString() {
return "Meter[mean=" + this.getMeanRate() +
", 1m=" + this.m1Rate.getRate(TimeUnit.SECONDS) +
", 5m=" + this.m5Rate.getRate(TimeUnit.SECONDS) +
", 15m=" + this.m15Rate.getRate(TimeUnit.SECONDS) + "]";
}
}
|
final long oldTick = lastTick.get();
final long newTick = clock.getTick();
final long age = newTick - oldTick;
if (age > TICK_INTERVAL) {
final long newIntervalStartTick = newTick - age % TICK_INTERVAL;
if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) {
final long requiredTicks = age / TICK_INTERVAL;
for (long i = 0; i < requiredTicks; i++) {
m1Rate.tick();
m5Rate.tick();
m15Rate.tick();
}
}
}
| 793
| 175
| 968
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/RatioGauge.java
|
Ratio
|
getValue
|
class Ratio {
/**
* Creates a new ratio with the given numerator and denominator.
*
* @param numerator the numerator of the ratio
* @param denominator the denominator of the ratio
* @return {@code numerator:denominator}
*/
public static Ratio of(double numerator, double denominator) {
return new Ratio(numerator, denominator);
}
private final double numerator;
private final double denominator;
private Ratio(double numerator, double denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
/**
* Returns the ratio, which is either a {@code double} between 0 and 1 (inclusive) or
* {@code NaN}.
*
* @return the ratio
*/
public double getValue() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return numerator + ":" + denominator;
}
}
|
final double d = denominator;
if (isNaN(d) || isInfinite(d) || d == 0) {
return Double.NaN;
}
return numerator / d;
| 265
| 54
| 319
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/ScheduledReporter.java
|
NamedThreadFactory
|
stop
|
class NamedThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private NamedThreadFactory(String name) {
final SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = "metrics-" + name + "-thread-";
}
@Override
public Thread newThread(Runnable r) {
final Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
t.setDaemon(true);
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
private static final AtomicInteger FACTORY_ID = new AtomicInteger();
private final MetricRegistry registry;
private final ScheduledExecutorService executor;
private final MetricFilter filter;
private final double durationFactor;
private final String durationUnit;
private final double rateFactor;
private final String rateUnit;
/**
* Creates a new {@link ScheduledReporter} instance.
*
* @param registry the {@link io.dropwizard.metrics.MetricRegistry} containing the metrics this
* reporter will report
* @param name the reporter's name
* @param filter the filter for which metrics to report
* @param rateUnit a unit of time
* @param durationUnit a unit of time
*/
protected ScheduledReporter(MetricRegistry registry,
String name,
MetricFilter filter,
TimeUnit rateUnit,
TimeUnit durationUnit) {
this(registry, filter, rateUnit, durationUnit,
Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())));
}
/**
* Creates a new {@link ScheduledReporter} instance.
*
* @param registry the {@link io.dropwizard.metrics.MetricRegistry} containing the metrics this
* reporter will report
* @param filter the filter for which metrics to report
* @param rateUnit the rate unit
* @param durationUnit the duration unit
* @param executor the executor to use while scheduling reporting of metrics.
*/
protected ScheduledReporter(MetricRegistry registry,
MetricFilter filter,
TimeUnit rateUnit,
TimeUnit durationUnit,
ScheduledExecutorService executor) {
this.registry = registry;
this.filter = filter;
this.executor = executor;
this.rateFactor = rateUnit.toSeconds(1);
this.rateUnit = calculateRateUnit(rateUnit);
this.durationFactor = 1.0 / durationUnit.toNanos(1);
this.durationUnit = durationUnit.toString().toLowerCase(Locale.US);
}
/**
* Starts the reporter polling at the given period.
*
* @param period the amount of time between polls
* @param unit the unit for {@code period}
*/
public void start(long period, TimeUnit unit) {
executor.scheduleAtFixedRate(() -> {
try {
report();
} catch (RuntimeException ex) {
LOG.error("RuntimeException thrown from {}#report. Exception was suppressed.", ScheduledReporter.this.getClass().getSimpleName(), ex);
}
}, period, period, unit);
}
/**
* Stops the reporter and shuts down its thread of execution.
*
* Uses the shutdown pattern from http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
*/
public void stop() {<FILL_FUNCTION_BODY>
|
executor.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
executor.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
LOG.warn(getClass().getSimpleName() + ": ScheduledExecutorService did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
| 1,005
| 193
| 1,198
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/SharedMetricRegistries.java
|
SharedMetricRegistries
|
getOrCreate
|
class SharedMetricRegistries {
private static final ConcurrentMap<String, MetricRegistry> REGISTRIES =
new ConcurrentHashMap<>();
private static volatile String defaultRegistryName = null;
private SharedMetricRegistries() { /* singleton */ }
public static void clear() {
REGISTRIES.clear();
}
public static Set<String> names() {
return REGISTRIES.keySet();
}
public static void remove(String key) {
REGISTRIES.remove(key);
}
public static MetricRegistry add(String name, MetricRegistry registry) {
return REGISTRIES.putIfAbsent(name, registry);
}
public static MetricRegistry getOrCreate(String name) {<FILL_FUNCTION_BODY>}
public synchronized static MetricRegistry setDefault(String name) {
final MetricRegistry registry = getOrCreate(name);
return setDefault(name, registry);
}
public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) {
if (defaultRegistryName == null) {
defaultRegistryName = name;
add(name, metricRegistry);
return metricRegistry;
}
throw new IllegalStateException("Default metric registry name is already set.");
}
public static MetricRegistry getDefault() {
if (defaultRegistryName != null) {
return getOrCreate(defaultRegistryName);
}
throw new IllegalStateException("Default registry name has not been set.");
}
}
|
final MetricRegistry existing = REGISTRIES.get(name);
if (existing == null) {
final MetricRegistry created = new MetricRegistry();
final MetricRegistry raced = add(name, created);
if (raced == null) {
return created;
}
return raced;
}
return existing;
| 395
| 91
| 486
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/Slf4jReporter.java
|
Builder
|
report
|
class Builder {
private final MetricRegistry registry;
private Logger logger;
private LoggingLevel loggingLevel;
private Marker marker;
private String prefix;
private TimeUnit rateUnit;
private TimeUnit durationUnit;
private MetricFilter filter;
private Builder(MetricRegistry registry) {
this.registry = registry;
this.logger = LoggerFactory.getLogger("metrics");
this.marker = null;
this.prefix = "";
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
this.loggingLevel = LoggingLevel.INFO;
}
/**
* Log metrics to the given logger.
*
* @param logger an SLF4J {@link Logger}
* @return {@code this}
*/
public Builder outputTo(Logger logger) {
this.logger = logger;
return this;
}
/**
* Mark all logged metrics with the given marker.
*
* @param marker an SLF4J {@link Marker}
* @return {@code this}
*/
public Builder markWith(Marker marker) {
this.marker = marker;
return this;
}
/**
* Prefix all metric names with the given string.
*
* @param prefix the prefix for all metric names
* @return {@code this}
*/
public Builder prefixedWith(String prefix) {
this.prefix = prefix;
return this;
}
/**
* Convert rates to the given time unit.
*
* @param rateUnit a unit of time
* @return {@code this}
*/
public Builder convertRatesTo(TimeUnit rateUnit) {
this.rateUnit = rateUnit;
return this;
}
/**
* Convert durations to the given time unit.
*
* @param durationUnit a unit of time
* @return {@code this}
*/
public Builder convertDurationsTo(TimeUnit durationUnit) {
this.durationUnit = durationUnit;
return this;
}
/**
* Only report metrics which match the given filter.
*
* @param filter a {@link MetricFilter}
* @return {@code this}
*/
public Builder filter(MetricFilter filter) {
this.filter = filter;
return this;
}
/**
* Use Logging Level when reporting.
*
* @param loggingLevel a (@link Slf4jReporter.LoggingLevel}
* @return {@code this}
*/
public Builder withLoggingLevel(LoggingLevel loggingLevel) {
this.loggingLevel = loggingLevel;
return this;
}
/**
* Builds a {@link Slf4jReporter} with the given properties.
*
* @return a {@link Slf4jReporter}
*/
public Slf4jReporter build() {
LoggerProxy loggerProxy;
switch (loggingLevel) {
case TRACE:
loggerProxy = new TraceLoggerProxy(logger);
break;
case INFO:
loggerProxy = new InfoLoggerProxy(logger);
break;
case WARN:
loggerProxy = new WarnLoggerProxy(logger);
break;
case ERROR:
loggerProxy = new ErrorLoggerProxy(logger);
break;
default:
case DEBUG:
loggerProxy = new DebugLoggerProxy(logger);
break;
}
return new Slf4jReporter(registry, loggerProxy, marker, prefix, rateUnit, durationUnit, filter);
}
}
private final LoggerProxy loggerProxy;
private final Marker marker;
private final MetricName prefix;
private Slf4jReporter(MetricRegistry registry,
LoggerProxy loggerProxy,
Marker marker,
String prefix,
TimeUnit rateUnit,
TimeUnit durationUnit,
MetricFilter filter) {
super(registry, "logger-reporter", filter, rateUnit, durationUnit);
this.loggerProxy = loggerProxy;
this.marker = marker;
this.prefix = MetricName.build(prefix);
}
@Override
public void report(SortedMap<MetricName, Gauge> gauges,
SortedMap<MetricName, Counter> counters,
SortedMap<MetricName, Histogram> histograms,
SortedMap<MetricName, Meter> meters,
SortedMap<MetricName, Timer> timers) {<FILL_FUNCTION_BODY>
|
if (loggerProxy.isEnabled(marker)) {
for (Entry<MetricName, Gauge> entry : gauges.entrySet()) {
logGauge(entry.getKey(), entry.getValue());
}
for (Entry<MetricName, Counter> entry : counters.entrySet()) {
logCounter(entry.getKey(), entry.getValue());
}
for (Entry<MetricName, Histogram> entry : histograms.entrySet()) {
logHistogram(entry.getKey(), entry.getValue());
}
for (Entry<MetricName, Meter> entry : meters.entrySet()) {
logMeter(entry.getKey(), entry.getValue());
}
for (Entry<MetricName, Timer> entry : timers.entrySet()) {
logTimer(entry.getKey(), entry.getValue());
}
}
| 1,171
| 223
| 1,394
|
<methods>public void close() ,public void report() ,public abstract void report(SortedMap<io.dropwizard.metrics.MetricName,Gauge#RAW>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Counter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Histogram>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Meter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Timer>) ,public void start(long, java.util.concurrent.TimeUnit) ,public void stop() <variables>private static final java.util.concurrent.atomic.AtomicInteger FACTORY_ID,private static final Logger LOG,private final non-sealed double durationFactor,private final non-sealed java.lang.String durationUnit,private final non-sealed java.util.concurrent.ScheduledExecutorService executor,private final non-sealed io.dropwizard.metrics.MetricFilter filter,private final non-sealed double rateFactor,private final non-sealed java.lang.String rateUnit,private final non-sealed io.dropwizard.metrics.MetricRegistry registry
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/SlidingTimeWindowReservoir.java
|
SlidingTimeWindowReservoir
|
getTick
|
class SlidingTimeWindowReservoir implements Reservoir {
// allow for this many duplicate ticks before overwriting measurements
private static final int COLLISION_BUFFER = 256;
// only trim on updating once every N
private static final int TRIM_THRESHOLD = 256;
private final Clock clock;
private final ConcurrentSkipListMap<Long, Long> measurements;
private final long window;
private final AtomicLong lastTick;
private final AtomicLong count;
/**
* Creates a new {@link SlidingTimeWindowReservoir} with the given window of time.
*
* @param window the window of time
* @param windowUnit the unit of {@code window}
*/
public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) {
this(window, windowUnit, Clock.defaultClock());
}
/**
* Creates a new {@link SlidingTimeWindowReservoir} with the given clock and window of time.
*
* @param window the window of time
* @param windowUnit the unit of {@code window}
* @param clock the {@link Clock} to use
*/
public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) {
this.clock = clock;
this.measurements = new ConcurrentSkipListMap<>();
this.window = windowUnit.toNanos(window) * COLLISION_BUFFER;
this.lastTick = new AtomicLong(clock.getTick() * COLLISION_BUFFER);
this.count = new AtomicLong();
}
@Override
public int size() {
trim();
return measurements.size();
}
@Override
public void update(long value) {
if (count.incrementAndGet() % TRIM_THRESHOLD == 0) {
trim();
}
measurements.put(getTick(), value);
}
@Override
public Snapshot getSnapshot() {
trim();
return new UniformSnapshot(measurements.values());
}
private long getTick() {<FILL_FUNCTION_BODY>}
private void trim() {
measurements.headMap(getTick() - window).clear();
}
}
|
for (; ; ) {
final long oldTick = lastTick.get();
final long tick = clock.getTick() * COLLISION_BUFFER;
// ensure the tick is strictly incrementing even if there are duplicate ticks
final long newTick = tick - oldTick > 0 ? tick : oldTick + 1;
if (lastTick.compareAndSet(oldTick, newTick)) {
return newTick;
}
}
| 585
| 120
| 705
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/SlidingWindowReservoir.java
|
SlidingWindowReservoir
|
getSnapshot
|
class SlidingWindowReservoir implements Reservoir {
private final long[] measurements;
private long count;
/**
* Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements.
*
* @param size the number of measurements to store
*/
public SlidingWindowReservoir(int size) {
this.measurements = new long[size];
this.count = 0;
}
@Override
public synchronized int size() {
return (int) min(count, measurements.length);
}
@Override
public synchronized void update(long value) {
measurements[(int) (count++ % measurements.length)] = value;
}
@Override
public Snapshot getSnapshot() {<FILL_FUNCTION_BODY>}
}
|
final long[] values = new long[size()];
for (int i = 0; i < values.length; i++) {
synchronized (this) {
values[i] = measurements[i];
}
}
return new UniformSnapshot(values, false);
| 208
| 72
| 280
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/Striped64.java
|
ThreadHashCode
|
retryUpdate
|
class ThreadHashCode extends ThreadLocal<HashCode> {
@Override
public HashCode initialValue() {
return new HashCode();
}
}
static final AtomicLongFieldUpdater<Striped64> baseUpdater = AtomicLongFieldUpdater.newUpdater(Striped64.class, "base");
static final AtomicIntegerFieldUpdater<Striped64> busyUpdater = AtomicIntegerFieldUpdater.newUpdater(Striped64.class, "busy");
/**
* Static per-thread hash codes. Shared across all instances to reduce ThreadLocal pollution and
* because adjustments due to collisions in one table are likely to be appropriate for others.
*/
static final ThreadHashCode threadHashCode = new ThreadHashCode();
/**
* Number of CPUS, to place bound on table size
*/
static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* Table of cells. When non-null, size is a power of 2.
*/
transient volatile Cell[] cells;
/**
* Base value, used mainly when there is no contention, but also as a fallback during table
* initialization races. Updated via CAS.
*/
transient volatile long base;
/**
* Spinlock (locked via CAS) used when resizing and/or creating Cells.
*/
transient volatile int busy;
/**
* Package-private default constructor
*/
Striped64() {
}
/**
* CASes the base field.
*/
final boolean casBase(long cmp, long val) {
return baseUpdater.compareAndSet(this, cmp, val);
}
/**
* CASes the busy field from 0 to 1 to acquire lock.
*/
final boolean casBusy() {
return busyUpdater.compareAndSet(this, 0, 1);
}
/**
* Computes the function of current and new value. Subclasses should open-code this update
* function for most uses, but the virtualized form is needed within retryUpdate.
*
* @param currentValue the current value (of either base or a cell)
* @param newValue the argument from a user update call
* @return result of the update function
*/
abstract long fn(long currentValue, long newValue);
/**
* Handles cases of updates involving initialization, resizing, creating new Cells, and/or
* contention. See above for explanation. This method suffers the usual non-modularity problems
* of optimistic retry code, relying on rechecked sets of reads.
*
* @param x the value
* @param hc the hash code holder
* @param wasUncontended false if CAS failed before call
*/
final void retryUpdate(long x, HashCode hc, boolean wasUncontended) {<FILL_FUNCTION_BODY>
|
int h = hc.code;
boolean collide = false; // True if last slot nonempty
for (; ; ) {
Cell[] as;
Cell a;
int n;
long v;
if ((as = cells) != null && (n = as.length) > 0) {
if ((a = as[(n - 1) & h]) == null) {
if (busy == 0) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
if (busy == 0 && casBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs;
int m, j;
if ((rs = cells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
busy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
} else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (a.cas(v = a.value, fn(v, x)))
break;
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (busy == 0 && casBusy()) {
try {
if (cells == as) { // Expand table unless stale
Cell[] rs = new Cell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
cells = rs;
}
} finally {
busy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h ^= h << 13; // Rehash
h ^= h >>> 17;
h ^= h << 5;
} else if (busy == 0 && cells == as && casBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
busy = 0;
}
if (init)
break;
} else if (casBase(v = base, fn(v, x)))
break; // Fall back on using base
}
hc.code = h; // Record index for next time
| 752
| 720
| 1,472
|
<methods>public void <init>() ,public byte byteValue() ,public abstract double doubleValue() ,public abstract float floatValue() ,public abstract int intValue() ,public abstract long longValue() ,public short shortValue() <variables>private static final long serialVersionUID
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/Timer.java
|
Context
|
toString
|
class Context implements AutoCloseable {
private final Timer timer;
private final Clock clock;
private final long startTime;
private Context(Timer timer, Clock clock) {
this.timer = timer;
this.clock = clock;
this.startTime = clock.getTick();
}
/**
* Updates the timer with the difference between current and start time. Call to this method will
* not reset the start time. Multiple calls result in multiple updates.
* @return the elapsed time in nanoseconds
*/
public long stop() {
final long elapsed = clock.getTick() - startTime;
timer.update(elapsed, TimeUnit.NANOSECONDS);
return elapsed;
}
/** Equivalent to calling {@link #stop()}. */
@Override
public void close() {
stop();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Timer.Context[start_time=" + this.startTime +
", " + this.timer + ", " + this.clock + "]";
| 250
| 41
| 291
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/UniformReservoir.java
|
UniformReservoir
|
nextLong
|
class UniformReservoir implements Reservoir {
private static final int DEFAULT_SIZE = 1028;
private static final int BITS_PER_LONG = 63;
private final AtomicLong count = new AtomicLong();
private final AtomicLongArray values;
/**
* Creates a new {@link UniformReservoir} of 1028 elements, which offers a 99.9% confidence level
* with a 5% margin of error assuming a normal distribution.
*/
public UniformReservoir() {
this(DEFAULT_SIZE);
}
/**
* Creates a new {@link UniformReservoir}.
*
* @param size the number of samples to keep in the sampling reservoir
*/
public UniformReservoir(int size) {
this.values = new AtomicLongArray(size);
for (int i = 0; i < values.length(); i++) {
values.set(i, 0);
}
count.set(0);
}
@Override
public int size() {
final long c = count.get();
if (c > values.length()) {
return values.length();
}
return (int) c;
}
@Override
public void update(long value) {
final long c = count.incrementAndGet();
if (c <= values.length()) {
values.set((int) c - 1, value);
} else {
final long r = nextLong(c);
if (r < values.length()) {
values.set((int) r, value);
}
}
}
/**
* Get a pseudo-random long uniformly between 0 and n-1. Stolen from
* {@link java.util.Random#nextInt()}.
*
* @param n the bound
* @return a value select randomly from the range {@code [0..n)}.
*/
@SuppressWarnings("NumericOverflow")
private static long nextLong(long n) {<FILL_FUNCTION_BODY>}
@Override
public Snapshot getSnapshot() {
final int s = size();
long[] copy = new long[s];
for (int i = 0; i < s; i++) {
copy[i] = values.get(i);
}
return new UniformSnapshot(copy, false);
}
}
|
long bits, val;
do {
bits = ThreadLocalRandom.current().nextLong() & (~(1L << BITS_PER_LONG));
val = bits % n;
} while (bits - val + (n - 1) < 0L);
return val;
| 610
| 75
| 685
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/UniformSnapshot.java
|
UniformSnapshot
|
getStdDev
|
class UniformSnapshot extends Snapshot {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final long[] values;
/**
* Create a new {@link Snapshot} with the given values.
*
* @param values an unordered set of values in the reservoir
*/
public UniformSnapshot(Collection<Long> values) {
this.values = new long[values.size()];
int i = 0;
for (Long value : values) {
this.values[i++] = value;
}
Arrays.sort(this.values);
}
/**
* Create a new {@link Snapshot} with the given values.
*
* @param values an unordered set of values in the reservoir
*/
public UniformSnapshot(long[] values) {
this(values, true);
}
/**
* Create a new {@link Snapshot} with the given values.
* Allows for trusted code to provide an array that won't be copied, for performance reasons.
*
* @param values an unordered set of values in the reservoir
* @param copy whether the array should be copied by the constructor
*/
protected UniformSnapshot(long[] values, boolean copy) {
if (copy) {
this.values = Arrays.copyOf(values, values.length);
} else {
this.values = values;
}
Arrays.sort(this.values);
}
/**
* Returns the value at the given quantile.
*
* @param quantile a given quantile, in {@code [0..1]}
* @return the value in the distribution at {@code quantile}
*/
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
final double pos = quantile * (values.length + 1);
final int index = (int) pos;
if (index < 1) {
return values[0];
}
if (index >= values.length) {
return values[values.length - 1];
}
final double lower = values[index - 1];
final double upper = values[index];
return lower + (pos - floor(pos)) * (upper - lower);
}
/**
* Returns the number of values in the snapshot.
*
* @return the number of values
*/
@Override
public int size() {
return values.length;
}
/**
* Returns the entire set of values in the snapshot.
*
* @return the entire set of values
*/
@Override
public long[] getValues() {
return Arrays.copyOf(values, values.length);
}
/**
* Returns the highest value in the snapshot.
*
* @return the highest value
*/
@Override
public long getMax() {
if (values.length == 0) {
return 0;
}
return values[values.length - 1];
}
/**
* Returns the lowest value in the snapshot.
*
* @return the lowest value
*/
@Override
public long getMin() {
if (values.length == 0) {
return 0;
}
return values[0];
}
/**
* Returns the arithmetic mean of the values in the snapshot.
*
* @return the arithmetic mean
*/
@Override
public double getMean() {
if (values.length == 0) {
return 0;
}
double sum = 0;
for (long value : values) {
sum += value;
}
return sum / values.length;
}
/**
* Returns the standard deviation of the values in the snapshot.
*
* @return the standard deviation value
*/
@Override
public double getStdDev() {<FILL_FUNCTION_BODY>}
/**
* Writes the values of the snapshot to the given stream.
*
* @param output an output stream
*/
@Override
public void dump(OutputStream output) {
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) {
for (long value : values) {
out.printf("%d%n", value);
}
}
}
}
|
// two-pass algorithm for variance, avoids numeric overflow
if (values.length <= 1) {
return 0;
}
final double mean = getMean();
double sum = 0;
for (long value : values) {
final double diff = value - mean;
sum += diff * diff;
}
final double variance = sum / (values.length - 1);
return Math.sqrt(variance);
| 1,181
| 116
| 1,297
|
<methods>public non-sealed void <init>() ,public abstract void dump(java.io.OutputStream) ,public double get75thPercentile() ,public double get95thPercentile() ,public double get98thPercentile() ,public double get999thPercentile() ,public double get99thPercentile() ,public abstract long getMax() ,public abstract double getMean() ,public double getMedian() ,public abstract long getMin() ,public abstract double getStdDev() ,public abstract double getValue(double) ,public abstract long[] getValues() ,public abstract int size() <variables>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/WeightedSnapshot.java
|
WeightedSample
|
getMin
|
class WeightedSample {
public final long value;
public final double weight;
public WeightedSample(long value, double weight) {
this.value = value;
this.weight = weight;
}
}
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final long[] values;
private final double[] normWeights;
private final double[] quantiles;
/**
* Create a new {@link Snapshot} with the given values.
*
* @param values an unordered set of values in the reservoir
*/
public WeightedSnapshot(Collection<WeightedSample> values) {
final WeightedSample[] copy = values.toArray( new WeightedSample[]{} );
Arrays.sort(copy, (o1, o2) -> {
if (o1.value > o2.value)
return 1;
if (o1.value < o2.value)
return -1;
return 0;
}
);
this.values = new long[copy.length];
this.normWeights = new double[copy.length];
this.quantiles = new double[copy.length];
double sumWeight = 0;
for (WeightedSample sample : copy) {
sumWeight += sample.weight;
}
for (int i = 0; i < copy.length; i++) {
this.values[i] = copy[i].value;
this.normWeights[i] = copy[i].weight / sumWeight;
}
for (int i = 1; i < copy.length; i++) {
this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1];
}
}
/**
* Returns the value at the given quantile.
*
* @param quantile a given quantile, in {@code [0..1]}
* @return the value in the distribution at {@code quantile}
*/
@Override
public double getValue(double quantile) {
if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) {
throw new IllegalArgumentException(quantile + " is not in [0..1]");
}
if (values.length == 0) {
return 0.0;
}
int posx = Arrays.binarySearch(quantiles, quantile);
if (posx < 0)
posx = ((-posx) - 1) - 1;
if (posx < 1) {
return values[0];
}
if (posx >= values.length) {
return values[values.length - 1];
}
return values[posx];
}
/**
* Returns the number of values in the snapshot.
*
* @return the number of values
*/
@Override
public int size() {
return values.length;
}
/**
* Returns the entire set of values in the snapshot.
*
* @return the entire set of values
*/
@Override
public long[] getValues() {
return Arrays.copyOf(values, values.length);
}
/**
* Returns the highest value in the snapshot.
*
* @return the highest value
*/
@Override
public long getMax() {
if (values.length == 0) {
return 0;
}
return values[values.length - 1];
}
/**
* Returns the lowest value in the snapshot.
*
* @return the lowest value
*/
@Override
public long getMin() {<FILL_FUNCTION_BODY>
|
if (values.length == 0) {
return 0;
}
return values[0];
| 953
| 30
| 983
|
<methods>public non-sealed void <init>() ,public abstract void dump(java.io.OutputStream) ,public double get75thPercentile() ,public double get95thPercentile() ,public double get98thPercentile() ,public double get999thPercentile() ,public double get99thPercentile() ,public abstract long getMax() ,public abstract double getMean() ,public double getMedian() ,public abstract long getMin() ,public abstract double getStdDev() ,public abstract double getValue(double) ,public abstract long[] getValues() ,public abstract int size() <variables>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/broadcom/APMEPAgentSender.java
|
APMEPAgentSender
|
writeData
|
class APMEPAgentSender implements TimeSeriesDbSender {
private static final Logger logger = LoggerFactory.getLogger(APMEPAgentSender.class);
private final String path;
private final String serviceId;
private final String productName;
private final HttpClientRequest httpClientRequest = new HttpClientRequest();
private final URL url;
private final InfluxDbWriteObject influxDbWriteObject;
public APMEPAgentSender(final String protocol, final String hostname, final int port, final String epAgentPath, final String serviceId, final String productName) throws MalformedURLException {
this(protocol, hostname, port, epAgentPath, serviceId, productName, TimeUnit.MILLISECONDS);
}
public APMEPAgentSender(final String protocol, final String hostname, final int port, final String epAgentPath, final String serviceId, final String productName, final TimeUnit timePrecision) throws MalformedURLException {
this.url = new URL(protocol, hostname, port, "");
this.path = epAgentPath;
this.serviceId = serviceId;
this.productName = productName;
if(logger.isInfoEnabled()) logger.info("APMEPAgentSender is created with path = {} and host = {}", path, url);
this.influxDbWriteObject = new InfluxDbWriteObject(timePrecision);
}
@Override
public void flush() {
influxDbWriteObject.setPoints(new HashSet<>());
}
@Override
public boolean hasSeriesData() {
return influxDbWriteObject.getPoints() != null && !influxDbWriteObject.getPoints().isEmpty();
}
@Override
public void appendPoints(final InfluxDbPoint point) {
if (point != null) {
influxDbWriteObject.getPoints().add(point);
}
}
@Override
public int writeData() throws Exception {<FILL_FUNCTION_BODY>}
private String convertInfluxDBWriteObjectToJSON(InfluxDbWriteObject influxDbWriteObject) throws ClientException {
EPAgentMetricRequest epAgentMetricRequest = new EPAgentMetricRequest();
List<EPAgentMetric> epAgentMetricList = new ArrayList<EPAgentMetric>();
for (InfluxDbPoint point : influxDbWriteObject.getPoints()) {
EPAgentMetric epAgentMetric = new EPAgentMetric();
epAgentMetric.setName(convertName(point));
// Need to convert the value from milliseconds with a decimal to milliseconds as a whole number
double milliseconds = Double.parseDouble(point.getValue());
int roundedMilliseconds = (int) Math.round(milliseconds);
epAgentMetric.setValue(Integer.toString(roundedMilliseconds));
epAgentMetric.setType("PerIntervalCounter");
epAgentMetricList.add(epAgentMetric);
}
epAgentMetricRequest.setMetrics(epAgentMetricList);
String json = "";
try {
json = Config.getInstance().getMapper().writeValueAsString(epAgentMetricRequest);
} catch (JsonProcessingException e) {
throw new ClientException(e);
}
return json;
}
private String convertName(InfluxDbPoint point) {
StringJoiner metricNameJoiner = new StringJoiner("|");
metricNameJoiner.add(productName);
metricNameJoiner.add(serviceId);
for (Entry<String, String> pair : point.getTags().entrySet()) {
Object value = pair.getValue();
if(value != null) {
metricNameJoiner.add(pair.getValue());
} else {
metricNameJoiner.add("null");
}
}
return metricNameJoiner.toString() + ":" + point.getMeasurement();
}
@Override
public void setTags(final Map<String, String> tags) {
if (tags != null) {
influxDbWriteObject.setTags(tags);
}
}
}
|
final String body = convertInfluxDBWriteObjectToJSON(influxDbWriteObject);
if(logger.isTraceEnabled()) logger.trace("APMEPAgentSender is sending data to host = {} with body = {}", url, body);
HttpRequest.Builder builder = httpClientRequest.initBuilder(this.url.toString() + this.path, HttpMethod.POST, Optional.of(body));
builder.setHeader("Content-Type", "application/json");
HttpResponse<String> response = (HttpResponse<String>) httpClientRequest.send(builder, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
if(statusCode >= 200 && statusCode < 300) {
return statusCode;
} else {
logger.error("Server returned HTTP response code: {} for path: {} and host: {} with content :'{}'",
statusCode, path, url, response.body());
throw new ClientException("Server returned HTTP response code: " + statusCode
+ "for path: " + path + " and host: " + url
+ " with content :'"
+ response.body() + "'");
}
| 1,053
| 289
| 1,342
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/influxdb/InfluxDbHttpSender.java
|
InfluxDbHttpSender
|
writeData
|
class InfluxDbHttpSender implements TimeSeriesDbSender {
private static final Logger logger = LoggerFactory.getLogger(InfluxDbReporter.class);
private final HttpClientRequest httpClientRequest = new HttpClientRequest();
private final URL url;
private final String path;
private final InfluxDbWriteObject influxDbWriteObject;
/**
* Creates a new http sender given connection details.
*
* @param protocol the influxDb protocol
* @param hostname the influxDb hostname
* @param port the influxDb http port
* @param database the influxDb database to write to
* @param username the username used to connect to influxDb
* @param password the password used to connect to influxDb
* @throws Exception exception while creating the influxDb sender(MalformedURLException)
*/
public InfluxDbHttpSender(final String protocol, final String hostname, final int port, final String database, final String username, final String password) throws Exception {
this(protocol, hostname, port, database, username, password, TimeUnit.MILLISECONDS);
}
/**
* Creates a new http sender given connection details.
*
* @param protocol the influxDb protocol
* @param hostname the influxDb hostname
* @param port the influxDb http port
* @param database the influxDb database to write to
* @param username the influxDb username
* @param password the influxDb password
* @param timePrecision the time precision of the metrics
* @throws Exception exception while creating the influxDb sender(MalformedURLException)
*/
public InfluxDbHttpSender(final String protocol, final String hostname, final int port, final String database, final String username, final String password,
final TimeUnit timePrecision) throws Exception {
this.url = new URL(protocol, hostname, port, "");
String queryDb = String.format("db=%s", URLEncoder.encode(database, "UTF-8"));
String queryCredential = String.format("u=%s&p=%s", URLEncoder.encode(username, "UTF8"), URLEncoder.encode(password, "UTF8"));
String queryPrecision = String.format("precision=%s", TimeUtils.toTimePrecision(timePrecision));
this.path = "/write?" + queryDb + "&" + queryCredential + "&" + queryPrecision;
if(logger.isInfoEnabled()) logger.info("InfluxDbHttpSender is created with path = " + path + " and host = " + url);
this.influxDbWriteObject = new InfluxDbWriteObject(timePrecision);
}
@Override
public void flush() {
influxDbWriteObject.setPoints(new HashSet<>());
}
@Override
public boolean hasSeriesData() {
return influxDbWriteObject.getPoints() != null && !influxDbWriteObject.getPoints().isEmpty();
}
@Override
public void appendPoints(final InfluxDbPoint point) {
if (point != null) {
influxDbWriteObject.getPoints().add(point);
}
}
@Override
public int writeData() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void setTags(final Map<String, String> tags) {
if (tags != null) {
influxDbWriteObject.setTags(tags);
}
}
}
|
final String body = influxDbWriteObject.getBody();
HttpRequest.Builder builder = httpClientRequest.initBuilder(this.url.toString() + this.path, HttpMethod.POST, Optional.of(body));
builder.setHeader("Content-Type", "text/plain");
HttpResponse<String> response = (HttpResponse<String>) httpClientRequest.send(builder, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
if(statusCode >= 200 && statusCode < 300) {
return statusCode;
} else {
logger.error("Server returned HTTP response code: " + statusCode
+ "for path: " + path + " and host: " + url
+ " with content :'"
+ response.body() + "'");
throw new ClientException("Server returned HTTP response code: " + statusCode
+ "for path: " + path + " and host: " + url
+ " with content :'"
+ response.body() + "'");
}
| 895
| 256
| 1,151
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/influxdb/InfluxDbReporter.java
|
Builder
|
report
|
class Builder {
private final MetricRegistry registry;
private Map<String, String> tags;
private TimeUnit rateUnit;
private TimeUnit durationUnit;
private MetricFilter filter;
private boolean skipIdleMetrics;
private Builder(MetricRegistry registry) {
this.registry = registry;
this.tags = null;
this.rateUnit = TimeUnit.SECONDS;
this.durationUnit = TimeUnit.MILLISECONDS;
this.filter = MetricFilter.ALL;
}
/**
* Add these tags to all metrics.
*
* @param tags a map containing tags common to all metrics
* @return {@code this}
*/
public Builder withTags(Map<String, String> tags) {
this.tags = Collections.unmodifiableMap(tags);
return this;
}
/**
* Convert rates to the given time unit.
*
* @param rateUnit a unit of time
* @return {@code this}
*/
public Builder convertRatesTo(TimeUnit rateUnit) {
this.rateUnit = rateUnit;
return this;
}
/**
* Convert durations to the given time unit.
*
* @param durationUnit a unit of time
* @return {@code this}
*/
public Builder convertDurationsTo(TimeUnit durationUnit) {
this.durationUnit = durationUnit;
return this;
}
/**
* Only report metrics which match the given filter.
*
* @param filter a {@link MetricFilter}
* @return {@code this}
*/
public Builder filter(MetricFilter filter) {
this.filter = filter;
return this;
}
/**
* Only report metrics that have changed.
*
* @param skipIdleMetrics true/false for skipping metrics not reported
* @return {@code this}
*/
public Builder skipIdleMetrics(boolean skipIdleMetrics) {
this.skipIdleMetrics = skipIdleMetrics;
return this;
}
public InfluxDbReporter build(final TimeSeriesDbSender influxDb) {
return new InfluxDbReporter(registry, influxDb, tags, rateUnit, durationUnit, filter, skipIdleMetrics);
}
}
private static final Logger logger = LoggerFactory.getLogger(InfluxDbReporter.class);
private final TimeSeriesDbSender influxDb;
private final boolean skipIdleMetrics;
private final Map<MetricName, Long> previousValues;
private InfluxDbReporter(final MetricRegistry registry, final TimeSeriesDbSender influxDb, final Map<String, String> tags,
final TimeUnit rateUnit, final TimeUnit durationUnit, final MetricFilter filter, final boolean skipIdleMetrics) {
super(registry, "influxDb-reporter", filter, rateUnit, durationUnit);
this.influxDb = influxDb;
influxDb.setTags(tags);
this.skipIdleMetrics = skipIdleMetrics;
this.previousValues = new TreeMap<>();
}
public static Builder forRegistry(MetricRegistry registry) {
return new Builder(registry);
}
@Override
public void report(final SortedMap<MetricName, Gauge> gauges, final SortedMap<MetricName, Counter> counters,
final SortedMap<MetricName, Histogram> histograms, final SortedMap<MetricName, Meter> meters, final SortedMap<MetricName, Timer> timers) {<FILL_FUNCTION_BODY>
|
final long now = System.currentTimeMillis();
if(logger.isDebugEnabled()) logger.debug("InfluxDbReporter report is called with counter size " + counters.size());
try {
influxDb.flush();
for (Map.Entry<MetricName, Gauge> entry : gauges.entrySet()) {
reportGauge(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Counter> entry : counters.entrySet()) {
reportCounter(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Histogram> entry : histograms.entrySet()) {
reportHistogram(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Meter> entry : meters.entrySet()) {
reportMeter(entry.getKey(), entry.getValue(), now);
}
for (Map.Entry<MetricName, Timer> entry : timers.entrySet()) {
reportTimer(entry.getKey(), entry.getValue(), now);
}
if (influxDb.hasSeriesData()) {
influxDb.writeData();
}
// reset counters
for (Map.Entry<MetricName, Counter> entry : counters.entrySet()) {
Counter counter = entry.getValue();
long count = counter.getCount();
counter.dec(count);
}
} catch (Exception e) {
logger.error("Unable to report to InfluxDB. Discarding data.", e);
}
| 914
| 406
| 1,320
|
<methods>public void close() ,public void report() ,public abstract void report(SortedMap<io.dropwizard.metrics.MetricName,Gauge#RAW>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Counter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Histogram>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Meter>, SortedMap<io.dropwizard.metrics.MetricName,io.dropwizard.metrics.Timer>) ,public void start(long, java.util.concurrent.TimeUnit) ,public void stop() <variables>private static final java.util.concurrent.atomic.AtomicInteger FACTORY_ID,private static final Logger LOG,private final non-sealed double durationFactor,private final non-sealed java.lang.String durationUnit,private final non-sealed java.util.concurrent.ScheduledExecutorService executor,private final non-sealed io.dropwizard.metrics.MetricFilter filter,private final non-sealed double rateFactor,private final non-sealed java.lang.String rateUnit,private final non-sealed io.dropwizard.metrics.MetricRegistry registry
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/influxdb/TimeUtils.java
|
TimeUtils
|
toTimePrecision
|
class TimeUtils {
/**
* Convert from a TimeUnit to a influxDB timeunit String.
*
* @param t time unit
* @return the String representation.
*/
public static String toTimePrecision(final TimeUnit t) {<FILL_FUNCTION_BODY>}
}
|
switch (t) {
case HOURS:
return "h";
case MINUTES:
return "m";
case SECONDS:
return "s";
case MILLISECONDS:
return "ms";
case MICROSECONDS:
return "u";
case NANOSECONDS:
return "n";
default:
EnumSet<TimeUnit> allowedTimeunits = EnumSet.of(
TimeUnit.HOURS,
TimeUnit.MINUTES,
TimeUnit.SECONDS,
TimeUnit.MILLISECONDS,
TimeUnit.MICROSECONDS,
TimeUnit.NANOSECONDS);
throw new IllegalArgumentException("time precision must be one of:" + allowedTimeunits);
}
| 79
| 205
| 284
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/influxdb/data/InfluxDbPoint.java
|
InfluxDbPoint
|
toString
|
class InfluxDbPoint {
private String measurement;
private Map<String, String> tags = Collections.emptyMap();
private long timestamp;
private String value;
public InfluxDbPoint(final String measurement, final long timestamp, final String value) {
this.measurement = measurement;
this.timestamp = timestamp;
this.value = value;
}
public InfluxDbPoint(final String measurement, final Map<String, String> tags, final long timestamp, final String value) {
this.measurement = measurement;
this.timestamp = timestamp;
this.value = value;
this.tags = tags;
}
public String getMeasurement() {
return measurement;
}
public void setMeasurement(String measurement) {
this.measurement = measurement;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
static public String map2String(final Map<String, String> tags) {
if(tags != null && !tags.isEmpty()) {
StringJoiner joined = new StringJoiner(",");
for (Object o : tags.entrySet()) {
Map.Entry pair = (Map.Entry) o;
joined.add(pair.getKey() + "=" + pair.getValue());
}
return joined.toString();
} else {
return "";
}
}
}
|
String t = map2String(tags);
return measurement +
(t.length() > 0? "," + t : "") +
" value=" + value +
" " + timestamp;
| 484
| 53
| 537
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics-config/src/main/java/io/dropwizard/metrics/influxdb/data/InfluxDbWriteObject.java
|
InfluxDbWriteObject
|
toTimePrecision
|
class InfluxDbWriteObject {
private String precision;
private Set<InfluxDbPoint> points;
private Map<String, String> tags = Collections.emptyMap();
public InfluxDbWriteObject(final TimeUnit timeUnit) {
this.points = new HashSet<>();
this.precision = toTimePrecision(timeUnit);
}
private static String toTimePrecision(TimeUnit t) {<FILL_FUNCTION_BODY>}
public String getPrecision() {
return precision;
}
public void setPrecision(String precision) {
this.precision = precision;
}
public Set<InfluxDbPoint> getPoints() {
return points;
}
public void setPoints(Set<InfluxDbPoint> points) {
this.points = points;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = Collections.unmodifiableMap(tags);
}
public String getBody() {
StringJoiner joiner = new StringJoiner("\n");
for (Object point : points) {
joiner.add(point.toString());
}
return joiner.toString();
}
}
|
switch (t) {
case HOURS:
return "h";
case MINUTES:
return "m";
case SECONDS:
return "s";
case MILLISECONDS:
return "ms";
case MICROSECONDS:
return "u";
case NANOSECONDS:
return "n";
default:
throw new IllegalArgumentException(
"time precision should be HOURS OR MINUTES OR SECONDS or MILLISECONDS or MICROSECONDS OR NANOSECONDS");
}
| 339
| 149
| 488
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics/src/main/java/com/networknt/metrics/APMMetricsHandler.java
|
APMMetricsHandler
|
handleRequest
|
class APMMetricsHandler extends AbstractMetricsHandler {
static final Logger logger = LoggerFactory.getLogger(APMMetricsHandler.class);
public static ServerConfig serverConfig;
// this is the indicator to start the reporter and construct the common tags. It cannot be static as
// the currentPort and currentAddress are not available during the handler initialization.
private boolean firstTime = true;
private volatile HttpHandler next;
public APMMetricsHandler() {
config = MetricsConfig.load();
if(config.getIssuerRegex() != null) {
pattern = Pattern.compile(config.getIssuerRegex());
}
serverConfig = ServerConfig.getInstance();
ModuleRegistry.registerModule(MetricsConfig.CONFIG_NAME, APMMetricsHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(MetricsConfig.CONFIG_NAME), null);
if(logger.isDebugEnabled()) logger.debug("APMMetricsHandler is constructed!");
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public HttpHandler getNext() {
return this.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(MetricsConfig.CONFIG_NAME, APMMetricsHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(MetricsConfig.CONFIG_NAME), null);
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(MetricsConfig.CONFIG_NAME, APMMetricsHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(MetricsConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("APMMetricsHandler is reloaded.");
}
}
|
if (firstTime) {
commonTags.put("api", ServerConfig.getInstance().getServiceId());
commonTags.put("env", ServerConfig.getInstance().getEnvironment());
commonTags.put("addr", Server.currentAddress);
commonTags.put("port", "" + (ServerConfig.getInstance().isEnableHttps() ? Server.currentHttpsPort : Server.currentHttpPort));
InetAddress inetAddress = Util.getInetAddress();
commonTags.put("host", inetAddress == null ? "unknown" : inetAddress.getHostName()); // will be container id if in docker.
if (logger.isDebugEnabled()) {
logger.debug(commonTags.toString());
}
try {
TimeSeriesDbSender sender =
new APMEPAgentSender(config.getServerProtocol(), config.getServerHost(), config.getServerPort(), config.getServerPath(), serverConfig.getServiceId(), config.getProductName());
APMAgentReporter reporter = APMAgentReporter
.forRegistry(registry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.build(sender);
reporter.start(config.getReportInMinutes(), TimeUnit.MINUTES);
logger.info("apmmetrics is enabled and reporter is started");
} catch (MalformedURLException e) {
logger.error("apmmetrics has failed to initialize APMEPAgentSender", e);
}
// reset the flag so that this block will only be called once.
firstTime = false;
}
long startTime = Clock.defaultClock().getTick();
exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
Map<String, Object> auditInfo = exchange1.getAttachment(AttachmentConstants.AUDIT_INFO);
if(logger.isTraceEnabled()) logger.trace("auditInfo = " + auditInfo);
if (auditInfo != null && !auditInfo.isEmpty()) {
Map<String, String> tags = new HashMap<>();
tags.put("endpoint", (String) auditInfo.get(Constants.ENDPOINT_STRING));
String clientId = auditInfo.get(Constants.CLIENT_ID_STRING) != null ? (String) auditInfo.get(Constants.CLIENT_ID_STRING) : "unknown";
if(logger.isTraceEnabled()) logger.trace("clientId = " + clientId);
tags.put("clientId", clientId);
// scope client id will only be available if two token is used. For example, authorization code flow.
if (config.isSendScopeClientId()) {
tags.put("scopeClientId", auditInfo.get(Constants.SCOPE_CLIENT_ID_STRING) != null ? (String) auditInfo.get(Constants.SCOPE_CLIENT_ID_STRING) : "unknown");
}
// caller id is the calling serviceId that is passed from the caller. It is not always available but some organizations enforce it.
if (config.isSendCallerId()) {
tags.put("callerId", auditInfo.get(Constants.CALLER_ID_STRING) != null ? (String) auditInfo.get(Constants.CALLER_ID_STRING) : "unknown");
}
if (config.isSendIssuer()) {
String issuer = (String) auditInfo.get(Constants.ISSUER_CLAIMS);
if (issuer != null) {
// we need to send issuer as a tag. Do we need to apply regex to extract only a part of the issuer?
if(config.getIssuerRegex() != null) {
Matcher matcher = pattern.matcher(issuer);
if (matcher.find()) {
String iss = matcher.group(1);
if(logger.isTraceEnabled()) logger.trace("Extracted issuer {} from Original issuer {] is sent.", iss, issuer);
tags.put("issuer", iss != null ? iss : "unknown");
}
} else {
if(logger.isTraceEnabled()) logger.trace("Original issuer {} is sent.", issuer);
tags.put("issuer", issuer);
}
}
}
MetricName metricName = new MetricName("response_time");
metricName = metricName.tagged(commonTags);
metricName = metricName.tagged(tags);
long time = Clock.defaultClock().getTick() - startTime;
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.TIMERS).update(time, TimeUnit.NANOSECONDS);
if(logger.isTraceEnabled()) logger.trace("metricName = " + metricName + " commonTags = " + JsonMapper.toJson(commonTags) + " tags = " + JsonMapper.toJson(tags));
incCounterForStatusCode(exchange1.getStatusCode(), commonTags, tags);
} else {
// when we reach here, it will be in light-gateway so no specification is loaded on the server and also the security verification is failed.
// we need to come up with the endpoint at last to ensure we have some meaningful metrics info populated.
logger.error("auditInfo is null or empty. Please move the path prefix handler to the top of the handler chain after metrics.");
}
nextListener.proceed();
});
Handler.next(exchange, next);
| 530
| 1,360
| 1,890
|
<methods>public void <init>() ,public void createJVMMetricsReporter(com.networknt.metrics.TimeSeriesDbSender) ,public void incCounterForStatusCode(int, Map<java.lang.String,java.lang.String>, Map<java.lang.String,java.lang.String>) ,public void injectMetrics(HttpServerExchange, long, java.lang.String, java.lang.String) ,public boolean isEnabled() <variables>public Map<java.lang.String,java.lang.String> commonTags,public static com.networknt.metrics.MetricsConfig config,static final Logger logger,static java.util.regex.Pattern pattern,public static final io.dropwizard.metrics.MetricRegistry registry
|
networknt_light-4j
|
light-4j/metrics/src/main/java/com/networknt/metrics/AbstractMetricsHandler.java
|
AbstractMetricsHandler
|
injectMetrics
|
class AbstractMetricsHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(AbstractMetricsHandler.class);
// The metrics.yml configuration that supports reload.
public static MetricsConfig config;
static Pattern pattern;
// The structure that collect all the metrics entries. Even others will be using this structure to inject.
public static final MetricRegistry registry = new MetricRegistry();
public Map<String, String> commonTags = new HashMap<>();
public AbstractMetricsHandler() {
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
public void createJVMMetricsReporter(final TimeSeriesDbSender sender) {
JVMMetricsDbReporter jvmReporter = new JVMMetricsDbReporter(new MetricRegistry(), sender, "jvm-reporter",
MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, commonTags);
jvmReporter.start(config.getReportInMinutes(), TimeUnit.MINUTES);
}
public void incCounterForStatusCode(int statusCode, Map<String, String> commonTags, Map<String, String> tags) {
MetricName metricName = new MetricName("request").tagged(commonTags).tagged(tags);
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.COUNTERS).inc();
if (statusCode >= 200 && statusCode < 400) {
metricName = new MetricName("success").tagged(commonTags).tagged(tags);
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.COUNTERS).inc();
} else if (statusCode == 401 || statusCode == 403) {
metricName = new MetricName("auth_error").tagged(commonTags).tagged(tags);
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.COUNTERS).inc();
} else if (statusCode >= 400 && statusCode < 500) {
metricName = new MetricName("request_error").tagged(commonTags).tagged(tags);
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.COUNTERS).inc();
} else if (statusCode >= 500) {
metricName = new MetricName("server_error").tagged(commonTags).tagged(tags);
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.COUNTERS).inc();
}
}
/**
* This is the method that is used for all other handlers to inject its metrics info to the real metrics handler impl.
*
* @param httpServerExchange the HttpServerExchange that is used to get the auditInfo to collect the metrics tag.
* @param startTime the start time passed in to calculate the response time.
* @param metricsName the name of the metrics that is collected.
* @param endpoint the endpoint that is used to collect the metrics. It is optional and only provided by the external handlers.
*/
public void injectMetrics(HttpServerExchange httpServerExchange, long startTime, String metricsName, String endpoint) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> auditInfo = httpServerExchange.getAttachment(AttachmentConstants.AUDIT_INFO);
if(logger.isTraceEnabled()) logger.trace("auditInfo = " + auditInfo);
Map<String, String> tags = new HashMap<>();
if (auditInfo != null) {
// for external handlers, the endpoint must be unknown in the auditInfo. If that is the case, use the endpoint passed in.
if (endpoint != null) {
tags.put(Constants.ENDPOINT_STRING, endpoint);
} else {
tags.put(Constants.ENDPOINT_STRING, (String) auditInfo.get(Constants.ENDPOINT_STRING));
}
String clientId = auditInfo.get(Constants.CLIENT_ID_STRING) != null ? (String) auditInfo.get(Constants.CLIENT_ID_STRING) : "unknown";
if(logger.isTraceEnabled()) logger.trace("clientId = " + clientId);
tags.put("clientId", clientId);
// scope client id will only be available if two token is used. For example, authorization code flow.
if (config.isSendScopeClientId()) {
tags.put("scopeClientId", auditInfo.get(Constants.SCOPE_CLIENT_ID_STRING) != null ? (String) auditInfo.get(Constants.SCOPE_CLIENT_ID_STRING) : "unknown");
}
// caller id is the calling serviceId that is passed from the caller. It is not always available but some organizations enforce it.
if (config.isSendCallerId()) {
tags.put("callerId", auditInfo.get(Constants.CALLER_ID_STRING) != null ? (String) auditInfo.get(Constants.CALLER_ID_STRING) : "unknown");
}
if (config.isSendIssuer()) {
String issuer = (String) auditInfo.get(Constants.ISSUER_CLAIMS);
if (issuer != null) {
// we need to send issuer as a tag. Do we need to apply regex to extract only a part of the issuer?
if(config.getIssuerRegex() != null) {
Matcher matcher = pattern.matcher(issuer);
if (matcher.find()) {
String iss = matcher.group(1);
if(logger.isTraceEnabled()) logger.trace("Extracted issuer {} from Original issuer {] is sent.", iss, issuer);
tags.put("issuer", iss != null ? iss : "unknown");
}
} else {
if(logger.isTraceEnabled()) logger.trace("Original issuer {} is sent.", issuer);
tags.put("issuer", issuer);
}
}
}
} else {
// for MRAS and Salesforce handlers that do not have auditInfo in the exchange as they may be called anonymously.
tags.put(Constants.ENDPOINT_STRING, endpoint == null ? "unknown" : endpoint);
tags.put("clientId", "unknown");
if (config.isSendScopeClientId()) {
tags.put("scopeClientId", "unknown");
}
if (config.isSendCallerId()) {
tags.put("callerId", "unknown");
}
if (config.isSendIssuer()) {
tags.put("issuer", "unknown");
}
}
MetricName metricName = new MetricName(metricsName);
metricName = metricName.tagged(commonTags);
metricName = metricName.tagged(tags);
long time = System.nanoTime() - startTime;
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.TIMERS).update(time, TimeUnit.NANOSECONDS);
if(logger.isTraceEnabled()) logger.trace("metricName = " + metricName + " commonTags = " + JsonMapper.toJson(commonTags) + " tags = " + JsonMapper.toJson(tags));
// the metrics handler will collect the status code metrics and increase the counter. Here we don't want to increase it again.
// incCounterForStatusCode(httpServerExchange.getStatusCode(), commonTags, tags);
| 807
| 1,041
| 1,848
|
<no_super_class>
|
networknt_light-4j
|
light-4j/metrics/src/main/java/com/networknt/metrics/MetricsHandler.java
|
MetricsHandler
|
handleRequest
|
class MetricsHandler extends AbstractMetricsHandler {
static final Logger logger = LoggerFactory.getLogger(MetricsHandler.class);
// this is the indicator to start the reporter and construct the common tags. It cannot be static as
// the currentPort and currentAddress are not available during the handler initialization.
private boolean firstTime = true;
static String MASK_KEY_SERVER_PASS= "serverPass";
private volatile HttpHandler next;
public MetricsHandler() {
config = MetricsConfig.load();
if(config.getIssuerRegex() != null) {
pattern = Pattern.compile(config.getIssuerRegex());
}
ModuleRegistry.registerModule(MetricsConfig.CONFIG_NAME, MetricsHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(MetricsConfig.CONFIG_NAME), List.of(MASK_KEY_SERVER_PASS));
if(logger.isDebugEnabled()) logger.debug("MetricsHandler is constructed!");
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void register() {
ModuleRegistry.registerModule(MetricsConfig.CONFIG_NAME, MetricsHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(MetricsConfig.CONFIG_NAME), List.of(MASK_KEY_SERVER_PASS));
}
@Override
public void reload() {
config.reload();
ModuleRegistry.registerModule(MetricsConfig.CONFIG_NAME, MetricsHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(MetricsConfig.CONFIG_NAME), List.of(MASK_KEY_SERVER_PASS));
if(logger.isInfoEnabled()) logger.info("MetricsHandler is reloaded.");
}
@Override
public HttpHandler getNext() {
return this.next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
}
|
if(logger.isDebugEnabled()) logger.debug("MetricsHandler.handleRequest starts.");
if(firstTime) {
commonTags.put("api", ServerConfig.getInstance().getServiceId());
commonTags.put("env", ServerConfig.getInstance().getEnvironment());
commonTags.put("addr", Server.currentAddress);
commonTags.put("port", "" + (ServerConfig.getInstance().isEnableHttps() ? Server.currentHttpsPort : Server.currentHttpPort));
InetAddress inetAddress = Util.getInetAddress();
commonTags.put("host", inetAddress == null ? "unknown" : inetAddress.getHostName()); // will be container id if in docker.
if(logger.isDebugEnabled()) {
logger.debug(commonTags.toString());
}
try {
TimeSeriesDbSender influxDb =
new InfluxDbHttpSender(config.getServerProtocol(), config.getServerHost(), config.getServerPort(),
config.getServerName(), config.getServerUser(), config.getServerPass());
InfluxDbReporter reporter = InfluxDbReporter
.forRegistry(registry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.build(influxDb);
reporter.start(config.getReportInMinutes(), TimeUnit.MINUTES);
if (config.enableJVMMonitor) {
createJVMMetricsReporter(influxDb);
}
logger.info("metrics is enabled and reporter is started");
} catch (Exception e) {
// if there are any exception, chances are influxdb is not available.
logger.error("metrics is failed to connect to the influxdb", e);
}
// reset the flag so that this block will only be called once.
firstTime = false;
}
long startTime = Clock.defaultClock().getTick();
exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
try {
Map<String, Object> auditInfo = exchange1.getAttachment(AttachmentConstants.AUDIT_INFO);
if(auditInfo != null && !auditInfo.isEmpty()) {
Map<String, String> tags = new HashMap<>();
tags.put("endpoint", (String)auditInfo.get(Constants.ENDPOINT_STRING));
tags.put("clientId", auditInfo.get(Constants.CLIENT_ID_STRING) != null ? (String)auditInfo.get(Constants.CLIENT_ID_STRING) : "unknown");
tags.put("scopeClientId", auditInfo.get(Constants.SCOPE_CLIENT_ID_STRING) != null ? (String)auditInfo.get(Constants.SCOPE_CLIENT_ID_STRING) : "unknown");
tags.put("callerId", auditInfo.get(Constants.CALLER_ID_STRING) != null ? (String)auditInfo.get(Constants.CALLER_ID_STRING) : "unknown");
long time = Clock.defaultClock().getTick() - startTime;
MetricName metricName = new MetricName("response_time");
metricName = metricName.tagged(commonTags);
metricName = metricName.tagged(tags);
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.TIMERS).update(time, TimeUnit.NANOSECONDS);
incCounterForStatusCode(exchange1.getStatusCode(), commonTags, tags);
} else {
// when we reach here, it will be in light-gateway so no specification is loaded on the server and also the security verification is failed.
// we need to come up with the endpoint at last to ensure we have some meaningful metrics info populated.
logger.error("auditInfo is null or empty. Please move the path prefix handler to the top of the handler chain after metrics.");
}
} catch (Throwable e) {
logger.error("ExchangeListener throwable", e);
} finally {
nextListener.proceed();
}
});
if(logger.isDebugEnabled()) logger.debug("MetricsHandler.handleRequest ends.");
Handler.next(exchange, next);
| 522
| 1,060
| 1,582
|
<methods>public void <init>() ,public void createJVMMetricsReporter(com.networknt.metrics.TimeSeriesDbSender) ,public void incCounterForStatusCode(int, Map<java.lang.String,java.lang.String>, Map<java.lang.String,java.lang.String>) ,public void injectMetrics(HttpServerExchange, long, java.lang.String, java.lang.String) ,public boolean isEnabled() <variables>public Map<java.lang.String,java.lang.String> commonTags,public static com.networknt.metrics.MetricsConfig config,static final Logger logger,static java.util.regex.Pattern pattern,public static final io.dropwizard.metrics.MetricRegistry registry
|
networknt_light-4j
|
light-4j/monad-result/src/main/java/com/networknt/monad/Success.java
|
Success
|
toString
|
class Success<T> implements Result<T> {
public static final Result<Void> SUCCESS = new Success<>(null);
public static final Result OPTIONAL_SUCCESS = Success.ofOptional(null);
@SuppressWarnings("unchecked")
static <T> Result<Optional<T>> emptyOptional() {
return (Result<Optional<T>>) OPTIONAL_SUCCESS;
}
private final T result;
public static <T> Result<T> of(T result) {
return new Success<>(result);
}
public static <T> Result<Optional<T>> ofOptional(T result) {
return new Success<>(Optional.ofNullable(result));
}
private Success(T result) {
this.result = result;
}
@Override
public boolean isSuccess() {
return true;
}
@Override
public Status getError() {
throw new NoSuchElementException("There is no error in Success");
}
@Override
public T getResult() {
return result;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
final String value = result != null ? result.toString() : "";
return String.format("Success[%s]", value);
| 306
| 35
| 341
|
<no_super_class>
|
networknt_light-4j
|
light-4j/portal-registry/src/main/java/com/networknt/portal/registry/PortalRegistryHeartbeatManager.java
|
PortalRegistryHeartbeatManager
|
run
|
class PortalRegistryHeartbeatManager {
private static final Logger logger = LoggerFactory.getLogger(PortalRegistryHeartbeatManager.class);
private PortalRegistryClient client;
private String token;
// all serviceIds that need heart beats.
private ConcurrentHashSet<PortalRegistryService> services = new ConcurrentHashSet<>();
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 PortalRegistryHeartbeatManager(PortalRegistryClient 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>}
}, PortalRegistryConstants.SWITCHER_CHECK_CIRCLE,
PortalRegistryConstants.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 (PortalRegistryService service : services) {
try {
jobExecutor.execute(new HeartbeatJob(service, isPass));
} catch (RejectedExecutionException ree) {
logger.error("execute heartbeat job fail! serviceId:"
+ service.getServiceId() + " 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 service PortalRegistryService
*/
public void addHeartbeatService(PortalRegistryService service) {
services.add(service);
}
/**
* remove service,corresponding service won't send heart beat
*
* @param service PortalRegistryService
*/
public void removeHeartbeatService(PortalRegistryService service) {
services.remove(service);
}
// check if heart beat switcher is on
private boolean isHeartbeatOpen() {
return currentHeartBeatSwitcherStatus;
}
public void setHeartbeatOpen(boolean open) {
currentHeartBeatSwitcherStatus = open;
}
class HeartbeatJob implements Runnable {
private PortalRegistryService service;
private boolean isPass;
public HeartbeatJob(PortalRegistryService service, boolean isPass) {
super();
this.service = service;
this.isPass = isPass;
}
@Override
public void run() {
try {
if (isPass) {
client.checkPass(service, token);
} else {
client.checkFail(service, token);
}
} catch (Exception e) {
logger.error(
"portal controller heartbeat-set check pass error!serviceId:"
+ service.getServiceId(), e);
}
}
}
public void setClient(PortalRegistryClient 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 >= PortalRegistryConstants.MAX_SWITCHER_CHECK_TIMES) {
processHeartbeat(true);
switcherCheckTimes = 0;
}
}
}
} catch (Exception e) {
logger.error("consul heartbeat executor err:",
e);
}
| 1,087
| 281
| 1,368
|
<no_super_class>
|
networknt_light-4j
|
light-4j/portal-registry/src/main/java/com/networknt/portal/registry/PortalRegistryService.java
|
PortalRegistryService
|
toString
|
class PortalRegistryService {
static PortalRegistryConfig config = (PortalRegistryConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, PortalRegistryConfig.class);
private String serviceId;
private String name;
private String tag;
private String protocol;
private String address;
private int port;
private String healthPath;
private String checkString;
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHealthPath() {
return healthPath;
}
public void setHealthPath(String healthPath) {
this.healthPath = healthPath;
}
public String getCheckString() {
return checkString;
}
public void setCheckString(String checkString) {
this.checkString = checkString;
}
public PortalRegistryService() {
if(config.httpCheck) {
checkString = ",\"check\":{\"id\":\"%1$s:%2$s:%3$s:%4$s\",\"deregisterCriticalServiceAfter\":" + config.deregisterAfter + ",\"healthPath\":\"" + config.healthPath + "\",\"tlsSkipVerify\":true,\"interval\":" + config.checkInterval + "}}";
} else {
checkString = ",\"check\":{\"id\":\"%1$s:%2$s:%3$s:%4$s\",\"deregisterCriticalServiceAfter\":" + config.deregisterAfter + ",\"interval\":" + config.checkInterval + "}}";
}
}
/**
* Construct a register json payload. Note that deregister internal minimum is 1m.
*
* @return String
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String key = tag == null ? serviceId : serviceId + "|" + tag;
return "{\"serviceId\":\"" + serviceId +
"\",\"name\":\"" + name
+ (tag != null ? "\",\"tag\":\"" + tag : "")
+ "\",\"protocol\":\"" + protocol
+ "\",\"address\":\"" + address
+ "\",\"port\":" + port
+ String.format(checkString, key, protocol, address, port, serviceId);
| 695
| 132
| 827
|
<no_super_class>
|
networknt_light-4j
|
light-4j/portal-registry/src/main/java/com/networknt/portal/registry/PortalRegistryUtils.java
|
PortalRegistryUtils
|
buildUrl
|
class PortalRegistryUtils {
/**
* 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) {
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);
}
/**
* build consul service from url
*
* @param url a URL object
* @return service PortalRegistryService
*/
public static PortalRegistryService buildService(URL url) {
PortalRegistryService service = new PortalRegistryService();
service.setAddress(url.getHost());
service.setServiceId(convertPortalRegistrySerivceId(url));
service.setName(url.getPath());
service.setProtocol(url.getProtocol());
service.setPort(url.getPort());
String env = url.getParameter(Constants.TAG_ENVIRONMENT);
if(env != null) service.setTag(env);
return service;
}
/**
* build url from service
* @param serviceId the serviceId
* @param tag the optional tag
* @param service service object map
* @return URL object
*/
public static URL buildUrl(String serviceId, String tag, Map<String, Object> service) {<FILL_FUNCTION_BODY>}
/**
* 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 url to consul service id. serviceid includes ip+port+service
*
* @param url a URL object
* @return service id
*/
public static String convertPortalRegistrySerivceId(URL url) {
return 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(":"));
}
}
|
URL url = null;
if (url == null) {
Map<String, String> params = new HashMap<>();
if(tag != null) params.put(URLParamType.environment.getName(), tag);
url = new URLImpl((String)service.get("protocol"), (String)service.get("address"), (Integer)service.get("port"), serviceId, params);
}
return url;
| 677
| 104
| 781
|
<no_super_class>
|
networknt_light-4j
|
light-4j/portal-registry/src/main/java/com/networknt/portal/registry/client/PortalRegistryWebSocketClient.java
|
FutureNotifier
|
handleDone
|
class FutureNotifier extends IoFuture.HandlingNotifier<WebSocketChannel, Object> {
private PortalRegistryWebSocketClient client;
public FutureNotifier(PortalRegistryWebSocketClient client) {
this.client = client;
}
@Override
public void handleFailed(IOException exception, Object attachment) {
this.client.onError(exception);
}
@Override
public void handleDone(WebSocketChannel channel, Object attachment) {<FILL_FUNCTION_BODY>}
}
|
this.client.channel = channel;
this.client.onOpen();
channel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel ws, BufferedTextMessage message) throws IOException {
client.onMessage(message.getData());
}
@Override
protected void onError(WebSocketChannel ws, Throwable error) {
super.onError(ws, error);
client.onError(new Exception(error));
}
});
channel.resumeReceives();
channel.addCloseTask(ws -> client.onClose(ws.getCloseCode(), ws.getCloseReason()));
| 130
| 178
| 308
|
<no_super_class>
|
networknt_light-4j
|
light-4j/prometheus/src/main/java/com/networknt/metrics/prometheus/PrometheusGetHandler.java
|
PrometheusGetHandler
|
handleRequest
|
class PrometheusGetHandler implements LightHttpHandler {
static final Logger logger = LoggerFactory.getLogger(PrometheusGetHandler.class);
static CollectorRegistry registry = CollectorRegistry.defaultRegistry;
public PrometheusGetHandler(){}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, registry.metricFamilySamples());
} catch (IOException e) {
logger.error("error on put result:", e);
}
exchange.getResponseSender().send(writer.toString());
| 99
| 79
| 178
|
<no_super_class>
|
networknt_light-4j
|
light-4j/prometheus/src/main/java/com/networknt/metrics/prometheus/PrometheusHandler.java
|
PrometheusHandler
|
handleRequest
|
class PrometheusHandler implements MiddlewareHandler {
public static final String CONFIG_NAME = "prometheus";
public static PrometheusConfig config =(PrometheusConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, PrometheusConfig.class);
private CollectorRegistry registry;
static final Logger logger = LoggerFactory.getLogger(PrometheusHandler.class);
private volatile HttpHandler next;
private final ConcurrentMap<String, Counter> counters = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Summary> response_times = new ConcurrentHashMap<>();
public static final String REQUEST_TOTAL = "requests_total";
public static final String SUCCESS_TOTAL = "success_total";
public static final String AUTO_ERROR_TOTAL = "auth_error_total";
public static final String REQUEST_ERROR_TOTAL = "request_error_total";
public static final String SERVER_ERROR_TOTAL = "server_error_total";
public static final String RESPONSE_TIME_SECOND = "response_time_seconds";
public PrometheusHandler() {
registry= CollectorRegistry.defaultRegistry;
}
@Override
public HttpHandler getNext() {
return this.next;
}
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
Handlers.handlerNotNull(next);
this.next = next;
return this;
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
public void register() {
ModuleRegistry.registerModule(PrometheusConfig.CONFIG_NAME, PrometheusHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(CONFIG_NAME), null);
}
@Override
public void reload() {
config =(PrometheusConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, PrometheusConfig.class);
}
private void incCounterForStatusCode(int statusCode, List<String> labels, List<String> labelValues) {
counter(REQUEST_TOTAL, labels).labels(labelValues.stream().toArray(String[]::new)).inc();
if(statusCode >= 200 && statusCode < 400) {
counter(SUCCESS_TOTAL , labels).labels(labelValues.stream().toArray(String[]::new)).inc();
} else if(statusCode == 401 || statusCode == 403) {
counter(AUTO_ERROR_TOTAL , labels).labels(labelValues.stream().toArray(String[]::new)).inc();
} else if(statusCode >= 400 && statusCode < 500) {
counter(REQUEST_ERROR_TOTAL , labels).labels(labelValues.stream().toArray(String[]::new)).inc();
} else if(statusCode >= 500) {
counter(SERVER_ERROR_TOTAL , labels).labels(labelValues.stream().toArray(String[]::new)).inc();
}
}
private Counter counter(String name, List<String> labels) {
String key = sanitizeName(name);
return counters.computeIfAbsent(key, k-> Counter.build().name(k).help(k).labelNames(labels.stream().toArray(String[]::new)).register(registry));
}
private Summary summary(String name, List<String> labels) {
String key = sanitizeName(name);
return response_times.computeIfAbsent(key, k-> Summary.build().name(k).help(k).labelNames(labels.stream().toArray(String[]::new)).register(registry));
}
private String sanitizeName(String name) {
return name.replaceAll("[^a-zA-Z0-9_:]", "_");
}
}
|
SimpleTimer respTimer = new SimpleTimer();
exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
try {
Map<String, Object> auditInfo = exchange1.getAttachment(AttachmentConstants.AUDIT_INFO);
if(auditInfo != null) {
Map<String, String> tags = new HashMap<>();
tags.put("endpoint", (String)auditInfo.get(Constants.ENDPOINT_STRING));
tags.put("clientId", auditInfo.get(Constants.CLIENT_ID_STRING) != null ? (String)auditInfo.get(Constants.CLIENT_ID_STRING) : "unknown");
// The tags can be empty in error cases.
if (!tags.isEmpty()) {
List<String> labels = new ArrayList<>(tags.keySet());
List<String> labelValues = new ArrayList<>(tags.values());
summary(RESPONSE_TIME_SECOND, labels).labels(labelValues.stream().toArray(String[]::new)).observe(respTimer.elapsedSeconds());
incCounterForStatusCode(exchange1.getStatusCode(), labels, labelValues);
if (config.enableHotspot) {
logger.info("Prometheus hotspot monitor enabled.");
DefaultExports.initialize();
}
} else {
logger.debug("Tags was empty. AuditInfo size " + auditInfo.size());
}
}
} catch (Throwable e) {
logger.error("ExchangeListener throwable", e);
} finally {
nextListener.proceed();
}
});
Handler.next(exchange, next);
| 1,015
| 416
| 1,431
|
<no_super_class>
|
networknt_light-4j
|
light-4j/proxy-handler/src/main/java/com/networknt/handler/config/UrlRewriteRule.java
|
UrlRewriteRule
|
convertToUrlRewriteRule
|
class UrlRewriteRule {
private static final Logger LOG = LoggerFactory.getLogger(UrlRewriteRule.class);
Pattern pattern;
String replace;
public UrlRewriteRule(Pattern pattern, String replace) {
this.pattern = pattern;
this.replace = replace;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
public String getReplace() {
return replace;
}
public void setReplace(String replace) {
this.replace = replace;
}
public static UrlRewriteRule convertToUrlRewriteRule(String s) {<FILL_FUNCTION_BODY>}
}
|
// make sure that the string has two parts and the first part can be compiled to a pattern.
var parts = StringUtils.split(s, ' ');
if (parts.length != 2) {
var error = "The URL rewrite rule " + s + " must have two parts";
if (LOG.isErrorEnabled())
LOG.error(error);
throw new ConfigException(error);
}
return new UrlRewriteRule(Pattern.compile(parts[0]), parts[1]);
| 201
| 131
| 332
|
<no_super_class>
|
networknt_light-4j
|
light-4j/proxy-handler/src/main/java/com/networknt/handler/thread/LightThreadExecutor.java
|
LightThreadExecutor
|
updateExchangeContext
|
class LightThreadExecutor implements Executor {
private final HttpServerExchange exchange;
public LightThreadExecutor(final HttpServerExchange exchange) {
this.exchange = exchange;
}
/**
* Updates thread MDC based on handler context map.
* We do not want to clear context beforehand because undertow might set context via worker thread (or io thread) beforehand.
*/
private void updateExchangeContext() {<FILL_FUNCTION_BODY>}
@Override
public void execute(Runnable command) {
this.updateExchangeContext();
command.run();
}
}
|
var context = this.exchange.getAttachment(AttachmentConstants.MDC_CONTEXT);
if (context != null)
for (var entry : context.entrySet())
MDC.put(entry.getKey(), entry.getValue());
| 157
| 65
| 222
|
<no_super_class>
|
networknt_light-4j
|
light-4j/rate-limit/src/main/java/com/networknt/limit/LimitHandler.java
|
LimitHandler
|
reload
|
class LimitHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(LimitHandler.class);
private volatile HttpHandler next;
private static RateLimiter rateLimiter;
private final LimitConfig config;
private static final ObjectMapper mapper = Config.getInstance().getMapper();
public LimitHandler() throws Exception{
config = LimitConfig.load();
logger.info("RateLimit started with key type:" + config.getKey().name());
rateLimiter = new RateLimiter(config);
}
/**
* This is a constructor for test cases only. Please don't use it.
*
* @param cfg limit config
* @throws Exception thrown when config is wrong.
*
*/
@Deprecated
public LimitHandler(LimitConfig cfg) throws Exception{
config = cfg;
logger.info("RateLimit started with key type:" + config.getKey().name());
rateLimiter = new RateLimiter(cfg);
}
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if(logger.isDebugEnabled()) logger.debug("LimitHandler.handleRequest starts.");
RateLimitResponse rateLimitResponse = rateLimiter.handleRequest(exchange, config.getKey());
if (rateLimitResponse.allow) {
if(logger.isDebugEnabled()) logger.debug("LimitHandler.handleRequest ends.");
Handler.next(exchange, next);
} else {
exchange.getResponseHeaders().add(new HttpString(Constants.RATELIMIT_LIMIT), rateLimitResponse.getHeaders().get(Constants.RATELIMIT_LIMIT));
exchange.getResponseHeaders().add(new HttpString(Constants.RATELIMIT_REMAINING), rateLimitResponse.getHeaders().get(Constants.RATELIMIT_REMAINING));
exchange.getResponseHeaders().add(new HttpString(Constants.RATELIMIT_RESET), rateLimitResponse.getHeaders().get(Constants.RATELIMIT_RESET));
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
int statusCode = config.getErrorCode()==0 ? HttpStatus.TOO_MANY_REQUESTS.value():config.getErrorCode();
exchange.setStatusCode(statusCode);
if(logger.isDebugEnabled()) logger.warn("LimitHandler.handleRequest ends with an error code {}", statusCode);
exchange.getResponseSender().send(mapper.writeValueAsString(rateLimitResponse));
}
}
@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(LimitConfig.CONFIG_NAME, LimitHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(LimitConfig.CONFIG_NAME), null);
}
@Override
public void reload() {<FILL_FUNCTION_BODY>}
}
|
config.reload();
try {
rateLimiter = new RateLimiter(config);
} catch (Exception e) {
logger.error("Failed to recreate RateLimiter with reloaded config.", e);
}
// after reload, we need to update the config in the module registry to ensure that server info returns the latest configuration.
ModuleRegistry.registerModule(LimitConfig.CONFIG_NAME, LimitHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(LimitConfig.CONFIG_NAME), null);
if(logger.isInfoEnabled()) logger.info("LimitHandler is reloaded.");
| 817
| 156
| 973
|
<no_super_class>
|
networknt_light-4j
|
light-4j/rate-limit/src/main/java/com/networknt/limit/RequestLimit.java
|
RequestLimit
|
handleRequest
|
class RequestLimit {
@SuppressWarnings("unused")
private volatile int requests;
private volatile int max;
private static final AtomicIntegerFieldUpdater<RequestLimit> requestsUpdater = AtomicIntegerFieldUpdater.newUpdater(RequestLimit.class, "requests");
public static LimitConfig config = (LimitConfig) Config.getInstance().getJsonObjectConfig(LimitConfig.CONFIG_NAME, LimitConfig.class);
/**
* The handler that will be invoked if the queue is full.
*/
private volatile HttpHandler failureHandler = new ResponseCodeHandler(config.getErrorCode());
private final Queue<SuspendedRequest> queue;
private final ExchangeCompletionListener COMPLETION_LISTENER = new ExchangeCompletionListener() {
@Override
public void exchangeEvent(final HttpServerExchange exchange, final NextListener nextListener) {
SuspendedRequest task = null;
boolean found = false;
while ((task = queue.poll()) != null) {
try {
task.exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
task.exchange.dispatch(task.next);
found = true;
break;
} catch (Throwable e) {
UndertowLogger.ROOT_LOGGER.error("Suspended request was skipped", e);
}
}
if (!found) {
decrementRequests();
}
nextListener.proceed();
}
};
public RequestLimit(int maximumConcurrentRequests) {
this(maximumConcurrentRequests, -1);
}
/**
* Construct a new instance. The maximum number of concurrent requests must be at least one.
*
* @param maximumConcurrentRequests the maximum concurrent requests
* @param queueSize The maximum number of requests to queue
*/
public RequestLimit(int maximumConcurrentRequests, int queueSize) {
if (maximumConcurrentRequests < 1) {
throw new IllegalArgumentException("Maximum concurrent requests must be at least 1");
}
max = maximumConcurrentRequests;
this.queue = new LinkedBlockingQueue<>(queueSize <= 0 ? Integer.MAX_VALUE : queueSize);
}
public void handleRequest(final HttpServerExchange exchange, final HttpHandler next) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Get the maximum concurrent requests.
*
* @return the maximum concurrent requests
*/
public int getMaximumConcurrentRequests() {
return max;
}
/**
* Set the maximum concurrent requests. The value must be greater than or equal to one.
*
* @param newMax the maximum concurrent requests
* @return max concurrent requests
*/
public int setMaximumConcurrentRequests(int newMax) {
if (newMax < 1) {
throw new IllegalArgumentException("Maximum concurrent requests must be at least 1");
}
int oldMax = this.max;
this.max = newMax;
if(newMax > oldMax) {
synchronized (this) {
while (!queue.isEmpty()) {
int oldVal, newVal;
do {
oldVal = requests;
if (oldVal >= max) {
return oldMax;
}
newVal = oldVal + 1;
} while (!requestsUpdater.compareAndSet(this, oldVal, newVal));
SuspendedRequest res = queue.poll();
res.exchange.dispatch(res.next);
}
}
}
return oldMax;
}
private void decrementRequests() {
requestsUpdater.decrementAndGet(this);
}
public HttpHandler getFailureHandler() {
return failureHandler;
}
public void setFailureHandler(HttpHandler failureHandler) {
this.failureHandler = failureHandler;
}
private static final class SuspendedRequest {
final HttpServerExchange exchange;
final HttpHandler next;
private SuspendedRequest(HttpServerExchange exchange, HttpHandler next) {
this.exchange = exchange;
this.next = next;
}
}
}
|
int oldVal, newVal;
do {
oldVal = requests;
if (oldVal >= max) {
exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
@Override
public void run() {
//we have to try again in the sync block
//we need to have already dispatched for thread safety reasons
synchronized (this) {
int oldVal, newVal;
do {
oldVal = requests;
if (oldVal >= max) {
if (!queue.offer(new SuspendedRequest(exchange, next))) {
Connectors.executeRootHandler(failureHandler, exchange);
}
return;
}
newVal = oldVal + 1;
} while (!requestsUpdater.compareAndSet(RequestLimit.this, oldVal, newVal));
exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
exchange.dispatch(next);
}
}
});
return;
}
newVal = oldVal + 1;
} while (!requestsUpdater.compareAndSet(this, oldVal, newVal));
exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
next.handleRequest(exchange);
| 1,067
| 313
| 1,380
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.