public static HttpMethod mapToUnirestHttpMethod(drinkwater.rest.HttpMethod methodAsAnnotation) { switch (methodAsAnnotation.value().toUpperCase()) { case "GET": return HttpMethod.GET; case "POST": return HttpMethod.POST; case "DELETE": return HttpMethod.DELETE; case "PUT": return HttpMethod.PUT; case "PATCH": return HttpMethod.PATCH; default: throw new RuntimeException(String.format("could not map correct http method : %s", methodAsAnnotation.value())); } }
@Test public void routesWithoutPathArg_works() throws Exception { app.routes(() -> { path("api", () -> { get(OK_HANDLER); post(OK_HANDLER); put(OK_HANDLER); delete(OK_HANDLER); patch(OK_HANDLER); path("user", () -> { get(OK_HANDLER); post(OK_HANDLER); put(OK_HANDLER); delete(OK_HANDLER); patch(OK_HANDLER); }); }); }); HttpMethod[] httpMethods = new HttpMethod[]{HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.PATCH}; for (HttpMethod httpMethod : httpMethods) { assertThat(call(httpMethod, "/api").getStatus(), is(200)); assertThat(call(httpMethod, "/api/user").getStatus(), is(200)); } }
private SwaggerGeneratorInput(String endpoint, HttpMethod method, Map<String, String> pathParams, Map<String, String> headers, Map<String, Object> parameters, String swaggerJSONFilePath, boolean isAuthentication, String username, String password, String host, String basePath, String apiPath, String apiName, String apiSummary, String apiDescription, List<String> apiTags){ this.endpoint = endpoint; this.pathParams = pathParams; this.headers = headers; this.parameters = parameters; this.swaggerJSONFile = swaggerJSONFilePath; this.method = method; this.authentication = isAuthentication; this.username = username; this.password = password; this.host = host; this.basePath = basePath; this.apiPath = apiPath; this.apiName = apiName; this.apiSummary = apiSummary; this.apiDescription = apiDescription; this.apiTags = apiTags; }
private static RestDefinition toRestdefinition(RouteBuilder builder, Method method, HttpMethod httpMethod, String restPath) { RestDefinition answer = builder.rest(); String fromPath = restPath; if (httpMethod == HttpMethod.GET) { answer = answer.get(fromPath); } else if (httpMethod == HttpMethod.POST) { answer = answer.post(fromPath); } else if (httpMethod == HttpMethod.PUT) { answer = answer.put(fromPath); } else if (httpMethod == HttpMethod.DELETE) { answer = answer.delete(fromPath); } else if (httpMethod == HttpMethod.PATCH) { answer = answer.patch(fromPath); } else { throw new RuntimeException("method currently not supported in Rest Paths : " + httpMethod); } answer = setBodyType(answer, method); return answer; }
@Test public void testRequestWithoutCustomHeaders() { // GIVEN a fake url String remote = "https://fake.kinto.url"; // AND a kintoClient KintoClient kintoClient = new KintoClient(remote); // AND an ENDPOINTS ENDPOINTS endpoint = ENDPOINTS.GROUPS; // WHEN calling request GetRequest request = kintoClient.request(endpoint); // THEN the root part is initialized assertThat(request.getUrl(), is(remote + "/buckets/{bucket}/groups")); // AND the get http method is used assertThat(request.getHttpMethod(), is(HttpMethod.GET)); // AND the default headers are set assertThat(request.getHeaders(), is(defaultHeaders)); }
@Test public void testRequestWithCustomHeaders() { // GIVEN a fake url String remote = "https://fake.kinto.url"; // AND custom headers Map<String, String> customHeaders = new HashMap<>(); customHeaders.put("Authorization", "Basic supersecurestuff"); customHeaders.put("Warning", "Be careful"); customHeaders.put("Accept", "application/html"); // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); customHeaders.forEach((k, v) -> expectedHeaders.merge(k, Arrays.asList(v), (a, b) -> a.addAll(b) ? a:a)); // AND a kintoClient KintoClient kintoClient = new KintoClient(remote, customHeaders); // AND an ENDPOINTS ENDPOINTS endpoint = ENDPOINTS.GROUPS; // WHEN calling request GetRequest request = kintoClient.request(endpoint); // THEN the root part is initialized assertThat(request.getUrl(), is(remote + "/buckets/{bucket}/groups")); // AND the get http method is used assertThat(request.getHttpMethod(), is(HttpMethod.GET)); // AND the default headers are set assertThat(request.getHeaders(), is(expectedHeaders)); }
/** * Perform a request with body to the API * * @param httpMethod * @param url path of request * @param body content to be sent * @param opts * @return the request response */ public JsonNode request(HttpMethod httpMethod, String url, JsonNode body, RequestOptions opts) { if (opts == null) { opts = RequestOptions.defaults(); } prepareRequest(); HttpRequestWithBody req = createRequest(httpMethod, url, opts); if (body != null) { req.body(body); } return tryRequest(req, opts); }
public String get(String key) throws Exception { HttpRequest request = new HttpRequestWithBody( HttpMethod.GET, makeConsulUrl(key) + "?raw" ).getHttpRequest(); authorizeHttpRequest(request); HttpResponse<String> response; try { response = HttpClientHelper.request(request, String.class); } catch (Exception exception) { throw new ConsulException("Consul request failed", exception); } if (response.getStatus() == 404) { return null; } String encrypted = response.getBody(); return encryption.decrypt(encrypted); }
private T doWork() { try { setupErrorHandlers(); WorkingContext workingContext = workingContext(); HttpRequest builtRequest = buildUnirest(workingContext) .queryString(workingContext.getQueryParams()) .headers(workingContext.getHeaders()).header("Ocp-Apim-Subscription-Key", cognitiveContext.subscriptionKey); if (!workingContext.getHttpMethod().equals(HttpMethod.GET) && workingContext().getPayload().size() > 0) { buildBody((HttpRequestWithBody) builtRequest); } HttpResponse response; if (typedResponse() == InputStream.class) response = builtRequest.asBinary(); else response = builtRequest.asString(); checkForError(response); return postProcess(typeResponse(response.getBody())); } catch (UnirestException | IOException e) { throw new CognitiveException(e); } }
public static HttpMethod httpMethodFor(Method method) { HttpMethod defaultHttpMethod = HttpMethod.GET; drinkwater.rest.HttpMethod methodAsAnnotation = method.getDeclaredAnnotation(drinkwater.rest.HttpMethod.class); if (methodAsAnnotation != null) { return mapToUnirestHttpMethod(methodAsAnnotation); } return List.ofAll(prefixesMap.entrySet()) .filter(prefix -> startsWithOneOf(method.getName(), prefix.getValue())) .map(entryset -> entryset.getKey()) .getOrElse(defaultHttpMethod); }
private static String restPath(Method method, HttpMethod httpMethod) { if (httpMethod == HttpMethod.OPTIONS) { return ""; } String fromPath = getPathFromAnnotation(method); if (fromPath == null || fromPath.isEmpty()) { fromPath = List.of(prefixesMap.get(httpMethod)) .filter(prefix -> method.getName().toLowerCase().startsWith(prefix)) .map(prefix -> method.getName().replace(prefix, "").toLowerCase()) .getOrElse(""); //if still empty if (fromPath.isEmpty()) { fromPath = method.getName(); } } if (httpMethod == HttpMethod.GET) { if (fromPath == null || fromPath.isEmpty()) { fromPath = javaslang.collection.List.of(method.getParameters()) .map(p -> "{" + p.getName() + "}").getOrElse(""); } } return fromPath; }
private void init() { HttpMethod httpMethod = httpMethodFor(method); List<Parameter> parameterInfos = javaslang.collection.List.of(method.getParameters()); NoBody noBodyAnnotation = method.getAnnotation(NoBody.class); hasReturn = returnsVoid(method); if (parameterInfos.size() == 0) { return; } if (httpMethod == HttpMethod.GET) { hasBody = false; } else if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.DELETE || httpMethod == HttpMethod.PUT) { if (parameterInfos.size() > 0) { hasBody = true; } if (noBodyAnnotation != null) { hasBody = false; } } else { throw new RuntimeException("come back here : MethodToRestParameters.init()"); } if (hasBody) { // first parameter of the method will be assigned with the body content headerNames = parameterInfos.tail().map(p -> mapName(p)).toList(); } else { headerNames = parameterInfos.map(p -> mapName(p)).toList(); } }
@Test public void test_json_jackson_throwsForBadObject() throws Exception { app.get("/hello", ctx -> ctx.status(200).json(new TestObject_NonSerializable())); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(500)); assertThat(response.getBody(), is("Internal server error")); }
@Test public void test_json_jacksonMapsJsonToObject_throwsForBadObject() throws Exception { app.get("/hello", ctx -> ctx.json(ctx.bodyAsClass(TestObject_NonSerializable.class).getClass().getSimpleName())); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(500)); assertThat(response.getBody(), is("Internal server error")); }
@Test public void test_justFilters_is404() throws Exception { Handler emptyHandler = ctx -> { }; app.before(emptyHandler); app.after(emptyHandler); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(404)); assertThat(response.getBody(), is("Not found")); }
@Test public void test_haltBeforeWildcard_works() throws Exception { app.before("/admin/*", ctx -> { throw new HaltException(401); }); app.get("/admin/protected", ctx -> ctx.result("Protected resource")); HttpResponse<String> response = call(HttpMethod.GET, "/admin/protected"); assertThat(response.getStatus(), is(401)); assertThat(response.getBody(), not("Protected resource")); }
@Test public void test_haltInRoute_works() throws Exception { app.get("/some-route", ctx -> { throw new HaltException(401, "Stop!"); }); HttpResponse<String> response = call(HttpMethod.GET, "/some-route"); assertThat(response.getBody(), is("Stop!")); assertThat(response.getStatus(), is(401)); }
@Test public void test_afterRuns_afterHalt() throws Exception { app.get("/some-route", ctx -> { throw new HaltException(401, "Stop!"); }).after(ctx -> { ctx.status(418); }); HttpResponse<String> response = call(HttpMethod.GET, "/some-route"); assertThat(response.getBody(), is("Stop!")); assertThat(response.getStatus(), is(418)); }
@Test public void test_all_mapped_verbs_ok() throws Exception { app.get("/mapped", OK_HANDLER); app.post("/mapped", OK_HANDLER); app.put("/mapped", OK_HANDLER); app.delete("/mapped", OK_HANDLER); app.patch("/mapped", OK_HANDLER); app.head("/mapped", OK_HANDLER); app.options("/mapped", OK_HANDLER); for (HttpMethod httpMethod : HttpMethod.values()) { assertThat(call(httpMethod, "/mapped").getStatus(), is(200)); } }
@Test public void test_resultString() throws Exception { app.get("/hello", ctx -> ctx.status(418) .result(MY_BODY) .header("X-HEADER-1", "my-header-1") .header("X-HEADER-2", "my-header-2")); HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(418)); assertThat(response.getBody(), is(MY_BODY)); assertThat(response.getHeaders().getFirst("X-HEADER-1"), is("my-header-1")); assertThat(response.getHeaders().getFirst("X-HEADER-2"), is("my-header-2")); }
@Test public void test_resultStream() throws Exception { byte[] buf = new byte[65537]; // big and not on a page boundary new Random().nextBytes(buf); app.get("/stream", ctx -> ctx.result(new ByteArrayInputStream(buf))); HttpResponse<String> response = call(HttpMethod.GET, "/stream"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); assertThat(IOUtils.copy(response.getRawBody(), bout), is(buf.length)); assertThat(buf, equalTo(bout.toByteArray())); }
@Test public void test_redirectWithStatus() throws Exception { app.get("/hello", ctx -> ctx.redirect("/hello-2", 302)); app.get("/hello-2", ctx -> ctx.result("Redirected")); Unirest.setHttpClient(noRedirectClient); // disable redirects HttpResponse<String> response = call(HttpMethod.GET, "/hello"); assertThat(response.getStatus(), is(302)); Unirest.setHttpClient(defaultHttpClient); // re-enable redirects response = call(HttpMethod.GET, "/hello"); assertThat(response.getBody(), is("Redirected")); }
@Test public void test_createCookie() throws Exception { app.post("/create-cookies", ctx -> ctx.cookie("name1", "value1").cookie("name2", "value2")); HttpResponse<String> response = call(HttpMethod.POST, "/create-cookies"); List<String> cookies = response.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem("name1=value1")); assertThat(cookies, hasItem("name2=value2")); }
@Test public void test_deleteCookie() throws Exception { app.post("/create-cookie", ctx -> ctx.cookie("name1", "value1")); app.post("/delete-cookie", ctx -> ctx.removeCookie("name1")); HttpResponse<String> response = call(HttpMethod.POST, "/create-cookies"); List<String> cookies = response.getHeaders().get("Set-Cookie"); assertThat(cookies, is(nullValue())); }
@Test public void test_cookieBuilder() throws Exception { app.post("/create-cookie", ctx -> { ctx.cookie(CookieBuilder.cookieBuilder("Test", "Tast")); }); HttpResponse<String> response = call(HttpMethod.POST, "/create-cookie"); List<String> cookies = response.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem("Test=Tast")); }
@Test public void listCollections() throws Exception { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<JSONObject>() { public JSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat(getRequest.getUrl(), is(remote + "/buckets/bucketName/collections")); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new JSONObject("{data:[{id: \"col1\"},{id:\"col2\"}]}"); } }) .when(kintoClient) .execute(any(GetRequest.class)); // WHEN calling listBuckets Set<Collection> collections = kintoClient.bucket("bucketName").listCollections(); // THEN check if the answer is correctly called by checking the result assertThat(collections.size(), is(2)); }
@Test public void getData() throws Exception { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<JSONObject>() { public JSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat(getRequest.getUrl(), is(remote + "/buckets/bucketName")); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new JSONObject("{}"); } }) .when(kintoClient) .execute(any(GetRequest.class)); // WHEN calling bucket getData JSONObject jsonObject = kintoClient.bucket("bucketName").getData(); // THEN check if the answer is correctly called by checking the result assertThat(jsonObject.toString(), is("{}")); }
@Test public void getData() throws Exception { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<JSONObject>() { public JSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat(getRequest.getUrl(), is(remote + "/buckets/bucketName/collections/collectionName")); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new JSONObject("{}"); } }) .when(kintoClient) .execute(any(GetRequest.class)); // WHEN calling bucket.collection.getData JSONObject jsonObject = kintoClient .bucket("bucketName") .collection("collectionName") .getData(); // THEN check if the answer is correctly called by checking the result assertThat(jsonObject.toString(), is("{}")); }
@Test public void listRecords() throws Exception { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<JSONObject>() { public JSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat( getRequest.getUrl(), is(remote + "/buckets/bucketName/collections/collectionName/records") ); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new JSONObject("{data:[{foo: \"bar\"},{bar: \"baz\"}]}"); } }) .when(kintoClient) .execute(any(GetRequest.class)); // WHEN calling bucket.collection.listRecords Set<JSONObject> records = kintoClient .bucket("bucketName") .collection("collectionName") .listRecords(); // THEN check if the answer is correctly called by checking the result assertThat(records.size(), is(2)); }
@Test public void listRecordsClazz() throws Exception { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<SimpleClass>() { public SimpleClass answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat( getRequest.getUrl(), is(remote + "/buckets/bucketName/collections/collectionName/records") ); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new SimpleClass("hello"); } }) .when(kintoClient) .execute(any(GetRequest.class), any(Class.class)); // WHEN calling bucket.collection.listRecords SimpleClass object = kintoClient .bucket("bucketName") .collection("collectionName") .listRecords(SimpleClass.class); // THEN check if the answer is correctly called by checking the result assertThat(object.getParam(), is("hello")); }
@Test public void getRecord() throws Exception { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<JSONObject>() { public JSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat( getRequest.getUrl(), is(remote + "/buckets/bucketName/collections/collectionName/records/recordId") ); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new JSONObject("{}"); } }) .when(kintoClient) .execute(any(GetRequest.class)); // WHEN calling bucket.collection.listRecords JSONObject jsonObject = kintoClient .bucket("bucketName") .collection("collectionName") .getRecord("recordId"); // THEN check if the answer is correctly called by checking the result assertThat(jsonObject.toString(), is("{}")); }
@Test public void testListBuckets() throws KintoException, ClientException, UnirestException { // GIVEN a fake remote kinto url String remote = "https://fake.kinto.url"; // AND expected headers Map<String, List<String>> expectedHeaders = new HashMap<>(defaultHeaders); // AND a kintoClient KintoClient kintoClient = spy(new KintoClient(remote)); // AND a mocked kintoClient doAnswer(new Answer<JSONObject>() { public JSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); GetRequest getRequest = (GetRequest)args[0]; // THEN the correct endpoint is called assertThat(getRequest.getUrl(), is(remote + "/buckets")); // AND headers are corrects assertThat(getRequest.getHeaders(), is(expectedHeaders)); // AND the get method is used assertThat(getRequest.getHttpMethod(), is(HttpMethod.GET)); return new JSONObject("{}"); } }) .when(kintoClient) .execute(any(GetRequest.class)); // WHEN calling listBuckets JSONObject jsonObject = kintoClient.listBuckets(); // THEN check if the answer is correctly called by checking the result assertThat(jsonObject.toString(), is("{}")); }
public void put(String key, String value) throws Exception { String encrypted; try { encrypted = encryption.encrypt(value); } catch (Exception e) { throw new Exception("Could not encrypt value"); } HttpRequest request = new HttpRequestWithBody( HttpMethod.PUT, makeConsulUrl(key) ).body(encrypted).getHttpRequest(); authorizeHttpRequest(request); HttpResponse<String> response; try { response = HttpClientHelper.request(request, String.class); } catch (Exception exception) { throw new ConsulException("Consul request failed", exception); } if (!response.getBody().equals("true")) { throw new ConsulException( String.format("Consul PUT %s failed", key) ); } }
public List<String> list(String key) throws Exception { HttpRequest request = new HttpRequestWithBody( HttpMethod.GET, makeConsulUrl(key) + "?keys&separator=/" ).getHttpRequest(); authorizeHttpRequest(request); HttpResponse<JsonNode> response; try { response = HttpClientHelper.request(request, JsonNode.class); } catch (Exception exception) { throw new ConsulException("Consul request failed", exception); } if (response.getStatus() == 404) { return null; } JsonNode data = response.getBody(); if (!data.isArray()) { throw new ConsulException("Malformed response - expected an array"); } List<String> keys = new ArrayList<>(data.getArray().length()); data.getArray().forEach((object) -> { String iter = object.toString(); if (prefix != null) { iter = iter.substring(prefix.length()); } keys.add(iter); }); return keys; }
private void buildContext(Object image) { workingContext.addQueryParameter("userData", userData) .setPath("face/v1.0/facelists/${faceListId}/persistedFaces").addPathVariable("faceListId", faceListId) .addQueryParameter("userData", userData) .httpMethod(HttpMethod.POST); if (isNotEmpty(targetFace)) workingContext.addQueryParameter("targetFace", targetFace); if (image instanceof String) workingContext.addPayload("url", String.valueOf(image)); if (image instanceof InputStream) workingContext.addPayload(IMAGE_INPUT_STREAM_KEY, image); }