Example usage for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

Introduction

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

Prototype

public LinkedMultiValueMap() 

Source Link

Document

Create a new LinkedMultiValueMap that wraps a LinkedHashMap .

Usage

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// ww  w .  j  a  va2 s . c o  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 a2 s.  co  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:fi.helsinki.moodi.integration.moodle.MoodleClient.java

private MultiValueMap<String, String> createParametersForFunction(final String function) {
    final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.set("wstoken", wstoken);
    params.set("wsfunction", function);
    params.set("moodlewsrestformat", "json");
    return params;
}

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

public boolean isValid(Link link) {
    Uri linkUri = link.getUri();//from   www . j ava  2  s.  c  o  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();/*ww  w .ja va 2s. com*/

    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:io.syndesis.runtime.ExtensionsITCase.java

private MultiValueMap<String, Object> multipartBody(byte[] data) {
    LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("file", new InputStreamResource(new ByteArrayInputStream(data)));
    return multipartData;
}

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 {/* w w  w.  j  ava 2s. c  om*/
        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.apache.servicecomb.demo.jaxrs.client.JaxrsClient.java

private static void testJaxRSDefaultValues(RestTemplate template) {
    String microserviceName = "jaxrs";
    for (String transport : DemoConst.transports) {
        CseContext.getInstance().getConsumerProviderManager().setTransport(microserviceName, transport);
        TestMgr.setMsg(microserviceName, transport);

        String cseUrlPrefix = "cse://" + microserviceName + "/JaxRSDefaultValues/";

        //default values
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        String result = template.postForObject(cseUrlPrefix + "/form", request, String.class);
        TestMgr.check("Hello 20bobo", result);

        headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        result = template.postForObject(cseUrlPrefix + "/header", entity, String.class);
        TestMgr.check("Hello 20bobo30", result);

        result = template.getForObject(cseUrlPrefix + "/query?d=10", String.class);
        TestMgr.check("Hello 20bobo4010", result);
        boolean failed = false;
        try {/*ww w.ja v  a  2 s.  com*/
            result = template.getForObject(cseUrlPrefix + "/query2", String.class);
        } catch (InvocationException e) {
            failed = true;
            TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
        }

        failed = false;
        try {
            result = template.getForObject(cseUrlPrefix + "/query2?d=2&e=2", String.class);
        } catch (InvocationException e) {
            failed = true;
            TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
        }
        TestMgr.check(failed, true);

        failed = false;
        try {
            result = template.getForObject(cseUrlPrefix + "/query2?a=&d=2&e=2", String.class);
        } catch (InvocationException e) {
            failed = true;
            TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
        }
        TestMgr.check(failed, true);

        result = template.getForObject(cseUrlPrefix + "/query2?d=30&e=2", String.class);
        TestMgr.check("Hello 20bobo40302", result);

        failed = false;
        try {
            result = template.getForObject(cseUrlPrefix + "/query3?a=2&b=2", String.class);
        } catch (InvocationException e) {
            failed = true;
            TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
        }
        TestMgr.check(failed, true);

        result = template.getForObject(cseUrlPrefix + "/query3?a=30&b=2", String.class);
        TestMgr.check("Hello 302", result);

        result = template.getForObject(cseUrlPrefix + "/query3?a=30", String.class);
        TestMgr.check("Hello 30null", result);

        //input values
        headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
        Map<String, String> params = new HashMap<>();
        params.put("a", "30");
        params.put("b", "sam");
        HttpEntity<Map<String, String>> requestPara = new HttpEntity<>(params, headers);
        result = template.postForObject(cseUrlPrefix + "/form", requestPara, String.class);
        TestMgr.check("Hello 30sam", result);

        headers = new HttpHeaders();
        headers.add("a", "30");
        headers.add("b", "sam");
        headers.add("c", "40");
        entity = new HttpEntity<>(null, headers);
        result = template.postForObject(cseUrlPrefix + "/header", entity, String.class);
        TestMgr.check("Hello 30sam40", result);

        result = template.getForObject(cseUrlPrefix + "/query?a=3&b=sam&c=5&d=30", String.class);
        TestMgr.check("Hello 3sam530", result);

        result = template.getForObject(cseUrlPrefix + "/query2?a=3&b=4&c=5&d=30&e=2", String.class);
        TestMgr.check("Hello 345302", result);
    }
}

From source file:org.apache.servicecomb.demo.jaxrs.client.JaxrsClient.java

private static void testSpringMvcDefaultValuesJavaPrimitive(RestTemplate template) {
    String microserviceName = "jaxrs";
    String cseUrlPrefix = "cse://" + microserviceName + "/JaxRSDefaultValues/";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

    //default values with primitive
    String result = template.postForObject(cseUrlPrefix + "/javaprimitiveint", request, String.class);
    TestMgr.check("Hello 0bobo", result);

    result = template.postForObject(cseUrlPrefix + "/javaprimitivenumber", request, String.class);
    TestMgr.check("Hello 0.0false", result);

    result = template.postForObject(cseUrlPrefix + "/javaprimitivestr", request, String.class);
    TestMgr.check("Hello", result);

    result = template.postForObject(cseUrlPrefix + "/javaprimitivecomb", request, String.class);
    TestMgr.check("Hello nullnull", result);

    result = template.postForObject(cseUrlPrefix + "/allprimitivetypes", null, String.class);
    TestMgr.check("Hello false,0,0,0,0,0,0.0,0.0,null", result);
}

From source file:org.apache.servicecomb.demo.springmvc.client.CodeFirstRestTemplateSpringmvc.java

private void testUpload(RestTemplate template, String cseUrlPrefix) throws IOException {
    String file1Content = "hello world";
    File file1 = File.createTempFile(" ", ".txt");
    FileUtils.writeStringToFile(file1, file1Content);

    String file2Content = " bonjour";
    File someFile = File.createTempFile("upload2", ".txt");
    FileUtils.writeStringToFile(someFile, file2Content);

    String expect = String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getName(), MediaType.TEXT_PLAIN_VALUE,
            file1Content, someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content);

    String result = testRestTemplateUpload(template, cseUrlPrefix, file1, someFile);
    TestMgr.check(expect, result);/*  w w w  .ja  va 2  s.  c  o  m*/

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(file1));

    result = template.postForObject(cseUrlPrefix + "/upload1", new HttpEntity<>(map), String.class);

    result = uploadPartAndFile.fileUpload(new FilePart(null, file1), someFile);
    TestMgr.check(expect, result);

    expect = String.format("null:%s:%s\n" + "%s:%s:%s", MediaType.APPLICATION_OCTET_STREAM_VALUE, file1Content,
            someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content);
    result = uploadStreamAndResource.fileUpload(
            new ByteArrayInputStream(file1Content.getBytes(StandardCharsets.UTF_8)),
            new PathResource(someFile.getAbsolutePath()));
    TestMgr.check(expect, result);
}