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.
*... |
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 ... |
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();
... | 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 DumperF... |
if(!dumpConfig.isResponseEnabled()) { return; }
Map<String, Object> responseResult = new LinkedHashMap<>();
for(IResponseDumpable dumper: dumperFactory.createResponseDumpers(dumpConfig, exchange)) {
if (dumper.isApplicableForResponse()) {
dumper.dumpResponse(respons... | 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 StoreResponseStreamSinkCond... |
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 = ... | 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>}
/**
* pu... |
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 = serv... | 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 stat... |
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.... | 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_B... |
// 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.
... | 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_... |
// 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(co... | 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() {
co... |
config.reload();
ModuleRegistry.registerModule(RouterConfig.CONFIG_NAME, RouterHandler.class.getName(), Config.getNoneDecryptedInstance().getJsonMapConfigNoCache(RouterConfig.CONFIG_NAME), null);
LoadBalancingRouterProxyClient client = new LoadBalancingRouterProxyClient();
if(config.htt... | 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 ... |
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 J... | 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... |
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... | 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";
... |
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("{")) {
... | 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");
co... |
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 serv... | 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);
prote... |
// 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 w... | 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";
... |
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);
... | 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 construct... |
String requestPath = exchange.getRequestURI();
String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
String[] serviceEntry = HandlerUtils.findServiceEntry(HandlerUtils.toInternalKey(httpMethod, requestPath), config.getMapping());
HeaderValues serviceIdHeader = excha... | 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... |
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", email... | 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... |
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.isTra... | 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>> requestEnco... |
ConduitWrapper<StreamSourceConduit> encodings = requestEncodings.get(exchange.getRequestHeaders().getFirst(Headers.CONTENT_ENCODING));
if (encodings != null && exchange.isRequestChannelAvailable()) {
exchange.addRequestWrapper(encodings);
// Nested handlers or even servlet filte... | 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, Ob... |
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.isTra... | 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 Co... |
AllowedContentEncodings encodings = contentEncodingRepository.getContentEncodings(exchange);
if (encodings == null || !exchange.isResponseChannelAvailable()) {
Handler.next(exchange, next);
} else if (encodings.isNoEncodingsAllowed()) {
setExchangeStatus(exchange, NO_ENC... | 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.c... |
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 ... | 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 pat... |
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 s... |
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();... | 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... |
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> ... | 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(HttpServ... |
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 setExchang... | 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 = "appli... |
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) {
... | 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 =... |
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 = (... | 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 Respons... |
// 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)) {
... | 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 th... |
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().rem... | 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";
privat... |
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)... | 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 confi... |
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 ReentrantReadWrite... |
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);
}
re... | 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);
}
... |
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 ... |
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<?> EM... |
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.toStr... |
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 ... |
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 ... | 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<St... |
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 !... | 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()) lo... |
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));
... | 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 = "enableHt... |
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 for... | 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 ... |
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";... |
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);
... | 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(... |
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.getDownstrea... | 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... |
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();... | 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";
... |
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) serverPat... | 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 ... |
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 = clie... | 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_FI... |
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 = mappedC... | 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 = LdapCo... |
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);
... | 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 = "downstrea... |
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 = getMap... | 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();... |
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.q... | 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) {
... |
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.M... |
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 MetricRegist... |
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 f... | 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.M... |
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.na... |
//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();
... | 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 = "... |
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 = mapped... | 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 timeou... |
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 Obje... | 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 /... |
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;
p... |
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 su... |
// 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 HdrHistogr... |
// 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 rese... |
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 ... |
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] = ... | 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... |
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;
p... |
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},... |
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 attributeN... |
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 ObjectNa... |
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 ... | 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}.
... |
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)",
runt... | 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 Lo... |
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)) {... | 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... |
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.getSecurityManage... |
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... | 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... |
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 r... | 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;
p... |
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.getV... | 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.M... |
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... |
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 (las... | 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 SlidingWindowR... |
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 AtomicIntegerF... |
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)... | 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();
... |
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... |
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... |
// 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;
... | 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... |
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... |
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... |
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 HttpClient... |
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, HttpMeth... | 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 InfluxDbWriteO... |
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>) h... | 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) {
... |
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()) {
report... | 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.M... |
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 NA... | 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.... |
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);
}
... |
switch (t) {
case HOURS:
return "h";
case MINUTES:
return "m";
case SECONDS:
return "s";
case MILLISECONDS:
return "ms";
case MICROSECONDS:
return "u";
case NA... | 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 cu... |
if (firstTime) {
commonTags.put("api", ServerConfig.getInstance().getServiceId());
commonTags.put("env", ServerConfig.getInstance().getEnvironment());
commonTags.put("addr", Server.currentAddress);
commonTags.put("port", "" + (ServerConfig.getInstance().isEnableH... | 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)... |
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 met... |
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... | 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 i... |
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.curre... | 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)... |
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... |
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 ConcurrentHa... |
// 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 chan... | 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;
... |
String key = tag == null ? serviceId : serviceId + "|" + tag;
return "{\"serviceId\":\"" + serviceId +
"\",\"name\":\"" + name
+ (tag != null ? "\",\"tag\":\"" + tag : "")
+ "\",\"protocol\":\"" + protocol
+ "\",\"address\":\"" + address
... | 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 && url... |
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"), serv... | 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 exc... |
this.client.channel = channel;
this.client.onOpen();
channel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel ws, BufferedTextMessage message) throws IOException {
... | 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 HttpServerE... |
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 ... |
SimpleTimer respTimer = new SimpleTimer();
exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
try {
Map<String, Object> auditInfo = exchange1.getAttachment(AttachmentConstants.AUDIT_INFO);
if(auditInfo != null) {
Map<Stri... | 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() {
... |
// 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.... | 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 ... |
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().ge... |
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 inf... | 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 = (LimitCon... |
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... | 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.