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:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java

@Override
protected MultiValueMap<String, String> getRootAndLinkedResources() {

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("authors", "books");
    map.add("books", "authors");

    return map;/*from w w  w.  j a  v  a  2  s. c om*/
}

From source file:org.springframework.http.converter.FormHttpMessageConverter.java

@Override
public MultiValueMap<String, String> read(@Nullable Class<? extends MultiValueMap<String, ?>> clazz,
        HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    Charset charset = (contentType != null && contentType.getCharset() != null ? contentType.getCharset()
            : this.charset);
    String body = StreamUtils.copyToString(inputMessage.getBody(), charset);

    String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
    MultiValueMap<String, String> result = new LinkedMultiValueMap<>(pairs.length);
    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(URLDecoder.decode(pair, charset.name()), null);
        } else {//from   w  ww  .ja  va 2s . co m
            String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
            String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
            result.add(name, value);
        }
    }
    return result;
}

From source file:org.springframework.http.converter.FormHttpMessageConverterTests.java

@Test
public void writeForm() throws IOException {
    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.set("name 1", "value 1");
    body.add("name 2", "value 2+1");
    body.add("name 2", "value 2+2");
    body.add("name 3", null);
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage);

    assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3",
            outputMessage.getBodyAsString(StandardCharsets.UTF_8));
    assertEquals("Invalid content-type", new MediaType("application", "x-www-form-urlencoded"),
            outputMessage.getHeaders().getContentType());
    assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length,
            outputMessage.getHeaders().getContentLength());
}

From source file:org.springframework.http.converter.FormHttpMessageConverterTests.java

@Test
public void writeMultipart() throws Exception {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("name 1", "value 1");
    parts.add("name 2", "value 2+1");
    parts.add("name 2", "value 2+2");
    parts.add("name 3", null);

    Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
    parts.add("logo", logo);

    // SPR-12108/*  w w w  .j  a  v a 2s  .com*/
    Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {
        @Override
        public String getFilename() {
            return "Hall\u00F6le.jpg";
        }
    };
    parts.add("utf8", utf8);

    Source xml = new StreamSource(new StringReader("<root><child/></root>"));
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(MediaType.TEXT_XML);
    HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
    parts.add("xml", entity);

    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

    final MediaType contentType = outputMessage.getHeaders().getContentType();
    assertNotNull("No boundary found", contentType.getParameter("boundary"));

    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertEquals(6, items.size());
    FileItem item = items.get(0);
    assertTrue(item.isFormField());
    assertEquals("name 1", item.getFieldName());
    assertEquals("value 1", item.getString());

    item = items.get(1);
    assertTrue(item.isFormField());
    assertEquals("name 2", item.getFieldName());
    assertEquals("value 2+1", item.getString());

    item = items.get(2);
    assertTrue(item.isFormField());
    assertEquals("name 2", item.getFieldName());
    assertEquals("value 2+2", item.getString());

    item = items.get(3);
    assertFalse(item.isFormField());
    assertEquals("logo", item.getFieldName());
    assertEquals("logo.jpg", item.getName());
    assertEquals("image/jpeg", item.getContentType());
    assertEquals(logo.getFile().length(), item.getSize());

    item = items.get(4);
    assertFalse(item.isFormField());
    assertEquals("utf8", item.getFieldName());
    assertEquals("Hall\u00F6le.jpg", item.getName());
    assertEquals("image/jpeg", item.getContentType());
    assertEquals(logo.getFile().length(), item.getSize());

    item = items.get(5);
    assertEquals("xml", item.getFieldName());
    assertEquals("text/xml", item.getContentType());
    verify(outputMessage.getBody(), never()).close();
}

From source file:org.springframework.http.converter.FormHttpMessageConverterTests.java

@Test
public void writeMultipartOrder() throws Exception {
    MyBean myBean = new MyBean();
    myBean.setString("foo");

    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("part1", myBean);

    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(MediaType.TEXT_XML);
    HttpEntity<MyBean> entity = new HttpEntity<>(myBean, entityHeaders);
    parts.add("part2", entity);

    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.setMultipartCharset(StandardCharsets.UTF_8);
    this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);

    final MediaType contentType = outputMessage.getHeaders().getContentType();
    assertNotNull("No boundary found", contentType.getParameter("boundary"));

    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertEquals(2, items.size());//from  w  ww .j  av a  2  s.c  om

    FileItem item = items.get(0);
    assertTrue(item.isFormField());
    assertEquals("part1", item.getFieldName());
    assertEquals("{\"string\":\"foo\"}", item.getString());

    item = items.get(1);
    assertTrue(item.isFormField());
    assertEquals("part2", item.getFieldName());

    // With developer builds we get: <MyBean><string>foo</string></MyBean>
    // But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
    // So... we make a compromise:
    assertThat(item.getString(), allOf(startsWith("<MyBean"), endsWith("><string>foo</string></MyBean>")));
}

From source file:org.springframework.http.server.reactive.AbstractServerHttpRequest.java

/**
 * A method for parsing of the query into name-value pairs. The return
 * value is turned into an immutable map and cached.
 * <p>Note that this method is invoked lazily on first access to
 * {@link #getQueryParams()}. The invocation is not synchronized but the
 * parsing is thread-safe nevertheless.//from  w w w. j  a  v  a  2  s. c o m
 */
protected MultiValueMap<String, String> initQueryParams() {
    MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
    String query = getURI().getRawQuery();
    if (query != null) {
        Matcher matcher = QUERY_PATTERN.matcher(query);
        while (matcher.find()) {
            String name = decodeQueryParam(matcher.group(1));
            String eq = matcher.group(2);
            String value = matcher.group(3);
            value = (value != null ? decodeQueryParam(value) : (StringUtils.hasLength(eq) ? "" : null));
            queryParams.add(name, value);
        }
    }
    return queryParams;
}

From source file:org.springframework.http.server.reactive.ServletServerHttpRequest.java

@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
    MultiValueMap<String, HttpCookie> httpCookies = new LinkedMultiValueMap<>();
    Cookie[] cookies;/*from   w  w  w.j  a  v a2s  .c o m*/
    synchronized (this.cookieLock) {
        cookies = this.request.getCookies();
    }
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
            httpCookies.add(name, httpCookie);
        }
    }
    return httpCookies;
}

From source file:org.springframework.http.server.reactive.UndertowServerHttpRequest.java

@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
    MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
    for (String name : this.exchange.getRequestCookies().keySet()) {
        Cookie cookie = this.exchange.getRequestCookies().get(name);
        HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
        cookies.add(name, httpCookie);
    }/*w w  w.  jav  a  2  s.c o m*/
    return cookies;
}

From source file:org.springframework.integration.samples.multipart.MultipartRestClient.java

public static void main(String[] args) throws Exception {
    RestTemplate template = new RestTemplate();
    Resource s2logo = new ClassPathResource(resourcePath);
    MultiValueMap<String, Object> multipartMap = new LinkedMultiValueMap<String, Object>();
    multipartMap.add("company", "SpringSource");
    multipartMap.add("company-logo", s2logo);
    logger.info("Created multipart request: " + multipartMap);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(new MediaType("multipart", "form-data"));
    HttpEntity<Object> request = new HttpEntity<Object>(multipartMap, headers);
    logger.info("Posting request to: " + uri);
    ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, Object.class);
    if (!httpResponse.getStatusCode().equals(HttpStatus.OK)) {
        logger.error("Problems with the request. Http status: " + httpResponse.getStatusCode());
    }/*from   www  . j a v  a2  s .  c  o  m*/
}

From source file:org.springframework.samples.portfolio.web.tomcat.IntegrationPortfolioTests.java

private static void loginAndSaveJsessionIdCookie(final String user, final String password,
        final HttpHeaders headersToUpdate) {

    String url = "http://localhost:" + port + "/login.html";

    new RestTemplate().execute(url, HttpMethod.POST,

            new RequestCallback() {
                @Override//  ww w  .ja  va 2s  . com
                public void doWithRequest(ClientHttpRequest request) throws IOException {
                    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
                    map.add("username", user);
                    map.add("password", password);
                    new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
                }
            },

            new ResponseExtractor<Object>() {
                @Override
                public Object extractData(ClientHttpResponse response) throws IOException {
                    headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
                    return null;
                }
            });
}