org.springframework.util.LinkedMultiValueMap Java Examples

The following examples show how to use org.springframework.util.LinkedMultiValueMap. 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: ExceptionCallTest.java    From springcloud-idempotent-starter with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void execDifferentCall() {
	String requestId1 = "execDiffrentCall_:"+UUID.randomUUID();
	String requestId2 = "execDiffrentCall_:"+UUID.randomUUID();

	MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
	headers.add(Constants.REQ_IDEM_ID, requestId1);
	headers.add("Content-Type", "application/json");
	HttpEntity requests = new HttpEntity(headers);
	
	ResponseEntity<String> response = restTemplate.exchange(REQ_URL, HttpMethod.POST, requests,
			String.class);
	String reponse1 = response.getBody();
	
	MultiValueMap<String, String> headers2 = new LinkedMultiValueMap<String, String>();
	headers.add(Constants.REQ_IDEM_ID, requestId2);
	headers.add("Content-Type", "application/json");
	HttpEntity requests2 = new HttpEntity(headers2);
	
	ResponseEntity<String> response2 = restTemplate.exchange(REQ_URL, HttpMethod.POST, requests2,
			String.class);
	String reponse2 = response2.getBody();
	System.out.println(reponse1 + "\n" + reponse2);
	Assert.assertNotEquals("The different result", reponse1, reponse2);
}
 
Example #2
Source File: AnnotatedElementUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the annotation attributes of <strong>all</strong> annotations of
 * the specified {@code annotationName} in the annotation hierarchy above
 * the supplied {@link AnnotatedElement} and store the results in a
 * {@link MultiValueMap}.
 * <p>Note: in contrast to {@link #getMergedAnnotationAttributes(AnnotatedElement, String)},
 * this method does <em>not</em> support attribute overrides.
 * <p>This method follows <em>get semantics</em> as described in the
 * {@linkplain AnnotatedElementUtils class-level javadoc}.
 * @param element the annotated element
 * @param annotationName the fully qualified class name of the annotation type to find
 * @param classValuesAsString whether to convert Class references into Strings or to
 * preserve them as Class references
 * @param nestedAnnotationsAsMap whether to convert nested Annotation instances into
 * {@code AnnotationAttributes} maps or to preserve them as Annotation instances
 * @return a {@link MultiValueMap} keyed by attribute name, containing the annotation
 * attributes from all annotations found, or {@code null} if not found
 */
public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element,
		String annotationName, final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) {

	final MultiValueMap<String, Object> attributesMap = new LinkedMultiValueMap<String, Object>();

	searchWithGetSemantics(element, null, annotationName, new SimpleAnnotationProcessor<Object>() {
		@Override
		public Object process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
			AnnotationAttributes annotationAttributes = AnnotationUtils.getAnnotationAttributes(
					annotation, classValuesAsString, nestedAnnotationsAsMap);
			for (Map.Entry<String, Object> entry : annotationAttributes.entrySet()) {
				attributesMap.add(entry.getKey(), entry.getValue());
			}
			return CONTINUE;
		}
	});

	return (!attributesMap.isEmpty() ? attributesMap : null);
}
 
Example #3
Source File: PageSearchForm.java    From wallride with Apache License 2.0 6 votes vote down vote up
public MultiValueMap<String, String> toQueryParams() {
	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	if (StringUtils.hasText(keyword)) {
		params.add("keyword", keyword);
	}
	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;
}
 
Example #4
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Logs out current logged in user session
 * 
 * <p><b>0</b> - successful operation
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
 */
public Mono<Void> logoutUser() throws WebClientResponseException {
    Object postBody = null;
    // create path and map variables
    final Map<String, Object> pathParams = new HashMap<String, Object>();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] localVarAccepts = { };
    final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String[] localVarContentTypes = { };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] {  };

    ParameterizedTypeReference<Void> localVarReturnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI("/user/logout", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #5
Source File: CloudSalesOrderService.java    From cloud-espm-cloud-native with Apache License 2.0 6 votes vote down vote up
private String getOAuthToken(final DestinationService destination) throws IOException {
	final String auth = destination.clientid + ":" + destination.clientsecret;
	final byte[] basicToken = Base64.getEncoder().encode(auth.getBytes());
	headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
	headers.set("Authorization", "Basic " + new String(basicToken));
	MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
	map.add("client_id", destination.clientid);
	map.add("grant_type", "client_credentials");
	final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
			headers);
	ResponseEntity<String> response = restTemplate.postForEntity(destination.url + "/oauth/token", request,
			String.class);
	final String responseString = response.getBody();
	JsonNode root = mapper.readTree(responseString);
	final String accessToken = root.get("access_token").asText();
	return accessToken;

}
 
Example #6
Source File: OrderController.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private void invokerAccountService(int orderMoney) {
	String url = "http://127.0.0.1:18084/account";
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

	MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

	map.add("userId", USER_ID);
	map.add("money", orderMoney + "");

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

	ResponseEntity<String> response = restTemplate.postForEntity(url, request,
			String.class);
}
 
Example #7
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Test serialization of outer boolean types
 * <p><b>200</b> - Output boolean
 * @param body Input boolean as post body
 * @return Boolean
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
 */
public Mono<Boolean> fakeOuterBooleanSerialize(Boolean body) throws WebClientResponseException {
    Object postBody = body;
    // create path and map variables
    final Map<String, Object> pathParams = new HashMap<String, Object>();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] localVarAccepts = { 
        "*/*"
    };
    final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String[] localVarContentTypes = { };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] {  };

    ParameterizedTypeReference<Boolean> localVarReturnType = new ParameterizedTypeReference<Boolean>() {};
    return apiClient.invokeAPI("/fake/outer/boolean", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #8
Source File: ArticleSearchForm.java    From wallride with Apache License 2.0 6 votes vote down vote up
public MultiValueMap<String, String> toQueryParams() {
	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	if (StringUtils.hasText(keyword)) {
		params.add("keyword", keyword);
	}
	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;
}
 
Example #9
Source File: AdminServiceAPI.java    From apollo with Apache License 2.0 6 votes vote down vote up
public ReleaseDTO createRelease(String appId, Env env, String clusterName, String namespace,
    String releaseName, String releaseComment, String operator,
    boolean isEmergencyPublish) {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
  MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
  parameters.add("name", releaseName);
  parameters.add("comment", releaseComment);
  parameters.add("operator", operator);
  parameters.add("isEmergencyPublish", String.valueOf(isEmergencyPublish));
  HttpEntity<MultiValueMap<String, String>> entity =
      new HttpEntity<>(parameters, headers);
  ReleaseDTO response = restTemplate.post(
      env, "apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases", entity,
      ReleaseDTO.class, appId, clusterName, namespace);
  return response;
}
 
Example #10
Source File: DefaultWebClientBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public DefaultWebClientBuilder(DefaultWebClientBuilder other) {
	Assert.notNull(other, "DefaultWebClientBuilder must not be null");

	this.baseUrl = other.baseUrl;
	this.defaultUriVariables =
			other.defaultUriVariables != null ? new LinkedHashMap<>(other.defaultUriVariables) : null;
	this.uriBuilderFactory = other.uriBuilderFactory;
	if (other.defaultHeaders != null) {
		this.defaultHeaders = new HttpHeaders();
		this.defaultHeaders.putAll(other.defaultHeaders);
	}
	else {
		this.defaultHeaders = null;
	}
	this.defaultCookies =
			other.defaultCookies != null ? new LinkedMultiValueMap<>(other.defaultCookies) : null;
	this.defaultRequest = other.defaultRequest;
	this.filters = other.filters != null ? new ArrayList<>(other.filters) : null;
	this.connector = other.connector;
	this.exchangeFunction = other.exchangeFunction;
	this.exchangeStrategies = other.exchangeStrategies;
}
 
Example #11
Source File: DefaultServerRequestBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private static MultiValueMap<String, String> parseQueryParams(URI uri) {
	MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
	String query = uri.getRawQuery();
	if (query != null) {
		Matcher matcher = QUERY_PATTERN.matcher(query);
		while (matcher.find()) {
			String name = UriUtils.decode(matcher.group(1), StandardCharsets.UTF_8);
			String eq = matcher.group(2);
			String value = matcher.group(3);
			if (value != null) {
				value = UriUtils.decode(value, StandardCharsets.UTF_8);
			}
			else {
				value = (StringUtils.hasLength(eq) ? "" : null);
			}
			queryParams.add(name, value);
		}
	}
	return queryParams;
}
 
Example #12
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 #13
Source File: WebUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Parse the given string with matrix variables. An example string would look
 * like this {@code "q1=a;q1=b;q2=a,b,c"}. The resulting map would contain
 * keys {@code "q1"} and {@code "q2"} with values {@code ["a","b"]} and
 * {@code ["a","b","c"]} respectively.
 * @param matrixVariables the unparsed matrix variables string
 * @return a map with matrix variable names and values (never {@code null})
 * @since 3.2
 */
public static MultiValueMap<String, String> parseMatrixVariables(String matrixVariables) {
	MultiValueMap<String, String> result = new LinkedMultiValueMap<>();
	if (!StringUtils.hasText(matrixVariables)) {
		return result;
	}
	StringTokenizer pairs = new StringTokenizer(matrixVariables, ";");
	while (pairs.hasMoreTokens()) {
		String pair = pairs.nextToken();
		int index = pair.indexOf('=');
		if (index != -1) {
			String name = pair.substring(0, index);
			String rawValue = pair.substring(index + 1);
			for (String value : StringUtils.commaDelimitedListToStringArray(rawValue)) {
				result.add(name, value);
			}
		}
		else {
			result.add(pair, "");
		}
	}
	return result;
}
 
Example #14
Source File: StoreApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Returns pet inventories by status
 * Returns a map of status codes to quantities
 * <p><b>200</b> - successful operation
 * @return Map&lt;String, Integer&gt;
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
 */
public Mono<Map<String, Integer>> getInventory() throws WebClientResponseException {
    Object postBody = null;
    // create path and map variables
    final Map<String, Object> pathParams = new HashMap<String, Object>();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] localVarAccepts = { 
        "application/json"
    };
    final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String[] localVarContentTypes = { };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "api_key" };

    ParameterizedTypeReference<Map<String, Integer>> localVarReturnType = new ParameterizedTypeReference<Map<String, Integer>>() {};
    return apiClient.invokeAPI("/store/inventory", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #15
Source File: HttpImpl.java    From heimdall with Apache License 2.0 6 votes vote down vote up
@Override
public HttpImpl body(Map<String, Object> params) {

    if (headers.containsKey("Content-Type")
            && headers.get("Content-Type").get(0).equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
        formData = new LinkedMultiValueMap<>();
        params.forEach((key, value) -> {
            List<String> values = new ArrayList<>();
            values.add(value.toString());
            formData.put(key, values);
        });
    } else {

        body = json.parse(params);
    }

    return this;
}
 
Example #16
Source File: WebExchangeDataBinderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testFieldDefaultPreemptsFieldMarker() throws Exception {
	MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
	formData.add("!postProcessed", "on");
	formData.add("_postProcessed", "visible");
	formData.add("postProcessed", "on");
	this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000));
	assertTrue(this.testBean.isPostProcessed());

	formData.remove("postProcessed");
	this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000));
	assertTrue(this.testBean.isPostProcessed());

	formData.remove("!postProcessed");
	this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000));
	assertFalse(this.testBean.isPostProcessed());
}
 
Example #17
Source File: RequestHeaderMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolveMultiValueMapArgument() throws Exception {
	String name = "foo";
	String value1 = "bar";
	String value2 = "baz";
	MockServerHttpRequest request = MockServerHttpRequest.get("/").header(name, value1, value2).build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	MultiValueMap<String, String> expected = new LinkedMultiValueMap<>(1);
	expected.add(name, value1);
	expected.add(name, value2);

	Mono<Object> mono = resolver.resolveArgument(paramMultiValueMap, null, exchange);
	Object result = mono.block();

	assertTrue(result instanceof MultiValueMap);
	assertEquals("Invalid result", expected, result);
}
 
Example #18
Source File: WebRequestDataBinderIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void partListBinding() {
	PartListBean bean = new PartListBean();
	partListServlet.setBean(bean);

	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("partList", "first value");
	parts.add("partList", "second value");
	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	parts.add("partList", logo);

	template.postForLocation(baseUrl + "/partlist", parts);

	assertNotNull(bean.getPartList());
	assertEquals(parts.get("partList").size(), bean.getPartList().size());
}
 
Example #19
Source File: StandardMultipartHttpServletRequestTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void multipartFileResource() throws IOException {
	String name = "file";
	String disposition = "form-data; name=\"" + name + "\"; filename=\"myFile.txt\"";
	StandardMultipartHttpServletRequest request = requestWithPart(name, disposition, "myBody");
	MultipartFile multipartFile = request.getFile(name);

	assertNotNull(multipartFile);

	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.add(name, multipartFile.getResource());

	MockHttpOutputMessage output = new MockHttpOutputMessage();
	new FormHttpMessageConverter().write(map, null, output);

	assertThat(output.getBodyAsString(StandardCharsets.UTF_8), containsString(
			"Content-Disposition: form-data; name=\"file\"; filename=\"myFile.txt\"\r\n" +
					"Content-Type: text/plain\r\n" +
					"Content-Length: 6\r\n" +
					"\r\n" +
					"myBody\r\n"));
}
 
Example #20
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity
        .post(URI.create(clientRegistration.getProviderDetails().getTokenUri()))
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(formParameters);

    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
 
Example #21
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Find pet by ID
 * Returns a single pet
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid ID supplied
 * <p><b>404</b> - Pet not found
 * @param petId ID of pet to return (required)
 * @return ResponseEntity&lt;Pet&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = apiClient.expandPath("/pet/{petId}", uriVariables);

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { 
        "application/xml", "application/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] { "api_key" };

    ParameterizedTypeReference<Pet> returnType = new ParameterizedTypeReference<Pet>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #22
Source File: UserApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Updated user
 * This can only be done by the logged in user.
 * <p><b>400</b> - Invalid user supplied
 * <p><b>404</b> - User not found
 * @param username name that need to be deleted (required)
 * @param body Updated user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> updateUserWithHttpInfo(String username, User body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'username' is set
    if (username == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser");
    }
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("username", username);
    String path = apiClient.expandPath("/user/{username}", uriVariables);

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #23
Source File: MessageForm.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * MessageForm validation method from STRUCT interface.
    *
    */
   public MultiValueMap<String, String> validate(HttpServletRequest request, MessageService messageService) {

MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<String, String>();

try {
    if (StringUtils.isBlank(message.getSubject())) {
	errorMap.add("message.subject", messageService.getMessage("error.subject.required"));
    }
    boolean isTestHarness = Boolean.valueOf(request.getParameter("testHarness"));
    if (!isTestHarness && StringUtils.isBlank(message.getBody())) {
	errorMap.add("message.body", messageService.getMessage("error.body.required"));
    }

    // validate item size
    boolean largeFile = true;
    if (request.getRequestURI().indexOf("/learning/") != -1) {
	if ((this.getAttachmentFile() != null)
		&& FileUtil.isExecutableFile(this.getAttachmentFile().getOriginalFilename())) {
	    errorMap.add("message.attachments", messageService.getMessage("error.attachment.executable"));
	}
	largeFile = false;
    }

    FileValidatorUtil.validateFileSize(this.getAttachmentFile(), largeFile);

} catch (Exception e) {
    MessageForm.logger.error("", e);
}
return errorMap;
   }
 
Example #24
Source File: WebExchangeDataBinderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testFieldDefaultNonBoolean() throws Exception {
	MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
	formData.add("!name", "anonymous");
	formData.add("name", "Scott");
	this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000));
	assertEquals("Scott", this.testBean.getName());

	formData.remove("name");
	this.binder.bind(exchange(formData)).block(Duration.ofMillis(5000));
	assertEquals("anonymous", this.testBean.getName());
}
 
Example #25
Source File: RegistrationService.java    From eureka-consul-adapter with MIT License 5 votes vote down vote up
private <T> Single<ChangeItem<T>> returnDeferred(long waitMillis, Long index,
                                                 Supplier<Long> lastEmitted, Function<Long, Observable<Long>> supplyObservable,
                                                 Supplier<T> fn) {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    if (index == null || !lastEmitted.get().equals(index)) {
        return Single.just(new ChangeItem<>(fn.get(), lastEmitted.get()));
    } else {
        return supplyObservable.apply(waitMillis)
                .map(idx -> new ChangeItem<>(fn.get(), idx))
                .first()
                .toSingle();
    }
}
 
Example #26
Source File: MatrixVariablesMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private MultiValueMap<String, String> getMatrixVariables(String pathVarName) {
	Map<String, MultiValueMap<String, String>> matrixVariables =
			this.exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	matrixVariables.put(pathVarName, params);

	return params;
}
 
Example #27
Source File: WebfluxTwitterDemoApplication.java    From webflux-twitter-demo with MIT License 5 votes vote down vote up
@Bean
public CommandLineRunner tweetBot(TwitterOAuth twitterOAuth, ReactiveTweetRepository tweetRepo) {

    return args -> {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();

        String tracks = "#cltjug,#FathersDay";
        if (args.length > 0) {
            log.info("Using arguments as tracks");
            tracks = String.join(",", args);
        }

        log.info("Filtering tracks [{}]", tracks);
        body.add("track", tracks);

        WebClient webClient = WebClient.create()
                .filter((currentRequest, next) ->
                        next.exchange(ClientRequest.from(currentRequest)
                                .header(HttpHeaders.AUTHORIZATION, twitterOAuth.oAuth1Header(
                                        currentRequest.url(), currentRequest.method(), body.toSingleValueMap()))
                                .build()));

        Flux<Tweet> tweets = webClient
                .post()
                .uri(TwitterApiEndpoint.TWITTER_STREAM_API_STATUS_FILTER_URL)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(BodyInserters.fromFormData(body))
                .exchange()
                .flatMapMany(clientResponse -> clientResponse.bodyToFlux(Tweet.class));

        tweetRepo.saveAll(tweets).subscribe(System.out::println);

    };
}
 
Example #28
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Find pet by ID
 * Returns a single pet
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid ID supplied
 * <p><b>404</b> - Pet not found
 * @param petId ID of pet to return (required)
 * @return ResponseEntity&lt;Pet&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = apiClient.expandPath("/pet/{petId}", uriVariables);

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { 
        "application/xml", "application/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] { "api_key" };

    ParameterizedTypeReference<Pet> returnType = new ParameterizedTypeReference<Pet>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #29
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * test inline additionalProperties
 * 
 * <p><b>200</b> - successful operation
 * @param param request body (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> testInlineAdditionalPropertiesWithHttpInfo(Map<String, String> param) throws RestClientException {
    Object postBody = param;
    
    // verify the required parameter 'param' is set
    if (param == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'param' when calling testInlineAdditionalProperties");
    }
    
    String path = apiClient.expandPath("/fake/inline-additionalProperties", Collections.<String, Object>emptyMap());

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #30
Source File: UndertowServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
	for (String name : this.exchange.getRequestCookies().keySet()) {
		Cookie cookie = this.exchange.getRequestCookies().get(name);
		HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
		cookies.add(name, httpCookie);
	}
	return cookies;
}