Java Code Examples for javax.ws.rs.HttpMethod#POST

The following examples show how to use javax.ws.rs.HttpMethod#POST . 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: Transaction.java    From pagarme-java with The Unlicense 6 votes vote down vote up
public Transaction refund(final BankAccount bankAccount) throws PagarMeException {
    validateId();

    final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST,
            String.format("/%s/%s/refund", getClassName(), getId()));
            
    Map<String, Object> bankAccountMap = JSONUtils.objectToMap(bankAccount);
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("bank_account", bankAccountMap);
    request.setParameters(parameters);

    final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class);
    copy(other);
    flush();

    return other;
}
 
Example 2
Source File: ResourceMethod.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private String httpMethod(Method method) {
    if (method.isAnnotationPresent(GET.class)) {
        return HttpMethod.GET;
    } else if (method.isAnnotationPresent(POST.class)) {
        return HttpMethod.POST;
    } else if (method.isAnnotationPresent(PUT.class)) {
        return HttpMethod.PUT;
    } else if (method.isAnnotationPresent(DELETE.class)) {
        return HttpMethod.DELETE;
    } else {
        return null;
    }
}
 
Example 3
Source File: UserInfoClient.java    From oxAuth with MIT License 5 votes vote down vote up
@Override
public String getHttpMethod() {
    if (request.getAuthorizationMethod() == null
            || request.getAuthorizationMethod() == AuthorizationMethod.AUTHORIZATION_REQUEST_HEADER_FIELD
            || request.getAuthorizationMethod() == AuthorizationMethod.URL_QUERY_PARAMETER) {
        return HttpMethod.GET;
    } else /*if (request.getAuthorizationMethod() == AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER)*/ {
        return HttpMethod.POST;
    }
}
 
Example 4
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Test
public void faultyPostRequestShouldBeLogged() throws URISyntaxException {

    String url = "/postAtFault";
    String headerStr = "postAtFaultHost";
    WireMock.stubFor(post(urlEqualTo(url))
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(aResponse().withFixedDelay(1000)));

    String requestMethod = HttpMethod.POST;


    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .setRequestTimeout(300)
                    .setMethod(requestMethod)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();

    Throwable exception = null;
    try {
        parsecHttpClient.criticalExecute(request).get();
    } catch (Exception e) {
        exception = e;
    }

    assertThat(exception, is(notNullValue()));

    String patternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "",-1, "single");

    then(mockAppender).should().doAppend(argThat(hasToString(matchesPattern(patternAsStr))));

}
 
Example 5
Source File: Recipient.java    From pagarme-java with The Unlicense 5 votes vote down vote up
public BulkAnticipation cancelAnticipation(BulkAnticipation anticipation) throws PagarMeException{
    validateId();
    String path = String.format("/%s/%s/%s/%s/cancel", getClassName(), getId(), anticipation.getClassName(), anticipation.getId());
    final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, path);
    JsonObject response = request.execute();
    BulkAnticipation canceledAnticipation = JSONUtils.getAsObject(response, BulkAnticipation.class);
    return canceledAnticipation;
}
 
Example 6
Source File: Subscription.java    From pagarme-java with The Unlicense 5 votes vote down vote up
public Subscription settleCharges(Integer chargesToSettle) throws PagarMeException {
    validateId();
    final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST,
            String.format("/%s/%s/settle_charge", getClassName(), getId()));
    if (chargesToSettle != null) {
        Map<String, Object> charges = new HashMap<String, Object>();
        charges.put("charges", chargesToSettle);
        request.setParameters(charges);
    }
    return JSONUtils.getAsObject((JsonObject) request.execute(), Subscription.class);
}
 
Example 7
Source File: CompaniesTemporary.java    From pagarme-java with The Unlicense 5 votes vote down vote up
public String getTemporaryCompanyApiKey(String apiVersion) {
    try {
        final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, "/companies/temporary");
        request.setParameters(buildApiVersionParameter(apiVersion));
        CompaniesTemporary company = JSONUtils.getAsObject((JsonObject) request.execute(), CompaniesTemporary.class);

        return company.apiKey.get("test").toString();

    } catch (PagarMeException exception) {
        throw new UnsupportedOperationException(exception);
    }
}
 
Example 8
Source File: AnnotationProcessor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * Read Method annotations indicating HTTP Methods
 *
 * @param annotation
 */
private String getHTTPMethodAnnotation(Annotation annotation) {
    if (annotation.annotationType().getName().equals(GET.class.getName())) {
        return HttpMethod.GET;
    } else if (annotation.annotationType().getName().equals(POST.class.getName())) {
        return HttpMethod.POST;
    } else if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) {
        return HttpMethod.OPTIONS;
    } else if (annotation.annotationType().getName().equals(DELETE.class.getName())) {
        return HttpMethod.DELETE;
    } else if (annotation.annotationType().getName().equals(PUT.class.getName())) {
        return HttpMethod.PUT;
    }
    return null;
}
 
Example 9
Source File: Recipient.java    From pagarme-java with The Unlicense 5 votes vote down vote up
public BulkAnticipation confirmBulkAnticipation(BulkAnticipation anticipation) throws PagarMeException{
    validateId();
    String path = String.format("/%s/%s/%s/%s/confirm", getClassName(), getId(), anticipation.getClassName(), anticipation.getId());
    final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, path);
    JsonObject response = request.execute();
    BulkAnticipation confirmedAnticipation = JSONUtils.getAsObject(response, BulkAnticipation.class);
    return confirmedAnticipation;
}
 
Example 10
Source File: EarlReporter.java    From teamengine with Apache License 2.0 5 votes vote down vote up
/**
 * Processes any attributes that were attached to a test result. Attributes
 * should describe relevant test events in order to help identify the root
 * cause of a fail verdict. Specifically, the following statements are added
 * to the report:
 * <ul>
 * <li>{@value #REQ_ATTR} : Information about the request message
 * (earl:TestResult --cite:message-- http:Request)</li>
 * <li>{@value #RSP_ATTR} : Information about the response message
 * (http:Request --http:resp-- http:Response)</li>
 * </ul>
 * 
 * @param earlResult
 *            An earl:TestResult resource.
 * @param tngResult
 *            The TestNG test result.
 */
void processResultAttributes(Resource earlResult, final ITestResult tngResult) {
    if (!tngResult.getAttributeNames().contains(REQ_ATTR))
        return;
    // keep it simple for now
    String reqVal = tngResult.getAttribute(REQ_ATTR).toString();
    String httpMethod = (reqVal.startsWith("<")) ? HttpMethod.POST : HttpMethod.GET;
    Resource httpReq = this.earlModel.createResource(HTTP.Request);
    httpReq.addProperty(HTTP.methodName, httpMethod);
    if (httpMethod.equals(HttpMethod.GET)) {
        httpReq.addProperty(HTTP.requestURI, reqVal);
    } else {
    	httpReq.addProperty(HTTP.requestURI, reqVal);
        Resource reqContent = this.earlModel.createResource(CONTENT.ContentAsXML);
        // XML content may be truncated and hence not well-formed
        reqContent.addProperty(CONTENT.rest, reqVal);
        httpReq.addProperty(HTTP.body, reqContent);
    }
    Object rsp = tngResult.getAttribute(RSP_ATTR);
    if (null != rsp) {
        Resource httpRsp = this.earlModel.createResource(HTTP.Response);
        // safe assumption, but need more response info to know for sure
        Resource rspContent = this.earlModel.createResource(CONTENT.ContentAsXML);
        rspContent.addProperty(CONTENT.rest, rsp.toString());
        httpRsp.addProperty(HTTP.body, rspContent);
        httpReq.addProperty(HTTP.resp, httpRsp);
    }
    earlResult.addProperty(CITE.message, httpReq);
}
 
Example 11
Source File: DcRequest.java    From io with Apache License 2.0 4 votes vote down vote up
/**
 * POSTメソッドとしてRequestオブジェクトを生成する.
 * @param url URL
 * @return req DcRequestオブジェクト
 */
public static DcRequest post(String url) {
    DcRequest req = new DcRequest(url);
    req.method = HttpMethod.POST;
    return req;
}
 
Example 12
Source File: PushTokenDeliveryClient.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public String getHttpMethod() {
    return HttpMethod.POST;
}
 
Example 13
Source File: TokenRevocationClient.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public String getHttpMethod() {
    return HttpMethod.POST;
}
 
Example 14
Source File: ClassIntrospectorTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 4 votes vote down vote up
@Test
public void testPlainResourceSeveralOperationsWithDifferentPath() {
    Bus bus = BusFactory.getDefaultBus(true);

    ResourceMethodInfoDTO[] resourceMethodInfoDTOS =
        ClassIntrospector.getResourceMethodInfos(
            PlainResourceSeveralOperationsDifferentPath.class, bus
        ).toArray(
                new ResourceMethodInfoDTO[0]
        );

    assertEquals(2, resourceMethodInfoDTOS.length);

    List<ResourceMethodInfoDTOWrapper> wrappers = Arrays.stream(
        resourceMethodInfoDTOS
    ).map(
        ResourceMethodInfoDTOWrapper::new
    ).collect(
        Collectors.toList()
    );

    ResourceMethodInfoDTO resourceMethodInfoDTO =
        new ResourceMethodInfoDTO();

    resourceMethodInfoDTO.method = HttpMethod.GET;
    resourceMethodInfoDTO.consumingMimeType = null;
    resourceMethodInfoDTO.producingMimeType = null;
    resourceMethodInfoDTO.path = "/common";
    resourceMethodInfoDTO.nameBindings = null;

    assertTrue(
        wrappers.remove(
            new ResourceMethodInfoDTOWrapper(resourceMethodInfoDTO)));

    resourceMethodInfoDTO = new ResourceMethodInfoDTO();

    resourceMethodInfoDTO.method = HttpMethod.POST;
    resourceMethodInfoDTO.consumingMimeType = null;
    resourceMethodInfoDTO.producingMimeType = null;
    resourceMethodInfoDTO.path = "/common/different";
    resourceMethodInfoDTO.nameBindings = null;

    assertTrue(
        wrappers.remove(
            new ResourceMethodInfoDTOWrapper(resourceMethodInfoDTO)));
}
 
Example 15
Source File: ClassIntrospectorTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 4 votes vote down vote up
@Test
public void testPlainResourceWithNameBinding() {
    Bus bus = BusFactory.getDefaultBus(true);

    ResourceMethodInfoDTO[] resourceMethodInfoDTOS =
        ClassIntrospector.getResourceMethodInfos(
            PlainResourceSeveralOperationsWithNameBinding.class, bus
        ).toArray(
            new ResourceMethodInfoDTO[0]
        );

    assertEquals(2, resourceMethodInfoDTOS.length);

    List<ResourceMethodInfoDTOWrapper> wrappers = Arrays.stream(
        resourceMethodInfoDTOS
    ).map(
        ResourceMethodInfoDTOWrapper::new
    ).collect(
        Collectors.toList()
    );

    ResourceMethodInfoDTO resourceMethodInfoDTO =
        new ResourceMethodInfoDTO();

    resourceMethodInfoDTO.method = HttpMethod.GET;
    resourceMethodInfoDTO.consumingMimeType = null;
    resourceMethodInfoDTO.producingMimeType = null;
    resourceMethodInfoDTO.path = "/";
    resourceMethodInfoDTO.nameBindings = new String[]{"test.types.Bound"};

    assertTrue(
        wrappers.remove(
            new ResourceMethodInfoDTOWrapper(resourceMethodInfoDTO)));

    resourceMethodInfoDTO = new ResourceMethodInfoDTO();
    resourceMethodInfoDTO.method = HttpMethod.POST;
    resourceMethodInfoDTO.consumingMimeType = null;
    resourceMethodInfoDTO.producingMimeType = null;
    resourceMethodInfoDTO.path = "/";
    resourceMethodInfoDTO.nameBindings = new String[]{"test.types.Bound"};

    assertTrue(
        wrappers.remove(
            new ResourceMethodInfoDTOWrapper(resourceMethodInfoDTO)));
}
 
Example 16
Source File: Transaction.java    From pagarme-java with The Unlicense 4 votes vote down vote up
/**
 * Você pode capturar o valor de uma transação após a autorização desta, no
 * prazo máximo de 5 dias após a autorização.
 *
 * @param amount
 * @return
 * @throws PagarMeException
 */
public Transaction capture(final Integer amount) throws PagarMeException {

    validateId();

    final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST,
            String.format("/%s/%s/capture", getClassName(), getId()));

    request.getParameters().put("amount", amount);
		
    if (this.getMetadata() != null)
        request.getParameters().put("metadata", this.getMetadata());

    if (this.getSplitRules() != null)
        request.getParameters().put("split_rules", this.getSplitRules());

    final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class);
    copy(other);
    flush();

    return other;
}
 
Example 17
Source File: FirebaseCloudMessagingClient.java    From oxAuth with MIT License 4 votes vote down vote up
@Override
public String getHttpMethod() {
    return HttpMethod.POST;
}
 
Example 18
Source File: ParsecAsyncHttpClientProfilingTest.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
@Test
public void postRequestRetriesShouldBeLogged() throws ExecutionException, InterruptedException {


    String url = "/postRequestRetriesProfiling";
    String headerStr = "postRetriesHost";

    String scenarioName = "postRetries";
    WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName)
            .whenScenarioStateIs(Scenario.STARTED)
            .willSetStateTo("requested count 1")
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(aResponse()
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH,"0")
                    .withStatus(500)));

    WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName)
            .whenScenarioStateIs("requested count 1")
            .withRequestBody(equalToJson(stubReqBodyJson))
            .willReturn(okJson(stubRespBodyJson)
                    .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH, String.valueOf(stubRespBodyJson.length()))
            ));

    String requestMethod = HttpMethod.POST;
    Map<String, Collection<String>> headers = new HashMap<>();
    headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr));

    ParsecAsyncHttpRequest request =
            new ParsecAsyncHttpRequest.Builder()
                    .setUrl(wireMockBaseUrl + url)
                    .setHeaders(headers)
                    .setRequestTimeout(COMMON_REQUEST_TIME_OUT)
                    .setMethod(requestMethod)
                    .setMaxRetries(2)
                    .addRetryStatusCode(500)
                    .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build();


    Response response = parsecHttpClient.criticalExecute(request).get();


    assertThat(response.getStatus(), equalTo(200));


    ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    then(mockAppender).should(times(2)).doAppend(loggingEventArgumentCaptor.capture());

    String loggedFailureMsg = loggingEventArgumentCaptor.getAllValues().get(0).toString();

    String failurePatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "0",500, "single");
    assertThat(loggedFailureMsg, matchesPattern(failurePatternAsStr));


    String successPatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr,
            "49", 200, "single\\|retry:500");

    String loggedSuccessMsg = loggingEventArgumentCaptor.getAllValues().get(1).toString();
    assertThat(loggedSuccessMsg, matchesPattern(successPatternAsStr));
}
 
Example 19
Source File: BulkReadResourceImplTest.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Test
void valid() {
    final BulkRequests.Request okTrigger = new BulkRequests.Request(HttpMethod.POST, "{\"enum\":\"V1\"}",
            singletonMap(HttpHeaders.CONTENT_TYPE, singletonList(APPLICATION_JSON)), "/api/v1/action/execute",
            new HashMap<String, List<String>>() {

                {
                    put("type", singletonList("user"));
                    put("family", singletonList("jdbc"));
                    put("action", singletonList("custom"));
                }
            });
    final BulkResponses responses =
            base
                    .path("bulk")
                    .request(APPLICATION_JSON_TYPE)
                    .post(entity(
                            new BulkRequests(asList(
                                    new BulkRequests.Request(HttpMethod.GET, null,
                                            singletonMap(HttpHeaders.CONTENT_TYPE, singletonList(APPLICATION_JSON)),
                                            "/api/v1/component/index", emptyMap()),
                                    new BulkRequests.Request(HttpMethod.GET, null,
                                            singletonMap(HttpHeaders.CONTENT_TYPE, singletonList(APPLICATION_JSON)),
                                            "/api/v1/documentation/component/" + client.getJdbcId(), emptyMap()),
                                    new BulkRequests.Request(HttpMethod.GET, null,
                                            singletonMap(HttpHeaders.CONTENT_TYPE, singletonList(APPLICATION_JSON)),
                                            "/api/v1/documentation/component/"
                                                    + client.getComponentId("chain", "list"),
                                            emptyMap()),
                                    okTrigger,
                                    new BulkRequests.Request(HttpMethod.POST, "{\"enum\":\"FAIL\"}",
                                            singletonMap(HttpHeaders.CONTENT_TYPE, singletonList(APPLICATION_JSON)),
                                            "/api/v1/action/execute", new HashMap<String, List<String>>() {

                                                {
                                                    put("type", singletonList("user"));
                                                    put("family", singletonList("jdbc"));
                                                    put("action", singletonList("custom"));
                                                }
                                            }),
                                    okTrigger)),
                            APPLICATION_JSON_TYPE), BulkResponses.class);
    final List<BulkResponses.Result> results = responses.getResponses();

    assertEquals(6, results.size());

    IntStream
            .of(0, 1, 3, 5)
            .mapToObj(results::get)
            .forEach(it -> assertEquals(HttpServletResponse.SC_OK, it.getStatus()));
    assertEquals(HttpServletResponse.SC_NOT_FOUND, results.get(2).getStatus());
    assertEquals(520, results.get(4).getStatus());
    results.forEach(it -> assertEquals(singletonList("application/json"), it.getHeaders().get("Content-Type")));
    assertEquals("{\n  \"value\":\"V1\"\n}",
            new String(results.get(3).getResponse(), StandardCharsets.UTF_8).trim());
    assertEquals(
            "{\n  \"code\":\"ACTION_ERROR\",\n"
                    + "  \"description\":\"Action execution failed with: this action failed intentionally\"\n}",
            new String(results.get(4).getResponse(), StandardCharsets.UTF_8).trim());

    assertTrue(new String(results.get(0).getResponse(), StandardCharsets.UTF_8)
            .contains("\"pluginLocation\":\"org.talend.comp:jdbc-component:jar:0.0.1:compile\""));
    assertEquals(
            "{\n  \"source\":\"== input\\n\\ndesc\\n\\n=== Configuration\\n\\nSomething1\",\n"
                    + "  \"type\":\"asciidoc\"\n" + "}",
            new String(results.get(1).getResponse(), StandardCharsets.UTF_8));
    assertEquals(
            "{\n  \"code\":\"COMPONENT_MISSING\",\n"
                    + "  \"description\":\"No component 'dGhlLXRlc3QtY29tcG9uZW50I2NoYWluI2xpc3Q'\"\n" + "}",
            new String(results.get(2).getResponse(), StandardCharsets.UTF_8));
}
 
Example 20
Source File: SnsRequestHandler.java    From jrestless with Apache License 2.0 2 votes vote down vote up
/**
 * Creates the http method for the actual request made to the Jersey
 * container.
 * <p>
 * The default implementation uses "POST", always.
 *
 * @param snsRecordAndContext
 * @return the request's http method
 */
@Nonnull
protected String createHttpMethod(@Nonnull SnsRecordAndLambdaContext snsRecordAndContext) {
	return HttpMethod.POST;
}