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 MasterClassVM getMasterClass(int id) {
    setStartTime();/*ww  w  . j a v  a  2  s .  c o  m*/

    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();
    String url = "http://" + IP + EXTENSION + "/teacher/masterClassT";
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

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

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

    getElapsedTime("getMasterClass - ");

    return masterClass;
}

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

@Override
public boolean changePassword(String newPassword) {

    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();

    String url = "http://" + IP + EXTENSION + "/teacher/changePasswordT/" + newPassword + ".json";
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

    ResponseEntity<UserVM> responseEntity;
    UserVM user = null;//from w  w  w.j a  va 2  s.c  o m

    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, UserVM.class);
        user = responseEntity.getBody();

    } catch (RestClientException e) {
        return false;
    }

    Log.d("TAAAG", user.toString());
    getElapsedTime("changePassword - ");
    if (user.getStatus().equals("OK"))
        return true;
    else
        return false;
}

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

@Override
public StudentsVM getStudentsForClass(int id) {
    setStartTime();// w  ww . j  a  v a2s  .  c o m

    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();
    String url = "http://" + IP + EXTENSION + "/teacher/classStudentsT/" + id + ".json";
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

    ResponseEntity<StudentsVM> responseEntity = null;
    StudentsVM students = null;

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

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

    getElapsedTime("getStudentsForClass - ");

    return students;
}

From source file:cz.muni.fi.mushroomhunter.restclient.MushroomDeleteSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    int selectedRow = restClient.getTblMushroom().getSelectedRow();
    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override/* w  w  w  . java 2s. c  o  m*/
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (HttpMethod.DELETE == httpMethod) {
                return new HttpEntityEnclosingDeleteRequest(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    });

    restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/mushroom/" + RestClient.getMushroomIDs().get(selectedRow),
            HttpMethod.DELETE, request, MushroomDto.class);

    RestClient.getMushroomIDs().remove(selectedRow);
    return selectedRow;
}

From source file:cz.muni.fi.mushroomhunter.restclient.LocationDeleteSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    int selectedRow = restClient.getTblLocation().getSelectedRow();
    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
        @Override//from  ww w.j a  v a2s.c o m
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (HttpMethod.DELETE == httpMethod) {
                return new HttpEntityEnclosingDeleteRequest(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    });

    restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/location/" + RestClient.getLocationIDs().get(selectedRow),
            HttpMethod.DELETE, request, LocationDto.class);

    RestClient.getLocationIDs().remove(selectedRow);
    return selectedRow;
}

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

@Override
public SemesterVM getSemestersInfo() {
    setStartTime();//from  www.java2 s  .  c o m
    HttpEntity<?> requestEntity = getAuthHttpEntity();

    RestTemplate restTemplate = new RestTemplate();

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

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

    ResponseEntity<SemesterVM> responseEntity;
    SemesterVM semester = null;
    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, SemesterVM.class);
        semester = responseEntity.getBody();

    } catch (Exception e) {
        return null;
    }

    getElapsedTime("getSemester - ");
    return semester;
}

From source file:org.obiba.mica.core.service.MailService.java

private synchronized void sendEmail(String subject, String templateName, Map<String, String> context,
        String recipient) {//w  w w.j  av a2 s  . c o m
    try {
        RestTemplate template = newRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(APPLICATION_AUTH_HEADER, getApplicationAuth());
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        StringBuilder form = new StringBuilder(Strings.isNullOrEmpty(recipient) ? "" : recipient + "&");
        form.append("subject=").append(encode(subject, "UTF-8")).append("&template=")
                .append(encode(templateName, "UTF-8"));
        context.forEach((k, v) -> {
            try {
                form.append("&").append(k).append("=").append(encode(v, "UTF-8"));
            } catch (UnsupportedEncodingException ignored) {
            }
        });
        HttpEntity<String> entity = new HttpEntity<>(form.toString(), headers);

        ResponseEntity<String> response = template.exchange(getNotificationsUrl(), HttpMethod.POST, entity,
                String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("Email sent via Agate");
        } else {
            log.error("Sending email via Agate failed with status: {}", response.getStatusCode());
        }
    } catch (Exception e) {
        log.error("Agate connection failure: {}", e.getMessage());
    }
}

From source file:org.starfishrespect.myconsumption.android.tasks.GCMRegister.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>//from w  w  w  .j a  va  2s . com
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
public void registerInBackground(final Context context) {
    AsyncTask<Void, List, String> task = new AsyncTask<Void, List, String>() {
        @Override
        protected String doInBackground(Void... params) {
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<String> responseEnt;
            template.getMessageConverters().add(new FormHttpMessageConverter());
            template.getMessageConverters().add(new StringHttpMessageConverter());
            String msg = "";

            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                String regid = gcm.register(Config.SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // Send the registration ID to the server
                String url = SingleInstance.getServerUrl() + "notifs/"
                        + SingleInstance.getUserController().getUser().getName() + "/id/" + regid;

                responseEnt = template.exchange(url, HttpMethod.POST, new HttpEntity<>(httpHeaders),
                        String.class);
                SimpleResponseDTO response = new ObjectMapper().readValue(responseEnt.getBody(),
                        SimpleResponseDTO.class);

                if (response.getStatus() != SimpleResponseDTO.STATUS_SUCCESS) {
                    msg = "Error: " + response.getStatus() + " Cannot post register id on server side.";
                }

                // Persist the registration ID - no need to register again.
                PrefUtils.setRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error:" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            LOGI(TAG, msg);
        }
    };

    task.execute();
}

From source file:com.marklogic.mgmt.admin.AdminManager.java

/**
 * Set whether SSL FIPS is enabled on the cluster or not by running against /v1/eval on the given appServicesPort.
 */// w  w w  . jav  a2  s .  c  o  m
public void setSslFipsEnabled(final boolean enabled, final int appServicesPort) {
    final String xquery = "import module namespace admin = 'http://marklogic.com/xdmp/admin' at '/MarkLogic/admin.xqy'; "
            + "admin:save-configuration(admin:cluster-set-ssl-fips-enabled(admin:get-configuration(), "
            + enabled + "()))";

    invokeActionRequiringRestart(new ActionRequiringRestart() {
        @Override
        public boolean execute() {
            RestTemplate rt = RestTemplateUtil.newRestTemplate(adminConfig.getHost(), appServicesPort,
                    adminConfig.getUsername(), adminConfig.getPassword());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("xquery", xquery);
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(
                    map, headers);
            String url = format("http://%s:%d/v1/eval", adminConfig.getHost(), appServicesPort);
            if (logger.isInfoEnabled()) {
                logger.info("Setting SSL FIPS enabled: " + enabled);
            }
            rt.exchange(url, HttpMethod.POST, entity, String.class);
            if (logger.isInfoEnabled()) {
                logger.info("Finished setting SSL FIPS enabled: " + enabled);
            }
            return true;
        }
    });
}