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

The following examples show how to use io.undertow.server.HttpServerExchange#endExchange() . 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: AbstractConfidentialityHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (isConfidential(exchange) || !confidentialityRequired(exchange)) {
        next.handleRequest(exchange);
    } else {
        try {
            URI redirectUri = getRedirectURI(exchange);
            UndertowLogger.SECURITY_LOGGER.debugf("Redirecting request %s to %s to meet confidentiality requirements", exchange, redirectUri);
            exchange.setStatusCode(StatusCodes.FOUND);
            exchange.setResponseHeader(HttpHeaderNames.LOCATION, redirectUri.toString());
        } catch (Exception e) {
            UndertowLogger.REQUEST_LOGGER.exceptionProcessingRequest(e);
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        }
        exchange.endExchange();
    }
}
 
Example 2
Source File: JsonContentHandler.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final HeaderValues contentType = exchange.getRequestHeaders().get(Headers.CONTENT_TYPE);
    if (null != contentType
            && contentType.size() == 1
            && contentType.getFirst().toLowerCase(Locale.ROOT).equals("application/json")) {
        next.handleRequest(exchange);
    } else {
        exchange.setStatusCode(StatusCodes.UNSUPPORTED_MEDIA_TYPE);
        exchange.getResponseHeaders()
                .put(Headers.CONTENT_TYPE, "text/plain; charset=utf-8");
        exchange.getResponseSender()
                .send("Content type must be application/json.", StandardCharsets.UTF_8);
        exchange.endExchange();
    }
}
 
Example 3
Source File: InfoHandler.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
    exchange.getResponseHeaders().put(Headers.SERVER, "GALEB");
    exchange.setStatusCode(StatusCodes.OK);
    long uptimeJVM = ManagementFactory.getRuntimeMXBean().getUptime();
    String uptime = getUptimeSO();
    String version = getClass().getPackage().getImplementationVersion();
    Map<String, Object> infoJson = new HashMap<>();
    infoJson.put("uptime-so", uptime);
    infoJson.put("uptime-jvm", uptimeJVM);
    infoJson.put("version", version);
    exchange.getResponseSender().send(gson.toJson(infoJson));
    exchange.endExchange();
}
 
Example 4
Source File: AuthorizationHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Ends the current request by sending a HTTP 401 status code and the default unauthorized template
 * @param exchange The HttpServerExchange
 */
private void endRequest(HttpServerExchange exchange) {
    exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
    
    Server.headers()
        .entrySet()
        .stream()
        .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
        .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
    
    exchange.endExchange();
}
 
Example 5
Source File: IPAddressAccessControlHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    InetSocketAddress peer = exchange.getSourceAddress();
    if (isAllowed(peer.getAddress())) {
        next.handleRequest(exchange);
    } else {
        exchange.setStatusCode(denyResponseCode);
        exchange.endExchange();
    }
}
 
Example 6
Source File: AuthenticationHandler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Ends the current request by sending a HTTP 302 status code and a direct to the given URL
 * @param exchange The HttpServerExchange
 */
private void endRequest(HttpServerExchange exchange, String redirect) {
    exchange.setStatusCode(StatusCodes.FOUND);
    
    Server.headers()
        .entrySet()
        .stream()
        .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
        .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
    
    exchange.getResponseHeaders().put(Header.LOCATION.toHttpString(), redirect);
    exchange.endExchange();
}
 
Example 7
Source File: AsyncReceiverImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void error(HttpServerExchange exchange, IOException e) {
    e.printStackTrace();
    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    exchange.endExchange();
}
 
Example 8
Source File: AionUndertowRpcHandler.java    From aion with MIT License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    boolean isPost = Methods.POST.equals(exchange.getRequestMethod());
    boolean isOptions = Methods.OPTIONS.equals(exchange.getRequestMethod());

    // only support POST & OPTIONS requests
    if (!isPost && !isOptions) {
        exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
        exchange.setPersistent(false); // don't need to keep-alive connection in case of error.
        exchange.endExchange();
        return;
    }

    // respond to cors-preflight request
    if (corsEnabled && isOptions) {
        addCorsHeaders(exchange);
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "0");
        exchange.getResponseSender().send("");
        return;
    }

    /** respond to rpc call; {@link io.Undertow.BlockingReceiverImpl#receiveFullString} */
    exchange.getRequestReceiver()
            .receiveFullString(
                    (_exchange, body) -> {
                        if (corsEnabled) addCorsHeaders(_exchange);
                        _exchange
                                .getResponseHeaders()
                                .put(Headers.CONTENT_TYPE, "application/json");
                        _exchange.getResponseSender().send(rpcProcessor.process(body));
                    });
}
 
Example 9
Source File: BlockingReceiverImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void error(HttpServerExchange exchange, IOException e) {
    if(!exchange.isResponseStarted()) {
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
    }
    exchange.setPersistent(false);
    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
    exchange.endExchange();
}
 
Example 10
Source File: DefaultIoCallback.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 {
        exchange.endExchange();
    } finally {
        IoUtils.safeClose(exchange.getConnection());
    }
}
 
Example 11
Source File: TracingHandlerTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatusCodeIsOk() throws Throwable {
    TracingHandler handler = new TracingHandler(template, httpHandler);
    HttpServerExchange exchange = buildExchange();
    handler.handleRequest(exchange);
    exchange.endExchange();
    assertThat(segmentStorage.getTraceSegments().size(), is(1));
    TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
    List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
    assertHttpSpan(spans.get(0));
}
 
Example 12
Source File: MCMPHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send an error message.
 *
 * @param type         the error type
 * @param errString    the error string
 * @param exchange     the http server exchange
 */
static void processError(String type, String errString, HttpServerExchange exchange) {
    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, CONTENT_TYPE);
    exchange.getResponseHeaders().add(new HttpString("Version"), VERSION_PROTOCOL);
    exchange.getResponseHeaders().add(new HttpString("Type"), type);
    exchange.getResponseHeaders().add(new HttpString("Mess"), errString);
    exchange.endExchange();
    UndertowLogger.ROOT_LOGGER.mcmpProcessingError(type, errString);
}
 
Example 13
Source File: PingHandler.java    From galeb with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    boolean hasNoUpdate = exchange.getQueryParameters().containsKey("noupdate");
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
    exchange.getResponseHeaders().put(Headers.SERVER, "GALEB");
    String statusBody = getStatusBody(hasNoUpdate);
    exchange.setStatusCode(StatusCodes.OK);
    exchange.getResponseSender().send(statusBody);
    if (!hasNoUpdate) {
        updaterService.sched();
    }
    exchange.endExchange();
}
 
Example 14
Source File: RedirectSenders.java    From StubbornJava with MIT License 4 votes vote down vote up
default void permanent(HttpServerExchange exchange, String location) {
    exchange.setStatusCode(StatusCodes.MOVED_PERMANENTLY);
    exchange.getResponseHeaders().put(Headers.LOCATION, location);
    exchange.endExchange();
}
 
Example 15
Source File: ResponseCache.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
    UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
    entry.dereference();
    exchange.endExchange();
}
 
Example 16
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();
    }
}
 
Example 17
Source File: RedirectSenders.java    From StubbornJava with MIT License 4 votes vote down vote up
default void permanent(HttpServerExchange exchange, String location) {
    exchange.setStatusCode(StatusCodes.MOVED_PERMANENTLY);
    exchange.getResponseHeaders().put(Headers.LOCATION, location);
    exchange.endExchange();
}
 
Example 18
Source File: HttpContexts.java    From thorntail with Apache License 2.0 4 votes vote down vote up
private void defaultUpHealthInfo(HttpServerExchange exchange) {
    exchange.setStatusCode(200);
    responseHeaders(exchange);
    exchange.getResponseSender().send("{\"status\":\"UP\", \"checks\":[]}");
    exchange.endExchange();
}
 
Example 19
Source File: JavaScriptHandler.java    From divolte-collector with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Requested received for {} from {}",
                     resource.getResourceName(), exchange.getSourceAddress().getHostString());
    }
    // Start with headers that we always set the same way.
    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CACHE_CONTROL, CACHE_CONTROL_HEADER_VALUE);

    // Figure out if we possibly need to deal with a compressed response,
    // based on client capability.
    final GzippableHttpBody uncompressedBody = resource.getEntityBody();
    final Optional<HttpBody> gzippedBody = uncompressedBody.getGzippedBody();
    final HttpBody bodyToSend;
    if (gzippedBody.isPresent()) {
        /*
         * Compressed responses can use Content-Encoding and/or Transfer-Encoding.
         * The semantics differ slightly, but it is suffice to say that most user
         * agents don't advertise their Transfer-Encoding support.
         * So for now we only support the Content-Encoding mechanism.
         * Some other notes:
         *  - Some clients implement 'deflate' incorrectly. Hence we only support 'gzip',
         *    despite it having slightly more overhead.
         *  - We don't use Undertow's built-in compression support because we've
         *    pre-calculated the compressed response and expect to serve it up
         *    repeatedly, instead of calculating it on-the-fly for every request.
         */
        responseHeaders.put(Headers.VARY, Headers.ACCEPT_ENCODING_STRING);
        final HeaderValues acceptEncoding =
                exchange.getRequestHeaders().get(Headers.ACCEPT_ENCODING);
        if (null != acceptEncoding &&
                acceptEncoding.stream()
                              .anyMatch((header) -> Iterables.contains(HEADER_SPLITTER.split(header), "gzip"))) {
            responseHeaders.put(Headers.CONTENT_ENCODING, "gzip");
            bodyToSend = gzippedBody.get();
        } else {
            bodyToSend = uncompressedBody;
        }
    } else {
        bodyToSend = uncompressedBody;
    }

    // Now we know which version of the entity is visible to this user-agent,
    // figure out if the client already has the current version or not.
    final ETag eTag = bodyToSend.getETag();
    responseHeaders.put(Headers.ETAG, eTag.toString());
    if (ETagUtils.handleIfNoneMatch(exchange, eTag, true)) {
        final ByteBuffer entityBody = bodyToSend.getBody();
        responseHeaders.put(Headers.CONTENT_TYPE, "application/javascript");
        exchange.getResponseSender().send(entityBody);
    } else {
        exchange.setStatusCode(StatusCodes.NOT_MODIFIED);
        exchange.endExchange();
    }
}
 
Example 20
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
public AuthenticationMechanismOutcome runFormAuth(final HttpServerExchange exchange, final SecurityContext securityContext) {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
        UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
        // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }

    try {
        final FormData data = parser.parseBlocking();
        if (data == null) {
            UndertowLogger.SECURITY_LOGGER.debug("Could not authenticate as no form parser is present");
            // TODO - May need a better error signaling mechanism here to prevent repeated attempts.
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }

        final FormData.FormValue jUsername = data.getFirst("j_username");
        final FormData.FormValue jPassword = data.getFirst("j_password");
        if (jUsername == null || jPassword == null) {
            UndertowLogger.SECURITY_LOGGER.debugf("Could not authenticate as username or password was not present in the posted result for %s", exchange);
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
        final String userName = jUsername.getValue();
        final String password = jPassword.getValue();
        AuthenticationMechanismOutcome outcome = null;
        PasswordCredential credential = new PasswordCredential(password.toCharArray());
        try {
            IdentityManager identityManager = getIdentityManager(securityContext);
            Account account = identityManager.verify(userName, credential);
            if (account != null) {
                securityContext.authenticationComplete(account, name, true);
                UndertowLogger.SECURITY_LOGGER.debugf("Authenticated user %s using for auth for %s", account.getPrincipal().getName(), exchange);
                outcome = AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                securityContext.authenticationFailed(MESSAGES.authenticationFailed(userName), name);
            }
        } finally {
            if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
                handleRedirectBack(exchange);
                exchange.endExchange();
            }
            return outcome != null ? outcome : AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}