Example usage for org.springframework.http HttpMethod POST

List of usage examples for org.springframework.http HttpMethod POST

Introduction

In this page you can find the example usage for org.springframework.http HttpMethod POST.

Prototype

HttpMethod POST

To view the source code for org.springframework.http HttpMethod POST.

Click Source Link

Usage

From source file:com.aktios.appthree.server.service.OAuthAuthenticationService.java

public String getAuthorizationCode(String accessTokenA, String redirectUri, String appTokenClientTwo) {
    RestOperations rest = new RestTemplate();

    HttpHeaders headersA = new HttpHeaders();
    headersA.set("Authorization", "Bearer " + accessTokenA);

    ResponseEntity<String> resAuth2 = rest.exchange(
            MessageFormat.format(
                    "{0}/oauth/authorize?"
                            + "client_id={1}&response_type=code&redirect_uri={2}&scope=read,write",
                    oauthServerBaseURL, appTokenClientTwo, redirectUri),
            HttpMethod.GET, new HttpEntity<String>(headersA), String.class);

    String sessionId = resAuth2.getHeaders().get("Set-Cookie").get(0);
    int p1 = sessionId.indexOf("=") + 1;
    int p2 = sessionId.indexOf(";");
    sessionId = sessionId.substring(p1, p2);
    headersA.add("Cookie", "JSESSIONID=" + sessionId);

    resAuth2 = rest.exchange(//www .  ja  va 2s  . co m
            MessageFormat.format("{0}/oauth/authorize?" + "user_oauth_approval=true&authorize=Authorize",
                    oauthServerBaseURL),
            HttpMethod.POST, new HttpEntity<String>(headersA), String.class);

    String code = resAuth2.getHeaders().get("location").get(0);
    p1 = code.lastIndexOf("=") + 1;
    code = code.substring(p1);

    return code;
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationRemoteLogServiceEnabledTest() throws Exception {
    TestLoginInfo loginInfo = login();//w ww .j a v a2s  .c  o m

    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    // This test requires the test CSRF Token. This implies passing JSESSIONID and CSRF Token
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath)
            .queryParam(DEFAULT_CSRF_PARAMETER_NAME, loginInfo.getXsrfToken());
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, String.class);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}

From source file:com.example.user.UserEndpoint.java

private ResponseEntity<Resource<UserEntity>> postUserToDbApp(final UserEntity userEntity) {
    final RequestEntity<UserEntity> req = RequestEntity.post(URI.create(USER_END_POINT))
            .contentType(MediaType.APPLICATION_JSON_UTF8).body(userEntity);
    return restTemplate.exchange(USER_END_POINT, HttpMethod.POST, req,
            new ParameterizedTypeReference<Resource<UserEntity>>() {
            });//from   www. java2  s .co m
}

From source file:bg.vitkinov.edu.services.JokeService.java

@RequestMapping(value = "/jokeImage/{id}", method = RequestMethod.GET, produces = { MediaType.IMAGE_PNG_VALUE })
public ResponseEntity<byte[]> getJokeImage(@PathVariable Long id,
        @RequestHeader(value = "Accept") String acceptType,
        @RequestParam(required = false, defaultValue = "Arial-14") String font,
        @RequestParam(required = false, defaultValue = "black") String foreColor,
        @RequestParam(required = false) String backColor) {
    Joke joke = jokeRepository.findOne(id);
    ServiceInstance instance = loadBalancerClient.choose("image-service");
    if (instance == null)
        return null;
    /*//from ww w . j  av a 2 s. c  om
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.set("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
      params.set("Accept", acceptType);
      params.set("base64", "true");
      params.set("font", font);
      params.set("foreColor", foreColor);
      params.set("foreColor", foreColor);
      params.set("backColor", backColor);
      */
    HttpHeaders params = new HttpHeaders();
    MediaType requestAcceptType = acceptType == null || "".equals(acceptType) ? MediaType.IMAGE_PNG
            : MediaType.parseMediaType(acceptType);
    params.setAccept(Arrays.asList(requestAcceptType));
    params.add("text", Base64.getEncoder().encodeToString(joke.getContent().getBytes()));
    params.add("base64", "true");
    params.add("font", font);
    params.add("foreColor", foreColor);
    params.add("backColor", backColor);

    //        URI url = URI.create(String.format("%s/img", instance.getUri().toString()))
    URI url = instance.getUri().resolve("/img");
    HttpEntity<byte[]> entity = new HttpEntity<byte[]>(null, params);
    return restTemplate.exchange(url.toString(), HttpMethod.POST, entity, byte[].class);
}

From source file:com.insys.cfclient.nozzle.InfluxDBSender.java

@Async
public void sendBatch(List<String> messages) {
    log.debug("ENTER sendBatch");
    httpClient.setErrorHandler(new ResponseErrorHandler() {
        @Override/*  ww w. j  av a2s .  co  m*/
        public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
            return clientHttpResponse.getRawStatusCode() > 399;
        }

        @Override
        public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {

        }
    });

    RetryTemplate retryable = new RetryTemplate();
    retryable.setBackOffPolicy(getBackOffPolicy());
    retryable.setRetryPolicy(new SimpleRetryPolicy(properties.getMaxRetries(),
            Collections.singletonMap(ResourceAccessException.class, true)));

    final AtomicInteger counter = new AtomicInteger(0);
    retryable.execute(retryContext -> {
        int count = counter.incrementAndGet();
        log.trace("Attempt {} to deliver this batch", count);
        final StringBuilder builder = new StringBuilder();
        messages.forEach(s -> builder.append(s).append("\n"));

        String body = builder.toString();

        RequestEntity<String> entity = new RequestEntity<>(body, HttpMethod.POST, getUri());

        ResponseEntity<String> response;

        response = httpClient.exchange(entity, String.class);

        if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
            log.error("Failed to write logs to InfluxDB! Expected error code 204, got {}",
                    response.getStatusCodeValue());

            log.trace("Request Body: {}", body);
            log.trace("Response Body: {}", response.getBody());

        } else {
            log.debug("batch sent successfully!");
        }

        log.debug("EXIT sendBatch");

        return null;
    }, recoveryContext -> {
        log.trace("Failed after {} attempts!", counter.get());
        return null;
    });
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.steps.AppRouteCreatingStep.java

private String createNewRoute(String appName, String domainGuid, String spaceGuid) throws IOException {

    String createRouteRequestBody = createRouteBody(appName, domainGuid, spaceGuid);

    String cfCreateRouteUrl = cfApiUrl + ROUTES_ENDPOINT;
    ResponseEntity<String> response = cfRestTemplate.exchange(cfCreateRouteUrl, HttpMethod.POST,
            HttpCommunication.postRequest(createRouteRequestBody), String.class);

    return JsonDataFetcher.getStringValue(response.getBody(), ROUTE_GUID_JSON_PATH);
}

From source file:org.cloudfoundry.identity.uaa.integration.ClientAdminEndpointsIntegrationTests.java

@Test
public void implicitAndAuthCodeGrantClient() throws Exception {
    BaseClientDetails client = new BaseClientDetails(new RandomValueStringGenerator().generate(), "", "foo,bar",
            "implicit,authorization_code", "uaa.none");
    ResponseEntity<UaaException> result = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/oauth/clients"), HttpMethod.POST,
            new HttpEntity<BaseClientDetails>(client, headers), UaaException.class);
    assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode());
    assertEquals("invalid_client", result.getBody().getErrorCode());
}

From source file:org.projecthdata.weight.service.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    Connection<HData> connection = connectionRepository.getPrimaryConnection(HData.class);

    this.prefs.edit().putString(Constants.PREF_SYNC_STATE, SyncState.WORKING.toString()).commit();
    //get all readings that are not synced
    try {//from   w  w  w.j  ava  2s . c  om
        Dao<WeightReading, Integer> dao = ormManager.getDatabaseHelper().getWeightDao();
        //TODO: query the database instead of iterating over the whole table

        String url = this.prefs.getString(Constants.PREF_EHR_URL, "");
        Uri uri = Uri.parse(url);
        uri = uri.buildUpon().appendPath("vitalsigns").appendPath("bodyweight").build();
        RestTemplate template = connection.getApi().getRootOperations().getRestTemplate();

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_XML);

        for (WeightReading reading : dao) {

            if (!reading.isSynched()) {
                Result result = new Result();
                //date and time
                result.setResultDateTime(new DateTime(reading.getDateTime().getTime()).toString(dateFormatter));
                //narrative
                result.setNarrative(NARRATIVE);
                //result id
                result.setResultId(UUID.randomUUID().toString());
                //result type code
                result.getResultType().setCode(CODE);
                //result type code system
                result.getResultType().setCodeSystem(CODE_SYSTEM);
                //status code
                result.setResultStatusCode(RESULT_STATUS_CODE);
                //value
                result.setResultValue(reading.getResultValue().toString());
                //value unit
                result.setResultValueUnit(UNITS);

                try {

                    HttpEntity<Result> requestEntity = new HttpEntity<Result>(result, requestHeaders);
                    template.exchange(uri.toString(), HttpMethod.POST, requestEntity, String.class);
                } catch (RestClientException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                reading.setSynched(true);
                dao.update(reading);
            }
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    this.prefs.edit().putString(Constants.PREF_SYNC_STATE, SyncState.READY.toString()).commit();

}

From source file:com.appglu.impl.UserTemplateTest.java

@Test
public void login() {
    responseHeaders.add(UserSessionPersistence.X_APPGLU_SESSION_HEADER, "sessionId");

    mockServer.expect(requestTo("http://localhost/appglu/v1/users/login")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", jsonMediaType.toString()))
            .andExpect(content().string(compactedJson("data/user_login"))).andRespond(withStatus(HttpStatus.OK)
                    .body(compactedJson("data/user_auth_response")).headers(responseHeaders));

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    AuthenticationResult result = userOperations.login("username", "password");
    Assert.assertTrue(result.succeed());

    Assert.assertTrue(appGluTemplate.isUserAuthenticated());
    Assert.assertNotNull(appGluTemplate.getAuthenticatedUser());

    Assert.assertEquals(new Long(1L), appGluTemplate.getAuthenticatedUser().getId());
    Assert.assertEquals("username", appGluTemplate.getAuthenticatedUser().getUsername());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser().getPassword());

    mockServer.verify();/*from w w w. ja v a2s  .  com*/
}

From source file:org.echocat.marquardt.example.ServiceLoginIntegrationTest.java

private void whenAccessingProtectedResourceWithSelfSignedCertificate(final byte[] attackersCertificate) {
    final RestTemplate restTemplate = new RestTemplate();
    final HttpHeaders headers = new HttpHeaders();
    headers.add(X_CERTIFICATE.getHeaderName(), new String(attackersCertificate));
    final HttpEntity<Object> requestEntity = new HttpEntity<>(headers);

    restTemplate.exchange(baseUriOfApp() + "/exampleservice/someProtectedResource", HttpMethod.POST,
            requestEntity, Void.class);
}