Java Code Examples for io.undertow.server.HttpServerExchange#addExchangeCompleteListener()

The following examples show how to use io.undertow.server.HttpServerExchange#addExchangeCompleteListener() . 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 File: TokenAuthenticator.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange serverExchange) throws Exception {
    AuthContext context = AuthContext.initialize(serverExchange);
    serverExchange.putAttachment(AUTH_CONTEXT_KEY, context);
    // Make sure the exchange attachment is removed in the end
    serverExchange.addExchangeCompleteListener((exchange, nextListener) -> {
        exchange.removeAttachment(AUTH_CONTEXT_KEY);
        nextListener.proceed();
    });
    if (context.isMissingTenantHeader()) {
        endExchange(serverExchange, BAD_REQUEST, MISSING_HEADERS_MSG);
        return;
    }

    // Marks the request as dispatched. If we don't do this, the exchange will be terminated by the container when
    // this method returns, but we need to wait for Kubernetes' master response.
    serverExchange.dispatch();
    XnioIoThread ioThread = serverExchange.getIoThread();
    ConnectionPool connectionPool = connectionPools.computeIfAbsent(ioThread, t -> new ConnectionPool(connectionFactory, componentName));
    PooledConnectionWaiter waiter = createWaiter(serverExchange);
    if (!connectionPool.offer(waiter)) {
        endExchange(serverExchange, INTERNAL_SERVER_ERROR, TOO_MANY_PENDING_REQUESTS);
    }
}
 
Example 2
Source File: MetricsHandler.java    From light-4j with 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 3
Source File: LearningPushHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String fullPath;
    String requestPath;
    if(exchange.getQueryString().isEmpty()) {
        fullPath = exchange.getRequestURL();
        requestPath = exchange.getRequestPath();
    } else{
        fullPath = exchange.getRequestURL() + "?" + exchange.getQueryString();
        requestPath = exchange.getRequestPath() + "?" + exchange.getQueryString();
    }

    doPush(exchange, fullPath);
    String referrer = exchange.getRequestHeaders().getFirst(Headers.REFERER);
    if (referrer != null) {
        String accept = exchange.getRequestHeaders().getFirst(Headers.ACCEPT);
        if (accept == null || !accept.contains("text/html")) {
            //if accept contains text/html it generally means the user has clicked
            //a link to move to a new page, and is not a resource load for the current page
            //we only care about resources for the current page

            exchange.addExchangeCompleteListener(new PushCompletionListener(fullPath, requestPath, referrer));
        }
    }
    next.handleRequest(exchange);
}
 
Example 4
Source File: TracingHttpHandlerConfiguration.java    From pivotal-bank-demo with Apache License 2.0 6 votes vote down vote up
@Override public void handleRequest(HttpServerExchange exchange) throws Exception {
  if (!exchange.isComplete()) {
    Span span = serverHandler.handleReceive(extractor, exchange.getRequestHeaders(), exchange);
    exchange.addExchangeCompleteListener((exch, nextListener) -> {
      try {
        nextListener.proceed();
      } finally {
        serverHandler.handleSend(exch, exch.getAttachment(ExceptionHandler.THROWABLE), span);
      }
    });
    try (Scope scope = currentTraceContext.newScope(span.context())) {
      next.handleRequest(exchange);
    } catch (Exception | Error e) { // move the error to where the complete listener can see it
      exchange.putAttachment(ExceptionHandler.THROWABLE, e);
      throw e;
    }
  } else {
    next.handleRequest(exchange);
  }
}
 
Example 5
Source File: ManagementHttpRequestHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final boolean proceed = service.beginRequest();
    try {
        if (proceed) {
            next.handleRequest(exchange);
        } else {
            exchange.setStatusCode(503);
            exchange.endExchange();
        }
    } finally {
        if (proceed && (exchange.isComplete() || !exchange.isDispatched())) {
            service.endRequest();
        } else if (proceed) {
            exchange.addExchangeCompleteListener(listener);
        }
    }
}
 
Example 6
Source File: GracefulShutdownHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    activeRequestsUpdater.incrementAndGet(this);
    if (shutdown) {
        decrementRequests();
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
        return;
    }
    exchange.addExchangeCompleteListener(listener);
    next.handleRequest(exchange);
}
 
Example 7
Source File: RequestLimit.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void handleRequest(final HttpServerExchange exchange, final HttpHandler next) throws Exception {
    int oldVal, newVal;
    do {
        oldVal = requests;
        if (oldVal >= max) {
            exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() {
                @Override
                public void run() {
                    //we have to try again in the sync block
                    //we need to have already dispatched for thread safety reasons
                    synchronized (RequestLimit.this) {
                        int oldVal, newVal;
                        do {
                            oldVal = requests;
                            if (oldVal >= max) {
                                if (!queue.offer(new SuspendedRequest(exchange, next))) {
                                    Connectors.executeRootHandler(failureHandler, exchange);
                                }
                                return;
                            }
                            newVal = oldVal + 1;
                        } while (!requestsUpdater.compareAndSet(RequestLimit.this, oldVal, newVal));
                        exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
                        exchange.dispatch(next);
                    }
                }
            });
            return;
        }
        newVal = oldVal + 1;
    } while (!requestsUpdater.compareAndSet(this, oldVal, newVal));
    exchange.addExchangeCompleteListener(COMPLETION_LISTENER);
    next.handleRequest(exchange);
}
 
Example 8
Source File: MetricsHandler.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
  // Start counting request handling time
  long start = requestTimer.start();

  // Attach a listener to request completion event
  exchange.addExchangeCompleteListener((ex, nxt) -> {

    // Get the name of the final handler or our default string if it does not exist
    String handler = ex.getAttachment(REQUEST_HANDLER_KEY);
    if (handler == null) {
      handler = NO_HANDLER;
    }

    // Emit the duration of request processing, implicitly also produces request count
    requestTimer.stop(start,
        REQUEST_METHOD, ex.getRequestMethod().toString(),
        REQUEST_HANDLER, handler,
        STATUS_CODE, Integer.toString(ex.getStatusCode()));

    // Chain to next listener
    nxt.proceed();
  });

  // Let the next handler process the request
  next.handleRequest(exchange);
}
 
Example 9
Source File: UndertowServerHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void registerListeners(HttpServerExchange exchange) {
	exchange.addExchangeCompleteListener((ex, next) -> {
		onAllDataRead();
		next.proceed();
	});
	this.channel.getReadSetter().set(c -> onDataAvailable());
	this.channel.getCloseSetter().set(c -> onAllDataRead());
	this.channel.resumeReads();
}
 
Example 10
Source File: SessionAttachmentHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    exchange.putAttachment(SessionManager.ATTACHMENT_KEY, sessionManager);
    exchange.putAttachment(SessionConfig.ATTACHMENT_KEY, sessionConfig);
    final UpdateLastAccessTimeListener handler = new UpdateLastAccessTimeListener(sessionConfig, sessionManager);
    exchange.addExchangeCompleteListener(handler);
    next.handleRequest(exchange);

}
 
Example 11
Source File: DumpHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    if(isEnabled()) {
        Map<String, Object> result = new LinkedHashMap<>();
        //create rootDumper which will do dumping.
        RootDumper rootDumper = new RootDumper(config, exchange);
        //dump request info into result right away
        rootDumper.dumpRequest(result);
        //only add response wrapper when response config is not set to "false"
        if(config.isResponseEnabled()) {
            //set Conduit to the conduit chain to store response body
            exchange.addResponseWrapper((factory, exchange12) -> new StoreResponseStreamSinkConduit(factory.create(), exchange12));
        }
        //when complete exchange, dump response info to result, and log the result.
        exchange.addExchangeCompleteListener((exchange1, nextListener) ->{
            rootDumper.dumpResponse(result);
            //log the result
            DumpHelper.logResult(result, config);
            nextListener.proceed();
        });
    }
    Handler.next(exchange, next);
}
 
Example 12
Source File: MetricsHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (!exchange.isComplete()) {
        exchange.addExchangeCompleteListener(new MetricsListener(System.currentTimeMillis()));
    }
    this.nextHandler.handleRequest(exchange);
}
 
Example 13
Source File: RequestTimeLogger.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    TimeMeasurer timeMeasurer = new TimeMeasurer(this.timeThreshold);
    timeMeasurer.setStartTime(System.currentTimeMillis());
    exchange.addExchangeCompleteListener(timeMeasurer);
    next.handleRequest(exchange);
}
 
Example 14
Source File: PrometheusHandler.java    From light-4j with 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 15
Source File: ValidatorHandler.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private void validateResponse(HttpServerExchange exchange, OpenApiOperation openApiOperation) {
    exchange.addResponseWrapper((factory, exchange12) -> new StoreResponseStreamSinkConduit(factory.create(), exchange12));

    exchange.addExchangeCompleteListener((exchange1, nextListener) ->{
        Status status = responseValidator.validateResponse(exchange, openApiOperation);
        if(status != null) {
            logger.error("Response validation error: {} \n with response body: {}", status.getDescription(), new String(exchange.getAttachment(StoreResponseStreamSinkConduit.RESPONSE)));
        }
        nextListener.proceed();
    });
}
 
Example 16
Source File: UndertowServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void registerListeners(HttpServerExchange exchange) {
	exchange.addExchangeCompleteListener((ex, next) -> {
		onAllDataRead();
		next.proceed();
	});
	this.channel.getReadSetter().set(c -> onDataAvailable());
	this.channel.getCloseSetter().set(c -> onAllDataRead());
	this.channel.resumeReads();
}
 
Example 17
Source File: HttpErrorLoggerExtension.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.addExchangeCompleteListener(new HttpErrorExchangeCompleteListener());
    next.handleRequest(exchange);
}
 
Example 18
Source File: LogbackAccessUndertowHttpHandler.java    From logback-access-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.addExchangeCompleteListener(this::handleExchangeEvent);
    nextHandler.handleRequest(exchange);
}
 
Example 19
Source File: AccessLogHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    exchange.addExchangeCompleteListener(exchangeCompletionListener);
    next.handleRequest(exchange);
}
 
Example 20
Source File: AuditHandler.java    From light-4j with 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);
}