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.unidle.social.ConnectionRepositoryImplTest.java

@Test
public void testFindConnectionsToUsers() throws Exception {
    final MultiValueMap<String, String> providerUserIds = new LinkedMultiValueMap<>();
    providerUserIds.add("twitter", "provider user id 1");
    providerUserIds.add("twitter", "provider user id 2");
    providerUserIds.add("twitter", "provider user id 3");
    providerUserIds.add("facebook", "provider user id 4");

    final MultiValueMap<String, Connection<?>> result = subject.findConnectionsToUsers(providerUserIds);

    assertThat(result).hasSize(2).satisfies(containsKey("twitter")).satisfies(containsKey("facebook"));
    assertThat(result.get("twitter")).hasSize(3);
    assertThat(result.get("twitter").get(0)).isNotNull();
    assertThat(result.get("twitter").get(1)).isNotNull();
    assertThat(result.get("twitter").get(2)).isNull();
    assertThat(result.get("facebook")).hasSize(1);
    assertThat(result.get("facebook").get(0)).isNull();
}

From source file:fr.itldev.koya.services.impl.AlfrescoRestService.java

@Override
public AlfrescoUploadReturn uploadToXpathNode(User user, Resource resource, String parentXPath)
        throws AlfrescoServiceException {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();

    parts.add("filedata", resource);
    parts.add("destination", xPathToNodeRef(user, parentXPath));
    parts.add("overwrite", "true");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, headers);

    return fromJSON(new TypeReference<AlfrescoUploadReturn>() {
    }, user.getRestTemplate().postForObject(getAlfrescoServerUrl() + REST_POST_UPLOAD, request, String.class));
}

From source file:com.lixiaocong.social.MyJdbcConnection.java

public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }/*  ww w . j  a  va 2  s.  co m*/
    StringBuilder providerUsersCriteriaSql = new StringBuilder();
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("userId", userId);
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        providerUsersCriteriaSql.append("providerId = :providerId_").append(providerId)
                .append(" and providerUserId in (:providerUserIds_").append(providerId).append(")");
        parameters.addValue("providerId_" + providerId, providerId);
        parameters.addValue("providerUserIds_" + providerId, entry.getValue());
        if (it.hasNext()) {
            providerUsersCriteriaSql.append(" or ");
        }
    }
    List<Connection<?>> resultList = new NamedParameterJdbcTemplate(jdbcTemplate)
            .query(selectFromUserConnection() + " where userId = :userId and " + providerUsersCriteriaSql
                    + " order by providerId, rank", parameters, connectionMapper);
    MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>();
    for (Connection<?> connection : resultList) {
        String providerId = connection.getKey().getProviderId();
        List<String> userIds = providerUsers.get(providerId);
        List<Connection<?>> connections = connectionsForUsers.get(providerId);
        if (connections == null) {
            connections = new ArrayList<Connection<?>>(userIds.size());
            for (int i = 0; i < userIds.size(); i++) {
                connections.add(null);
            }
            connectionsForUsers.put(providerId, connections);
        }
        String providerUserId = connection.getKey().getProviderUserId();
        int connectionIndex = userIds.indexOf(providerUserId);
        connections.set(connectionIndex, connection);
    }
    return connectionsForUsers;
}

From source file:io.kahu.hawaii.util.logger.RequestLogBuilderTest.java

@Test
public void testFormParams() throws Exception {
    MultiValueMap<String, String> m = new LinkedMultiValueMap<String, String>();
    m.add("foo", "bar");
    m.add("foo", "baz");
    m.add("fred", "derf");
    RequestLogBuilder builder = new RequestLogBuilder(logManager, "the-type");
    builder = builder.formParams(m);//from   ww w . jav  a 2s.  c  o m
    builder.logIncoming();

    JSONObject params = new JSONObject();
    JSONArray a = new JSONArray();
    a.put("bar");
    a.put("baz");
    params.put("foo", a);
    a = new JSONArray();
    a.put("derf");
    params.put("fred", a);

    verify(logManager).logIncomingCallStart(eq("the-type"), isNull(String.class), eq(params));
}

From source file:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restUploadFileTest() throws IOException {

    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file", new ClassPathResource("application.yml"));
    String qlQuery = "mutation UploadFileMutation{uploadFile(input: {clientMutationId:\"m-123\"}){ filename }}";
    map.add("query", qlQuery);
    map.add("variables", "{}");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

    ResponseEntity<GraphQLServerResult> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + "/graphql", HttpMethod.POST, requestEntity, GraphQLServerResult.class);

    GraphQLServerResult result = responseEntity.getBody();
    Assert.assertTrue(CollectionUtils.isEmpty(result.getErrors()));
    Assert.assertFalse(CollectionUtils.isEmpty(result.getData()));
    LOGGER.info(objectMapper.writeValueAsString(result.getData()));
}

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

/**
 * http://open.weibo.com/wiki/2/statuses/filter/create
 * @deprecated TODO: need to added testcase.
 * @param id// w ww.  ja  va2  s .c  o m
 * @param accessToken
 * @return
 */
public Status filterCreate(String id, String accessToken) {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("id", id);
    map.add("access_token", accessToken);
    return weiboHttpClient.postForm(STATUSES_FILTER_CREATE_URL, map, Status.class);
}

From source file:org.opendatakit.api.admin.UserAdminServiceTest.java

@Test
public void testChangePlaintextPassword() {
    TestUtils.putGetOneUser(restTemplate, server, testUser3);
    String username = testUser3.getUserId().substring(SecurityConsts.USERNAME_COLON.length());
    String password = "mypass";

    String changePasswordUrl = ConstantsUtils.url(server) + "/admin/users/" + testUser3.getUserId()
            + "/password";

    logger.info("Updating password for " + username + " using " + changePasswordUrl);

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("Content-Type", "application/json");
    HttpEntity<?> request = new HttpEntity<>(password, headers);
    ResponseEntity<String> postResponse = restTemplate.postForEntity(changePasswordUrl, request, String.class);
    assertThat(postResponse.getStatusCode(), is(HttpStatus.OK));

    logger.info("Retrieving data using " + username + "'s new password");

    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    RestTemplate userRestTemplate = restTemplateBuilder.basicAuthorization(username, password).build();
    String getUserUrl = ConstantsUtils.url(server) + "/admin/users/" + testUser3.getUserId();
    ResponseEntity<UserEntity> getResponse = userRestTemplate.exchange(getUserUrl, HttpMethod.GET, null,
            UserEntity.class);
    UserEntity body = getResponse.getBody();
    assertThat(getResponse.getStatusCode(), is(HttpStatus.OK));
    assertThat(body.getUserId(), equalTo(testUser3.getUserId()));

    logger.info("Cleanup: deleting " + username);
    TestUtils.deleteGetOneUser(restTemplate, server, testUser3);
}

From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java

/**
 * Obtains the authorization code from the access token request.
 *
 * @param details the authenticatoin details
 * @param request the access token request
 * @return the authorization code//from w  w  w .  j a  v a  2s.c o m
 * @throws UserRedirectRequiredException when redirection is required
 * @throws UserApprovalRequiredException when the user requires approval
 * @throws AccessDeniedException when the user is denied access
 * @throws OAuth2AccessDeniedException when the user is denied access but we dont want the default Spring Security handling
 */
public final String obtainAuthorizationCode(final OAuth2ProtectedResourceDetails details,
        final AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException,
        AccessDeniedException, OAuth2AccessDeniedException {

    GoogleAuthCodeResourceDetails resource;

    try {
        resource = (GoogleAuthCodeResourceDetails) details;
    } catch (ClassCastException ex) {
        throw new IllegalArgumentException("details is not an instance of class GoogleAuthCodeResourceDetails");
    }

    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
        form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        for (String scope : details.getScope()) {
            form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        }
    } else {
        form.putAll(getParametersForAuthorizeRequest(resource, request));
    }
    authorizationRequestEnhancer.enhance(request, resource, form, headers);
    final AccessTokenRequest copy = request;

    final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
    ResponseExtractor<ResponseEntity<Void>> extractor = new CookieResponseExtractor(copy, delegate);
    // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
    // subclasses
    ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(),
            HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());

    if (response.getStatusCode() == HttpStatus.OK) {
        // Need to re-submit with approval...
        throw getUserApprovalSignal(resource, request);
    }

    URI location = response.getHeaders().getLocation();
    String query = location.getQuery();
    Map<String, String> map = OAuth2Utils.extractMap(query);
    if (map.containsKey("state")) {
        request.setStateKey(map.get("state"));
        if (request.getPreservedState() == null) {
            String redirectUri = resource.getRedirectUri(request);
            if (redirectUri != null) {
                request.setPreservedState(redirectUri);
            } else {
                request.setPreservedState(new Object());
            }
        }
    }

    String code = map.get("code");
    if (code == null) {
        throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
    }
    request.set("code", code);
    return code;

}

From source file:spring.AbstractAuthorizationCodeProviderTests.java

@Test
public void testIllegalAttemptToApproveWithoutUsingAuthorizationRequest() throws Exception {

    HttpHeaders headers = getAuthenticatedHeaders();

    String authorizeUrl = getAuthorizeUrl("my-trusted-client", "http://anywhere.com", "read");
    authorizeUrl = authorizeUrl + "&user_oauth_approval=true";
    ResponseEntity<String> response = http.postForStatus(authorizeUrl, headers,
            new LinkedMultiValueMap<String, String>());
    assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
}

From source file:com.taxamo.example.ec.ApplicationController.java

/**
 * This method is invoked after Taxamo has successfully verified tax location evidence and
 * created a transaction.//from   w w  w . ja  v a 2  s. c  om
 *
 * Two things happen then:
 * - first, the express checkout token is used to capture payment in PayPal
 * - next, transaction is confirmed with Taxamo
 *
 * After that, confirmation page is displayed to the customer.
 *
 * @param payerId
 * @param token
 * @param transactionKey
 * @param model
 * @return
 */
@RequestMapping(value = "/confirm")
public String confirm(@RequestParam("PayerID") String payerId, @RequestParam("token") String token,
        @RequestParam("taxamo_transaction_key") String transactionKey, Model model) {

    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("USER", ppUser);
    map.add("PWD", ppPass);
    map.add("SIGNATURE", ppSign);
    map.add("VERSION", "117");
    map.add("METHOD", "DoExpressCheckoutPayment");
    map.add("PAYERID", payerId);
    map.add("TOKEN", token);

    GetTransactionOut transaction; //more transaction details should be verified in real-life implementation
    try {
        transaction = taxamoApi.getTransaction(transactionKey);
    } catch (ApiException e) {
        e.printStackTrace();
        model.addAttribute("error", "ERROR result: " + e.getMessage());
        return "error";
    }

    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");
    map.add("PAYMENTREQUEST_0_AMT", transaction.getTransaction().getTotalAmount().toString());
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    template.setMessageConverters(messageConverters);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
            requestHeaders);
    ResponseEntity<String> res = template.exchange(
            URI.create(properties.get(PropertiesConstants.PAYPAL_NVP).toString()), HttpMethod.POST, request,
            String.class);

    Map<String, List<String>> params = parseQueryParams(res.getBody());

    String ack = params.get("ACK").get(0);
    if (!ack.equals("Success")) {
        model.addAttribute("error", params.get("L_LONGMESSAGE0").get(0));
        return "error";
    } else {
        try {
            ConfirmTransactionOut transactionOut = taxamoApi.confirmTransaction(transactionKey,
                    new ConfirmTransactionIn());
            model.addAttribute("status", transactionOut.getTransaction().getStatus());
        } catch (ApiException ae) {
            ae.printStackTrace();
            model.addAttribute("error", "ERROR result: " + ae.getMessage());
            return "error";
        }
        model.addAttribute("taxamo_transaction_key", transactionKey);

        return "redirect:/success-checkout";
    }
}