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

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

Introduction

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

Prototype

@Override
    public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
            ParameterizedTypeReference<T> responseType) throws RestClientException 

Source Link

Usage

From source file:com.catalog.core.Api.java

@Override
public Attendance editAttendance(int attendanceId, boolean motivated) {
    setStartTime();//from   w  w  w  . j  av  a2 s  . c o  m
    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();

    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());

    String url = "http://" + IP + EXTENSION + "/teacher/editAttendanceT/" + attendanceId + ".json";

    ResponseEntity<AttendanceSingleVM> responseEntity = null;
    AttendanceSingleVM response = null;

    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, AttendanceSingleVM.class);
        response = responseEntity.getBody();
    } catch (RestClientException e) {
        return null;
    }

    Log.d("TAAAG", response.toString());
    getElapsedTime("editAttendance - ");
    return response.getAttendance();
}

From source file:com.catalog.core.Api.java

@Override
public StudentMark editStudentMark(int markId, int newMark, long date) {
    setStartTime();/*ww  w.j a va 2 s .  c o  m*/

    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();

    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());

    String url = "http://" + IP + EXTENSION + "/teacher/editStudentMarkT/" + markId + "," + newMark + "," + date
            + ".json";

    ResponseEntity<StudentMarkVM> responseEntity = null;
    StudentMarkVM response = null;

    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, StudentMarkVM.class);
        response = responseEntity.getBody();
    } catch (RestClientException e) {
        return null;
    }

    Log.d("TAAAG", response.toString());
    getElapsedTime("editStudentMark - ");
    return response.getStudentMark();
}

From source file:com.catalog.core.Api.java

@Override
public Attendance addAttendance(int studentId, int stfcId, long date) {
    setStartTime();/*from   w  w  w . ja v  a  2  s .  co m*/

    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();

    // Add the Jackson message converter
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());

    String url = "http://" + IP + EXTENSION + "/teacher/formAttendanceT/" + studentId + "," + stfcId + ","
            + date + ".json";

    ResponseEntity<AttendanceSingleVM> responseEntity = null;
    AttendanceSingleVM response = null;
    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, AttendanceSingleVM.class);
        response = responseEntity.getBody();
    } catch (RestClientException e) {
        return null;
    }

    Log.d("TAAAG", response.toString());

    getElapsedTime("addAttendance - ");
    return response.getAttendance();
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping("/order")
public @ResponseBody String orderProductNowById(@RequestParam("cartId") String cartId,
        @RequestParam("prodId") String productId) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {//from   w  w  w. j  a v a  2s  . com
        jsonObj.put("cartId", Integer.parseInt(cartId));
        jsonObj.put("productId", Integer.parseInt(productId));
        jsonObj.put("attributeId", 1);
        jsonObj.put("quantity", 1);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("param jsonObj=>" + jsonObj.toString());

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.QUOTE_SERVER_URI + URIConstants.ADD_PRODUCT_TO_CART)
            .queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    return returnString.getBody();
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext fetchTokenFromCode(final TokenRequest request) {
    String clientBasicAuth = getClientBasicAuthHeader(request);

    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }/*  w w w  .j  ava  2 s  .c o  m*/
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.GRANT_TYPE, "authorization_code");
    form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString());
    String responseType = "token";
    if (request.wantsIdToken()) {
        responseType += " id_token";
    }
    form.add(OAuth2Utils.RESPONSE_TYPE, responseType);
    form.add("code", request.getAuthorizationCode());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

From source file:org.projecthdata.weight.service.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    Connection<HData> connection = connectionRepository.getPrimaryConnection(HData.class);

    this.prefs.edit().putString(Constants.PREF_SYNC_STATE, SyncState.WORKING.toString()).commit();
    //get all readings that are not synced
    try {/*w w  w  .j a  v a2 s . c o m*/
        Dao<WeightReading, Integer> dao = ormManager.getDatabaseHelper().getWeightDao();
        //TODO: query the database instead of iterating over the whole table

        String url = this.prefs.getString(Constants.PREF_EHR_URL, "");
        Uri uri = Uri.parse(url);
        uri = uri.buildUpon().appendPath("vitalsigns").appendPath("bodyweight").build();
        RestTemplate template = connection.getApi().getRootOperations().getRestTemplate();

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

        for (WeightReading reading : dao) {

            if (!reading.isSynched()) {
                Result result = new Result();
                //date and time
                result.setResultDateTime(new DateTime(reading.getDateTime().getTime()).toString(dateFormatter));
                //narrative
                result.setNarrative(NARRATIVE);
                //result id
                result.setResultId(UUID.randomUUID().toString());
                //result type code
                result.getResultType().setCode(CODE);
                //result type code system
                result.getResultType().setCodeSystem(CODE_SYSTEM);
                //status code
                result.setResultStatusCode(RESULT_STATUS_CODE);
                //value
                result.setResultValue(reading.getResultValue().toString());
                //value unit
                result.setResultValueUnit(UNITS);

                try {

                    HttpEntity<Result> requestEntity = new HttpEntity<Result>(result, requestHeaders);
                    template.exchange(uri.toString(), HttpMethod.POST, requestEntity, String.class);
                } catch (RestClientException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                reading.setSynched(true);
                dao.update(reading);
            }
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    this.prefs.edit().putString(Constants.PREF_SYNC_STATE, SyncState.READY.toString()).commit();

}

From source file:com.playhaven.android.req.PlayHavenRequest.java

public void send(final Context context) {
    final StringHttpMessageConverter stringHttpMessageConverter;

    try {//from   w w w  . ja v a  2  s . c  om
        /**
        * Charset.availableCharsets() called by StringHttpMessageConverter constructor is not multi-thread safe.
        * Calling it on the main thread to avoid a possible crash.
        * More details here: https://code.google.com/p/android/issues/detail?id=42769
        */
        stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName(UTF8));
    } catch (Exception e) {
        handleResponse(new PlayHavenException(e.getMessage()));
        return;
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                /**
                 * First, check if we are mocking the URL
                 */
                String mockJsonResponse = getMockJsonResponse();
                if (mockJsonResponse != null) {
                    /**
                     * Mock the response
                     */
                    PlayHaven.v("Mock Response: %s", mockJsonResponse);
                    handleResponse(mockJsonResponse);
                    return;
                }

                /**
                 * Not mocking the response. Do an actual server call.
                 */
                String url = getUrl(context);
                PlayHaven.v("Request(%s) %s: %s", PlayHavenRequest.this.getClass().getSimpleName(), restMethod,
                        url);

                // Add the gzip Accept-Encoding header
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setAcceptEncoding(ContentCodingType.GZIP);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

                // Create our REST handler
                RestTemplate rest = new RestTemplate();
                rest.setErrorHandler(new ServerErrorHandler());

                // Capture the JSON for signature verification
                rest.getMessageConverters().add(stringHttpMessageConverter);

                ResponseEntity<String> entity = null;

                switch (restMethod) {
                case POST:
                    SharedPreferences pref = PlayHaven.getPreferences(context);
                    String apiServer = getString(pref, APIServer)
                            + context.getResources().getString(getApiPath(context));
                    url = url.replace(apiServer, "");
                    if (url.startsWith("?") && url.length() > 1)
                        url = url.substring(1);

                    requestHeaders.setContentType(new MediaType("application", "x-www-form-urlencoded"));
                    entity = rest.exchange(apiServer, restMethod, new HttpEntity<>(url, requestHeaders),
                            String.class);
                    break;
                default:
                    entity = rest.exchange(url, restMethod, new HttpEntity<>(requestHeaders), String.class);
                    break;
                }

                String json = entity.getBody();

                List<String> digests = entity.getHeaders().get("X-PH-DIGEST");
                String digest = (digests == null || digests.size() == 0) ? null : digests.get(0);

                validateSignatures(context, digest, json);

                HttpStatus statusCode = entity.getStatusCode();
                PlayHaven.v("Response (%s): %s", statusCode, json);

                serverSuccess(context);
                handleResponse(json);
            } catch (PlayHavenException e) {
                handleResponse(e);
            } catch (IOException e2) {
                handleResponse(new PlayHavenException(e2));
            } catch (Exception e3) {
                handleResponse(new PlayHavenException(e3.getMessage()));
            }
        }
    }).start();
}

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

/**
 * This method is invoked after Taxamo has successfully verified tax location evidence and
 * created a transaction.//from   ww w  .j a  va 2 s.  c om
 *
 * Two things happen then:
 * - first, the express checkout token is used to capture payment in PayPal
 * - next, transaction is confirmed with Taxamo
 *
 * After that, confirmation page is displayed to the customer.
 *
 * @param payerId
 * @param token
 * @param transactionKey
 * @param model
 * @return
 */
@RequestMapping(value = "/confirm")
public String confirm(@RequestParam("PayerID") String payerId, @RequestParam("token") String token,
        @RequestParam("taxamo_transaction_key") String transactionKey, 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", "DoExpressCheckoutPayment");
    map.add("PAYERID", payerId);
    map.add("TOKEN", token);

    GetTransactionOut transaction; //more transaction details should be verified in real-life implementation
    try {
        transaction = taxamoApi.getTransaction(transactionKey);
    } catch (ApiException e) {
        e.printStackTrace();
        model.addAttribute("error", "ERROR result: " + e.getMessage());
        return "error";
    }

    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");
    map.add("PAYMENTREQUEST_0_AMT", transaction.getTransaction().getTotalAmount().toString());
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");

    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 {
        try {
            ConfirmTransactionOut transactionOut = taxamoApi.confirmTransaction(transactionKey,
                    new ConfirmTransactionIn());
            model.addAttribute("status", transactionOut.getTransaction().getStatus());
        } catch (ApiException ae) {
            ae.printStackTrace();
            model.addAttribute("error", "ERROR result: " + ae.getMessage());
            return "error";
        }
        model.addAttribute("taxamo_transaction_key", transactionKey);

        return "redirect:/success-checkout";
    }
}

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//  w ww  . j av a 2  s .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:org.devefx.httpmapper.binding.MapperMethod.java

@SuppressWarnings("unchecked")
public Object execute(RestTemplate restTemplate, Object[] args) throws Exception {
    Object result = null;/*  w w  w . j  av a2s  . c om*/

    do {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(command.getContentType()));

        Map<String, Object> paramMap = null;
        Object param = method.convertArgsToCommandParam(args);
        if (param instanceof Map) {
            paramMap = (Map<String, Object>) param;
            body.setAll(paramMap);
        }

        URI uri = expandURI(command.getUrl(), args);

        RequestEntity requestEntity = new RequestEntity(body, headers, command.getHttpMethod(), uri,
                method.getReturnType());

        mappedHandler.onRequest(requestEntity);

        // FIXME: application/x-www-form-urlencoded
        if (headers.getContentType().includes(MediaType.APPLICATION_FORM_URLENCODED)) {
            if (paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    Object value = entry.getValue();
                    if (value != null && !ReflectUtils.isUserType(value)) {
                        entry.setValue(String.valueOf(value));
                    }
                }
                body.setAll(paramMap);
            } else if (param != null && ReflectUtils.isUserType(param)) {
                body.setAll(mapper.<Map<String, Object>>convertValue(param, mapType));
            }
        }

        if (requestEntity.getMethod() == HttpMethod.GET) {
            uri = appendUrlParams(requestEntity.getUrl(), body);
            requestEntity.setUrl(uri);
        }

        if (logger.isInfoEnabled()) {
            String preStr = command.getName() + " ====> ";
            logger.info(preStr + "Request: " + requestEntity.getUrl());
            logger.info(preStr + "Parameters: " + requestEntity.getBody());
            logger.info(preStr + "Headers: " + requestEntity.getHeaders());
        }

        ResponseEntity<JsonNode> responseEntity = restTemplate.exchange(requestEntity.getUrl(),
                requestEntity.getMethod(),
                new HttpEntity<>(requestEntity.getBody(), requestEntity.getHeaders()), JsonNode.class);

        if (logger.isInfoEnabled()) {
            StringBuffer buf = new StringBuffer();
            buf.append(command.getName() + " ====> ");
            buf.append("Response: [status=").append(responseEntity.getStatusCode()).append("] ");
            if (responseEntity.hasBody()) {
                buf.append(responseEntity.getBody());
            }
            logger.info(buf.toString());
        }

        if (responseEntity != null) {
            org.devefx.httpmapper.http.ResponseEntity entity = new org.devefx.httpmapper.http.ResponseEntity(
                    responseEntity.getBody(), responseEntity.getHeaders(), responseEntity.getStatusCode());

            mappedHandler.onResponse(requestEntity, entity);

            if (entity.hasBody()) {
                Object responseBody = entity.getBody();
                if (method.getRawType().isInstance(responseBody)) {
                    result = responseBody;
                    break;
                }

                JavaType valueType = mapper.getTypeFactory().constructType(method.getReturnType());
                if (responseBody instanceof String) {
                    result = mapper.readValue((String) responseBody, valueType);
                } else {
                    result = mapper.convertValue(responseBody, valueType);
                }
            }
        }

    } while (false);

    if (result == null && method.returnsPrimitive() && !method.returnsVoid()) {
        throw new BindingException("Mapper method '" + command.getUrl()
                + " attempted to return null from a method with a primitive return type ("
                + method.getReturnType() + ").");
    }
    return result;
}