org.springframework.core.ParameterizedTypeReference Java Examples

The following examples show how to use org.springframework.core.ParameterizedTypeReference. 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: ServerClient.java    From agent with 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 #2
Source File: DashboardRestConsumer.java    From yugastore-java with 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 #3
Source File: CredHubCertificateTemplate.java    From spring-credhub with 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 #4
Source File: RestApiApplicationTest.java    From flowable-engine with 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 #5
Source File: WebClientIntegrationTests.java    From spring-analysis-note with 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 #6
Source File: SimpleQueryClient.java    From skywalking with 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 #7
Source File: RestTemplateDemoController.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
/**
   * 根据用户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 File: FakeApi.java    From openapi-generator with 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 #9
Source File: IngredientServiceClient.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: SimpleQueryClient.java    From skywalking with 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 #11
Source File: AccessIdControllerIntTest.java    From taskana with 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 #12
Source File: ClassificationControllerIntTest.java    From taskana with 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 #13
Source File: AbstractAuthServerRestClient.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: CredHubCredentialTemplate.java    From spring-credhub with 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 #15
Source File: StoreApi.java    From tutorials with 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 #16
Source File: ProductCompositeIntegration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
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 #17
Source File: ExtensionsITCase.java    From syndesis with 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 #18
Source File: ConfigurationLoader.java    From influx-proxy with 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 #19
Source File: GatewayServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public GuildDto getGuildInfo(long guildId) {
    GuildDto dto = template.convertSendAndReceiveAsType(QUEUE_GUILD_INFO_REQUEST, guildId,
            new ParameterizedTypeReference<GuildDto>() {
            });
    return dto != null && dto.getId() != null ? dto : null;
}
 
Example #20
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * uploads an image (required)
 * 
 * <p><b>200</b> - successful operation
 * @param petId ID of pet to update
 * @param requiredFile file to upload
 * @param additionalMetadata Additional data to pass to server
 * @return ModelApiResponse
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
 */
public Mono<ModelApiResponse> uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException {
    Object postBody = null;
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new WebClientResponseException("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null);
    }
    // verify the required parameter 'requiredFile' is set
    if (requiredFile == null) {
        throw new WebClientResponseException("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile", 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>();

    pathParams.put("petId", petId);

    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>();

    if (additionalMetadata != null)
        formParams.add("additionalMetadata", additionalMetadata);
    if (requiredFile != null)
        formParams.add("requiredFile", new FileSystemResource(requiredFile));

    final String[] localVarAccepts = { 
        "application/json"
    };
    final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String[] localVarContentTypes = { 
        "multipart/form-data"
    };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

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

    ParameterizedTypeReference<ModelApiResponse> localVarReturnType = new ParameterizedTypeReference<ModelApiResponse>() {};
    return apiClient.invokeAPI("/fake/{petId}/uploadImageWithRequiredFile", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #21
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Find pet by ID
 * Returns a single pet
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid ID supplied
 * <p><b>404</b> - Pet not found
 * @param petId ID of pet to return (required)
 * @return ResponseEntity&lt;Pet&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId) 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 getPetById");
    }
    
    // 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();

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

    ParameterizedTypeReference<Pet> returnType = new ParameterizedTypeReference<Pet>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #22
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * To test enum parameters
 * To test enum parameters
 * <p><b>400</b> - Invalid request
 * <p><b>404</b> - Not found
 * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList&lt;String&gt;())
 * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg)
 * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList&lt;String&gt;())
 * @param enumQueryString Query parameter enum test (string) (optional, default to -efg)
 * @param enumQueryInteger Query parameter enum test (double) (optional)
 * @param enumQueryDouble Query parameter enum test (double) (optional)
 * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $)
 * @param enumFormString Form parameter enum test (string) (optional, default to -efg)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> testEnumParametersWithHttpInfo(List<String> enumHeaderStringArray, String enumHeaderString, List<String> enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List<String> enumFormStringArray, String enumFormString) throws RestClientException {
    Object postBody = null;
    
    String path = apiClient.expandPath("/fake", 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("csv".toUpperCase(Locale.ROOT)), "enum_query_string_array", enumQueryStringArray));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_string", enumQueryString));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble));

    if (enumHeaderStringArray != null)
    headerParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray));
    if (enumHeaderString != null)
    headerParams.add("enum_header_string", apiClient.parameterToString(enumHeaderString));

    if (enumFormStringArray != null)
        formParams.put("enum_form_string_array", enumFormStringArray);
    if (enumFormString != null)
        formParams.add("enum_form_string", enumFormString);

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #23
Source File: TaskHistoryEventControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSecondPageSortedByKey() {
  String parameters =
      "/api/v1/task-history-event?sort-by=workbasket-key&order=desc&page=2&page-size=2";
  ResponseEntity<TaskHistoryEventListResource> response =
      template.exchange(
          server + port + parameters,
          HttpMethod.GET,
          request,
          ParameterizedTypeReference.forType(TaskHistoryEventListResource.class));

  assertThat(response.getBody().getContent()).hasSize(2);
  assertThat(response.getBody().getContent().iterator().next().getWorkbasketKey())
      .isEqualTo("WBI:100000000000000000000000000000000002");
  assertThat(response.getBody().getLink(IanaLinkRelations.SELF)).isNotNull();
  assertThat(
          response
              .getBody()
              .getRequiredLink(IanaLinkRelations.SELF)
              .getHref()
              .endsWith(parameters))
      .isTrue();
  assertThat(response.getBody().getLink("allTaskHistoryEvent")).isNotNull();
  assertThat(
          response
              .getBody()
              .getRequiredLink("allTaskHistoryEvent")
              .getHref()
              .endsWith("/api/v1/task-history-event"))
      .isTrue();
  assertThat(response.getBody().getLink(IanaLinkRelations.FIRST)).isNotNull();
  assertThat(response.getBody().getLink(IanaLinkRelations.LAST)).isNotNull();
}
 
Example #24
Source File: Jira.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
protected JiraComponents getJiraComponents(ProjectKey projectKey) {

		HttpHeaders headers = new HttpHeaders();
		Map<String, Object> parameters = newUrlTemplateVariables();
		parameters.put("project", projectKey.getKey());

		List<JiraComponent> components = operations.exchange(PROJECT_COMPONENTS_TEMPLATE, HttpMethod.GET,
				new HttpEntity<>(headers), new ParameterizedTypeReference<List<JiraComponent>>() {}, parameters).getBody();

		return JiraComponents.of(components);
	}
 
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
 * @param name Updated name of the pet
 * @param status Updated status of the pet
 * @throws WebClientResponseException if an error occurs while attempting to invoke the API
 */
public Mono<Void> updatePetWithForm(Long petId, String name, String status) throws WebClientResponseException {
    Object postBody = null;
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new WebClientResponseException("Missing the required parameter 'petId' when calling updatePetWithForm", 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>();

    pathParams.put("petId", petId);

    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>();

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

    final String[] localVarAccepts = { };
    final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    final String[] localVarContentTypes = { 
        "application/x-www-form-urlencoded"
    };
    final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

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

    ParameterizedTypeReference<Void> localVarReturnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI("/pet/{petId}", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
 
Example #26
Source File: RestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity,
		ParameterizedTypeReference<T> responseType) throws RestClientException {

	Type type = responseType.getType();
	RequestCallback requestCallback = httpEntityCallback(requestEntity, type);
	ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
	return execute(url, method, requestCallback, responseExtractor);
}
 
Example #27
Source File: CommentHelper.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@HystrixCommand(fallbackMethod = "defaultComments")
public List<Comment> getComments(Image image) {
	return restTemplate.exchange(
		"http://COMMENTS/comments/{imageId}",
		HttpMethod.GET,
		null,
		new ParameterizedTypeReference<List<Comment>>() {},
		image.getId()).getBody();

}
 
Example #28
Source File: RequestEntityTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-13154
public void types() throws URISyntaxException {
	URI url = new URI("https://example.com");
	List<String> body = Arrays.asList("foo", "bar");
	ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<String>>() {};

	RequestEntity<?> entity = RequestEntity.post(url).body(body, typeReference.getType());
	assertEquals(typeReference.getType(), entity.getType());
}
 
Example #29
Source File: ReservationApiGatewayRestController.java    From spring-cloud-in-action with MIT License 5 votes vote down vote up
@RequestMapping("/names")
@HystrixCommand(fallbackMethod = "getReservationNamesFallback")
public Collection<String> getReservationNames() {
  logger.info("Get reservation names via rest template!");

  ParameterizedTypeReference<Resources<Reservation>> parameterizedTypeReference =
          new ParameterizedTypeReference<Resources<Reservation>>() {
          };

  ResponseEntity<Resources<Reservation>> exchange = rt.exchange(
          "http://reservation-service/reservations",
          HttpMethod.GET, null, parameterizedTypeReference);

  return exchange.getBody().getContent().stream().map(Reservation::getReservationName).collect(Collectors.toList());
}
 
Example #30
Source File: WechatHttpServiceInternal.java    From jeeves with 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();
}