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.ambraproject.wombat.controller.SearchController.java

/**
 * This is a catch for advanced searches originating from Old Ambra. It transforms the
 * "unformattedQuery" param into "q" which is used by Wombat's new search.
 * todo: remove this method and direct all advancedSearch requests to the simple search method
 *//*  w w w  .  jav a 2s  .  c  o m*/
@RequestMapping(name = "advancedSearch", value = "/search", params = { "unformattedQuery", "!q" })
public String advancedSearch(HttpServletRequest request, Model model, @SiteParam Site site,
        @RequestParam MultiValueMap<String, String> params) throws IOException {
    String queryString = params.getFirst("unformattedQuery");
    params.remove("unformattedQuery");
    params.add("q", queryString);
    return search(request, model, site, params);
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Set defaults and performs search for subject area landing page
 *
 * @param request HTTP request for browsing subject areas
 * @param model   model that will be passed to the template
 * @param site    site the request originates from
 * @param params  HTTP request params/*from   w  w  w. j ava  2  s.  co m*/
 * @param subject the subject area to be search; return all articles if no subject area is provided
 * @throws IOException
 */
private void subjectAreaSearch(HttpServletRequest request, Model model, Site site,
        MultiValueMap<String, String> params, String subject) throws IOException {

    TaxonomyGraph taxonomyGraph = modelSubjectHierarchy(model, site, subject);

    String subjectName;
    if (Strings.isNullOrEmpty(subject)) {
        params.add("subject", "");
        subjectName = "All Subject Areas";
    } else {
        subject = subject.replace("_", " ");
        params.add("subject", subject);
        subjectName = taxonomyGraph.getName(subject);
    }
    model.addAttribute("subjectName", subjectName);

    // set defaults for subject area landing page
    if (isNullOrEmpty(params.get("resultsPerPage"))) {
        params.add("resultsPerPage", BROWSE_RESULTS_PER_PAGE);
    }

    if (isNullOrEmpty(params.get("sortOrder"))) {
        params.add("sortOrder", "DATE_NEWEST_FIRST");
    }

    if (isNullOrEmpty(params.get("filterJournals"))) {
        params.add("filterJournals", site.getJournalKey());
    }

    CommonParams commonParams = modelCommonParams(request, model, site, params, false);
    ArticleSearchQuery.Builder query = ArticleSearchQuery.builder().setQuery("").setSimple(false);
    commonParams.fill(query);

    ArticleSearchQuery queryObj = query.build();
    Map<String, ?> searchResults = solrSearchApi.search(queryObj, site);

    model.addAttribute("articles", SolrArticleAdapter.unpackSolrQuery(searchResults));
    model.addAttribute("searchResults", solrSearchApi.addArticleLinks(searchResults, request, site, siteSet));
    model.addAttribute("page", commonParams.getSingleParam(params, "page", "1"));
    model.addAttribute("journalKey", site.getKey());
    model.addAttribute("isBrowse", true);

    String authId = request.getRemoteUser();
    boolean subscribed = false;
    if (authId != null) {
        String subjectParam = Strings.isNullOrEmpty(subject) ? "" : subjectName;
        subscribed = alertService.isUserSubscribed(authId, site.getJournalKey(), subjectParam);
    }
    model.addAttribute("subscribed", subscribed);
}

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

private void testUpload(RestTemplate template, String cseUrlPrefix) throws IOException {
    String file1Content = "hello world";
    File file1 = File.createTempFile(" ", ".txt");
    FileUtils.writeStringToFile(file1, file1Content);

    String file2Content = " bonjour";
    File someFile = File.createTempFile("upload2", ".txt");
    FileUtils.writeStringToFile(someFile, file2Content);

    String expect = String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getName(), MediaType.TEXT_PLAIN_VALUE,
            file1Content, someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content);

    String result = testRestTemplateUpload(template, cseUrlPrefix, file1, someFile);
    TestMgr.check(expect, result);//from  w w  w. j  av  a 2s .c  o  m

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(file1));

    result = template.postForObject(cseUrlPrefix + "/upload1", new HttpEntity<>(map), String.class);

    result = uploadPartAndFile.fileUpload(new FilePart(null, file1), someFile);
    TestMgr.check(expect, result);

    expect = String.format("null:%s:%s\n" + "%s:%s:%s", MediaType.APPLICATION_OCTET_STREAM_VALUE, file1Content,
            someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content);
    result = uploadStreamAndResource.fileUpload(
            new ByteArrayInputStream(file1Content.getBytes(StandardCharsets.UTF_8)),
            new PathResource(someFile.getAbsolutePath()));
    TestMgr.check(expect, result);
}

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.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));/*from ww w  .jav a 2  s  .  co m*/

    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.
 *//*from w w  w .  j  av  a 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;
    }
}