Java Code Examples for org.springframework.util.LinkedMultiValueMap

The following examples show how to use org.springframework.util.LinkedMultiValueMap. These examples are extracted from open source projects. 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 Project: lams   Source File: AnnotatedElementUtils.java    License: 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 2
Source Project: wallride   Source File: PageSearchForm.java    License: 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 3
Source Project: openapi-generator   Source File: UserApi.java    License: 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 4
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 5
Source Project: spring-cloud-alibaba   Source File: OrderController.java    License: 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 6
Source Project: openapi-generator   Source File: FakeApi.java    License: 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 7
Source Project: wallride   Source File: ArticleSearchForm.java    License: 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 8
Source Project: apollo   Source File: AdminServiceAPI.java    License: 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 9
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 10
Source Project: spring-analysis-note   Source File: DefaultWebClientBuilder.java    License: 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
@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 12
Source Project: spring-analysis-note   Source File: DefaultServerRequestBuilder.java    License: 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 13
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 14
Source Project: spring-analysis-note   Source File: WebUtils.java    License: 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 15
Source Project: openapi-generator   Source File: StoreApi.java    License: 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 16
Source Project: heimdall   Source File: HttpImpl.java    License: 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 17
Source Project: java-technology-stack   Source File: WebExchangeDataBinderTests.java    License: 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 18
@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 19
@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 20
@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 21
@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));
}
 
Example 22
Source Project: bearchoke   Source File: QuotesWebSocketIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 23
Source Project: lams   Source File: AdminController.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
    * 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;
   }
 
Example 24
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);
}
 
Example 25
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;
}
 
Example 26
Source Project: tutorials   Source File: UserApi.java    License: MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 27
@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 Project: spring-analysis-note   Source File: WebExchangeDataBinderTests.java    License: 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 29
Source Project: openapi-generator   Source File: UserApi.java    License: 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 30
Source Project: lams   Source File: MessageForm.java    License: 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;
   }