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

The following examples show how to use io.undertow.server.HttpServerExchange#isResponseChannelAvailable() . 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: 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 2
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 3
Source File: SimpleErrorPageHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean handleDefaultResponse(final HttpServerExchange exchange) {
    if (!exchange.isResponseChannelAvailable()) {
        return false;
    }
    Set<Integer> codes = responseCodes;
    if (codes == null ? exchange.getStatusCode() >= StatusCodes.BAD_REQUEST : codes.contains(Integer.valueOf(exchange.getStatusCode()))) {
        final String errorPage = "<html><head><title>Error</title></head><body>" + exchange.getStatusCode() + " - " + StatusCodes.getReason(exchange.getStatusCode()) + "</body></html>";
        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + errorPage.length());
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
        Sender sender = exchange.getResponseSender();
        sender.send(errorPage);
        return true;
    }
    return false;
}
 
Example 4
Source File: UndertowHttpHandler.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void handleRequest(HttpServerExchange exchange) throws Exception {
    try {
        ContainerRequest request = createContainerRequest(exchange);
        request.setWriter(new UndertowResponseWriter(exchange, container));
        container.getApplicationHandler().handle(request);
    } 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: HttpContinue.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sends a continuation using async IO, and calls back when it is complete.
 *
 * @param exchange The exchange
 * @param callback The completion callback
 */
public static void sendContinueResponse(final HttpServerExchange exchange, final IoCallback callback) {
    if (!exchange.isResponseChannelAvailable()) {
        callback.onException(exchange, null, UndertowMessages.MESSAGES.cannotSendContinueResponse());
        return;
    }
    internalSendContinueResponse(exchange, callback);
}
 
Example 6
Source File: EncodingHandler.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 {
    AllowedContentEncodings encodings = contentEncodingRepository.getContentEncodings(exchange);
    if (encodings == null || !exchange.isResponseChannelAvailable()) {
        next.handleRequest(exchange);
    } else if (encodings.isNoEncodingsAllowed()) {
        noEncodingHandler.handleRequest(exchange);
    } else {
        exchange.addResponseWrapper(encodings);
        exchange.putAttachment(AllowedContentEncodings.ATTACHMENT_KEY, encodings);
        next.handleRequest(exchange);
    }
}
 
Example 7
Source File: ResponseEncodeHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    AllowedContentEncodings encodings = contentEncodingRepository.getContentEncodings(exchange);
    if (encodings == null || !exchange.isResponseChannelAvailable()) {
        Handler.next(exchange, next);
    } else if (encodings.isNoEncodingsAllowed()) {
        setExchangeStatus(exchange, NO_ENCODING_HANDLER);
        return;
    } else {
        exchange.addResponseWrapper(encodings);
        exchange.putAttachment(AllowedContentEncodings.ATTACHMENT_KEY, encodings);
        Handler.next(exchange, next);
    }
}
 
Example 8
Source File: UndertowHTTPTestHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange undertowExchange) throws Exception {
    try {

        HttpServletResponseImpl response = new HttpServletResponseImpl(undertowExchange,
                                                                       (ServletContextImpl)servletContext);
        HttpServletRequestImpl request = new HttpServletRequestImpl(undertowExchange,
                                                                    (ServletContextImpl)servletContext);

        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);

        // just return the response for testing
        response.getOutputStream().write(responseStr.getBytes());
        response.flushBuffer();
    } 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);
        }
    }
}
 
Example 9
Source File: ExceptionHandler.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@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 10
Source File: UndertowHTTPHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
@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);
        }
    }
}