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

@Override
@Transactional(readOnly = true)//from w  ww.j  a  va  2  s . co  m
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        final MultiValueMap<String, String> providerUserIds) {

    final MultiValueMap<String, Connection<?>> connections = new LinkedMultiValueMap<>();

    for (final String providerId : providerUserIds.keySet()) {

        final List<String> singleProviderUserIds = providerUserIds.get(providerId);
        final List<UserConnection> userConnections = userConnectionRepository.findAll(user, providerId,
                singleProviderUserIds);

        for (final String providerUserId : singleProviderUserIds) {

            UserConnection userConnection = null;
            for (UserConnection candidateUserConnection : userConnections) {
                if (providerUserId.equals(candidateUserConnection.getProviderUserId())) {
                    userConnection = candidateUserConnection;
                    break;
                }
            }

            connections.add(providerId,
                    Functions.toConnection(connectionFactoryLocator, textEncryptor).apply(userConnection));
        }

    }

    return connections;
}

From source file:de.zib.vold.client.VolDClient.java

/**
 * Insert a set of keys./*  w w  w .  j  av a2 s .c o m*/
 */
public void insert(String source, Map<Key, Set<String>> map, final long timeStamp) {
    // guard
    {
        log.trace("Insert: " + map.toString());

        // nothing to do here?
        if (0 == map.size())
            return;

        checkState();

        if (null == map) {
            throw new IllegalArgumentException("null is no valid argument!");
        }
    }

    // build greatest common scope
    String commonscope;
    {
        List<String> scopes = new ArrayList<String>(map.size());

        for (Key k : map.keySet()) {
            scopes.add(k.get_scope());
        }

        commonscope = getGreatestCommonPrefix(scopes);
    }

    // build variable map
    String url;
    {
        url = buildURL(commonscope, null);
        log.debug("INSERT URL: " + url);
    }

    // build request body
    MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    {
        for (Map.Entry<Key, Set<String>> entry : map.entrySet()) {
            // remove common prefix from scope
            String scope = entry.getKey().get_scope().substring(commonscope.length());
            String type = entry.getKey().get_type();
            String keyname = entry.getKey().get_keyname();

            URIKey key = new URIKey(source, scope, type, keyname, false, false, enc);
            String urikey = key.toURIString();

            for (String value : entry.getValue()) {
                request.add(urikey, value);
            }
        }
    }

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("TIMESTAMP", String.valueOf(timeStamp));
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
            request, requestHeaders);
    final ResponseEntity<HashMap> responseEntity = rest.exchange(url, HttpMethod.PUT, requestEntity,
            HashMap.class);
    //rest.put( url, request );
}

From source file:com.vedri.mtp.frontend.support.stomp.DefaultSubscriptionRegistry.java

private MultiValueMap<String, String> filterSubscriptions(MultiValueMap<String, String> allMatches,
        Message<?> message) {/*  w w w  .  j av a 2  s .c  o  m*/

    if (!this.selectorHeaderInUse) {
        return allMatches;
    }
    EvaluationContext context = null;
    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(allMatches.size());
    for (String sessionId : allMatches.keySet()) {
        for (String subId : allMatches.get(sessionId)) {
            SessionSubscriptionInfo info = this.subscriptionRegistry.getSubscriptions(sessionId);
            if (info == null) {
                continue;
            }
            Subscription sub = info.getSubscription(subId);
            if (sub == null) {
                continue;
            }
            Expression expression = sub.getSelectorExpression();
            if (expression == null) {
                result.add(sessionId, subId);
                continue;
            }
            if (context == null) {
                context = new StandardEvaluationContext(message);
                context.getPropertyAccessors().add(new SimpMessageHeaderPropertyAccessor());
            }
            try {
                if (expression.getValue(context, boolean.class)) {
                    result.add(sessionId, subId);
                }
            } catch (SpelEvaluationException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to evaluate selector: " + ex.getMessage());
                }
            } catch (Throwable ex) {
                logger.debug("Failed to evaluate selector", ex);
            }
        }
    }
    return result;
}

From source file:org.socialsignin.spring.data.dynamodb.repository.query.AbstractDynamoDBQueryCriteria.java

protected String getGlobalSecondaryIndexName() {

    // Lazy evaluate the globalSecondaryIndexName if not already set

    // We must have attribute conditions specified in order to use a global secondary index, otherwise return null for index name
    // Also this method only evaluates the 
    if (globalSecondaryIndexName == null && attributeConditions != null && !attributeConditions.isEmpty()) {
        // Declare map of index names by attribute name which we will populate below - this will be used to determine which index to use if multiple indexes are applicable
        Map<String, String[]> indexNamesByAttributeName = new HashMap<String, String[]>();

        // Declare map of attribute lists by index name which we will populate below - this will be used to determine whether we have an exact match index for specified attribute conditions
        MultiValueMap<String, String> attributeListsByIndexName = new LinkedMultiValueMap<String, String>();

        // Populate the above maps
        for (Entry<String, String[]> indexNamesForPropertyNameEntry : entityInformation
                .getGlobalSecondaryIndexNamesByPropertyName().entrySet()) {
            String propertyName = indexNamesForPropertyNameEntry.getKey();
            String attributeName = getAttributeName(propertyName);
            indexNamesByAttributeName.put(attributeName, indexNamesForPropertyNameEntry.getValue());
            for (String indexNameForPropertyName : indexNamesForPropertyNameEntry.getValue()) {
                attributeListsByIndexName.add(indexNameForPropertyName, attributeName);
            }/*from  w  w w .  j av a2  s .  c o m*/
        }

        // Declare lists to store matching index names
        List<String> exactMatchIndexNames = new ArrayList<String>();
        List<String> partialMatchIndexNames = new ArrayList<String>();

        // Populate matching index name lists - an index is either an exact match ( the index attributes match all the specified criteria exactly)
        // or a partial match ( the properties for the specified criteria are contained within the property set for an index )
        for (Entry<String, List<String>> attributeListForIndexNameEntry : attributeListsByIndexName
                .entrySet()) {
            String indexNameForAttributeList = attributeListForIndexNameEntry.getKey();
            List<String> attributeList = attributeListForIndexNameEntry.getValue();
            if (attributeList.containsAll(attributeConditions.keySet())) {
                if (attributeConditions.keySet().containsAll(attributeList)) {
                    exactMatchIndexNames.add(indexNameForAttributeList);
                } else {
                    partialMatchIndexNames.add(indexNameForAttributeList);
                }
            }
        }

        if (exactMatchIndexNames.size() > 1) {
            throw new RuntimeException(
                    "Multiple indexes defined on same attribute set:" + attributeConditions.keySet());
        } else if (exactMatchIndexNames.size() == 1) {
            globalSecondaryIndexName = exactMatchIndexNames.get(0);
        } else if (partialMatchIndexNames.size() > 1) {
            if (attributeConditions.size() == 1) {
                globalSecondaryIndexName = getFirstDeclaredIndexNameForAttribute(indexNamesByAttributeName,
                        partialMatchIndexNames, attributeConditions.keySet().iterator().next());
            }
            if (globalSecondaryIndexName == null) {
                globalSecondaryIndexName = partialMatchIndexNames.get(0);
            }
        } else if (partialMatchIndexNames.size() == 1) {
            globalSecondaryIndexName = partialMatchIndexNames.get(0);
        }
    }
    return globalSecondaryIndexName;
}

From source file:ee.jaaaar.dreamestate.core.StreamingMultipartResolver.java

@Override
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, String[]> multipartParameters = new HashMap<String, String[]>();

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

    // Parse the request
    try {/*from  www.  j  ava  2  s.c  o  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);
            }
        }
    } 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);
}

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 {//from ww  w  .  j a  va 2s  . c o  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:tigase.muc.modules.PresenceModule.java

private int internalValidRoom(String room, String user) {
    int result = -1;
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    try {/* w w  w.j ava2 s  . c om*/
        String userId = user.substring(0, user.indexOf("@"));
        String domain = user.substring(user.indexOf("@"), user.length());
        String roomId = room.substring(0, room.indexOf("@"));
        map.add("roomId", roomId);
        ResponseEntity<Map> data = DataUtil.postForm(DataUtil.WEB_SERVER_ADDRESS + "internalRoom", map,
                Map.class);
        Map body = data.getBody();
        if (data.getStatusCode() == HttpStatus.OK) {
            String ownerId = (String) body.get("ownerId");
            String status = (String) body.get("status");
            if (ownerId != null && ownerId.equals(userId)) {
                result = 0;
            } else if ("1".equals(status)) {
                result = 1;
            }
        }
    } catch (Exception e) {
        // TODO log exception
        e.printStackTrace();
    }
    return result;
}

From source file:org.mitre.oauth2.introspectingfilter.IntrospectingTokenService.java

/**
 * Validate a token string against the introspection endpoint,
 * then parse it and store it in the local cache if caching is enabled.
 *
 * @param accessToken Token to pass to the introspection endpoint
 * @return TokenCacheObject containing authentication and token if the token was valid, otherwise null
 *//*w w w .j  a  v  a  2 s. co  m*/
private TokenCacheObject parseToken(String accessToken) {

    // find out which URL to ask
    String introspectionUrl;
    RegisteredClient client;
    try {
        introspectionUrl = introspectionConfigurationService.getIntrospectionUrl(accessToken);
        client = introspectionConfigurationService.getClientConfiguration(accessToken);
    } catch (IllegalArgumentException e) {
        logger.error("Unable to load introspection URL or client configuration", e);
        return null;
    }
    // Use the SpringFramework RestTemplate to send the request to the
    // endpoint
    String validatedToken = null;

    RestTemplate restTemplate;
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();

    final String clientId = client.getClientId();
    final String clientSecret = client.getClientSecret();

    if (SECRET_BASIC.equals(client.getTokenEndpointAuthMethod())) {
        // use BASIC auth if configured to do so
        restTemplate = new RestTemplate(factory) {

            @Override
            protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
                ClientHttpRequest httpRequest = super.createRequest(url, method);
                httpRequest.getHeaders().add("Authorization", String.format("Basic %s",
                        Base64.encode(String.format("%s:%s", clientId, clientSecret))));
                return httpRequest;
            }
        };
    } else { //Alternatively use form based auth
        restTemplate = new RestTemplate(factory);

        form.add("client_id", clientId);
        form.add("client_secret", clientSecret);
    }

    form.add("token", accessToken);

    try {
        validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
    } catch (RestClientException rce) {
        logger.error("validateToken", rce);
        return null;
    }
    if (validatedToken != null) {
        // parse the json
        JsonElement jsonRoot = new JsonParser().parse(validatedToken);
        if (!jsonRoot.isJsonObject()) {
            return null; // didn't get a proper JSON object
        }

        JsonObject tokenResponse = jsonRoot.getAsJsonObject();

        if (tokenResponse.get("error") != null) {
            // report an error?
            logger.error("Got an error back: " + tokenResponse.get("error") + ", "
                    + tokenResponse.get("error_description"));
            return null;
        }

        if (!tokenResponse.get("active").getAsBoolean()) {
            // non-valid token
            logger.info("Server returned non-active token");
            return null;
        }
        // create an OAuth2Authentication
        OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse),
                createAuthentication(tokenResponse));
        // create an OAuth2AccessToken
        OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);

        if (token.getExpiration() == null || token.getExpiration().after(new Date())) {
            // Store them in the cache
            TokenCacheObject tco = new TokenCacheObject(token, auth);
            if (cacheTokens && (cacheNonExpiringTokens || token.getExpiration() != null)) {
                authCache.put(accessToken, tco);
            }
            return tco;
        }
    }

    // when the token is invalid for whatever reason
    return null;
}

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 {// ww  w.  j ava 2 s  .  c o  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);
}