io.undertow.util.StatusCodes Java Examples

The following examples show how to use io.undertow.util.StatusCodes. 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: HttpErrorLoggerExtension.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void exchangeEvent(HttpServerExchange exchange, ExchangeCompletionListener.NextListener nextListener) {
    int httpStatusCode = exchange.getStatusCode();
    if (httpStatusCode >= StatusCodes.BAD_REQUEST) {
        final String path;
        final String query = exchange.getQueryString();
        if (!query.isEmpty()) {
            path = exchange.getRequestPath() + "?" + query;
        } else {
            path = exchange.getRequestPath();
        }
        HttpString method = exchange.getRequestMethod();
        log.warnf("Endpoint %s %s fails with HTTP code: %d", method, path, httpStatusCode);
    }
    nextListener.proceed();
}
 
Example #2
Source File: FormControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlashify() {
    // given
    String data = "this is my [email protected]";
    Multimap<String, String> parameter = ArrayListMultimap.create();
    parameter.put("name", "this is my name");
    parameter.put("email", "[email protected]");
    
    // when
    TestResponse response = TestRequest.post("/submit")
            .withContentType(MediaType.FORM_DATA.withoutParameters().toString())
            .withForm(parameter)
            .execute();

    // then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo(data));
}
 
Example #3
Source File: HttpContinueReadHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public long read(final ByteBuffer[] dsts, final int offs, final int len) throws IOException {
    if (exchange.getStatusCode() == StatusCodes.EXPECTATION_FAILED) {
        //rejected
        return -1;
    }
    if (!sent) {
        sent = true;
        response = HttpContinue.createResponseSender(exchange);
    }
    if (response != null) {
        if (!response.send()) {
            return 0;
        }
        response = null;
    }
    return super.read(dsts, offs, len);
}
 
Example #4
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public boolean deleteUserByEmail(String email) {
    HttpUrl route = HttpUrl.parse(host + "/users")
                           .newBuilder()
                           .addPathSegment(email)
                           .build();
    Request request = new Request.Builder().url(route).delete().build();
    return Unchecked.booleanSupplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.code() == StatusCodes.NO_CONTENT) {
                return true;
            }

            // Maybe you would throw an exception here? We don't feel the need to.
            if (response.code() == StatusCodes.NOT_FOUND) {
                return false;
            }
            throw HttpClient.unknownException(response);
        }
    }).getAsBoolean();
}
 
Example #5
Source File: ApplicationControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testBinaryDownload(@TempDir Path tempDir) throws IOException {
    //given
    final Config config = Application.getInjector().getInstance(Config.class);
    final String host = config.getConnectorHttpHost();
    final int port = config.getConnectorHttpPort();
    final Path path = tempDir.resolve(UUID.randomUUID().toString());
    final OutputStream fileOutputStream = Files.newOutputStream(path);

    //when
    final CloseableHttpClient httpclient = HttpClients.custom().build();
    final HttpGet httpget = new HttpGet("http://" + host + ":" + port + "/binary");
    final CloseableHttpResponse response = httpclient.execute(httpget);
    fileOutputStream.write(EntityUtils.toByteArray(response.getEntity()));
    fileOutputStream.close();
    response.close();

    //then
    assertThat(response.getStatusLine().getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(Files.readString(path), equalTo("This is an attachment"));
}
 
Example #6
Source File: HttpServletResponseImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void sendRedirect(final String location) throws IOException {
    if (responseStarted()) {
        throw UndertowServletMessages.MESSAGES.responseAlreadyCommited();
    }
    resetBuffer();
    setStatus(StatusCodes.FOUND);
    String realPath;
    if (isAbsoluteUrl(location)) {//absolute url
        exchange.getResponseHeaders().put(Headers.LOCATION, location);
    } else {
        if (location.startsWith("/")) {
            realPath = location;
        } else {
            String current = exchange.getRelativePath();
            int lastSlash = current.lastIndexOf("/");
            if (lastSlash != -1) {
                current = current.substring(0, lastSlash + 1);
            }
            realPath = CanonicalPathUtils.canonicalize(servletContext.getContextPath() + current + location);
        }
        String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + realPath;
        exchange.getResponseHeaders().put(Headers.LOCATION, loc);
    }
    responseDone();
}
 
Example #7
Source File: AuthorizationControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteAuthorized() {
    //given
    TestBrowser instance = TestBrowser.open();
    TestResponse response = instance.to("/authorize/bob")
            .withHTTPMethod(Methods.GET.toString())
            .withDisabledRedirects()
            .execute();
    
    //given
    instance.to("/write")
        .withHTTPMethod(Methods.POST.toString())
        .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("can write"));
}
 
Example #8
Source File: ConcurrentControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentJsonParsing() throws InterruptedException {
    MatcherAssert.assertThat(t -> {
        //given
        String uuid = UUID.randomUUID().toString();
        String json = "{\"firstname\":\"$$\",\"lastname\":\"Parker\",\"age\":24}";
        json = json.replace("$$", uuid);
        
        TestResponse response = TestRequest.post("/parse")
                .withContentType(MediaType.JSON_UTF_8.withoutParameters().toString())
                .withStringBody(json)
                .execute();
        
        // then
        return response.getStatusCode() == StatusCodes.OK && response.getContent().equals(uuid + ";Parker;24");
    }, new org.llorllale.cactoos.matchers.RunsInThreads<>(new AtomicInteger(), TestExtension.THREADS));
}
 
Example #9
Source File: IPAddressAccessControlHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public HandlerWrapper build(Map<String, Object> config) {

    String[] acl = (String[]) config.get("acl");
    Boolean defaultAllow = (Boolean) config.get("default-allow");
    Integer failureStatus = (Integer) config.get("failure-status");

    List<Holder> peerMatches = new ArrayList<>();
    for(String rule :acl) {
        String[] parts = rule.split(" ");
        if(parts.length != 2) {
            throw UndertowMessages.MESSAGES.invalidAclRule(rule);
        }
        if(parts[1].trim().equals("allow")) {
            peerMatches.add(new Holder(parts[0].trim(), false));
        } else if(parts[1].trim().equals("deny")) {
            peerMatches.add(new Holder(parts[0].trim(), true));
        } else {
            throw UndertowMessages.MESSAGES.invalidAclRule(rule);
        }
    }
    return new Wrapper(peerMatches, defaultAllow == null ? false : defaultAllow, failureStatus == null ? StatusCodes.FORBIDDEN : failureStatus);
}
 
Example #10
Source File: AbstractConfidentialityHandler.java    From lams with GNU General Public License v2.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.getResponseHeaders().put(Headers.LOCATION, redirectUri.toString());
        } catch (Exception e) {
            UndertowLogger.REQUEST_LOGGER.exceptionProcessingRequest(e);
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        }
        exchange.endExchange();
    }
}
 
Example #11
Source File: AuthorizationControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadUnAuthorized() {
    //given
    TestBrowser instance = TestBrowser.open();
    TestResponse response = instance.to("/authorize/jack")
            .withHTTPMethod(Methods.GET.toString())
            .withDisabledRedirects()
            .execute();
    
    //given
    instance.to("/read")
        .withHTTPMethod(Methods.GET.toString())
        .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED));
    assertThat(response.getContent(), not(equalTo("can read")));
}
 
Example #12
Source File: ShowVirtualHostCachedHandler.java    From galeb with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final String etag = cache.etag();
    if (exchange.getRequestHeaders().contains(X_GALEB_SHOW_CACHE)) {
        String virtualhostStr = exchange.getRequestHeaders().getFirst(X_GALEB_SHOW_CACHE);
        VirtualHost virtualhost = cache.get(virtualhostStr);
        if (virtualhost != null) {
            virtualhost.getEnvironment().getProperties().put("fullhash", etag);
            exchange.setStatusCode(StatusCodes.OK);
            exchange.getResponseSender().send(gson.toJson(virtualhost, VirtualHost.class));
        } else {
            exchange.setStatusCode(StatusCodes.NOT_FOUND);
            exchange.getResponseSender().send("{}");
        }
    } else {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("last_hash", cache.etag());
        jsonMap.put("virtualhosts", cache.values());
        exchange.setStatusCode(StatusCodes.OK);
        exchange.getResponseSender().send(gson.toJson(jsonMap));
    }
    exchange.endExchange();
}
 
Example #13
Source File: ListUserHandler.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleAsyncRequest(HttpServerExchange exchange, PooledByteBufferInputStream content)
		throws Exception {

	Map<String, Deque<String>> params = exchange.getQueryParameters();
	String pageNoStr = params.get("pageNo").getFirst();
	int pageNo = Integer.parseInt(pageNoStr);

	Page<User> userList = userService.listUser(pageNo);

	ByteBufferPool pool = exchange.getConnection().getByteBufferPool();
	PooledByteBufferOutputStream output = new PooledByteBufferOutputStream(pool);
	objectMapper.writeValue(output, userList);

	send(exchange, StatusCodes.OK, output);
}
 
Example #14
Source File: RestClient.java    From StubbornJava with MIT License 6 votes vote down vote up
public User updateUser(User inputUser) {
    HttpUrl route = HttpUrl.parse(host + "/users");
    Request request = new Request.Builder()
            .url(route)
            .put(RequestBodies.jsonObj(inputUser))
            .build();
    return Unchecked.supplier(() -> {
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef());
                return user;
            }

            if (response.code() == StatusCodes.NOT_FOUND) {
                return null;
            }
            throw HttpClient.unknownException(response);
        }
    }).get();
}
 
Example #15
Source File: AuthorizationControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadAuthorized() {
    //given
    TestBrowser instance = TestBrowser.open();
    TestResponse response = instance.to("/authorize/alice")
            .withHTTPMethod(Methods.GET.toString())
            .withDisabledRedirects()
            .execute();
    
    //given
    instance.to("/read")
        .withHTTPMethod(Methods.GET.toString())
        .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("can read"));
}
 
Example #16
Source File: FormControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormPost() {
	// given
	Multimap<String, String> parameter = ArrayListMultimap.create();
	parameter.put("username", "vip");
	parameter.put("password", "secret");

	// when
	TestResponse response = TestRequest.post("/form")
			.withForm(parameter)
			.execute();

	// then
	assertThat(response, not(nullValue()));
	assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
	assertThat(response.getContent(), equalTo("vip;secret"));
}
 
Example #17
Source File: EncodeDecodeHandlerTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public void runTest(final String theMessage, String encoding) throws Exception {
    try (CloseableHttpClient client = HttpClientBuilder.create().disableContentCompression().build()){
        message = theMessage;
        HttpGet get = new HttpGet("http://localhost:8080/encode");
        get.setHeader(Headers.ACCEPT_ENCODING_STRING, encoding);
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
        Assert.assertEquals(encoding, header[0].getValue());
        byte[] body = HttpClientUtils.readRawResponse(result);

        HttpPost post = new HttpPost("http://localhost:8080/decode");
        post.setEntity(new ByteArrayEntity(body));
        post.addHeader(Headers.CONTENT_ENCODING_STRING, encoding);

        result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String sb = HttpClientUtils.readResponse(result);
        Assert.assertEquals(theMessage.length(), sb.length());
        Assert.assertEquals(theMessage, sb);
    }
}
 
Example #18
Source File: ProxyHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleException(Channel channel, IOException exception) {
    IoUtils.safeClose(channel);
    IoUtils.safeClose(clientConnection);
    if (exchange.isResponseStarted()) {
        UndertowLogger.REQUEST_IO_LOGGER.debug("Exception reading from target server", exception);
        if (!exchange.isResponseStarted()) {
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            exchange.endExchange();
        } else {
            IoUtils.safeClose(exchange.getConnection());
        }
    } else {
        UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
        exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
        exchange.endExchange();
    }
}
 
Example #19
Source File: ApplicationControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testPut() {
    //given
    final TestResponse response = TestRequest.put("/put")
            .withStringBody("The king of the north!")
            .execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContentType(), equalTo(TEXT_PLAIN));
    assertThat(response.getContent(), equalTo("The king of the north!"));
}
 
Example #20
Source File: ResponseTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithUnauthorized() {
    //given
    Response response = Response.withUnauthorized();
    
    //then
    assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED));
}
 
Example #21
Source File: JsonControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonRequestBodyPost() {
    //given
    TestResponse response = TestRequest.post("/requestAndJson")
            .withContentType(MediaType.JSON_UTF_8.withoutParameters().toString())
            .withStringBody(json)
            .execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("/requestAndJsonPeter"));
}
 
Example #22
Source File: ResponseTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithNotFound() {
    //given
    Response response = Response.withNotFound();
    
    //then
    assertThat(response.getStatusCode(), equalTo(StatusCodes.NOT_FOUND));
}
 
Example #23
Source File: ApplicationControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testIndexPage() {
    //when
    TestResponse response = TestRequest.get("/").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), containsString("Hello World!"));
}
 
Example #24
Source File: ParameterControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testFloatParameter() {
    //given
    TestResponse response = TestRequest.get("/float/1.24").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("1.24"));
}
 
Example #25
Source File: AccessControlListHandler.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 {
    String attribute = this.attribute.readAttribute(exchange);
    if (isAllowed(attribute)) {
        next.handleRequest(exchange);
    } else {
        exchange.setStatusCode(StatusCodes.FORBIDDEN);
        exchange.endExchange();
    }
}
 
Example #26
Source File: SessionControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testSessionCookie() {
    //when
    Config config = Application.getInstance(Config.class);
    TestResponse response = TestRequest.get("/session").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getCookie(config.getSessionCookieName()).getName(), equalTo(config.getSessionCookieName()));
}
 
Example #27
Source File: ApplicationControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnauthorized() {
    //given
    final TestResponse response = TestRequest.get("/unauthorized").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getContentType(), equalTo(TEXT_PLAIN));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED));
}
 
Example #28
Source File: AdminControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testToolsAjaxAuthorized() {
    //given
    TestResponse response = login().to("/@admin/tools/ajax")
            .withHTTPMethod(Methods.POST.toString())
            .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContentType(), equalTo("application/json; charset=UTF-8"));
}
 
Example #29
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 #30
Source File: ShutdownHandlerTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void handleShutdown() {
    handler.shutdown();
    assertThat(handler.handle(exchange)).isTrue();

    verify(exchange).setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
    verify(exchange).setPersistent(false);
    verify(exchange).endExchange();
}