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

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

Introduction

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

Prototype

public RestTemplate() 

Source Link

Document

Create a new instance of the RestTemplate using default settings.

Usage

From source file:org.client.one.service.OAuthAuthenticationService.java

public String loginSSO(String code, String redirectUri) throws JSONException {
    RestOperations rest = new RestTemplate();
    String resAuth = rest.postForObject(
            MessageFormat.format(
                    "{0}/oauth/token?code={1}&client_id={2}&client_secret={3}&grant_type={4}&redirect_uri={5}",
                    oauthServerBaseURL, code, appToken, appPassword, "authorization_code", redirectUri),
            null, String.class);
    System.out.println(resAuth);//from  w  w w  .  j  av a 2  s. c o m
    JSONObject resJsA = new JSONObject(resAuth);
    return resJsA.getString("access_token");
}

From source file:jp.go.aist.six.util.core.web.spring.SpringHttpClientImpl.java

/**
 * Generic HTTP method execution.// w  ww  . java  2 s .  c  o  m
 *
 * @throws  HttpException
 *  when an exceptional condition occurred during the HTTP method execution.
 */
protected <T> T _execute(final String string_url, final HttpMethod method, final RequestCallback callback,
        final ResponseExtractor<T> extractor) {
    _LOG_.debug("HTTP: method = " + method + ", URL=" + string_url);

    URI uri = null;
    try {
        URL url = new URL(string_url); //throws MalformedURLException
        uri = url.toURI(); //throws URISyntaxException
    } catch (Exception ex) {
        _LOG_.error("HTTP client error: " + ex);
        throw new HttpException(ex);
    }

    T response = null;
    try {
        RestTemplate rest = new RestTemplate();
        response = rest.execute(uri, method, callback, extractor);
        //throws RestClientException
    } catch (Exception ex) {
        _LOG_.error("HTTP client error: " + ex);
        throw new HttpException(ex);
    }

    return response;
}

From source file:fi.vrk.xroad.catalog.collector.configuration.ApplicationConfiguration.java

@Bean
@Qualifier("listClientsRestOperations")
public RestOperations getRestOperations() {
    return new RestTemplate();
}

From source file:io.lavagna.config.WebSecurityConfig.java

@Lazy
@Bean//from   w w w.  j ava  2 s.c om
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(asList(new FormHttpMessageConverter(), new GsonHttpMessageConverter()));
    return restTemplate;
}

From source file:org.nuvola.tvshowtime.ApplicationLauncher.java

@Scheduled(fixedDelay = Long.MAX_VALUE)
public void init() {
    tvShowTimeTemplate = new RestTemplate();

    File storeToken = new File(tvShowTimeConfig.getTokenFile());
    if (storeToken.exists()) {
        try {//  w ww .j  ava 2 s  .  c  o  m
            FileInputStream fileInputStream = new FileInputStream(storeToken);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            accessToken = (AccessToken) objectInputStream.readObject();
            objectInputStream.close();
            fileInputStream.close();

            LOG.info("AccessToken loaded from file with success : " + accessToken);
        } catch (Exception e) {
            LOG.error("Error parsing the AccessToken stored in 'session_token'.");
            LOG.error("Please remove the 'session_token' file, and try again.");
            LOG.error(e.getMessage());

            System.exit(1);
        }

        try {
            processWatchedEpisodes();
        } catch (Exception e) {
            LOG.error("Error during marking episodes as watched.");
            LOG.error(e.getMessage());

            System.exit(1);
        }
    } else {
        requestAccessToken();
    }
}

From source file:com.javafxpert.wikibrowser.WikiThumbnailController.java

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> locatorEndpoint(
        @RequestParam(value = "title", defaultValue = "") String articleTitle,
        @RequestParam(value = "id", defaultValue = "") String itemId,
        @RequestParam(value = "lang") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);

    String thumbnailUrlStr = null;
    if (!articleTitle.equals("")) {
        // Check cache for thumbnail
        thumbnailUrlStr = ThumbnailCache.getThumbnailUrlByTitle(articleTitle, language);

        if (thumbnailUrlStr == null) {
            log.info(/*from  w ww .  j a v a2s . c o m*/
                    "Thumbnail NOT previously requested for articleTitle: " + articleTitle + ", lang: " + lang);

            thumbnailUrlStr = title2Thumbnail(articleTitle, language);
            ThumbnailCache.setThumbnailUrlByTitle(articleTitle, language, thumbnailUrlStr);
        }
    } else if (!itemId.equals("")) {
        ItemInfoResponse itemInfoResponse = null;

        // Check cache for thumbnail
        thumbnailUrlStr = ThumbnailCache.getThumbnailUrlById(itemId, language);

        if (thumbnailUrlStr == null) {
            log.info("Thumbnail NOT previously requested for itemId: " + itemId + ", lang: " + lang);

            try {
                String url = this.wikiBrowserProperties.getLocatorServiceUrl(itemId, lang);
                itemInfoResponse = new RestTemplate().getForObject(url, ItemInfoResponse.class);

                //log.info(itemInfoResponse.toString());

                if (itemInfoResponse != null) {
                    thumbnailUrlStr = title2Thumbnail(itemInfoResponse.getArticleTitle(), language);
                } else {
                    thumbnailUrlStr = "";
                }

                ThumbnailCache.setThumbnailUrlById(itemId, language, thumbnailUrlStr);

            } catch (Exception e) {
                e.printStackTrace();
                log.info("Caught exception when calling /locator?id=" + itemId + " : " + e);
            }

        }
    }

    return Optional.ofNullable(thumbnailUrlStr).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Wikipedia thumbnail query unsuccessful",
                    HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:com.iata.ndc.trial.controllers.DefaultController.java

@RequestMapping(value = "/sita", method = RequestMethod.GET)
public String getSita() {

    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.getObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    converters.add(converter);//from   w  ww. j  a va2 s .c  o m
    restTemplate.setMessageConverters(converters);

    HttpHeaders headers = new HttpHeaders();
    headers.add("client-key", "zmd9apqgg2jwekf8zgqg5ybf");
    headers.setContentType(MediaType.APPLICATION_JSON);

    ResponseEntity<BALocationsResponseWrapper> baLocationsResponse = restTemplate.exchange(
            "https://api.ba.com/rest-v1/v1/balocations", HttpMethod.GET, new HttpEntity<Object>(headers),
            BALocationsResponseWrapper.class);
    System.out.println(baLocationsResponse.getBody().getGetBALocationsResponse().getCountry().size());
    return "index";
}

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  .co m
        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:com.xyxy.platform.examples.showcase.demos.hystrix.service.UserService.java

/**
 * Hystrix Command???, Thread-SafedRestTemplate.
 */// w  w  w .  ja  v  a2s . c  o  m
@PostConstruct
public void init() {
    // ?RestTemplate
    restTemplate = new RestTemplate();

    // Command?? //
    commandConfig = Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
            .andCommandKey(HystrixCommandKey.Factory.asKey("GetUserCommand"));

    HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
    commandConfig.andCommandPropertiesDefaults(commandProperties);

    //  //
    // ?? 520
    commandProperties.withCircuitBreakerSleepWindowInMilliseconds(20000)
            // rolling windows?50%?.
            .withCircuitBreakerErrorThresholdPercentage(50)
            // rolling window???20, 3.
            .withCircuitBreakerRequestVolumeThreshold(3)
            // rolling windows 20120???.
            .withMetricsRollingStatisticalWindowInMilliseconds(120000)
            .withMetricsRollingStatisticalWindowBuckets(120);

    // ? //
    if (isolateThreadPool) { // Hystrix
        // 13.
        commandProperties.withExecutionIsolationThreadTimeoutInMilliseconds(3000);
        //  ?10??5?.
        commandConfig.andThreadPoolPropertiesDefaults(
                HystrixThreadPoolProperties.Setter().withCoreSize(10).withQueueSizeRejectionThreshold(5));
    } else { // 
        // ??RestTemplate10
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setReadTimeout(10000);

        // ?10?.
        commandProperties.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
                .withExecutionIsolationSemaphoreMaxConcurrentRequests(10);
    }
}

From source file:eu.falcon.semantic.client.DenaClient.java

public static JSONObject getClassAttributes(String classURI) {

    final String uri = "http://falconsemanticmanager.euprojects.net/api/v1/ontology/class/attributes";
    //final String uri = "http://localhost:8090/api/v1/ontology/class/attributes";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    RestTemplate restTemplate = new RestTemplate();

    HttpEntity<String> entity = new HttpEntity<>(classURI, headers);

    String result = restTemplate.postForObject(uri, entity, String.class);

    return new JSONObject(result);
}