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

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

Introduction

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

Prototype

public List<HttpMessageConverter<?>> getMessageConverters() 

Source Link

Document

Return the list of message body converters.

Usage

From source file:com.nbempire.dentalnavarra.dao.impl.RememberDaoImplSpring.java

@Override
public RemembersDTO findRemembers(String patientId) {
    RestTemplate restTemplate = new RestTemplate();

    // Add a JSON converter (use GSON instead of Jackson because is a smaller library)
    restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());

    String urlString = MainKeys.API_HOST + "/patients/" + patientId + "/notifications";
    Log.d(TAG, "Getting resource: " + urlString);

    RemembersDTO response = null;//w  w w .  j  ava  2 s .c  o  m
    URI url = null;
    try {
        url = new URI(urlString);

        response = restTemplate.getForObject(url, RemembersDTO.class);
    } catch (URISyntaxException e) {
        Log.e(TAG, "There was an error creating the URI: " + urlString);
    } catch (RestClientException restClientException) {
        Log.e(TAG, "There was an error getting remembers from URL: " + url);
        Log.e(TAG, restClientException.getMessage());
    }

    return response != null ? response : new RemembersDTO();
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchWeatherList.java

/**
 * Method, where all weatherList are read from server.
 * All heavy lifting is made here./*w w  w.  j  a  v  a 2s . c o  m*/
 *
 * @param params parameters - omitted here
 * @return list of fetched weather
 */
@Override
protected List<Weather> doInBackground(Void... params) {

    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_WEATHER + "/" + researchGroupId;

    setState(RUNNING, R.string.working_ws_weather);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<Object> entity = new HttpEntity<Object>(requestHeaders);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    try {
        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<WeatherList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                WeatherList.class);
        WeatherList body = response.getBody();

        if (body != null) {
            return body.getWeatherList();
        }

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return Collections.emptyList();
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.RemoveReservation.java

/**
 * Method, where reservation information is pushed to server in order to remove it.
 * All heavy lifting is made here./* w ww. j av a  2  s  . c  o  m*/
 *
 * @param params only one Reservation object is accepted
 * @return true if reservation is removed
 */
@Override
protected Boolean doInBackground(Reservation... params) {

    Reservation data = params[0];

    //nothing to remove
    if (data == null)
        return false;

    try {

        setState(RUNNING, R.string.working_ws_remove);

        SharedPreferences credentials = getCredentials();
        String username = credentials.getString("username", null);
        String password = credentials.getString("password", null);
        String url = credentials.getString("url", null) + Values.SERVICE_RESERVATION + data.getReservationId();

        HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAuthorization(authHeader);
        HttpEntity<Reservation> entity = new HttpEntity<Reservation>(requestHeaders);

        SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
        // Create a new RestTemplate instance
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

        Log.d(TAG, url + "\n" + entity);
        restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);
        return true;
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return false;
}

From source file:com.develcom.reafolder.ClienteBajaArchivo.java

public void buscarArchivo() throws FileNotFoundException, IOException {

    CodDecodArchivos cda = new CodDecodArchivos();
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    Bufer bufer = new Bufer();
    byte[] buffer = null;
    ResponseEntity<byte[]> response;

    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    headers.setAccept(Arrays.asList(MediaType.ALL));
    HttpEntity<String> entity = new HttpEntity<>(headers);

    response = restTemplate.exchange(//from ww w.  j av a  2s .com
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();
        FileOutputStream output = new FileOutputStream(new File("c:/documentos/archivo.cod"));
        IOUtils.write(response.getBody(), output);
        cda.decodificar("c:/documentos/archivo.cod", "c:/documentos/archivo.pdf");
    }

}

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

@Override
protected Void doInBackground(Void... params) {
    RestTemplate template = new RestTemplate();
    HttpHeaders httpHeaders = CryptoUtils.createHeaders(username, password);
    template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    try {//  w  w  w  . jav a 2  s.co  m
        ResponseEntity<UserDTO> response = template.exchange(
                SingleInstance.getServerUrl() + "users/" + username, HttpMethod.GET,
                new HttpEntity<>(httpHeaders), UserDTO.class);
        UserDTO user = response.getBody();
        UserData userData = new UserData(user);
        for (String sensor : user.getSensors()) {
            try {
                ResponseEntity<SensorDTO> responseSensor = template.exchange(
                        SingleInstance.getServerUrl() + "sensors/" + sensor, HttpMethod.GET,
                        new HttpEntity<>(httpHeaders), SensorDTO.class);
                SensorDTO SensorDTO = responseSensor.getBody();
                userData.addSensor(new SensorData(SensorDTO));
            } catch (RestClientException e) {
                e.printStackTrace();
            }
        }
        publishProgress(userData);
    } catch (RestClientException e) {
        e.printStackTrace();
        publishProgress(null);
    }
    return null;
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateScenario.java

/**
 * Method, where scenario information is pushed to server in order to new scenario.
 * All heavy lifting is made here./*from  w w w .  jav  a2  s.c  om*/
 *
 * @param scenarios only one scenario is accepted - scenario to be uploaded
 * @return scenario stored
 */
@Override
protected Scenario doInBackground(Scenario... scenarios) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_SCENARIOS;

    setState(RUNNING, R.string.working_ws_create_scenario);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    //so files wont buffer in memory
    factory.setBufferRequestBody(false);
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Scenario scenario = scenarios[0];

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(scenario.getFilePath());

        //due to multipart file, MultiValueMap is the simplest approach for performing the post request
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("scenarioName", scenario.getScenarioName());
        form.add("researchGroupId", scenario.getResearchGroupId());
        form.add("description", scenario.getDescription());
        form.add("mimeType", scenario.getMimeType());
        form.add("private", Boolean.toString(scenario.isPrivate()));
        form.add("file", toBeUploadedFile);

        HttpEntity<Object> entity = new HttpEntity<Object>(form, requestHeaders);
        // Make the network request
        ResponseEntity<Scenario> response = restTemplate.postForEntity(url, entity, Scenario.class);
        return response.getBody();
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.springframework.cloud.dataflow.rest.client.DataflowTemplateTests.java

@Test
public void testPrepareRestTemplateWithRestTemplateThatHasNoMessageConverters() {
    final RestTemplate providedRestTemplate = new RestTemplate();
    providedRestTemplate.getMessageConverters().clear();

    try {//from ww  w. j a v  a2 s . c  om
        DataFlowTemplate.prepareRestTemplate(providedRestTemplate);
    } catch (IllegalArgumentException e) {
        assertEquals("'messageConverters' must not be empty", e.getMessage());
        return;
    }

    fail("Expected an IllegalArgumentException to be thrown.");
}

From source file:com.develcom.cliente.Cliente.java

public void buscarArchivo() throws FileNotFoundException, IOException {

    CodDecodArchivos cda = new CodDecodArchivos();
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    //        Bufer bufer = new Bufer();
    byte[] buffer = null;
    ResponseEntity<byte[]> response;

    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    headers.setAccept(Arrays.asList(MediaType.ALL));
    HttpEntity<String> entity = new HttpEntity<>(headers);

    response = restTemplate.exchange(//from   w  w w. ja v a2  s  .  c o m
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();
        FileOutputStream output = new FileOutputStream(new File("c:/documentos/archivo.cod"));
        IOUtils.write(response.getBody(), output);
        cda.decodificar("c:/documentos/archivo.cod", "c:/documentos/archivo.pdf");
    }

}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchExperiments.java

/**
 * Method, where all experiments are read from server.
 * All heavy lifting is made here./* ww w.jav a 2s.c  om*/
 *
 * @param params not used (omitted) here
 * @return list of fetched experiments
 */
@Override
protected List<Experiment> doInBackground(Void... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_EXPERIMENTS;

    setState(RUNNING, R.string.working_ws_experiments);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<Object> entity = new HttpEntity<Object>(requestHeaders);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    try {

        //obtain all public records if qualifier is all
        if (Values.SERVICE_QUALIFIER_ALL.equals(qualifier)) {
            String countUrl = url + "count";
            ResponseEntity<RecordCount> count = restTemplate.exchange(countUrl, HttpMethod.GET, entity,
                    RecordCount.class);

            url += "public/" + count.getBody().getPublicRecords();
        } else
            url += qualifier;

        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<ExperimentList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ExperimentList.class);
        ExperimentList body = response.getBody();

        if (body != null) {
            return body.getExperiments();
        }

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return Collections.emptyList();
}

From source file:org.openinfinity.sso.common.ss.sp.filters.PreAuthenticatedTokenAuthenticationFilter.java

private org.springframework.security.core.Authentication springAuthenticationBy(final String ssoID) {

    LOG.debug("Building the authentication context by token");

    org.springframework.security.core.Authentication springAuthentication = cache.authenticationBy(ssoID);
    if (springAuthentication != null) {
        LOG.debug("Auth {} found in cache by token {}", springAuthentication, ssoID);
        return springAuthentication;
    }/*w  w w  . ja  v  a2  s .  c o m*/

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new SpringAuthenticationMessageConverter());
    LOG.debug("No luck in cache, calling IDP by REST");
    springAuthentication = restTemplate.getForObject(attributeURL,
            org.springframework.security.core.Authentication.class, ssoID);
    LOG.debug("Got authentication {} from IDP via REST", springAuthentication);

    cache.put(ssoID, springAuthentication);
    return springAuthentication;
}