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.formkiq.web.AbstractIntegrationTest.java

/**
 * Creates New Form.//from w w w  .ja va2  s  .c  o  m
 *
 * @param token {@link String}
 * @param foldername {@link String}
 * @param email {@link String}
 * @return {@link String}
 * @throws IOException IOException
 */
protected String createFolder(final String token, final String foldername, final String email)
        throws IOException {

    String url = getDefaultHostAndPort() + API_FOLDER_SAVE + "?foldername=" + foldername + "&access_token="
            + token;

    if (StringUtils.hasText(email)) {
        url += "&email=" + email;
    }

    ResponseEntity<String> entity = exchangeRest(HttpMethod.POST, url);

    assertEquals(SC_OK, entity.getStatusCode().value());

    ApiMessageResponse dto = this.jsonService.readValue(entity.getBody(), ApiMessageResponse.class);

    assertEquals("Folder added", dto.getMessage());

    return dto.getId();
}

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

@Test
public void writeAllDataTypes() throws ParseException {
    mockServer.expect(requestTo("http://localhost/appglu/v1/tables/data_types"))
            .andExpect(method(HttpMethod.POST)).andExpect(header("Content-Type", jsonMediaType.toString()))
            .andExpect(content().string(compactedJson("data/crud_write_all_data_types")))
            .andRespond(withStatus(HttpStatus.CREATED).body(compactedJson("data/crud_create_response"))
                    .headers(responseHeaders));

    Row row = new Row();

    String string = new String("a very long string for test");

    row.put("boolean", true);
    row.put("short", new Short((short) 1));
    row.put("byte", new Byte((byte) 2));
    row.put("byteArray", string.getBytes());
    row.put("float", new Float(1.5f));
    row.put("double", new Double(7.5d));
    row.put("integer", new Integer(10));
    row.put("long", new Long(21474836475L));
    row.put("bigInteger", new BigInteger("9223372036854775807123"));
    row.put("string", string);

    Date datetime = DateUtils.parseDate("2010-01-15T12:10:00+0000");
    row.putDatetime("datetime", datetime);

    Date time = DateUtils.parseDate("1970-01-01T12:10:00+0000");
    row.putTime("time", time);

    Date date = DateUtils.parseDate("2010-01-15T00:00:00+0000");
    row.putDate("date", date);

    Object id = crudOperations.create("data_types", row);
    Assert.assertEquals(8, id);//from   w  w w .  j  a v a 2s.c om

    mockServer.verify();
}

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

@Override
public MobileVerificationDetailsDTO getMobileVerificationDetailsByCustomerIdTypeAndMobile(Long customerId,
        Integer customerType, Integer mobileType) throws MobileVerificationDetailsNotFoundException {

    CustomerIdTypeMobileTypeDTO mobileDTO = new CustomerIdTypeMobileTypeDTO(customerId, customerType,
            mobileType);//from   w ww  .  j a v  a2 s .c o m

    HttpEntity<CustomerIdTypeMobileTypeDTO> entity = new HttpEntity<CustomerIdTypeMobileTypeDTO>(mobileDTO);

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

    if (result.getStatusCode() == HttpStatus.FOUND)
        return result.getBody();
    else
        throw new MobileVerificationDetailsNotFoundException();

}

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

protected ResponseEntity<String> callRemoteLogWithAccessToken() {
    RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO();
    remoteLogRequest.setLogLevel("DEBUG");
    remoteLogRequest.setMessage("This is my log message!");

    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath);
    builder.queryParam("access_token", accessToken);

    ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);
    return result;
}

From source file:io.getlime.push.controller.web.WebAdminController.java

@RequestMapping(value = "web/admin/message/create/do.submit", method = RequestMethod.POST)
public String actionCreatePushMessage(@Valid ComposePushMessageForm form, BindingResult bindingResult,
        RedirectAttributes attr, HttpServletRequest httpRequest) {
    if (bindingResult.hasErrors()) {
        attr.addFlashAttribute("fields", bindingResult);
        attr.addFlashAttribute("form", form);
        return "redirect:/web/admin/message/create";
    }//  ww  w .  j av  a2s . c o  m
    SendPushMessageRequest request = new SendPushMessageRequest();
    request.setAppId(form.getAppId());
    PushMessage message = new PushMessage();
    message.setUserId(form.getUserId());
    PushMessageBody body = new PushMessageBody();
    body.setTitle(form.getTitle());
    body.setBody(form.getBody());
    body.setSound(form.isSound() ? "default" : null);
    message.setBody(body);
    request.setMessage(message);
    HttpEntity<ObjectRequest<SendPushMessageRequest>> requestEntity = new HttpEntity<>(
            new ObjectRequest<>(request));
    RestTemplate template = new RestTemplate();
    String baseUrl = String.format("%s://%s:%d/%s", httpRequest.getScheme(), httpRequest.getServerName(),
            httpRequest.getServerPort(), httpRequest.getContextPath());
    template.exchange(baseUrl + "/push/message/send", HttpMethod.POST, requestEntity,
            new ParameterizedTypeReference<ObjectResponse<PushMessageSendResult>>() {
            });
    return "redirect:/web/admin/message/create";
}

From source file:com.sitewhere.rest.service.SiteWhereClient.java

@Override
public DeviceLocation createDeviceLocation(String assignmentToken, DeviceLocationCreateRequest request)
        throws SiteWhereException {
    Map<String, String> vars = new HashMap<String, String>();
    vars.put("token", assignmentToken);
    return sendRest(getBaseUrl() + "assignments/{token}/locations", HttpMethod.POST, request,
            DeviceLocation.class, vars);
}

From source file:com.catalog.core.Api.java

@Override
public SubjectTeacherForClassVM getSubjectTeacherForClass(int subjectId, int teacherId, int classGroupId) {
    setStartTime();/* ww  w  . jav a2  s  . co m*/

    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();

    String url = "http://" + IP + EXTENSION + "/teacher/findByClassSubjectTeacherT/" + classGroupId + ","
            + subjectId + "," + teacherId + ".json";

    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

    ResponseEntity<SubjectTeacherForClassVM> responseEntity = null;
    SubjectTeacherForClassVM stfc = null;

    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                SubjectTeacherForClassVM.class);
        stfc = responseEntity.getBody();
    } catch (RestClientException e) {
        return null;
    }

    Log.d("TAAAG", stfc.toString());

    getElapsedTime("getSubjectTeacherForClass - ");
    return stfc;
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Create User./*from   ww w  . ja  v  a2s .  c  o m*/
 * @param token {@link String}
 * @param email {@link String}
 * @param pass {@link String}
 * @param loginToken {@link String}
 */
protected void createUser(final String token, final String email, final String pass, final String loginToken) {

    setProperty(token, INVITE_ONLY, "false");

    String url = getDefaultHostAndPort() + API_USER_SAVE + "?email=" + email + "&access_token=" + token
            + "&password=" + pass + "&confirmpassword=" + pass + "&role=" + UserRole.ROLE_USER + "&status="
            + UserStatus.ACTIVE;

    if (StringUtils.hasText(loginToken)) {
        url += "&logintoken=" + loginToken;
    }

    ResponseEntity<String> entity = exchangeRest(HttpMethod.POST, url);

    assertEquals("{\"message\":\"User has been saved\"}", entity.getBody());
    assertEquals(SC_OK, entity.getStatusCode().value());
}

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

@Override
public AuthenticationDetailsDTO verifyLoginDetails(LoginVerificationDTO loginVerificationDTO)
        throws AuthenticationDetailsNotFoundException {

    HttpEntity<LoginVerificationDTO> entity = new HttpEntity<LoginVerificationDTO>(loginVerificationDTO);

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

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

}

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

private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher)
        throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
        String type = rTypes.next();
        responseType.append(type);/*from w w w  .  j  av  a  2  s  .co m*/
        if (rTypes.hasNext()) {
            responseType.append(" ");
        }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://anywhere.com";
    String uri = loginUrl + "/oauth/authorize?response_type={response_type}&"
            + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}";

    ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers),
            Void.class, responseType, state, clientId, redirectUri);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("username"));
    assertTrue(response.getBody().contains("password"));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", user.getUserName());
    formData.add("password", "secret");

    // Should be redirected to the original URL, but now authenticated
    result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(formData, headers), Void.class);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("You can change your approval of permissions"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST,
                new HttpEntity<>(formData, headers), Void.class);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
    }
    assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString()));

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("redirect_uri", redirectUri);
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    String basicDigestHeaderValue = "Basic "
            + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    tokenHeaders.set("Authorization", basicDigestHeaderValue);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(formData, tokenHeaders), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}