Example usage for org.springframework.util MultiValueMap toSingleValueMap

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

Introduction

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

Prototype

Map<K, V> toSingleValueMap();

Source Link

Document

Return a Map with the first values contained in this MultiValueMap .

Usage

From source file:org.n52.io.QueryParameters.java

/**
 * Creates an simple view on given query. The {@link MultiValueMap} is flattened to a single value map.
 * /*  w w  w. j  a va  2  s  . c  om*/
 * @param query
 *        the incoming query parameters.
 * @return a query parameters instance handling Web exceptions.
 * @see WebException
 */
public static IoParameters createFromQuery(MultiValueMap<String, String> query) {
    return createFromQuery(query.toSingleValueMap());
}

From source file:org.ff4j.spring.boot.resources.FF4jResource.java

@RequestMapping(value = ROOT + OPERATION_CHECK + ROOT
        + PATH_PARAM_UID, method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE)
@ApiOperation(value = "<b>Advanced check</b> feature toggle (parametrized)", response = Boolean.class)
@ApiResponses({ @ApiResponse(code = 200, message = "If feature is flipped"),
        @ApiResponse(code = 400, message = "Invalid parameter"),
        @ApiResponse(code = 404, message = "Feature not found") })
public ResponseEntity<Boolean> check(@PathVariable(value = PARAM_UID) String featureUID,
        @RequestParam MultiValueMap<String, String> formParams) {
    Map<String, String> map = formParams.toSingleValueMap();
    Boolean status = ff4JServices.check(featureUID, map);
    return new ResponseEntity<>(status, OK);
}

From source file:com.acc.storefront.controllers.integration.FraudUpdateController.java

@RequestMapping(value = "/integration/order_review_callback", method = RequestMethod.POST)
public void process(@RequestBody final MultiValueMap<String, String> bodyParameterMap,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    initializeSiteFromRequest(request);/*from   w w  w . j  av  a 2  s.  c  om*/

    try {
        acceleratorPaymentService.handleFraudUpdate(bodyParameterMap.toSingleValueMap());
    } finally {
        //Kill this session at the end of the request processing in order to reduce the server overhead, otherwise
        //this session will hang around until it's timed out.
        final HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.fbr.services.SecurityService.java

@Transactional
public String createLogin(final MultiValueMap<String, String> credentials, LoginResponse loginResponse) {
    UserDbType userDbType = null;/*from  w  ww.jav a2  s. co  m*/
    String password = "";
    UUID uuid = null;
    boolean isAppUser = false;
    final Map<String, String> credentialsMap = credentials.toSingleValueMap();
    for (Entry<String, String> nameValuePair : credentialsMap.entrySet()) {
        if (nameValuePair.getKey().equals("username")) {
            logger.debug("Username given is {0}" + nameValuePair.getValue());
            userDbType = userService.findUserName(nameValuePair.getValue());
        } else if (nameValuePair.getKey().equals("password")) {
            logger.debug("password given is {0}" + nameValuePair.getValue());
            password = nameValuePair.getValue();
        } else if (nameValuePair.getKey().equals("uuid")) {
            logger.debug("uuid given is {0}" + nameValuePair.getValue());
            uuid = UUID.fromString(nameValuePair.getValue());
            isAppUser = true;
        }
    }
    if (isAppUser) {
        userDbType = licenseService.validateUUID(uuid);
        logger.debug("uuid " + uuid + " validated");
    } else {
        userService.validatePassword(userDbType, password);

        logger.debug("password is validated");
    }
    int companyId = userDbType.getCompanyDbType().getCompanyId();
    loginResponse.setCompanyId(companyId);
    loginResponse.setRole(userDbType.getRole());

    SessionDbType sessionDbType = new SessionDbType();
    Date now = new Date();
    sessionDbType.setCreationTime(now);
    sessionDbType.setLastAccessTime(now);
    sessionDbType.setUserDbType(userDbType);
    sessionDao.add(sessionDbType);

    return sessionDbType.getId();
}

From source file:com.httpMessageConvert.FormHttpMessageConverter.java

public Object read(Class<? extends Object> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : this.charset;
    String body = StreamUtils.copyToString(inputMessage.getBody(), charset);

    String[] pairs = StringUtils.tokenizeToStringArray(body, "&");

    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);

    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(URLDecoder.decode(pair, charset.name()), null);
        } else {/*from   ww w.j  a  v  a  2  s.c  o  m*/
            String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
            String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
            result.add(name, value);
        }
    }

    Map<String, String> map = result.toSingleValueMap();
    String json = JSONObject.toJSONString(map);
    JavaType javaType = getJavaType(clazz, null);
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(json, javaType);
}

From source file:org.cloudfoundry.identity.uaa.login.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();/* ww w  .  j a  v  a2  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"));

    validateToken("access_token", params.toSingleValueMap(), scopes);
    validateToken("id_token", params.toSingleValueMap(), scopes);
}

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   www. j  ava2 s.  co  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:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java

public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
        throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException,
        OAuth2AccessDeniedException {

    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details;

    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    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));
        }//  w  w w.j a  va  2  s .  c o  m
    } 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 ResponseExtractor<ResponseEntity<Void>>() {
        @Override
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            if (response.getHeaders().containsKey("Set-Cookie")) {
                copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
            }
            return delegate.extractData(response);
        }
    };
    // 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:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java

@Test
public void testFormEncodedAutologinRequest() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class);

    String autologinCode = (String) autologinResponseEntity.getBody().get("code");
    assertEquals(10, autologinCode.length());
}

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   www  . j a  v a 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" });
}