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

The following examples show how to use io.undertow.server.HttpServerExchange#startBlocking() . 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: HttpContinue.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sends a continue response using blocking IO
 *
 * @param exchange The exchange
 */
public static void sendContinueResponseBlocking(final HttpServerExchange exchange) throws IOException {
    if (!exchange.isResponseChannelAvailable()) {
        throw UndertowMessages.MESSAGES.cannotSendContinueResponse();
    }
    if(exchange.getAttachment(ALREADY_SENT) != null) {
        return;
    }
    HttpServerExchange newExchange = exchange.getConnection().sendOutOfBandResponse(exchange);
    exchange.putAttachment(ALREADY_SENT, true);
    newExchange.setStatusCode(StatusCodes.CONTINUE);
    newExchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
    newExchange.startBlocking();
    newExchange.getOutputStream().close();
    newExchange.getInputStream().close();
}
 
Example 2
Source File: BinaryHandler.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    exchange.setStatusCode(this.response.getStatusCode());

    Server.headers()
        .entrySet()
        .stream()
        .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
        .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
    
    exchange.getResponseHeaders().put(Header.CONTENT_TYPE.toHttpString(), MediaType.OCTET_STREAM.withoutParameters().toString());
    exchange.getResponseHeaders().put(Header.CONTENT_DISPOSITION.toHttpString(), "inline; filename=" + this.response.getBinaryFileName());        
    this.response.getHeaders().forEach((key, value) -> exchange.getResponseHeaders().add(key, value));
    exchange.getOutputStream().write(this.response.getBinaryContent());
}
 
Example 3
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 4
Source File: FaviconErrorHandler.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private boolean writeFavicon(InputStream inputStream, HttpServerExchange exchange) throws IOException {
    if (inputStream != null) {
        exchange.startBlocking();
        OutputStream os = exchange.getOutputStream();
        byte[] buffer = new byte[1024];

        while (inputStream.read(buffer) > -1) {
            os.write(buffer);
        }

        exchange.endExchange();

        return true;
    }

    return false;
}
 
Example 5
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 6
Source File: TwitterCallbackPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: DomainApiUploadHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static void writeResponse(HttpServerExchange exchange, ModelNode response, String contentType) {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, contentType  + "; charset=" + Common.UTF_8);
    exchange.setStatusCode(200);

    //TODO Content-Length?
    exchange.startBlocking();

    PrintWriter print = new PrintWriter(exchange.getOutputStream());
    try {
        response.writeJSONString(print, true);
    } finally {
        IoUtils.safeClose(print);
    }
}
 
Example 8
Source File: RequestHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the complete request body from the request
 *
 * @param exchange The Undertow HttpServerExchange
 * @return A body object containing the request body
 *
 * @throws IOException
 */
protected String getRequestBody(HttpServerExchange exchange) throws IOException {
    String body = "";
    if (RequestUtils.isPostPutPatch(exchange)) {
        exchange.startBlocking();
        body = IOUtils.toString(exchange.getInputStream(), Default.ENCODING.toString());
    }

    return body;
}
 
Example 9
Source File: FormHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the form parameter from a request
 *
 * @param exchange The Undertow HttpServerExchange
 *
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
protected Form getForm(HttpServerExchange exchange) throws IOException {
    final Form form = Application.getInstance(Form.class);
    if (RequestUtils.isPostPutPatch(exchange)) {
        final Builder builder = FormParserFactory.builder();
        builder.setDefaultCharset(StandardCharsets.UTF_8.name());
        try (final FormDataParser formDataParser = builder.build().createParser(exchange)) {
            if (formDataParser != null) {
                exchange.startBlocking();
                final FormData formData = formDataParser.parseBlocking();
                for (String data : formData) {
                    Deque<FormValue> deque = formData.get(data);
                    if (deque != null) {
                        FormValue formValue = deque.element();
                        if (formValue != null) {
                            if (formValue.isFileItem() && formValue.getFileItem().getFile() != null) {
                                form.addFile(Files.newInputStream(formValue.getFileItem().getFile()));
                            } else {
                                if (data.contains("[]")) {
                                    String key = StringUtils.replace(data, "[]", "");
                                    for (Iterator iterator = deque.iterator(); iterator.hasNext();)  {
                                        form.addValueList(new HttpString(key).toString(), ((FormValue) iterator.next()).getValue());
                                    }
                                } else {
                                    form.addValue(new HttpString(data).toString(), formValue.getValue());
                                }
                            }    
                        }
                    }
                }
            }
        }
        
        form.setSubmitted(true);
    }

    return form;
}
 
Example 10
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 11
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 12
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 13
Source File: GithubCallbackPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    String code = Utils.extractParam(exchange, "code");
    if (code == null) {
        exchange.setStatusCode(StatusCodes.BAD_REQUEST);
        return;
    }

    try {
        String accessToken = githubHelper.exchangeCode(code);

        CookieImpl cookie = new CookieImpl("PYX-Github-Token", accessToken);
        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 14
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 15
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 16
Source File: ServletInitialHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void dispatchMockRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    final DefaultByteBufferPool bufferPool = new DefaultByteBufferPool(false, 1024, 0, 0);
    MockServerConnection connection = new MockServerConnection(bufferPool);
    HttpServerExchange exchange = new HttpServerExchange(connection);
    exchange.setRequestScheme(request.getScheme());
    exchange.setRequestMethod(new HttpString(request.getMethod()));
    exchange.setProtocol(Protocols.HTTP_1_0);
    exchange.setResolvedPath(request.getContextPath());
    String relative;
    if (request.getPathInfo() == null) {
        relative = request.getServletPath();
    } else {
        relative = request.getServletPath() + request.getPathInfo();
    }
    exchange.setRelativePath(relative);
    final ServletPathMatch info = paths.getServletHandlerByPath(request.getServletPath());
    final HttpServletResponseImpl oResponse = new HttpServletResponseImpl(exchange, servletContext);
    final HttpServletRequestImpl oRequest = new HttpServletRequestImpl(exchange, servletContext);
    final ServletRequestContext servletRequestContext = new ServletRequestContext(servletContext.getDeployment(), oRequest, oResponse, info);
    servletRequestContext.setServletRequest(request);
    servletRequestContext.setServletResponse(response);
    //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);

    try {
        dispatchRequest(exchange, servletRequestContext, info.getServletChain(), DispatcherType.REQUEST);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new ServletException(e);
    }
}
 
Example 17
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);
    }
}