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.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

/**
 * The oauth authentication url/*from  w w  w.j av  a 2  s.c o  m*/
 * 
 * @param state the value of the oauth state parameter to be passed in the authentication url
 * @return The complete oauth authentication url
 */
public String getAuthenticateUrl(String state) {
    String authenticateUrl = null;

    if (state != null) {
        MultiValueMap<String, String> additionalParameters = new LinkedMultiValueMap<String, String>(1);
        additionalParameters.add("access_type", "offline");

        OAuth2Parameters parameters = new OAuth2Parameters(GoogleDocsConstants.REDIRECT_URI,
                GoogleDocsConstants.SCOPE, state, additionalParameters);
        parameters.getAdditionalParameters();
        authenticateUrl = connectionFactory.getOAuthOperations()
                .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, parameters);
    }

    log.debug("Authentication URL: " + authenticateUrl);
    return authenticateUrl;
}

From source file:cn.clxy.studio.common.web.multipart.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, containing Spring MultipartFile
 * instances and a Map of multipart parameter.
 *
 * @param fileItems the Commons FileIterms to parse
 * @param encoding the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 *//*from  ww w.  j ava 2s. c o m*/
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

private HttpEntity<MultiValueMap<String, ?>> generatePartialResourceRequest(
        UploadApplicationPayload application, CloudResources knownRemoteResources) throws IOException {
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(2);
    body.add("application", application);
    ObjectMapper mapper = new ObjectMapper();
    String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
    body.add("resources", knownRemoteResourcesPayload);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    return new HttpEntity<MultiValueMap<String, ?>>(body, headers);
}

From source file:com.muk.services.api.impl.PayPalPaymentService.java

private String getTokenHeader() {
    final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.paymentApiTokenCache);
    final String token = "paypal";
    ValueWrapper valueWrapper = cache.get(token);
    String cachedHeader = StringUtils.EMPTY;

    if (valueWrapper == null || valueWrapper.get() == null) {
        try {//from   w  w  w.j av  a2  s . com
            final String value = securityCfgService.getPayPalClientId() + ":"
                    + keystoreService.getPBEKey(securityCfgService.getPayPalClientId());

            final HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.AUTHORIZATION,
                    "Basic " + nonceService.encode(value.getBytes(StandardCharsets.UTF_8)));

            final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
            body.add("grant_type", "client_credentials");

            final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
                    body, headers);

            final ResponseEntity<JsonNode> response = restTemplate.postForEntity(
                    securityCfgService.getPayPalUri() + "/oauth2/token", request, JsonNode.class);

            cache.put(token, response.getBody().get("access_token").asText());
            valueWrapper = cache.get(token);
            cachedHeader = (String) valueWrapper.get();
        } catch (final IOException ioEx) {
            LOG.error("Failed read keystore", ioEx);
            cachedHeader = StringUtils.EMPTY;
        } catch (final GeneralSecurityException secEx) {
            LOG.error("Failed to get key", secEx);
            cachedHeader = StringUtils.EMPTY;
        }
    } else {
        cachedHeader = (String) valueWrapper.get();
    }

    return "Bearer " + cachedHeader;
}

From source file:com.muk.services.api.impl.StripePaymentService.java

private ResponseEntity<JsonNode> send(String path, JsonNode payload) {
    final HttpHeaders headers = new HttpHeaders();

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader());

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    final Iterator<Entry<String, JsonNode>> nodes = payload.fields();

    while (nodes.hasNext()) {
        final Map.Entry<String, JsonNode> entry = nodes.next();

        if (entry.getValue().isObject()) {
            final String key = entry.getKey();
            final Iterator<Entry<String, JsonNode>> metadataNodes = entry.getValue().fields();

            while (metadataNodes.hasNext()) {
                final Map.Entry<String, JsonNode> element = metadataNodes.next();
                body.add(key + "[\"" + element.getKey() + "\"]", element.getValue().asText());
            }/*from w  ww. j  a v a  2s .c o m*/
        } else {
            body.add(entry.getKey(), entry.getValue().asText());
        }
    }

    return restTemplate.postForEntity(securityCfgService.getStripeUri() + path,
            new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@SuppressWarnings("unchecked")
@Override//from   w  ww  .  j a v a  2s. c om
public Map<String, Object> loginForClient(String username, String password, String clientId,
        UriComponents inUrlComponents) {
    final Map<String, Object> responsePayload = new HashMap<String, Object>();

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());

    // login for csrf
    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build();

    ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers,
            String.class);

    final List<String> cookies = new ArrayList<String>();
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", username);
    formData.add("password", password);
    formData.add(CSRF, getCsrf(cookies));

    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));
    headers.add(HttpHeaders.REFERER, loginUri.toUriString());

    // login.do
    response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(),
            HttpMethod.POST, formData, headers, String.class);

    if (response.getStatusCode() != HttpStatus.FOUND
            || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) {
        responsePayload.put("error", "bad credentials");
        return responsePayload;
    }

    removeCookie(cookies, "X-Uaa-Csrf");
    cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE));
    removeExpiredCookies(cookies);
    headers.remove(HttpHeaders.REFERER);
    headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies));

    // authorize
    final ResponseEntity<JsonNode> authResponse = exchangeForType(
            uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
                    .queryParam("response_type", "code").queryParam("client_id", clientId)
                    .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(),
            HttpMethod.GET, null, headers, JsonNode.class);

    if (authResponse.getStatusCode() == HttpStatus.OK) {
        removeCookie(cookies, "X-Uaa-Csrf");
        cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE));
        // return approval data
        final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>();

        for (final String cookie : cookies) {
            parsedCookies.add(HttpCookie.parse(cookie).get(0));
        }

        responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>());

        for (final HttpCookie parsedCookie : parsedCookies) {
            if (!parsedCookie.getName().startsWith("Saved-Account")) {
                parsedCookie.setPath(inUrlComponents.getPath());
                ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE))
                        .add(httpCookieToString(parsedCookie));
            }
        }

        responsePayload.put("json", authResponse.getBody());
    } else {
        // get auth_code from Location Header
        responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]);
    }

    return responsePayload;
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@Override
public String approveClient(String approvalQuery, String cookie) {
    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; ");
    while (cookieTokenizer.hasMoreTokens()) {
        headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken());
    }// ww w  . j  a v  a  2  s  .c o  m

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    for (final String pair : approvalQuery.split("&")) {
        final String[] nv = pair.split("=");
        formData.add(nv[0], nv[1]);
    }
    formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE)));

    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
            .build();

    final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData,
            headers, String.class);

    if (approvalQuery.contains("false")) {
        return null; // approval declined.
    }

    // accepted, but location contains error
    if (response.getHeaders().getLocation().getQuery().startsWith("error")) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
                response.getHeaders().getLocation().getQuery());
    }

    // accepted with related auth code
    return response.getHeaders().getLocation().getQuery().split("=")[1];
}

From source file:com.muk.services.util.GoogleOAuthService.java

private String requestAccessToken(String jwt) {
    final HttpHeaders headers = new HttpHeaders();
    String token = "error";

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    body.add("grant_type", TOKEN_GRANT);
    body.add("assertion", jwt);

    try {//from  www . j  a v  a2 s. co m
        final ResponseEntity<JsonNode> response = restTemplate.postForEntity(JWT_AUD,
                new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);

        token = response.getBody().get("access_token").asText();
    } catch (final HttpClientErrorException httpClientEx) {
        LOG.error("Failed to request token.", httpClientEx);
    }

    return token;
}

From source file:com.nouveauxterritoires.eterritoires.identityserver.openid.connect.client.TaxeUserInfoFetcher.java

public UserInfo loadUserInfo(final OIDCAuthenticationToken token) {

    ServerConfiguration serverConfiguration = token.getServerConfiguration();

    if (serverConfiguration == null) {
        logger.warn("No server configuration found.");
        return null;
    }/*from  w  ww  .ja va 2 s .  c o  m*/

    if (Strings.isNullOrEmpty(serverConfiguration.getUserInfoUri())) {
        logger.warn("No userinfo endpoint, not fetching.");
        return null;
    }

    try {

        // if we got this far, try to actually get the userinfo
        HttpClient httpClient = new SystemDefaultHttpClient();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

        String userInfoString = null;

        if (serverConfiguration.getUserInfoTokenMethod() == null
                || serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.HEADER)) {
            RestTemplate 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("Bearer %s", token.getAccessTokenValue()));
                    return httpRequest;
                }
            };

            userInfoString = restTemplate.getForObject(serverConfiguration.getUserInfoUri(), String.class);

        } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.FORM)) {
            MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
            form.add("access_token", token.getAccessTokenValue());

            RestTemplate restTemplate = new RestTemplate(factory);
            userInfoString = restTemplate.postForObject(serverConfiguration.getUserInfoUri(), form,
                    String.class);
        } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.QUERY)) {
            URIBuilder builder = new URIBuilder(serverConfiguration.getUserInfoUri());
            builder.setParameter("access_token", token.getAccessTokenValue());

            RestTemplate restTemplate = new RestTemplate(factory);
            userInfoString = restTemplate.getForObject(builder.toString(), String.class);
        }

        if (!Strings.isNullOrEmpty(userInfoString)) {

            JsonObject userInfoJson = new JsonParser().parse(userInfoString).getAsJsonObject();

            UserInfo userInfo = TaxeUserInfo.fromJson(userInfoJson);

            return userInfo;
        } else {
            // didn't get anything, return null
            return null;
        }
    } catch (Exception e) {
        logger.warn("Error fetching taxeuserinfo", e);
        return null;
    }

}

From source file:com.sojw.ahnchangho.core.util.UriUtils.java

/**
 * Multi value map.//from  w  w  w .jav a 2 s  . c  o  m
 *
 * @param map the map
 * @return the multi value map
 */
public static MultiValueMap<String, String> multiValueMap(Map<String, String> map) {
    if (MapUtils.isEmpty(map)) {
        return null;
    }

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        params.add(entry.getKey(), entry.getValue());
    }
    return params;
}