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 Project: galeb   Author: galeb   File: ShowVirtualHostCachedHandler.java    License: 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 #2
Source Project: lams   Author: lamsfoundation   File: AbstractConfidentialityHandler.java    License: 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 #3
Source Project: hawkular-metrics   Author: hawkular   File: HttpErrorLoggerExtension.java    License: 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 #4
Source Project: mangooio   Author: svenkubiak   File: AuthorizationControllerTest.java    License: 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 #5
Source Project: lams   Author: lamsfoundation   File: HttpServletResponseImpl.java    License: 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 #6
Source Project: mangooio   Author: svenkubiak   File: ApplicationControllerTest.java    License: 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 #7
Source Project: StubbornJava   Author: StubbornJava   File: RestClient.java    License: 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 #8
Source Project: mangooio   Author: svenkubiak   File: AuthorizationControllerTest.java    License: 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 #9
Source Project: mangooio   Author: svenkubiak   File: AuthorizationControllerTest.java    License: 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 #10
Source Project: StubbornJava   Author: StubbornJava   File: RestClient.java    License: 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 #11
Source Project: lams   Author: lamsfoundation   File: HttpContinueReadHandler.java    License: 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 #12
Source Project: lams   Author: lamsfoundation   File: IPAddressAccessControlHandler.java    License: 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 #13
Source Project: mangooio   Author: svenkubiak   File: FormControllerTest.java    License: 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 #14
Source Project: lams   Author: lamsfoundation   File: ProxyHandler.java    License: 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 #15
Source Project: light-4j   Author: networknt   File: EncodeDecodeHandlerTest.java    License: 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 #16
Source Project: mangooio   Author: svenkubiak   File: ConcurrentControllerTest.java    License: 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 #17
Source Project: mangooio   Author: svenkubiak   File: FormControllerTest.java    License: 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 #18
Source Project: rpc-benchmark   Author: hank-whu   File: ListUserHandler.java    License: 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 #19
Source Project: quarkus-http   Author: quarkusio   File: Http2Server.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    String version = System.getProperty("java.version");
    System.out.println("Java version " + version);
    if(version.charAt(0) == '1' && Integer.parseInt(version.charAt(2) + "") < 8 ) {
        System.out.println("This example requires Java 1.8 or later");
        System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's");
        System.out.println("See section 9.2.2 of the HTTP2 specification for details");
        System.exit(1);
    }
    String bindAddress = System.getProperty("bind.address", "localhost");
    SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore"));
    Undertow server = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8080, bindAddress)
            .addHttpsListener(8443, bindAddress, sslContext)
            .setHandler(new SessionAttachmentHandler(new LearningPushHandler(100, -1, Handlers.header(predicate(secure(), resource(new PathResourceManager(Paths.get(System.getProperty("example.directory", System.getProperty("user.home"))), 100))
                    .setDirectoryListingEnabled(true), new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath());
                    exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                }
            }), "x-undertow-transport", ExchangeAttributes.transportProtocol())), new InMemorySessionManager("test"), new SessionCookieConfig())).build();

    server.start();

    SSLContext clientSslContext = createSSLContext(loadKeyStore("client.keystore"), loadKeyStore("client.truststore"));
    LoadBalancingProxyClient proxy = new LoadBalancingProxyClient()
            .addHost(new URI("https://localhost:8443"), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, clientSslContext), UndertowOptionMap.create(UndertowOptions.ENABLE_HTTP2, true))
            .setConnectionsPerThread(20);

    Undertow reverseProxy = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8081, bindAddress)
            .addHttpsListener(8444, bindAddress, sslContext)
            .setHandler(ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime( 30000).build())
            .build();
    reverseProxy.start();

}
 
Example #20
Source Project: aion   Author: aionnetwork   File: AionUndertowRpcHandler.java    License: 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 #21
Source Project: SikuliX1   Author: RaiMan   File: SikulixServer.java    License: 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 #22
Source Project: mangooio   Author: svenkubiak   File: ParameterControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIntParameter() {
    //given
    TestResponse response = TestRequest.get("/int/42").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("42"));
}
 
Example #23
Source Project: mangooio   Author: svenkubiak   File: HttpMethodsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPut() {
    //given
    final TestResponse response = TestRequest.put("/put").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
}
 
Example #24
Source Project: proteus   Author: noboomu   File: ServerFallbackHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception
{
    final int statusCode = 404;

    exchange.setStatusCode(statusCode);

    final String responseBody;
    final String reason = StatusCodes.getReason(statusCode);

    if (ServerPredicates.ACCEPT_JSON_PREDICATE.resolve(exchange)) {
        responseBody = objectMapper.writeValueAsString(new Message(statusCode, reason));

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_JSON);
    } else if (ServerPredicates.ACCEPT_XML_PREDICATE.resolve(exchange)) {
        responseBody = xmlMapper.writeValueAsString(new Message(statusCode, reason));

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_XML);
    } else if (ServerPredicates.ACCEPT_HTML_PREDICATE.resolve(exchange)) {
        responseBody = "<html><head><title>Error</title></head><body>" + statusCode + " - " + reason + "</body></html>";

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.TEXT_HTML);
    } else {
        responseBody = statusCode + " - " + reason;

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, javax.ws.rs.core.MediaType.TEXT_PLAIN);
    }

    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, "" + responseBody.length());
    exchange.getResponseSender().send(responseBody);
}
 
Example #25
Source Project: mangooio   Author: svenkubiak   File: JsonControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonEmptyResponseBody() {
    //given
    TestResponse response = TestRequest.post("/body")
            .withContentType(MediaType.JSON_UTF_8.withoutParameters().toString())
            .withStringBody("")
            .execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), not(nullValue()));
}
 
Example #26
Source Project: galeb   Author: galeb   File: PingHandler.java    License: 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 #27
Source Project: mangooio   Author: svenkubiak   File: ApplicationControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPlainText() {
    //given
    final TestResponse response = TestRequest.get("/text").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getContentType(), equalTo(TEXT_PLAIN));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
}
 
Example #28
Source Project: mangooio   Author: svenkubiak   File: ApplicationControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonPathWithPost() {
    //given
    final TestResponse response = TestRequest.post("/jsonpathpost")
            .withStringBody(JSON)
            .execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContentType(), equalTo(TEXT_PLAIN));
    assertThat(response.getContent(), equalTo(JSON));
}
 
Example #29
Source Project: mangooio   Author: svenkubiak   File: HttpMethodsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOptions() {
    //given
    final TestResponse response = TestRequest.options("/").execute();

    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
}
 
Example #30
Source Project: mangooio   Author: svenkubiak   File: FallbackHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Server.headers()
        .entrySet()
        .stream()
        .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
        .forEach(entry -> exchange.getResponseHeaders().add(entry.getKey().toHttpString(), entry.getValue()));
    
    exchange.getResponseHeaders().put(Header.CONTENT_TYPE.toHttpString(), Default.CONTENT_TYPE.toString());
    exchange.setStatusCode(StatusCodes.NOT_FOUND);
    exchange.getResponseSender().send(Template.DEFAULT.notFound());
}