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

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

Introduction

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

Prototype

@Override
    @Nullable
    public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException 

Source Link

Usage

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

@RequestMapping(value = "/articles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getArticlesAround(@RequestParam Double lat, @RequestParam Double lon)
        throws InterruptedException, ExecutionException, JsonProcessingException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(GEO_URL).queryParam("lat", lat.toString())
            .queryParam("lon", lon.toString());

    RestTemplate template = new RestTemplate();
    List<Map<String, Object>> geoResponse = template.getForObject(builder.build().encode().toUri(), List.class);

    Iterator<Map<String, Object>> it = geoResponse.iterator();
    List<Future<ResponseEntity<Map>>> jobs = new ArrayList<>();

    // to be able to merge answers from rating to geoitems there is a need 
    // to map the article to its articleID
    // (articleID) => (articleItem)
    Map<String, Map<String, Object>> mappedResponseObjects = new HashMap<>();
    while (it.hasNext()) {
        Map<String, Object> item = it.next();

        AsyncRestTemplate async = new AsyncRestTemplate();
        Future<ResponseEntity<Map>> futureResult = async.getForEntity((String) item.get("rating"), Map.class);
        jobs.add(futureResult);//w  w w  . java 2  s .c  o m
        mappedResponseObjects.put((String) item.get("articleID"), item);
    }

    for (Future<ResponseEntity<Map>> job : jobs) {
        Map<String, Object> ratingMap = job.get().getBody();
        String articleID = (String) ratingMap.get("articleID");

        if ((Boolean) ratingMap.get("appropriate")) {
            mappedResponseObjects.get(articleID).putAll(ratingMap);
        } else {
            mappedResponseObjects.remove(articleID);
        }
    }

    WeightingPolicy policy = new WeightingPolicyImpl();
    List<Map<String, Object>> orderedResponse = policy.sortIncludingRating(mappedResponseObjects.values());
    List<Map<String, Object>> result = new ResponseMapFilterImpl().filter(orderedResponse);

    return new ResponseEntity<>(objectMapper.writeValueAsString(result), HttpStatus.OK);
}

From source file:org.n52.tamis.rest.forward.capabilities.CapabilitiesRequestForwarder.java

/**
 * {@inheritDoc} <br/>//w  w  w .j a  va2 s .c  om
 * <br/>
 * Delegates an incoming getCapabilities request to the WPS proxy, receives
 * the extended capabilities document and creates an instance of
 * {@link Capabilities_Tamis}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance
 * @return an instance of {@link Capabilities_Tamis}
 */
public final Capabilities_Tamis forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    // assure that the URL variable "serviceId" is existent
    initializeRequestSpecificParameters(parameterValueStore);

    String capabilities_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate capabilitiesTemplate = new RestTemplate();

    // fetch extended capabilitiesDoc from WPS proxy and deserialize it into
    // shortened capabilitiesDoc
    Capabilities_Tamis capabilitiesDoc = capabilitiesTemplate.getForObject(capabilities_url_wpsProxy,
            Capabilities_Tamis.class);

    /*
     * Override the URL of  capabilitiesDoc with the base URL of the tamis WPS proxy.
     * 
     * Retrieve the base URL from the HtteServletRequest object 
     */
    String requestURL = request.getRequestURL().toString();
    //      String wpsBaseUrl_tamisProxy = requestURL.split(URL_Constants_TAMIS.TAMIS_PREFIX)[0];
    capabilitiesDoc.setUrl(requestURL);

    return capabilitiesDoc;
}

From source file:org.manalith.ircbot.plugin.google.GooglePlugin.java

public String getGoogleTopResult(String keyword) {
    try {/* w w w. jav  a 2s.  c  om*/
        // http://code.google.com/apis/websearch/docs/#fonje
        final String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0" //
                + "&q=" + keyword //
                + "&key=" + apiKey //
                + "&userip=" + InetAddress.getLocalHost().getHostAddress();

        MappingJackson2HttpMessageConverter conv = new MappingJackson2HttpMessageConverter();
        conv.setSupportedMediaTypes(
                Collections.singletonList(new MediaType("text", "javascript", Charset.forName("UTF-8"))));

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(conv);

        SearchResponse res = restTemplate.getForObject(url, SearchResponse.class);

        if (res.responseData != null && ArrayUtils.isNotEmpty(res.responseData.results)) {

            SearchResult result = res.responseData.results[0];

            // HTML  
            return result.content.replace("<b>", HIGH_INTENSITY).replace("</b>", LOW_INTENSITY)
                    .replace("&quot;", "\"").replace("&#39;", "'").replace("&gt;", ">").replace("&lt;", "<")
                    .replace("&amp;", "&").replace("\n", "") + " : " + result.unescapedUrl;
        }
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    }

    return null;
}

From source file:au.org.ala.fielddata.mobile.service.FieldDataServiceClient.java

public List<SpeciesGroup> downloadSpeciesGroups() {

    String url = getServerUrl() + "/species/speciesGroups";
    Log.d("URL", url);
    RestTemplate restTemplate = getRestTemplate();
    SpeciesGroupResponse[] response = restTemplate.getForObject(url, SpeciesGroupResponse[].class);
    if (response == null) {
        return new ArrayList<SpeciesGroup>(0);
    }/*from w  ww .ja  v a2 s.  co m*/
    List<SpeciesGroup> speciesGroups = new ArrayList<SpeciesGroup>(response.length);
    for (SpeciesGroupResponse responseGroup : response) {
        speciesGroups.add(responseGroup.toSpeciesGroup());
    }
    return speciesGroups;
}

From source file:org.n52.tamis.rest.forward.processes.ProcessesRequestForwarder.java

/**
 * {@inheritDoc} <br/>/*from w w w . ja v a2 s .  co m*/
 * <br/>
 * Delegates an incoming processes (overview) request to the WPS proxy,
 * receives the extended processes document and creates an instance of
 * {@link Processes_Tamis}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance
 * @return an instance of {@link Processes_Tamis}
 */
public final Processes_Tamis forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    // assure that the URL variable "serviceId" is existent
    initializeRequestSpecificParameters(parameterValueStore);

    String processes_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate processesTemplate = new RestTemplate();

    // fetch extended processesDoc from WPS proxy and deserialize it into
    // shortened processesDoc
    Processes_Tamis processesDoc = processesTemplate.getForObject(processes_url_wpsProxy,
            Processes_Tamis.class);

    /*
     * set the URL.
     * 
     * construct it via the requestURL from HttpServletRequest object and
     * append the process identifier.
     */
    setUrls(processesDoc, request.getRequestURL());

    return processesDoc;
}

From source file:org.n52.tamis.rest.forward.processes.execute.SosRequestConstructor.java

private SosTimeseriesInformation fetchSosTimeseriesInformation(String timespanParameterValue,
        String targetUrl_timeseriesApi) throws IOException {
    RestTemplate timeseriesApiTemplate = new RestTemplate();
    SosTimeseriesInformation timeseriesInformation = timeseriesApiTemplate.getForObject(targetUrl_timeseriesApi,
            SosTimeseriesInformation.class);

    // set the temporal filter from timespan parameter
    timeseriesInformation.setTemporalFilterFromEncodedTimespan(timespanParameterValue);

    return timeseriesInformation;
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

private void makeRequest(HttpClient httpClient, String url) {
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getForObject(url, String.class);
}

From source file:org.n52.tamis.rest.controller.processes.jobs.ResultController.java

private ResultDocument fetchResultDocumentForJob(String jobId, HttpServletRequest request) {
    /*//from   ww w.jav  a2 s  . co  m
     * Fetches the complete resultDocument (by sending a GET outputs request
     * against the specified jobId) and extracts the requested output with
     * the specified id.
     */
    /*
     * request URL looks like =
     * <tamis-rest-baseURL>/prefixes/services/{serviceID}/processes/{
     * processID}/jobs/{jobId}/outputs/{outputId}
     * 
     * outputs request URL looks like (trailing outputId must be cut off):
     * request URL looks like =
     * <tamis-rest-baseURL>/prefixes/services/{serviceID}/processes/{
     * processID}/jobs/{jobId}/outputs
     */

    logger.info("Trying to fetch the complete result document from job with jobId=\"{}\"", jobId);

    String slashOutputId = "/"
            + parameterValueStore.getParameterValuePairs().get(URL_Constants_TAMIS.OUTPUT_ID_VARIABLE_NAME);
    String getOutputsUrl = request.getRequestURL().toString().split(slashOutputId)[0];

    RestTemplate getOutputs = new RestTemplate();
    ResultDocument resultDocument = getOutputs.getForObject(getOutputsUrl, ResultDocument.class);

    return resultDocument;
}

From source file:com.bytebybyte.mapquest.geocoding.service.standard.MapQuestTest.java

@Test
public void testgetLatAndLon2() throws UnsupportedEncodingException {
    RestTemplate restTemplate = new RestTemplate();

    String location = "Wokingham, UK";

    String url = ADDRESS_URL + location;
    String result = restTemplate.getForObject(url, String.class);
    System.out.println("Result : " + result);

    JsonElement jelement = new JsonParser().parse(result);
    JsonArray jsonArray = jelement.getAsJsonArray();

    Double[] position = null;// ww  w  . j a v  a2 s  .c  o  m
    List<Double[]> positions = new ArrayList<Double[]>();

    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject jo = jsonArray.get(i).getAsJsonObject();
        String lat = removeDoubleQuotes(jo.get("lat").toString());
        String lon = removeDoubleQuotes(jo.get("lon").toString());
        position = new Double[] { Double.parseDouble(lat), Double.parseDouble(lon) };
        positions.add(position);
    }

    for (Double[] doubles : positions) {
        System.out.println("----------------------");
        System.out.println("Lat : [" + doubles[0] + "[, Lon :[" + doubles[1] + "]");
    }
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

@SuppressWarnings("unchecked")
private void getQueueDetails(RestTemplate restTemplate, String queueName, URI uri) {
    Map<String, Object> queue = restTemplate.getForObject(uri, Map.class);
    if (queue.get("consumers") != Integer.valueOf(0)) {
        throw new RabbitAdminException("Queue " + queueName + " is in use");
    }/*  w  ww  .  j ava  2  s  .c o  m*/
}