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

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

Introduction

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

Prototype

@Override
    public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException 

Source Link

Usage

From source file:demo.ServerRunning.java

@Override
public Statement apply(final Statement base, FrameworkMethod method, Object target) {

    // Check at the beginning, so this can be used as a static field
    Assume.assumeTrue(serverOnline.get(port));

    RestTemplate client = new RestTemplate();
    boolean followRedirects = HttpURLConnection.getFollowRedirects();
    HttpURLConnection.setFollowRedirects(false);
    boolean online = false;
    try {/*  w  ww .j  a  v  a 2  s. c  om*/
        client.getForEntity(new UriTemplate(getUrl("/info")).toString(), String.class);
        online = true;
        logger.info("Basic connectivity test passed");
    } catch (RestClientException e) {
        logger.warn(String.format(
                "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
                port), e);
        Assume.assumeNoException(e);
    } finally {
        HttpURLConnection.setFollowRedirects(followRedirects);
        if (!online) {
            serverOnline.put(port, false);
        }
    }

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
        }
    };

}

From source file:sample.tomcat.SslApplicationTests.java

@Test
public void testAuthenticatedHello() throws Exception {
    RestTemplate template = new RestTemplate();
    final LocalhostClientHttpRequestFactory factory = new LocalhostClientHttpRequestFactory(
            secureSocketFactory());/*from w  w  w . j  a  va 2 s. co m*/
    template.setRequestFactory(factory);

    ResponseEntity<String> httpsEntity = template.getForEntity("https://localhost:" + this.port + "/hello",
            String.class);
    assertEquals(HttpStatus.OK, httpsEntity.getStatusCode());
    assertEquals("hello", httpsEntity.getBody());
}

From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java

/**
 * Test insecure endpoint without authentication
 *///w w w.  java2 s.  c o  m
@Test
public void testInsecureEndpointNoAuthentication() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = null;
    try {
        response = restTemplate.getForEntity(INSECURE_ENDPOINT, String.class);
        assertEquals("You are home.", response.getBody());
        assertEquals(HttpStatus.OK, response.getStatusCode());
    } catch (ResourceAccessException ex) {
        fail("It appears that the server may not be running. Please start it before running tests");
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
}

From source file:com.concentricsky.android.khanacademy.data.remote.KAEntityCollectionFetcherTask.java

@Override
protected List<T> doInBackground(Void... arg0) {
    // call  API and fetch an entity tree (commonly the tree rooted at the root topic)

    RestTemplate restTemplate = new RestTemplate();
    if (consumer != null) {
        restTemplate.setRequestFactory(new SpringRequestFactory(consumer));
    }//ww  w .j  a  va  2 s.  com

    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
    String body = result.getBody();

    // String tag = "~~~~~~~~~~~~~~~~";
    // Log.setLevel(tag, Log.VERBOSE);
    // Log.d(tag, "result body is a " + body.getClass().getCanonicalName());
    // Log.d(tag, "result is " + body);

    ObjectMapper mapper = new ObjectMapper();

    List<T> list = null;
    try {
        list = mapper.readValue(body, type);
    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JsonMappingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return list;
}

From source file:com.provenance.cloudprovenance.connector.traceability.TraceabilityStoreConnector.java

public String getCurrentTraceabilityRecordId(URL serviceId) {
    // URI encoded

    RestTemplate restTemplate = new RestTemplate();

    // restTemplate.get

    ResponseEntity<String> traceabilityResponseEntity = null;

    try {/*from  w w w  . j  a  v a 2 s .c om*/
        traceabilityResponseEntity = restTemplate.getForEntity(serviceId.toExternalForm(), String.class);

        if (traceabilityResponseEntity.getStatusCode().value() == 200) {
            return traceabilityResponseEntity.getBody();
        } else {
            return null;
        }

    } catch (org.springframework.web.client.HttpClientErrorException ex) {
        logger.warn(ex.toString());
        return null;
    }
}

From source file:com.provenance.cloudprovenance.connector.traceability.TraceabilityStoreConnector.java

public String getCurrentTraceabilityRecordId(String serviceId) {

    // URI encoded
    String restURI = UriEncoder.encode("http://" + server_add + ":" + port_no + "/" + service + "/" + resource
            + "/" + serviceId + "/" + this.TRACEABILITY_TYPE);

    RestTemplate restTemplate = new RestTemplate();

    // restTemplate.get

    ResponseEntity<String> traceabilityResponseEntity = null;

    try {//from w  w w  .  j  a v  a 2 s  .c  om
        traceabilityResponseEntity = restTemplate.getForEntity(restURI, String.class);

        if (traceabilityResponseEntity.getStatusCode().value() == 200) {
            return traceabilityResponseEntity.getBody();
        } else {
            return null;
        }

    } catch (org.springframework.web.client.HttpClientErrorException ex) {
        logger.warn(ex.toString());
        return null;
    }

    // ResponseEntity<String> traceabilityDocId =
    // restTemplate.exchange(restURI, HttpMethod.GET, null, String.class);
    // System.out.println(traceabilityDocId.getBody());
    // System.out.println(traceabilityDocId.getStatusCode());

    // return traceabilityDocId.getBody();

}

From source file:org.cloudfoundry.identity.varz.integration.ServerRunning.java

@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {

    // Check at the beginning, so this can be used as a static field
    if (!integrationTest) {
        Assume.assumeTrue(serverOnline.get(port));
    }//from   ww w  .  j av  a2s .c o m

    RestTemplate client = new RestTemplate();
    boolean online = false;
    try {
        client.getForEntity(new UriTemplate(getUrl("/info")).toString(), String.class);
        online = true;
        logger.info("Basic connectivity test passed");
    } catch (RestClientException e) {
        logger.warn(String.format(
                "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
                port), e);
        if (!integrationTest) {
            Assume.assumeNoException(e);
        }
    } finally {
        if (!online) {
            serverOnline.put(port, false);
        }
    }

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
        }

    };

}

From source file:org.cloudfoundry.identity.batch.integration.ServerRunning.java

@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {

    // Check at the beginning, so this can be used as a static field
    if (!integrationTest) {
        Assume.assumeTrue(serverOnline.get(port));
    }/*from  w  w  w  .j a v  a2s.c  o  m*/

    RestTemplate client = new RestTemplate();
    boolean online = false;
    try {
        client.getForEntity(new UriTemplate(getUrl("/login")).toString(), String.class);
        online = true;
        logger.info("Basic connectivity test passed");
    } catch (RestClientException e) {
        logger.warn(String.format(
                "Not executing tests because basic connectivity test failed for hostName=%s, port=%d", hostName,
                port), e);
        if (!integrationTest) {
            Assume.assumeNoException(e);
        }
    } finally {
        if (!online) {
            serverOnline.put(port, false);
        }
    }

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
        }

    };

}

From source file:com.ge.predix.uaa.token.lib.ZacTokenServiceTest.java

@SuppressWarnings("unchecked")
private OAuth2Authentication loadAuthentication(final String zoneName, final String zoneUserScope,
        final String requestUri, final List<String> nonZoneUriPatterns) {

    ZacTokenService zacTokenServices = new ZacTokenService();
    zacTokenServices.setServiceZoneHeaders(PREDIX_ZONE_HEADER_NAME);

    Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(zoneUserScope));

    OAuth2Authentication oauth2Authentication = Mockito.mock(OAuth2Authentication.class);

    Mockito.when(oauth2Authentication.isAuthenticated()).thenReturn(true);
    FastTokenServices mockFTS = Mockito.mock(FastTokenServices.class);
    Mockito.doNothing().when(mockFTS).setUseHttps(true);
    Mockito.doNothing().when(mockFTS).setStoreClaims(true);
    Mockito.doNothing().when(mockFTS).setTrustedIssuers(Matchers.anyList());
    Mockito.when(oauth2Authentication.getAuthorities()).thenReturn(authorities);
    Mockito.when(mockFTS.loadAuthentication(Matchers.anyString())).thenReturn(oauth2Authentication);

    FastTokenServicesCreator mockFTSC = Mockito.mock(FastTokenServicesCreator.class);
    when(mockFTSC.newInstance()).thenReturn(mockFTS);

    zacTokenServices.setFastRemoteTokenServicesCreator(mockFTSC);
    zacTokenServices.setServiceBaseDomain(BASE_DOMAIN);
    zacTokenServices.setServiceId(SERVICEID);

    DefaultZoneConfiguration zoneConfig = new DefaultZoneConfiguration();

    List<String> trustedIssuers;
    // Non zone specific request, using default issuer
    if (StringUtils.isEmpty(zoneName)) {
        trustedIssuers = Arrays.asList(DEFAULT_TRUSTED_ISSUER);
        // Zone specific request, using the issuers returned by mockTrustedIssuersResponseEntity
    } else {//ww  w  .  jav a2 s  .com
        trustedIssuers = ZONE_TRUSTED_ISSUERS;
    }
    zoneConfig.setTrustedIssuerIds(trustedIssuers);
    zacTokenServices.setDefaultZoneConfig(zoneConfig);
    zoneConfig.setAllowedUriPatterns(nonZoneUriPatterns);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    when(request.getServerName()).thenReturn("localhost");
    when(request.getHeader(PREDIX_ZONE_HEADER_NAME)).thenReturn(zoneName);
    when(request.getRequestURI()).thenReturn(requestUri);
    zacTokenServices.setRequest(request);
    RestTemplate restTemplateMock = Mockito.mock(RestTemplate.class);
    zacTokenServices.setOauth2RestTemplate(restTemplateMock);
    try {
        zacTokenServices.afterPropertiesSet();
    } catch (Exception e) {
        Assert.fail("Unexpected exception after properties set on zacTokenServices " + e.getMessage());
    }

    when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + ZONE, TrustedIssuers.class))
            .thenReturn(mockTrustedIssuersResponseEntity());

    when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + INVALID_ZONE,
            TrustedIssuers.class)).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));

    String accessToken = this.tokenUtil.mockAccessToken(600, zoneUserScope);
    OAuth2Authentication loadAuthentication = zacTokenServices.loadAuthentication(accessToken);

    // Making sure we are passing the right set of issuers to the FastTokenServices
    Mockito.verify(mockFTS).setTrustedIssuers(trustedIssuers);
    return loadAuthentication;
}

From source file:comsat.sample.tomcat.SampleTomcatTwoConnectorsApplicationTests.java

@Test
public void testHello() throws Exception {
    RestTemplate template = new RestTemplate();
    final MySimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory(
            new HostnameVerifier() {

                @Override/*from w w w.ja  v a 2 s. com*/
                public boolean verify(final String hostname, final SSLSession session) {
                    return true; // these guys are alright by me...
                }
            });
    template.setRequestFactory(factory);

    ResponseEntity<String> entity = template.getForEntity("http://localhost:" + this.port + "/hello",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("hello", entity.getBody());

    ResponseEntity<String> httpsEntity = template
            .getForEntity("https://localhost:" + this.context.getBean("port") + "/hello", String.class);
    assertEquals(HttpStatus.OK, httpsEntity.getStatusCode());
    assertEquals("hello", httpsEntity.getBody());
}