Java Code Examples for org.springframework.util.LinkedMultiValueMap#add()

The following examples show how to use org.springframework.util.LinkedMultiValueMap#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultPathContainerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void pathSegmentParams() throws Exception {
	// basic
	LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.add("colors", "red");
	params.add("colors", "blue");
	params.add("colors", "green");
	params.add("year", "2012");
	testPathSegment("cars;colors=red,blue,green;year=2012", "cars", params);

	// trailing semicolon
	params = new LinkedMultiValueMap<>();
	params.add("p", "1");
	testPathSegment("path;p=1;", "path", params);

	// params with spaces
	params = new LinkedMultiValueMap<>();
	params.add("param name", "param value");
	testPathSegment("path;param%20name=param%20value;%20", "path", params);

	// empty params
	params = new LinkedMultiValueMap<>();
	params.add("p", "1");
	testPathSegment("path;;;%20;%20;p=1;%20", "path", params);
}
 
Example 2
Source File: RestConnectionFactory.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
private void refreshAccessToken() {
    RestOAuth2Template t = new RestOAuth2Template(this.clientId, this.clientSecret, this.authorizeUrl,
            this.accessTokenUrl, this.template);
    if (this.refreshToken == null) {
        if (this.username != null && this.password != null) {
            this.accessGrant = t.exchangeCredentialsForAccess(this.username, this.password,
                    new LinkedMultiValueMap<String, String>());
        } else {
            throw new IllegalStateException("openid-connect authentication configured, "
                    + "however userid/password information not provided nor refreshToken");
        }
    } else {
        LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("scope", this.scope);
        this.accessGrant = t.refreshAccess(this.refreshToken, params);
    }
}
 
Example 3
Source File: ConnectorsITCase.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateConnectorWithoutIconViaMultipart() throws IOException {
    final Connector initialConnector = dataManager.fetch(Connector.class, "twitter");

    final Connector connectorWithNewdescription = new Connector.Builder().createFrom(initialConnector)
        .description("Updated!").build();

    final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("connector", connectorWithNewdescription);

    put("/api/v1/connectors/twitter",
        multipartData, Void.class, tokenRule.validToken(), HttpStatus.NO_CONTENT,
        multipartHeaders());

    final ResponseEntity<Connector> updatedConnector = get("/api/v1/connectors/twitter", Connector.class);

    assertThat(updatedConnector.getBody().getId()).isPresent();
    assertThat(updatedConnector.getBody().getDescription()).isNotBlank().isEqualTo("Updated!");
    assertThat(updatedConnector.getBody().getIcon()).isNotBlank().isEqualTo(initialConnector.getIcon());
}
 
Example 4
Source File: SampleCamundaRestApplicationIT.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
public void multipartFileUploadCamundaRestIsWorking() throws Exception {
  final String variableName = "testvariable";
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TestProcess");
  LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
  map.add("data", new ClassPathResource("/bpmn/test.bpmn"));
  map.add("valueType", "File");
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  headers.setContentDispositionFormData("data", "test.bpmn");

  HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
  ResponseEntity<String> exchange = testRestTemplate.exchange("/rest/engine/{enginename}/process-instance/{id}/variables/{variableName}/data",
      HttpMethod.POST, requestEntity, String.class, camundaBpmProperties.getProcessEngineName(), processInstance.getId(), variableName);

  assertEquals(HttpStatus.NO_CONTENT, exchange.getStatusCode());

  VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().processInstanceIdIn(processInstance.getId()).variableName(variableName)
      .singleResult();
  ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream) variableInstance.getValue();
  assertTrue(byteArrayInputStream.available() > 0);
}
 
Example 5
Source File: GraphQLReactiveControllerTest.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultControllerTest_POST_flux() {
    LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("query", "{greetingFromAnnotatedSourceReactive_flux}");

    webTestClient.post().uri(URI.create("/" + apiContext))
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(BodyInserters.fromFormData(body))
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class)
            .consumeWith(c -> {
                assertThat("", c.getResponseBody(), containsString("First Hello world !"));
                assertThat("", c.getResponseBody(), containsString("Second Hello world !"));
            });
}
 
Example 6
Source File: SampleCamundaRestApplicationIT.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void multipartFileUploadCamundaRestIsWorking() throws Exception {
  final String variableName = "testvariable";
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TestProcess");
  LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
  map.add("data", new ClassPathResource("/bpmn/test.bpmn"));
  map.add("valueType", "File");
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  headers.setContentDispositionFormData("data", "test.bpmn");

  HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
  ResponseEntity<String> exchange = testRestTemplate.exchange("/engine-rest/engine/{enginename}/process-instance/{id}/variables/{variableName}/data",
      HttpMethod.POST, requestEntity, String.class, camundaBpmProperties.getProcessEngineName(), processInstance.getId(), variableName);

  assertEquals(HttpStatus.NO_CONTENT, exchange.getStatusCode());

  VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().processInstanceIdIn(processInstance.getId()).variableName(variableName)
      .singleResult();
  ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream) variableInstance.getValue();
  assertTrue(byteArrayInputStream.available() > 0);
}
 
Example 7
Source File: DefaultPathContainerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void pathSegmentParams() throws Exception {
	// basic
	LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.add("colors", "red");
	params.add("colors", "blue");
	params.add("colors", "green");
	params.add("year", "2012");
	testPathSegment("cars;colors=red,blue,green;year=2012", "cars", params);

	// trailing semicolon
	params = new LinkedMultiValueMap<>();
	params.add("p", "1");
	testPathSegment("path;p=1;", "path", params);

	// params with spaces
	params = new LinkedMultiValueMap<>();
	params.add("param name", "param value");
	testPathSegment("path;param%20name=param%20value;%20", "path", params);

	// empty params
	params = new LinkedMultiValueMap<>();
	params.add("p", "1");
	testPathSegment("path;;;%20;%20;p=1;%20", "path", params);
}
 
Example 8
Source File: CoffeeApplicationTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testCreateCustomer() {
  LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
  map.add("name", "Bob");
  map.add("email", "[email protected]");

  HttpHeaders headers = new HttpHeaders();
  HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
  ResponseEntity<String> response =
      this.restTemplate.postForEntity("/createCustomer", request, String.class);

  assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();

  ArrayList<Customer> allCustomers = new ArrayList<>();
  for (Customer c : customerRepository.findAll()) {
    allCustomers.add(c);
  }

  assertThat(allCustomers).hasSize(1);
  assertThat(allCustomers.get(0).getName()).isEqualTo("Bob");
}
 
Example 9
Source File: DefaultSubscriptionRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public LinkedMultiValueMap<String, String> getSubscriptions(String destination, Message<?> message) {
	LinkedMultiValueMap<String, String> result = this.accessCache.get(destination);
	if (result == null) {
		synchronized (this.updateCache) {
			result = new LinkedMultiValueMap<String, String>();
			for (SessionSubscriptionInfo info : subscriptionRegistry.getAllSubscriptions()) {
				for (String destinationPattern : info.getDestinations()) {
					if (getPathMatcher().match(destinationPattern, destination)) {
						for (Subscription subscription : info.getSubscriptions(destinationPattern)) {
							result.add(info.sessionId, subscription.getId());
						}
					}
				}
			}
			if (!result.isEmpty()) {
				this.updateCache.put(destination, result.deepCopy());
				this.accessCache.put(destination, result);
			}
		}
	}
	return result;
}
 
Example 10
Source File: DefaultSubscriptionRegistry.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public LinkedMultiValueMap<String, String> getSubscriptions(String destination, Message<?> message) {
	LinkedMultiValueMap<String, String> result = this.accessCache.get(destination);
	if (result == null) {
		synchronized (this.updateCache) {
			result = new LinkedMultiValueMap<>();
			for (SessionSubscriptionInfo info : subscriptionRegistry.getAllSubscriptions()) {
				for (String destinationPattern : info.getDestinations()) {
					if (getPathMatcher().match(destinationPattern, destination)) {
						for (Subscription sub : info.getSubscriptions(destinationPattern)) {
							result.add(info.sessionId, sub.getId());
						}
					}
				}
			}
			if (!result.isEmpty()) {
				this.updateCache.put(destination, result.deepCopy());
				this.accessCache.put(destination, result);
			}
		}
	}
	return result;
}
 
Example 11
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param samlAssertion
 * @return
 */
public LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion) {
    LinkedMultiValueMap<String, String> attributes = new LinkedMultiValueMap<String, String>();

    AttributeStatement attributeStatement = samlAssertion.getAttributeStatements().get(0);

    for (org.opensaml.saml2.core.Attribute attribute : attributeStatement.getAttributes()) {
        String samlAttributeName = attribute.getName();
        List<XMLObject> valueObjects = attribute.getAttributeValues();
        for (XMLObject valueXmlObject : valueObjects) {
            attributes.add(samlAttributeName, valueXmlObject.getDOM().getTextContent());
        }
    }
    return attributes;
}
 
Example 12
Source File: RestTemplateMain.java    From feign-client-test with MIT License 5 votes vote down vote up
public static void main(String args[]) throws Exception {
//        System.setProperty("log4j.logger.httpclient.wire", "TRACE");
        RestTemplate template = new RestTemplate();
        
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();

        HttpHeaders filePartHeaders = new HttpHeaders();
        filePartHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        Resource multipartFileResource = new MultipartFileResource(new byte[]{65, 66, 67, 68}, "testFile.tmp");
        HttpEntity<Resource> filePart = new HttpEntity<>(multipartFileResource, filePartHeaders);
        
        map.add("file", multipartFileResource);

        HttpHeaders jsonPartHeaders = new HttpHeaders();
        jsonPartHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<UploadMetadata> jsonPart = new HttpEntity<>(new UploadMetadata("username"), jsonPartHeaders);

        map.add("metadata", jsonPart);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
        ResponseEntity<UploadInfo> result = template.exchange("http://localhost:8080/upload/{folder}",
                HttpMethod.POST, requestEntity, UploadInfo.class, Collections.singletonMap("folder", "testFolder"));

        System.out.println(result.getBody().toString());
    }
 
Example 13
Source File: ShortMessageRepository.java    From Spring-Boot-2-Fundamentals with MIT License 5 votes vote down vote up
public List<ShortMessage> retrieveAll() {
    LinkedMultiValueMap<Integer, Author> authorsMap = new LinkedMultiValueMap<>();
    RowCallbackHandler addAuthor = rs -> authorsMap.add(
            rs.getInt("message_id"),
            authorService.retrieveAuthor(rs.getInt("author_id")));
    jdbcTemplate.query("SELECT message_id, author_id FROM message_authors", addAuthor);

    return jdbcTemplate.query("SELECT id, posted_time, message_text FROM short_message",
            (rs, rowNum) -> {
                List<Author> authors = authorsMap.get(rs.getInt("id"));
                LocalDateTime postedTime = rs.getTimestamp("posted_time").toLocalDateTime();
                String messageText = rs.getString("message_text");
                return new ShortMessage(authors, postedTime, messageText);
            });
}
 
Example 14
Source File: AgentInstances.java    From gocd with Apache License 2.0 5 votes vote down vote up
public LinkedMultiValueMap<String, ElasticAgentMetadata> getAllElasticAgentsGroupedByPluginId() {
    LinkedMultiValueMap<String, ElasticAgentMetadata> map = new LinkedMultiValueMap<>();

    for (Map.Entry<String, AgentInstance> entry : uuidToAgentInstanceMap.entrySet()) {
        AgentInstance agentInstance = entry.getValue();
        if (agentInstance.isElastic()) {
            ElasticAgentMetadata metadata = agentInstance.elasticAgentMetadata();
            map.add(metadata.elasticPluginId(), metadata);
        }
    }

    return map;
}
 
Example 15
Source File: CustomSwaggerConnectorITCase.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static MultiValueMap<String, Object> multipartBodyForInfo(final ConnectorSettings connectorSettings, final InputStream is)
    throws IOException {
    final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("connectorSettings", connectorSettings);
    multipartData.add("specification", Okio.buffer(Okio.source(is)).readUtf8());
    return multipartData;
}
 
Example 16
Source File: TWBTranslationServiceTest.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public void testSendEncodedDocument() throws Exception {
    String filename = "TWB_Source_"+System.currentTimeMillis()+".csv";

    //decide whether its better to send file or content
    String content = "被害のダウ";
    byte[] bytes = content.getBytes(StandardCharsets.UTF_8);

    final String url=BASE_URL+"/documents";
    HttpHeaders requestHeaders=new HttpHeaders();
    requestHeaders.add("X-Proz-API-Key", API_KEY);
    requestHeaders.setContentType(new MediaType("multipart","form-data"));
    RestTemplate restTemplate=new RestTemplate();
    restTemplate.getMessageConverters()
            .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("document", bytes);
    map.add("name", "translation_source.csv");

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new    HttpEntity<LinkedMultiValueMap<String, Object>>(
            map, requestHeaders);

    ResponseEntity<Map> result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
    Map resultMap = result.getBody();
    String download_Link = (String)resultMap.get("download_link");
    String returnedDocumentContent = getTranslationDocumentContent(download_Link) ;
    assert (returnedDocumentContent.equals(content));

}
 
Example 17
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
private void addFile(int executionId, String uid, AbstractResource resource) {
	LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.add("file", resource);
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.MULTIPART_FORM_DATA);

	HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
			map, headers);
	template.exchange(base.toString() + "executions/" + executionId + "/details/" + uid + "/file/", HttpMethod.POST,
			requestEntity, Void.class);
}
 
Example 18
Source File: BaseRestInvokerProxyFactoryBean.java    From spring-rest-invoker with Apache License 2.0 5 votes vote down vote up
protected void augmentHeadersWithCookies(LinkedMultiValueMap<String, String> headers, Map<String, String> cookies) {
	if (cookies.isEmpty())
		return;
	String cookieHeader = "";
	String prefix = "";
	for (String cookieName : cookies.keySet()) {
		cookieHeader = cookieHeader + prefix + cookieName + "=" + cookies.get(cookieName);
		prefix = "&";
	}
	headers.add("Cookie", cookieHeader);

}
 
Example 19
Source File: CustomConnectorITCase.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static MultiValueMap<String, Object> multipartBody(final ConnectorSettings connectorSettings, final InputStream icon) {
    final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("connectorSettings", connectorSettings);
    multipartData.add("icon", new InputStreamResource(icon));
    return multipartData;
}
 
Example 20
Source File: ConnectorsITCase.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateConnectorAndIconViaMultipart() throws IOException {
    final Connector initialConnector = dataManager.fetch(Connector.class, "twitter");

    assertThat(initialConnector.getIcon()).isNotBlank().doesNotStartWith("db:");

    final Connector connectorWithNewdescription = new Connector.Builder().createFrom(initialConnector)
        .description("Updated!").build();

    final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("connector", connectorWithNewdescription);
    multipartData.add("icon", new InputStreamResource(getClass().getResourceAsStream("test-image.png")));

    put("/api/v1/connectors/twitter",
        multipartData, Void.class, tokenRule.validToken(), HttpStatus.NO_CONTENT,
        multipartHeaders());

    final ResponseEntity<Connector> updatedConnector = get("/api/v1/connectors/twitter", Connector.class);

    assertThat(updatedConnector.getBody().getId()).isPresent();
    assertThat(updatedConnector.getBody().getIcon()).isNotBlank().startsWith("db:");
    assertThat(updatedConnector.getBody().getDescription()).isNotBlank().isEqualTo("Updated!");

    final ResponseEntity<ByteArrayResource> got = get("/api/v1/connectors/twitter/icon", ByteArrayResource.class);
    assertThat(got.getHeaders().getFirst("Content-Type")).isEqualTo("image/png");

    try (ImageInputStream iis = ImageIO.createImageInputStream(got.getBody().getInputStream());) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            final ImageReader reader = readers.next();
            try {
                reader.setInput(iis);
                final Dimension dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0));
                assertThat(dimensions.getHeight()).as("Wrong image height").isEqualTo(106d);
                assertThat(dimensions.getWidth()).as("Wrong image width").isEqualTo(106d);
            } finally {
                reader.dispose();
            }
        }
    }
}