Example usage for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

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

Introduction

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

Prototype

public LinkedMultiValueMap() 

Source Link

Document

Create a new LinkedMultiValueMap that wraps a LinkedHashMap .

Usage

From source file:org.apache.servicecomb.demo.springmvc.client.CodeFirstRestTemplateSpringmvc.java

private String testRestTemplateUpload(RestTemplate template, String cseUrlPrefix, File file1, File someFile) {
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(file1));
    map.add("someFile", new FileSystemResource(someFile));

    return template.postForObject(cseUrlPrefix + "/upload", new HttpEntity<>(map), String.class);
}

From source file:org.apache.servicecomb.demo.springmvc.client.SpringmvcClient.java

private static void testSpringMvcDefaultValues(RestTemplate template, String microserviceName) {
    String cseUrlPrefix = "cse://" + microserviceName + "/SpringMvcDefaultValues/";
    //default values
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
    String result = template.postForObject(cseUrlPrefix + "/form", request, String.class);
    TestMgr.check("Hello 20bobo", result);

    headers = new HttpHeaders();
    HttpEntity<String> entity = new HttpEntity<>(null, headers);
    result = template.postForObject(cseUrlPrefix + "/header", entity, String.class);
    TestMgr.check("Hello 20bobo30", result);

    result = template.getForObject(cseUrlPrefix + "/query?d=10", String.class);
    TestMgr.check("Hello 20bobo4010", result);
    boolean failed = false;
    try {/*  ww w . j  a va2  s . com*/
        result = template.getForObject(cseUrlPrefix + "/query2", String.class);
    } catch (InvocationException e) {
        failed = true;
        TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
    }

    failed = false;
    try {
        result = template.getForObject(cseUrlPrefix + "/query2?d=2&e=2", String.class);
    } catch (InvocationException e) {
        failed = true;
        TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
    }
    TestMgr.check(failed, true);

    failed = false;
    try {
        result = template.getForObject(cseUrlPrefix + "/query2?a=&d=2&e=2", String.class);
    } catch (InvocationException e) {
        failed = true;
        TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
    }
    TestMgr.check(failed, true);

    result = template.getForObject(cseUrlPrefix + "/query2?d=30&e=2", String.class);
    TestMgr.check("Hello 20bobo40302", result);

    failed = false;
    try {
        result = template.getForObject(cseUrlPrefix + "/query3?a=2&b=2", String.class);
    } catch (InvocationException e) {
        failed = true;
        TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST);
    }
    TestMgr.check(failed, true);

    result = template.getForObject(cseUrlPrefix + "/query3?a=30&b=2", String.class);
    TestMgr.check("Hello 302", result);

    result = template.getForObject(cseUrlPrefix + "/query3?a=30", String.class);
    TestMgr.check("Hello 30null", result);

    //input values
    headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<Map<String, String>> requestPara = new HttpEntity<>(null, headers);
    result = template.postForObject(cseUrlPrefix + "/form?a=30&b=sam", requestPara, String.class);
    TestMgr.check("Hello 30sam", result);

    headers = new HttpHeaders();
    headers.add("a", "30");
    headers.add("b", "sam");
    headers.add("c", "40");
    entity = new HttpEntity<>(null, headers);
    result = template.postForObject(cseUrlPrefix + "/header", entity, String.class);
    TestMgr.check("Hello 30sam40", result);

    result = template.getForObject(cseUrlPrefix + "/query?a=3&b=sam&c=5&d=30", String.class);
    TestMgr.check("Hello 3sam530", result);

    result = template.getForObject(cseUrlPrefix + "/query2?a=3&b=4&c=5&d=30&e=2", String.class);
    TestMgr.check("Hello 345302", result);
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToUploadFile() throws Exception {
    String file1Content = "hello world";
    String file2Content = "bonjour";
    String username = "mike";

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
    map.add("someFile", new FileSystemResource(newFile(file2Content).getAbsolutePath()));
    map.add("name", username);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    String result = restTemplate.postForObject(codeFirstUrl + "upload", new HttpEntity<>(map, headers),
            String.class);

    assertThat(result, is(file1Content + file2Content + username));

    ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate
            .postForEntity(codeFirstUrl + "upload", new HttpEntity<>(map, headers), String.class);
    ResponseEntity<String> responseEntity = listenableFuture.get();
    assertThat(responseEntity.getBody(), is(file1Content + file2Content + username));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToUploadFileWithoutAnnotation() throws Exception {
    String file1Content = "hello world";
    String file2Content = "bonjour";
    String username = "mike";

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
    map.add("file2", new FileSystemResource(newFile(file2Content).getAbsolutePath()));
    map.add("name", username);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    String result = restTemplate.postForObject(codeFirstUrl + "uploadWithoutAnnotation",
            new HttpEntity<>(map, headers), String.class);

    assertThat(result, is(file1Content + file2Content + username));

    ListenableFuture<ResponseEntity<String>> listenableFuture = asyncRestTemplate.postForEntity(
            codeFirstUrl + "uploadWithoutAnnotation", new HttpEntity<>(map, headers), String.class);
    ResponseEntity<String> responseEntity = listenableFuture.get();
    assertThat(responseEntity.getBody(), is(file1Content + file2Content + username));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void blowsUpWhenFileNameDoesNotMatch() throws Exception {
    String file1Content = "hello world";
    String file2Content = "bonjour";

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
    map.add("unmatched name", new FileSystemResource(newFile(file2Content).getAbsolutePath()));

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

    ResponseEntity<String> response = restTemplate.postForEntity(codeFirstUrl + "uploadWithoutAnnotation",
            new HttpEntity<>(map, headers), String.class);
    assertThat(response.getStatusCodeValue(), is(590));
    assertThat(response.getBody(), is("CommonExceptionData [message=Cse Internal Server Error]"));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToPostDate() throws Exception {
    ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS);
    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("date",
            RestObjectMapperFactory.getRestObjectMapper().convertToString(Date.from(date.toInstant())));

    HttpHeaders headers = new HttpHeaders();
    headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);

    int seconds = 1;
    Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}",
            new HttpEntity<>(body, headers), Date.class, seconds);

    assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant())));

    ListenableFuture<ResponseEntity<Date>> listenableFuture = asyncRestTemplate.postForEntity(
            codeFirstUrl + "addDate?seconds={seconds}", new HttpEntity<>(body, headers), Date.class, seconds);
    ResponseEntity<Date> dateResponseEntity = listenableFuture.get();
    assertThat(dateResponseEntity.getBody(), is(Date.from(date.plusSeconds(seconds).toInstant())));
}

From source file:org.apache.servicecomb.demo.springmvc.tests.SpringMvcIntegrationTestBase.java

@Test
public void ableToPostForm() throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("a", "5");
    params.add("b", "3");

    HttpHeaders headers = new HttpHeaders();
    headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);
    int result = restTemplate.postForObject(codeFirstUrl + "add", new HttpEntity<>(params, headers),
            Integer.class);

    assertThat(result, is(8));// www  .j  a  v  a  2 s . com

    ListenableFuture<ResponseEntity<Integer>> listenableFuture = asyncRestTemplate
            .postForEntity(codeFirstUrl + "add", new HttpEntity<>(params, headers), Integer.class);
    ResponseEntity<Integer> futureResponse = listenableFuture.get();
    assertThat(futureResponse.getBody(), is(8));
}

From source file:org.apereo.portal.events.tincan.providers.DefaultTinCanAPIProvider.java

/**
 * Initialize the API.  Just sends an initialization event to the LRS provider.
 * This uses the activities/state API to do the initial test.
 *///w  ww . j a va 2 s .co  m
@Override
public void init() {
    loadConfig();

    if (!isEnabled()) {
        return;
    }

    try {
        String actorStr = format(ACTOR_FORMAT, actorName, actorEmail);

        // Setup GET params...
        List<BasicNameValuePair> getParams = new ArrayList<>();
        getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId));
        getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr));
        getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId));

        Object body = null;
        if (formEncodeActivityData) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED);
            map.add(activitiesFormParamName, json);
            body = map;

        } else {
            // just post a simple:  {"status": "started"} record to the states API to verify
            // the service is up.
            Map<String, String> data = new HashMap<String, String>();
            data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED);
            body = data;
        }

        ResponseEntity<Object> response = sendRequest(STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body,
                Object.class);
        if (response.getStatusCode().series() != Series.SUCCESSFUL) {
            logger.error("LRS provider for URL " + LRSUrl
                    + " it not configured properly, or is offline.  Disabling provider.");
        }

        // todo: Need to think through a strategy for handling errors submitting
        // to the LRS.
    } catch (HttpClientErrorException e) {
        // log some additional info in this case...
        logger.error("LRS provider for URL " + LRSUrl
                + " failed to contact LRS for initialization.  Disabling provider.", e);
        logger.error("  Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
        enabled = false;

    } catch (Exception e) {
        logger.error("LRS provider for URL " + LRSUrl
                + " failed to contact LRS for initialization.  Disabling provider", e);
        enabled = false;
    }
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext fetchTokenFromCode(final TokenRequest request) {
    String clientBasicAuth = getClientBasicAuthHeader(request);

    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }/*  w w  w  . j a v  a 2  s  .c  o m*/
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.GRANT_TYPE, "authorization_code");
    form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString());
    String responseType = "token";
    if (request.wantsIdToken()) {
        responseType += " id_token";
    }
    form.add(OAuth2Utils.RESPONSE_TYPE, responseType);
    form.add("code", request.getAuthorizationCode());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext authenticateSaml2BearerAssertion(final TokenRequest request) {
    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }//  w  w  w.j  a va 2s  . c  om
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.CLIENT_ID, request.getClientId());
    form.add("client_secret", request.getClientSecret());
    form.add(OAuth2Utils.GRANT_TYPE, "urn:ietf:params:oauth:grant-type:saml2-bearer");
    form.add("assertion", request.getAuthCodeAPIToken());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}