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

The following examples show how to use io.undertow.server.HttpServerExchange#setStatusCode() . 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: 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 2
Source File: SikulixServer.java    From SikuliX1 with MIT License 5 votes vote down vote up
protected static void sendResponse(HttpServerExchange exchange, int stateCode, Object responseObject) {
  exchange.setStatusCode(stateCode);
  exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
  String head = exchange.getProtocol() + " " + exchange.getStatusCode() + " " + StatusCodes.getReason(exchange.getStatusCode());
  try {
    String body = mapper.writeValueAsString(responseObject);
    exchange.getResponseSender().send(body);
    dolog("returned for <%s %s %s> from %s:\n%s\n%s",
          exchange.getRequestMethod(), exchange.getRequestURI(), exchange.getProtocol(), exchange.getSourceAddress(),
          head, body);
  } catch (JsonProcessingException ex) {
    dolog(-1, "serialize to json: Exception:\n" + ex);
    ex.printStackTrace();
  }
}
 
Example 3
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 4
Source File: PageRoutes.java    From StubbornJava with MIT License 5 votes vote down vote up
public static HttpHandler redirector(HttpHandler next) {
    return (HttpServerExchange exchange) -> {
        HttpUrl currentUrl = Exchange.urls().currentUrl(exchange);
        String protocolForward = Exchange.headers().getHeader(exchange, "X-Forwarded-Proto").orElse(null);
        String host = currentUrl.host();
        boolean redirect = false;

        Builder newUrlBuilder = currentUrl.newBuilder();

        if (host.equals("stubbornjava.com")) {
            host = "www." + host;
            newUrlBuilder.host(host);
            redirect = true;
            logger.debug("Host {} does not start with www redirecting to {}", currentUrl.host(), host);
        }

        if (null != protocolForward && protocolForward.equalsIgnoreCase("http")) {
            logger.debug("non https switching to https", currentUrl.host(), host);
            newUrlBuilder.scheme("https")
                         .port(443);
            redirect = true;
        }

        if (redirect) {
            HttpUrl newUrl = newUrlBuilder.build();
            exchange.setStatusCode(301);
            exchange.getResponseHeaders().put(Headers.LOCATION, newUrl.toString());
            exchange.endExchange();
            return;
        }
        next.handleRequest(exchange);
    };
}
 
Example 5
Source File: ResponseCodeHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    exchange.setStatusCode(responseCode);
    if(traceEnabled) {
        log.tracef("Setting response code %s for exchange %s", responseCode, exchange);
    }
}
 
Example 6
Source File: AllowedMethodsHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (allowedMethods.contains(exchange.getRequestMethod())) {
        next.handleRequest(exchange);
    } else {
        exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
        exchange.endExchange();
    }
}
 
Example 7
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void couldNotResolveBackend(HttpServerExchange exchange) {
    if (exchange.isResponseStarted()) {
        IoUtils.safeClose(exchange.getConnection());
    } else {
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        exchange.endExchange();
    }
}
 
Example 8
Source File: RealmReadinessHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    if (readyFunction.apply(exchange)) {
        next.handleRequest(exchange);
    } else {
        try {
            rejectRequest(exchange);
        } catch (IOException e) {
            ROOT_LOGGER.error(e);
            exchange.setStatusCode(500);
            exchange.endExchange();
        }
    }
}
 
Example 9
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    String responseBody = null;
    if(exchange.getAttachment(BodyHandler.REQUEST_BODY) != null) {
        responseBody = Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY));
    }
    Status status = validator.validateResponseContent(responseBody, exchange);
    if(status == null) {
        exchange.getResponseSender().send("good");
    } else {
        exchange.setStatusCode(400);
        exchange.getResponseSender().send("bad");
    }
}
 
Example 10
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 11
Source File: DisallowedMethodsHandler.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 {
    if (disallowedMethods.contains(exchange.getRequestMethod())) {
        exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
        exchange.endExchange();
    } else {
        next.handleRequest(exchange);
    }
}
 
Example 12
Source File: GithubCallbackPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    String code = Utils.extractParam(exchange, "code");
    if (code == null) {
        exchange.setStatusCode(StatusCodes.BAD_REQUEST);
        return;
    }

    try {
        String accessToken = githubHelper.exchangeCode(code);

        CookieImpl cookie = new CookieImpl("PYX-Github-Token", accessToken);
        cookie.setMaxAge(COOKIE_MAX_AGE);
        exchange.setResponseCookie(cookie);
        exchange.getResponseHeaders().add(Headers.LOCATION, REDIRECT_LOCATION);
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } catch (Throwable ex) {
        logger.error("Failed processing the request: " + exchange, ex);
        throw ex;
    }
}
 
Example 13
Source File: WebpackServer.java    From StubbornJava with MIT License 4 votes vote down vote up
public static void error(HttpServerExchange exchange) {
    exchange.setStatusCode(500);
    Exchange.body().sendHtmlTemplate(exchange, "static/templates/src/serverError", SimpleResponse.create());
}
 
Example 14
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 15
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 16
Source File: LimitHandler.java    From mangooio with Apache License 2.0 4 votes vote down vote up
/**
 * Ends the current request by sending a HTTP 429 status code
 * @param exchange The HttpServerExchange
 */
private void endRequest(HttpServerExchange exchange) {
    exchange.setStatusCode(StatusCodes.TOO_MANY_REQUESTS);
    exchange.getResponseSender().send(Template.DEFAULT.tooManyRequests());
    exchange.endExchange(); 
}
 
Example 17
Source File: ApiHandlers.java    From StubbornJava with MIT License 4 votes vote down vote up
public static void badRequest(HttpServerExchange exchange, String message) {
    ApiError error = new ApiError(400, message);
    exchange.setStatusCode(error.getStatusCode());
    Exchange.body().sendJson(exchange, error);
}
 
Example 18
Source File: FailsafeWebserver.java    From StubbornJava with MIT License 4 votes vote down vote up
private static final void serverError(HttpServerExchange exchange) {
    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
    Exchange.body().sendText(exchange, "500 - Internal Server Error");
}
 
Example 19
Source File: Oauth2CodeGetHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    // parse all the parameters here as this is a redirected get request.
    Map<String, String> params = new HashMap<>();
    Map<String, Deque<String>> pnames = exchange.getQueryParameters();
    for (Map.Entry<String, Deque<String>> entry : pnames.entrySet()) {
        String pname = entry.getKey();
        Iterator<String> pvalues = entry.getValue().iterator();
        if(pvalues.hasNext()) {
            params.put(pname, pvalues.next());
        }
    }
    if(logger.isDebugEnabled()) logger.debug("params", params);
    String clientId = params.get("client_id");
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        String code = Util.getUUID();
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        Set<String> roles = context.getAuthenticatedAccount().getRoles();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("userId", userId);
        if(roles != null && !roles.isEmpty()) {
            codeMap.put("roles", String.join(" ", roles));
        }
        String scope = params.get("scope");
        if(scope != null) {
            codeMap.put("scope", scope);
        }
        String redirectUri = params.get("redirect_uri");
        if(redirectUri == null) {
            redirectUri = client.getRedirectUri();
        } else {
            codeMap.put("redirectUri", redirectUri);
        }
        // https://tools.ietf.org/html/rfc7636#section-4 PKCE
        String codeChallenge = params.get(OAuth2Constants.CODE_CHALLENGE);
        String codeChallengeMethod = params.get(OAuth2Constants.CODE_CHALLENGE_METHOD);
        if (codeChallenge == null) {
            // PKCE is not used by this client.
            // Do we need to force native client to use PKCE?
        } else {
            if(codeChallengeMethod != null) {
                // https://tools.ietf.org/html/rfc7636#section-4.2
                // plain or S256
                if (!codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_S256) &&
                        !codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN)) {
                    setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_METHOD, codeChallengeMethod);
                    processAudit(exchange);
                    return;
                }
            } else {
                // https://tools.ietf.org/html/rfc7636#section-4.3
                // default code_challenge_method is plain
                codeChallengeMethod = CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN;
            }
            // validate codeChallenge.
            if(codeChallenge.length() < CodeVerifierUtil.MIN_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_SHORT, codeChallenge);
                processAudit(exchange);
                return;
            }
            if(codeChallenge.length() > CodeVerifierUtil.MAX_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_LONG, codeChallenge);
                processAudit(exchange);
                return;
            }
            // check the format
            Matcher m = CodeVerifierUtil.VALID_CODE_CHALLENGE_PATTERN.matcher(codeChallenge);
            if(!m.matches()) {
                setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_FORMAT, codeChallenge);
                processAudit(exchange);
                return;
            }
            // put the code challenge and method into the codes map.
            codeMap.put(OAuth2Constants.CODE_CHALLENGE, codeChallenge);
            codeMap.put(OAuth2Constants.CODE_CHALLENGE_METHOD, codeChallengeMethod);
        }

        CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);
        redirectUri = redirectUri + "?code=" + code;
        String state = params.get("state");
        if(state != null) {
            redirectUri = redirectUri + "&state=" + state;
        }
        if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
        // now redirect here.
        exchange.setStatusCode(StatusCodes.FOUND);
        exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
        exchange.endExchange();
        processAudit(exchange);
    }
}
 
Example 20
Source File: RedirectSenders.java    From StubbornJava with MIT License 4 votes vote down vote up
default void temporary(HttpServerExchange exchange, String location) {
    exchange.setStatusCode(StatusCodes.FOUND);
    exchange.getResponseHeaders().put(Headers.LOCATION, location);
    exchange.endExchange();
}