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:org.tangram.spring.StreamingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);
    String encoding = determineEncoding(request);
    Map<String, String[]> multipartParameters = new HashMap<>();
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
    Map<String, String> multipartFileContentTypes = new HashMap<>();

    try {//from  ww  w. j av a 2  s.co m
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream, encoding);
                String[] curParam = multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                try {
                    MultipartFile file = new StreamingMultipartFile(item);
                    multipartFiles.add(name, file);
                    multipartFileContentTypes.put(name, file.getContentType());
                } catch (final IOException e) {
                    LOG.warn("({})", e.getCause().getMessage(), e);
                    MultipartFile file = new MultipartFile() {

                        @Override
                        public String getName() {
                            return "";
                        }

                        @Override
                        public String getOriginalFilename() {
                            return e.getCause().getMessage();
                        }

                        @Override
                        public String getContentType() {
                            return ERROR;
                        }

                        @Override
                        public boolean isEmpty() {
                            return true;
                        }

                        @Override
                        public long getSize() {
                            return 0L;
                        }

                        @Override
                        public byte[] getBytes() throws IOException {
                            return new byte[0];
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return null;
                        }

                        @Override
                        public void transferTo(File file) throws IOException, IllegalStateException {
                            throw new UnsupportedOperationException("NYI", e);
                        }
                    };
                    multipartFiles.add(name, file);
                    multipartFileContentTypes.put(name, file.getContentType());
                } // try/catch
            } // if
        } // while
    } catch (IOException | FileUploadException e) {
        throw new MultipartException("Error uploading a file", e);
    } // try/catch

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters,
            multipartFileContentTypes);
}

From source file:com.fns.grivet.service.NamedQueryServiceSprocTest.java

@Test
public void testSuccessfulNamedQueryExecution() throws IOException {
    Resource r = resolver.getResource("classpath:TestSprocQuery.json");
    String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
    NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
    namedQueryService.create(namedQuery);

    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
    params.add("createdTime", tomorrow);
    String result = namedQueryService.get("sproc.getAttributesCreatedBefore", params);
    String[] expected = { "bigint", "varchar", "decimal", "datetime", "int", "text", "json", "boolean" };
    List<String> actual = JsonPath.given(result).getList("NAME");
    Assertions.assertTrue(actual.size() == 8, "Result should contain 8 attributes");
    Assertions.assertTrue(actual.containsAll(Arrays.asList(expected)));
}

From source file:org.cloudfoundry.identity.statsd.integration.UaaMetricsEmitterIT.java

@Test
public void testStatsDClientEmitsMetricsCollectedFromUAA() throws InterruptedException, IOException {
    RestTemplate template = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.set(headers.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> loginResponse = template.exchange(UAA_BASE_URL + "/login", HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);

    if (loginResponse.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : loginResponse.getHeaders().get("Set-Cookie")) {
            headers.add("Cookie", cookie);
        }//from   w  w w.j a  v  a  2  s  .c o  m
    }
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());

    LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("username", TEST_USERNAME);
    body.add("password", TEST_PASSWORD);
    body.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf);
    loginResponse = template.exchange(UAA_BASE_URL + "/login.do", HttpMethod.POST,
            new HttpEntity<>(body, headers), String.class);
    assertEquals(HttpStatus.FOUND, loginResponse.getStatusCode());
    assertNotNull(getMessage("uaa.audit_service.user_authentication_count:1", 5000));
}

From source file:com.example.SampleAppIntegrationTest.java

@Test
public void testSample() throws Exception {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    String message = "test message " + UUID.randomUUID();

    map.add("messageBody", message);
    map.add("username", "testUserName");

    this.restTemplate.postForObject("/newMessage", map, String.class);

    Callable<Boolean> logCheck = () -> baos.toString()
            .contains("New message received from testUserName via polling: " + message);
    Awaitility.await().atMost(10, TimeUnit.SECONDS).until(logCheck);

    assertThat(logCheck.call()).isTrue();
}

From source file:org.wallride.web.controller.admin.article.ArticleSearchForm.java

public MultiValueMap<String, String> toQueryParams() {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    if (StringUtils.hasText(keyword)) {
        params.add("keyword", keyword);
    }/*from w  ww.j a  va 2  s.co m*/
    if (categoryId != null) {
        params.add("categoryId", Long.toString(categoryId));
    }
    if (tagId != null) {
        params.add("tagId", Long.toString(tagId));
    }
    if (authorId != null) {
        params.add("authorId", Long.toString(authorId));
    }
    if (status != null) {
        params.add("status", status.toString());
    }
    return params;
}

From source file:ru.arch_timeline.spring.multipart.StreamingMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    //Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartContentTypes = new HashMap<String, String>();

    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();

    // Parse the request
    try {// w  ww  .j ava2  s . co m
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }

            } else {

                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.add(name, file);
                multipartContentTypes.put(name, file.getContentType());
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters,
            multipartContentTypes);
}

From source file:org.meruvian.yama.social.core.SocialConnectionService.java

@Override
public MultiValueMap<String, Connection<?>> findAllConnections() {
    List<SocialConnection> socialConnections = connectionRepository.findByUserIdOrderByRankAsc(userId);

    MultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<String, Connection<?>>();
    Set<String> registeredProviderIds = connectionFactoryLocator.registeredProviderIds();

    for (String registeredProviderId : registeredProviderIds) {
        connections.put(registeredProviderId, Collections.<Connection<?>>emptyList());
    }/* w  ww  . j  a  va 2s .c o  m*/

    for (SocialConnection uc : socialConnections) {
        Connection<?> connection = connectionMapper.mapRow(uc);
        String providerId = connection.getKey().getProviderId();
        if (connections.get(providerId).size() == 0) {
            connections.put(providerId, new LinkedList<Connection<?>>());
        }
        connections.add(providerId, connection);
    }

    return connections;
}

From source file:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java

@Test
public void testLogin() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "admin");
    form.set("password", "admin");
    getCsrf(form, headers);/*from  w ww.  ja v  a  2  s.  c om*/
    ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login",
            HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class);
    assertEquals(HttpStatus.FOUND, entity.getStatusCode());
    assertEquals("http://localhost:" + this.port + "/", entity.getHeaders().getLocation().toString());
}

From source file:org.cloudfoundry.identity.uaa.login.integration.AutologinContollerIntegrationTests.java

@Test
public void testGetCodeWithFormEncodedRequest() {
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    request.set("username", testAccounts.getUserName());
    request.set("password", testAccounts.getPassword());
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/autologin"),
            HttpMethod.POST, new HttpEntity<MultiValueMap>(request, headers), Map.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, Object> result = (Map<String, Object>) entity.getBody();
    assertNotNull(result.get("code"));
}

From source file:com.weibo.api.OAuth2.java

/**
 * http://open.weibo.com/wiki/OAuth2/access_token
 * @param appKey//w w  w . java 2  s .  com
 * @param appSecret
 * @param redirectUri
 * @param code
 * @return
 */
public AccessToken accessToken(String appKey, String appSecret, String redirectUri, String code) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("client_id", appKey);
    map.add("client_secret", appSecret);
    map.add("grant_type", "authorization_code");
    map.add("code", code);
    map.add("redirect_uri", redirectUri);
    String result = weiboHttpClient.postForm(OAUTH2_ACCESS_TOKEN, map, String.class);
    try {
        AccessToken accessToken = weiboObjectMapper.readValue(result, AccessToken.class);
        return accessToken;
    } catch (JsonParseException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    } catch (JsonMappingException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    } catch (IOException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    }
    return null;
}