Example usage for org.springframework.http.converter FormHttpMessageConverter FormHttpMessageConverter

List of usage examples for org.springframework.http.converter FormHttpMessageConverter FormHttpMessageConverter

Introduction

In this page you can find the example usage for org.springframework.http.converter FormHttpMessageConverter FormHttpMessageConverter.

Prototype

public FormHttpMessageConverter() 

Source Link

Usage

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/*from  w w w .j  a  v 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.craftercms.search.service.impl.RestClientSearchService.java

public RestClientSearchService() {
    restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new ByteArrayHttpMessageConverter());
    StringHttpMessageConverterExtended stringHttpMessageConverter = new StringHttpMessageConverterExtended(
            Charset.forName(CharEncoding.UTF_8));
    messageConverters.add(stringHttpMessageConverter);
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new ResourceHttpMessageConverter());
    messageConverters.add(new SourceHttpMessageConverter());
    messageConverters.add(new XmlAwareFormHttpMessageConverter());
    if (jaxb2Present) {
        messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
    }/*from  w w  w. ja v  a  2 s  . c  o m*/
    if (jacksonPresent) {
        messageConverters.add(new MappingJacksonHttpMessageConverter());
    }
    if (romePresent) {
        messageConverters.add(new AtomFeedHttpMessageConverter());
        messageConverters.add(new RssChannelHttpMessageConverter());
    }

    restTemplate.setMessageConverters(messageConverters);
}

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. j  a va 2s .  c o  m*/
 *
 * @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.jhk.pulsing.web.config.WebControllerConfig.java

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);

    final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

    SerializationHelper.getAvroRecordStream().forEach(avroRecord -> {
        Class<? extends SpecificRecord> clazz = avroRecord.getClazz();
        builder.deserializerByType(clazz, new JsonAvroDeserializer<>(clazz, avroRecord.getSchema()));
        builder.serializerByType(clazz, new AvroJsonSerializer(clazz));
    });//from   w w w . ja  v  a  2 s.c  om

    converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    converters.add(new StringHttpMessageConverter());
    converters.add(new ResourceHttpMessageConverter());
    converters.add(new FormHttpMessageConverter());
}

From source file:org.starfishrespect.myconsumption.android.ui.CreateAccountActivity.java

private int createAccount() {
    RestTemplate template = new RestTemplate();
    template.getMessageConverters().add(new FormHttpMessageConverter());
    template.getMessageConverters().add(new StringHttpMessageConverter());
    MultiValueMap<String, String> postParams = new LinkedMultiValueMap<>();
    postParams.add("password", CryptoUtils.sha256(editTextPassword.getText().toString()));
    try {/*  ww  w.  j  a  v a 2s.  c  om*/
        String result = template.postForObject(
                SingleInstance.getServerUrl() + "users/" + editTextUsername.getText().toString(), postParams,
                String.class);
        LOGD(TAG, result);

        SimpleResponseDTO response = new ObjectMapper().readValue(result, SimpleResponseDTO.class);
        return response.getStatus();

    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

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

/**
 * Create a new job on Crowdflower using supplied job class. If this class had been retrieved with retrieveJob(String jobid),
 * then you copied the job without its data. Can be used to copy jobs across different accounts if API key is changed between the call to retrieveJob
 * @param job - job class that should be replicated as new job on Crowdflower
 * @return job class which represents the new job
 * @throws HttpServerErrorException//www  . j a va  2  s  .c  o  m
 */
CrowdJob createNewJob(CrowdJob job) throws HttpServerErrorException {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    JsonNode result = restTemplate.postForObject(newJobURL, job.getArgumentMap(), JsonNode.class, apiKey);

    return new CrowdJob(result);
}

From source file:com.miapc.ipudong.Application.java

@Bean
public RestTemplate getRestTemplate() {
    SSLContext sslcontext = null;
    Set<KeyManager> keymanagers = new LinkedHashSet<>();
    Set<TrustManager> trustmanagers = new LinkedHashSet<>();
    try {/* w ww .  j a v  a2  s  . c o  m*/
        trustmanagers.add(new HttpsTrustManager());
        KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]);
        TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]);
        sslcontext = SSLContexts.custom().build();
        sslcontext.init(km, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(factory);
    // ?3?
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // ????Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    headers.add(new BasicHeader("Authorization", "reslibu"));
    httpClientBuilder.setDefaultHeaders(headers);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    if (httpClient != null) {
        // httpClient??RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        // 
        clientHttpRequestFactory.setConnectTimeout(60 * 1000);
        // ???SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000);
        // ????
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        // ?truePOSTPUT????false?
        // clientHttpRequestFactory.setBufferRequestBody(false);
        // ?
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    } else {
        return null;
    }

}

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 . j  a va  2s .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:org.exoplatform.acceptance.rest.administration.credential.CredentialCRUDControllerTest.java

private ExceptionHandlerExceptionResolver createExceptionResolver() {
    ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
        protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod,
                Exception exception) {
            Method method = new ExceptionHandlerMethodResolver(JsonErrorHandler.class).resolveMethod(exception);
            return new ServletInvocableHandlerMethod(jsonErrorHandler, method);
        }//from w w w.ja v  a2s . c om
    };
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    exceptionResolver.setMessageConverters(messageConverters);
    exceptionResolver.afterPropertiesSet();
    return exceptionResolver;
}