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:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restUploadFileUrlEncodedTest() throws IOException {

    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("query",
            "mutation AddTodoMutationMutation{addTodoMutation(input: {clientMutationId:\"m-123\", addTodoInput:{text: \"text\"}}){ clientMutationId, todoEdge {cursor, node {text, complete}} }}");
    map.add("variables", "{}");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    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:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

private MultiValueMap<String, String> parseFragmentParams(UriComponents locationComponents) {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    String[] tuples = locationComponents.getFragment().split("&");
    for (String tuple : tuples) {
        String[] parts = tuple.split("=");
        params.add(parts[0], parts[1]);//from   w  ww .java2 s .c o  m
    }
    return params;
}

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)
 *///w  w w .j a  v a2  s .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:com.music.web.AuthenticationController.java

@RequestMapping("/persona/auth")
@ResponseBody//from  w  w w . j  a  va2 s. c  o m
public String authenticateWithPersona(@RequestParam String assertion,
        @RequestParam boolean userRequestedAuthentication, HttpServletRequest request,
        HttpServletResponse httpResponse, Model model) throws IOException {
    if (context.getUser() != null) {
        return "";
    }
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("assertion", assertion);
    params.add("audience", request.getScheme() + "://" + request.getServerName() + ":"
            + (request.getServerPort() == 80 ? "" : request.getServerPort()));
    PersonaVerificationResponse response = restTemplate.postForObject(
            "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);
    if (response.getStatus().equals("okay")) {
        User user = userService.getUserByEmail(response.getEmail());
        if (user == null && userRequestedAuthentication) {
            return "/socialSignUp?email=" + response.getEmail();
        } else if (user != null) {
            if (userRequestedAuthentication || user.isLoginAutomatically()) {
                signInAdapter.signIn(user, httpResponse, true);
                return "/";
            } else {
                return "";
            }
        } else {
            return ""; //in case this is not a user-requested operation, do nothing
        }
    } else {
        logger.warn("Persona authentication failed due to reason: " + response.getReason());
        throw new IllegalStateException("Authentication failed");
    }
}

From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java

public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_)
        throws ColdFusionException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol);
        HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_);

        MultipartEntityBuilder me = MultipartEntityBuilder.create();
        me.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        if (methodArgs_ != null) {
            for (String s : methodArgs_.keySet()) {
                Object obj = methodArgs_.get(s);

                if (obj != null) {
                    if (obj instanceof String) {
                        me.addTextBody(s, (String) obj);
                    } else if (obj instanceof Integer) {
                        me.addTextBody(s, ((Integer) obj).toString());
                    } else if (obj instanceof File) {
                        me.addBinaryBody(s, (File) obj);
                    } else if (obj instanceof IDocument) {
                        me.addBinaryBody(s, ((IDocument) obj).getFile());
                        //me.addTextBody( "name", ((IDocument)obj).getFileName() );
                        //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType );
                    } else if (obj instanceof IDocument[]) {
                        for (int i = 0; i < ((IDocument[]) obj).length; i++) {
                            IDocument iDocument = ((IDocument[]) obj)[i];
                            me.addBinaryBody(s, iDocument.getFile());
                            //me.addTextBody("name", iDocument.getFileName() );
                            //me.addTextBody("contentType", iDocument.getContentType().contentType );
                        }//from  w  w  w. j  a va  2s  . co m

                    } else if (obj instanceof BufferedImage) {

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ImageIO.write((BufferedImage) obj, "jpg", baos);

                        String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME);
                        String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE))
                                .getExtension();
                        ContentType _contentType = ContentType.create(_mimeType);
                        me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName);
                    } else if (obj instanceof byte[]) {
                        me.addBinaryBody(s, (byte[]) obj);
                    } else if (obj instanceof Map) {
                        ObjectMapper mapper = new ObjectMapper();
                        String _json = mapper.writeValueAsString(obj);

                        me.addTextBody(s, _json);
                    }
                }
            }
        }

        HttpEntity httpEntity = me.build();
        method.setEntity(httpEntity);

        HttpResponse response = httpClient.execute(host, method);//, responseHandler);

        // Examine the response status
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                //return inputStream;

                byte[] _body = IOUtils.toByteArray(inputStream);

                MultiValueMap _headers = new LinkedMultiValueMap();
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equalsIgnoreCase("content-length")) {
                        _headers.add(header.getName(), header.getValue());
                    } else if (header.getName().equalsIgnoreCase("content-type")) {
                        _headers.add(header.getName(), header.getValue());

                        // special condition to add zip to the file name.
                        if (header.getValue().indexOf("text/") > -1) {
                            //add nothing extra
                        } else if (header.getValue().indexOf("zip") > -1) {
                            if (methodArgs_.get("file") != null) {
                                String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                                _headers.add("Content-Disposition",
                                        "attachment; filename=\"" + _fileName + ".zip\"");
                            }
                        } else if (methodArgs_.get("file") != null) {
                            String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                            _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\"");
                        }

                    }
                }

                return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK);
                //Map json = (Map)deSerializeJson(inputStream);
                //return json;
            }
        }

        MultiValueMap _headers = new LinkedMultiValueMap();
        _headers.add("Content-Type", "text/plain");
        return new ResponseEntity(response.getStatusLine().toString(), _headers,
                org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:com.goldengekko.meetr.itest.AuthITest.java

@Test
public void testHappyUserAccess() {
    //register token
    JConnection fedResponse = registerToken(restTemplate);

    // get my user profile
    LinkedMultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    HttpEntity requestEntity = new HttpEntity(request, getHttpBasicHeader());

    ResponseEntity<MeetingPage> myResponse = restTemplate.exchange(
            API_URL + "/meeting/v10?access_token={access_token}", HttpMethod.GET, requestEntity,
            MeetingPage.class, TOKEN);
    assertEquals(HttpStatus.OK, myResponse.getStatusCode());
    assertNotNull(myResponse.getBody());
}

From source file:com.ge.predix.test.utils.UaaTestUtil.java

private BaseClientDetails createOrUpdateClient(final BaseClientDetails client) {

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    if (StringUtils.isNotEmpty(this.zone)) {
        headers.add("X-Identity-Zone-Id", "uaa");
    }//from ww w. j  a v a 2  s .co  m

    HttpEntity<String> postEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);

    ResponseEntity<String> clientCreate = null;
    try {
        clientCreate = this.adminRestTemplate.exchange(this.uaaUrl + "/oauth/clients", HttpMethod.POST,
                postEntity, String.class);
        if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
            return JSON_UTILS.deserialize(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException(
                    "Unexpected return code for client create: " + clientCreate.getStatusCode());
        }
    } catch (InvalidClientException ex) {
        if (ex.getMessage().equals("Client already exists: " + client.getClientId())) {
            HttpEntity<String> putEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);
            ResponseEntity<String> clientUpdate = this.adminRestTemplate.exchange(
                    this.uaaUrl + "/oauth/clients/" + client.getClientId(), HttpMethod.PUT, putEntity,
                    String.class);
            if (clientUpdate.getStatusCode() == HttpStatus.OK) {
                return JSON_UTILS.deserialize(clientUpdate.getBody(), BaseClientDetails.class);
            } else {
                throw new RuntimeException(
                        "Unexpected return code for client update: " + clientUpdate.getStatusCode());
            }
        }
    }
    throw new RuntimeException("Unexpected return code for client creation: " + clientCreate.getStatusCode());
}

From source file:io.github.davejoyce.dao.composite.social.connect.jpa.JpaConnectionRepository.java

/**
 * {@inheritDoc}//from   w  ww.  j  a  v  a 2  s .  c o  m
 */
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(
        MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }
    StringBuilder providerUsersCriteriaJpaQl = new StringBuilder(QUERY_SELECT_FROM)
            .append("WHERE ausc.key.appUser.userId = :userId").append(" AND ");
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        providerUsersCriteriaJpaQl.append("ausc.key.providerId = :providerId_").append(providerId)
                .append("AND ausc.key.providerUserId IN (:providerUserIds_").append(providerId).append(")");
        if (it.hasNext()) {
            providerUsersCriteriaJpaQl.append(" OR ");
        }
    }
    providerUsersCriteriaJpaQl.append(" ORDER BY ausc.key.providerId, ausc.rank");
    TypedQuery<AppUserSocialConnection> query = entityManager
            .createQuery(providerUsersCriteriaJpaQl.toString(), AppUserSocialConnection.class)
            .setParameter("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();
        query.setParameter(("providerId_" + providerId), providerId)
                .setParameter(("providerUserIds_" + providerId), entry.getValue());
    }
    List<Connection<?>> resultList = appUserSocialConnectionsToConnections(query.getResultList());
    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:org.mitreid.multiparty.web.ClientController.java

@RequestMapping(value = "/fetch", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_FORM_URLENCODED_VALUE)
public String fetch(@RequestParam("resource") String resource, Model m, HttpSession session) {

    // get the access token if we have one
    String accessTokenValue = acccessTokenService.getAccessToken(resource);

    // send our request to the resource

    HttpHeaders headers = new HttpHeaders();
    if (!Strings.isNullOrEmpty(accessTokenValue)) {
        headers.add("Authorization", "Bearer " + accessTokenValue);
    }//  w w w  .  ja  v  a2 s .co  m

    @SuppressWarnings("rawtypes")
    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(resource, HttpMethod.GET, request,
            String.class);

    if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
        // if we get back data, display it
        JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
        m.addAttribute("label", rso.get("label").getAsString());
        m.addAttribute("value", rso.get("value").getAsString());
        return "home";
    } else {
        // if we get back an error, try to get an access token
        List<String> authHeaders = responseEntity.getHeaders().get(HttpHeaders.WWW_AUTHENTICATE);
        // assume there's only one auth header for now
        String authHeader = Iterators.getOnlyElement(authHeaders.iterator());

        // parse the header to get the good bits
        String authServerUri = null;
        String ticket = null;
        Iterable<String> parts = Splitter.on(",").split(authHeader.substring("UMA ".length()));
        for (String part : parts) {
            List<String> subparts = Splitter.on("=").splitToList(part.trim());
            if (subparts.get(0).equals("as_uri")) {
                authServerUri = subparts.get(1);
                // strip quotes
                authServerUri = authServerUri.substring(1, authServerUri.length() - 1);
            } else if (subparts.get(0).equals("ticket")) {
                ticket = subparts.get(1);
                // strip quotes
                ticket = ticket.substring(1, ticket.length() - 1);
            }
        }

        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(authServerUri);

        // find the client configuration (maybe register)
        RegisteredClient client = clientConfig.getClientConfiguration(server);

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

        // send request to the token endpoint
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("client_id", client.getClientId());
        params.add("client_secret", client.getClientSecret());
        params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation");
        params.add("ticket", ticket);
        //params.add("scope", "read write");

        HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders);

        ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(),
                tokenRequest, String.class);
        JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject();

        if (o.has("error")) {
            if (o.get("error").getAsString().equals("need_info")) {
                // if we get need info, redirect

                JsonObject details = o.get("error_details").getAsJsonObject();

                // this is the URL to send the user to
                String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString();
                String newTicket = details.get("ticket").getAsString();

                // set a state value for our return
                String state = UUID.randomUUID().toString();
                session.setAttribute(STATE_SESSION_VAR, state);

                // save bits about the request we were trying to make
                session.setAttribute(RESOURCE_SESSION_VAR, resource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, authServerUri);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint)
                        .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket)
                        .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt
                        .queryParam("state", state);

                return "redirect:" + builder.build();
            } else {
                // it's an error we don't know how to deal with, give up
                logger.error("Unknown error from token endpoint: " + o.get("error").getAsString());
                return "home";
            }
        } else {
            // if we get an access token, try it again

            accessTokenValue = o.get("access_token").getAsString();
            acccessTokenService.saveAccesstoken(resource, accessTokenValue);

            headers = new HttpHeaders();
            if (!Strings.isNullOrEmpty(accessTokenValue)) {
                headers.add("Authorization", "Bearer " + accessTokenValue);
            }

            request = new HttpEntity<>(headers);

            responseEntity = restTemplate.exchange(resource, HttpMethod.GET, request, String.class);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                // if we get back data, display it
                JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
                m.addAttribute("label", rso.get("label").getAsString());
                m.addAttribute("value", rso.get("value").getAsString());
                return "home";
            } else {
                logger.error("Unable to get a token");
                return "home";
            }
        }

    }

}

From source file:org.apigw.util.OAuthTestHelper.java

private MultiValueMap<String, String> getTokenFormData(String clientId, String redirectUri, String code,
        String scope) {/*from w  ww  .  j  a v  a2s . c o m*/
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "authorization_code");
    formData.add("client_id", clientId);
    formData.add("scope", scope);
    formData.add("redirect_uri", redirectUri);
    formData.add("state", "gzzFqB!!!");
    if (code != null) {
        formData.add("code", code);
    }
    return formData;
}