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.cloudfoundry.identity.uaa.integration.AuthorizationCodeGrantIntegrationTests.java

@Test
public void testSuccessfulAuthorizationCodeFlow() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource();

    URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code")
            .queryParam("state", "mystateid").queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri()).build();
    ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), headers);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = result.getHeaders().getLocation().toString();

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }/*from   www.  j  ava2  s .c om*/

    ResponseEntity<String> response = serverRunning.getForString(location, headers);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("auth_key"));
    assertTrue(response.getBody().contains("password"));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("auth_key", testAccounts.getUserName());
    formData.add("password", testAccounts.getPassword());

    // Should be redirected to the original URL, but now authenticated
    result = serverRunning.postForResponse("/login.do", headers, formData);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    response = serverRunning.getForString(result.getHeaders().getLocation().toString(), headers);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("Do you authorize"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = serverRunning.postForResponse("/oauth/authorize", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = result.getHeaders().getLocation().toString();
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = response.getHeaders().getLocation().toString();
    }
    assertTrue("Wrong location: " + location,
            location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+"));

    formData.clear();
    formData.add("client_id", resource.getClientId());
    formData.add("redirect_uri", resource.getPreEstablishedRedirectUri());
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    tokenHeaders.set("Authorization",
            testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}

From source file:org.messic.android.util.RestJSONClient.java

/**
 * Rest GET petition to the server at the url param, sending all the post parameters defiend at formData. This post
 * return an object (json marshalling) of class defined at clazz parameter. You should register a
 * {@link RestListener} in order to obtain the returned object, this is because the petition is done in an async
 * process./*from w ww .  j ava2s.c  o  m*/
 * 
 * @param url {@link string} URL to attack
 * @param clazz Class<T/> class that you will marshall to a json object
 * @param rl {@link RestListener} listener to push the object returned
 */
public static <T> void get(final String url, final Class<T> clazz, final RestListener<T> rl) {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    // Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
    final HttpEntity<MultiValueMap<?, ?>> requestEntity = new HttpEntity<MultiValueMap<?, ?>>(
            new LinkedMultiValueMap<String, Object>(), requestHeaders);

    AsyncTask<Void, Void, Void> at = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, clazz);
                rl.response(response.getBody());
            } catch (Exception e) {
                rl.fail(e);
            }
            return null;
        }

    };

    at.execute();
}

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

@Test
public void testNamedQueryNotFound() throws IOException {
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
        params.add("createdTime", tomorrow);
        namedQueryService.get("sproc.getAttributesCreatedBefore", params);
    });/*  w  w  w  .j  a va2 s  . c o  m*/
}

From source file:com.expedia.seiso.web.controller.delegate.RepoSearchDelegateTests.java

private void setUpTestData() {
    this.params = new LinkedMultiValueMap<>();
    params.set("name", "Aurelius");

    when(pagingItemMeta.getRepositorySearchMethod(SEARCH_PATH)).thenReturn(queryMethodWithPagingResults);

    this.queryMethodWithPagingResults = ReflectionUtils.findMethod(PersonRepo.class, "findByLastName",
            String.class, Pageable.class);
    assert (queryMethodWithPagingResults != null);

    this.queryMethodWithUniqueResult = ReflectionUtils.findMethod(ServiceRepo.class, "findByName",
            String.class);
    assert (queryMethodWithUniqueResult != null);

    this.queryMethods = Arrays.asList(queryMethodWithUniqueResult);
    when(repoInfo.getQueryMethods()).thenReturn(queryMethods);

    when(pagingItemMeta.getRepositorySearchMethod(SEARCH_PATH)).thenReturn(queryMethodWithPagingResults);
}

From source file:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addArticleEntry(@RequestBody LocalPressArticleEntity entity,
        @RequestHeader HttpHeaders headers)
        throws UnauthorizedException, GeneralLocalPressException, JsonProcessingException {
    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(entity.getRelease());

    List<String> userHeader = headers.get("UserID");
    if (userHeader == null || userHeader.isEmpty()) {
        throw new UnauthorizedException("There needs to be set a UserID-Header!", "", "");
    }//from  w ww . j  a va  2 s .  c  o  m

    MultiValueMap<String, String> geoHeaders = new LinkedMultiValueMap<>();
    geoHeaders.add("UserID", userHeader.get(0));

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, geoHeaders);

    RestTemplate template = new RestTemplate();
    String ratingURL = RATING_URL + "feedback";
    ResponseEntity<Map> result;
    try {
        result = template.postForEntity(ratingURL, request, Map.class);
    } catch (RestClientException e) {
        GeneralLocalPressException ex = new GeneralLocalPressException(
                "There happened an error by trying to invoke the geo API!", e);
        log.error(ex.getLoggingString());
        throw ex;
    }

    if (!result.getStatusCode().equals(HttpStatus.CREATED)) {
        GeneralLocalPressException e = new GeneralLocalPressException(result.getStatusCode().getReasonPhrase());
        log.error(e.getLoggingString());
        throw e;
    }

    String articleID = (String) result.getBody().get("articleID");
    if (articleID == null) {
        GeneralLocalPressException e = new GeneralLocalPressException(
                "No articleID found in response from rating module by trying to add new article!");
        log.error(e.getLoggingString());
        throw e;
    }

    HttpEntity<LocalPressArticleEntity> second = new HttpEntity<>(entity, geoHeaders);

    template.put(GEO_URL + articleID, second);

    String url = (String) result.getBody().get("feedbackURL");

    Map<String, Object> returnMap = new LinkedHashMap<>();
    returnMap.put("articleID", articleID);
    returnMap.put("userID", userHeader.get(0));

    Timestamp now = new Timestamp(new Date().getTime());
    returnMap.put("timestamp", now);
    returnMap.put("status", 201);
    returnMap.put("message", "Created.");

    returnMap.put("feedbackURL", url);

    return new ResponseEntity<>(objectMapper.writeValueAsString(returnMap), HttpStatus.CREATED);
}

From source file:org.pad.pgsql.loadmovies.LoadFiles.java

/**
 * Read tags and load them in a multivalue map.
 *
 * @return MultivalueMap with key movieId and values all tags.
 * @throws Exception it is only a demo./*from   www . j a  v a  2  s.co m*/
 */
private static LinkedMultiValueMap<Integer, Tag> readTags() throws Exception {
    TagDao tagDao = new TagDao(DS);
    LinkedMultiValueMap<Integer, Tag> tags = new LinkedMultiValueMap();
    final Reader reader = new FileReader("C:\\PRIVE\\SRC\\ml-20m\\tags.csv");
    CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
    for (CSVRecord record : parser) {

        Integer movieId = Integer.parseInt(record.get("movieId"));
        Integer userId = Integer.parseInt(record.get("userId"));
        if (keepId(movieId) && keepId(userId)) {
            //CSV Header : userId,movieId,tag,timestamp
            Tag newTag = new Tag();
            newTag.setUserId(userId);
            newTag.setMovieId(movieId);
            newTag.setTag(record.get("tag"));
            newTag.setDate(new Date(Long.parseLong(record.get("timestamp")) * 1000));
            //Adding to map for json loading
            tags.add(newTag.getMovieId(), newTag);
            //Saving in tag table
            //tagDao.save(newTag);
        }
    }
    return tags;
}

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

@Test
public void testDenied() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("username", "user");
    form.set("password", "user");
    getCsrf(form, headers);/*from   w  w w.  java 2  s  . c o m*/
    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());
    String cookie = entity.getHeaders().getFirst("Set-Cookie");
    headers.set("Cookie", cookie);
    ResponseEntity<String> page = new TestRestTemplate().exchange(entity.getHeaders().getLocation(),
            HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
    assertEquals(HttpStatus.FORBIDDEN, page.getStatusCode());
    assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(),
            page.getBody().contains("Access denied"));
}

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

/**
 * http://open.weibo.com/wiki/2/statuses/update
 * @param status/*from  w ww. j av  a 2 s  . c o  m*/
 * @param visible
 * @param listId
 * @param accessToken
 * @return
 */
public Status update(String status, Visible visible, String listId, String accessToken) {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("status", status);
    if (visible != null) {
        map.add("visible", visible.getCode());
        if (visible == Visible.GROUP) {
            map.add("list_id", listId);
        }
    }
    map.add("access_token", accessToken);
    return weiboHttpClient.postForm(STATUSES_UPDATE_URL, map, Status.class);
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.set("username", username);
    parameters.set("password", password);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = restTemplate.exchange(loginUrl, HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class);

    if (response.getStatusCode() == HttpStatus.OK) {
        String userFromUaa = (String) response.getBody().get("username");

        if (userFromUaa.equals(userFromUaa)) {
            logger.info("Successful authentication request for " + authentication.getName());
            return new UsernamePasswordAuthenticationToken(username, null, UaaAuthority.USER_AUTHORITIES);
        }// w  ww . jav a2s.c o m
    } else if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        logger.info("Failed authentication request");
        throw new BadCredentialsException("Authentication failed");
    } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
        logger.info("Internal error from UAA. Please Check the UAA logs.");
    } else {
        logger.error("Unexpected status code " + response.getStatusCode() + " from the UAA."
                + " Is a compatible version running?");
    }
    throw new RuntimeException("Could not authenticate with remote server");
}

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

/**
 * http://open.weibo.com/wiki/Oauth2/get_token_info
 * @param accessToken/*w w  w .  j  a  va 2s  .  c o  m*/
 * @return
 */
public TokenInfo getTokenInfo(String accessToken) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("access_token", accessToken);
    String result = weiboHttpClient.postForm(OAUTH2_GET_TOKEN_INFO, map, String.class);
    try {
        TokenInfo tokenInfo = weiboObjectMapper.readValue(result, TokenInfo.class);
        return tokenInfo;
    } 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;
}