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:fragment.web.AccessDecisionTest.java

@Test
public void testAuthenticatedUrls() {
    Object[][] authenticatedAccessValid = { { HttpMethod.GET, "/portal/portal/" },
            { HttpMethod.GET, "/portal/portal/home" }, { HttpMethod.GET, "/portal/portal/profile" },
            { HttpMethod.GET, "/portal/portal/profile/edit" }, { HttpMethod.POST, "/portal/portal/profile" },
            { HttpMethod.POST, "/portal/portal/acceptCookies" }, { HttpMethod.GET, "/portal/portal/users" },
            { HttpMethod.GET, "/portal/portal/users/new" }, { HttpMethod.POST, "/portal/portal/users" },
            { HttpMethod.GET, "/portal/portal/users/1" }, { HttpMethod.PUT, "/portal/portal/users/1" },
            { HttpMethod.GET, "/portal/portal/tenants" }, { HttpMethod.POST, "/portal/portal/tenants" },
            { HttpMethod.GET, "/portal/portal/tenants/new" }, { HttpMethod.GET, "/portal/portal/tenants/1" },
            { HttpMethod.GET, "/portal/portal/tenants/1/edit" }, { HttpMethod.PUT, "/portal/portal/tenants/1" },
            { HttpMethod.GET, "/portal/portal/tasks/" }, { HttpMethod.GET, "/portal/portal/tasks/1/" },
            { HttpMethod.GET, "/portal/portal/tasks/approval-task/1" },
            { HttpMethod.POST, "/portal/portal/tasks/approval-task" } };

    User user = getRootUser();//from  w  ww  .ja va  2 s .c o m
    Authentication auth = createAuthenticationToken(user);
    verify(auth, authenticatedAccessValid, null);
}

From source file:de.swm.nis.logicaldecoding.gwc.GWCInvalidator.java

private void postSeedRequest(Envelope envelope) {

    String gwcurl = gwcBaseUrl + "seed/" + layername + ".json";

    Bounds bounds = new Bounds(
            new Coordinates(envelope.getMinX(), envelope.getMinY(), envelope.getMaxX(), envelope.getMaxY()));
    Srs srs = new Srs(epsgCode);
    SeedRequest request = new SeedRequest(layername, bounds, srs, zoomStart, zoomStop, imageFormat, operation,
            numThreads);//from  w  w  w .  ja v  a2 s.  c  o  m

    HttpEntity<GwcSeedDAO> httpentity = new HttpEntity<GwcSeedDAO>(new GwcSeedDAO(request),
            createHeaders(gwcUserName, gwcPassword));
    ResponseEntity response = template.exchange(gwcurl, HttpMethod.POST, httpentity, String.class);
    HttpStatus returncode = response.getStatusCode();
    if (!returncode.is2xxSuccessful()) {
        log.warn("HTTP Call to " + gwcurl + " was not successfull, Status code: " + response.getStatusCode());
    } else {
        log.debug("HTTP Call to " + gwcurl + "succeeded");
    }

}

From source file:com.garyclayburg.UserRestSmokeTest.java

@Ignore
@Test//from w  w w  . j ava 2 s .co  m
public void testJsonApache() throws Exception {
    RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    SimpleUser user1 = new SimpleUser();
    user1.setFirstname("Tommy");
    user1.setLastname("Deleteme");
    user1.setId("112" + (int) (Math.floor(Math.random() * 10000)));

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Content-Type", "application/json");
    //        HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<?> requestEntity = new HttpEntity(user1, requestHeaders);

    ResponseEntity<SimpleUser> simpleUserResponseEntity = rest.exchange(
            "http://" + endpoint + "/audited-users/auditedsave", HttpMethod.POST, requestEntity,
            SimpleUser.class);

    //        ResponseEntity<SimpleUser> userResponseEntity =
    //            rest.postForEntity("http://" + endpoint + "/audited-users/auditedsave",user1,SimpleUser.class);
    log.info("got a response");
    MatcherAssertionErrors.assertThat(simpleUserResponseEntity.getStatusCode(),
            Matchers.equalTo(HttpStatus.OK));

}

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

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    ResponseEntity<Map> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());//from   ww w.j  ava  2 s . c o m
    headers = getAppBasicAuthHttpHeaders();
    headers.add("Cookie", cookies.get(0));

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true").build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token")
            .queryParam("response_type", "token").queryParam("grant_type", "authorization_code")
            .queryParam("code", newCode).queryParam("redirect_uri", appUrl).build().toUriString();

    ResponseEntity<Map> tokenResponse = template.exchange(tokenUrl, HttpMethod.POST,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    ResponseEntity<Void> loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());
    headers.clear();
    headers.add("Cookie", cookies.get(0));
    restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, headers), Void.class);

    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:io.spring.initializr.actuate.stat.ProjectGenerationStatPublisherTests.java

@Test
public void fatalErrorOnlyLogs() {
    ProjectRequest request = createProjectRequest();
    this.retryTemplate
            .setRetryPolicy(new SimpleRetryPolicy(2, Collections.singletonMap(Exception.class, true)));

    this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
            .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

    this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
            .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

    this.statPublisher.handleEvent(new ProjectGeneratedEvent(request));
    this.mockServer.verify();
}

From source file:fragment.web.SystemHealthControllerTest.java

@Test
public void testRouting() throws Exception {
    logger.debug("Testing routing....");
    DispatcherTestServlet servlet = this.getServletInstance();
    Class<? extends SystemHealthController> controllerClass = controller.getClass();

    Method expected = locateMethod(controllerClass, "health",
            new Class[] { String.class, int.class, ModelMap.class });
    Method handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/health"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "showStatusDetails",
            new Class[] { String.class, String.class, String.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/health/show_status_details"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "getHealthStatusForServiceInstance",
            new Class[] { String.class, HttpServletRequest.class, ModelMap.class });
    handler = servlet//from w  w w .  j a  v  a2  s . c  o m
            .recognize(getRequestTemplate(HttpMethod.GET, "/health/get_health_status_for_service_instance"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "showAddStatus", new Class[] { String.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/health/add_status"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "showAddSchedMaintenance",
            new Class[] { String.class, String.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/health/add_scheduled_maintenance"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "addStatus",
            new Class[] { ServiceNotificationForm.class, HttpServletRequest.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/health/add_status"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "saveMaintenanceSchedule",
            new Class[] { ServiceNotificationForm.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/health/save_maintenance_schedule"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "updateMaintenanceSchedule",
            new Class[] { ServiceNotificationForm.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/health/update_maintenance_schedule"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "editStatusDetails", new Class[] { String.class, ModelMap.class });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/health/edit_status_details"));
    Assert.assertEquals(expected, handler);

}

From source file:org.cloudfoundry.identity.uaa.login.integration.AutologinContollerIntegrationTests.java

@Test
public void testClientUnauthorized() {
    AutologinRequest request = new AutologinRequest();
    request.setUsername(testAccounts.getUserName());
    request.setPassword(testAccounts.getPassword());
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/autologin"),
            HttpMethod.POST, new HttpEntity<AutologinRequest>(request), Map.class);
    assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, Object> result = (Map<String, Object>) entity.getBody();
    assertNull(result.get("code"));
}

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

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

    analyticsOperations.uploadSession(session());

    mockServer.verify();/*from w  w  w .j  a  v a2  s  .  c  om*/
}

From source file:uta.ak.TestNodejsInterface.java

private void testFromDB() throws Exception {

    Connection con = null; //MYSQL
    Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
    System.out.println("connection yes");

    System.out.println("query records...");
    String querySQL = "SELECT" + "   * " + "FROM " + "   c_rawtext " + "WHERE " + "tag like 'function%'";

    PreparedStatement preparedStmt = con.prepareStatement(querySQL);
    ResultSet rs = preparedStmt.executeQuery();

    Set<String> filterDupSet = new HashSet<>();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);// ww w.ja v a2  s.  c o m
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    while (rs.next()) {

        System.out.println(rs.getString("title") + "  " + rs.getString("text") + "  " + rs.getString("tag"));

        String formattedDate = format1.format(new Date());

        String interfaceMsg = "<message> " + "    <title> " + rs.getString("title") + "    </title> "
                + "    <text> " + StringEscapeUtils.escapeXml10(rs.getString("text")) + "    </text> "
                + "    <textCreatetime> " + formattedDate + "    </textCreatetime> " + "    <tag> "
                + rs.getString("tag") + "    </tag> " + "</message>";

        //            String restUrl="http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";
        String restUrl = "http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_XML);
        headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        //            headers.setContentLength();
        HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

        ResponseEntity<String> result = restTemplate.exchange(restUrl, HttpMethod.POST, entity, String.class);

        System.out.println(result.getBody());

    }

}