Java Code Examples for io.undertow.server.HttpServerExchange#dispatch()
The following examples show how to use
io.undertow.server.HttpServerExchange#dispatch() .
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 |
@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: AsyncContextImpl.java From lams with GNU General Public License v2.0 | 6 votes |
public AsyncContextImpl(final HttpServerExchange exchange, final ServletRequest servletRequest, final ServletResponse servletResponse, final ServletRequestContext servletRequestContext, boolean requestSupplied, final AsyncContextImpl previousAsyncContext) { this.exchange = exchange; this.servletRequest = servletRequest; this.servletResponse = servletResponse; this.servletRequestContext = servletRequestContext; this.requestSupplied = requestSupplied; this.previousAsyncContext = previousAsyncContext; initiatingThread = Thread.currentThread(); exchange.dispatch(SameThreadExecutor.INSTANCE, new Runnable() { @Override public void run() { exchange.setDispatchExecutor(null); initialRequestDone(); } }); }
Example 3
Source File: AuthenticationCallHandler.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Only allow the request through if successfully authenticated or if authentication is not required. * * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange) */ @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if(exchange.isInIoThread()) { exchange.dispatch(this); return; } SecurityContext context = exchange.getSecurityContext(); if (context.authenticate()) { if(!exchange.isComplete()) { next.handleRequest(exchange); } } else { exchange.endExchange(); } }
Example 4
Source File: UndertowIOHandler.java From jweb-cms with GNU Affero General Public License v3.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } try { if (hasBody(exchange)) { RequestBodyParser reader = new RequestBodyParser(exchange, next); StreamSourceChannel channel = exchange.getRequestChannel(); reader.read(channel); if (!reader.complete()) { channel.getReadSetter().set(reader); channel.resumeReads(); return; } } exchange.dispatch(next); } catch (Throwable e) { if (exchange.isResponseChannelAvailable()) { exchange.setStatusCode(500); exchange.getResponseHeaders().add(new HttpString("Content-Type"), "text/plain"); exchange.getResponseSender().send(Exceptions.stackTrace(e)); } } }
Example 5
Source File: FormEncodedDataDefinition.java From quarkus-http with Apache License 2.0 | 6 votes |
@Override public void accept(InputChannel inputChannel, HttpServerExchange exchange) { while (inputChannel.isReadable()) { try { doParse(inputChannel.readAsync()); if (state == 4) { exchange.dispatch(SameThreadExecutor.INSTANCE, handler); return; } } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioExceptionReadingFromChannel(e); exchange.close(); } } exchange.getInputChannel().setReadHandler(this, exchange); }
Example 6
Source File: AuthenticationCallHandler.java From quarkus-http with Apache License 2.0 | 6 votes |
/** * Only allow the request through if successfully authenticated or if authentication is not required. * * @see io.undertow.server.HttpHandler#handleRequest(io.undertow.server.HttpServerExchange) */ @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if(exchange.isInIoThread()) { exchange.dispatch(this); return; } SecurityContext context = exchange.getSecurityContext(); if (context.authenticate()) { if(!exchange.isComplete()) { next.handleRequest(exchange); } } else { exchange.endExchange(); } }
Example 7
Source File: TwitterCallbackPath.java From PYX-Reloaded with Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.startBlocking(); if (exchange.isInIoThread()) { exchange.dispatch(this); return; } try { String token = Utils.extractParam(exchange, "oauth_token"); String verifier = Utils.extractParam(exchange, "oauth_verifier"); if (token == null || verifier == null) throw new IllegalArgumentException("Missing token or verifier!"); Cookie tokensCookie = exchange.getRequestCookies().get("PYX-Twitter-Token"); if (tokensCookie == null) throw new IllegalArgumentException("Missing 'PYX-Twitter-Token' cookie!"); List<NameValuePair> tokens = URLEncodedUtils.parse(tokensCookie.getValue(), Charset.forName("UTF-8")); if (!Objects.equals(token, Utils.get(tokens, "oauth_token"))) throw new IllegalStateException("Missing token in cookie or tokens don't match!"); String secret = Utils.get(tokens, "oauth_token_secret"); if (secret == null) throw new IllegalArgumentException("Missing token secret in cookie!"); OAuth1AccessToken accessToken = helper.accessToken(new OAuth1RequestToken(token, secret), verifier); CookieImpl cookie = new CookieImpl("PYX-Twitter-Token", accessToken.getRawResponse()); cookie.setMaxAge(COOKIE_MAX_AGE); exchange.setResponseCookie(cookie); exchange.getResponseHeaders().add(Headers.LOCATION, REDIRECT_LOCATION); exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT); } catch (Throwable ex) { logger.error("Failed processing the request: " + exchange, ex); throw ex; } }
Example 8
Source File: PathResource.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public void serveRangeAsync(OutputChannel outputStream, HttpServerExchange exchange, long start, long end) { //todo implement non blocking IO exchange.dispatch(new Runnable() { @Override public void run() { try { serveRangeBlocking(exchange.getOutputStream(), exchange, start, end); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); exchange.endExchange(); } } }); }
Example 9
Source File: RequestLimit.java From quarkus-http with Apache License 2.0 | 5 votes |
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 10
Source File: BlockingHandler.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(handler); } else { handler.handleRequest(exchange); } }
Example 11
Source File: TokenAuthenticator.java From hawkular-metrics with Apache License 2.0 | 5 votes |
/** * Called when the Kubernetes master server reponse has been inspected. */ private void onRequestResult(HttpServerExchange serverExchange, PooledConnection connection, boolean allowed) { connectionPools.get(serverExchange.getIoThread()).release(connection); // Remove attachment early to make it eligible for GC AuthContext context = serverExchange.removeAttachment(AUTH_CONTEXT_KEY); apiLatency.update(context.getClientResponseTime(), NANOSECONDS); authLatency.update(context.getLatency(), NANOSECONDS); if (allowed) { serverExchange.dispatch(containerHandler); } else { endExchange(serverExchange, FORBIDDEN); } }
Example 12
Source File: UndertowHttpHandler.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Handle the request. * * @param exchange the HTTP server exchange. * @throws Exception when a serious error occurs. */ @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } httpServerProcessor.process( new UndertowHttpRequest(exchange), new UndertowHttpResponse(exchange)); }
Example 13
Source File: ServletInitialHandler.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { final String path = exchange.getRelativePath(); if (isForbiddenPath(path)) { exchange.setStatusCode(StatusCodes.NOT_FOUND); return; } final ServletPathMatch info = paths.getServletHandlerByPath(path); if (info.getType() == ServletPathMatch.Type.REWRITE) { // this can only happen if the path ends with a / // otherwise there would be a redirect instead exchange.setRelativePath(info.getRewriteLocation()); exchange.setRequestPath(exchange.getResolvedPath() + info.getRewriteLocation()); } final HttpServletResponseImpl response = new HttpServletResponseImpl(exchange, servletContext); final HttpServletRequestImpl request = new HttpServletRequestImpl(exchange, servletContext); final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), request, response, info); //set the max request size if applicable if (info.getServletChain().getManagedServlet().getMaxRequestSize() > 0) { exchange.setMaxEntitySize(info.getServletChain().getManagedServlet().getMaxRequestSize()); } exchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext); exchange.startBlocking(new ServletBlockingHttpExchange(exchange)); servletRequestContext.setServletPathMatch(info); Executor executor = info.getServletChain().getExecutor(); if (executor == null) { executor = servletContext.getDeployment().getExecutor(); } if (exchange.isInIoThread() || executor != null) { //either the exchange has not been dispatched yet, or we need to use a special executor exchange.dispatch(executor, dispatchHandler); } else { dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST); } }
Example 14
Source File: UndertowServer.java From openshift-ping with Apache License 2.0 | 5 votes |
public void handleRequest(HttpServerExchange exchange) throws Exception { if(exchange.isInIoThread()) { exchange.dispatch(this); return; } exchange.startBlocking(); String clusterName = exchange.getRequestHeaders().getFirst(CLUSTER_NAME); JChannel channel = server.getChannel(clusterName); try (InputStream stream = exchange.getInputStream()) { handlePingRequest(channel, stream); } }
Example 15
Source File: NodePingUtil.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Try to open a socket connection to given address. * * @param address the socket address * @param exchange the http servers exchange * @param callback the ping callback * @param options the options */ static void pingHost(InetSocketAddress address, HttpServerExchange exchange, PingCallback callback, OptionMap options) { final XnioIoThread thread = exchange.getIoThread(); final XnioWorker worker = thread.getWorker(); final HostPingTask r = new HostPingTask(address, worker, callback, options); // Schedule timeout task scheduleCancelTask(exchange.getIoThread(), r, 5, TimeUnit.SECONDS); exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : thread, r); }
Example 16
Source File: HealthCheckHandler.java From bouncr with Eclipse Public License 1.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HealthCheckResponse response = HealthCheckResponse.builder() .name("bouncr-proxy") .up() .build(); exchange.setStatusCode(200); exchange.getResponseSender().send(mapper.writeValueAsString(response)); }
Example 17
Source File: BlockingHandler.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.startBlocking(); if (exchange.isInIoThread()) { exchange.dispatch(handler); } else { handler.handleRequest(exchange); } }
Example 18
Source File: HTTPIOHandler.java From core-ng-project with Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (HEALTH_CHECK_PATH.equals(exchange.getRequestPath())) { // not treat health-check as action exchange.endExchange(); // end exchange will send 200 / content-length=0 return; } boolean shutdown = shutdownHandler.handle(new Exchange(exchange)); if (shutdown) return; if (hasBody(exchange)) { // parse body early, not process until body is read (e.g. for chunked), to save one blocking thread during read FormDataParser parser = formParserFactory.createParser(exchange); if (parser != null) { parser.parse(handler); return; } var reader = new RequestBodyReader(exchange, handler); StreamSourceChannel channel = exchange.getRequestChannel(); reader.read(channel); // channel will be null if getRequestChannel() is already called, but here should not be that case if (!reader.complete()) { channel.getReadSetter().set(reader); channel.resumeReads(); return; } } exchange.dispatch(handler); }
Example 19
Source File: ExceptionHandler.java From light-4j with Apache License 2.0 | 4 votes |
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { // dispatch here to make sure that all exceptions will be capture in this handler // otherwise, some of the exceptions will be captured in Connectors class in Undertow // As we've updated Server.java to redirect the logs to slf4j but still it make sense // to handle the exception on our ExcpetionHandler. if (exchange.isInIoThread()) { exchange.dispatch(this); return; } try { Handler.next(exchange, next); } catch (Throwable e) { logger.error("Exception:", e); if(exchange.isResponseChannelAvailable()) { //handle exceptions if(e instanceof RuntimeException) { // check if it is FrameworkException which is subclass of RuntimeException. if(e instanceof FrameworkException) { FrameworkException fe = (FrameworkException)e; exchange.setStatusCode(fe.getStatus().getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(fe.getStatus().toString()); logger.error(fe.getStatus().toString(), e); } else { setExchangeStatus(exchange, STATUS_RUNTIME_EXCEPTION); } } else { if(e instanceof ApiException) { ApiException ae = (ApiException)e; exchange.setStatusCode(ae.getStatus().getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(ae.getStatus().toString()); logger.error(ae.getStatus().toString(), e); } else if(e instanceof ClientException){ ClientException ce = (ClientException)e; if(ce.getStatus().getStatusCode() == 0){ setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION); } else { exchange.setStatusCode(ce.getStatus().getStatusCode()); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(ce.getStatus().toString()); } } else { setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION); } } } } finally { // at last, clean the MDC. Most likely, correlationId in side. //logger.debug("Clear MDC"); MDC.clear(); } }
Example 20
Source File: UndertowHTTPHandler.java From cxf with Apache License 2.0 | 4 votes |
@Override public void handleRequest(HttpServerExchange undertowExchange) throws Exception { try { // perform blocking operation on exchange if (undertowExchange.isInIoThread()) { undertowExchange.dispatch(this); return; } HttpServletResponseImpl response = new HttpServletResponseImpl(undertowExchange, (ServletContextImpl)servletContext); HttpServletRequestImpl request = new HttpServletRequestImpl(undertowExchange, (ServletContextImpl)servletContext); if (request.getMethod().equals(METHOD_TRACE)) { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } ServletRequestContext servletRequestContext = new ServletRequestContext(((ServletContextImpl)servletContext) .getDeployment(), request, response, null); undertowExchange.putAttachment(ServletRequestContext.ATTACHMENT_KEY, servletRequestContext); request.setAttribute("HTTP_HANDLER", this); request.setAttribute("UNDERTOW_DESTINATION", undertowHTTPDestination); SSLSessionInfo ssl = undertowExchange.getConnection().getSslSessionInfo(); if (ssl != null) { request.setAttribute(SSL_CIPHER_SUITE_ATTRIBUTE, ssl.getCipherSuite()); try { request.setAttribute(SSL_PEER_CERT_CHAIN_ATTRIBUTE, ssl.getPeerCertificates()); } catch (Exception e) { // for some case won't have the peer certification // do nothing } } undertowHTTPDestination.doService(servletContext, request, response); } catch (Throwable t) { t.printStackTrace(); if (undertowExchange.isResponseChannelAvailable()) { undertowExchange.setStatusCode(500); final String errorPage = "<html><head><title>Error</title>" + "</head><body>Internal Error 500" + t.getMessage() + "</body></html>"; undertowExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, Integer.toString(errorPage.length())); undertowExchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html"); Sender sender = undertowExchange.getResponseSender(); sender.send(errorPage); } } }