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

The following examples show how to use io.undertow.server.HttpServerExchange#getInputStream() . 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: Parameters.java    From PYX-Reloaded with Apache License 2.0 7 votes vote down vote up
public static Parameters fromExchange(HttpServerExchange exchange) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    InputStream in = exchange.getInputStream();
    byte[] buffer = new byte[8 * 1024];

    int read;
    while ((read = in.read(buffer)) != -1)
        out.write(buffer, 0, read);

    Parameters params = new Parameters();
    Map<String, Deque<String>> rawParams = QueryParameterUtils.parseQueryString(new String(out.toByteArray()), "UTF-8");
    for (Map.Entry<String, Deque<String>> entry : rawParams.entrySet())
        params.put(entry.getKey(), entry.getValue().getFirst());

    return params;
}
 
Example 2
Source File: SavedRequest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange) {
    int maxSize = getMaxBufferSizeToSave(exchange);
    if (maxSize > 0) {
        //if this request has a body try and cache the response
        if (!exchange.isRequestComplete()) {
            final long requestContentLength = exchange.getRequestContentLength();
            if (requestContentLength > maxSize) {
                UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
                return;//failed to save the request, we just return
            }
            //TODO: we should really be used pooled buffers
            //TODO: we should probably limit the number of saved requests at any given time
            byte[] buffer = new byte[maxSize];
            int read = 0;
            int res = 0;
            InputStream in = exchange.getInputStream();
            try {
                while ((res = in.read(buffer, read, buffer.length - read)) > 0) {
                    read += res;
                    if (read == maxSize) {
                        UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
                        return;//failed to save the request, we just return
                    }
                }
                //save request from buffer
                trySaveRequest(exchange, buffer, read);
            } catch (IOException e) {
                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
            }
        }
    }
}
 
Example 3
Source File: SavedRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange) {
    int maxSize = getMaxBufferSizeToSave(exchange);
    if (maxSize > 0) {
        //if this request has a body try and cache the response
        if (!exchange.isRequestComplete()) {
            final long requestContentLength = exchange.getRequestContentLength();
            if (requestContentLength > maxSize) {
                UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
                return;//failed to save the request, we just return
            }
            //TODO: we should really be used pooled buffers
            //TODO: we should probably limit the number of saved requests at any given time
            byte[] buffer = new byte[maxSize];
            int read = 0;
            int res = 0;
            InputStream in = exchange.getInputStream();
            try {
                while ((res = in.read(buffer, read, buffer.length - read)) > 0) {
                    read += res;
                    if (read == maxSize) {
                        UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
                        return;//failed to save the request, we just return
                    }
                }
                //save request from buffer
                trySaveRequest(exchange, buffer, read);
            } catch (IOException e) {
                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
            }
        }
    }
}
 
Example 4
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 5
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 6
Source File: BlockingWebSocketHttpServerExchange.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public BlockingWebSocketHttpServerExchange(final HttpServerExchange exchange, Set<WebSocketChannel> peerConnections) {
    super(exchange, peerConnections);
    out = exchange.getOutputStream();
    in = exchange.getInputStream();
}
 
Example 7
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();
}