Example usage for org.springframework.util LinkedMultiValueMap add

List of usage examples for org.springframework.util LinkedMultiValueMap add

Introduction

In this page you can find the example usage for org.springframework.util LinkedMultiValueMap add.

Prototype

@Override
    public void add(K key, @Nullable V value) 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.login.feature.ImplicitGrantIT.java

@Test
public void testDefaultScopes() 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");
    postBody.add("source", "credentials");
    postBody.add("username", testAccounts.getUserName());
    postBody.add("password", testAccounts.getPassword());

    ResponseEntity<Void> responseEntity = restOperations.exchange(baseUrl + "/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 ava  2s .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"));

    Jwt access_token = JwtHelper.decode(params.getFirst("access_token"));

    Map<String, Object> claims = new ObjectMapper().readValue(access_token.getClaims(),
            new TypeReference<Map<String, Object>>() {
            });

    Assert.assertThat((String) claims.get("jti"), is(params.getFirst("jti")));
    Assert.assertThat((String) claims.get("client_id"), is("cf"));
    Assert.assertThat((String) claims.get("cid"), is("cf"));
    Assert.assertThat((String) claims.get("user_name"), is(testAccounts.getUserName()));

    Assert.assertThat(((List<String>) claims.get("scope")), containsInAnyOrder(scopes));

    Assert.assertThat(((List<String>) claims.get("aud")),
            containsInAnyOrder("cf", "scim", "openid", "cloud_controller", "password"));
}

From source file:net.gplatform.spring.social.weibo.connect.WeiboOAuth2Template.java

@Override
protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
    HttpMessageConverter<?> messageConverter = new FormHttpMessageConverter() {

        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override/* ww w  . j  av  a  2 s. c  o  m*/
        public boolean canRead(Class<?> clazz, MediaType mediaType) {
            return true;
        }

        @Override
        public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz,
                HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

            TypeReference<Map<String, ?>> mapType = new TypeReference<Map<String, ?>>() {
            };
            LinkedHashMap<String, ?> readValue = objectMapper.readValue(inputMessage.getBody(), mapType);
            LinkedMultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>();
            for (Entry<String, ?> currentEntry : readValue.entrySet()) {
                result.add(currentEntry.getKey(), currentEntry.getValue().toString());
            }
            return result;
        }
    };

    restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
    return restTemplate;
}

From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

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

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    ResponseEntity<Map> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());/*from   ww w. ja v a2  s. co  m*/
    headers = getAppBasicAuthHttpHeaders();
    headers.add("Cookie", cookies.get(0));

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true").build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token")
            .queryParam("response_type", "token").queryParam("grant_type", "authorization_code")
            .queryParam("code", newCode).queryParam("redirect_uri", appUrl).build().toUriString();

    ResponseEntity<Map> tokenResponse = template.exchange(tokenUrl, HttpMethod.POST,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    ResponseEntity<Void> loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());
    headers.clear();
    headers.add("Cookie", cookies.get(0));
    restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, headers), Void.class);

    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:info.smartkit.hairy_batman.query.KJsonApiQuery.java

private LinkedMultiValueMap<String, String> getParameters() {
    LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    this.queriedSubscriber = this.subscribers.remove(0);
    LOG.info("this.queriedSubscriber: " + this.queriedSubscriber.toString());
    parameters.add("urls", this.queriedSubscriber.getArticleUrl());
    // "http://mp.weixin.qq.com/s?__biz=MjM5ODE4MTUzMg==&mid=202895379&idx=1&sn=a46187dd2e3fc704b72277dbf863f356&3rd=MzA3MDU4NTYzMw==&scene=6#rd");
    return parameters;
}

From source file:com.github.notizklotz.derbunddownloader.download.IssueDownloadService.java

private boolean checkUserAccount() {
    if (BuildConfig.DEBUG) {
        Log.d(LOG_TAG, "Checking user account validity");
    }//from www .j  a v a  2s  .c  o m

    try {
        final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        final String username = sharedPref.getString(Settings.KEY_USERNAME, "");
        final String password = sharedPref.getString(Settings.KEY_PASSWORD, "");

        RestTemplate restTemplate = new RestTemplate(true);
        LinkedMultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
        form.add("user", username);
        form.add("password", password);
        form.add("dologin", "1");
        form.add("t", "");

        String response = restTemplate.postForObject("http://epaper.derbund.ch", form, String.class);
        boolean loginSuccessful = response.contains("flashcontent");
        Log.d(LOG_TAG, "Login successful? " + loginSuccessful);
        return loginSuccessful;
    } catch (RestClientException e) {
        Log.e(LOG_TAG, "Error while trying to login", e);
        return false;
    }
}

From source file:com.sybase365.mobiliser.custom.project.channels.HttpChannelEnd.java

@SuppressWarnings("unchecked")
@Override//from  w  ww . j  a  v a2 s.com
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:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java

@Test
public void testPasswordGrant() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes()));

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", basicDigestHeaderValue);

    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("grant_type", "password");
    postBody.add("username", user.getUserName());
    postBody.add("password", "secret");

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

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

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("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, scopes);
    validateToken("id_token", params, scopes);
}

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 w w w  .  j  a  va2  s  .  com*/
    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.ezsource_mobile.fileservice.FileService.java

public FileUploadResponse[] uploadFile(final MultipartFile[] files, final String relativePath,
        final HttpServletRequest httpServletRequest) {
    LOGGER.debug("start of uploadFile method");

    final RestTemplate restTemplate = new RestTemplate();
    FileUploadResponse[] result;/*from w w w .j a  v a 2 s .co  m*/
    try {
        final String url = getFileUploadUrl(httpServletRequest);
        final String fileName = files[0].getOriginalFilename();

        final LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        final ByteArrayResource contentsAsResource = new ByteArrayResource(files[0].getBytes()) {
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        body.add("files", contentsAsResource);

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Authorization",
                "Basic " + Base64.encodeBase64String(new StringBuilder(securityService.getUserName())
                        .append(":").append(getHash()).toString().getBytes()));

        final HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<LinkedMultiValueMap<String, Object>>(
                body, headers);
        result = restTemplate.postForObject(url, request, FileUploadResponse[].class);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    LOGGER.debug("end of uploadFile method" + result);
    return result;

}

From source file:de.tudarmstadt.ukp.csniper.webapp.evaluation.EvaluationRepository.java

/**
 * Persist the given items. If they already exist in the database, replace the item in the list
 * with the item from the database. Transient data (e.g. match offsets) is preserved.
 * // w ww  .  j a  v a2s.co m
 * @param aCreate
 *            true = missing evaluation items are created and returned; false = missing
 *            evaluation items are not created and returned
 */
@Transactional
public List<EvaluationItem> writeEvaluationItems(List<EvaluationItem> aItems, boolean aCreate) {
    long start = System.currentTimeMillis();

    log.info("Building index on in-memory items");
    List<EvaluationItem> result = new ArrayList<EvaluationItem>(aItems.size());
    LinkedMultiValueMap<String, EvaluationItem> idx = new LinkedMultiValueMap<String, EvaluationItem>();
    for (EvaluationItem i : aItems) {
        idx.add(i.getCollectionId() + "-" + i.getDocumentId() + "-" + i.getType(), i);
    }

    TypedQuery<EvaluationItem> query = entityManager
            .createQuery("FROM EvaluationItem WHERE collectionId = :collectionId AND documentId = "
                    + ":documentId AND type = :type", EvaluationItem.class);

    log.info("Merging with in-database items in " + idx.size() + " chunks");
    ProgressMeter progress = new ProgressMeter(idx.size());
    for (List<EvaluationItem> items : idx.values()) {
        progress.next();
        EvaluationItem ref = items.get(0);
        List<EvaluationItem> pItems = query.setParameter("collectionId", ref.getCollectionId())
                .setParameter("documentId", ref.getDocumentId()).setParameter("type", ref.getType())
                .getResultList();

        Comparator<EvaluationItem> cmp = new Comparator<EvaluationItem>() {
            @Override
            public int compare(EvaluationItem aO1, EvaluationItem aO2) {
                if (aO1.getBeginOffset() > aO2.getBeginOffset()) {
                    return 1;
                } else if (aO1.getBeginOffset() < aO2.getBeginOffset()) {
                    return -1;
                } else if (aO1.getEndOffset() > aO2.getEndOffset()) {
                    return 1;
                } else if (aO1.getEndOffset() < aO2.getEndOffset()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        };

        Collections.sort(pItems, cmp);

        for (EvaluationItem item : items) {
            int i = Collections.binarySearch(pItems, item, cmp);
            if (i < 0) {
                if (aCreate) {
                    entityManager.persist(item);
                    result.add(item);
                }
            } else {
                EvaluationItem pItem = pItems.get(i);
                pItem.copyTransientData(item);
                result.add(pItem);
            }
        }

        log.info(progress);
    }

    log.info("writeEvaluationItems for " + aItems.size() + " items completed in "
            + (System.currentTimeMillis() - start) + " ms");

    return result;

    // String query = "FROM EvaluationItem WHERE collectionId = :collectionId AND documentId = "
    // +
    // ":documentId AND type = :type AND beginOffset = :beginOffset AND endOffset = :endOffset";
    // for (ListIterator<EvaluationItem> li = aItems.listIterator(); li.hasNext();) {
    // EvaluationItem item = li.next();
    // try {
    // EvaluationItem pItem = entityManager.createQuery(query, EvaluationItem.class)
    // .setParameter("collectionId", item.getCollectionId())
    // .setParameter("documentId", item.getDocumentId())
    // .setParameter("type", item.getType())
    // .setParameter("beginOffset", item.getBeginOffset())
    // .setParameter("endOffset", item.getEndOffset()).getSingleResult();
    //
    // // if item already exists, use that instead of persisting the new
    // pItem.copyTransientData(item);
    // li.set(pItem);
    // }
    // catch (NoResultException e) {
    // // persist item if not exists
    // if (aCreate) {
    // entityManager.persist(item);
    // }
    // }
    // }
}