public void registerWithRouter(Router router) { // Priming queries router.route(HttpMethod.POST, "/prime/:clusterIdOrName").handler(this::primeQuery); router .route(HttpMethod.POST, "/prime/:clusterIdOrName/:datacenterIdOrName") .handler(this::primeQuery); router .route(HttpMethod.POST, "/prime/:clusterIdOrName/:datacenterIdOrName/:nodeIdOrName") .handler(this::primeQuery); // Deleting primed queries router.route(HttpMethod.DELETE, "/prime/:clusterIdOrName").handler(this::clearPrimedQueries); router .route(HttpMethod.DELETE, "/prime/:clusterIdOrName/:datacenterIdOrName") .handler(this::clearPrimedQueries); router .route(HttpMethod.DELETE, "/prime/:clusterIdOrName/:datacenterIdOrName/:nodeIdOrName") .handler(this::primeQuery); }
public void registerWithRouter(Router router) { router.route(HttpMethod.GET, "/log/:clusterIdOrName").handler(this::getQueryLog); router .route(HttpMethod.GET, "/log/:clusterIdOrName/:datacenterIdOrName") .handler(this::getQueryLog); router .route(HttpMethod.GET, "/log/:clusterIdOrName/:datacenterIdOrName/:nodeIdOrName") .handler(this::getQueryLog); router.route(HttpMethod.DELETE, "/log/:clusterIdOrName").handler(this::deleteQueryLog); router .route(HttpMethod.DELETE, "/log/:clusterIdOrName/:datacenterIdOrName") .handler(this::deleteQueryLog); router .route(HttpMethod.DELETE, "/log/:clusterIdOrName/:datacenterIdOrName/:nodeIdOrName") .handler(this::deleteQueryLog); }
@Test public void getFormattedElement() { AccessLogParam param = new AccessLogParam(); RoutingContext mockContext = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); String uri = "/test/uri"; param.setRoutingContext(mockContext); Mockito.when(mockContext.request()).thenReturn(request); Mockito.when(request.method()).thenReturn(HttpMethod.DELETE); Mockito.when(request.path()).thenReturn(uri); Mockito.when(request.version()).thenReturn(HttpVersion.HTTP_1_1); String result = ELEMENT.getFormattedElement(param); assertEquals("\"DELETE " + uri + " HTTP/1.1\"", result); }
@Test public void testLog() { RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); long startMillisecond = 1416863450581L; AccessLogParam accessLogParam = new AccessLogParam().setStartMillisecond(startMillisecond) .setRoutingContext(context); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DatetimeConfigurableElement.DEFAULT_DATETIME_PATTERN, DatetimeConfigurableElement.DEFAULT_LOCALE); simpleDateFormat.setTimeZone(TimeZone.getDefault()); Mockito.when(context.request()).thenReturn(request); Mockito.when(request.method()).thenReturn(HttpMethod.DELETE); Deencapsulation.invoke(ACCESS_LOG_HANDLER, "log", accessLogParam); Mockito.verify(logger).info("DELETE" + " - " + simpleDateFormat.format(startMillisecond)); }
@Test public void testCreateRequest() { HttpClient client = mock(HttpClient.class); Invocation invocation = mock(Invocation.class); OperationMeta operationMeta = mock(OperationMeta.class); Endpoint endpoint = mock(Endpoint.class); URIEndpointObject address = mock(URIEndpointObject.class); when(invocation.getEndpoint()).thenReturn(endpoint); when(endpoint.getAddress()).thenReturn(address); when(address.isSslEnabled()).thenReturn(false); when(invocation.getOperationMeta()).thenReturn(operationMeta); RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class); when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation); IpPort ipPort = mock(IpPort.class); when(ipPort.getPort()).thenReturn(10); when(ipPort.getHostOrIp()).thenReturn("ever"); AsyncResponse asyncResp = mock(AsyncResponse.class); List<HttpMethod> methods = new ArrayList<>( Arrays.asList(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PATCH)); for (HttpMethod method : methods) { when(swaggerRestOperation.getHttpMethod()).thenReturn(method.toString()); HttpClientRequest obj = VertxHttpMethod.INSTANCE.createRequest(client, invocation, ipPort, "good", asyncResp); Assert.assertNull(obj); } }
@SuppressWarnings("unchecked") private Router logRoutes(Router router) { try { for (Route route : router.getRoutes()) { // path is public but methods are not, we use reflection to make that accessible @SuppressWarnings("JavaReflectionMemberAccess") Field f = route.getClass().getDeclaredField("methods"); f.setAccessible(true); Set<HttpMethod> methods = (Set<HttpMethod>) f.get(route); if (isNotBlank(route.getPath())) { methods.forEach(httpMethod -> logger.info("Route: [{}] {}", httpMethod, route.getPath())); } } } catch (Exception ex) { logger.info("Could not list a route due to: {}!", ex.getMessage()); } return router; }
public static void asyncPostStringWithData(String url, String body, ContentType type, String encode, Handler<String> callback) { checkInitialized(); HttpClientRequest req = client.requestAbs(HttpMethod.POST, url, resp -> { resp.bodyHandler(buf -> { callback.handle(buf.toString()); }); }); switch (type) { case XML: req.putHeader("content-type", "application/xml;charset=" + encode); break; case JSON: req.putHeader("content-type", "application/json;charset=" + encode); break; case FORM: req.putHeader("content-type", "application/x-www-form-urlencoded" + encode); break; } // req.putHeader("content-length", String.valueOf(body.length())); // req.write(body); req.end(body, encode); }
/** * Enables CORS * * @param allowedOriginPattern allowed origin * @param allowCredentials allow credentials (true/false) * @param maxAge in seconds * @param allowedHeaders set of allowed headers * @param methods list of methods ... if empty all methods are allowed @return self * @return self */ public RestBuilder enableCors(String allowedOriginPattern, boolean allowCredentials, int maxAge, Set<String> allowedHeaders, HttpMethod... methods) { corsHandler = CorsHandler.create(allowedOriginPattern) .allowCredentials(allowCredentials) .maxAgeSeconds(maxAge); if (methods == null || methods.length == 0) { // if not given than all methods = HttpMethod.values(); } for (HttpMethod method : methods) { corsHandler.allowedMethod(method); } corsHandler.allowedHeaders(allowedHeaders); return this; }
/** * @param router to add handler to * @param allowedOriginPattern origin pattern * @param allowCredentials allowed credentials * @param maxAge in seconds * @param allowedHeaders set of headers or null for none * @param methods list of methods or empty for all */ public void enableCors(Router router, String allowedOriginPattern, boolean allowCredentials, int maxAge, Set<String> allowedHeaders, HttpMethod... methods) { CorsHandler handler = CorsHandler.create(allowedOriginPattern) .allowCredentials(allowCredentials) .maxAgeSeconds(maxAge); if (methods == null || methods.length == 0) { // if not given than all methods = HttpMethod.values(); } for (HttpMethod method : methods) { handler.allowedMethod(method); } handler.allowedHeaders(allowedHeaders); router.route().handler(handler); }
/** * Register this but also register the {@link CorsHandler}. The * {@link CorsHandler} will deal with the normal CORS headers after it has been * processed initially by this handler. {@inheritDoc} */ @Override public void register(final Router router) { router.route().handler(this); router.route().handler(CorsHandler.create(".+") .maxAgeSeconds(600) .allowedMethod(HttpMethod.GET) .allowedMethod(HttpMethod.POST) .allowedMethod(HttpMethod.PUT) .allowedMethod(HttpMethod.DELETE) .allowedMethod(HttpMethod.OPTIONS) .allowedHeader("Content-Type") .allowedHeader("Accept") .allowedHeader("Accept-Language") .allowedHeader("Authorization")); }
@Override public void handle(RoutingContext ctx) { StringBuilder logStrBuilder = new StringBuilder(); logStrBuilder.append(ctx.request().host()).append(" : "); logStrBuilder.append(ctx.request().method()).append(" "); logStrBuilder.append(ctx.request().uri()).append("\n"); if(ctx.request().method() != HttpMethod.GET) { // Parameters show in Request URI logStrBuilder.append("Body - ").append(ctx.request().formAttributes()); } Log.request(logStrBuilder.toString()); ctx.next(); }
@Test public void testExceptionInHandler() throws Exception { { router.route("/exception").handler(routingContext -> { throw new IllegalArgumentException("msg"); }); request("/exception", HttpMethod.GET,500); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(6, mockSpan.tags().size()); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(500, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/exception", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(1, mockSpan.logEntries().size()); Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size()); Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event")); Assert.assertTrue(mockSpan.logEntries().get(0).fields().get("error.object") instanceof Throwable); }
public static HttpMethod resolve(final Method method) { // 1. Method checking. Fn.flingUp(null == method, LOGGER, MethodNullException.class, MethodResolver.class); final Annotation[] annotations = method.getDeclaredAnnotations(); // 2. Method ignore HttpMethod result = null; for (final Annotation annotation : annotations) { final Class<?> key = annotation.annotationType(); if (METHODS.containsKey(key)) { result = METHODS.get(key); break; } } // 2. Ignore this method. if (null == result) { LOGGER.info(Info.METHOD_IGNORE, method.getName()); } return result; }
@Test public void testNoURLMapping() throws Exception { { request("/noUrlMapping", HttpMethod.GET, 404); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(404, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/noUrlMapping", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(0, mockSpan.logEntries().size()); }
/** * This method handles the registration of the various routes responsible for setting and * retrieving cluster information via http. * * @param router The router to register the endpoint with. */ public void registerWithRouter(Router router) { router.route(HttpMethod.POST, "/cluster").handler(this::provisionCluster); router.route(HttpMethod.DELETE, "/cluster/:clusterIdOrName").handler(this::unregisterCluster); router.route(HttpMethod.DELETE, "/cluster").handler(this::unregisterCluster); router.route(HttpMethod.GET, "/cluster/:clusterIdOrName").handler(this::getCluster); router.route(HttpMethod.GET, "/cluster").handler(this::getCluster); }
private void defineInitialisationRoute() { Route route = router.route(HttpMethod.GET, "/_init").produces(APPLICATION_JSON); route.blockingHandler(routingContext -> { logInfo("Initialising Java SDK modules... (" + new Date().toString() + ")"); sdk = APIMappingGenerator.getSDK(); logDebug(JsonObject.mapFrom(sdk).encodePrettily()); JsonObject emptyResponse = new JsonObject(); setResponse(routingContext).end(emptyResponse.encode()); }); }
private HttpTestResponse clearQueries(HttpClient client, Scope scope) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); try { client .request( HttpMethod.DELETE, portNum, "127.0.0.1", "/prime/" + scope.toString(), response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .end(); HttpTestResponse responseToValidate = future.get(); assertThat(responseToValidate.response.statusCode()).isEqualTo(202); return responseToValidate; } catch (Exception e) { logger.error("Exception", e); fail("Exception encountered"); } return null; }
private ClusterSpec createSingleNodeCluster(HttpClient client) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); client .request( HttpMethod.POST, portNum, "127.0.0.1", "/cluster/?data_centers=1", response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .end(); try { HttpTestResponse responseToValidate = future.get(); ObjectMapper om = ObjectMapperHolder.getMapper(); // create cluster object from json return code assertThat(responseToValidate.response.statusCode()).isEqualTo(201); ClusterSpec cluster = om.readValue(responseToValidate.body, ClusterSpec.class); return cluster; } catch (Exception e) { fail("Exception encountered"); return null; } }
private ClusterSpec createMultiNodeCluster(HttpClient client, String datacenters) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); client .request( HttpMethod.POST, portNum, "127.0.0.1", "/cluster/?data_centers=" + datacenters, response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .end(); try { HttpTestResponse responseToValidate = future.get(); ObjectMapper om = ObjectMapperHolder.getMapper(); // create cluster object from json return code assertThat(responseToValidate.response.statusCode()).isEqualTo(201); ClusterSpec cluster = om.readValue(responseToValidate.body, ClusterSpec.class); return cluster; } catch (Exception e) { fail(e.getMessage()); return null; } }
private void cors(Router router) { router.route().handler(CorsHandler.create("*") .allowedMethod(HttpMethod.GET) .allowedMethod(HttpMethod.POST) .allowedHeader("Content-Type") .allowedHeader("Accept") ); }
public static RequestContext createRequestContext(HttpMethod method, IpPort ipPort, String uri, RequestParam requestParam) { RequestContext requestContext = new RequestContext(); requestContext.setMethod(method); requestContext.setIpPort(ipPort); requestContext.setUri(uri); requestContext.setParams(requestParam); return requestContext; }
@Test public void defaultHeadersContainServiceRegistryAndAuthentication() throws Exception { MultiMap headers = RestUtils.getDefaultHeaders(); headers.addAll(RestUtils.getSignAuthHeaders(RestUtils.createSignRequest(HttpMethod.GET.toString(), new IpPort("127.0.0.1", 443), new RequestParam().addQueryParam("testParam", "test"), "test", new HashMap<>()))); assertThat(headers.get("Content-Type"), is("application/json")); assertThat(headers.get("User-Agent"), is("cse-serviceregistry-client/1.0.0")); assertThat(headers.get("x-domain-name"), is("default")); assertThat(headers.get("X-Service-AK"), is("blah...")); }
@Override public String getFormattedElement(AccessLogParam accessLogParam) { HttpServerRequest request = accessLogParam.getRoutingContext().request(); if (null == request) { return EMPTY_RESULT; } HttpMethod method = request.method(); if (null == method) { return EMPTY_RESULT; } return method.toString(); }
@Test public void testCircuitBreakerOpen(TestContext ctx) throws Exception { Async async = ctx.async(); Router router = Router.router(vertx); HttpServer server = vertx.createHttpServer().requestHandler(router::accept); Flow flow = Flow.flow(vertx) .withDiscovery(discovery); flow.route(router.get("/foo"), httpFlow -> { AtomicInteger count = new AtomicInteger(6); doRec(6, fut -> { httpFlow.httpRequest(new JsonObject().put("name", "hello-service"), HttpMethod.GET, "/", ctx.asyncAssertFailure(v1 -> { CircuitBreakerState state = flow.breaker("hello-service").state(); int val = count.decrementAndGet(); if (val == 0) { ctx.assertEquals(CircuitBreakerState.OPEN, state); httpFlow.response().end("failed"); async.complete(); } else if (val == 1) { ctx.assertEquals(CircuitBreakerState.OPEN, state); } else { ctx.assertEquals(CircuitBreakerState.CLOSED, state); } fut.complete(); })); }); }); Async listenAsync = ctx.async(); server.listen(8080, ctx.asyncAssertSuccess(v -> listenAsync.complete())); listenAsync.awaitSuccess(10000); client .get(8080, "localhost", "/foo") .send(ctx.asyncAssertSuccess(resp -> { ctx.assertEquals(200, resp.statusCode()); ctx.assertEquals("failed", resp.bodyAsString()); })); }
private static void asyncRequestString(HttpMethod method, String url, Handler<String> callback){ checkInitialized(); client.requestAbs(method, url, resp -> { resp.bodyHandler(buf -> { callback.handle(buf.toString()); }); }).end(); }
private static void asyncRequestJson(HttpMethod method, String url, Handler<JsonObject> callback){ checkInitialized(); client.requestAbs(method, url, resp -> { resp.bodyHandler(buf -> { callback.handle(buf.toJsonObject()); }); }).end(); }
private static void asyncRequestJson(HttpMethod method, String url, Future<JsonObject> callback){ checkInitialized(); client.requestAbs(method, url, resp -> { resp.bodyHandler(buf -> { callback.complete(buf.toJsonObject()); }); }).end(); }
@Override public StopWatch responsePushed(StopWatch socketWatch, HttpMethod method, String uri, HttpServerResponse response) { counterService.increment("responses.pushed"); StopWatch stopWatch = new StopWatch(); stopWatch.start(); return stopWatch; }
public void get(String uri, JsonObject param, Handler<AsyncResult<HttpResponse<Buffer>>> h) { HttpRequest<Buffer> req = app.webclient.get(this.port,this.host, uri) .timeout(app.timeout); if(param!=null){ param.forEach(entry -> { req.addQueryParam(entry.getKey(), "" + entry.getValue()); }); } Handler<AsyncResult<HttpResponse<Buffer>>> callback =res->{ if(res.succeeded()){ continueFailTimes=0; log.info("{}, {} http://{}:{}{}",app.name,HttpMethod.GET,this.host,this.port,uri); h.handle(Future.succeededFuture(res.result())); }else{ Throwable t = res.cause(); this.onException(t, uri); h.handle(Future.failedFuture(t)); } }; // taskInProcessing=taskInProcessing+1; if(this.breaker!=null){ breaker.<HttpResponse<Buffer>>execute(f->{ req.send(f); }).setHandler(callback); }else{ req.send(callback); } }
@Test public void testExceptionInHandlerWithFailureHandler() throws Exception { { router.route("/exceptionWithHandler").handler(routingContext -> { throw new IllegalArgumentException("msg"); }).failureHandler(event -> { event.response() .setStatusCode(404) .end(); }); request("/exceptionWithHandler", HttpMethod.GET, 404); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(6, mockSpan.tags().size()); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(404, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/exceptionWithHandler", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(1, mockSpan.logEntries().size()); Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size()); Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event")); Assert.assertTrue(mockSpan.logEntries().get(0).fields().get("error.object") instanceof Throwable); }
@Test public void testPush(TestContext context) { StringBuilder res = new StringBuilder(); response.push(HttpMethod.GET, "/", ar -> { res.append("DONE"); context.assertTrue(ar.failed()); }); context.assertEquals("DONE", res.toString()); }
private RouteDefinition method(String value) { for (HttpMethod item : HttpMethod.values()) { if (StringUtils.equals(value, item.name(), true)) { Assert.isNull(method, "Method already set to: " + method + "!"); method = item; break; } } return this; }
@Test public void testTimeoutHandler() throws Exception { { router.route().handler(TimeoutHandler.create(300, 501)); router.route("/timeout") .blockingHandler(routingContext -> { try { Thread.sleep(10000); routingContext.response() .setStatusCode(202) .end(); } catch (InterruptedException e) { e.printStackTrace(); routingContext.response().end(); } }); request("/timeout", HttpMethod.GET, 501); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(6, mockSpan.tags().size()); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(501, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/timeout", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(0, mockSpan.logEntries().size()); }
private static void sendErrorResponse(final RoutingContext context, final WebApplicationException webAppException) { context.response().setStatusCode(webAppException.getResponse().getStatus()); context.response().setStatusMessage(webAppException.getResponse().getStatusInfo().getReasonPhrase()); if (context.request().method() != HttpMethod.HEAD) { if (webAppException.getResponse().getMediaType() == null) { context.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); } else { context.response().putHeader(HttpHeaders.CONTENT_TYPE, webAppException.getResponse().getMediaType().toString()); } context.response().end(webAppException.getResponse().getStatusInfo().getReasonPhrase()); } }
/** * Constructs JaxRsPath. * * @param path * path * @param consumes * content types consumed * @param produces * content types produced * @param method * HTTP method. */ public JaxRsPath(final String path, final String[] consumes, final String[] produces, final HttpMethod method) { if (path.isEmpty()) { throw new IllegalArgumentException("path cannot be empty"); } this.path = path; this.consumes = consumes; this.produces = produces; this.method = method; final Pattern placeholderPattern = Pattern.compile("/\\{([^}]+)}"); final Pattern regexPlaceholderPattern = Pattern.compile("[-A-Za-z_0-9]+:\\s*(.+)"); final Matcher matcher = placeholderPattern.matcher(path); final StringBuffer b = new StringBuffer(); while (matcher.find()) { final Matcher m2 = regexPlaceholderPattern.matcher(matcher.group(1)); if (m2.matches()) { matcher.appendReplacement(b, "/" + m2.group(1)); } else { matcher.appendReplacement(b, "/[^/]+"); } } matcher.appendTail(b); pathRegex = b.toString(); exact = pathRegex.equals(path); }
/** * Gets the {@link HttpMethod} based on the annotation associated with the * method. Only GET, POST, PUT, DELETE are supported. * * @param m * method * @return {@link HttpMethod} */ private HttpMethod getHttpMethod(final Method m) { if (m.getAnnotation(GET.class) != null) { return HttpMethod.GET; } else if (m.getAnnotation(POST.class) != null) { return HttpMethod.POST; } else if (m.getAnnotation(PUT.class) != null) { return HttpMethod.PUT; } else if (m.getAnnotation(DELETE.class) != null) { return HttpMethod.DELETE; } else { throw new IllegalStateException("Unabel to determine HTTP Method"); } }
@Test public void testHttpToHttp(TestContext ctx) throws Exception { Async async = ctx.async(); Router router = Router.router(vertx); HttpServer server = vertx.createHttpServer().requestHandler(router::accept); Flow flow = Flow.flow(vertx) .withDiscovery(discovery); flow.route(router.get("/foo"), httpFlow -> { httpFlow.httpRequest(new JsonObject().put("name", "hello-service"), HttpMethod.GET, "/", ctx.asyncAssertSuccess(req -> { req.send(ctx.asyncAssertSuccess(resp -> { ctx.assertEquals(200, resp.statusCode()); httpFlow.response().end(resp.body()); async.complete(); })); })); }); Async listenAsync = ctx.async(); server.listen(8080, ctx.asyncAssertSuccess(v -> listenAsync.complete())); listenAsync.awaitSuccess(10000); startBackendBlocking(ctx); publishBackendBlocking(ctx); client .get(8080, "localhost", "/foo") .send(ctx.asyncAssertSuccess(resp -> { ctx.assertEquals(200, resp.statusCode()); ctx.assertEquals("Hello World", resp.bodyAsString()); })); }
@Test public void testSimplePlaceholder() { final JaxRsPath path = new JaxRsPath("/exact/{id}", new String[0], new String[0], HttpMethod.POST); assertFalse(path.isExact()); assertEquals("/exact/[^/]+", path.getPathRegex()); }
@Test public void testSimplePlaceholder2() { final JaxRsPath path = new JaxRsPath("/exact/{id}/foo", new String[0], new String[0], HttpMethod.POST); assertFalse(path.isExact()); assertEquals("/exact/[^/]+/foo", path.getPathRegex()); }
@Test public void testSimplePlaceholder3() { final JaxRsPath path = new JaxRsPath("/exact/{id}/foo/{x}", new String[0], new String[0], HttpMethod.PUT); assertFalse(path.isExact()); assertEquals("/exact/[^/]+/foo/[^/]+", path.getPathRegex()); }