Java Code Examples for org.springframework.core.ParameterizedTypeReference

The following examples show how to use org.springframework.core.ParameterizedTypeReference. 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: yugastore-java   Source File: DashboardRestConsumer.java    License: Apache License 2.0 7 votes vote down vote up
public String removeProductFromCart(String asin) {

		String restURL = restUrlBase + "shoppingCart/removeProduct";
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.add("asin", asin);
		

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, null);

		ResponseEntity<String> rateResponse =
		        restTemplate.exchange(restURL,
		                    HttpMethod.POST, request, new ParameterizedTypeReference<String>() {
		            });
		String addProductJsonResponse = rateResponse.getBody();
		return addProductJsonResponse;
	}
 
Example 2
Source Project: spring-credhub   Source File: CredHubCertificateTemplate.java    License: Apache License 2.0 7 votes vote down vote up
public List<CertificateCredentialDetails> updateTransitionalVersion(final String id, final String versionId) {
	Assert.notNull(id, "credential ID must not be null");

	final ParameterizedTypeReference<List<CertificateCredentialDetails>> ref = new ParameterizedTypeReference<List<CertificateCredentialDetails>>() {
	};

	return this.credHubOperations.doWithRest((restOperations) -> {
		Map<String, String> request = new HashMap<>(1);
		request.put(VERSION_REQUEST_FIELD, versionId);

		ResponseEntity<List<CertificateCredentialDetails>> response = restOperations
				.exchange(UPDATE_TRANSITIONAL_URL_PATH, HttpMethod.PUT, new HttpEntity<Object>(request), ref, id);

		ExceptionUtils.throwExceptionOnError(response);

		return response.getBody();
	});
}
 
Example 3
Source Project: agent   Source File: ServerClient.java    License: MIT License 7 votes vote down vote up
public UploadFile uploadFile(File file, Integer fileType) {
    MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
    multiValueMap.add("file", new FileSystemResource(file));

    Response<UploadFile> response = restTemplate.exchange(uploadFileUrl,
            HttpMethod.POST,
            new HttpEntity<>(multiValueMap),
            new ParameterizedTypeReference<Response<UploadFile>>() {
            },
            fileType).getBody();

    if (response.isSuccess()) {
        return response.getData();
    } else {
        throw new RuntimeException(response.getMsg());
    }
}
 
Example 4
Source Project: influx-proxy   Source File: ConfigurationLoader.java    License: Apache License 2.0 6 votes vote down vote up
public List<BackendNode> getAllNodes(){
    if(proxyConfiguration.isEnable()){
        return proxyConfiguration.getNode();
    }else if(!StringUtils.isEmpty(opsPath)){
        ResponseEntity<List<BackendNode>> response = restTemplate.exchange(opsPath+"/node", HttpMethod.GET, null, new ParameterizedTypeReference<List<BackendNode>>() {
        });
        return response.getBody();
    }
    return EMPTY;
}
 
Example 5
Source Project: tutorials   Source File: StoreApi.java    License: MIT License 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 ResponseEntity&lt;Map&lt;String, Integer&gt;&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo() throws RestClientException {
    Object postBody = null;

    String path = apiClient.expandPath("/store/inventory", 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/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Map<String, Integer>> returnType = new ParameterizedTypeReference<Map<String, Integer>>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 6
Source Project: flowable-engine   Source File: RestApiApplicationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testContentRestApiIntegration() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/content-api/content-service/content-items";

    ResponseEntity<DataResponse<ContentItemResponse>> response = restTemplate
        .exchange(processDefinitionsUrl, HttpMethod.GET, null, new ParameterizedTypeReference<DataResponse<ContentItemResponse>>() {

        });

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<ContentItemResponse> contentItems = response.getBody();
    assertThat(contentItems).isNotNull();
    assertThat(contentItems.getData())
        .isEmpty();
    assertThat(contentItems.getTotal()).isZero();
}
 
Example 7
/**
   * 根据用户id 查询用户
   * @return
   */
  @Test
  public void getAll(){
  	URI uri = UriComponentsBuilder
		.fromUriString("http://localhost:8080/sbe/bootUser/")
		.build(1);
  	@SuppressWarnings("unchecked")
List<User> users = restTemplate.getForObject(uri, List.class);
  	Assert.assertTrue(users!=null && users.size()>0);
  	
  	
  /*	URI uri2 = UriComponentsBuilder
		.fromUriString("http://localhost:8080/coffee/?name={name}")
		.build("mocha");*/
  	
  	ParameterizedTypeReference<List<User>> ptr =
		new ParameterizedTypeReference<List<User>>() {};

ResponseEntity<List<User>> responseEntity = restTemplate
		.exchange(uri, HttpMethod.GET, null, ptr);
List<User> body = responseEntity.getBody();
Assert.assertTrue(users!=null && users.size()>0);
  }
 
Example 8
Source Project: skywalking   Source File: SimpleQueryClient.java    License: Apache License 2.0 6 votes vote down vote up
public Endpoints endpoints(final EndpointQuery query) throws Exception {
    final URL queryFileUrl = Resources.getResource("endpoints.gql");
    final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
                                        .stream()
                                        .filter(it -> !it.startsWith("#"))
                                        .collect(Collectors.joining())
                                        .replace("{serviceId}", query.serviceId());
    final ResponseEntity<GQLResponse<Endpoints>> responseEntity = restTemplate.exchange(
        new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
        new ParameterizedTypeReference<GQLResponse<Endpoints>>() {
        }
    );

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
    }

    return Objects.requireNonNull(responseEntity.getBody()).getData();
}
 
Example 9
Source Project: openapi-generator   Source File: FakeApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Test serialization of object with outer number type
 * <p><b>200</b> - Output composite
 * @param body Input composite as post body (optional)
 * @return ResponseEntity&lt;OuterComposite&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<OuterComposite> fakeOuterCompositeSerializeWithHttpInfo(OuterComposite body) throws RestClientException {
    Object postBody = body;
    
    String path = apiClient.expandPath("/fake/outer/composite", Collections.<String, Object>emptyMap());

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

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

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

    ParameterizedTypeReference<OuterComposite> returnType = new ParameterizedTypeReference<OuterComposite>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 10
@HystrixCommand(fallbackMethod="getDefaultIngredients",
    commandProperties={
        @HystrixProperty(
            name="execution.isolation.thread.timeoutInMilliseconds",
            value="500"),
            @HystrixProperty(
                name="circuitBreaker.requestVolumeThreshold",
                value="30"),
            @HystrixProperty(
                name="circuitBreaker.errorThresholdPercentage",
                value="25"),
            @HystrixProperty(
                name="metrics.rollingStats.timeInMilliseconds",
                value="20000"),
            @HystrixProperty(
                name="circuitBreaker.sleepWindowInMilliseconds",
                value="60000")
    })
public Iterable<Ingredient> getAllIngredients() {
  ParameterizedTypeReference<List<Ingredient>> stringList =
      new ParameterizedTypeReference<List<Ingredient>>() {};
  return rest.exchange(
      "http://ingredient-service/ingredients", HttpMethod.GET,
      HttpEntity.EMPTY, stringList).getBody();
}
 
Example 11
public List<Recommendation> getRecommendations(int productId) {

        try {
            String url = recommendationServiceUrl + productId;

            LOG.debug("Will call getRecommendations API on URL: {}", url);
            List<Recommendation> recommendations = restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<List<Recommendation>>() {}).getBody();

            LOG.debug("Found {} recommendations for a product with id: {}", recommendations.size(), productId);
            return recommendations;

        } catch (Exception ex) {
            LOG.warn("Got an exception while requesting recommendations, return zero recommendations: {}", ex.getMessage());
            return new ArrayList<>();
        }
    }
 
Example 12
protected void deleteObject(String path, Object... uriVariables) throws AuthServerClientException {
    String requestUri = buildFullUriString(path, clientProperties.getHttpScheme(),
            clientProperties.getHost(), clientProperties.getPort());

    URI expandedUri = userJwtSsoTokenRestTemplate.getUriTemplateHandler().expand(requestUri, uriVariables);

    ResponseEntity<AuthServerRestResponseDto<Object>> responseEntity = userJwtSsoTokenRestTemplate.exchange(
            expandedUri, HttpMethod.DELETE, buildRequestEntity(null),
            new ParameterizedTypeReference<AuthServerRestResponseDto<Object>>() {
            });
    AuthServerRestResponseDto<Object> responseDto = responseEntity.getBody();
    String status = responseDto.getStatus();
    if (!AuthServerRestResponseDto.STATUS_OK.equalsIgnoreCase(status)) {
        getLogger().warn("rest service invocation failed,status={},message={}", responseDto.getStatus(),
                responseDto.getMessage());
        throw new AuthServerClientException(responseDto.getStatus(), responseDto.getMessage());
    }
}
 
Example 13
Source Project: taskana   Source File: AccessIdControllerIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testBadRequestWhenSearchForIsTooShort() {
  ThrowingCallable httpCall =
      () -> {
        template.exchange(
            restHelper.toUrl(Mapping.URL_ACCESSID) + "?search-for=al",
            HttpMethod.GET,
            restHelper.defaultRequest(),
            ParameterizedTypeReference.forType(List.class));
      };
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .hasMessageContaining("Minimum searchFor length =")
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example 14
Source Project: skywalking   Source File: SimpleQueryClient.java    License: Apache License 2.0 6 votes vote down vote up
public Topology topo(final TopoQuery query) throws Exception {
    final URL queryFileUrl = Resources.getResource("topo.gql");
    final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
                                        .stream()
                                        .filter(it -> !it.startsWith("#"))
                                        .collect(Collectors.joining())
                                        .replace("{step}", query.step())
                                        .replace("{start}", query.start())
                                        .replace("{end}", query.end());
    final ResponseEntity<GQLResponse<TopologyResponse>> responseEntity = restTemplate.exchange(
        new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
        new ParameterizedTypeReference<GQLResponse<TopologyResponse>>() {
        }
    );

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
    }

    return Objects.requireNonNull(responseEntity.getBody()).getData().getTopo();
}
 
Example 15
Source Project: taskana   Source File: ClassificationControllerIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@DirtiesContext
void testCreateClassificationWithClassificationIdReturnsError400() {
  String newClassification =
      "{\"classificationId\":\"someId\",\"category\":\"MANUAL\","
          + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\","
          + "\"name\":\"new classification\",\"type\":\"TASK\"}";

  ThrowingCallable httpCall =
      () -> {
        template.exchange(
            restHelper.toUrl(Mapping.URL_CLASSIFICATIONS),
            HttpMethod.POST,
            new HttpEntity<>(newClassification, restHelper.getHeadersBusinessAdmin()),
            ParameterizedTypeReference.forType(ClassificationRepresentationModel.class));
      };
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example 16
Source Project: spring-credhub   Source File: CredHubCredentialTemplate.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> CredentialDetails<T> write(final CredentialRequest<T> credentialRequest) {
	Assert.notNull(credentialRequest, "credentialRequest must not be null");

	final ParameterizedTypeReference<CredentialDetails<T>> ref = new ParameterizedTypeReference<CredentialDetails<T>>() {
	};

	return this.credHubOperations.doWithRest((restOperations) -> {
		ResponseEntity<CredentialDetails<T>> response = restOperations.exchange(BASE_URL_PATH, HttpMethod.PUT,
				new HttpEntity<>(credentialRequest), ref);

		ExceptionUtils.throwExceptionOnError(response);

		return response.getBody();
	});
}
 
Example 17
Source Project: spring-analysis-note   Source File: WebClientIntegrationTests.java    License: MIT License 6 votes vote down vote up
@Test  // SPR-16715
public void shouldReceiveJsonAsTypeReferenceString() {
	String content = "{\"containerValue\":{\"fooValue\":\"bar\"}}";
	prepareResponse(response -> response
			.setHeader("Content-Type", "application/json").setBody(content));

	Mono<ValueContainer<Foo>> result = this.webClient.get()
			.uri("/json").accept(MediaType.APPLICATION_JSON)
			.retrieve()
			.bodyToMono(new ParameterizedTypeReference<ValueContainer<Foo>>() {});

	StepVerifier.create(result)
			.assertNext(valueContainer -> {
				Foo foo = valueContainer.getContainerValue();
				assertNotNull(foo);
				assertEquals("bar", foo.getFooValue());
			})
			.expectComplete().verify(Duration.ofSeconds(3));

	expectRequestCount(1);
	expectRequest(request -> {
		assertEquals("/json", request.getPath());
		assertEquals("application/json", request.getHeader(HttpHeaders.ACCEPT));
	});
}
 
Example 18
Source Project: syndesis   Source File: ExtensionsITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldListNoDependencyLibraries() throws IOException {
    // Create one extension
    final ResponseEntity<Extension> created = post("/api/v1/extensions", multipartBody(extensionData(1)),
        Extension.class, tokenRule.validToken(), HttpStatus.OK, multipartHeaders());

    assertThat(created.getBody().getId()).isPresent();
    final String id = created.getBody().getId().get();

    // Install it
    post("/api/v1/extensions/" + id + "/install", null, Void.class,
        tokenRule.validToken(), HttpStatus.NO_CONTENT);

    final ResponseEntity<ListResult<Extension>> list = get("/api/v1/extensions?extensionType=Libraries",
        new ParameterizedTypeReference<ListResult<Extension>>() {
        }, tokenRule.validToken(), HttpStatus.OK);

    assertThat(list.getBody().getItems()).hasSize(0);
}
 
Example 19
Source Project: jeeves   Source File: WechatHttpServiceInternal.java    License: MIT License 5 votes vote down vote up
byte[] downloadImage(String url) {
    HttpHeaders customHeader = new HttpHeaders();
    customHeader.set("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
    customHeader.set("Referer", this.refererValue);
    HeaderUtils.assign(customHeader, getHeader);
    ResponseEntity<byte[]> responseEntity
            = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(customHeader), new ParameterizedTypeReference<byte[]>() {
    });
    return responseEntity.getBody();
}
 
Example 20
Source Project: openapi-generator   Source File: PetApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a pet
 * 
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid pet value
 * @param petId Pet id to delete (required)
 * @param apiKey  (optional)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey) 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 deletePet");
    }
    
    // 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 (apiKey != null)
    headerParams.add("api_key", apiClient.parameterToString(apiKey));

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

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 21
Source Project: tutorials   Source File: PetApi.java    License: MIT License 5 votes vote down vote up
/**
 * uploads an image
 * 
 * <p><b>200</b> - successful operation
 * @param petId ID of pet to update
 * @param additionalMetadata Additional data to pass to server
 * @param file file to upload
 * @return ModelApiResponse
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) 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 uploadFile");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = UriComponentsBuilder.fromPath("/pet/{petId}/uploadImage").buildAndExpand(uriVariables).toUriString();
    
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    
    if (additionalMetadata != null)
        formParams.add("additionalMetadata", additionalMetadata);
    if (file != null)
        formParams.add("file", new FileSystemResource(file));

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

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

    ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 22
Source Project: spring-cloud-dataflow   Source File: TaskTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<CurrentTaskExecutionsResource> currentTaskExecutions() {
	ParameterizedTypeReference<Collection<CurrentTaskExecutionsResource>> typeReference =
		new ParameterizedTypeReference<Collection<CurrentTaskExecutionsResource>>() {
	};
	return restTemplate
		.exchange(executionsCurrentLink.getHref(),HttpMethod.GET,null, typeReference).getBody();
}
 
Example 23
Source Project: WeEvent   Source File: RestfulTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testListWithGroupId() {
    ResponseEntity<BaseResponse<TopicPage>> rsp = rest.exchange(url + "list?pageIndex={pageIndex}&pageSize={pageSize}&groupId={groupId}", HttpMethod.GET, null, new ParameterizedTypeReference<BaseResponse<TopicPage>>() {
    }, "0", "10", WeEvent.DEFAULT_GROUP_ID);

    Assert.assertEquals(200, rsp.getStatusCodeValue());
    Assert.assertNotNull(rsp.getBody());
    Assert.assertTrue(rsp.getBody().getData().getTotal() > 0);
}
 
Example 24
@Test
void should_returnBadRequest_ifAccessIdIsGroup() {
  String parameters = "?access-id=cn=monitor-users,cn=groups,ou=test,o=taskana";
  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_WORKBASKET_ACCESS_ITEMS) + parameters,
              HttpMethod.DELETE,
              restHelper.defaultRequest(),
              ParameterizedTypeReference.forType(Void.class));
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example 25
Source Project: mPass   Source File: RemoteApiProxyFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 填充泛型参数的变量
 */
private ParameterizedTypeReference<?> parameterize(Class<?> root,
                                                   Type type) {
    Map<String, Class<?>> varTypes = ifaceVarTypes.get(root.getName());
    if (varTypes == null) {
        return ParameterizedTypeReference.forType(type);
    }
    Type newType = PluginReflectUtil.parameterize(type, var -> {
        return varTypes.get(var.getName());
    });
    return ParameterizedTypeReference.forType(newType);
}
 
Example 26
Source Project: tutorials   Source File: UserApi.java    License: MIT License 5 votes vote down vote up
/**
 * Creates list of users with given input array
 * 
 * <p><b>0</b> - successful operation
 * @param body List of user object
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void createUsersWithArrayInput(List<User> 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 createUsersWithArrayInput");
    }
    
    String path = UriComponentsBuilder.fromPath("/user/createWithArray").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>();

    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<Void> returnType = new ParameterizedTypeReference<Void>() {};
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 27
@Test
public void flux() {
	ParameterizedTypeReference<List<Person>> reference = new ParameterizedTypeReference<List<Person>>() {};
	ResponseEntity<List<Person>> result =
			restTemplate.exchange("http://localhost:" + port + "/flux", HttpMethod.GET, null, reference);

	assertEquals(HttpStatus.OK, result.getStatusCode());
	List<Person> body = result.getBody();
	assertEquals(2, body.size());
	assertEquals("John", body.get(0).getName());
	assertEquals("Jane", body.get(1).getName());
}
 
Example 28
Source Project: lams   Source File: AsyncRestTemplate.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity,
		ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException {

	Type type = responseType.getType();
	AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, type);
	ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
	return execute(url, method, requestCallback, responseExtractor, uriVariables);
}
 
Example 29
Source Project: spring-analysis-note   Source File: BodyInserters.java    License: MIT License 5 votes vote down vote up
@Override
public <T, P extends Publisher<T>> MultipartInserter withPublisher(
		String name, P publisher, ParameterizedTypeReference<T> typeReference) {

	this.builder.asyncPart(name, publisher, typeReference);
	return this;
}
 
Example 30
Source Project: moserp   Source File: ValueListControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindByKey() {
    ValueList valueList = new ValueList();
    valueList.setKey(key);
    valueList.addValue(new ValueListItem("TestValue"));
    valueListRepository.save(valueList);
    Resources<ValueListItem> valueListItems = restTemplate
            .exchange(testEnvironment.createRestUri("valueLists/" + key + "/values"), HttpMethod.GET, null, new ParameterizedTypeReference<Resources<ValueListItem>>() {
            }).getBody();
    assertEquals("size", 1, valueListItems.getContent().size());
    assertEquals("value", valueList.getValues().get(0), valueListItems.getContent().iterator().next());
}