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:com.thoughtworks.go.server.domain.AgentInstances.java

public LinkedMultiValueMap<String, ElasticAgentMetadata> allElasticAgentsGroupedByPluginId() {
    LinkedMultiValueMap<String, ElasticAgentMetadata> map = new LinkedMultiValueMap<>();

    for (Map.Entry<String, AgentInstance> entry : agentInstances.entrySet()) {
        AgentInstance agentInstance = entry.getValue();
        if (agentInstance.isElastic()) {
            ElasticAgentMetadata metadata = agentInstance.elasticAgentMetadata();
            map.add(metadata.elasticPluginId(), metadata);
        }//from  ww w.j a v  a  2 s  .c o  m
    }

    return map;
}

From source file:eionet.webq.service.CDREnvelopeServiceImpl.java

/**
 * Transform raw envelope service response to usable form.
 *
 * @param response service response//from w ww.  jav a2 s .  com
 * @return {@link XmlFile} grouped by xml schema.
 */
@SuppressWarnings("unchecked")
private MultiValueMap<String, XmlFile> transformGetXmlFilesResponse(Object response) {
    LinkedMultiValueMap<String, XmlFile> result = new LinkedMultiValueMap<String, XmlFile>();
    if (response != null) {
        try {
            for (Map.Entry<String, Object[]> entry : ((Map<String, Object[]>) response).entrySet()) {
                String xmlSchema = entry.getKey();
                for (Object values : entry.getValue()) {
                    Object[] xmlFileData = (Object[]) values;
                    result.add(xmlSchema, new XmlFile(xmlFileData[0].toString(), xmlFileData[1].toString()));
                }
            }
        } catch (ClassCastException e) {
            LOGGER.error("received response=" + response);
            throw new CDREnvelopeException("unexpected response format from CDR envelope service.", e);
        }
    } else {
        LOGGER.warn("expected not null response from envelope service");
    }
    LOGGER.info("Xml files received=" + result);
    return result;
}

From source file:eionet.webq.web.controller.cdr.IntegrationWithCDRController.java

/**
 * WebQEdit request handler.//from  w  w  w  .j  ava2 s .c om
 *
 * @param request current request
 * @param model   model
 * @return view name
 * @throws FileNotAvailableException if remote file not available.
 */
@RequestMapping("/WebQEdit")
public String webQEdit(HttpServletRequest request, Model model) throws FileNotAvailableException {
    CdrRequest parameters = convertAndPutResultIntoSession(request);

    LOGGER.info("Received WebQEdit request with parameters:" + parameters.toString());

    String schema = parameters.getSchema();
    if (StringUtils.isEmpty(schema)) {
        throw new IllegalArgumentException("schema parameter is required");
    }

    Collection<ProjectFile> webForms = webFormService.findWebFormsForSchemas(Arrays.asList(schema));
    if (webForms.isEmpty()) {
        throw new IllegalArgumentException("no web forms for '" + schema + "' schema found");
    }
    String instanceUrl = parameters.getInstanceUrl();
    String fileName = parameters.getInstanceName();
    if (webForms.size() > 1) {
        LinkedMultiValueMap<String, XmlFile> xmlFiles = new LinkedMultiValueMap<String, XmlFile>();
        xmlFiles.add(schema, new XmlFile(instanceUrl, fileName));
        return deliverMenu(webForms, xmlFiles, parameters, model);
    }
    return editFile(webForms.iterator().next(), fileName, instanceUrl, parameters);
}

From source file:io.syndesis.runtime.ExtensionsITCase.java

private MultiValueMap<String, Object> multipartBody(byte[] data) {
    LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("file", new InputStreamResource(new ByteArrayInputStream(data)));
    return multipartData;
}

From source file:org.cloudfoundry.identity.uaa.integration.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.toSingleValueMap(), 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");
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), String.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    int cookiesAdded = 0;
    headers = getAppBasicAuthHttpHeaders();
    for (String cookie : cookies) {
        if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) {
            headers.add("Cookie", cookie);
            cookiesAdded++;/*from  ww  w.  j  av  a 2s.c  om*/
        }
    }
    assertEquals(2, cookiesAdded);

    //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")
                .queryParam(DEFAULT_CSRF_COOKIE_NAME,
                        IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody()))
                .build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), String.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").build().toUriString();

    MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>();
    tokenParams.add("response_type", "token");
    tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
    tokenParams.add("code", newCode);
    tokenParams.add("redirect_uri", appUrl);
    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers,
            HttpMethod.POST, new URI(tokenUrl));
    ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();

    BasicCookieStore cookieStore = new BasicCookieStore();
    ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, loginResponse);
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf);

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem(startsWith("JSESSIONID")));
    assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf")));
    if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) {
        assertThat(cookies, hasItem(startsWith("Saved-Account-")));
    }
    assertThat(cookies, hasItem(startsWith("Current-User")));
    cookieStore.clear();
    setCookiesFromResponse(cookieStore, loginResponse);
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

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

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 w  w .  j a  v a2 s  .c  om
    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.integration.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", "uaa.user"));

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

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

@Test
public void testInvalidSaml2Bearer() throws Exception {
    SamlIdentityProviderDefinition idpDef = createLocalSamlIdpDefinition(IDP_ENTITY_ID, "uaa");
    @SuppressWarnings("unchecked")
    IdentityProvider<SamlIdentityProviderDefinition> provider = IntegrationTestUtils.createIdentityProvider(
            "Local SAML IdP", IDP_ENTITY_ID, true, this.baseUrl, this.serverRunning, idpDef);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    postBody.add("client_id", "oauth_showcase_saml2_bearer");
    postBody.add("client_secret", "secret");
    postBody.add("assertion",
            "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDI6QXNzZXJ0aW9uIHhtbG5zOnNhbWwyPS"
                    + "J1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIiBJRD0iXzBkNzhhYTdhLTY4MzctNDUyNi1iNTk4"
                    + "LTliZGE0MTI5NTE0YiIgSXNzdWVJbnN0YW50PSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIFZlcnNpb249IjIuMC"
                    + "IgeG1sbnM6eHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIj48c2FtbDI6SXNzdWVyPmNsb3VkZm91"
                    + "bmRyeS1zYW1sLWxvZ2luPC9zYW1sMjpJc3N1ZXI-PHNhbWwyOlN1YmplY3Q-PHNhbWwyOk5hbWVJRCBGb3JtYXQ9In"
                    + "VybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMTpuYW1laWQtZm9ybWF0OnVuc3BlY2lmaWVkIj5Vbml0VGVzdFRlc3RV"
                    + "c2VyPC9zYW1sMjpOYW1lSUQ-PHNhbWwyOlN1YmplY3RDb25maXJtYXRpb24gTWV0aG9kPSJ1cm46b2FzaXM6bmFtZX"
                    + "M6dGM6U0FNTDoyLjA6Y206YmVhcmVyIj48c2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbkRhdGEgTm90T25PckFmdGVy"
                    + "PSIyMDE3LTExLTIyVDIyOjAyOjMwLjI5NloiIFJlY2lwaWVudD0iaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYX"
                    + "V0aC90b2tlbiIvPjwvc2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWwyOlN1YmplY3Q-PHNhbWwyOkNvbmRp"
                    + "dGlvbnMgTm90QmVmb3JlPSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIE5vdE9uT3JBZnRlcj0iMjAxNy0xMS0yMl"
                    + "QyMjowMjozMC4yOTZaIj48c2FtbDI6QXVkaWVuY2VSZXN0cmljdGlvbj48c2FtbDI6QXVkaWVuY2U-aHR0cDovL2xv"
                    + "Y2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbjwvc2FtbDI6QXVkaWVuY2U-PC9zYW1sMjpBdWRpZW5jZVJlc3RyaW"
                    + "N0aW9uPjwvc2FtbDI6Q29uZGl0aW9ucz48c2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdHRyaWJ1dGUg"
                    + "TmFtZT0iR3JvdXBzIj48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMD"
                    + "AxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LndyaXRlPC9zYW1sMjpBdHRy"
                    + "aWJ1dGVWYWx1ZT48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1"
                    + "hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LnJlYWQ8L3NhbWwyOkF0dHJpYnV0"
                    + "ZVZhbHVlPjwvc2FtbDI6QXR0cmlidXRlPjwvc2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdXRoblN0YX"
                    + "RlbWVudCBBdXRobkluc3RhbnQ9IjIwMTYtMTEtMjJUMjI6MDI6MzAuMjk5WiIgU2Vzc2lvbk5vdE9uT3JBZnRlcj0i"
                    + "MjAxNi0xMi0yMlQyMjowMjozMC4yOTlaIj48c2FtbDI6QXV0aG5Db250ZXh0PjxzYW1sMjpBdXRobkNvbnRleHRDbG"
                    + "Fzc1JlZj51cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZDwvc2FtbDI6QXV0aG5D"
                    + "b250ZXh0Q2xhc3NSZWY-PC9zYW1sMjpBdXRobkNvbnRleHQ-PC9zYW1sMjpBdXRoblN0YXRlbWVudD48L3NhbWwyOk"
                    + "Fzc2VydGlvbj4");

    try {/*from  w  w w .  jav  a2s. co m*/
        restOperations.exchange(baseUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(postBody, headers),
                Void.class);
    } catch (HttpClientErrorException he) {
        Assert.assertEquals(HttpStatus.UNAUTHORIZED, he.getStatusCode());
    }

    provider.setActive(false);
    IntegrationTestUtils.updateIdentityProvider(this.baseUrl, this.serverRunning, provider);
}

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

@Test
public void testValidSaml2Bearer() throws Exception {
    SamlIdentityProviderDefinition idpDef = createLocalSamlIdpDefinition(IDP_ENTITY_ID, "uaa");
    @SuppressWarnings("unchecked")
    IdentityProvider<SamlIdentityProviderDefinition> provider = IntegrationTestUtils.createIdentityProvider(
            "Local SAML IdP", IDP_ENTITY_ID, true, this.baseUrl, this.serverRunning, idpDef);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    postBody.add("client_id", "oauth_showcase_saml2_bearer");
    postBody.add("client_secret", "secret");
    postBody.add("assertion", samlTestUtils.mockAssertionEncoded(IDP_ENTITY_ID,
            "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", "Saml2BearerIntegrationUser",
            "http://localhost:8080/uaa/oauth/token/alias/cloudfoundry-saml-login", "cloudfoundry-saml-login"));

    ResponseEntity<CompositeAccessToken> token = restOperations.exchange(
            baseUrl + "/oauth/token/alias/cloudfoundry-saml-login", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), CompositeAccessToken.class);

    Assert.assertEquals(HttpStatus.OK, token.getStatusCode());
    Assert.assertTrue(token.hasBody());/*from   ww w .j  a  v a 2 s.  c  om*/
    provider.setActive(false);
    IntegrationTestUtils.updateIdentityProvider(this.baseUrl, this.serverRunning, provider);
}

From source file:org.cloudfoundry.identity.uaa.integration.OpenIdTokenAuthorizationWithApprovalIntegrationTests.java

@Test
public void testOpenIdTokenUsingLoginClientOauthTokenEndpoint() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "app");
    postBody.add("client_secret", "appclientsecret");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("source", "login");
    postBody.add("user_id", user.getId());
    postBody.add("add_new", "false");

    ResponseEntity<Map> responseEntity = loginClient.exchange(serverRunning.getBaseUrl() + "/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"));
}