Java Code Examples for io.undertow.io.Sender#send()

The following examples show how to use io.undertow.io.Sender#send() . 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: UndertowResponse.java    From actframework with Apache License 2.0 6 votes vote down vote up
@Override
public UndertowResponse writeContent(ByteBuffer byteBuffer) {
    beforeWritingContent();
    try {
        endAsync = !blocking();
        Sender sender = sender();
        if (endAsync) {
            sender.send(byteBuffer, IoCallback.END_EXCHANGE);
        } else {
            sender.send(byteBuffer);
        }
        afterWritingContent();
    } catch (RuntimeException e) {
        endAsync = false;
        afterWritingContent();
        throw e;
    }
    return this;
}
 
Example 5
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 6
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 7
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 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: NonBlockOutput.java    From actframework with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete(HttpServerExchange exchange, Sender sender) {
    ByteBuffer next = pending.poll();
    if (null == next) {
        sending.set(false);
    } else {
        sender.send(next, this);
    }
}
 
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();
}
 
Example 11
Source File: CachedResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serveRange(Sender sender, HttpServerExchange exchange, long start, long end, IoCallback completionCallback) {
    final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
    if(dataCache == null) {
        ((RangeAwareResource)underlyingResource).serveRange(sender, exchange, start, end, completionCallback);
        return;
    }

    final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
    final Long length = getContentLength();
    //if it is not eligible to be served from the cache
    if (length == null || length > cachingResourceManager.getMaxFileSize()) {
        underlyingResource.serve(sender, exchange, completionCallback);
        return;
    }
    //it is not cached yet, just serve it directly
    if (existing == null || !existing.enabled() || !existing.reference()) {
        //it is not cached yet, install a wrapper to grab the data
        ((RangeAwareResource)underlyingResource).serveRange(sender, exchange, start, end, completionCallback);
    } else {
        //serve straight from the cache
        ByteBuffer[] buffers;
        boolean ok = false;
        try {
            LimitedBufferSlicePool.PooledByteBuffer[] pooled = existing.buffers();
            buffers = new ByteBuffer[pooled.length];
            for (int i = 0; i < buffers.length; i++) {
                // Keep position from mutating
                buffers[i] = pooled[i].getBuffer().duplicate();
            }
            ok = true;
        } finally {
            if (!ok) {
                existing.dereference();
            }
        }
        if(start > 0) {
            long startDec = start;
            long endCount = 0;
            //handle the start of the range
            for(ByteBuffer b : buffers) {
                if(endCount == end) {
                    b.limit(b.position());
                    continue;
                } else if(endCount + b.remaining() < end) {
                    endCount += b.remaining();
                } else {
                    b.limit((int) (b.position() + (end - endCount)));
                    endCount = end;
                }
                if(b.remaining() >= startDec) {
                    startDec = 0;
                    b.position((int) (b.position() + startDec));
                } else {
                    startDec -= b.remaining();
                    b.position(b.limit());
                }
            }
        }
        sender.send(buffers, new DereferenceCallback(existing, completionCallback));
    }
}
 
Example 12
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 13
Source File: ByteArrayBody.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public void send(Sender sender, ResponseHandlerContext context) {
    LOGGER.debug("[response] body=bytes[{}]", bytes.length);
    sender.send(ByteBuffer.wrap(bytes));
}
 
Example 14
Source File: TextBody.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public void send(Sender sender, ResponseHandlerContext context) {
    byte[] bytes = Strings.bytes(text);
    logger.debug("[response] body={}", text);
    sender.send(ByteBuffer.wrap(bytes));
}
 
Example 15
Source File: TemplateBody.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public void send(Sender sender, ResponseHandlerContext context) {
    String content = context.templateManager.process(templatePath, model, language);
    sender.send(content);
}
 
Example 16
Source File: BeanBody.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public void send(Sender sender, ResponseHandlerContext context) {
    byte[] body = context.responseBeanMapper.toJSON(bean);
    LOGGER.debug("[response] body={}", new JSONLogParam(body, UTF_8));
    sender.send(ByteBuffer.wrap(body));
}
 
Example 17
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);
}