Java Code Examples for com.networknt.httpstring.AttachmentConstants

The following examples show how to use com.networknt.httpstring.AttachmentConstants. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: light-rest-4j   Source File: ValidatorHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    SwaggerOperation swaggerOperation = null;
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo != null) {
        swaggerOperation = (SwaggerOperation)auditInfo.get(Constants.SWAGGER_OPERATION_STRING);
    }
    if(swaggerOperation == null) {
        setExchangeStatus(exchange, STATUS_MISSING_SWAGGER_OPERATION);
        return;
    }

    Status status = requestValidator.validateRequest(requestPath, exchange, swaggerOperation);
    if(status != null) {
        exchange.setStatusCode(status.getStatusCode());
        status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\"));
        exchange.getResponseSender().send(status.toString());
        if(config.isLogError()) logger.error("ValidationError:" + status.toString());
        return;
    }
    Handler.next(exchange, next);
}
 
Example 2
Source Project: light-rest-4j   Source File: ValidatorHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    OpenApiOperation openApiOperation = null;
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo != null) {
        openApiOperation = (OpenApiOperation)auditInfo.get(Constants.OPENAPI_OPERATION_STRING);
    }
    if(openApiOperation == null) {
        setExchangeStatus(exchange, STATUS_MISSING_OPENAPI_OPERATION);
        return;
    }
    Status status = requestValidator.validateRequest(requestPath, exchange, openApiOperation);
    if(status != null) {
        setExchangeStatus(exchange, status);
        if(config.logError) logger.error("ValidationError:" + status.toString());
        return;
    }

    if(config.validateResponse) {
        validateResponse(exchange, openApiOperation);
    }
    Handler.next(exchange, next);
}
 
Example 3
Source Project: light-4j   Source File: MetricsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    long startTime = Clock.defaultClock().getTick();
    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        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");

            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);
        }
        nextListener.proceed();
    });
    
    Handler.next(exchange, next);
}
 
Example 4
Source Project: light-4j   Source File: LightHttpHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * There are situations that the downstream service returns an error status response and we just
 * want to bubble up to the caller and eventually to the original caller.
 *
 * @param exchange HttpServerExchange
 * @param status error status
 */
default void setExchangeStatus(HttpServerExchange exchange, Status status) {
    exchange.setStatusCode(status.getStatusCode());
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
    status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\"));
    exchange.getResponseSender().send(status.toString());
    StackTraceElement[] elements = Thread.currentThread().getStackTrace();
    logger.error(status.toString() + " at " + elements[2].getClassName() + "." + elements[2].getMethodName() + "(" + elements[2].getFileName() + ":" + elements[2].getLineNumber() + ")");
    // In normal case, the auditInfo shouldn't be null as it is created by OpenApiHandler with
    // endpoint and openapiOperation available. This handler will enrich the auditInfo.
    @SuppressWarnings("unchecked")
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo == null) {
        auditInfo = new HashMap<>();
        exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);
    }

    // save info for auditing purposes in case of an error
    if(auditOnError)
        auditInfo.put(Constants.STATUS, status);
    if(auditStackTrace) {
        auditInfo.put(Constants.STACK_TRACE, Arrays.toString(elements));
    }
}
 
Example 5
Source Project: light-rest-4j   Source File: SwaggerHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {

    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    final Optional<NormalisedPath> maybeApiPath = SwaggerHelper.findMatchingApiPath(requestPath);
    if (!maybeApiPath.isPresent()) {
        setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
        return;
    }

    final NormalisedPath swaggerPathString = maybeApiPath.get();
    final Path swaggerPath = SwaggerHelper.swagger.getPath(swaggerPathString.original());

    final HttpMethod httpMethod = HttpMethod.valueOf(exchange.getRequestMethod().toString());
    final Operation operation = swaggerPath.getOperationMap().get(httpMethod);

    if (operation == null) {
        setExchangeStatus(exchange, STATUS_METHOD_NOT_ALLOWED);
        return;
    }

    // This handler can identify the swaggerOperation and endpoint only. Other info will be added by JwtVerifyHandler.
    final SwaggerOperation swaggerOperation = new SwaggerOperation(swaggerPathString, swaggerPath, httpMethod, operation);
    String endpoint = swaggerPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
    Map<String, Object> auditInfo = new HashMap<>();
    auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
    auditInfo.put(Constants.SWAGGER_OPERATION_STRING, swaggerOperation);
    exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);

    Handler.next(exchange, next);
}
 
Example 6
Source Project: light-rest-4j   Source File: SwaggerHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/get", exchange -> exchange.getResponseSender().send("get"))
            .add(Methods.POST, "/v2/pet", exchange -> {
                Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
                if(auditInfo != null) {
                    exchange.getResponseSender().send("withAuditInfo");
                } else {
                    exchange.getResponseSender().send("withoutAuditInfo");
                }
            })
            .add(Methods.GET, "/v2/pet", exchange -> exchange.getResponseSender().send("get"));
}
 
Example 7
Source Project: light-rest-4j   Source File: OpenApiHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
    if (!maybeApiPath.isPresent()) {
        setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
        return;
    }

    final NormalisedPath openApiPathString = maybeApiPath.get();
    final Path path = OpenApiHelper.openApi3.getPath(openApiPathString.original());

    final String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
    final Operation operation = path.getOperation(httpMethod);

    if (operation == null) {
        setExchangeStatus(exchange, STATUS_METHOD_NOT_ALLOWED);
        return;
    }

    // This handler can identify the openApiOperation and endpoint only. Other info will be added by JwtVerifyHandler.
    final OpenApiOperation openApiOperation = new OpenApiOperation(openApiPathString, path, httpMethod, operation);
    
    try {
    	ParameterDeserializer.deserialize(exchange, openApiOperation);
    }catch (Throwable t) {// do not crash the handler
    	logger.error(t.getMessage(), t);
    }
    
    String endpoint = openApiPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
    Map<String, Object> auditInfo = new HashMap<>();
    auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
    auditInfo.put(Constants.OPENAPI_OPERATION_STRING, openApiOperation);
    exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);

    Handler.next(exchange, next);
}
 
Example 8
Source Project: light-rest-4j   Source File: OpenApiHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/pets", exchange -> exchange.getResponseSender().send("get"))
            .add(Methods.POST, "/v1/pets", exchange -> {
                Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
                if(auditInfo != null) {
                    exchange.getResponseSender().send("withAuditInfo");
                } else {
                    exchange.getResponseSender().send("withoutAuditInfo");
                }
            })
            .add(Methods.DELETE, "/v1/pets", exchange -> exchange.getResponseSender().send("deleted"));
}
 
Example 9
Source Project: light-4j   Source File: Http2Client.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Support API to API calls with scope token. The token is the original token from consumer and
 * the client credentials token of caller API is added from cache.
 *
 * This method is used in API to API call
 *
 * @param request the http request
 * @param exchange the http server exchange
 * @return Result
 */
public Result propagateHeaders(ClientRequest request, final HttpServerExchange exchange) {
    String token = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
    boolean injectOpenTracing = ClientConfig.get().isInjectOpenTracing();
    if(injectOpenTracing) {
        Tracer tracer = exchange.getAttachment(AttachmentConstants.EXCHANGE_TRACER);
        return populateHeader(request, token, tracer);
    } else {
        String tid = exchange.getRequestHeaders().getFirst(HttpStringConstants.TRACEABILITY_ID);
        String cid = exchange.getRequestHeaders().getFirst(HttpStringConstants.CORRELATION_ID);
        return populateHeader(request, token, cid, tid);
    }
}
 
Example 10
Source Project: light-4j   Source File: PrometheusHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    SimpleTimer respTimer = new SimpleTimer();

    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        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");

            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();
            }
        }
        nextListener.proceed();
    });

    Handler.next(exchange, next);
}
 
Example 11
Source Project: light-4j   Source File: JaegerHandler.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Extract the context, start and stop the span here.
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // get the path and method to construct the endpoint for the operation of tracing.
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    String endpoint = null;
    if(auditInfo != null) {
        endpoint = (String)auditInfo.get(Constants.ENDPOINT_STRING);
    } else {
        endpoint = exchange.getRequestPath() + "@" + exchange.getRequestMethod();
    }

    HeaderMap headerMap = exchange.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<>();
    for(HttpString key : headerMap.getHeaderNames()) {
        headers.put(key.toString(), headerMap.getFirst(key));
    }
    TextMap carrier = new TextMapAdapter(headers);

    // start the server span.
    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, carrier);
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(endpoint);
        } else {
            spanBuilder = tracer.buildSpan(endpoint).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(endpoint);
    }
    Span rootSpan = spanBuilder
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
            .withTag(Tags.PEER_HOSTNAME.getKey(), NetUtils.getLocalAddressByDatagram())
            .withTag(Tags.PEER_PORT.getKey(), Server.config.getHttpsPort())
            .start();
    tracer.activateSpan(rootSpan);
    // This can be retrieved in the business handler to add tags and logs for tracing.
    exchange.putAttachment(ROOT_SPAN, rootSpan);
    // The client module can use this to inject tracer.
    exchange.putAttachment(EXCHANGE_TRACER, tracer);

    // add an exchange complete listener to close the Root Span for the request.
    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        Span span = exchange1.getAttachment(ROOT_SPAN);
        if(span != null) {
            span.finish();
        }
        nextListener.proceed();
    });

    Handler.next(exchange, next);
}
 
Example 12
Source Project: light-4j   Source File: AuditHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    Map<String, Object> auditMap = new LinkedHashMap<>();
    final long start = System.currentTimeMillis();
    auditMap.put(TIMESTAMP, System.currentTimeMillis());

    // dump audit info fields according to config
    boolean needAuditData = auditInfo != null && auditConfig.hasAuditList();
    if(needAuditData) {
        auditFields(auditInfo, auditMap);
    }

    // dump headers field according to config
    if(auditConfig.hasHeaderList()) {
        auditHeader(exchange, auditMap);
    }

    if(auditConfig.isStatusCode() || auditConfig.isResponseTime()) {
        exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
            if (auditConfig.isStatusCode()) {
                auditMap.put(STATUS_CODE, exchange1.getStatusCode());
            }
            if (auditConfig.isResponseTime()) {
                auditMap.put(RESPONSE_TIME, System.currentTimeMillis() - start);
            }

            // add additional fields accumulated during the microservice execution
            // according to the config
            //Map<String, Object> auditInfo1 = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
            if(auditInfo != null) {
                if(auditConfig.getAuditList() != null && auditConfig.getAuditList().size() > 0) {
                    for(String name: auditConfig.getAuditList()) {
                        auditMap.putIfAbsent(name, auditInfo.get(name));
                    }
                }
            }

            try {
                // audit entries only is it is an error, if auditOnError flag is set
                if(auditConfig.isAuditOnError()) {
                    if (exchange1.getStatusCode() >= 400)
                        auditConfig.getAuditFunc().accept(Config.getInstance().getMapper().writeValueAsString(auditMap));
                } else {
                    auditConfig.getAuditFunc().accept(Config.getInstance().getMapper().writeValueAsString(auditMap));
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            nextListener.proceed();
        });
    } else {
        auditConfig.getAuditFunc().accept(auditConfig.getConfig().getMapper().writeValueAsString(auditMap));
    }
    next(exchange);
}