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:com.test.MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html");
    //PrintWriter out = response.getWriter();

    String jsonText = "";
    String jsonText2 = "";

    String serverPath = "https://" + request.getServerName();
    try {//  w w w . j av  a2s .  c  o m
        RestTemplate template = new RestTemplate();
        URLBuilder url = new URLBuilder(serverPath);
        url.addPath("headerfooter-portlet/api/secure/jsonws/headerfooter/get-header");
        url.addQueryParam("isAdmin", "true");
        jsonText = template.getForObject(url.toString(), String.class);
        JsonParser parser = new JsonParser();
        jsonText = parser.parse(jsonText).getAsString();

        RestTemplate template2 = new RestTemplate();
        URLBuilder url2 = new URLBuilder(serverPath);
        url2.addPath("headerfooter-portlet/api/secure/jsonws/headerfooter/get-footer");
        url2.addQueryParam("isAdmin", "true");
        jsonText2 = template2.getForObject(url2.toString(), String.class);
        JsonParser parser2 = new JsonParser();
        jsonText2 = parser2.parse(jsonText2).getAsString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    request.setAttribute("servletName", "MyServlet");
    request.setAttribute("jsonText", jsonText);
    request.setAttribute("jsonText2", jsonText2);
    getServletConfig().getServletContext().getRequestDispatcher("/html/wsClient.jsp").forward(request,
            response);

}

From source file:org.springframework.yarn.boot.YarnRestTemplateAutoConfigurationTests.java

@Test
public void testBasicEnabledWithSsl() throws Exception {
    context = SpringApplication.run(//from   w  w w  . j  a v a2s .co  m
            new Object[] { CustomRestTemplateConfiguration.class, YarnRestTemplateAutoConfiguration.class,
                    FallbackYarnRestTemplateAutoConfiguration.class, VanillaWebConfiguration.class,
                    WebConfiguration.class },
            new String[] { "--security.basic.enabled=true", "--security.user.name=username",
                    "--security.user.password=password", "--security.require-ssl=true",
                    "--server.ssl.key-store=classpath:test.jks", "--server.ssl.key-store-password=secret",
                    "--server.ssl.key-password=password" });

    PortInitListener portInitListener = context.getBean(PortInitListener.class);
    assertThat(portInitListener.latch.await(10, TimeUnit.SECONDS), is(true));
    int port = portInitListener.port;

    RestTemplate restTemplate = context.getBean(YarnSystemConstants.DEFAULT_ID_RESTTEMPLATE,
            RestTemplate.class);

    String response = restTemplate.getForObject("https://localhost:" + port + "/", String.class);
    assertThat(response, is("home"));
}

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

public List<Species> downloadSpecies(Survey survey, List<Integer> downloadedSurveys, int first,
        int maxResults) {

    String url = getServerUrl() + String.format(speciesUrl, ident, survey.server_id, first, maxResults);
    for (Integer id : downloadedSurveys) {
        url += "&surveysOnDevice=" + id;
    }/*w w  w .  j av a  2  s. com*/

    RestTemplate restTemplate = getRestTemplate();
    Log.d("URL", url);
    DownloadSpeciesResponse response = restTemplate.getForObject(url, DownloadSpeciesResponse.class);

    return response.list;
}

From source file:org.springframework.yarn.boot.YarnRestTemplateAutoConfigurationTests.java

@Test
public void testBasicEnabled() throws Exception {
    context = SpringApplication.run(/*from   www .  j  a  va 2s . c  o  m*/
            new Object[] { YarnRestTemplateAutoConfiguration.class,
                    FallbackYarnRestTemplateAutoConfiguration.class, VanillaWebConfiguration.class,
                    WebConfiguration.class },
            new String[] { "--security.basic.enabled=true", "--security.user.name=username",
                    "--security.user.password=password" });

    PortInitListener portInitListener = context.getBean(PortInitListener.class);
    assertThat(portInitListener.latch.await(10, TimeUnit.SECONDS), is(true));
    int port = portInitListener.port;

    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.context)
            .addFilters(this.context.getBean("springSecurityFilterChain", Filter.class)).build();
    mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isUnauthorized())
            .andExpect(MockMvcResultMatchers.header().string("www-authenticate",
                    Matchers.containsString("realm=\"Spring\"")));

    RestTemplate restTemplate = context.getBean(YarnSystemConstants.DEFAULT_ID_RESTTEMPLATE,
            RestTemplate.class);

    String response = restTemplate.getForObject("http://localhost:" + port + "/", String.class);
    assertThat(response, is("home"));
}

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

/**
 * {@inheritDoc} <br/>//  w  w  w .  j  av a 2s  . c  om
 * <br/>
 * Delegates an incoming status description request to the WPS proxyand
 * creates an instance of {@link StatusDescription}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance and
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to
 *            identify the process and
 *            {@link URL_Constants_TAMIS#JOB_ID_VARIABLE_NAME} to identify
 *            the job
 * @return an instance of {@link StatusDescription}
 */
@Override
public StatusDescription forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    initializeRequestSpecificParameters(parameterValueStore);

    String statusDescription_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate statusDescriptionTemplate = new RestTemplate();

    // fetch the status description from WPS proxy and
    // deserialize it into TAMIS status decsription
    StatusDescription statusDescriptionDoc = statusDescriptionTemplate
            .getForObject(statusDescription_url_wpsProxy, StatusDescription.class);

    String outputs = statusDescriptionDoc.getStatusInfo().getOutput();

    if (outputs != null) {
        /*
         * we want to replace the baseURL of the outputUrl field of the
         * statusDescription. From the WPS proxy, the returned outputUrl
         * field will point to a URL specific for the proxy. We need to
         * replace it with the right URL of this application (the base URL
         * will change).
         * 
         * outputURL_wpsProxy =
         * <baseURL_WpsProxy>/processes/<process_id>/jobs/<job_id>
         * outputURL_tamis =
         * <baseURL_Tamis>tamis_prefix/<service_id>/processes/<process_id>/
         * jobs/< job_id>
         */
        String tamis_baseUrl = constructTamisBaseUrl(request);

        String outputURL_tamis = tamis_baseUrl + "/" + URL_Constants_TAMIS.API_V1_BASE_PREFIX + "/"
                + URL_Constants_TAMIS.TAMIS_PREFIX + "/" + this.getServiceId()
                + URL_Constants_TAMIS.SLASH_PROCESSES + "/" + this.getProcessId()
                + URL_Constants_TAMIS.SLASH_JOBS + "/" + this.getJobId() + URL_Constants_TAMIS.SLASH_OUTPUTS;
        statusDescriptionDoc.getStatusInfo().setOutput(outputURL_tamis);
    }

    return statusDescriptionDoc;
}

From source file:currency.converter.openexchangerate.OpenExchangeCurrencyConverter.java

/**
 * Retrieves latest exchange rates from <a href="https://openexchangerates.org">OpenExchangeRates</a> by using
 * REST template. Retrieved rates are stored as search history for the specific user.
 * //from ww w.j ava 2  s .c om
 * @param baseCurrency Base currency for exchange rates
 * @param amount Amount
 * 
 * @return {@link CurrencyRateModel}
 * 
 * @throws InvalidParameterException for invalid arguments
 */
public CurrencyRateModel getLatestCurrencyRates(String baseCurrency, double amount)
        throws InvalidParameterException {

    if (StringUtils.isNullOrEmpty(baseCurrency)) {
        baseCurrency = SupportedCurrencies.USD.name();
    }

    if (amount <= ZERO) {
        amount = MINIMUM_AMOUNT;
    }

    StringBuilder builder = new StringBuilder();
    String apiKey = configuration.getOpenExchangeApiKey();
    builder.append("https://openexchangerates.org/api/latest.json?app_id=").append(apiKey).append("&base=")
            .append(baseCurrency);

    boolean isCommercialApi = configuration.isOpenExchangeCommercialLicense();
    if (isCommercialApi) {
        builder.append(getTargetCurrencies(baseCurrency));
    }

    logger.info("Latest rate API URL : " + builder.toString());

    RestTemplate restTemplate = new RestTemplate();
    CurrencyRateModel rates = restTemplate.getForObject(builder.toString(), CurrencyRateModel.class);

    multiplyAmount(rates, amount, baseCurrency);
    logger.info(rates.toString());

    // save currency history
    String userName = userService.getLoggedInUserName();
    saveExchangeRate(rates, baseCurrency, amount, LocalDate.now(), userName);

    return rates;
}

From source file:IntergrationTest.OCSPIntegrationTest.java

@Test
public void testChangeMode() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    String resp = restTemplate.getForObject(OCSP_MODE_URL.toString(), String.class);
    MatcherAssert.assertThat(resp, CoreMatchers.containsString("AUTO"));
    resp = restTemplate.getForObject(OCSP_MODE_URL.toString() + "?mode=1", String.class);
    MatcherAssert.assertThat(resp, CoreMatchers.containsString("GOOD"));
    resp = restTemplate.getForObject(OCSP_MODE_URL.toString() + "?mode=2", String.class);
    MatcherAssert.assertThat(resp, CoreMatchers.containsString("REVOKED"));
    resp = restTemplate.getForObject(OCSP_MODE_URL.toString() + "?mode=3", String.class);
    MatcherAssert.assertThat(resp, CoreMatchers.containsString("UNKNOWN"));
    resp = restTemplate.getForObject(OCSP_MODE_URL.toString() + "?mode=bad", String.class);
    MatcherAssert.assertThat(resp, CoreMatchers.containsString("Illegal"));
}

From source file:fi.vrk.xroad.catalog.collector.actors.ListClientsRestTest.java

@Test
public void testErrorResponseCode() throws Exception {
    RestTemplate t = new RestTemplate();
    MockRestServiceServer mockServer = MockRestServiceServer.createServer(t);

    mockServer.expect(requestTo(TEST_REQUEST_PATH)).andRespond(withServerError());
    try {/*from  w  w  w  . j a  v  a 2  s.c  o m*/
        ClientList clientList = t.getForObject(TEST_REQUEST_PATH, ClientList.class);
        fail("should fail since not http 200 OK");
    } catch (Exception expected) {
        log.error("expected exception: ", expected);
    }
}

From source file:currency.converter.openexchangerate.OpenExchangeCurrencyConverter.java

/**
 * Retrieves latest exchange rates from <a href="https://openexchangerates.org">OpenExchangeRates</a> by using
 * REST template. Retrieved rates are stored as search history for the specific user.
 * /*from w  w w .j a  v a  2s. c  o m*/
 * @param baseCurrency Base currency for exchange rates
 * @param amount Amount
 * @param dateOfRate Date for getting the historical exchange rate
 * 
 * @return {@link CurrencyRateModel}
 * 
 * @throws InvalidParameterException for invalid date
 */
public CurrencyRateModel getHistoricalCurrencyRates(String baseCurrency, double amount, LocalDate dateOfRate)
        throws InvalidParameterException {

    if (dateOfRate == null) {
        throw new InvalidParameterException("Date of rate is mandatory for historical currency rates!");
    }

    if (StringUtils.isNullOrEmpty(baseCurrency)) {
        baseCurrency = SupportedCurrencies.USD.name();
    }

    if (amount <= ZERO) {
        amount = MINIMUM_AMOUNT;
    }

    String apiKey = configuration.getOpenExchangeApiKey();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    StringBuilder builder = new StringBuilder();
    builder.append("https://openexchangerates.org/api/historical/").append(dateOfRate.format(formatter))
            .append(".json?app_id=").append(apiKey).append("&base=").append(baseCurrency);

    boolean isCommercialApi = configuration.isOpenExchangeCommercialLicense();
    if (isCommercialApi) {
        builder.append(getTargetCurrencies(baseCurrency));
    }

    logger.info("Historical rate API URL : " + builder.toString());

    RestTemplate restTemplate = new RestTemplate();
    CurrencyRateModel rates = restTemplate.getForObject(builder.toString(), CurrencyRateModel.class);

    multiplyAmount(rates, amount, baseCurrency);
    logger.info(rates.toString());

    // save currency history
    String userName = userService.getLoggedInUserName();
    saveExchangeRate(rates, baseCurrency, amount, dateOfRate, userName);

    return rates;
}

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

/**
 * {@inheritDoc} <br/>//ww  w .  jav a  2s.  c  o  m
 * <br/>
 * Delegates an incoming single process description request to the WPS
 * proxy, receives the extended single process description document and
 * creates an instance of {@link ProcessDescription_singleProcess}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance and
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to
 *            identify the process
 * @return an instance of {@link ProcessDescription_singleProcess}
 */
@Override
public ProcessDescription_singleProcess forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    initializeRequestSpecificParameters(parameterValueStore);

    String singleProcessDescription_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate singleProcessDescriptionTemplate = new RestTemplate();

    // fetch extended singlePocessDescriptionDoc from WPS proxy and
    // deserialize it into
    // shortened singlePocessDescriptionDoc
    ProcessDescription_singleProcess singeleProcessDescriptionDoc = singleProcessDescriptionTemplate
            .getForObject(singleProcessDescription_url_wpsProxy, ProcessDescription_singleProcess.class);

    return singeleProcessDescriptionDoc;
}