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

The following examples show how to use io.undertow.server.HttpServerExchange#getResponseSender() . 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: 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 2
Source File: AsyncHttpHandler.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
/**
 * response
 * 
 * @param exchange
 * @param statusCode
 * @param output
 *            auto release
 */
protected final void send(HttpServerExchange exchange, int statusCode, PooledByteBufferOutputStream output) {
	try {
		output.flip();

		StreamSinkChannel channel = getResponseChannel(exchange);
		Sender sender = exchange.getResponseSender();

		setStatusCode(exchange, statusCode);
		setResponseChannel(sender, channel);
		setPooledBuffers(sender, output.getPooledByteBuffers());

		sender.send(output.getByteBuffers());
	} catch (Throwable t) {
		UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t);
	}
}
 
Example 3
Source File: CRLRule.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    String fullFile = AbstractX509AuthenticationTest.getAuthServerHome() + File.separator + crlFileName;
    InputStream is = new FileInputStream(new File(fullFile));

    final byte[] responseBytes = IOUtils.toByteArray(is);

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/pkix-crl");
    // TODO: Add caching support? CRLs provided by well-known CA usually adds them

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

    exchange.endExchange();
}
 
Example 4
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 5
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send a simple response string.
 *
 * @param exchange    the http server exchange
 * @param response    the response string
 */
static void sendResponse(final HttpServerExchange exchange, final String response) {
    exchange.setStatusCode(StatusCodes.OK);
    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
    final Sender sender = exchange.getResponseSender();
    UndertowLogger.ROOT_LOGGER.mcmpSendingResponse(exchange.getSourceAddress(), exchange.getStatusCode(), exchange.getResponseHeaders(), response);
    sender.send(response);
}
 
Example 6
Source File: Http2ClientIT.java    From light-4j with Apache License 2.0 5 votes vote down vote up
static void sendMessage(final HttpServerExchange exchange) {
    exchange.setStatusCode(StatusCodes.OK);
    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, message.length() + "");
    final Sender sender = exchange.getResponseSender();
    sender.send(message);
    sender.close();
}
 
Example 7
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 8
Source File: Http2ClientTest.java    From light-4j with Apache License 2.0 4 votes vote down vote up
static void sendMessage(final HttpServerExchange exchange) {
    exchange.setStatusCode(StatusCodes.OK);
    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, message.length() + "");
    final Sender sender = exchange.getResponseSender();
    sender.send(message);
}
 
Example 9
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);
        }
    }
}
 
Example 10
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();
}