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.sojw.ahnchangho.core.util.UriUtils.java

/**
 * Multi value map./*from  w  w  w. j a v  a  2s.  co m*/
 *
 * @param <T> the generic type
 * @param request the request
 * @return the string
 */
public static <T> MultiValueMap<String, String> multiValueMap(final T request) {
    if (request == null) {
        return null;
    }

    Map<String, Object> requestMap = JsonUtils.convertValue(request, new TypeReference<Map<String, Object>>() {
    });
    if (MapUtils.isEmpty(requestMap)) {
        return null;
    }

    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    for (Entry<String, Object> entry : requestMap.entrySet()) {
        if (entry.getValue() instanceof List) {
            ((List) entry.getValue()).forEach(each -> {
                parameters.add(entry.getKey(), each.toString());
            });
        } else {
            parameters.add(entry.getKey(), entry.getValue().toString());
        }
    }

    return parameters;
}

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/*w ww.  j a  v a  2 s . c  o m*/
 * @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:eionet.webq.service.CDREnvelopeServiceImpl.java

/**
 * Prepares parameters for saveXml remote method.
 *
 * @param file file to be saved.//from   w  ww  .  j  a  va 2s  .  co  m
 * @return http entity representing request
 */
HttpEntity<MultiValueMap<String, Object>> prepareXmlSaveRequestParameters(UserFile file) {

    HttpHeaders authorization = getAuthorizationHeader(file);

    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentDispositionFormData("file", file.getName());
    fileHeaders.setContentType(MediaType.TEXT_XML);

    MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
    byte[] content = file.getContent();
    if (StringUtils.isNotEmpty(file.getConversionId())) {
        content = conversionService.convert(file, file.getConversionId()).getBody();
    }
    request.add("file", new HttpEntity<byte[]>(content, fileHeaders));
    request.add("file_id", new HttpEntity<String>(file.getName()));
    request.add("title", new HttpEntity<String>(StringUtils.defaultString(file.getTitle())));
    if (file.isApplyRestriction()) {
        request.add("applyRestriction", new HttpEntity<String>("1"));
        request.add("restricted", new HttpEntity<String>(file.isRestricted() ? "1" : "0"));
    }

    return new HttpEntity<MultiValueMap<String, Object>>(request, authorization);
}

From source file:eionet.webq.web.controller.WebQProxyDelegation.java

/**
 * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used.
 *
 * @param uri              the address to forward the request
 * @param fileId           UserFile id stored in session
 * @param multipartRequest file part in multipart request
 * @return response from remote host/*from w w w  .j  a  v a 2  s.co m*/
 * @throws URISyntaxException provide URI is incorrect
 * @throws IOException        could not read file from request
 */
@RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId,
        MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException {

    UserFile file = userFileHelper.getUserFile(fileId, multipartRequest);

    if (!multipartRequest.getFileNames().hasNext()) {
        throw new IllegalArgumentException("File not found in multipart request.");
    }
    Map<String, String[]> parameters = multipartRequest.getParameterMap();
    // limit request to one file
    String fileName = multipartRequest.getFileNames().next();
    MultipartFile multipartFile = multipartRequest.getFile(fileName);

    HttpHeaders authorization = new HttpHeaders();
    if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) {
        authorization = envelopeService.getAuthorizationHeader(file);
    }

    HttpHeaders fileHeaders = new HttpHeaders();
    fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename());
    fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType()));

    MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
    byte[] content = multipartFile.getBytes();
    request.add("file", new HttpEntity<byte[]>(content, fileHeaders));
    for (Map.Entry<String, String[]> parameter : parameters.entrySet()) {
        if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId")
                && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) {
            request.add(parameter.getKey(),
                    new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0])));
        }
    }

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(
            request, authorization);

    LOGGER.info("/restProxyFileUpload [POST] uri=" + uri);
    return restTemplate.postForObject(uri, requestEntity, String.class);
}

From source file:ex.fileupload.spring.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring
 * MultipartParsingResult, containing Spring MultipartFile instances and a
 * Map of multipart parameter.//  w  w w  .  j a v a 2 s. c o  m
 * 
 * @param fileItems
 *            the Commons FileIterms to parse
 * @param encoding
 *            the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 */
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:io.mandrel.data.filters.link.SanitizeParamsFilter.java

public boolean isValid(Link link) {
    Uri linkUri = link.getUri();/*ww  w.  ja  va 2 s  .  co m*/
    if (linkUri != null && StringUtils.isNotBlank(linkUri.toString())) {
        String uri = linkUri.toString();
        int pos = uri.indexOf('?');
        if (pos > -1) {
            String uriWithoutParams = uri.substring(0, pos);

            if (CollectionUtils.isNotEmpty(exclusions)) {
                String query = uri.substring(pos + 1, uri.length());

                if (StringUtils.isNotBlank(query)) {
                    String[] paramPairs = QUERY.split(query);

                    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
                    if (paramPairs != null) {
                        for (String pair : paramPairs) {
                            String[] paramValue = PARAMS.split(pair);
                            if (exclusions.contains(paramValue[0])) {
                                params.add(paramValue[0], paramValue.length > 1 ? paramValue[1] : null);
                            }
                        }
                    }

                    StringBuilder builder = new StringBuilder();
                    params.entrySet().forEach(entry -> {
                        entry.getValue().forEach(value -> {
                            builder.append(entry.getKey());
                            if (StringUtils.isNotBlank(value)) {
                                builder.append("=").append(value);
                            }
                            builder.append("&");
                        });
                    });
                    if (builder.length() > 0 && builder.charAt(builder.length() - 1) == '&') {
                        builder.deleteCharAt(builder.length() - 1);
                    }
                    if (builder.length() > 0) {
                        link.setUri(Uri.create(uriWithoutParams + "?" + builder.toString()));
                    } else {
                        link.setUri(Uri.create(uriWithoutParams));
                    }
                } else {
                    link.setUri(Uri.create(uriWithoutParams));
                }
            } else {
                link.setUri(Uri.create(uriWithoutParams));
            }
        }
    }
    return true;
}

From source file:io.pivotal.strepsirrhini.chaoslemur.infrastructure.StandardDirectorUtils.java

private static String getBoshDirectorUaaToken(String host, String directorName, String password)
        throws GeneralSecurityException {

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();/* w  w w. j  av  a 2 s.c  o  m*/

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setSSLSocketFactory(connectionFactory).build();
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    String base64Passowrd = encodePassword(directorName, password);
    headers.add("Authorization", "Basic " + base64Passowrd);
    headers.add("Content-Type", "application/x-www-form-urlencoded");

    String postArgs = "grant_type=client_credentials";

    HttpEntity<String> requestEntity = new HttpEntity<String>(postArgs, headers);
    String uri = "https://" + host + ":8443/oauth/token";
    UaaToken response = restTemplate.postForObject(uri, requestEntity, UaaToken.class);

    log.info("Uaa token:" + response);
    return response.getAccess_token();
}

From source file:it.infn.mw.iam.authn.oidc.DefaultOidcTokenRequestor.java

protected void formAuthRequest(RegisteredClient clientConfig, MultiValueMap<String, String> requestParams) {

    requestParams.add("client_id", clientConfig.getClientId());
    requestParams.add("client_secret", clientConfig.getClientSecret());

}

From source file:it.polimi.diceH2020.launcher.Experiment.java

public boolean send(String filename, String content) {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("name", filename);
    map.add("filename", filename);

    try {//from   w ww . j  a va2  s  .com
        ByteArrayResource contentsAsResource = new ByteArrayResource(content.getBytes("UTF-8")) {
            @Override
            public String getFilename() {
                return filename;
            }
        };
        map.add("file", contentsAsResource);

        try {
            restWrapper.postForObject(UPLOAD_ENDPOINT, map, String.class);
        } catch (Exception e) {
            notifyWsUnreachability();
            return false;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Performs an advanced search and serves the result as XML to be read by an RSS reader
 *
 * @param request HttpServletRequest//  ww w .  jav a2  s. co m
 * @param model   model that will be passed to the template
 * @param site    site the request originates from
 * @param params  search parameters identical to the {@code search} method
 * @return RSS view of articles returned by the search
 * @throws IOException
 */
@RequestMapping(name = "advancedSearchFeed", value = "/search/feed/{feedType:atom|rss}", params = {
        "unformattedQuery" }, method = RequestMethod.GET)
public ModelAndView getAdvancedSearchRssFeedView(HttpServletRequest request, Model model, @SiteParam Site site,
        @PathVariable String feedType, @RequestParam MultiValueMap<String, String> params) throws IOException {
    String queryString = params.getFirst("unformattedQuery");
    params.remove("unformattedQuery");
    params.add("q", queryString);
    return getSearchRssFeedView(request, model, site, feedType, params);
}