Example usage for org.springframework.util MultiValueMap getFirst

List of usage examples for org.springframework.util MultiValueMap getFirst

Introduction

In this page you can find the example usage for org.springframework.util MultiValueMap getFirst.

Prototype

@Nullable
V getFirst(K key);

Source Link

Document

Return the first value for the given key.

Usage

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Performs a simple search and serves the result as XML to be read by an RSS reader
 *
 * @param request HttpServletRequest/*from   w  w w.ja v  a2  s  .  co m*/
 * @param model   model that will be passed to the template
 * @param site    site the request originates from
 * @param params  search parameters identical to the {@code search} method
 * @return RSS view of articles returned by the search
 * @throws IOException
 */
@RequestMapping(name = "searchFeed", value = "/search/feed/{feedType:atom|rss}", params = {
        "q" }, method = RequestMethod.GET)
public ModelAndView getSearchRssFeedView(HttpServletRequest request, Model model, @SiteParam Site site,
        @PathVariable String feedType, @RequestParam MultiValueMap<String, String> params) throws IOException {
    CommonParams commonParams = modelCommonParams(request, model, site, params, false);

    String queryString = params.getFirst("q");
    ArticleSearchQuery.Builder query = ArticleSearchQuery.builder().setQuery(queryString)
            .setSimple(commonParams.isSimpleSearch(queryString)).setIsRssSearch(true);
    commonParams.fill(query);
    ArticleSearchQuery queryObj = query.build();

    Map<String, ?> searchResults = solrSearchApi.search(queryObj, site);

    String feedTitle = representQueryParametersAsString(params);
    return getFeedModelAndView(site, feedType, feedTitle, searchResults);
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Performs an advanced search and serves the result as XML to be read by an RSS reader
 *
 * @param request HttpServletRequest//w  w  w .ja  va2  s  .c om
 * @param model   model that will be passed to the template
 * @param site    site the request originates from
 * @param params  search parameters identical to the {@code search} method
 * @return RSS view of articles returned by the search
 * @throws IOException
 */
@RequestMapping(name = "advancedSearchFeed", value = "/search/feed/{feedType:atom|rss}", params = {
        "unformattedQuery" }, method = RequestMethod.GET)
public ModelAndView getAdvancedSearchRssFeedView(HttpServletRequest request, Model model, @SiteParam Site site,
        @PathVariable String feedType, @RequestParam MultiValueMap<String, String> params) throws IOException {
    String queryString = params.getFirst("unformattedQuery");
    params.remove("unformattedQuery");
    params.add("q", queryString);
    return getSearchRssFeedView(request, model, site, feedType, params);
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Performs a csv export of a search.// w w  w. j  a  v  a 2  s .  co  m
 *
 * @param request HttpServletRequest
 * @param model   model that will contain search results
 * @param site    site the request originates from
 * @param params  all URL parameters
 * @return String indicating template location
 * @throws IOException
 */

@RequestMapping(name = "csvExport", value = "/csvExport", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public FileSystemResource csvExport(HttpServletRequest request, Model model, HttpServletResponse response,
        @SiteParam Site site, @RequestParam MultiValueMap<String, String> params) throws IOException {
    final Integer totalRows = Integer.parseInt(params.getFirst("rows"));
    final String filename = String.format("solrCsvExport-%s-q-%s.csv", Instant.now(), params.getFirst("q"));
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    return convertToCsvFile(collateCsvResults(request, model, site, params, totalRows));
}

From source file:org.ambraproject.wombat.controller.SearchController.java

private boolean performValidSearch(HttpServletRequest request, Model model, @SiteParam Site site,
        @RequestParam MultiValueMap<String, String> params, boolean isCsvExport) throws IOException {
    CommonParams commonParams = modelCommonParams(request, model, site, params, isCsvExport);

    String queryString = params.getFirst("q");
    ArticleSearchQuery.Builder query = ArticleSearchQuery.builder().setQuery(queryString)
            .setSimple(commonParams.isSimpleSearch(queryString)).setIsCsvSearch(isCsvExport);
    commonParams.fill(query);/*from  ww  w.  j  av  a 2  s.  c om*/
    ArticleSearchQuery queryObj = query.build();
    Map<?, ?> searchResults;
    try {
        searchResults = solrSearchApi.search(queryObj, site);
    } catch (ServiceRequestException sre) {
        model.addAttribute(
                isInvalidSolrRequest(queryString, sre) ? CANNOT_PARSE_QUERY_ERROR : UNKNOWN_QUERY_ERROR, true);
        return false; //not a valid search - report errors
    }

    if (!isCsvExport) {
        searchResults = solrSearchApi.addArticleLinks(searchResults, request, site, siteSet);
        addFiltersToModel(request, model, site, commonParams, queryObj, searchResults);
    }
    model.addAttribute("searchResults", searchResults);

    model.addAttribute("alertQuery", alertService.convertParamsToJson(params));
    return true; //valid search - proceed to return results
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * This is a catch for advanced searches originating from Old Ambra. It transforms the
 * "unformattedQuery" param into "q" which is used by Wombat's new search.
 * todo: remove this method and direct all advancedSearch requests to the simple search method
 *///from   w ww. jav  a 2s . c  o m
@RequestMapping(name = "advancedSearch", value = "/search", params = { "unformattedQuery", "!q" })
public String advancedSearch(HttpServletRequest request, Model model, @SiteParam Site site,
        @RequestParam MultiValueMap<String, String> params) throws IOException {
    String queryString = params.getFirst("unformattedQuery");
    params.remove("unformattedQuery");
    params.add("q", queryString);
    return search(request, model, site, params);
}

From source file:org.broadleafcommerce.core.web.api.endpoint.order.CartEndpoint.java

protected HashMap<String, String> getOptions(MultiValueMap<String, String> requestParams) {
    HashMap<String, String> productOptions = new HashMap<String, String>();

    //Fill up a map of key values that will represent product options
    Set<String> keySet = requestParams.keySet();
    for (String key : keySet) {
        if (requestParams.getFirst(key) != null) {
            //Product options should be returned with "productOption." as a prefix. We'll look for those, and 
            //remove the prefix.
            if (key.startsWith("productOption.")) {
                productOptions.put(StringUtils.removeStart(key, "productOption."), requestParams.getFirst(key));
            }/*from  w ww  . j  a v  a 2s.com*/
        }
    }
    return productOptions;
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.OpenIdTokenGrantsIT.java

@Test
public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Void> responseEntity = restOperations.exchange(loginUrl + "/oauth/authorize",
            HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();//from w  ww .java  2  s.  c  o m
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read", "uaa.user"));

    validateToken("access_token", params.toSingleValueMap(), scopes, aud);
    validateToken("id_token", params.toSingleValueMap(), openid, new String[] { "cf" });
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;//from w w  w  . j a v a 2  s  .c  o m
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        if (!addNew) {
            throw new LoginSAMLException("SAML user does not exist. "
                    + "You can correct this by creating a shadow user for the SAML user.", e);
        }
        // Register new users automatically
        publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
        try {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        } catch (UsernameNotFoundException ex) {
            throw new BadCredentialsException(
                    "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

protected UaaUser getUser(UaaPrincipal principal, MultiValueMap<String, String> userAttributes) {
    String name = principal.getName();
    String email = userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME);
    String givenName = userAttributes.getFirst(GIVEN_NAME_ATTRIBUTE_NAME);
    String familyName = userAttributes.getFirst(FAMILY_NAME_ATTRIBUTE_NAME);
    String phoneNumber = userAttributes.getFirst(PHONE_NUMBER_ATTRIBUTE_NAME);
    String userId = Origin.NotANumber;
    String origin = principal.getOrigin() != null ? principal.getOrigin() : Origin.LOGIN_SERVER;
    String zoneId = principal.getZoneId();
    if (name == null && email != null) {
        name = email;/* w  ww . j av a2 s.c o m*/
    }
    if (name == null && Origin.NotANumber.equals(userId)) {
        throw new BadCredentialsException("Cannot determine username from credentials supplied");
    } else if (name == null) {
        //we have user_id, name is irrelevant
        name = "unknown";
    }
    if (email == null) {
        if (name.contains("@")) {
            if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) {
                email = name;
            } else {
                email = name.replaceAll("@", "") + "@unknown.org";
            }
        } else {
            email = name + "@unknown.org";
        }
    }
    if (givenName == null) {
        givenName = email.split("@")[0];
    }
    if (familyName == null) {
        familyName = email.split("@")[1];
    }
    return new UaaUser(new UaaUserPrototype().withEmail(email).withGivenName(givenName)
            .withFamilyName(familyName).withPhoneNumber(phoneNumber).withModified(new Date()).withId(userId)
            .withUsername(name).withPassword("").withAuthorities(Collections.EMPTY_LIST).withCreated(new Date())
            .withOrigin(origin).withExternalId(name).withVerified(true).withZoneId(zoneId).withSalt(null)
            .withPasswordLastModified(null));
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void invalidScopeErrorMessageIsNotShowingAllClientScopes() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "openid";
    setUpClients(clientId, scopes, scopes, "authorization_code", true);

    String username = "testuser" + generator.generate();
    ScimUser developer = setUpUser(username, "scim.write", OriginKeys.UAA,
            IdentityZoneHolder.getUaaZone().getId());
    MockHttpSession session = getAuthenticatedSession(developer);

    String basicDigestHeaderValue = "Basic " + new String(
            org.apache.commons.codec.binary.Base64.encodeBase64((clientId + ":" + SECRET).getBytes()));

    String state = generator.generate();
    MockHttpServletRequestBuilder authRequest = get("/oauth/authorize")
            .header("Authorization", basicDigestHeaderValue).session(session)
            .param(OAuth2Utils.RESPONSE_TYPE, "code").param(OAuth2Utils.SCOPE, "scim.write")
            .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)
            .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI);

    MvcResult mvcResult = getMockMvc().perform(authRequest).andExpect(status().is3xxRedirection()).andReturn();

    UriComponents locationComponents = UriComponentsBuilder
            .fromUri(URI.create(mvcResult.getResponse().getHeader("Location"))).build();
    MultiValueMap<String, String> queryParams = locationComponents.getQueryParams();
    String errorMessage = URIUtil
            .encodeQuery("scim.write is invalid. Please use a valid scope name in the request");
    assertTrue(!queryParams.containsKey("scope"));
    assertEquals(errorMessage, queryParams.getFirst("error_description"));
}