下面列出了怎么用org.springframework.core.ParameterizedTypeReference的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* <p><b>200</b> - successful operation
* @return ResponseEntity<Map<String, Integer>>
* @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);
}
@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();
}
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();
});
}
/**
* 根据用户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);
}
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();
}
/**
*
* Test serialization of object with outer number type
* <p><b>200</b> - Output composite
* @param body Input composite as post body (optional)
* @return ResponseEntity<OuterComposite>
* @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);
}
@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();
}
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<>();
}
}
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());
}
}
@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);
}
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();
}
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());
}
}
@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);
}
@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();
});
}
@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));
});
}
@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);
}
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();
}
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;
}
/**
* 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<Void>
* @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);
}
/**
* 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);
}
@Override
public Collection<CurrentTaskExecutionsResource> currentTaskExecutions() {
ParameterizedTypeReference<Collection<CurrentTaskExecutionsResource>> typeReference =
new ParameterizedTypeReference<Collection<CurrentTaskExecutionsResource>>() {
};
return restTemplate
.exchange(executionsCurrentLink.getHref(),HttpMethod.GET,null, typeReference).getBody();
}
@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);
}
@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);
}
/**
* 填充泛型参数的变量
*/
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);
}
/**
* 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);
}
@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());
}
public Response<Browser> getBrowser(String agentIp, int agentPort, String browserId) {
String url = getUrl(agentIp, agentPort, "/browser/{browserId}");
return restTemplate.exchange(url,
HttpMethod.GET,
null,
new ParameterizedTypeReference<Response<Browser>>() {
},
browserId).getBody();
}
@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);
}
@Override
public <T, P extends Publisher<T>> MultipartInserter withPublisher(
String name, P publisher, ParameterizedTypeReference<T> typeReference) {
this.builder.asyncPart(name, publisher, typeReference);
return this;
}