Example usage for org.springframework.util MultiValueMap add

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

Introduction

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

Prototype

void add(K key, @Nullable V value);

Source Link

Document

Add the given single value to the current list of values for the given key.

Usage

From source file:org.kurento.repository.test.util.HttpRepositoryTest.java

protected void uploadFileWithMultiparts(String uploadURL, File fileToUpload) {

    RestTemplate template = getRestTemplate();

    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
    parts.add("file", new FileSystemResource(fileToUpload));

    ResponseEntity<String> entity = postWithRetries(uploadURL, template, parts);

    assertEquals("Returned response: " + entity.getBody(), HttpStatus.OK, entity.getStatusCode());
}

From source file:com.example.DatastoreSampleApplicationTests.java

private String sendRequest(String url, String json, HttpMethod method) {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("Content-Type", "application/json");

    HttpEntity<String> entity = new HttpEntity<>(json, map);
    ResponseEntity<String> response = this.restTemplate.exchange(url, method, entity, String.class);
    return response.getBody();
}

From source file:org.wallride.web.controller.admin.article.ArticleSearchForm.java

public MultiValueMap<String, String> toQueryParams() {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    if (StringUtils.hasText(keyword)) {
        params.add("keyword", keyword);
    }/*  w  w  w  .j  ava 2  s.  c om*/
    if (categoryId != null) {
        params.add("categoryId", Long.toString(categoryId));
    }
    if (tagId != null) {
        params.add("tagId", Long.toString(tagId));
    }
    if (authorId != null) {
        params.add("authorId", Long.toString(authorId));
    }
    if (status != null) {
        params.add("status", status.toString());
    }
    return params;
}

From source file:io.lavagna.web.security.login.PersonaLogin.java

@Override
public boolean doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (!("POST".equalsIgnoreCase(req.getMethod()) && req.getParameterMap().containsKey("assertion"))) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return true;
    }//from w  w  w  .  ja  va  2 s  .c om

    String audience = configurationRepository.getValue(Key.PERSONA_AUDIENCE);

    MultiValueMap<String, String> toPost = new LinkedMultiValueMap<>();
    toPost.add("assertion", req.getParameter("assertion"));
    toPost.add("audience", audience);
    VerifierResponse verifier = restTemplate.postForObject("https://verifier.login.persona.org/verify", toPost,
            VerifierResponse.class);

    if ("okay".equals(verifier.status) && audience.equals(verifier.audience)
            && userRepository.userExistsAndEnabled(USER_PROVIDER, verifier.email)) {
        String url = Redirector.cleanupRequestedUrl(req.getParameter("reqUrl"));
        UserSession.setUser(userRepository.findUserByName(USER_PROVIDER, verifier.email), req, resp,
                userRepository);
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/json");
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("redirectTo", new JsonPrimitive(url));
        resp.getWriter().write(jsonObject.toString());
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
    return true;
}

From source file:com.github.moscaville.contactsdb.controller.BaseController.java

public String saveItem(RecordWrapper<T> recordWrapper, ID id) {

    if (OFFLINE_TEST) {
        return "";
    }//from   w ww. j  a v a2  s  .  c  o  m
    String result = null;

    //RecordWrapper<T> recordWrapper = new RecordWrapper<>();
    //BeanUtils.copyProperties(t, recordWrapper.getFields());
    StringBuilder sUri = new StringBuilder();
    sUri.append(AIRTABLE_ENDPOINT_URL).append(getAirTableName());
    URI uri;
    if (id == null) {
        try {
            uri = new URI(sUri.toString());
            ResponseEntity<BaseResponse> response = restTemplate.postForEntity(uri, recordWrapper,
                    BaseResponse.class);
            if (response != null && response.getBody() != null) {
                result = response.getBody().getId();
            }
        } catch (URISyntaxException ex) {
            Logger.getLogger(BaseController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        sUri.append("/").append(id.toString());
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("HeaderName", "value");
        headers.add("Content-Type", "application/json");
        ObjectMapper objectMapper = new ObjectMapper();
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        messageConverter.setObjectMapper(objectMapper);
        restTemplate.getMessageConverters().add(messageConverter);
        HttpEntity<RecordWrapper> request = new HttpEntity<>(recordWrapper, headers);
        try {
            uri = new URI(sUri.toString());
            restTemplate.put(uri, request);
            result = "";
        } catch (RestClientException e) {
            if (e instanceof HttpStatusCodeException) {
                String errorResponse = ((HttpStatusCodeException) e).getResponseBodyAsString();
                System.out.println(errorResponse);
            }
        } catch (URISyntaxException ex) {
            Logger.getLogger(BaseController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateScenario.java

/**
 * Method, where scenario information is pushed to server in order to new scenario.
 * All heavy lifting is made here./*from  w w  w  .ja  v  a 2  s  .  com*/
 *
 * @param scenarios only one scenario is accepted - scenario to be uploaded
 * @return scenario stored
 */
@Override
protected Scenario doInBackground(Scenario... scenarios) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_SCENARIOS;

    setState(RUNNING, R.string.working_ws_create_scenario);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    //so files wont buffer in memory
    factory.setBufferRequestBody(false);
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Scenario scenario = scenarios[0];

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(scenario.getFilePath());

        //due to multipart file, MultiValueMap is the simplest approach for performing the post request
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("scenarioName", scenario.getScenarioName());
        form.add("researchGroupId", scenario.getResearchGroupId());
        form.add("description", scenario.getDescription());
        form.add("mimeType", scenario.getMimeType());
        form.add("private", Boolean.toString(scenario.isPrivate()));
        form.add("file", toBeUploadedFile);

        HttpEntity<Object> entity = new HttpEntity<Object>(form, requestHeaders);
        // Make the network request
        ResponseEntity<Scenario> response = restTemplate.postForEntity(url, entity, Scenario.class);
        return response.getBody();
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.opendatakit.api.admin.UserAdminServiceTest.java

@Test
public void testChangePlaintextPassword() {
    TestUtils.putGetOneUser(restTemplate, server, testUser3);
    String username = testUser3.getUserId().substring(SecurityConsts.USERNAME_COLON.length());
    String password = "mypass";

    String changePasswordUrl = ConstantsUtils.url(server) + "/admin/users/" + testUser3.getUserId()
            + "/password";

    logger.info("Updating password for " + username + " using " + changePasswordUrl);

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    headers.add("Content-Type", "application/json");
    HttpEntity<?> request = new HttpEntity<>(password, headers);
    ResponseEntity<String> postResponse = restTemplate.postForEntity(changePasswordUrl, request, String.class);
    assertThat(postResponse.getStatusCode(), is(HttpStatus.OK));

    logger.info("Retrieving data using " + username + "'s new password");

    RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
    RestTemplate userRestTemplate = restTemplateBuilder.basicAuthorization(username, password).build();
    String getUserUrl = ConstantsUtils.url(server) + "/admin/users/" + testUser3.getUserId();
    ResponseEntity<UserEntity> getResponse = userRestTemplate.exchange(getUserUrl, HttpMethod.GET, null,
            UserEntity.class);
    UserEntity body = getResponse.getBody();
    assertThat(getResponse.getStatusCode(), is(HttpStatus.OK));
    assertThat(body.getUserId(), equalTo(testUser3.getUserId()));

    logger.info("Cleanup: deleting " + username);
    TestUtils.deleteGetOneUser(restTemplate, server, testUser3);
}

From source file:org.jasig.portlet.notice.service.ssp.SSPApi.java

/**
 * Get the authentication token to use./*from   w  w  w .j av a  2  s .c o  m*/
 *
 * @param forceUpdate if true, get a new auth token even if a cached instance exists.
 * @return The authentication token
 * @throws MalformedURLException if the authentication URL is invalid
 * @throws RestClientException if an error occurs when talking to SSP
 */
private synchronized SSPToken getAuthenticationToken(boolean forceUpdate)
        throws MalformedURLException, RestClientException {
    if (authenticationToken != null && !authenticationToken.hasExpired() && !forceUpdate) {
        return authenticationToken;
    }

    String authString = getClientId() + ":" + getClientSecret();
    String authentication = new Base64().encodeToString(authString.getBytes());

    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION, BASIC + " " + authentication);

    // form encode the grant_type...
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(GRANT_TYPE, CLIENT_CREDENTIALS);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);

    URL authURL = getAuthenticationURL();
    authenticationToken = restTemplate.postForObject(authURL.toExternalForm(), request, SSPToken.class);
    return authenticationToken;
}

From source file:com.ge.predix.test.utils.UaaTestUtil.java

private BaseClientDetails createOrUpdateClient(final BaseClientDetails client) {

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    if (StringUtils.isNotEmpty(this.zone)) {
        headers.add("X-Identity-Zone-Id", "uaa");
    }/*from  ww w.ja v a  2s .  c o  m*/

    HttpEntity<String> postEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);

    ResponseEntity<String> clientCreate = null;
    try {
        clientCreate = this.adminRestTemplate.exchange(this.uaaUrl + "/oauth/clients", HttpMethod.POST,
                postEntity, String.class);
        if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
            return JSON_UTILS.deserialize(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException(
                    "Unexpected return code for client create: " + clientCreate.getStatusCode());
        }
    } catch (InvalidClientException ex) {
        if (ex.getMessage().equals("Client already exists: " + client.getClientId())) {
            HttpEntity<String> putEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);
            ResponseEntity<String> clientUpdate = this.adminRestTemplate.exchange(
                    this.uaaUrl + "/oauth/clients/" + client.getClientId(), HttpMethod.PUT, putEntity,
                    String.class);
            if (clientUpdate.getStatusCode() == HttpStatus.OK) {
                return JSON_UTILS.deserialize(clientUpdate.getBody(), BaseClientDetails.class);
            } else {
                throw new RuntimeException(
                        "Unexpected return code for client update: " + clientUpdate.getStatusCode());
            }
        }
    }
    throw new RuntimeException("Unexpected return code for client creation: " + clientCreate.getStatusCode());
}

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

@Test
public void testSuccessfulAuthorizationCodeFlow() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource();

    URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code")
            .queryParam("state", "mystateid").queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri()).build();
    ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), headers);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = result.getHeaders().getLocation().toString();

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }//from ww  w.jav a 2  s. c o  m

    ResponseEntity<String> response = serverRunning.getForString(location, headers);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("auth_key"));
    assertTrue(response.getBody().contains("password"));

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

    // Should be redirected to the original URL, but now authenticated
    result = serverRunning.postForResponse("/login.do", headers, formData);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    response = serverRunning.getForString(result.getHeaders().getLocation().toString(), headers);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("Do you authorize"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = serverRunning.postForResponse("/oauth/authorize", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = result.getHeaders().getLocation().toString();
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = response.getHeaders().getLocation().toString();
    }
    assertTrue("Wrong location: " + location,
            location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+"));

    formData.clear();
    formData.add("client_id", resource.getClientId());
    formData.add("redirect_uri", resource.getPreEstablishedRedirectUri());
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    tokenHeaders.set("Authorization",
            testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}