Example usage for org.springframework.util MultiValueMap add

List of usage examples for org.springframework.util MultiValueMap add

Introduction

In this page you can find the example usage for org.springframework.util MultiValueMap add.

Prototype

void add(K key, @Nullable V value);

Source Link

Document

Add the given single value to the current list of values for the given key.

Usage

From source file:com.taxamo.example.ec.ApplicationController.java

/**
 * This method is invoked after Taxamo has successfully verified tax location evidence and
 * created a transaction./*from   www.  j  a v  a  2s  .  com*/
 *
 * Two things happen then:
 * - first, the express checkout token is used to capture payment in PayPal
 * - next, transaction is confirmed with Taxamo
 *
 * After that, confirmation page is displayed to the customer.
 *
 * @param payerId
 * @param token
 * @param transactionKey
 * @param model
 * @return
 */
@RequestMapping(value = "/confirm")
public String confirm(@RequestParam("PayerID") String payerId, @RequestParam("token") String token,
        @RequestParam("taxamo_transaction_key") String transactionKey, 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", "DoExpressCheckoutPayment");
    map.add("PAYERID", payerId);
    map.add("TOKEN", token);

    GetTransactionOut transaction; //more transaction details should be verified in real-life implementation
    try {
        transaction = taxamoApi.getTransaction(transactionKey);
    } catch (ApiException e) {
        e.printStackTrace();
        model.addAttribute("error", "ERROR result: " + e.getMessage());
        return "error";
    }

    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");
    map.add("PAYMENTREQUEST_0_AMT", transaction.getTransaction().getTotalAmount().toString());
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");

    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 {
        try {
            ConfirmTransactionOut transactionOut = taxamoApi.confirmTransaction(transactionKey,
                    new ConfirmTransactionIn());
            model.addAttribute("status", transactionOut.getTransaction().getStatus());
        } catch (ApiException ae) {
            ae.printStackTrace();
            model.addAttribute("error", "ERROR result: " + ae.getMessage());
            return "error";
        }
        model.addAttribute("taxamo_transaction_key", transactionKey);

        return "redirect:/success-checkout";
    }
}

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

/**
 * Sets a single key in Crowdflowers job with a given value
 * @param job/*ww w  .j  a v a2s  .co m*/
 * @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:eu.freme.broker.eservices.Pipelines.java

private ResponseEntity<String> createOKJSONResponse(final String contents) {
    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, RDFConstants.RDFSerialization.JSON.contentType());
    return new ResponseEntity<>(contents, headers, HttpStatus.OK);
}

From source file:org.ihtsdo.otf.refset.security.RefsetIdentityService.java

protected UserDetails authenticate(String userName, String token) {

    LOGGER.debug("Authenticating user {} ", userName);

    User user = getGuestUser();/*from   w w w  .ja  va2  s. c o m*/

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("username", userName);
    params.add("password", token);
    params.add("queryName", "getUserByNameAuth");

    try {

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(token)) {

            throw new AccessDeniedException("User is unauthorized. Please check user name and password");
        }
        Assert.notNull(rt, "Rest template can not be empty");

        LOGGER.debug("Calling authentication service with URL {}, User {} and Parameters {} ", otfServiceUrl,
                userName);

        JsonNode obj = rt.postForObject(otfServiceUrl, params, JsonNode.class);

        LOGGER.debug("authentication service call successfully returned with {} ", obj);

        //populate user with other user details
        populateUser(user, obj);

        //now check if user has access to Refset app.
        params = new LinkedMultiValueMap<String, String>();
        params.add("username", userName);
        params.add("queryName", "getUserApps");

        LOGGER.debug("Calling autorization service with URL {}, User {} and Parameters {} ", otfServiceUrl,
                userName);

        JsonNode appJson = rt.postForObject(otfServiceUrl, params, JsonNode.class);

        LOGGER.debug("autorization service call successfully returned with {} ", appJson);

        JsonNode apps = appJson.get("apps");
        Collection<RefsetRole> roles = new ArrayList<RefsetRole>();

        for (JsonNode object : apps) {

            if (object != null && object.asText().equals(APP_NAME)) {

                RefsetRole role = new RefsetRole();
                role.setAuthority(ROLE_USER);
                roles.add(role);
                break;
            }
        }
        user.setAuthorities(roles);

        if (isUserHasRole(user)) {

            String info = userName + ":" + token;
            Token key = service.allocateToken(info);
            user.setToken(key.getKey());
        }

    } catch (Exception e) {

        LOGGER.error("Error during authentication for user:password - {} ", userName + ":" + token, e);

        throw new AccessDeniedException("User is unauthorized. Please check user name and password");
    }

    return user;

}

From source file:de.codecentric.batch.test.metrics.BatchMetricsFlatFileToDbIntegrationTest.java

private JobExecution runJob(String jobName, String pathToFile) throws InterruptedException {
    MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
    requestMap.add("jobParameters", "pathToFile=" + pathToFile);
    Long executionId = restTemplate.postForObject(
            "http://localhost:" + port + "/batch/operations/jobs/" + jobName, requestMap, Long.class);
    while (!restTemplate
            .getForObject("http://localhost:" + port + "/batch/operations/jobs/executions/{executionId}",
                    String.class, executionId)
            .equals("COMPLETED")
            && !restTemplate.getForObject(
                    "http://localhost:" + port + "/batch/operations/jobs/executions/{executionId}",
                    String.class, executionId).equals("FAILED")) {
        Thread.sleep(1000);//w  w w  .j ava2s . c  o m
    }
    JobExecution jobExecution = jobExplorer.getJobExecution(executionId);
    return jobExecution;
}

From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java

public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException, OAuth2AccessDeniedException {
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("grant_type", "refresh_token");
    form.add("refresh_token", refreshToken.getValue());
    try {//w ww.  j a  va  2 s.  co  m
        return retrieveToken(request, resource, form, getHeadersForTokenRequest(request));
    } catch (OAuth2AccessDeniedException e) {
        throw getRedirectForAuthorization((AuthorizationCodeResourceDetails) resource, request);
    }
}

From source file:com.t163.http.client.T163HttpClient.java

/**
 * getBodyMap/*  ww w  . ja  va 2s .c o m*/
 * @param object
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
private MultiValueMap<String, String> getBodyMap(Object object)
        throws IllegalArgumentException, IllegalAccessException {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if (field.get(object) != null) {
            map.add(String.valueOf(field.getName()), String.valueOf(field.get(object)));
        }
    }
    return map;
}

From source file:eu.freme.broker.eservices.Pipelines.java

/**
 * <p>Calls the pipelining service.</p>
 * <p>Some predefined Requests can be formed using the class {@link RequestFactory}. It also converts request objects
 * from and to JSON.</p>//from ww  w  .  j ava2  s  .  c o m
 * <p><To create custom requests, use the {@link RequestBuilder}.</p>
 * <p>Examples can be found in the unit tests in {@link eu/freme/broker/integration_tests/pipelines}.</p>
 * @param requests   The requests to send to the service.
 * @param stats      If "true": wrap the response of the last request and add timing statistics.
 * @return          The response of the last request.
 * @throws BadRequestException            The contents of the request is not valid.
 * @throws InternalServerErrorException      Something goes wrong that shouldn't go wrong.
 */
@RequestMapping(value = "pipelining/chain", method = RequestMethod.POST, consumes = "application/json", produces = {
        "text/turtle", "application/json", "application/ld+json", "application/n-triples",
        "application/rdf+xml", "text/n3", "text/html" })
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> pipeline(@RequestBody String requests,
        @RequestParam(value = "stats", defaultValue = "false", required = false) String stats) {
    try {
        boolean wrapResult = Boolean.parseBoolean(stats);
        List<SerializedRequest> serializedRequests = Serializer.fromJson(requests);
        WrappedPipelineResponse pipelineResult = pipelineAPI.chain(serializedRequests);
        MultiValueMap<String, String> headers = new HttpHeaders();

        if (wrapResult) {
            headers.add(HttpHeaders.CONTENT_TYPE, RDFConstants.RDFSerialization.JSON.contentType());
            return new ResponseEntity<>(Serializer.toJson(pipelineResult), headers, HttpStatus.OK);
        } else {
            headers.add(HttpHeaders.CONTENT_TYPE, pipelineResult.getContent().getContentType());
            PipelineResponse lastResponse = pipelineResult.getContent();
            return new ResponseEntity<>(lastResponse.getBody(), headers, HttpStatus.OK);
        }

    } catch (ServiceException serviceError) {
        // TODO: see if this can be replaced by excsption(s) defined in the broker.
        logger.error(serviceError.getMessage(), serviceError);
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, serviceError.getResponse().getContentType());
        return new ResponseEntity<>(serviceError.getMessage(), headers, serviceError.getStatus());
    } catch (JsonSyntaxException jsonException) {
        logger.error(jsonException.getMessage(), jsonException);
        String errormsg = jsonException.getCause() != null ? jsonException.getCause().getMessage()
                : jsonException.getMessage();
        throw new BadRequestException("Error detected in the JSON body contents: " + errormsg);
    } catch (UnirestException unirestException) {
        logger.error(unirestException.getMessage(), unirestException);
        throw new BadRequestException(unirestException.getMessage());
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        // throw an Internal Server exception if anything goes really wrong...
        throw new InternalServerErrorException(t.getMessage());
    }
}