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

The following examples show how to use io.undertow.server.HttpServerExchange#getRequestChannel() . 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: AsyncReceiverImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AsyncReceiverImpl(HttpServerExchange exchange) {
    this.exchange = exchange;
    this.channel = exchange.getRequestChannel();
    if (channel == null) {
        throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided();
    }
}
 
Example 3
Source File: UndertowInputStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public UndertowInputStream(final HttpServerExchange exchange) {
    if (exchange.isRequestChannelAvailable()) {
        this.channel = exchange.getRequestChannel();
    } else {
        this.channel = new EmptyStreamSourceChannel(exchange.getIoThread());
    }
    this.bufferPool = exchange.getConnection().getByteBufferPool();
}
 
Example 4
Source File: HTTPIOHandler.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (HEALTH_CHECK_PATH.equals(exchange.getRequestPath())) {      // not treat health-check as action
        exchange.endExchange(); // end exchange will send 200 / content-length=0
        return;
    }

    boolean shutdown = shutdownHandler.handle(new Exchange(exchange));
    if (shutdown) return;

    if (hasBody(exchange)) {    // parse body early, not process until body is read (e.g. for chunked), to save one blocking thread during read
        FormDataParser parser = formParserFactory.createParser(exchange);
        if (parser != null) {
            parser.parse(handler);
            return;
        }

        var reader = new RequestBodyReader(exchange, handler);
        StreamSourceChannel channel = exchange.getRequestChannel();
        reader.read(channel);  // channel will be null if getRequestChannel() is already called, but here should not be that case
        if (!reader.complete()) {
            channel.getReadSetter().set(reader);
            channel.resumeReads();
            return;
        }
    }

    exchange.dispatch(handler);
}
 
Example 5
Source File: DomainApiHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ModelNode convertPostRequest(HttpServerExchange exchange, boolean encode) throws IOException {
    InputStream in = new ChannelInputStream(exchange.getRequestChannel());
    try {
        return encode ? ModelNode.fromBase64(in) : ModelNode.fromJSONStream(in);
    } finally {
        IoUtils.safeClose(in);
    }
}
 
Example 6
Source File: UndertowServerHttpRequest.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public RequestBodyPublisher(HttpServerExchange exchange, DataBufferFactory bufferFactory) {
	super(UndertowServerHttpRequest.this.getLogPrefix());
	this.channel = exchange.getRequestChannel();
	this.bufferFactory = bufferFactory;
	this.byteBufferPool = exchange.getConnection().getByteBufferPool();
}
 
Example 7
Source File: UndertowServerHttpRequest.java    From java-technology-stack with MIT License 4 votes vote down vote up
public RequestBodyPublisher(HttpServerExchange exchange, DataBufferFactory bufferFactory) {
	super(UndertowServerHttpRequest.this.getLogPrefix());
	this.channel = exchange.getRequestChannel();
	this.bufferFactory = bufferFactory;
	this.byteBufferPool = exchange.getConnection().getByteBufferPool();
}
 
Example 8
Source File: AsyncRequestBodyReceiver.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
private void receive(final BiConsumer<InputStream, Integer> callback,
                     final HttpServerExchange exchange,
                     final Optional<Integer> contentLength,
                     final int provisionChunks) {
    logger.debug("Starting to receive request body.");
    final StreamSourceChannel channel = exchange.getRequestChannel();
    if (channel == null) {
        throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided();
    }

    /*
     * NOTE: We could make this use buffers from Undertow's / XNio's buffer pool,
     * instead of allocating our own. On G1, I think it makes more sense to
     * allocate the buffers without pooling, though. As they are fixed size and
     * < 1MB, allocation and pooling shouldn't differ that much performance-wise.
     * Undertow's buffer pool consists of native buffer in most cases, while these
     * buffers are used exclusively on heap after receiving the bytes from the
     * socket.
     */
    ChunkyByteBuffer.fill(channel, provisionChunks, contentLength.isPresent() ? provisionChunks : maximumChunks,
                          new ChunkyByteBuffer.CompletionHandler() {
        @Override
        public void overflow() {
            if (logger.isWarnEnabled()) {
                logger.warn("Request body too large; rejecting request from {}", getPeerHost(exchange));
            }
            rejectLargeRequest(exchange);
        }
        @Override
        public void failed(final Throwable e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error while reading request body received from " + getPeerHost(exchange), e);
            }
            Connectors.executeRootHandler(exchange -> exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR)
                                                              .endExchange(),
                                          exchange);
        }
        @Override
        public void completed(final InputStream body, final int bodyLength) {
            // Sanity check that the body size matches the content-length header, if it
            // was supplied.
            if (contentLength.map(l -> l != bodyLength).orElse(false)) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Bad request from {}; content length ({}) didn't match actual body length ({}).",
                                getPeerHost(exchange), contentLength.orElse(-1), bodyLength);
                }
                exchange.setStatusCode(StatusCodes.BAD_REQUEST)
                        .endExchange();
                return;
            }
            // First bump the global default for the number of chunks that we pre-allocate.
            final int newNumChunks = calculateChunks(bodyLength);
            int currentNumChunks;
            while ((currentNumChunks = preallocateChunks.get()) < newNumChunks) {
                if (preallocateChunks.compareAndSet(currentNumChunks, newNumChunks)) {
                    logger.info("Updated default body buffer size from {} to {}",
                                 currentNumChunks * ChunkyByteBuffer.CHUNK_SIZE,
                                 newNumChunks * ChunkyByteBuffer.CHUNK_SIZE);
                    break;
                }
            }
            // Pass the body on to the upstream handler.
            callback.accept(body, bodyLength);
        }
    });
}
 
Example 9
Source File: MappingTestServer.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
private void handleEvent(final HttpServerExchange exchange) throws Exception {
    try (final ChannelInputStream cis = new ChannelInputStream(exchange.getRequestChannel())) {
        final JsonNode payload = EVENT_PARAMETERS_READER.readTree(cis);
        final String generatedPageViewId = DivolteIdentifier.generate().value;

        final DivolteEvent.BrowserEventData browserEventData = new DivolteEvent.BrowserEventData(
                get(payload, "page_view_id", String.class).orElse(generatedPageViewId),
                get(payload, "location", String.class),
                get(payload, "referer", String.class),
                get(payload, "viewport_pixel_width", Integer.class),
                get(payload, "viewport_pixel_height", Integer.class),
                get(payload, "screen_pixel_width", Integer.class),
                get(payload, "screen_pixel_height", Integer.class),
                get(payload, "device_pixel_ratio", Integer.class));
        final Instant now = Instant.now();
        final DivolteEvent divolteEvent = DivolteEvent.createBrowserEvent(
                exchange,
                get(payload, "corrupt", Boolean.class).orElse(false),
                get(payload, "party_id", String.class).flatMap(DivolteIdentifier::tryParse).orElse(DivolteIdentifier.generate()),
                get(payload, "session_id", String.class).flatMap(DivolteIdentifier::tryParse).orElse(DivolteIdentifier.generate()),
                get(payload, "event_id", String.class).orElse(generatedPageViewId + "0"),
                now, now,
                get(payload, "new_party_id", Boolean.class).orElse(false),
                get(payload, "first_in_session", Boolean.class).orElse(false),
                get(payload, "event_type", String.class),
                () -> get(payload, "parameters", JsonNode.class),
                browserEventData);

        get(payload, "remote_host", String.class)
            .ifPresent(ip -> {
                try {
                    final InetAddress address = InetAddress.getByName(ip);
                    // We have no way of knowing the port
                    exchange.setSourceAddress(new InetSocketAddress(address, 0));
                } catch (final UnknownHostException e) {
                    log.warn("Could not parse remote host: " + ip, e);
                }
            });

        exchange.putAttachment(DUPLICATE_EVENT_KEY, get(payload, "duplicate", Boolean.class).orElse(false));

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
        exchange.getResponseChannel().write(ByteBuffer.wrap(mapper.newRecordFromExchange(divolteEvent).toString().getBytes(StandardCharsets.UTF_8)));
        exchange.endExchange();
    }
}