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.craftercms.commerce.client.itest.data.SolrTestDataService.java

public void destroyTestData() {

    String updateUrl = solrServerUrl + UPDATE_URI;
    new RestTemplate().postForLocation(updateUrl, DELETE_ALL_COMMAND);

    LOGGER.info("Finished destroying Solr test data.");
}

From source file:com.taxamo.example.ec.ApplicationController.java

/**
 * This method initializes Express Checkout token with PayPal and then redirects to Taxamo checkout form.
 *
 * Please note that only Express Checkout token is provided to Taxamo - and Taxamo will use
 * provided PayPal credentials to get order details from it and render the checkout form.
 *
 *
 * @param model/*from  w  w w  . j a v  a 2s  .c o  m*/
 * @return
 */
@RequestMapping("/express-checkout")
public String expressCheckout(Model model) {

    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("USER", ppUser);
    map.add("PWD", ppPass);
    map.add("SIGNATURE", ppSign);
    map.add("VERSION", "117");
    map.add("METHOD", "SetExpressCheckout");
    map.add("returnUrl", properties.getProperty(PropertiesConstants.STORE)
            + properties.getProperty(PropertiesConstants.CONFIRM_LINK));
    map.add("cancelUrl", properties.getProperty(PropertiesConstants.STORE)
            + properties.getProperty(PropertiesConstants.CANCEL_LINK));

    //shopping item(s)
    map.add("PAYMENTREQUEST_0_AMT", "20.00"); // total amount
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");
    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");

    map.add("L_PAYMENTREQUEST_0_NAME0", "ProdName");
    map.add("L_PAYMENTREQUEST_0_DESC0", "ProdName desc");
    map.add("L_PAYMENTREQUEST_0_AMT0", "20.00");
    map.add("L_PAYMENTREQUEST_0_QTY0", "1");
    map.add("L_PAYMENTREQUEST_0_ITEMCATEGORY0", "Digital");

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    template.setMessageConverters(messageConverters);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
            requestHeaders);
    ResponseEntity<String> res = template.exchange(
            URI.create(properties.get(PropertiesConstants.PAYPAL_NVP).toString()), HttpMethod.POST, request,
            String.class);

    Map<String, List<String>> params = parseQueryParams(res.getBody());

    String ack = params.get("ACK").get(0);
    if (!ack.equals("Success")) {
        model.addAttribute("error", params.get("L_LONGMESSAGE0").get(0));
        return "error";
    } else {
        String token = params.get("TOKEN").get(0);
        return "redirect:" + properties.get(PropertiesConstants.TAXAMO) + "/checkout/index.html?" + "token="
                + token + "&public_token=" + publicToken + "&cancel_url="
                + new String(
                        Base64.encodeBase64((properties.getProperty(PropertiesConstants.STORE)
                                + properties.getProperty(PropertiesConstants.CANCEL_LINK)).getBytes()))
                + "&return_url="
                + new String(Base64.encodeBase64((properties.getProperty(PropertiesConstants.STORE)
                        + properties.getProperty(PropertiesConstants.CONFIRM_LINK)).getBytes()))
                + "#/paypal_express_checkout";
    }
}

From source file:info.smartkit.hairy_batman.query.KJsonApiQuery.java

public void query() {
    // KJSON API testing using RestTemplate.
    RestTemplate restTemplate = new RestTemplate();
    // restTemplate.getMessageConverters().add(new
    // StringHttpMessageConverter());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    // @see:/*  www.  jav  a  2  s. c o m*/
    // http://stackoverflow.com/questions/22329368/spring-android-rest-template-parse-json-data-with-content-type-text-html
    converter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML));
    restTemplate.getMessageConverters().add(converter);
    // Spring batch for CSV reading.
    //
    WxBar api_query_resutls = new WxBar();

    try {
        /*System.out.println("this.getParameters():" + this.getParameters());
        api_query_resutls = restTemplate.postForObject(
              GlobalConsts.KJSON_API_URI, this.getParameters(),
              WxBar.class);*/
    } catch (RestClientException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (api_query_resutls.getData() != null) {// FIXME: null JSON
        // exception handler
        // here.

        // WxBar returns =
        // restTemplate.getForObject(GlobalConsts.KJSON_API_URI,
        // WxBar.class);
        ArrayList<WxKJson> api_query_resutls_data = api_query_resutls.getData();
        // System.out.println("ApiQuery result data:  " +
        // api_query_resutls_data);
        LOG.info("ApiQuery result data:  " + api_query_resutls_data.toString());
        WxKJson wxKJson = api_query_resutls_data.get(0);
        // System.out.println("Parsed ApiQuery results,articleReadNum:" +
        // wxKJson.getRead() + ",articleLikeNum: "
        // + wxKJson.getLike());
        LOG.info("Parsed ApiQuery results,articleReadNum:" + wxKJson.getRead() + ",articleLikeNum: "
                + wxKJson.getLike());
        //
        this.readNum = Long.parseLong(wxKJson.getRead());
        this.likeNum = Long.parseLong(wxKJson.getLike());
        this.queriedSubscriber.setArticleReadNum(wxKJson.getRead());
        this.queriedSubscriber.setArticleLikeNum(wxKJson.getLike());
        double likeRate = (double) likeNum / readNum * 100;
        java.math.BigDecimal bigLikeRate = new java.math.BigDecimal(likeRate);
        String bigLikeRateStr = bigLikeRate
                .setScale(GlobalConsts.DEFINITION_PRECISION, java.math.BigDecimal.ROUND_HALF_UP).doubleValue()
                + "%";
        this.queriedSubscriber.setArticleLikeRate(bigLikeRateStr);
        //
        this.queriedSubscriber.setMoniterTime(GlobalVariables.now());
        this.queriedSubscriber.setArticleUrl(wxKJson.getUrl());
        //
        GlobalVariables.wxFooListWithOpenIdArticleReadLike.add(this.queriedSubscriber);
        // File reporting...
        new FileReporter(GlobalConsts.REPORT_FILE_OUTPUT_OPENID_ARITICLE_READ_LIKE,
                GlobalVariables.wxFooListWithOpenIdArticleReadLike,
                FileReporter.REPORTER_TYPE.R_T_OPENID_ARTICLE_READ_LIKE, FileReporter.REPORTER_FILE_TYPE.EXCEL)
                        .write();
        // Save to DB.
        Object[] params = { likeNum.intValue(), readNum.intValue(), this.queriedSubscriber.getArticleLikeRate(),
                this.queriedSubscriber.getArticleUrl() };
        int[] types = { Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.VARCHAR };
        int rows = GlobalVariables.jdbcTempate.update(GlobalConsts.JDBC_QUERY_UPDATE_OPENID_ARTICLE_READ_LIKE,
                params, types);
        LOG.info("rows(s): " + rows + " updated." + ",likeNum: " + likeNum + ",readNum: " + readNum
                + ",bigLikeRateStr: " + bigLikeRateStr + ",articleUrl: "
                + this.queriedSubscriber.getArticleUrl());
        //
        LOG.info("GlobalVariables.wxFooListWithOpenIdArticleReadLike(size):"
                + GlobalVariables.wxFooListWithOpenIdArticleReadLike.size() + ",raw: "
                + GlobalVariables.wxFooListWithOpenIdArticleReadLike.toString());
        //
        if (this.subscribers.size() > 0) {
            this.query();// Recursively call.
            GlobalVariables.kjsonQueryCounter++;
            if (GlobalVariables.kjsonQueryCounter >= GlobalConsts.KJSON_API_QPM) {
                try {
                    Thread.sleep(30000);
                    GlobalVariables.kjsonQueryCounter = 0;
                } catch (InterruptedException e) {
                    LOG.error(e.toString());
                }
            }
        } else {
            //
        }
    }
}

From source file:eu.cloudwave.wp5.monitoring.rest.FeedbackHandlerMonitoringClient.java

/**
 * Sends monitoring data (i.e. the call trace) and its attached metrics to the Feedback Handler.
 * // w w  w  .  j ava  2 s.c o m
 * @param executions
 *          the {@link RunningProcedureExecution}'s (i.e. the call trace)
 * @return <code>true</code> if the data has been successfully sent to the Feedback Handler, <code>false</code>
 *         otherwise
 */
public boolean postData(final RunningProcedureExecution rootProcedureExecution) {
    final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add(Headers.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    headers.add(Headers.ACCESS_TOKEN, accessToken());
    headers.add(Headers.APPLICATION_ID, applicationId());
    final HttpEntity<MetricContainingProcedureExecutionDto> httpEntity = new HttpEntity<MetricContainingProcedureExecutionDto>(
            rootProcedureExecution, headers);
    final ResponseEntity<Boolean> result = new RestTemplate().exchange(url(), HttpMethod.POST, httpEntity,
            Boolean.class);
    return result.getBody();
}

From source file:com.pepaproch.gtswsdlclient.TestBase.java

protected RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> list = new ArrayList<>();
    list.add(new MappingJackson2HttpMessageConverter());
    restTemplate.setMessageConverters(list);
    return restTemplate;

}

From source file:com.github.shirashiki.ideastore.cloud.test.integration.AbstractApiTest.java

/**
 * GreetingController implements the path greeting, which should return an echo message.
 * This is using Jackson (https://github.com/FasterXML/jackson) to convert JSON
 * to object//w  w  w.j  a  v  a2 s  . c om
 * @throws Exception
 */
@Test
public void testGreetingEcho() throws Exception {
    RestTemplate restTemplate = new RestTemplate();

    // Checks if returns the default greeting
    Greeting emptyGreeting = restTemplate.getForObject(TEST_URL + "/greeting", Greeting.class);
    assertEquals(1, emptyGreeting.getId());
    assertEquals("Hello, World!", emptyGreeting.getContent());

    // Checks if generates the greeting with parameters 
    String echoStr = "Montreal Canadiens";
    Greeting myGreeting = restTemplate.getForObject(TEST_URL + "/greeting?name=" + echoStr, Greeting.class);
    assertEquals(1, myGreeting.getId());
    assertEquals("Hello, " + echoStr + "!", myGreeting.getContent());
}

From source file:uy.edu.ort.fachada.FachadaOperaciones.java

public static void listarBarcos() {
    String url = ManejoPropiedades.obtenerInstancia().obtenerPropiedad("restService") + "restbarco/barcos.htm";

    RestTemplate restTemplate1 = new RestTemplate();
    restTemplate1.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate1.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

    Barco[] barcos = restTemplate1.getForObject(url, Barco[].class);
    System.out.println(//from w ww .jav  a  2 s . c  om
            "\tId \t\tCodigo \t\tNombre \t\tBandera \t\tCapacidad(kgs) \t\tAo \t\tCantidadTripulantes");
    for (Barco barco : barcos) {
        System.out.println("\t" + barco.getId() + "\t\t" + barco.getCodigo() + " \t\t" + barco.getNombre()
                + " \t\t" + barco.getBandera() + " \t\t" + barco.getCapacidadTransporte() + " \t\t"
                + String.valueOf(barco.getAnioFabricacion()) + " \t\t" + barco.getCantidadTripulantes());
    }
}

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

/**
 * {@inheritDoc} <br/>//from  w ww.jav  a2s  .  co m
 * <br/>
 * Delegates an incoming outputs (result document) request to the WPS proxy
 * and creates an instance of {@link ResultDocument}
 * 
 * @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 ResultDocument}
 */
@Override
public <T> ResultDocument forwardRequestToWpsProxy(HttpServletRequest request, T requestBody,
        ParameterValueStore parameterValueStore) {
    initializeRequestSpecificParameters(parameterValueStore);

    String outputs_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate outputsTemplate = new RestTemplate();

    // fetch the result document from WPS proxy and
    // deserialize it into TAMIS ResultDocument
    ResultDocument resultDocument = outputsTemplate.getForObject(outputs_url_wpsProxy, ResultDocument.class);

    return resultDocument;
}

From source file:web.rufer.swisscom.sms.api.client.SwisscomSmsSender.java

/**
 * Extended Constructor/*from   www.  j a va  2s  .  c  o m*/
 *
 * @param apiKey the API-key generated by http://developer.swisscom.com
 * @param senderNumber the number of the sender (i.e. +41791234567)
 * @param senderName [ONLY IN PARTNER MODE] Name of the sender, which should be displayed on the receivers phone
 * @param clientCorrelator An id that can be found in the logs of Swisscom
 */
public SwisscomSmsSender(String apiKey, String senderNumber, String senderName, String clientCorrelator) {
    validationChain.executeValidation(senderNumber);
    this.apiKey = apiKey;
    this.senderNumber = senderNumber;
    this.senderName = senderName;
    this.clientCorrelator = clientCorrelator;
    this.restTemplate = new RestTemplate();
}