Example usage for org.springframework.web.client RestTemplate postForEntity

List of usage examples for org.springframework.web.client RestTemplate postForEntity

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate postForEntity.

Prototype

@Override
    public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)
            throws RestClientException 

Source Link

Usage

From source file:de.loercher.localpress.integration.GeoAndRatingITest.java

@Test
public void testAddArticle() {
    String nowString = "2015-10-12T08:00+02:00[Europe/Berlin]";
    ZonedDateTime now = new DateTimeConverter().fromString(nowString);

    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(nowString);
    Instant instant = now.toInstant();
    Instant fir = Instant.now();

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("UserID", "ulf");

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, headers);

    RestTemplate template = new RestTemplate();
    ResponseEntity<Map> result = template.postForEntity("http://52.29.77.191:8080/localpress/feedback", request,
            Map.class);

    Instant afterRating = Instant.now();

    GeoBaseEntity.EntityBuilder builder = new GeoBaseEntity.EntityBuilder();
    GeoBaseEntity entity = builder.author("ulf")
            .coordinates(Arrays.asList(new Coordinate[] { new Coordinate(50.1, 8.4) }))
            .timestamp(now.toEpochSecond()).content("abc.de").title("mein titel").user("ulf").build();

    HttpEntity<GeoBaseEntity> second = new HttpEntity<>(entity, headers);
    System.out.println(result.getBody().get("articleID"));

    template.put("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"), second);

    Instant afterGeoPut = Instant.now();

    result = template.getForEntity("http://euve33985.vserver.de:8080/geo/" + result.getBody().get("articleID"),
            Map.class);

    Instant afterGeoGet = Instant.now();

    assertEquals("User ID has changed over time!", "ulf", result.getBody().get("user"));
    assertEquals("Content URL has changed over time!", "abc.de", result.getBody().get("content"));

    DateTimeConverter conv = new DateTimeConverter();

    Duration first = Duration.between(fir, afterRating);
    Duration sec = Duration.between(afterRating, afterGeoPut);
    Duration third = Duration.between(afterGeoPut, afterGeoGet);

    System.out.println("Begin: " + conv.toString(now));
    System.out.println("Time until POST to rating: " + new Double(first.toMillis()) / 1000);
    System.out.println("Time until PUT to geo: " + new Double(sec.toMillis()) / 1000);
    System.out.println("Time until GET to geo: " + new Double(third.toMillis()) / 1000);
}

From source file:dk.skogemann.airline.project.ApiController.java

@RequestMapping(value = "/reservation/{flightId}", method = RequestMethod.POST)
@ResponseBody/* ww  w .j  a v a  2  s  . c om*/
public ReservationResponse bookFlight(@PathVariable("flightId") String flightId,
        @RequestBody Reservation reservation) {

    String url = "http://angularairline-plaul.rhcloud.com/api/flightreservation";

    System.out.println("kalder remote");
    RestTemplate template = new RestTemplate();
    ResponseEntity<ReservationResponse> postForEntity = template.postForEntity(url, reservation,
            ReservationResponse.class);
    System.out.println(postForEntity);
    System.out.println("bookFlight apicontroller");

    return postForEntity.getBody();
}

From source file:org.bonitasoft.web.designer.studio.workspace.StudioWorkspaceResourceHandler.java

protected ResponseEntity<String> doPost(final Path filePath, WorkspaceResourceEvent actionEvent) {
    if (actionEvent == null) {
        throw new IllegalArgumentException("actionEvent is null");
    }//from  w w  w .ja  va2 s. c  om
    if (restClient.isConfigured()) {
        final String url = createPostURL(actionEvent);
        RestTemplate restTemplate = restClient.getRestTemplate();
        return restTemplate.postForEntity(URI.create(url), filePath != null ? filePath.toString() : null,
                String.class);
    }
    return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

private ResponseEntity<Integer> eraseAllData() {
    HttpHeaders headers = this.getHeaders("myusername" + ":" + "mypwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>("{}", headers);

    ResponseEntity<Integer> entity = template.postForEntity("http://localhost:8085/xacml/populators/dvla/reset",
            requestEntity, Integer.class);

    return entity;
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

private ResponseEntity<Driver> createOneDriver() {
    HttpHeaders headers = this.getHeaders("myusername" + ":" + "mypwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(DriverFixtures.standardDriverJSON(), headers);

    ResponseEntity<Driver> entity = template.postForEntity(
            "http://localhost:8085/xacml/populators/dvla/driveradd", requestEntity, Driver.class);
    return entity;
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

private ResponseEntity<Vehicle> createOneVehicle() {
    HttpHeaders headers = this.getHeaders("myusername" + ":" + "mypwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(VehicleFixtures.strandardVehicleJSON(), headers);

    ResponseEntity<Vehicle> entity = template.postForEntity(
            "http://localhost:8085/xacml/populators/dvla/vehicleadd", requestEntity, Vehicle.class);
    return entity;
}

From source file:org.kurento.repository.test.util.HttpRepositoryTest.java

private ResponseEntity<String> postWithRetries(String uploadURL, RestTemplate template, Object request) {

    ResponseEntity<String> entity = null;

    int numRetries = 0;
    while (true) {
        try {//w ww .j ava  2s.  c  om
            entity = template.postForEntity(uploadURL, request, String.class);
            break;
        } catch (Exception e) {
            log.warn("Exception when uploading file with POST. Retring...");
            log.warn("Exception message: " + e.getMessage());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            numRetries++;
            if (numRetries > 5) {
                throw new RuntimeException(e);
            }
        }
    }
    return entity;
}

From source file:org.kurento.repository.test.OneRecordingServerTest.java

protected void uploadFileWithPOST(String uploadURL, File fileToUpload)
        throws FileNotFoundException, IOException {

    RestTemplate template = new RestTemplate();

    ByteArrayOutputStream fileBytes = new ByteArrayOutputStream();
    IOUtils.copy(new FileInputStream(fileToUpload), fileBytes);

    ResponseEntity<String> entity = template.postForEntity(uploadURL, fileBytes.toByteArray(), String.class);

    assertEquals("Returned response: " + entity.getBody(), HttpStatus.OK, entity.getStatusCode());

}

From source file:com.salmon.security.xacml.demo.springmvc.rest.HTTPPopulatorsTest.java

@Test
public void badUserPrevented() {
    HttpHeaders headers = this.getHeaders("wrongusername" + ":" + "wrongpwd");

    RestTemplate template = new RestTemplate();

    HttpEntity<String> requestEntity = new HttpEntity<String>(DriverFixtures.standardDriverJSON(), headers);

    try {//from   w  w w  .  j a v  a2 s  . co m
        ResponseEntity<Driver> entity = template.postForEntity(
                "http://localhost:8085/xacml/populators/dvla/driveradd", requestEntity, Driver.class);
        fail("Request Passed incorrectly with status " + entity.getStatusCode());
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getStatusCode());
    }

}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateReservation.java

/**
 * Method, where reservation information is pushed to server in order to create reservation record.
 * All heavy lifting is made here./*from   w  ww .jav  a2s  .c om*/
 *
 * @param params only one reservation instance is allowed here - reservation to be created
 * @return object of created reservation if any
 */
@Override
protected Reservation doInBackground(Reservation... params) {

    Reservation data = params[0];
    try {

        setState(RUNNING, R.string.working_ws_create);

        SharedPreferences credentials = getCredentials();
        String username = credentials.getString("username", null);
        String password = credentials.getString("password", null);
        String url = credentials.getString("url", null) + Values.SERVICE_RESERVATION;

        //set HTTP connection
        HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAuthorization(authHeader);
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
        requestHeaders.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<Reservation> entity = new HttpEntity<Reservation>(data, requestHeaders);

        SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

        Log.d(TAG, url);
        ResponseEntity<Reservation> dataEntity = restTemplate.postForEntity(url, entity, Reservation.class);
        return dataEntity.getBody();
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}