Example usage for org.springframework.util MultiValueMap get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.unidle.social.ConnectionRepositoryImplTest.java

@Test
public void testFindConnectionsToUsers() throws Exception {
    final MultiValueMap<String, String> providerUserIds = new LinkedMultiValueMap<>();
    providerUserIds.add("twitter", "provider user id 1");
    providerUserIds.add("twitter", "provider user id 2");
    providerUserIds.add("twitter", "provider user id 3");
    providerUserIds.add("facebook", "provider user id 4");

    final MultiValueMap<String, Connection<?>> result = subject.findConnectionsToUsers(providerUserIds);

    assertThat(result).hasSize(2).satisfies(containsKey("twitter")).satisfies(containsKey("facebook"));
    assertThat(result.get("twitter")).hasSize(3);
    assertThat(result.get("twitter").get(0)).isNotNull();
    assertThat(result.get("twitter").get(1)).isNotNull();
    assertThat(result.get("twitter").get(2)).isNull();
    assertThat(result.get("facebook")).hasSize(1);
    assertThat(result.get("facebook").get(0)).isNull();
}

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();/*from www. j  a va2  s  .  co  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.sybase365.mobiliser.custom.project.channels.HttpChannelEnd.java

@SuppressWarnings("unchecked")
@Override//from  w  w w.  ja  v a 2  s .c o  m
public void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("Incoming {} request", request.getMethod());

    checkAndPrepare(request, response, false);

    final MultiValueMap<String, String> result = (MultiValueMap<String, String>) this.converter.read(null,
            new ServletServerHttpRequest(request));

    final List<String> textList = result.get("text");
    final List<String> fromList = result.get("from");
    final List<String> toList = result.get("to");
    final List<String> typeList = result.get("type");

    if (textList == null || textList.isEmpty()) {
        throw new MissingServletRequestParameterException("text", "string");
    }

    if (fromList == null || fromList.isEmpty()) {
        throw new MissingServletRequestParameterException("from", "string");
    }

    if (toList == null || toList.isEmpty()) {
        throw new MissingServletRequestParameterException("to", "string");
    }

    final String type;
    if (null == typeList || typeList.isEmpty()) {
        type = "sms";
    } else {
        type = typeList.get(0);
    }

    final Message req = this.messagingEngine.parseSimpleTextMessage(type, textList.get(0));
    req.setSender(fromList.get(0));
    req.setRecipient(toList.get(0));

    if (LOG.isDebugEnabled()) {
        LOG.debug("{} message received for {} from {}",
                new Object[] { type, req.getRecipient(), req.getSender() });
    }

    final Future<Message> responseMessage = this.receiveCallback.receiveAndRespondMessage(req, this.channelId,
            this.incomingChannelId);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Handed off message to {} for {} awaiting response", this.receiveCallback,
                this.incomingChannelId);
    }

    final Message message;
    try {
        message = responseMessage.get();

        if (message == null) {
            LOG.warn("Timed out waiting for response from {}", responseMessage);

            throw new NestedServletException("Timed out waiting for message");
        }
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt(); // reset flag

        throw new NestedServletException("Interrupted during processing", e);

    } catch (final ExecutionException e) {
        if (e.getCause() instanceof InterruptedException) {
            throw new NestedServletException( // NOSONAR
                    "Interrupted during processing", e.getCause());
        }

        throw new NestedServletException("Processing message failed", // NOSONAR
                e.getCause());
    }

    LOG.debug("Writing response back to client");

    final LinkedMultiValueMap<String, Object> responseMap = new LinkedMultiValueMap<String, Object>();

    responseMap.add("from", message.getSender().getAddress());
    responseMap.add("to", message.getRecipient().getAddress());

    if (message instanceof SmsMessage) {
        responseMap.add("text", new String(((SmsMessage) message).getText().getContent(),
                ((SmsMessage) message).getText().getCharset()));
    } else if (message instanceof UssdTextMessage) {
        responseMap.add("text", new String(((UssdTextMessage) message).getText().getContent(),
                ((UssdTextMessage) message).getText().getCharset()));
    }

    this.converter.write(responseMap, this.mediaType, new ServletServerHttpResponse(response));

}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private Header[] convertHeaders(MultiValueMap<String, String> headers) {
    List<Header> list = new ArrayList<>();
    for (String name : headers.keySet()) {
        for (String value : headers.get(name)) {
            list.add(new BasicHeader(name, value));
        }/*  w w  w  .  j av  a  2  s . c o m*/
    }
    return list.toArray(new BasicHeader[0]);
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.restapi.PublisherController.java

@ApiOperation(value = "Exposes H2O scoring engine model for download as JAR file", notes = "Privilege level: Any consumer of this endpoint must have a valid access token")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = FileSystemResource.class),
        @ApiResponse(code = 400, message = "Request was malformed"),
        @ApiResponse(code = 500, message = "Internal server error, e.g. error building or publishing model") })
@RequestMapping(method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded", value = "/rest/h2o/engines/{modelName}/downloads", produces = "application/java-archive")
@ResponseBody/*from w w w  .j  av a 2  s . co  m*/
public FileSystemResource downloadEngine(@Valid @RequestBody MultiValueMap<String, String> request,
        @PathVariable String modelName) throws EngineBuildingException, ValidationException {

    LOGGER.info("Got download request: " + request + " modelName:" + modelName);
    validationRules.forEach(rule -> rule.validate(request));

    BasicAuthServerCredentials h2oServerCredentials = new BasicAuthServerCredentials(request.get("host").get(0),
            request.get("username").get(0), request.get("password").get(0));

    return new FileSystemResource(publisher.getScoringEngineJar(h2oServerCredentials, modelName).toFile());
}

From source file:org.unidle.social.ConnectionRepositoryImpl.java

@Override
@Transactional(readOnly = true)/*from   ww  w  . ja v  a  2s .  c o  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:net.acesinc.convergentui.content.ContentFetchCommand.java

@Override
protected ContentResponse run() throws Exception {
    log.debug("Getting live content from [ " + location + " ]");
    try {//w w  w  . j a  v  a2 s. c  o  m
        HttpServletRequest request = requestContext.getRequest();
        MultiValueMap<String, String> headers = this.helper.buildZuulRequestHeaders(request);

        if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
            MultiValueMap<String, String> params = this.helper.buildZuulRequestQueryParams(request);
        }

        HttpHeaders requestHeaders = new HttpHeaders();
        for (String key : headers.keySet()) {
            for (String s : headers.get(key)) {
                requestHeaders.add(key, s);
            }
        }
        HttpEntity requestEntity = new HttpEntity(null, requestHeaders);

        ResponseEntity<Object> exchange = this.restTemplate.exchange(location, HttpMethod.GET, requestEntity,
                Object.class);

        ContentResponse response = new ContentResponse();
        response.setContent(exchange.getBody());
        response.setContentType(exchange.getHeaders().getContentType());
        response.setError(false);

        return response;
    } catch (Exception e) {
        log.debug("Error fetching live content from [ " + location + " ]", e);
        throw e;
    }
}

From source file:org.awesomeagile.webapp.security.AwesomeAgileConnectionRepositoryTest.java

@Test
public void testFindAllConnections() throws Exception {
    Connection connection = mock(Connection.class);
    ArgumentCaptor<ConnectionData> connectionDataCaptor = ArgumentCaptor.forClass(ConnectionData.class);
    when(connectionFactoryOne.createConnection(connectionDataCaptor.capture())).thenReturn(connection);
    MultiValueMap<String, Connection<?>> allConnections = connectionRepository.findAllConnections();
    assertNotNull(allConnections);/*from   w  ww.  j  a  v  a  2s  .  c  o  m*/
    assertEquals(1, allConnections.size());
    List<Connection<?>> providerOneConnections = allConnections.get(PROVIDER_ONE);
    assertThat(providerOneConnections, contains(connection));
    ConnectionData connectionData = connectionDataCaptor.getValue();
    assertConnectionData(user(), connectionData);
}

From source file:jails.http.converter.FormHttpMessageConverter.java

private boolean isMultipart(MultiValueMap<String, ?> map, MediaType contentType) {
    if (contentType != null) {
        return MediaType.MULTIPART_FORM_DATA.equals(contentType);
    }// w w w  .  jav  a  2 s.c o  m
    for (String name : map.keySet()) {
        for (Object value : map.get(name)) {
            if (value != null && !(value instanceof String)) {
                return true;
            }
        }
    }
    return false;
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private MultiValueMap<String, String> revertHeaders(Header[] headers) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    for (Header header : headers) {
        String name = header.getName();
        if (!map.containsKey(name)) {
            map.put(name, new ArrayList<String>());
        }/* w  w w .j ava2  s . c  om*/
        map.get(name).add(header.getValue());
    }
    return map;
}