Java 类com.mashape.unirest.http.HttpMethod 实例源码

项目:drinkwater-java    文件:RestHelper.java   
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()));
    }
}
项目:javalin    文件:TestApiBuilder.java   
@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));
    }
}
项目:api2swagger    文件:SwaggerGeneratorInput.java   
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;
}
项目:drinkwater-java    文件:RestHelper.java   
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()));
    }
}
项目:drinkwater-java    文件:RestHelper.java   
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;
}
项目:kinto-http-java    文件:KintoClientTest.java   
@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));
}
项目:kinto-http-java    文件:KintoClientTest.java   
@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));
}
项目:raptor    文件:HttpClient.java   
/**
 * 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);
}
项目:gatekeeper    文件:Client.java   
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);
}
项目:cognitivej    文件:RestAction.java   
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);
    }
}
项目:drinkwater-java    文件:RestHelper.java   
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);
    }
项目:drinkwater-java    文件:RestHelper.java   
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;
}
项目:drinkwater-java    文件:RestHelper.java   
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;
}
项目:drinkwater-java    文件:MethodToRestParameters.java   
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();
    }

}
项目:javalin    文件:TestTranslators.java   
@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"));
}
项目:javalin    文件:TestTranslators.java   
@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"));
}
项目:javalin    文件:TestFilters.java   
@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"));
}
项目:javalin    文件:TestHaltException.java   
@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"));
}
项目:javalin    文件:TestHaltException.java   
@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));
}
项目:javalin    文件:TestHaltException.java   
@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));
}
项目:javalin    文件:TestHttpVerbs.java   
@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));
    }
}
项目:javalin    文件:TestResponse.java   
@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"));
}
项目:javalin    文件:TestResponse.java   
@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()));
}
项目:javalin    文件:TestResponse.java   
@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"));
}
项目:javalin    文件:TestResponse.java   
@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"));
}
项目:javalin    文件:TestResponse.java   
@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()));
}
项目:javalin    文件:TestResponse.java   
@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"));
}
项目:drinkwater-java    文件:RestHelper.java   
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);
    }
项目:drinkwater-java    文件:RestHelper.java   
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;
}
项目:drinkwater-java    文件:MethodToRestParameters.java   
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();
    }

}
项目:kinto-http-java    文件:BucketTest.java   
@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));
}
项目:kinto-http-java    文件:BucketTest.java   
@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("{}"));
}
项目:kinto-http-java    文件:CollectionTest.java   
@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("{}"));
}
项目:kinto-http-java    文件:CollectionTest.java   
@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));
}
项目:kinto-http-java    文件:CollectionTest.java   
@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"));
}
项目:kinto-http-java    文件:CollectionTest.java   
@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("{}"));
}
项目:kinto-http-java    文件:KintoClientTest.java   
@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("{}"));
}
项目:gatekeeper    文件:Client.java   
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)
        );
    }
}
项目:gatekeeper    文件:Client.java   
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;
}
项目:cognitivej    文件:AddFaceToFaceListAction.java   
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);
}