org.springframework.util.MultiValueMap Java Examples

The following examples show how to use org.springframework.util.MultiValueMap. 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: GetCallTest.java    From springcloud-idempotent-starter with GNU General Public License v3.0 7 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.GET, 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.GET, requests2,
			String.class);
	String reponse2 = response2.getBody();
	System.out.println(reponse1 + "\n" + reponse2);
	Assert.assertNotEquals("The different result", reponse1, reponse2);
}
 
Example #2
Source File: SlackClient.java    From mojito with Apache License 2.0 7 votes vote down vote up
Channel openIm(User user) throws SlackClientException {
    Preconditions.checkNotNull(user.getId());

    MultiValueMap<String, Object> payload = getBasePayloadMapWithAuthToken();
    payload.add("user", user.getId());
    payload.add("return_im", "true");

    HttpEntity<MultiValueMap<String, Object>> httpEntity = getHttpEntityForPayload(payload);

    ImOpenResponse imOpenResponse = restTemplate.postForObject(getUrl(API_IM_OPEN), httpEntity, ImOpenResponse.class);

    if (!imOpenResponse.getOk()) {
        String msg = MessageFormat.format("Cannot open instant message: {0}", imOpenResponse.getError());
        logger.debug(msg);
        throw new SlackClientException(msg);
    }

    return imOpenResponse.getChannel();
}
 
Example #3
Source File: StandardMultipartHttpServletRequestTests.java    From spring-analysis-note 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 #4
Source File: ClientHttpRequest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the HTTP request entity encapsulating the headers and body of the HTTP message.  The body of the HTTP request
 * message will consist of an URL encoded application form (a mapping of key-value pairs) for POST/PUT HTTP requests.
 * <p/>
 * @return an HttpEntity with the headers and body for the HTTP request message.
 * @see #getParameters()
 * @see org.springframework.http.HttpEntity
 * @see org.springframework.http.HttpHeaders
 */
public HttpEntity<?> createRequestEntity() {
  if (isPost() || isPut()) {
    // NOTE HTTP request parameters take precedence over HTTP message body content/media
    if (!getParameters().isEmpty()) {
      getHeaders().setContentType(determineContentType(MediaType.APPLICATION_FORM_URLENCODED));
      return new HttpEntity<MultiValueMap<String, Object>>(getParameters(), getHeaders());
    }
    else {
      // NOTE the HTTP "Content-Type" header will be determined and set by the appropriate HttpMessageConverter
      // based on the Class type of the "content".
      return new HttpEntity<Object>(getContent(), getHeaders());
    }
  }
  else {
    return new HttpEntity<Object>(getHeaders());
  }
}
 
Example #5
Source File: HttpPutFormContentFilter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	if (("PUT".equals(request.getMethod()) || "PATCH".equals(request.getMethod())) && isFormContentType(request)) {
		HttpInputMessage inputMessage = new ServletServerHttpRequest(request) {
			@Override
			public InputStream getBody() throws IOException {
				return request.getInputStream();
			}
		};
		MultiValueMap<String, String> formParameters = formConverter.read(null, inputMessage);
		HttpServletRequest wrapper = new HttpPutFormContentRequestWrapper(request, formParameters);
		filterChain.doFilter(wrapper, response);
	}
	else {
		filterChain.doFilter(request, response);
	}
}
 
Example #6
Source File: StompHeaderAccessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void createWithConnectNativeHeaders() {
	MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
	extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe");
	extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123");

	StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders);

	assertEquals(StompCommand.CONNECT, headerAccessor.getCommand());
	assertEquals(SimpMessageType.CONNECT, headerAccessor.getMessageType());
	assertNotNull(headerAccessor.getHeader("stompCredentials"));
	assertEquals("joe", headerAccessor.getLogin());
	assertEquals("joe123", headerAccessor.getPasscode());
	assertThat(headerAccessor.toString(), CoreMatchers.containsString("passcode=[PROTECTED]"));

	Map<String, List<String>> output = headerAccessor.toNativeHeaderMap();
	assertEquals("joe", output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0));
	assertEquals("PROTECTED", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0));
}
 
Example #7
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 #8
Source File: UserInfoService.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) {
    RestTemplate restTemplate = new RestTemplate();

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(
            getHeader(accessToken),
            HttpMethod.GET,
            URI.create("https://www.googleapis.com/oauth2/v3/userinfo")
    );

    ResponseEntity<Map> result = restTemplate.exchange(
            requestEntity, Map.class);

    if (result.getStatusCode().is2xxSuccessful()) {
        return result.getBody();
    }

    throw new RuntimeException("It wasn't possible to retrieve userInfo");
}
 
Example #9
Source File: HierarchicalUriComponents.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Encode all URI components using their specific encoding rules and return
 * the result as a new {@code UriComponents} instance.
 * @param encoding the encoding of the values
 * @return the encoded uri components
 * @throws UnsupportedEncodingException if the given encoding is not supported
 */
@Override
public HierarchicalUriComponents encode(String encoding) throws UnsupportedEncodingException {
	if (this.encoded) {
		return this;
	}
	Assert.hasLength(encoding, "Encoding must not be empty");
	String schemeTo = encodeUriComponent(getScheme(), encoding, Type.SCHEME);
	String userInfoTo = encodeUriComponent(this.userInfo, encoding, Type.USER_INFO);
	String hostTo = encodeUriComponent(this.host, encoding, getHostType());
	PathComponent pathTo = this.path.encode(encoding);
	MultiValueMap<String, String> paramsTo = encodeQueryParams(encoding);
	String fragmentTo = encodeUriComponent(getFragment(), encoding, Type.FRAGMENT);
	return new HierarchicalUriComponents(schemeTo, userInfoTo, hostTo, this.port,
			pathTo, paramsTo, fragmentTo, true, false);
}
 
Example #10
Source File: WorkbasketController.java    From taskana with Apache License 2.0 6 votes vote down vote up
@GetMapping(path = Mapping.URL_WORKBASKET)
@Transactional(readOnly = true, rollbackFor = Exception.class)
public ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> getWorkbaskets(
    @RequestParam MultiValueMap<String, String> params) throws InvalidArgumentException {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Entry to getWorkbaskets(params= {})", params);
  }

  WorkbasketQuery query = workbasketService.createWorkbasketQuery();
  query = applySortingParams(query, params);
  applyFilterParams(query, params);

  PageMetadata pageMetadata = getPageMetadata(params, query);
  List<WorkbasketSummary> workbasketSummaries = getQueryList(query, pageMetadata);
  TaskanaPagedModel<WorkbasketSummaryRepresentationModel> pagedModels =
      workbasketSummaryRepresentationModelAssembler.toPageModel(
          workbasketSummaries, pageMetadata);

  ResponseEntity<TaskanaPagedModel<WorkbasketSummaryRepresentationModel>> response =
      ResponseEntity.ok(pagedModels);
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Exit from getWorkbaskets(), returning {}", response);
  }

  return response;
}
 
Example #11
Source File: FacebookTokenServices.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2Authentication loadAuthentication(final String accessToken)
    throws AuthenticationException, InvalidTokenException {

  final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
  formData.add(tokenName, accessToken);

  final HttpHeaders headers = new HttpHeaders();
  String req = "";
  try {
    req = checkTokenEndpointUrl + "?access_token=" + URLEncoder.encode(accessToken, "UTF-8");
  } catch (final UnsupportedEncodingException e) {
    logger.error("Unsupported encoding", e);
  }

  final Map<String, Object> map = getForMap(req, formData, headers);

  if (map.containsKey("error")) {
    logger.debug("check_token returned error: " + map.get("error"));
    throw new InvalidTokenException(accessToken);
  }

  return tokenConverter.extractAuthentication(map);
}
 
Example #12
Source File: LearningController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private boolean validateBeforeFinish(HttpServletRequest request, String sessionMapID) {
SessionMap<String, Object> sessionMap = getSessionMap(request);
Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);

HttpSession ss = SessionManager.getSession();
UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
Long userID = user.getUserID().longValue();

int numberCompletedTasks = taskListService.getNumTasksCompletedByUser(sessionId, userID);
int minimumNumberTasks = taskListService.getTaskListBySessionId(sessionId).getMinimumNumberTasks();
// if current user view less than reqired view count number, then just return error message.
if ((minimumNumberTasks - numberCompletedTasks) > 0) {
    MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();
    errorMap.add("GLOBAL", messageService.getMessage("lable.learning.minimum.view.number"));
    request.setAttribute("errorMap", errorMap);
    return false;
}

return true;
   }
 
Example #13
Source File: WebMvcStompWebSocketEndpointRegistrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void handshakeHandlerAndInterceptorWithAllowedOrigins() {
	WebMvcStompWebSocketEndpointRegistration registration =
			new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);

	DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
	HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();
	String origin = "https://mydomain.com";
	registration.setHandshakeHandler(handshakeHandler).addInterceptors(interceptor).setAllowedOrigins(origin);

	MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
	assertEquals(1, mappings.size());

	Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
	assertEquals(Arrays.asList("/foo"), entry.getValue());

	WebSocketHttpRequestHandler requestHandler = (WebSocketHttpRequestHandler) entry.getKey();
	assertNotNull(requestHandler.getWebSocketHandler());
	assertSame(handshakeHandler, requestHandler.getHandshakeHandler());
	assertEquals(2, requestHandler.getHandshakeInterceptors().size());
	assertEquals(interceptor, requestHandler.getHandshakeInterceptors().get(0));
	assertEquals(OriginHandshakeInterceptor.class, requestHandler.getHandshakeInterceptors().get(1).getClass());
}
 
Example #14
Source File: SynchronossPartHttpMessageReaderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void canRead() {
	assertTrue(this.reader.canRead(
			forClassWithGenerics(MultiValueMap.class, String.class, Part.class),
			MediaType.MULTIPART_FORM_DATA));

	assertFalse(this.reader.canRead(
			forClassWithGenerics(MultiValueMap.class, String.class, Object.class),
			MediaType.MULTIPART_FORM_DATA));

	assertFalse(this.reader.canRead(
			forClassWithGenerics(MultiValueMap.class, String.class, String.class),
			MediaType.MULTIPART_FORM_DATA));

	assertFalse(this.reader.canRead(
			forClassWithGenerics(Map.class, String.class, String.class),
			MediaType.MULTIPART_FORM_DATA));

	assertFalse(this.reader.canRead(
			forClassWithGenerics(MultiValueMap.class, String.class, Part.class),
			MediaType.APPLICATION_FORM_URLENCODED));
}
 
Example #15
Source File: SpringMvcIntegrationTestBase.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void ableToPostDate() throws Exception {
  ZonedDateTime date = ZonedDateTime.now().truncatedTo(SECONDS);
  MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
  body.add("date", RestObjectMapperFactory.getRestObjectMapper().convertToString(Date.from(date.toInstant())));

  HttpHeaders headers = new HttpHeaders();
  headers.add(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE);

  int seconds = 1;
  Date result = restTemplate.postForObject(codeFirstUrl + "addDate?seconds={seconds}",
      new HttpEntity<>(body, headers),
      Date.class,
      seconds);

  assertThat(result, is(Date.from(date.plusSeconds(seconds).toInstant())));

  ListenableFuture<ResponseEntity<Date>> listenableFuture = asyncRestTemplate
      .postForEntity(codeFirstUrl + "addDate?seconds={seconds}",
          new HttpEntity<>(body, headers),
          Date.class,
          seconds);
  ResponseEntity<Date> dateResponseEntity = listenableFuture.get();
  assertThat(dateResponseEntity.getBody(), is(Date.from(date.plusSeconds(seconds).toInstant())));
}
 
Example #16
Source File: RestTemplateBasicLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenFooService_whenFormSubmit_thenResourceIsCreated() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
    map.add("id", "1");

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

    ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);

    assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
    final String fooResponse = response.getBody();
    assertThat(fooResponse, notNullValue());
    assertThat(fooResponse, is("1"));
}
 
Example #17
Source File: FormHttpMessageReaderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void readFormError() {
	DataBuffer fooBuffer = stringBuffer("name=value");
	Flux<DataBuffer> body =
			Flux.just(fooBuffer).concatWith(Flux.error(new RuntimeException()));
	MockServerHttpRequest request = request(body);

	Flux<MultiValueMap<String, String>> result = this.reader.read(null, request, null);
	StepVerifier.create(result)
			.expectError()
			.verify();
}
 
Example #18
Source File: XsuaaOAuth2TokenServicePasswordTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void retrieveToken_setsUsername() throws OAuth2ServiceException {
	cut.retrieveAccessTokenViaPasswordGrant(tokenEndpoint, clientCredentials,
			username, password, null, null);

	ArgumentCaptor<HttpEntity<MultiValueMap<String, String>>> requestEntityCaptor = captureRequestEntity();

	assertThat(valueOfParameter(USERNAME, requestEntityCaptor)).isEqualTo(username);
}
 
Example #19
Source File: DefaultSubscriptionRegistryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void registerSubscriptionWithSelector() {
	String sessionId = "sess01";
	String subscriptionId = "subs01";
	String destination = "/foo";
	String selector = "headers.foo == 'bar'";

	this.registry.registerSubscription(subscribeMessage(sessionId, subscriptionId, destination, selector));

	// First, try with selector header

	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
	accessor.setDestination(destination);
	accessor.setNativeHeader("foo", "bar");
	Message<?> message = MessageBuilder.createMessage("", accessor.getMessageHeaders());

	MultiValueMap<String, String> actual = this.registry.findSubscriptions(message);
	assertNotNull(actual);
	assertEquals(1, actual.size());
	assertEquals(Collections.singletonList(subscriptionId), actual.get(sessionId));

	// Then without

	actual = this.registry.findSubscriptions(createMessage(destination));
	assertNotNull(actual);
	assertEquals(0, actual.size());
}
 
Example #20
Source File: RequestParamMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
public void handle(
		@RequestParam Map<String, String> param1,
		@RequestParam MultiValueMap<String, String> param2,
		@RequestParam Map<String, MultipartFile> param3,
		@RequestParam MultiValueMap<String, MultipartFile> param4,
		@RequestParam Map<String, Part> param5,
		@RequestParam MultiValueMap<String, Part> param6,
		@RequestParam("name") Map<String, String> param7,
		Map<String, String> param8) {
}
 
Example #21
Source File: RequestMappingInfoHandlerMapping.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Map<String, MultiValueMap<String, String>> extractMatrixVariables(
		HttpServletRequest request, Map<String, String> uriVariables) {

	Map<String, MultiValueMap<String, String>> result = new LinkedHashMap<String, MultiValueMap<String, String>>();
	for (Entry<String, String> uriVar : uriVariables.entrySet()) {
		String uriVarValue = uriVar.getValue();

		int equalsIndex = uriVarValue.indexOf('=');
		if (equalsIndex == -1) {
			continue;
		}

		String matrixVariables;

		int semicolonIndex = uriVarValue.indexOf(';');
		if ((semicolonIndex == -1) || (semicolonIndex == 0) || (equalsIndex < semicolonIndex)) {
			matrixVariables = uriVarValue;
		}
		else {
			matrixVariables = uriVarValue.substring(semicolonIndex + 1);
			uriVariables.put(uriVar.getKey(), uriVarValue.substring(0, semicolonIndex));
		}

		MultiValueMap<String, String> vars = WebUtils.parseMatrixVariables(matrixVariables);
		result.put(uriVar.getKey(), getUrlPathHelper().decodeMatrixVariables(request, vars));
	}
	return result;
}
 
Example #22
Source File: StoreApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Place an order for a pet
 * 
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid Order
 * @param body order placed for purchasing the pet (required)
 * @return ResponseEntity&lt;Order&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Order> placeOrderWithHttpInfo(Order body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder");
    }
    
    String path = apiClient.expandPath("/store/order", 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 = { 
        "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<Order> returnType = new ParameterizedTypeReference<Order>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #23
Source File: AsyncRestTemplateIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void multipart() throws Exception {
	MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
	parts.add("name 1", "value 1");
	parts.add("name 2", "value 2+1");
	parts.add("name 2", "value 2+2");
	Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
	parts.add("logo", logo);

	HttpEntity<MultiValueMap<String, Object>> requestBody = new HttpEntity<>(parts);
	Future<URI> future = template.postForLocation(baseUrl + "/multipart", requestBody);
	future.get();
}
 
Example #24
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Add a new pet to the store
 * 
 * <p><b>200</b> - successful operation
 * <p><b>405</b> - Invalid input
 * @param body Pet object that needs to be added to the store
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
 */
public Mono<Void> addPet(Pet body) throws WebClientResponseException {
    Object postBody = body;
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new WebClientResponseException("Missing the required parameter 'body' when calling addPet", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, 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 = { 
        "application/json", "application/xml"
    };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

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

    ParameterizedTypeReference<Void> localVarReturnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI("/pet", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #25
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Updates a pet in the store with form data
 * 
 * <p><b>405</b> - Invalid input
 * @param petId ID of pet that needs to be updated (required)
 * @param name Updated name of the pet (optional)
 * @param status Updated status of the pet (optional)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status) 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 updatePetWithForm");
    }
    
    // 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();

    if (name != null)
        formParams.add("name", name);
    if (status != null)
        formParams.add("status", status);

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

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #26
Source File: AbstractNamedValueServiceParameterResolver.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolve(RestMethodMetadata restMethodMetadata,
		MethodParameterMetadata methodParameterMetadata, HttpServerRequest request) {

	Collection<String> names = getNames(restMethodMetadata, methodParameterMetadata);

	if (isEmpty(names)) { // index can't match
		return null;
	}

	MultiValueMap<String, String> nameAndValues = getNameAndValuesMap(request);

	String targetName = null;

	for (String name : names) {
		if (nameAndValues.containsKey(name)) {
			targetName = name;
			break;
		}
	}

	if (targetName == null) { // request parameter is abstract
		return null;
	}

	Class<?> parameterType = resolveClass(methodParameterMetadata.getType());

	Object paramValue = null;

	if (parameterType.isArray()) { // Array type
		paramValue = nameAndValues.get(targetName);
	}
	else {
		paramValue = nameAndValues.getFirst(targetName);
	}

	return resolveValue(paramValue, parameterType);
}
 
Example #27
Source File: PetApi.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Finds Pets by tags
 * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid tag value
 * @param tags Tags to filter by (required)
 * @return ResponseEntity&lt;List&lt;Pet&gt;&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
@Deprecated
public ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags) throws RestClientException {
    Object postBody = null;

    // verify the required parameter 'tags' is set
    if (tags == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags");
    }

    String path = apiClient.expandPath("/pet/findByTags", 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();

    queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "tags", tags));

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

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

    ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #28
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * This method will get necessary information from commonCartridge item form and save or update into
    * <code>HttpSession</code> CommonCartridgeItemList. Notice, this save is not persist them into database, just save
    * <code>HttpSession</code> temporarily. Only they will be persist when the entire authoring page is being
    * persisted.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   @RequestMapping(path = "/saveOrUpdateItem", method = RequestMethod.POST)
   private String saveOrUpdateItem(
    @ModelAttribute("commonCartridgeItemForm") CommonCartridgeItemForm commonCartridgeItemForm,
    HttpServletRequest request) {
MultiValueMap<String, String> errorMap = validateCommonCartridgeItem(commonCartridgeItemForm);

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return findForward(commonCartridgeItemForm.getItemType());
}

short type = commonCartridgeItemForm.getItemType();
try {
    if (type == CommonCartridgeConstants.RESOURCE_TYPE_COMMON_CARTRIDGE) {
	uploadCommonCartridge(request, commonCartridgeItemForm);
    } else {
	extractFormToCommonCartridgeItem(request, commonCartridgeItemForm);
    }
} catch (Exception e) {
    // any upload exception will display as normal error message rather then throw exception directly
    errorMap.add("GLOBAL", messageService.getMessage(CommonCartridgeConstants.ERROR_MSG_UPLOAD_FAILED,
	    new Object[] { e.getMessage() }));
    if (!errorMap.isEmpty()) {
	request.setAttribute("errorMap", errorMap);
	return findForward(commonCartridgeItemForm.getItemType());
    }
}
// set session map ID so that itemlist.jsp can get sessionMAP
request.setAttribute(CommonCartridgeConstants.ATTR_SESSION_MAP_ID, commonCartridgeItemForm.getSessionMapID());
// return null to close this window

if (type == CommonCartridgeConstants.RESOURCE_TYPE_COMMON_CARTRIDGE) {
    return "pages/authoring/parts/selectResources";
} else {
    return "pages/authoring/parts/itemlist";
}
   }
 
Example #29
Source File: RSQLCommonSupport.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
public static Map<String, MultiValueMap<String, String>> toComplexMultiValueMap(final String rsqlQuery) {
	log.debug("toComplexMultiValueMap(rsqlQuery:{})", rsqlQuery);
	Map<String, MultiValueMap<String, String>> map = new HashMap<>();
	if (StringUtils.hasText(rsqlQuery)) {
		new RSQLParser(RSQLOperators.supportedOperators()).parse(rsqlQuery).accept(new RSQLComplexConverter(), map);
	}
	return map;
}
 
Example #30
Source File: WebExchangeDataBinderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testFieldPrefixCausesFieldReset() throws Exception {
	MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
	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));
	assertFalse(this.testBean.isPostProcessed());
}