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

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

Introduction

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

Prototype

@Override
    public void put(URI url, @Nullable Object request) throws RestClientException 

Source Link

Usage

From source file:com.tyro.oss.pact.spring4.pact.consumer.PactPublisher.java

private static void publishPactFile(String provider, String consumer, String version, String pactFile,
        String brokerBaseUrl) throws IOException {
    if (version.contains("-SNAPSHOT")) {
        version = version.replace("-SNAPSHOT", "");
    }// w ww.ja  v  a2  s  . c  om

    String url = brokerBaseUrl + "/pacts/provider/" + provider + "/consumer/" + consumer + "/version/"
            + version;

    String pactJson = FileUtils.readFileToString(new File(pactFile));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> httpEntity = new HttpEntity<>(pactJson, headers);

    try {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.put(url, httpEntity);
    } catch (ResourceAccessException e) {
        throw new NoPactBrokerException(String.format("Could not reach Pact broker: %s.", brokerBaseUrl), e);
    } catch (HttpClientErrorException e) {
        throw e;
    }
}

From source file:com.hatta.consumer.App.java

private static void updateCustomer(User user, AuthTokenInfo tokenInfo) {
    Assert.notNull(tokenInfo, "Authenticate first please......");
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<Object> request = new HttpEntity<Object>(user, getHeaders());
    System.out.println("Update a customer: " + user.getId());
    restTemplate.put(REST_SERVICE_URI + "/api/user" + QPM_ACCESS_TOKEN + tokenInfo.getAccess_token(), request);

}

From source file:features.steps.APISteps.java

@Ignore
@And("^I PUT \\/espi\\/1_1\\/resource\\/RetailCustomer\\/\\{RetailCustomerID\\}\\/UsagePoint\\/\\{UsagePointID\\}$")
public void I_PUT_espi__resource_RetailCustomer_RetailCustomerID_UsagePoint_UsagePointID() throws Throwable {
    driver.get(StepUtils.DATA_CUSTODIAN_BASE_URL + "/espi/1_1/resource/RetailCustomer/1/UsagePoint");
    String xml = driver.getPageSource();

    String idWithPrefix = getXPathValue("/:feed/:entry/:title[contains(text(),'Created')]/../:id", xml);
    String id = idWithPrefix.replace("urn:uuid:", "");
    String selfHref = getXPathValue(
            "/:feed/:entry/:title[contains(text(),'Created')]/../:link[@rel='self']/@href", xml);

    String requestBody = "<entry xmlns=\"http://www.w3.org/2005/Atom\">>" + "  <id>" + idWithPrefix + "</id>"
            + "  <published>2012-10-24T00:00:00Z</published>" + "  <updated>2012-10-24T00:00:00Z</updated>"
            + "  <link rel=\"self\"" + "        href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint/" + id
            + "\"/>" + "  <link rel=\"up\""
            + "        href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint\"/>" + "  <link rel=\"related\""
            + "        href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint/" + id + "/MeterReading\"/>"
            + "  <link rel=\"related\"" + "        href=\"/espi/1_1/resource/RetailCustomer/1/UsagePoint/" + id
            + "/ElectricPowerUsageSummary\"/>" + "  <link rel=\"related\""
            + "        href=\"/espi/1_1/resource/UsagePoint/01/LocalTimeParameters/01\"/>"
            + "  <title>Updated</title>" + "  <content>" + "    <UsagePoint xmlns=\"http://naesb.org/espi\">"
            + "      <ServiceCategory>" + "        <kind>0</kind>" + "      </ServiceCategory>"
            + "    </UsagePoint>" + "  </content>" + "</entry>";
    HttpEntity<String> request = new HttpEntity<>(requestBody);
    RestTemplate rest = new RestTemplate();
    rest.put(StepUtils.DATA_CUSTODIAN_BASE_URL + selfHref, request);
}

From source file:com.ge.predix.test.utils.ZoneHelper.java

public Zone createZone(final String zoneName, final String subdomain, final String description,
        final Map<String, Object> trustedIssuers) throws JsonParseException, JsonMappingException, IOException {
    Zone zone = new Zone(zoneName, subdomain, description);
    RestTemplate acs = this.acsRestTemplateFactory.getACSTemplateWithPolicyScope();
    registerServicetoZac(subdomain, trustedIssuers);
    acs.put(this.acsBaseUrl + ACS_ZONE_API_PATH + zoneName, zone);
    return zone;/*from  www.j  a  va 2  s .  c om*/
}

From source file:com.ge.predix.test.utils.PolicyHelper.java

public CreatePolicyStatus createPolicySet(final String policyFile, final RestTemplate restTemplate,
        final HttpHeaders headers) {
    PolicySet policySet;/*  w  w  w . ja  v a2  s .co m*/
    try {
        policySet = new ObjectMapper().readValue(new File(policyFile), PolicySet.class);
        String policyName = policySet.getName();
        restTemplate.put(zoneHelper.getAcsBaseURL() + ACS_POLICY_SET_API_PATH + policyName,
                new HttpEntity<>(policySet, headers));
        return CreatePolicyStatus.SUCCESS;
    } catch (IOException e) {
        return CreatePolicyStatus.JSON_ERROR;
    } catch (HttpClientErrorException httpException) {
        return httpException.getStatusCode() != null
                && httpException.getStatusCode().equals(HttpStatus.UNPROCESSABLE_ENTITY)
                        ? CreatePolicyStatus.INVALID_POLICY_SET
                        : CreatePolicyStatus.ACS_ERROR;
    } catch (RestClientException e) {
        return CreatePolicyStatus.ACS_ERROR;
    }
}

From source file:com.ge.predix.test.utils.PolicyHelper.java

public String setTestPolicy(final RestTemplate acs, final HttpHeaders headers, final String endpoint,
        final String policyFile) throws JsonParseException, JsonMappingException, IOException {

    PolicySet policySet = new ObjectMapper().readValue(new File(policyFile), PolicySet.class);
    String policyName = policySet.getName();
    acs.put(endpoint + ACS_POLICY_SET_API_PATH + policyName, new HttpEntity<>(policySet, headers));
    return policyName;
}

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:com.ge.predix.test.utils.ZoneHelper.java

public Zone createTestZone(final RestTemplate restTemplate, final String zoneId, final boolean registerWithZac,
        final Map<String, Object> trustedIssuers) throws JsonParseException, JsonMappingException, IOException {
    Zone zone = new Zone(zoneId, zoneId, "Zone for integration testing.");
    if (registerWithZac) {
        ResponseEntity<String> response = registerServicetoZac(zoneId, trustedIssuers);
        if (!response.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException(String.format("Failed to register '%s' zone with ZAC.", zoneId));
        }//from www .ja  v a 2  s  .  c o  m
    }

    restTemplate.put(this.acsBaseUrl + ACS_ZONE_API_PATH + zoneId, zone);
    return zone;
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderCleanerTests.java

@Test
public void testCleanStream() {
    final RabbitBindingCleaner cleaner = new RabbitBindingCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;// w ww  .j  av a2  s. c  o m
    CachingConnectionFactory connectionFactory = rabbitWithMgmtEnabled.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    for (int i = 0; i < 5; i++) {
        String queue1Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + i);
        String queue2Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".default." + i);
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", AbstractBinder.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        TopicExchange exchange = new TopicExchange(queue1Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue1Name)).to(exchange).with(queue1Name));
        exchange = new TopicExchange(queue2Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue2Name)).to(exchange).with(queue2Name));
    }
    final TopicExchange topic1 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic1).with("#"));
    String foreignQueue = UUID.randomUUID().toString();
    rabbitAdmin.declareQueue(new Queue(foreignQueue));
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(foreignQueue)).to(topic1).with("#"));
    final TopicExchange topic2 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic2).with("#"));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + 4);
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Queue " + queueName + " is in use");
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Cannot delete exchange ");
                assertThat(e).hasMessageContaining("; it has bindings:");
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertThat(n < 100).withFailMessage("Consumer state remained at " + state + " after 10 seconds");
        }

    });
    rabbitAdmin.deleteExchange(topic1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.deleteQueue(foreignQueue);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertThat(cleanedMap).hasSize(2);
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertThat(cleanedQueues).hasSize(10);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i * 2)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i);
        assertThat(cleanedQueues.get(i * 2 + 1)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i + ".dlq");
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertThat(cleanedMap).hasSize(2);
    cleanedQueues = cleanedMap.get("queues");
    assertThat(cleanedQueues).hasSize(5);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i)).isEqualTo(BINDER_PREFIX + stream2 + ".default." + i);
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);
}

From source file:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addArticleEntry(@RequestBody LocalPressArticleEntity entity,
        @RequestHeader HttpHeaders headers)
        throws UnauthorizedException, GeneralLocalPressException, JsonProcessingException {
    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(entity.getRelease());

    List<String> userHeader = headers.get("UserID");
    if (userHeader == null || userHeader.isEmpty()) {
        throw new UnauthorizedException("There needs to be set a UserID-Header!", "", "");
    }/*from   w w w  .  j a v  a  2 s  . c o m*/

    MultiValueMap<String, String> geoHeaders = new LinkedMultiValueMap<>();
    geoHeaders.add("UserID", userHeader.get(0));

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

    RestTemplate template = new RestTemplate();
    String ratingURL = RATING_URL + "feedback";
    ResponseEntity<Map> result;
    try {
        result = template.postForEntity(ratingURL, request, Map.class);
    } catch (RestClientException e) {
        GeneralLocalPressException ex = new GeneralLocalPressException(
                "There happened an error by trying to invoke the geo API!", e);
        log.error(ex.getLoggingString());
        throw ex;
    }

    if (!result.getStatusCode().equals(HttpStatus.CREATED)) {
        GeneralLocalPressException e = new GeneralLocalPressException(result.getStatusCode().getReasonPhrase());
        log.error(e.getLoggingString());
        throw e;
    }

    String articleID = (String) result.getBody().get("articleID");
    if (articleID == null) {
        GeneralLocalPressException e = new GeneralLocalPressException(
                "No articleID found in response from rating module by trying to add new article!");
        log.error(e.getLoggingString());
        throw e;
    }

    HttpEntity<LocalPressArticleEntity> second = new HttpEntity<>(entity, geoHeaders);

    template.put(GEO_URL + articleID, second);

    String url = (String) result.getBody().get("feedbackURL");

    Map<String, Object> returnMap = new LinkedHashMap<>();
    returnMap.put("articleID", articleID);
    returnMap.put("userID", userHeader.get(0));

    Timestamp now = new Timestamp(new Date().getTime());
    returnMap.put("timestamp", now);
    returnMap.put("status", 201);
    returnMap.put("message", "Created.");

    returnMap.put("feedbackURL", url);

    return new ResponseEntity<>(objectMapper.writeValueAsString(returnMap), HttpStatus.CREATED);
}