io.undertow.io.Sender Java Examples

The following examples show how to use io.undertow.io.Sender. 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: 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 #2
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 #3
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 #4
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 #5
Source File: ByteArrayBodyTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void send() {
    var sender = mock(Sender.class);
    var body = new ByteArrayBody(new byte[10]);
    body.send(sender, null);

    verify(sender).send(any(ByteBuffer.class));
}
 
Example #6
Source File: FileBody.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Sender sender, ResponseHandlerContext context) {
    LOGGER.debug("[response] file={}", path);
    try {
        FileChannel channel = FileChannel.open(path, StandardOpenOption.READ);
        sender.transferFrom(channel, new FileBodyCallback(channel));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
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: HealthCheckHandlerTest.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Test
void healthCheck_Normal() throws Exception {
    HttpServerExchange exchange = mock(HttpServerExchange.class);
    Sender sender = mock(Sender.class);
    given(exchange.getResponseSender()).willReturn(sender);
    HealthCheckHandler handler = new HealthCheckHandler();
    handler.handleRequest(exchange);
    verify(sender).send(anyString());
}
 
Example #9
Source File: AsyncHttpHandler.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
/**
 * just for async release
 * 
 * @param sender
 * @param pooledBuffers
 *            will be released
 */
private void setPooledBuffers(Sender sender, PooledByteBuffer[] pooledBuffers) {
	if (!(sender instanceof AsyncSenderImpl)) {
		throw new RuntimeException("only support AsyncSenderImpl");
	}

	unsafe().getAndSetObject(sender, asyncSenderImplPooledBuffersFieldOffset, pooledBuffers);
}
 
Example #10
Source File: AsyncHttpHandler.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
/**
 * force set response channel
 * 
 * @param sender
 * @param channel
 */
private void setResponseChannel(Sender sender, StreamSinkChannel channel) {
	if (!(sender instanceof AsyncSenderImpl)) {
		throw new RuntimeException("only support AsyncSenderImpl");
	}

	unsafe().getAndSetObject(sender, asyncSenderImplChannelFieldOffset, channel);
}
 
Example #11
Source File: HttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Sender getSender() {
    if (sender == null) {
        sender = new BlockingSenderImpl(exchange, getOutputStream());
    }
    return sender;
}
 
Example #12
Source File: HttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the response sender.
 * <p>
 * For blocking exchanges this will return a sender that uses the underlying output stream.
 *
 * @return the response sender, or {@code null} if another party already acquired the channel or the sender
 * @see #getResponseChannel()
 */
public Sender getResponseSender() {
    if (blockingHttpExchange != null) {
        return blockingHttpExchange.getSender();
    }
    if (sender != null) {
        return sender;
    }
    return sender = new AsyncSenderImpl(this);
}
 
Example #13
Source File: BeanBodyTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void send() {
    var sender = mock(Sender.class);
    var responseBeanMapper = new ResponseBeanMapper(new BeanMappers());
    responseBeanMapper.register(TestBean.class, new BeanClassNameValidator());
    var context = new ResponseHandlerContext(responseBeanMapper, null);
    var body = new BeanBody(new TestBean());
    assertThatThrownBy(() -> body.send(sender, context))
            .isInstanceOf(ValidationException.class);
}
 
Example #14
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 #15
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 #16
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 #17
Source File: UndertowResponse.java    From actframework with Apache License 2.0 5 votes vote down vote up
Sender sender() {
    if (null == sender) {
        sender = hse.getResponseSender();
        endAsync = !blocking();
    }
    return sender;
}
 
Example #18
Source File: CachedResource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
    UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
    try {
        entry.dereference();
    } finally {
        callback.onException(exchange, sender, exception);
    }
}
 
Example #19
Source File: CachedResource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onComplete(final HttpServerExchange exchange, final Sender sender) {
    try {
        entry.dereference();
    } finally {
        callback.onComplete(exchange, sender);
    }
}
 
Example #20
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 #21
Source File: ServletBlockingHttpExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Sender getSender() {
    try {
        return new BlockingSenderImpl(exchange, getOutputStream());
    } catch (IllegalStateException e) {
        ServletResponse response = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletResponse();
        try {
            return new BlockingWriterSenderImpl(exchange, response.getWriter(), response.getCharacterEncoding());
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }
}
 
Example #22
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 #23
Source File: NonBlockOutput.java    From actframework with Apache License 2.0 4 votes vote down vote up
NonBlockOutput(Sender sender) {
    this.sender = $.requireNotNull(sender);
}
 
Example #24
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 #25
Source File: NonBlockOutput.java    From actframework with Apache License 2.0 4 votes vote down vote up
@Override
public void onException(HttpServerExchange exchange, Sender sender, IOException exception) {
}
 
Example #26
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 #27
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 #28
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 #29
Source File: FileBody.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public void onException(HttpServerExchange exchange, Sender sender, IOException exception) {
    IoUtils.safeClose(channel);
    END_EXCHANGE.onException(exchange, sender, exception);
    throw convertException(exception);
}
 
Example #30
Source File: FileBody.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public void onComplete(HttpServerExchange exchange, Sender sender) {
    IoUtils.safeClose(channel);
    END_EXCHANGE.onComplete(exchange, sender);
}