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:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Sets a single key in Crowdflowers job with a given value
 * @param job/*from   w w w  . j a v  a  2  s.com*/
 * @param key
 * @param value
 */

void updateVariable(CrowdJob job, String Url, String key, String value) {
    MultiValueMap<String, String> argumentMap = new LinkedMultiValueMap<String, String>();
    argumentMap.add(key, value);

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    restTemplate.put(Url, argumentMap, job.getId(), apiKey);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Update the list of allowed countries for this job to Crowdflower (the list is set in the job)
 * @param job/*  ww  w .java2 s. c  o m*/
 * @throws HttpServerErrorException
 */
void updateAllowedCountries(CrowdJob job) throws HttpServerErrorException {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    if (job.getExcludedCountries().size() > 0) {
        restTemplate.put(baseJobURL, job.getExcludedCountriesMap(), job.getId(), apiKey);
    }

    if (job.getIncludedCountries().size() > 0) {
        restTemplate.put(baseJobURL, job.getIncludedCountriesMap(), job.getId(), apiKey);
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Retrieves raw judgments for a given job
 * @param job/*from  w  w w  . j a v  a 2s  .c o  m*/
 * @return raw judgments as string
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
String retrieveRawJudgments(CrowdJob job) throws UnsupportedEncodingException, IOException {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

    //Crowdflower sends back a zip file with a single JSON file, which make things a bit awkward here:
    byte[] resultJsonZip = restTemplate.getForObject(judgmentsURL, byte[].class, job.getId(), apiKey);

    if (resultJsonZip != null && resultJsonZip.length > 0) {
        String resultJsonString = new String(unzip(resultJsonZip), "UTF-8");
        return resultJsonString;
    } else {
        return "";
    }
}

From source file:org.drugis.addis.config.MainConfig.java

@Bean
public RestTemplate restTemplate(RequestConfig requestConfig)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, IOException {
    RestTemplate restTemplate = new RestTemplate(
            new HttpComponentsClientHttpRequestFactory(httpClient(requestConfig)));
    restTemplate.getMessageConverters().add(new JenaGraphMessageConverter());
    return restTemplate;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Orders the job given by its jobid. Pay is per assigment, which is by default 5 units.
 *
 * @param job as CrowdJob//from w ww  .  j a  v  a  2 s . c  om
 * @param channels : a vector of channels, in which the job should be made available
 * @param units : number of units to order
 * @param payPerAssigment : pay in (dollar) cents for each assignments
 * @return JsonNode that Crowdflower returns
 */

JsonNode orderJob(CrowdJob job, Vector<String> channels, int units, int payPerAssigment) {
    Log LOG = LogFactory.getLog(getClass());

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    MultiValueMap<String, String> argumentMap = new LinkedMultiValueMap<String, String>();

    argumentMap.add(debitKey, String.valueOf(units));
    for (String channel : channels) {
        argumentMap.add(channelKey + "[]", channel);
    }

    updateVariable(job, jobPaymentKey, String.valueOf(payPerAssigment));

    LOG.info("Order Job: #" + job.getId() + " with " + units + " judgments for " + payPerAssigment
            + " cents (dollar) per assigment.");
    JsonNode result = restTemplate.postForObject(orderJobURL, argumentMap, JsonNode.class, job.getId(), apiKey);

    return result;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Upload the data vector as JSON to the specified Crowdflower job
 * @param job/*  w ww .j  a  v a  2s  .c  o  m*/
 * @param data - Generic vector of data, containing ordinary java classes.
 * They should be annotated so that Jackson understands how to map them to JSON.
 *
 */

void uploadData(CrowdJob job, List<?> data) {
    Log LOG = LogFactory.getLog(getClass());

    //Crowdflower wants a Multi-line JSON, with each line having a new JSON object
    //Thus we have to map each (raw) object in data individually to a JSON string

    ObjectMapper mapper = new ObjectMapper();
    String jsonObjectCollection = "";

    StringBuilder jsonStringBuilder = new StringBuilder();
    int count = 0;
    for (Object obj : data) {
        count++;
        JsonNode jsonData = mapper.convertValue(obj, JsonNode.class);
        jsonStringBuilder.append(jsonData.toString());
        jsonStringBuilder.append("\n");
    }

    jsonObjectCollection = jsonStringBuilder.toString();

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(jsonObjectCollection, headers);

    String result = "";

    if (job == null) {
        LOG.info("Upload new data and create new job: " + String.valueOf(count) + " data items");
        result = restTemplate.postForObject(uploadDataURL, request, String.class, apiKey);
    } else {
        LOG.info("Uploading new data to job: " + job.getId() + ": " + String.valueOf(count) + " data items");
        result = restTemplate.postForObject(uploadDataWithJobURL, request, String.class, job.getId(), apiKey);
    }
    LOG.info("Upload response:" + result);

    //set gold? this is what i would like to do...
    //updateVariable(job, "https://api.crowdflower.com/v1/jobs/{jobid}/gold?key={apiKey}", "set_standard_gold", "TRUE");
}

From source file:cn.org.once.cstack.cli.rest.RestUtils.java

/**
 * /*from   ww w .  j a  va2s.  c  om*/
 * /** sendPostCommand
 *
 * @param url
 * @param parameters
 * @return
 * @throws ClientProtocolException
 */
public Map<String, Object> sendPostForUpload(String url, Map<String, Object> parameters) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setBufferRequestBody(false);

    RestTemplate restTemplate = new RestTemplate(requestFactory);
    List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters();
    mc.add(new MappingJackson2HttpMessageConverter());
    restTemplate.setMessageConverters(mc);

    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(parameters);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    HttpEntity<Object> request = new HttpEntity<Object>(postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put(CONTENT_TYPE, contentType);
    response.put(STATUS_CODE, statusCode);
    response.put(BODY, body);

    return response;

}

From source file:won.protocol.rest.LinkedDataRestClientHttps.java

@Override
public Dataset readResourceData(URI resourceURI, final URI requesterWebID) {

    HttpMessageConverter datasetConverter = new RdfDatasetConverter();
    RestTemplate restTemplate;
    try {//w  ww.j  a  v a  2 s  .  c  o  m
        restTemplate = getRestTemplateForReadingLinkedData(requesterWebID.toString());
    } catch (Exception e) {
        logger.error("Failed to create ssl tofu rest template", e);
        throw new RuntimeException(e);
    }
    restTemplate.getMessageConverters().add(datasetConverter);

    return super.readResourceData(resourceURI, restTemplate, entity);
}

From source file:com.auditbucket.client.AbRestClient.java

public String ping() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    HttpHeaders httpHeaders = getHeaders(userName, password);
    HttpEntity requestEntity = new HttpEntity<>(httpHeaders);
    try {/*from   ww w.  jav  a2 s .  co  m*/
        ResponseEntity<String> response = restTemplate.exchange(PING, HttpMethod.GET, requestEntity,
                String.class);
        return response.getBody();
    } catch (HttpClientErrorException e) {
        // ToDo: Rest error handling pretty useless. need to know why it's failing
        logger.error("AB Client Audit error {}", getErrorMessage(e));
        return "err";
    } catch (HttpServerErrorException e) {
        logger.error("AB Server Audit error {}", getErrorMessage(e));
        return "err";

    }

}

From source file:com.auditbucket.client.AbRestClient.java

private String flushAudit(List<MetaInputBean> auditInput) {
    if (simulateOnly || auditInput.isEmpty())
        return "OK";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders httpHeaders = getHeaders(userName, password);
    HttpEntity<List<MetaInputBean>> requestEntity = new HttpEntity<>(auditInput, httpHeaders);

    try {/*from   ww w . j  a v  a2 s  .  c o  m*/
        restTemplate.exchange(NEW_HEADER, HttpMethod.PUT, requestEntity, TrackResultBean.class);
        return "OK";
    } catch (HttpClientErrorException e) {
        // ToDo: Rest error handling pretty useless. need to know why it's failing
        logger.error("AB Client Audit error {}", getErrorMessage(e));
        return null;
    } catch (HttpServerErrorException e) {
        logger.error("AB Server Audit error {}", getErrorMessage(e));
        return null;

    }
}