Java Code Examples for org.springframework.web.client.RestTemplate.postForEntity()

The following are Jave code examples for showing how to use postForEntity() of the org.springframework.web.client.RestTemplate class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: be.liege.cti.ged   File: SearchCategories.java   Source Code and License Vote up 7 votes
private void oldSchool(RestTemplate restTemplate) {
    final ObjectNode body = getAllCategoryMissionWithFacets();
    logger.debug("query body: {}", body.toString());
    final ResponseEntity<ObjectNode> objectNodeResponseEntity =
            restTemplate.postForEntity(alfredUrl + AlfredConstants.SEARCH, body, ObjectNode.class);
    if (objectNodeResponseEntity.getStatusCode().equals(HttpStatus.OK)) {
        final ObjectNode bodyResponse = objectNodeResponseEntity.getBody();
        final JsonNode nodeRefs = bodyResponse.get("noderefs");
        nodeRefs.elements()
                .forEachRemaining(node -> {
                    logger.info("{}: {}", node, getNodeName(restTemplate, node.asText()));
                });
    } else {
        logger.warn("Problème pour retrouver les informations: {}", objectNodeResponseEntity.getStatusCode());
    }
}
 
Example 2
Project: SaleWeb   File: Comunicacion.java   Source Code and License Vote up 6 votes
public void enviar(String direccion, String subject, String body){
	RestTemplate restTemplate = new RestTemplate();
       MultiValueMap<String, String> email= new LinkedMultiValueMap<String, String>();
       email.add("email", direccion);
       email.add("subject", subject);
       email.add("body", body);
       ResponseEntity<String> response =  restTemplate.postForEntity(URL,email,String.class);
}
 
Example 3
Project: Sound.je   File: FacebookPoster.java   Source Code and License Vote up 6 votes
/**
 * Create occurrence.
 *
 * @param occurrence the occurrence
 * @return the occurrence
 */
public Occurrence create(Occurrence occurrence) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("message", createMessage(occurrence));
    map.add("link", occurrence.getUrl());
    map.add("place", occurrence.getEvent().flatMap(Event::getLocation).map(Location::getFacebookId).map(String::valueOf).orElse(""));
    map.add("published", "false");
    map.add("scheduled_publish_time", String.valueOf(occurrence.getStartTime().minusHours((int) (Math.random() * 6 + 1)).getMillis() / 1000));

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<FacebookPost> response = restTemplate.postForEntity(generateRequestUrl(), request, FacebookPost.class);

    occurrence.setFacebookPostId(response.getBody().getId());
    return occurrence;
}
 
Example 4
Project: cas-5.1.0   File: RestMultifactorAuthenticationTrustStorage.java   Source Code and License Vote up 5 votes
@Override
protected MultifactorAuthenticationTrustRecord setInternal(final MultifactorAuthenticationTrustRecord record) {
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<Object> response = restTemplate.postForEntity(this.endpoint, record, Object.class);
    if (response != null && response.getStatusCode() == HttpStatus.OK) {
        return record;
    }
    return null;
}
 
Example 5
Project: cas-5.1.0   File: RestEndpointMultifactorAuthenticationPolicyEventResolver.java   Source Code and License Vote up 5 votes
/**
 * Call rest endpoint for multifactor.
 *
 * @param principal the principal
 * @param context   the context
 * @return return the rest response, typically the mfa id.
 */
protected String callRestEndpointForMultifactor(final Principal principal, final RequestContext context) {
    final RestTemplate restTemplate = new RestTemplate();
    final Service resolvedService = resolveServiceFromAuthenticationRequest(context);
    final RestEndpointEntity entity = new RestEndpointEntity(principal.getId(), resolvedService.getId());
    final ResponseEntity<String> responseEntity = restTemplate.postForEntity(restEndpoint, entity, String.class);
    if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
        return responseEntity.getBody();
    }
    return null;
}
 
Example 6
Project: keti   File: AccessControlServiceIT.java   Source Code and License Vote up 5 votes
@Test(dataProvider = "endpointProvider")
public void testPolicyEvalWithNoOauthToken(final String endpoint) {
    RestTemplate acs = new RestTemplate();
    // Use vanilla rest template with no oauth token.
    try {
        acs.postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH,
                new HttpEntity<>(this.policyHelper.createEvalRequest(MARISSA_V1.getSubjectIdentifier(), "sanramon"),
                        this.acsitSetUpFactory.getZone1Headers()),
                PolicyEvaluationResult.class);
        Assert.fail("No exception thrown when making policy evaluation request without token.");
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.UNAUTHORIZED);
    }
}
 
Example 7
Project: keti   File: PolicyHelper.java   Source Code and License Vote up 5 votes
public ResponseEntity<PolicyEvaluationResult> sendEvaluationRequest(final RestTemplate restTemplate,
        final HttpHeaders headers, final PolicyEvaluationRequestV1 randomEvalRequest) {
    ResponseEntity<PolicyEvaluationResult> evaluationResponse = restTemplate.postForEntity(
            this.zoneFactory.getAcsBaseURL() + ACS_POLICY_EVAL_API_PATH,
            new HttpEntity<>(randomEvalRequest, headers), PolicyEvaluationResult.class);
    return evaluationResponse;
}
 
Example 8
Project: loom   File: KeystoneV3Provider.java   Source Code and License Vote up 5 votes
@Override
public boolean authenticate(final Credentials creds) {
    boolean allowed = false;
    try {
        LOG.info("authenticate call: starting...");
        RestTemplate rt = restManager.getRestTemplate("keystone-auth");
        LOG.info("posting to " + keystoneTokenURI.toString());
        ResponseEntity<String> resp =
                rt.postForEntity(keystoneTokenURI, KeystoneUtils.getUnscopedAuth(creds), String.class);
        if (resp != null) {
            LOG.info("response is not null: " + resp.getStatusCode());
            if (resp.getStatusCode() == HttpStatus.CREATED) {
                LOG.info("response is CREATED");
                String token = resp.getHeaders().getFirst("X-Subject-Token");
                if (token != null) {
                    LOG.info("response contains header X-Subject-Token with value: " + token);
                    TokenManager.getInstance().setTokenHolder(creds.getUsername(), new TokenHolder(token));
                    allowed = true;
                }
            }
        }
    } catch (HttpClientErrorException ex) {
        // LOG.error(ex);
        // LOG.error("authentication refused for user: "+ creds.getUsername(),ex);
        LOG.error("authentication refused for user: " + creds.getUsername() + " - " + ex.getMessage());
    }
    LOG.info("authenticate call: and we're done...");
    return allowed;
}
 
Example 9
Project: loom   File: NovaServersImpl.java   Source Code and License Vote up 5 votes
private void performAction(final String serverId, final JsonAction jsonAction) {
    String resourcesUri = jsonEndpoint.getUrl() + "/" + getUriSuffix() + "s/" + serverId + "/action";
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());

    try {
        rt.postForEntity(resourcesUri, jsonAction, String.class);
    } catch (HttpStatusCodeException ex) {
        // check if it's a 401
        if (ex.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            throw new AuthenticationFailureException(ex);
        } else {
            throw ex;
        }
    }
}
 
Example 10
Project: loom   File: NovaServersImpl.java   Source Code and License Vote up 5 votes
@Override
public JsonServers createInstance(final JsonServers server) {
    System.out.println(RestUtils.toJson(server));
    String url = jsonEndpoint.getUrl() + "/" + getUriSuffix() + "s";
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonServers> result = rt.postForEntity(url, server, JsonServers.class);

    return result.getBody();
}
 
Example 11
Project: loom   File: KeystoneProjects.java   Source Code and License Vote up 5 votes
/**
 * Authenticate for the given baseUrl, username and password.
 *
 * @param baseUrl keystone url to try authenticating against
 * @param username username
 * @param password password
 * @return true if it was successful
 */
public boolean authenticate(final String baseUrl, final String username, final String password) {
    boolean allowed = false;
    try {
        URI keystoneTokenURI = EndpointUtils.keystoneTokenURINoCatalog(baseUrl);
        RestTemplate rt = openstackApp.getRestManager().getRestTemplate("keystone-auth");
        JsonAuth auth = KeystoneUtils.getUnscopedAuth(username, password);
        LOG.info("AUTH " + keystoneTokenURI);
        LOG.info("AUTH " + RestUtils.toJson(auth));
        ResponseEntity<JsonTokens> resp = rt.postForEntity(keystoneTokenURI, auth, JsonTokens.class);
        if (resp != null) {
            if (resp.getStatusCode() == HttpStatus.CREATED) {
                String token = resp.getHeaders().getFirst("X-Subject-Token");
                LOG.info("AUTH token1 " + token);

                if (token != null) {
                    TokenHolder tokenHolder = new TokenHolder(token);
                    openstackApp.getTokenManager().setTokenHolder(tokenHolder);
                    openstackApp.getTokenManager().setJsonUser(resp.getBody().getToken().getUser());
                    LOG.info("AUTH token2 " + resp.getBody().getToken());
                    allowed = true;
                }
            }
        }
    } catch (HttpClientErrorException ex) {
        LOG.error("authentication refused for user: " + username + " - " + ex.getMessage());
    }
    return allowed;
}
 
Example 12
Project: loom   File: KeystoneBase.java   Source Code and License Vote up 5 votes
/**
 * Gets the service catalog for a given project id and stores it with the project name.
 *
 * @param projectId project id to get catalog for
 * @param projectName project name to get catalog for
 */
public void getServiceCatalog(final String projectId, final String projectName) {
    try {
        URI keystoneTokenURI = EndpointUtils.keystoneTokenURIWithCatalog(openstackApp.getKeystoneUriBase());

        RestTemplate rt = openstackApp.getRestManager().getRestTemplate("keystone-auth");
        JsonAuth auth = KeystoneUtils.getScopedAuth(openstackApp.getTokenManager().getTokenHolder().getUnscoped(),
                projectId);

        ResponseEntity<JsonTokens> resp = rt.postForEntity(keystoneTokenURI, auth, JsonTokens.class);
        String token = null;
        JsonToken jsonToken = null;
        if (resp != null) {
            if (resp.getStatusCode() == HttpStatus.CREATED) {
                token = resp.getHeaders().getFirst("X-Subject-Token");
                jsonToken = resp.getBody().getToken();
            }
        }

        if (token != null && token.length() > MAX_HEADER_SIZE) {
            keystoneTokenURI = EndpointUtils.keystoneTokenURINoCatalog(openstackApp.getKeystoneUriBase());

            resp = rt.postForEntity(keystoneTokenURI, auth, JsonTokens.class);
            if (resp != null) {
                if (resp.getStatusCode() == HttpStatus.CREATED) {
                    token = resp.getHeaders().getFirst("X-Subject-Token");
                }
            }
        }
        if (token != null && jsonToken != null) {
            openstackApp.getTokenManager().getTokenHolder().setScopedToken(projectId, projectName, token,
                    jsonToken);
        }
    } catch (HttpClientErrorException ex) {
        LOG.error("authentication refused for user: " + projectId + " - " + ex.getMessage());
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("authenticate call: and we're done...");
    }
}
 
Example 13
Project: loom   File: CinderVolumeImpl.java   Source Code and License Vote up 5 votes
@Override
public JsonVolumes createVolume(final String projectId, final JsonVolumes volumes) {
    String url = jsonEndpoint.getUrl() + "/volumes";
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonVolumes> result = rt.postForEntity(url, volumes, JsonVolumes.class);

    return result.getBody();

}
 
Example 14
Project: loom   File: NeutronSubnetsImpl.java   Source Code and License Vote up 5 votes
@Override
public JsonSubnets createSubnets(final JsonSubnets subnets) {
    String url = getUri();
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonSubnets> result = rt.postForEntity(url, subnets, JsonSubnets.class);

    return result.getBody();
}
 
Example 15
Project: loom   File: NeutronNetworksImpl.java   Source Code and License Vote up 5 votes
@Override
public JsonNetworks createNetworks(final JsonNetworks networks) {
    String url = getUri();
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonNetworks> result = rt.postForEntity(url, networks, JsonNetworks.class);

    return result.getBody();
}
 
Example 16
Project: cas-5.1.0   File: RestMultifactorAuthenticationTrustStorage.java   Source Code and License Vote up 4 votes
@Override
public void expire(final LocalDate onOrBefore) {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForEntity(this.endpoint, onOrBefore, Object.class);
}
 
Example 17
Project: cas-5.1.0   File: RestMultifactorAuthenticationTrustStorage.java   Source Code and License Vote up 4 votes
@Override
public void expire(final String key) {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForEntity(this.endpoint, key, Object.class);
}
 
Example 18
Project: apollo-custom   File: ItemSetControllerTest.java   Source Code and License Vote up 4 votes
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetDeleted() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets createChangeSet = new ItemChangeSets();
  createChangeSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdTemplate = new TestRestTemplate("created", "");
  createdTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    createChangeSet.addCreateItem(item);
  }

  ResponseEntity<Void> response = createdTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      createChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

  ItemDTO[] items =
      restTemplate.getForObject(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items",
          ItemDTO[].class);

  ItemChangeSets deleteChangeSet = new ItemChangeSets();
  deleteChangeSet.setDataChangeLastModifiedBy("deleted");
  RestTemplate deletedTemplate = new TestRestTemplate("deleted", "");
  deletedTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int deletedSize = 1;
  for (int i = 0; i < deletedSize; i++) {
    items[i].setValue("deleted_value_" + i);
    deleteChangeSet.addDeleteItem(items[i]);
  }

  response = deletedTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      deleteChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize - deletedSize, savedItems.size());
  Item item0 = savedItems.get(0);
  Assert.assertEquals("key_1", item0.getKey());
  Assert.assertEquals("created_value_1", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
}
 
Example 19
Project: apollo-custom   File: ItemSetControllerTest.java   Source Code and License Vote up 4 votes
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetCreated() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets itemSet = new ItemChangeSets();
  itemSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdTemplate = new TestRestTemplate("created", "");
  createdTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    itemSet.addCreateItem(item);
  }

  ResponseEntity<Void> response =
      createdTemplate.postForEntity(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
          itemSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> items = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize, items.size());
  Item item0 = items.get(0);
  Assert.assertEquals("key_0", item0.getKey());
  Assert.assertEquals("created_value_0", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
}
 
Example 20
Project: apollo-custom   File: ItemSetControllerTest.java   Source Code and License Vote up 4 votes
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetUpdated() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets createChangeSet = new ItemChangeSets();
  createChangeSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdRestTemplate = new TestRestTemplate("created", "");
  createdRestTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    createChangeSet.addCreateItem(item);
  }

  ResponseEntity<Void> response = createdRestTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      createChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

  ItemDTO[] items =
      createdRestTemplate.getForObject(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items",
          ItemDTO[].class);

  ItemChangeSets updateChangeSet = new ItemChangeSets();
  updateChangeSet.setDataChangeLastModifiedBy("updated");

  RestTemplate updatedRestTemplate = new TestRestTemplate("updated", "");
  updatedRestTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int updatedSize = 2;
  for (int i = 0; i < updatedSize; i++) {
    items[i].setValue("updated_value_" + i);
    updateChangeSet.addUpdateItem(items[i]);
  }

  response = updatedRestTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      updateChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize, savedItems.size());
  Item item0 = savedItems.get(0);
  Assert.assertEquals("key_0", item0.getKey());
  Assert.assertEquals("updated_value_0", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertEquals("updated", item0.getDataChangeLastModifiedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
  Assert.assertNotNull(item0.getDataChangeLastModifiedTime());
}