类org.springframework.util.LinkedMultiValueMap源码实例Demo

下面列出了怎么用org.springframework.util.LinkedMultiValueMap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: lams   文件: AdminController.java
/**
    * Validate BasicLTIConfigItems.
    *
    * @param adminForm
    * @return
    */
   private MultiValueMap<String, String> validateAdminForm(AdminForm commonCartridgeAdminForm) {
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();

// if ((adminForm.isAllowExposeUserName() == null) || adminForm.isAllowExposeUserName().equals("")) {
// if (!isParsableToInt(adminForm.isAllowExposeUserName())) {
// errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
// BasicLTIConstants.ERROR_MSG_ENTERED_VALUES_NOT_INTEGERS));
// }
// } else {
// errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
// BasicLTIConstants.ERROR_MSG_REQUIRED_FIELDS_MISSING));
// }
//
// if ((adminForm.isAllowExposeUserEmail() != null) && !adminForm.isAllowExposeUserEmail().equals("")) {
// if (!isParsableToInt(adminForm.isAllowExposeUserEmail())) {
// errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
// BasicLTIConstants.ERROR_MSG_ENTERED_VALUES_NOT_INTEGERS));
// }
// } else {
// errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
// BasicLTIConstants.ERROR_MSG_REQUIRED_FIELDS_MISSING));
// }

return errorMap;
   }
 
源代码2 项目: lams   文件: AnnotatedElementUtils.java
/**
 * 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);
}
 
源代码3 项目: wallride   文件: PageSearchForm.java
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;
}
 
源代码4 项目: openapi-generator   文件: UserApi.java
/**
 * 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);
}
 
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;

}
 
源代码6 项目: spring-cloud-alibaba   文件: OrderController.java
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);
}
 
源代码7 项目: openapi-generator   文件: FakeApi.java
/**
 * 
 * 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);
}
 
源代码8 项目: wallride   文件: ArticleSearchForm.java
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;
}
 
源代码9 项目: apollo   文件: AdminServiceAPI.java
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;
}
 
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);
    }
}
 
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;
}
 
@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"));
}
 
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;
}
 
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;
}
 
源代码15 项目: spring-analysis-note   文件: WebUtils.java
/**
 * 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;
}
 
源代码16 项目: openapi-generator   文件: StoreApi.java
/**
 * 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);
}
 
源代码17 项目: heimdall   文件: HttpImpl.java
@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;
}
 
@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());
}
 
@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);
}
 
@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());
}
 
@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);
}
 
@Override
public <T> T postFileForObject(String url, File file, Class<T> responseType, String... params) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(1);
    body.add("file", file);

    return execute(() -> restTemplate.postForObject(url, new HttpEntity<>(body, headers), responseType, (Object[]) params));
}
 
源代码23 项目: bearchoke   文件: QuotesWebSocketIntegrationTest.java
private static void loginAndSaveXAuthToken(final String user, final String password,
										   final HttpHeaders headersToUpdate) {

	log.info("Authenticating user before subscribing to web socket");

	String url = "http://dev.bearchoke.com:" + port + "/api/authenticate";

	try {
		new RestTemplate().execute(url, HttpMethod.POST,

				request -> {
					MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
					map.add("username", user);
					map.add("password", password);
					new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
				},

				response -> {
					String xAuthToken = response.getHeaders().getFirst(ServerConstants.X_AUTH_TOKEN);
					log.info("Retrieved x-auth-token: " + xAuthToken);
					headersToUpdate.add(ServerConstants.X_AUTH_TOKEN, xAuthToken);
					return null;
				});
	} catch (Exception ex) {
		log.error(ex.getMessage(), ex);
	}
}
 
源代码24 项目: chuidiang-ejemplos   文件: RestRequests.java
public void postGreeting(RestTemplate restTemplate) {
   String name = "New Greeting";
   MultiValueMap<String, Object> values = new LinkedMultiValueMap<String, Object>();
   values.add("content", name);
   Greeting gretting = restTemplate.postForObject(
         "http://localhost:8080/greeting", values, Greeting.class);
   System.out.println("POSTED: " + gretting);
}
 
protected ExitStatus runJobAndWaitForCompletion(String hostname, String port, String jobName, String jobParameters)
		throws InterruptedException {
	MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
	parameters.add("jobParameters", jobParameters);
	String jobExecutionId = restTemplate.postForObject(
			"http://" + hostname + ":" + port + "/batch/operations/jobs/" + jobName + "", parameters, String.class);
	ExitStatus exitStatus = getStatus(hostname, port, jobExecutionId);
	// Wait for end of job
	while (exitStatus.isRunning()) {
		Thread.sleep(100);
		exitStatus = getStatus(hostname, port, jobExecutionId);
	}
	return exitStatus;
}
 
源代码26 项目: tutorials   文件: UserApi.java
/**
 * Logs user into the system
 * 
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid username/password supplied
 * @param username The user name for login
 * @param password The password for login in clear text
 * @return String
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public String loginUser(String username, String password) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'username' is set
    if (username == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser");
    }
    
    // verify the required parameter 'password' is set
    if (password == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser");
    }
    
    String path = UriComponentsBuilder.fromPath("/user/login").build().toUriString();
    
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password));

    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[] {  };

    ParameterizedTypeReference<String> returnType = new ParameterizedTypeReference<String>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
@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);

    };
}
 
@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());
}
 
源代码29 项目: openapi-generator   文件: UserApi.java
/**
 * 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);
}
 
源代码30 项目: lams   文件: MessageForm.java
/**
    * 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;
   }
 
 类所在包
 类方法
 同包方法