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.orange.ngsi.client.UpdateContextRequestTest.java

@Test(expected = HttpClientErrorException.class)
public void performPostWith404() throws Exception {

    protocolRegistry.unregisterHost(brokerUrl);

    this.mockServer.expect(requestTo(brokerUrl + "/ngsi10/updateContext")).andExpect(method(HttpMethod.POST))
            .andRespond(withStatus(HttpStatus.NOT_FOUND));

    ngsiClient.updateContext(brokerUrl, null, createUpdateContextTempSensor(0)).get();
}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.implicit.Oauth2ImplicitFlowPredefinedTests.java

@Test
public void oauth2FlowTest() throws Exception {
    // Obtains the token
    obtainTokenFromOuth2LoginEndpoint();

    // Call remotelog        
    ResponseEntity<String> result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.OK, result.getStatusCode());

    if (!isJwtTokenStore) {
        // The following code is executed only if the token store is not a JwtTokenStore. The reason is that using this kind of store
        // the tokens can't be revoked (they just expire) and so this part of the test would fail.
        // A JwtTokenStore is not a proper store as the tokens are not stored anywhere (as they contain all the required info about the user
        // themselves. That's why the token revocation is not possible.
        // We call logout endpoint (we need to use the access token for this)
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(authServerBaseUrl + baseApiPath + oauth2LogoutEndpointPath);
        builder.queryParam("access_token", accessToken);

        ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(),
                HttpMethod.POST, null, String.class);
        assertEquals(HttpStatus.OK, result2.getStatusCode());

        // We try to call the protected API again (after having logged out which removes the token) - We expect not to be able to call the service.
        // This will throw a exception. In this case here in the test we receive an exception but really what happened was 'access denied'
        // A production client will receive the proper http error
        result = callRemoteLogWithAccessToken();
        assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    }/*from  w  w w. ja  va  2 s  . c o m*/
}

From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java

@Test
public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", "secret");

    ResponseEntity<Void> responseEntity = restOperations.exchange(loginUrl + "/oauth/authorize",
            HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();/*from  www  .j  av  a2  s . c  o  m*/
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));

    validateToken("access_token", params.toSingleValueMap(), scopes);
    validateToken("id_token", params.toSingleValueMap(), scopes);
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

public Map<String, Object> sendPostForUpload(String url, String path, Log log) throws IOException {
    File file = new File(path);
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.available();/*  w w w.j  av a 2 s .  co  m*/
    fileInputStream.close();
    FileSystemResource resource = new FileSystemResource(file);
    Map<String, Object> params = new HashMap<>();
    params.put("file", resource);
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(params);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>(
            postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put("content-type", contentType);
    response.put("statusCode", statusCode);
    response.put("body", body);

    return response;
}

From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java

/**
 * Obtains the authorization code from the access token request.
 *
 * @param details the authenticatoin details
 * @param request the access token request
 * @return the authorization code//from   w  w w  .  java 2s . c  om
 * @throws UserRedirectRequiredException when redirection is required
 * @throws UserApprovalRequiredException when the user requires approval
 * @throws AccessDeniedException when the user is denied access
 * @throws OAuth2AccessDeniedException when the user is denied access but we dont want the default Spring Security handling
 */
public final String obtainAuthorizationCode(final OAuth2ProtectedResourceDetails details,
        final AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException,
        AccessDeniedException, OAuth2AccessDeniedException {

    GoogleAuthCodeResourceDetails resource;

    try {
        resource = (GoogleAuthCodeResourceDetails) details;
    } catch (ClassCastException ex) {
        throw new IllegalArgumentException("details is not an instance of class GoogleAuthCodeResourceDetails");
    }

    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
        form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        for (String scope : details.getScope()) {
            form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        }
    } else {
        form.putAll(getParametersForAuthorizeRequest(resource, request));
    }
    authorizationRequestEnhancer.enhance(request, resource, form, headers);
    final AccessTokenRequest copy = request;

    final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
    ResponseExtractor<ResponseEntity<Void>> extractor = new CookieResponseExtractor(copy, delegate);
    // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
    // subclasses
    ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(),
            HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());

    if (response.getStatusCode() == HttpStatus.OK) {
        // Need to re-submit with approval...
        throw getUserApprovalSignal(resource, request);
    }

    URI location = response.getHeaders().getLocation();
    String query = location.getQuery();
    Map<String, String> map = OAuth2Utils.extractMap(query);
    if (map.containsKey("state")) {
        request.setStateKey(map.get("state"));
        if (request.getPreservedState() == null) {
            String redirectUri = resource.getRedirectUri(request);
            if (redirectUri != null) {
                request.setPreservedState(redirectUri);
            } else {
                request.setPreservedState(new Object());
            }
        }
    }

    String code = map.get("code");
    if (code == null) {
        throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
    }
    request.set("code", code);
    return code;

}

From source file:com.projectx.mvc.servicehandler.quickregister.QuickRegisterHandler.java

@Override
public QuickRegisterDTO getByCustomerIdType(CustomerIdTypeDTO customerIdDTO)
        throws QuickRegisterEntityNotFoundException {

    HttpEntity<CustomerIdTypeDTO> entity = new HttpEntity<CustomerIdTypeDTO>(customerIdDTO);

    ResponseEntity<QuickRegisterDTO> result = restTemplate.exchange(
            env.getProperty("rest.host") + "/customer/quickregister/getByCustomerId", HttpMethod.POST, entity,
            QuickRegisterDTO.class);

    if (result.getStatusCode() == HttpStatus.FOUND)
        return result.getBody();
    else//from w  w w . j a  va 2s . c o  m
        throw new QuickRegisterEntityNotFoundException();
}

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

@Test
public void changesForTablesUsingCallback_ArrayAndObject() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/sync/changes")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", jsonMediaType.toString()))
            .andExpect(content().string(compactedJson("data/sync_changes_for_tables_request")))
            .andRespond(withStatus(HttpStatus.OK).body(compactedJson("data/sync_parser_array_and_object"))
                    .headers(responseHeaders));

    MemoryTableChangesCallback callback = new MemoryTableChangesCallback();

    TableVersion loggedTable = new TableVersion("logged_table");
    TableVersion otherTable = new TableVersion("other_table", 1);

    this.syncOperations.changesForTables(callback, loggedTable, otherTable);

    this.assertChanges(callback.getTableChanges());

    mockServer.verify();/*from w w w  .jav  a2  s.  c  om*/
}

From source file:io.github.restdocsext.jersey.JerseyRequestConverterTest.java

@Test
public void convert_json_request() {
    final ClientRequest clientRequest = Mocks.clientRequestBuilder().method("POST")
            .contentType(MediaType.APPLICATION_JSON_TYPE).configProp(REQUEST_BODY_KEY, "{}".getBytes())
            .header("X-Request-Header", "SomeValue").uri(URI.create("http://localhost/api/?a=alpha&b=bravo"))
            .build();/*from   ww  w  .  j  a v  a 2 s. com*/
    final OperationRequest request = new JerseyRequestConverter().convert(clientRequest);
    assertThat(request.getMethod(), is(HttpMethod.POST));
    assertThat(request.getParameters().getFirst("a"), is("alpha"));
    assertThat(request.getParameters().getFirst("b"), is("bravo"));
    assertThat(request.getHeaders().getFirst("X-Request-Header"), is("SomeValue"));
    assertThat(request.getContentAsString(), is("{}"));
}

From source file:org.cloudfoundry.identity.api.web.ServerRunning.java

@SuppressWarnings("rawtypes")
public ResponseEntity<Map> postForMap(String path, MultiValueMap<String, String> formData,
        HttpHeaders headers) {/*from  www. j a va2 s .  c o m*/
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class);
}

From source file:org.apigw.authserver.ServerRunning.java

public ResponseEntity<String> postForString(String path, HttpHeaders headers,
        MultiValueMap<String, String> formData) {
    HttpHeaders actualHeaders = new HttpHeaders();
    actualHeaders.putAll(headers);//  ww  w  .j a v a  2s. c om
    actualHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, actualHeaders), String.class);
}