Example usage for org.springframework.http HttpEntity HttpEntity

List of usage examples for org.springframework.http HttpEntity HttpEntity

Introduction

In this page you can find the example usage for org.springframework.http HttpEntity HttpEntity.

Prototype

public HttpEntity(MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given headers and no body.

Usage

From source file:org.starfishrespect.myconsumption.android.tasks.StatValuesUpdater.java

public void refreshDB() {

    AsyncTask<Void, List, Void> task = new AsyncTask<Void, List, Void>() {
        @Override//ww w . j ava2s .  c  o  m
        protected Void doInBackground(Void... params) {
            DatabaseHelper db = SingleInstance.getDatabaseHelper();
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<StatDTO[]> responseEnt;
            template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

            try {
                for (SensorData sensor : db.getSensorDao().queryForAll()) {
                    // Stats
                    String url = String.format(SingleInstance.getServerUrl() + "stats/sensor/%s",
                            sensor.getSensorId());

                    responseEnt = template.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders),
                            StatDTO[].class);
                    StatDTO[] statsArray = responseEnt.getBody();
                    List<StatDTO> stats = new ArrayList<>(Arrays.asList(statsArray));

                    ObjectMapper mapper = new ObjectMapper();

                    try {
                        String json = mapper.writeValueAsString(stats);
                        String key = "stats_" + sensor.getSensorId();

                        int id = db.getIdForKey(key);
                        KeyValueData valueData = new KeyValueData(key, json);
                        valueData.setId(id);

                        LOGD(TAG, "writing stat in local db: " + json);
                        db.getKeyValueDao().createOrUpdate(valueData);

                    } catch (IOException e) {
                        LOGD(TAG, "Cannot create stats " + stats.toString(), e);
                    }

                }
            } catch (SQLException e) {
                LOGD(TAG, "Cannot create stats ", e);
            } catch (ResourceAccessException | HttpClientErrorException e) {
                LOGE(TAG, "Cannot access server ", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (statUpdateFinishedCallback != null) {
                statUpdateFinishedCallback.onStatUpdateFinished();
            }
        }
    };

    task.execute();
}

From source file:com.himanshu.poc.springbootsec.SampleControllerSecurityTestIT.java

@Test
public void testSecureGetWithToken() {
    ResponseEntity<String> response = new TestRestTemplate("Himanshu", "Bhardwaj")
            .getForEntity(url.concat("/secure/generate/token/Himanshu"), String.class);
    logger.info("Response is :->" + response);
    String tokenReceived = response.getBody();
    Assert.assertThat(response.getStatusCode(), Matchers.equalTo(HttpStatus.OK));

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic ".concat(generateAuthorizationToken(tokenReceived)));

    HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);

    ResponseEntity<String> response2 = new TestRestTemplate().exchange(url.concat("/secure/sample/test"),
            HttpMethod.GET, requestEntity, String.class);
    logger.info("Response2 is :->" + response2);
    Assert.assertThat(response2.getStatusCode(), Matchers.equalTo(HttpStatus.OK));

    ResponseEntity<String> response3 = new TestRestTemplate()
            .exchange(url.concat("/secure/sample/test/forbidden"), HttpMethod.GET, requestEntity, String.class);
    logger.info("Response3 is :->" + response3);
    Assert.assertThat(response3.getStatusCode(), Matchers.equalTo(HttpStatus.FORBIDDEN));

}

From source file:svc.data.citations.datasources.tyler.TylerCitationDataSource.java

private List<Citation> performRestTemplateCall(URI uri) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("apikey", tylerConfiguration.apiKey);
    HttpEntity<?> query = new HttpEntity<>(headers);
    ResponseEntity<List<TylerCitation>> tylerCitationsResponse = null;
    ParameterizedTypeReference<List<TylerCitation>> type = new ParameterizedTypeReference<List<TylerCitation>>() {
    };//from ww w .  jav a 2 s. c o m

    List<TylerCitation> tylerCitations = null;
    try {
        tylerCitationsResponse = restTemplate.exchange(uri, HttpMethod.GET, query, type);
        tylerCitations = tylerCitationsResponse.getBody();
        return citationFilter
                .RemoveCitationsWithExpiredDates(citationTransformer.fromTylerCitations(tylerCitations));
    } catch (RestClientException ex) {
        System.out.println("Tyler datasource is down.");
        return Lists.newArrayList();
    }

}

From source file:org.scrutmydocs.webapp.itest.api.settings.rivers.RiversApiTest.java

/**
 * Add a river//ww w.  j  a  va 2s  . co  m
 * @param fsriver
 */
protected void addRiver(FSRiver fsriver) {
    HttpEntity<FSRiver> entity = new HttpEntity<FSRiver>(fsriver);
    restTemplate.put(buildFullApiUrl("fs/"), entity);
}

From source file:org.cloudfoundry.identity.uaa.integration.TokenAdminEndpointsIntegrationTests.java

@Test
@OAuth2ContextConfiguration(resource = TokenResourceOwnerPassword.class)
public void testRevokeTokenByUser() throws Exception {

    OAuth2AccessToken token = context.getAccessToken();
    String hash = new StandardPasswordEncoder().encode(token.getValue());

    HttpEntity<?> request = new HttpEntity<String>(token.getValue());
    assertEquals(HttpStatus.OK,/*from   ww  w.j  av a 2s  .c  o m*/
            serverRunning
                    .getRestTemplate().exchange(serverRunning.getUrl("/oauth/users/{user}/tokens/{token}"),
                            HttpMethod.DELETE, request, Void.class, testAccounts.getUserName(), hash)
                    .getStatusCode());

    // The token was revoked so if we trya nd use it again it should come back unauthorized
    ResponseEntity<String> result = serverRunning
            .getForString("/oauth/users/" + testAccounts.getUserName() + "/tokens");
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    String body = result.getBody();
    assertTrue("Wrong body: " + body, body.contains("invalid_token"));

}

From source file:com.bailen.radioOnline.recursos.REJA.java

public Cancion[] random(String apiKey) throws IOException {
    HttpHeaders header = new HttpHeaders();
    header.set("Authorization", apiKey);
    HttpEntity entity = new HttpEntity(header);
    String lista = new String();
    HttpEntity<String> response;
    response = new RestTemplate().exchange("http://ceatic.ujaen.es:8075/radioapi/v2/random", HttpMethod.GET,
            entity, String.class, lista);

    String canc = response.getBody();
    StringTokenizer st = new StringTokenizer(canc, "[", true);
    st.nextToken();//  ww w  . j  a  va2s . com
    st.nextToken();
    canc = "[" + st.nextToken();

    try {

        ObjectMapper a = new ObjectMapper();
        Item[] listilla = a.readValue(canc, Item[].class);
        Vector<Integer> ids = new Vector<>();
        for (int i = 0; i < listilla.length; ++i) {
            ids.add(listilla[i].getId());
        }
        return jamendo.canciones(ids);

    } catch (Exception e) {
        //return null;
        throw new IOException("no se han recibido canciones");
    }

}

From source file:com.interop.webapp.WebAppTests.java

@Test
public void testLoginPage() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login",
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertTrue("Wrong content:\n" + entity.getBody(), entity.getBody().contains("_csrf"));
}

From source file:com.springsource.html5expense.security.EndpointTokenServices.java

public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    // TODO: Probably should catch REST client exceptions and rethrow as AuthenticationException
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + accessToken);
    HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
    ResponseEntity<OAuth2Authentication> response = restTemplate.exchange(oauthAuthenticationUrl,
            HttpMethod.GET, requestEntity, OAuth2Authentication.class);

    OAuth2Authentication oauth2Authentication = response.getBody();
    return oauth2Authentication;
}

From source file:demo.service.impl.DefaultServiceLocationService.java

/**
 * Enriches the provided {@link CurrentPosition} with the closest service location
 * IF the {@link CurrentPosition} has a {@link VehicleStatus} of:
 *
 * <ul>/*from  www . j ava 2s .  c  o  m*/
 *   <li>{@link VehicleStatus#SERVICE_NOW}</li>
 *   <li>{@link VehicleStatus#SERVICE_SOON}</li>
 *   <li>{@link VehicleStatus#STOP_NOW}</li>
 * <ul>
 *
 * @param currentPosition Will be enriched with the closest service location
 * @throws Exception
 */
@HystrixCommand(commandKey = "serviceLocations", commandProperties = {
        //@HystrixProperty(name = "circuitBreaker.forceOpen", value = "true")
}, fallbackMethod = "handleServiceLocationServiceFailure")
@Override
public void updateServiceLocations(CurrentPosition currentPosition) {

    switch (currentPosition.getVehicleStatus()) {

    case SERVICE_NOW:
    case SERVICE_SOON:
    case STOP_NOW:
        ResponseEntity<Resource<ServiceLocation>> result = this.restTemplate.exchange(
                "http://service-location-service/serviceLocations/search/findFirstByLocationNear?location={lat},{long}",
                HttpMethod.GET, new HttpEntity<Void>((Void) null),
                new ParameterizedTypeReference<Resource<ServiceLocation>>() {
                }, currentPosition.getLocation().getLatitude(), currentPosition.getLocation().getLongitude());
        if (result.getStatusCode() == HttpStatus.OK && result.getBody().getContent() != null) {
            currentPosition.setServiceLocation(result.getBody().getContent());
        }
        break;
    default:
    }

}