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:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchElectrodeTypes.java

/**
 * Method, where all electrodeTypes are read from server.
 * All heavy lifting is made here./*from   w  w  w .  j a  va  2  s .  c om*/
 *
 * @param params omitted here
 * @return list of fetched electrodeTypes
 */
@Override
protected List<ElectrodeType> 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_ELECTRODE_TYPES;

    setState(RUNNING, R.string.working_ws_electrode_type);
    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<ElectrodeTypeList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ElectrodeTypeList.class);
        ElectrodeTypeList body = response.getBody();

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

    } 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.FetchPharmaceuticals.java

/**
 * Method, where all pharmaceuticals are read from server.
 * All heavy lifting is made here./*from  www. j a  va2s .c  om*/
 *
 * @param params omitted here
 * @return list of fetched pharmaceuticals
 */
@Override
protected List<Pharmaceutical> 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_PHARMACEUTICAL;

    setState(RUNNING, R.string.working_ws_pharmaceutical);
    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<PharmaceuticalList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                PharmaceuticalList.class);
        PharmaceuticalList body = response.getBody();

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

    } 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.FetchElectrodeSystems.java

/**
 * Method, where all electrodeSystems are read from server.
 * All heavy lifting is made here./*w w w .  jav a  2 s  . c o  m*/
 *
 * @param params omitted here
 * @return list of fetched electrodeSystems
 */
@Override
protected List<ElectrodeSystem> 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_ELECTRODE_SYSTEMS;

    setState(RUNNING, R.string.working_ws_electrode_system);
    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<ElectrodeSystemList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ElectrodeSystemList.class);
        ElectrodeSystemList body = response.getBody();

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

    } 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.FetchElectrodeLocations.java

/**
 * Method, where all electrodeLocations are read from server.
 * All heavy lifting is made here./*from  w ww .  j av a2  s.  co  m*/
 *
 * @param params omitted here
 * @return list of fetched electrodeLocations
 */
@Override
protected List<ElectrodeLocation> 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_ELECTRODE_LOCATIONS;

    setState(RUNNING, R.string.working_ws_electrode_location);
    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<ElectrodeLocationList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ElectrodeLocationList.class);
        ElectrodeLocationList body = response.getBody();

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

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

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(
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();//from   w ww  . java 2 s  .  c  o  m
        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:io.fabric8.che.starter.client.CheRestClient.java

public Workspace getWorkspaceByKey(String cheServerURL, String workspaceId) {
    String url = generateURL(cheServerURL, CheRestEndpoints.GET_WORKSPACE_BY_ID, workspaceId);

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    return template.exchange(url, HttpMethod.GET, entity, Workspace.class).getBody();
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>/*from   w w w. ja  v a  2s .com*/
 * RHEV Manager  API   .
 * </pre>
 * @param api RHEV Manager API (/api, /api/vms )
 * @param body xml contents
 * @param clazz ? Target Object Class
 * @return
 * @throws RestClientException
 * @throws Exception
 */
public synchronized <T> T submit(String api, HttpMethod method, Object body, String rootElementName,
        Class<T> clazz) throws RestClientException, Exception {
    Assert.isTrue(StringUtils.isNotEmpty(api), "api must not be null");
    Assert.notNull(clazz, "clazz must not be null.");

    // Multi RHEV Manager        ? ?? HostnameVerifier ??,
    // ??    ? ?.(java.io.IOException: HTTPS hostname wrong:  should be <{host}>)
    //init();

    try {
        RestTemplate rt = new RestTemplate();

        ResponseEntity<?> response = rt.exchange(new URI(getUrl(api)), method,
                setHTTPEntity(body, rootElementName), clazz);

        logger.debug("[Request URL] : {}", getUrl(api));
        logger.debug("[Response] : {}", response);

        if (response.getStatusCode().equals(HttpStatus.BAD_REQUEST)
                || response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || response.getStatusCode().equals(HttpStatus.PAYMENT_REQUIRED)
                || response.getStatusCode().equals(HttpStatus.FORBIDDEN)
                || response.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED)
                || response.getStatusCode().equals(HttpStatus.NOT_ACCEPTABLE)
                || response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)
                || response.getStatusCode().equals(HttpStatus.NOT_IMPLEMENTED)
                || response.getStatusCode().equals(HttpStatus.BAD_GATEWAY)
                || response.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE)
                || response.getStatusCode().equals(HttpStatus.GATEWAY_TIMEOUT)) {
            throw new Exception(response.getStatusCode().value() + " " + response.getStatusCode().toString());
        }

        return clazz.cast(response.getBody());
    } catch (RestClientException e) {
        logger.error("RestClientException has occurred.", e);
        throw e;
    } catch (Exception e) {
        logger.error("Unhandled Exception has occurred.", e);
        throw e;
    }
}

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(
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();/*from w  w  w.  ja va  2 s .c om*/
        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.FetchReservationsToDate.java

/**
 * Method, where all reservations to specified date are read from server.
 * All heavy lifting is made here./*from w  w  w. j a  va  2  s.  c  om*/
 *
 * @param params only one TimeContainer parameter is allowed here - specifies day, month and year
 * @return list of fetched reservations
 */
@Override
protected List<Reservation> doInBackground(TimeContainer... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_RESERVATION;

    if (params.length == 1) {
        TimeContainer time = params[0];
        url = url + time.getDay() + "-" + time.getMonth() + "-" + time.getYear();
    } else {
        Log.e(TAG, "Invalid params count! There must be one TimeContainer instance");
        setState(ERROR, "Invalid params count! There must be one TimeContainer instance");
        return Collections.emptyList();
    }

    setState(RUNNING, R.string.working_ws_msg);

    // Populate the HTTP Basic Authentication header with the username and
    // password
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    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<ReservationList> response = restTemplate.exchange(url, HttpMethod.GET,
                new HttpEntity<Object>(requestHeaders), ReservationList.class);
        ReservationList body = response.getBody();

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

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

From source file:io.fabric8.che.starter.client.CheRestClient.java

public WorkspaceStatus checkWorkspace(String cheServerURL, String workspaceId) {
    String url = generateURL(cheServerURL, CheRestEndpoints.CHECK_WORKSPACE, workspaceId);

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    ResponseEntity<WorkspaceStatus> status = template.exchange(url, HttpMethod.GET, entity,
            WorkspaceStatus.class);
    return status.getBody();
}