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

The following examples show how to use io.undertow.server.HttpServerExchange#isInIoThread() . 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: ServletAuthenticationCallHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
/**
 * 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 {
        if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
            src.getOriginalResponse().sendError(exchange.getStatusCode());
        } else {
            exchange.endExchange();
        }
    }
}
 
Example 2
Source File: UndertowIOHandler.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 3
Source File: WebManifestPath.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");

    Cookie primaryColor = exchange.getRequestCookies().get("PYX-Theme-Primary");
    if (primaryColor == null) {
        exchange.getResponseSender().send(baseManifestString);
    } else {
        JsonObject manifest = baseManifest.deepCopy();
        manifest.addProperty("theme_color", URLDecoder.decode(primaryColor.getValue(), "UTF-8"));
        exchange.getResponseSender().send(manifest.toString());
    }
}
 
Example 4
Source File: ServletAuthenticationCallHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 {
        if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
            ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
            src.getOriginalResponse().sendError(exchange.getStatusCode());
        } else {
            exchange.endExchange();
        }
    }
}
 
Example 5
Source File: TwitterStartAuthFlowPath.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    try {
        OAuth1RequestToken token = helper.requestToken();
        CookieImpl cookie = new CookieImpl("PYX-Twitter-Token", token.getRawResponse());
        cookie.setMaxAge(COOKIE_MAX_AGE);
        exchange.setResponseCookie(cookie);
        exchange.getResponseHeaders().add(Headers.LOCATION, helper.authorizationUrl(token) + "&force_login=false");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } catch (Throwable ex) {
        logger.error("Failed processing the request." + exchange, ex);
        throw ex;
    }
}
 
Example 6
Source File: ServletInitialHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: BodyHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Check the header starts with application/json and parse it into map or list
 * based on the first character "{" or "[". Otherwise, check the header starts
 * with application/x-www-form-urlencoded or multipart/form-data and parse it
 * into formdata
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // parse the body to map or list if content type is application/json
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType != null) {
        if (exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }
        exchange.startBlocking();
        try {
            if (contentType.startsWith("application/json")) {
                InputStream inputStream = exchange.getInputStream();
                String unparsedRequestBody = StringUtils.inputStreamToString(inputStream, StandardCharsets.UTF_8);
                // attach the unparsed request body into exchange if the cacheRequestBody is enabled in body.yml
                if (config.isCacheRequestBody()) {
                    exchange.putAttachment(REQUEST_BODY_STRING, unparsedRequestBody);
                }
                // attach the parsed request body into exchange if the body parser is enabled
                attachJsonBody(exchange, unparsedRequestBody);
            } else if (contentType.startsWith("multipart/form-data") || contentType.startsWith("application/x-www-form-urlencoded")) {
                // attach the parsed request body into exchange if the body parser is enabled
                attachFormDataBody(exchange);
            }
        } catch (IOException e) {
            logger.error("IOException: ", e);
            setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, contentType);
            return;
        }
    }
    Handler.next(exchange, next);
}
 
Example 8
Source File: CacheRefreshHandler.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    realmCache.refresh();
    exchange.setStatusCode(204);
    exchange.getResponseSender().send("");

}
 
Example 9
Source File: HealthCheckHandler.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@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 10
Source File: DispatcherHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if ( (RequestUtils.isPostPutPatch(exchange) || this.blocking) && exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final Attachment attachment = Attachment.build()
        .withControllerInstance(Application.getInstance(this.controllerClass))
        .withControllerClass(this.controllerClass)
        .withControllerClassName(this.controllerClassName)
        .withControllerMethodName(this.controllerMethodName)
        .withClassAnnotations(this.classAnnotations)
        .withMethodAnnotations(this.methodAnnotations)
        .withMethodParameters(this.methodParameters)
        .withMethod(this.method)
        .withMethodParameterCount(this.methodParametersCount)
        .withRequestFilter(this.requestFilter)
        .withRequestParameter(RequestUtils.getRequestParameters(exchange))
        .withMessages(this.messages)
        .withLimit(this.limit)
        .withAuthentication(this.authentication)
        .withAuthorization(this.authorization)
        .withBasicAuthentication(this.username, this.password)
        .withTemplateEngine(this.templateEngine);

    exchange.putAttachment(RequestUtils.getAttachmentKey(), attachment);
    nextHandler(exchange);
}
 
Example 11
Source File: HTTPHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);  // in io handler form parser will dispatch to current io thread
        return;
    }

    handle(exchange);
}
 
Example 12
Source File: VersionPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(json);
}
 
Example 13
Source File: BlockingHandler.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.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(handler);
    } else {
        handler.handleRequest(exchange);
    }
}
 
Example 14
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HttpString method = exchange.getRequestMethod();
    if(!handlesMethod(method)) {
        next.handleRequest(exchange);
        return;
    }
    /*
     * Proxy the request that needs to be proxied and process others
     */
    // TODO maybe this should be handled outside here?
    final InetSocketAddress addr = exchange.getConnection().getLocalAddress(InetSocketAddress.class);
    if (!addr.isUnresolved() && addr.getPort() != config.getManagementSocketAddress().getPort() || !Arrays.equals(addr.getAddress().getAddress(), config.getManagementSocketAddress().getAddress().getAddress())) {
        next.handleRequest(exchange);
        return;
    }

    if(exchange.isInIoThread()) {
        //for now just do all the management stuff in a worker, as it uses blocking IO
        exchange.dispatch(this);
        return;
    }

    try {
        handleRequest(method, exchange);
    } catch (Exception e) {
        UndertowLogger.ROOT_LOGGER.failedToProcessManagementReq(e);
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
        final Sender sender = exchange.getResponseSender();
        sender.send("failed to process management request");
    }
}
 
Example 15
Source File: UndertowHttpHandler.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 16
Source File: HandleRequestInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) {
    if (isExceptionHandler(objInst)) {
        HttpServerExchange exchange = (HttpServerExchange) allArguments[0];

        if (Config.Plugin.Light4J.TRACE_HANDLER_CHAIN && !exchange.isInIoThread()) {
            ContextManager.stopSpan();
        }
    } else if (Config.Plugin.Light4J.TRACE_HANDLER_CHAIN && (isMiddlewareHandler(objInst) || isBusinessHandler(objInst))) {
        ContextManager.stopSpan();
    }
    return ret;
}
 
Example 17
Source File: UndertowServer.java    From openshift-ping with Apache License 2.0 5 votes vote down vote up
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 18
Source File: ServletInitialHandler.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 {
    final String path = exchange.getRelativePath();
    if(isForbiddenPath(path)) {
        exchange.setStatusCode(StatusCodes.NOT_FOUND);
        return;
    }
    final ServletPathMatch info = paths.getServletHandlerByPath(path);
    //https://issues.jboss.org/browse/WFLY-3439
    //if the request is an upgrade request then we don't want to redirect
    //as there is a good chance the web socket client won't understand the redirect
    //we make an exception for HTTP2 upgrade requests, as this would have already be handled at
    //the connector level if it was going to be handled.
    String upgradeString = exchange.getRequestHeaders().getFirst(Headers.UPGRADE);
    boolean isUpgradeRequest = upgradeString != null && !upgradeString.startsWith(HTTP2_UPGRADE_PREFIX);
    if (info.getType() == ServletPathMatch.Type.REDIRECT && !isUpgradeRequest) {
        //UNDERTOW-89
        //we redirect on GET requests to the root context to add an / to the end
        if(exchange.getRequestMethod().equals(Methods.GET) || exchange.getRequestMethod().equals(Methods.HEAD)) {
            exchange.setStatusCode(StatusCodes.FOUND);
        } else {
            exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
        }
        exchange.getResponseHeaders().put(Headers.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
        return;
    } else 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 19
Source File: UndertowKeycloakConsumer.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange httpExchange) throws Exception {
    if (shouldSkip(httpExchange.getRequestPath())) {
        super.handleRequest(httpExchange);
        return;
    }

    //perform only non-blocking operation on exchange
    if (httpExchange.isInIoThread()) {
        httpExchange.dispatch(this);
        return;
    }

    OIDCUndertowHttpFacade facade = new OIDCUndertowHttpFacade(httpExchange);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);

    if (deployment == null || !deployment.isConfigured()) {
        httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
        LOG.fine("deployment not configured");
        return;
    }

    LOG.fine("executing PreAuthActionsHandler");
    SessionManagementBridge bridge = new SessionManagementBridge(userSessionManagement, sessionManager);
    PreAuthActionsHandler preAuth = new PreAuthActionsHandler(bridge, deploymentContext, facade);
    if (preAuth.handleRequest()) return;

    SecurityContext securityContext = httpExchange.getSecurityContext();
    if (securityContext == null) {
        securityContext = new SecurityContextImpl(httpExchange, IDENTITY_MANAGER);
    }
    AdapterTokenStore tokenStore = getTokenStore(httpExchange, facade, deployment, securityContext);
    tokenStore.checkCurrentToken();

    LOG.fine("executing AuthenticatedActionsHandler");
    RequestAuthenticator authenticator = new UndertowRequestAuthenticator(facade, deployment, confidentialPort, securityContext, httpExchange, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();

    if (outcome == AuthOutcome.AUTHENTICATED) {
        LOG.fine("AUTHENTICATED");
        if (httpExchange.isResponseComplete()) {
            return;
        }
        AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, facade);
        if (actions.handledRequest()) {
            return;
        } else {
            final Account authenticatedAccount = securityContext.getAuthenticatedAccount();
            if (authenticatedAccount instanceof KeycloakUndertowAccount) {
                final KeycloakUndertowAccount kua = (KeycloakUndertowAccount) authenticatedAccount;
                httpExchange.putAttachment(KEYCLOAK_PRINCIPAL_KEY, (KeycloakPrincipal) kua.getPrincipal());
            }

            Set<String> roles = Optional
              .ofNullable(authenticatedAccount.getRoles())
              .orElse((Set<String>) Collections.EMPTY_SET);

            LOG.log(Level.FINE, "Allowed roles: {0}, current roles: {1}", new Object[] {allowedRoles, roles});

            if (isRoleAllowed(roles, httpExchange)) {
                super.handleRequest(httpExchange);
            } else {
                httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
            }

            return;
        }
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        LOG.fine("challenge");
        challenge.challenge(facade);
        return;
    }

    httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
}
 
Example 20
Source File: OcspHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }

    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();

    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build()
            .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));

    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);

    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }

    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();

        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }

    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption),
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);

    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL,
            responseBuilder.build(contentSigner, chain, new Date()));

    final byte[] responseBytes = response.getEncoded();

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}