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.cloudfoundry.identity.uaa.integration.NativeApplicationIntegrationTests.java

/**
 * tests a happy-day flow of the Resource Owner Password Credentials grant type. (formerly native application
 * profile).//from w ww.j  a  v a2  s.c  o m
 */
@Test
public void testHappyDay() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization",
            testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    ResponseEntity<String> response = serverRunning.postForString("/oauth/token", formData, headers);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));
}

From source file:org.n52.io.request.IoParametersTest.java

@Test
public void when_creationViaFromMultiValuedMap_then_keysGetLowerCased() {
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("camelCased", "value");
    map.add("UPPERCASED", "value");
    IoParameters parameters = createFromMultiValueMap(map);
    Assert.assertTrue(parameters.containsParameter("camelCased"));
    Assert.assertTrue(parameters.containsParameter("camelcased"));
    Assert.assertTrue(parameters.containsParameter("UPPERCASED"));
    Assert.assertTrue(parameters.containsParameter("uppercased"));
}

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

/**
 * tests that an error occurs if you attempt to use bad client credentials.
 *///from  w ww .  java2s.  c  o  m
@Test
// Need a custom auth entry point to get the correct JSON response here.
public void testInvalidClient() throws Exception {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "password");
    formData.add("username", resource.getUsername());
    formData.add("password", resource.getPassword());
    formData.add("scope", "cloud_controller.read");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8"))));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    List<String> newCookies = response.getHeaders().get("Set-Cookie");
    if (newCookies != null && !newCookies.isEmpty()) {
        fail("No cookies should be set. Found: " + newCookies.get(0) + ".");
    }
    assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));

    @SuppressWarnings("unchecked")
    OAuth2Exception error = OAuth2Exception.valueOf(response.getBody());
    assertEquals("invalid_client", error.getOAuth2ErrorCode());
}

From source file:org.esupportail.filex.web.WebController.java

@RequestMapping("VIEW")
protected ModelAndView renderView(RenderRequest request, RenderResponse response) throws Exception {

    ModelMap model = new ModelMap();

    final PortletPreferences prefs = request.getPreferences();
    String eppnAttr = prefs.getValue(PREF_EPPN_ATTR, null);
    String restUrl = prefs.getValue(PREF_REST_URL, null);

    Map userInfos = (Map) request.getAttribute(PortletRequest.USER_INFO);
    String eppn = (String) userInfos.get(eppnAttr);

    log.info("Try to get FileX info for " + eppn);

    try {//w ww. ja  v a2 s.  c om

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        headers.add("eppn", eppn);

        HttpEntity<MultiValueMap<String, String>> httpRequest = new HttpEntity<MultiValueMap<String, String>>(
                null, headers);

        ResponseEntity<Filex> filexEntity = restTemplate.exchange(restUrl, HttpMethod.GET, httpRequest,
                Filex.class);
        log.debug("FileX info for " + eppn + " : " + filexEntity.getBody().toString());

        model.put("filex", filexEntity.getBody());
    } catch (HttpClientErrorException e) {
        return new ModelAndView("error", model);
    }

    model.put("serviceUrl", prefs.getValue(PREF_SERVICE_URL, null));
    return new ModelAndView("view", model);
}

From source file:com.ggk.hrms.authentication.CustomTokenServices.java

private Map<String, Object> checkToken(String accessToken) {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    String accessTokenUrl = new StringBuilder(checkTokenEndpointUrl).append("?access_token=")
            .append(accessToken).toString();
    return postForMap(accessTokenUrl, formData, headers);
}

From source file:com.example.SampleAppIntegrationTest.java

@Test
public void testSample() throws Exception {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    String message = "test message " + UUID.randomUUID();

    map.add("messageBody", message);
    map.add("username", "testUserName");

    this.restTemplate.postForObject("/newMessage", map, String.class);

    Callable<Boolean> logCheck = () -> baos.toString()
            .contains("New message received from testUserName via polling: " + message);
    Awaitility.await().atMost(10, TimeUnit.SECONDS).until(logCheck);

    assertThat(logCheck.call()).isTrue();
}

From source file:com.electronicpanopticon.spring.web.rest.RestClient.java

/**
 * This method logs into a service by doing an standard http using the
 * configuration in this class./*w  ww  . j  av  a2  s  .c  o  m*/
 * 
 * @param username
 *            the username to log into the application with
 * @param password
 *            the password to log into the application with
 * 
 * @return the url that the login redirects to
 */
public String login(String username, String password) {
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add(usernameInputFieldName, username);
    form.add(passwordInputFieldName, password);
    URI location = this.template.postForLocation(loginUrl(), form);
    return location.toString();
}

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

/**
 * Method, where data file information is pushed to server in order to create data file record.
 * All heavy lifting is made here./*  ww  w . ja v  a  2s.  c o  m*/
 *
 * @param dataFileContents must be three params in order - experiment id, description, path to file
 * @return URI of uploaded file
 */
@Override
protected URI doInBackground(String... dataFileContents) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DATAFILE;

    setState(RUNNING, R.string.working_ws_upload_data_file);
    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());

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(dataFileContents[2]);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("experimentId", dataFileContents[0]);
        form.add("description", dataFileContents[1]);
        form.add("file", toBeUploadedFile);

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

From source file:org.callistasoftware.netcare.core.spi.impl.PushNotificationServiceImpl.java

void sendApnsNotification(final String registrationId, final String message) {
    getLog().info("Preparing to send APNS message: {}", apnsCount);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("token", registrationId);
    params.add("message", message);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params,
            headers);/* w ww .  j  a  v a2s .co  m*/

    String result = new RestTemplate().postForObject(apnsServiceUrl, request, String.class);

    if (result.equals("success")) {
        getLog().debug("Push notification " + apnsCount + " sent. Result: " + result);
        apnsCount++;
    } else {
        getLog().error("Push notification could not be sent. Server result:\n" + result);
    }
}

From source file:am.ik.categolj2.app.authentication.AuthenticationHelper.java

public HttpEntity<MultiValueMap<String, Object>> createRopRequest(String username, String password) {
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("username", username);
    params.add("password", password);
    params.add("grant_type", "password");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    byte[] clientInfo = (adminClientProperties.getClientId() + ":" + adminClientProperties.getClientSecret())
            .getBytes(StandardCharsets.UTF_8);
    String basic = new String(Base64.getEncoder().encode(clientInfo), StandardCharsets.UTF_8);
    headers.set(com.google.common.net.HttpHeaders.AUTHORIZATION, "Basic " + basic);
    return new HttpEntity<>(params, headers);
}