io.undertow.util.Methods Java Examples

The following examples show how to use io.undertow.util.Methods. 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: ChannelUpgradeHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final List<String> upgradeStrings = exchange.getRequestHeaders().get(Headers.UPGRADE);
    if (upgradeStrings != null && exchange.getRequestMethod().equals(Methods.GET)) {
        for (String string : upgradeStrings) {
            final List<Holder> holders = handlers.get(string);
            if (holders != null) {
                for (Holder holder : holders) {
                    final HttpUpgradeListener listener = holder.listener;
                    if (holder.handshake != null) {
                        if (!holder.handshake.handleUpgrade(exchange)) {
                            //handshake did not match, try again
                            continue;
                        }
                    }

                    exchange.upgradeChannel(string,listener);
                    exchange.endExchange();
                    return;
                }
            }
        }
    }
    nonUpgradeHandler.handleRequest(exchange);
}
 
Example #2
Source File: AllowedContentEncodings.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) {
    if (exchange.getResponseHeaders().contains(Headers.CONTENT_ENCODING)) {
        //already encoded
        return factory.create();
    }
    //if this is a zero length response we don't want to encode
    if (exchange.getResponseContentLength() != 0
            && exchange.getStatusCode() != StatusCodes.NO_CONTENT
            && exchange.getStatusCode() != StatusCodes.NOT_MODIFIED) {
        EncodingMapping encoding = getEncoding();
        if (encoding != null) {
            exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, encoding.getName());
            if (exchange.getRequestMethod().equals(Methods.HEAD)) {
                //we don't create an actual encoder for HEAD requests, but we set the header
                return factory.create();
            } else {
                return encoding.getEncoding().getResponseWrapper().wrap(factory, exchange);
            }
        }
    }
    return factory.create();
}
 
Example #3
Source File: I18nControllerTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithI18nCookie() {
    //given
    TestBrowser browser = TestBrowser.open();
    TestResponse response = browser.withHTTPMethod(Methods.GET.toString()).to("/localize").execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getCookie(Default.I18N_COOKIE_NAME.toString()), not(nullValue()));
    
    //given
    response = browser.to("/translation").execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo("welcome"));
}
 
Example #4
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 #5
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");
        TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
        HttpHandler handler = Handlers.routing()
                .add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #6
Source File: ResourceHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.getRequestMethod().equals(Methods.GET) ||
            exchange.getRequestMethod().equals(Methods.POST)) {
        serveResource(exchange, true);
    } else if (exchange.getRequestMethod().equals(Methods.HEAD)) {
        serveResource(exchange, false);
    } else {
        if (KNOWN_METHODS.contains(exchange.getRequestMethod())) {
            exchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
            exchange.getResponseHeaders().add(Headers.ALLOW,
                    String.join(", ", Methods.GET_STRING, Methods.HEAD_STRING, Methods.POST_STRING));
        } else {
            exchange.setStatusCode(StatusCodes.NOT_IMPLEMENTED);
        }
        exchange.endExchange();
    }
}
 
Example #7
Source File: SikulixServer.java    From SikuliX1 with MIT License 6 votes vote down vote up
public ScriptsCommand(TasksCommand tasks) {
  this.taskId = new AtomicInteger();
  this.tasks = tasks;
  this.run.addExceptionHandler(Throwable.class, getExceptionHttpHandler());
  getRouting()
      .add(Methods.GET, "/scripts", 
          getScripts)
      .add(Methods.GET, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/run$"),
          run)
      .add(Methods.POST, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/run$"),
          run)
      .add(Methods.POST, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/task$"),
          task)
      .add(Methods.GET, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/tasks(/.*)*$"),
          delegate)
      .add(Methods.PUT, "/scripts/*",
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/[^/].*/tasks(/.*)*$"),
          delegate)
      .add(Methods.GET, "/scripts/*", 
          Predicates.regex(RelativePathAttribute.INSTANCE, "^/scripts/([^/].*)?[^/]$"),
          getScript);
}
 
Example #8
Source File: HandlerTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedPathsAndSource() {
    Handler.config.setPaths(Arrays.asList(
        mkPathChain(null, "/my-api/first", "post", "third"),
        mkPathChain(MockEndpointSource.class.getName(), null, null, "secondBeforeFirst", "third"),
        mkPathChain(null, "/my-api/second", "put", "third")
    ));
    Handler.init();

    Map<HttpString, PathTemplateMatcher<String>> methodToMatcher = Handler.methodToMatcherMap;

    PathTemplateMatcher<String> getMatcher = methodToMatcher.get(Methods.GET);
    PathTemplateMatcher.PathMatchResult<String> getFirst = getMatcher.match("/my-api/first");
    Assert.assertNotNull(getFirst);
    PathTemplateMatcher.PathMatchResult<String> getSecond = getMatcher.match("/my-api/second");
    Assert.assertNotNull(getSecond);
    PathTemplateMatcher.PathMatchResult<String> getThird = getMatcher.match("/my-api/third");
    Assert.assertNull(getThird);
}
 
Example #9
Source File: CamelUndertowHostService.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
boolean remove(String method, String path) {
    MethodPathKey key = new MethodPathKey(method, path);
    boolean result;
    synchronized (paths) {
        MethodPathValue value = paths.get(key);
        if (value != null) {
            value.removeRef();
            if (value.refCount <= 0) {
                paths.remove(key);
            }
        }
        result = paths.isEmpty();
    }
    delegate.remove(Methods.fromString(method), path);
    return result;
}
 
Example #10
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Enumeration<String> getParameterNames() {
    if (queryParameters == null) {
        queryParameters = exchange.getQueryParameters();
    }
    final Set<String> parameterNames = new HashSet<>(queryParameters.keySet());
    if (exchange.getRequestMethod().equals(Methods.POST)) {
        final FormData parsedFormData = parseFormData();
        if (parsedFormData != null) {
            Iterator<String> it = parsedFormData.iterator();
            while (it.hasNext()) {
                String name = it.next();
                for(FormData.FormValue param : parsedFormData.get(name)) {
                    if(!param.isFile()) {
                        parameterNames.add(name);
                        break;
                    }
                }
            }
        }
    }
    return new IteratorEnumeration<>(parameterNames.iterator());
}
 
Example #11
Source File: AssetsService.java    From proteus with Apache License 2.0 6 votes vote down vote up
public RoutingHandler get()
{
    RoutingHandler router = new RoutingHandler();
    final String assetsPath = serviceConfig.getString("path");
    final String assetsDirectoryName = serviceConfig.getString("dir");
    final Integer assetsCacheTime = serviceConfig.getInt("cache.time");
    final FileResourceManager fileResourceManager = new FileResourceManager(Paths.get(assetsDirectoryName).toFile());

    router.add(Methods.GET,
            assetsPath + "/*",
            io.undertow.Handlers.rewrite("regex('" + assetsPath + "/(.*)')",
                    "/$1",
                    getClass().getClassLoader(),
                    new ResourceHandler(fileResourceManager).setCachable(TruePredicate.instance()).setCacheTime(assetsCacheTime)));

    this.registeredEndpoints.add(EndpointInfo.builder()
            .withConsumes("*/*")
            .withProduces("*/*")
            .withPathTemplate(assetsPath)
            .withControllerName(this.getClass().getSimpleName())
            .withMethod(Methods.GET)
            .build());

    return router;
}
 
Example #12
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    return Handlers.routing()


        .add(Methods.POST, "/oauth2/provider", new Oauth2ProviderPostHandler())
        .add(Methods.GET, "/oauth2/provider", new Oauth2ProviderGetHandler())
       .add(Methods.DELETE, "/oauth2/provider/{providerId}", new Oauth2ProviderProviderIdDeleteHandler())
            .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
            .add(Methods.PUT, "/oauth2/provider", new Oauth2ProviderPutHandler())

            ;
}
 
Example #13
Source File: AdminControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchedulerAuthorized() {
    //given
    TestResponse response = login().to("/@admin/scheduler")
            .withHTTPMethod(Methods.GET.toString())
            .execute();
    
    //then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContentType(), equalTo(TEXT_HTML));
    assertThat(response.getContent(), containsString(SCHEDULER));
}
 
Example #14
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    final IdentityManager identityManager = new MapIdentityManager(users);

    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/authorize", addBasicSecurity(new Oauth2AuthorizeGetHandler(), identityManager))
        .add(Methods.POST, "/oauth2/authorize", addFormSecurity(new Oauth2AuthorizePostHandler(), identityManager))
    ;
    return handler;
}
 
Example #15
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.POST, "/oauth2/password/{userId}", new Oauth2PasswordUserIdPostHandler())
        .add(Methods.GET, "/oauth2/user", new Oauth2UserGetHandler())
        .add(Methods.POST, "/oauth2/user", new Oauth2UserPostHandler())
        .add(Methods.PUT, "/oauth2/user", new Oauth2UserPutHandler())
        .add(Methods.DELETE, "/oauth2/user/{userId}", new Oauth2UserUserIdDeleteHandler())
        .add(Methods.GET, "/oauth2/user/{userId}", new Oauth2UserUserIdGetHandler())
    ;
    return handler;
}
 
Example #16
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    final IdentityManager basicIdentityManager = new LightIdentityManager();

    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health/"+server.get("serviceId"), new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/code", addGetSecurity(new Oauth2CodeGetHandler(), basicIdentityManager))
        .add(Methods.POST, "/oauth2/code", addFormSecurity(new Oauth2CodePostHandler(), basicIdentityManager))
    ;
    return handler;
}
 
Example #17
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    return Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/refresh_token", new Oauth2RefreshTokenGetHandler())
        .add(Methods.DELETE, "/oauth2/refresh_token/{refreshToken}", new Oauth2RefreshTokenRefreshTokenDeleteHandler())
        .add(Methods.GET, "/oauth2/refresh_token/{refreshToken}", new Oauth2RefreshTokenRefreshTokenGetHandler())
    ;
}
 
Example #18
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
RoutingHandler getPetStoreHandler() {
    ForwardRequestHandler forwardHandler = new ForwardRequestHandler();
    return Handlers.routing()
            .add(Methods.POST, "/v1/pets", exchange -> exchange.getResponseSender().send("addPet"))
            .add(Methods.GET, "/v1/pets/{petId}", exchange -> exchange.getResponseSender().send("getPetById"))
            .add(Methods.DELETE, "/v1/pets/{petId}", exchange -> exchange.getResponseSender().send("deletePetById"))
            .add(Methods.GET, "/v1/todoItems", forwardHandler)
            .add(Methods.GET, "/v1/pets", exchange -> {
                if (exchange.getQueryParameters() != null && exchange.getQueryParameters().containsKey("arr")) {
                    exchange.getResponseSender().send("getPets" + ", the query parameter = " + exchange.getQueryParameters() + ", length = " + exchange.getQueryParameters().get("arr").size());
                } else {
                    exchange.getResponseSender().send("getPets");
                }
            });
}
 
Example #19
Source File: JwtVerifyHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/v1/pets/{petId}", exchange -> {
                Map<String, Object> examples = new HashMap<>();
                examples.put("application/xml", StringEscapeUtils.unescapeHtml4("&lt;Pet&gt;  &lt;id&gt;123456&lt;/id&gt;  &lt;name&gt;doggie&lt;/name&gt;  &lt;photoUrls&gt;    &lt;photoUrls&gt;string&lt;/photoUrls&gt;  &lt;/photoUrls&gt;  &lt;tags&gt;  &lt;/tags&gt;  &lt;status&gt;string&lt;/status&gt;&lt;/Pet&gt;"));
                examples.put("application/json", StringEscapeUtils.unescapeHtml4("{  &quot;photoUrls&quot; : [ &quot;aeiou&quot; ],  &quot;name&quot; : &quot;doggie&quot;,  &quot;id&quot; : 123456789,  &quot;category&quot; : {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  },  &quot;tags&quot; : [ {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  } ],  &quot;status&quot; : &quot;aeiou&quot;}"));
                if(examples.size() > 0) {
                    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
                    exchange.getResponseSender().send((String)examples.get("application/json"));
                } else {
                    exchange.endExchange();
                }
            })
            .add(Methods.GET, "/v1/pets", exchange -> exchange.getResponseSender().send("get"));
}
 
Example #20
Source File: HttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param connectListener
 * @return
 */
public HttpServerExchange acceptConnectRequest(HttpUpgradeListener connectListener) {
    if(!getRequestMethod().equals(Methods.CONNECT)) {
        throw UndertowMessages.MESSAGES.notAConnectRequest();
    }
    connection.setConnectListener(connectListener);
    return this;
}
 
Example #21
Source File: HttpTraceHandler.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(exchange.getRequestMethod().equals(Methods.TRACE)) {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "message/http");
        StringBuilder body = new StringBuilder("TRACE ");
        body.append(exchange.getRequestURI());
        if(!exchange.getQueryString().isEmpty()) {
            body.append('?');
            body.append(exchange.getQueryString());
        }
        body.append(' ');
        body.append(exchange.getProtocol().toString());
        body.append("\r\n");
        for(HeaderValues header : exchange.getRequestHeaders()) {
            for(String value : header) {
                body.append(header.getHeaderName());
                body.append(": ");
                body.append(value);
                body.append("\r\n");
            }
        }
        body.append("\r\n");
        exchange.getResponseSender().send(body.toString());
    } else {
        handler.handleRequest(exchange);
    }
}
 
Example #22
Source File: TestResponse.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Simulates a FORM post by setting:
 * 
 * Content-Type to application/x-www-form-urlencoded
 * HTTP method to POST
 * URLEncoding of the given parameters
 * 
 * @param parameters The parameters to use
 * @return TestResponse instance
 */
public TestResponse withForm(Multimap<String, String> parameters) {
    String form = parameters.entries()
            .stream()
            .map(entry -> entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), Charset.forName(Default.ENCODING.toString())))
            .collect(Collectors.joining("&"));
    
    this.httpRequest.header(CONTENT_TYPE, "application/x-www-form-urlencoded");
    this.body = BodyPublishers.ofString(form);
    this.method = Methods.POST.toString();
    
    return this;
}
 
Example #23
Source File: HttpServerExchange.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @return The number of bytes sent in the entity body
 */
public long getResponseBytesSent() {
    if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) {
        return responseBytesSent;
    } else {
        return 0; //body is not allowed, even if we attempt to write it will be ignored
    }
}
 
Example #24
Source File: UndertowXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void executeReceiveRequest(final TransportRequest transportRequest,
		final URI url, final HttpHeaders headers, final XhrClientSockJsSession session,
		final SettableListenableFuture<WebSocketSession> connectFuture) {

	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR receive request for " + url);
	}

	ClientCallback<ClientConnection> clientCallback = new ClientCallback<ClientConnection>() {
		@Override
		public void completed(ClientConnection connection) {
			ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(url.getPath());
			HttpString headerName = HttpString.tryFromString(HttpHeaders.HOST);
			request.getRequestHeaders().add(headerName, url.getHost());
			addHttpHeaders(request, headers);
			HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
			connection.sendRequest(request, createReceiveCallback(transportRequest,
					url, httpHeaders, session, connectFuture));
		}

		@Override
		public void failed(IOException ex) {
			throw new SockJsTransportFailureException("Failed to execute request to " + url, ex);
		}
	};

	this.undertowBufferSupport.httpClientConnect(this.httpClient, clientCallback, url, worker, this.optionMap);
}
 
Example #25
Source File: BodyStringCachingTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.POST, "/post", exchange -> {
                String bodyString = (String) exchange.getAttachment(BodyHandler.REQUEST_BODY_STRING);
                if (bodyString == null) {
                    exchange.getResponseSender().send("nobody");
                } else {
                    exchange.getResponseSender().send(bodyString);
                }
            });
}
 
Example #26
Source File: LimitHandlerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/", exchange -> {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                exchange.getResponseSender().send("OK");
            });
}
 
Example #27
Source File: ConsulClientImpl.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterService(String serviceId, String token) {
	String path = "/v1/agent/service/deregister/" + serviceId;
	try {
		ConsulConnection connection = getConnection(UNREGISTER_CONNECTION_KEY + Thread.currentThread().getId());
           final AtomicReference<ClientResponse> reference = connection.send(Methods.PUT, path, token, null);
           int statusCode = reference.get().getResponseCode();
           if(statusCode >= UNUSUAL_STATUS_CODE){
               logger.error("Failed to unregister on Consul, body = {}", reference.get().getAttachment(Http2Client.RESPONSE_BODY));
           }
	} catch (Exception e) {
		logger.error("Failed to unregister on Consul, Exception:", e);
	}
}
 
Example #28
Source File: RequestUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsPut() {
    // given
    HttpServerExchange mockedExchange = Mockito.mock(HttpServerExchange.class);

    // when
    when(mockedExchange.getRequestMethod()).thenReturn(Methods.PUT);
    boolean postPutPatch = RequestUtils.isPostPutPatch(mockedExchange);

    // then
    assertThat(postPutPatch, equalTo(true));
}
 
Example #29
Source File: ExceptionHandlerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ConstantOverflow")
static RoutingHandler getTestHandler() {
    return Handlers.routing()
            .add(Methods.GET, "/normal", exchange -> exchange.getResponseSender().send("normal"))
            .add(Methods.GET, "/runtime", exchange -> {
                int i = 1/0;
            })
            .add(Methods.GET, "/api", exchange -> {
                Status error = new Status("ERR10001");
                throw new ApiException(error);
            })
            .add(Methods.GET, "/uncaught", exchange -> {
                String content = new Scanner(new File("djfkjoiwejjhh9032d")).useDelimiter("\\Z").next();
            });
}
 
Example #30
Source File: ClientRequestComposerProvider.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public ClientRequest composeClientRequest(TokenRequest tokenRequest) {
    ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath(tokenRequest.getUri());
    request.getRequestHeaders().put(Headers.HOST, "localhost");
    request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
    request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
    return request;
}