org.springframework.web.client.HttpClientErrorException Java Examples

The following examples show how to use org.springframework.web.client.HttpClientErrorException. 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: OAuth2AuthenticationServiceTest.java    From cubeai with Apache License 2.0 7 votes vote down vote up
private void mockRefreshGrant() {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "refresh_token");
    params.add("refresh_token", REFRESH_TOKEN_VALUE);
    //we must authenticate with the UAA server via HTTP basic authentication using the browser's client_id with no client secret
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", CLIENT_AUTHORIZATION);
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
    OAuth2AccessToken newAccessToken = createAccessToken(NEW_ACCESS_TOKEN_VALUE, NEW_REFRESH_TOKEN_VALUE);
    when(restTemplate.postForEntity("http://uaa/oauth/token", entity, OAuth2AccessToken.class))
        .thenReturn(new ResponseEntity<OAuth2AccessToken>(newAccessToken, HttpStatus.OK));
    //headers missing -> unauthorized
    HttpEntity<MultiValueMap<String, String>> headerlessEntity = new HttpEntity<>(params, new HttpHeaders());
    when(restTemplate.postForEntity("http://uaa/oauth/token", headerlessEntity, OAuth2AccessToken.class))
        .thenThrow(new HttpClientErrorException(HttpStatus.UNAUTHORIZED));
}
 
Example #2
Source File: RetryNTimesTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOriginalException() {
	assertTrue(RetryNTimes.getOriginalException(new IOException("test")) instanceof IOException);
	assertTrue(RetryNTimes.getOriginalException(
			new ExecutionException(new IllegalArgumentException("test"))) instanceof IllegalArgumentException);
	assertTrue(RetryNTimes.getOriginalException(new ExecutionException(null)) instanceof ExecutionException);
	assertTrue(RetryNTimes.getOriginalException(new ExecutionException(new InvocationTargetException(
			new HttpClientErrorException(HttpStatus.BAD_REQUEST, "test")))) instanceof HttpClientErrorException);
	assertTrue(RetryNTimes.getOriginalException(
			new ExecutionException(new InvocationTargetException(null))) instanceof InvocationTargetException);
	assertTrue(RetryNTimes.getOriginalException(new InvocationTargetException(new IOException("test"))) instanceof IOException);
	assertTrue(RetryNTimes.getOriginalException(new InvocationTargetException(null)) instanceof InvocationTargetException);

	assertFalse(RetryNTimes.getOriginalException(
			new InvocationTargetException(new IOException())) instanceof InvocationTargetException);
	assertFalse(RetryNTimes.getOriginalException(new ExecutionException(
			new InvocationTargetException(new IOException("test")))) instanceof ExecutionException);
}
 
Example #3
Source File: StatelessTestAction.java    From jsets-shiro-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/jwt_post")
  public @ResponseBody BaseResponse jwtPost(
  						 @RequestParam(name="apiName") String apiName
  						,@RequestParam(name="jwt") String jwt
  						,HttpServletRequest request) {
  	
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
form.add("jwt", jwt); 
   try{
   	String restPostUrl = request.getRequestURL().toString().replace("stateless/jwt_post", "");
   	restPostUrl += "jwt_api/"+apiName;
   	RestTemplate restTemplate = new RestTemplate();
   	String result = restTemplate.postForObject(restPostUrl, form, String.class);
   	return BaseResponse.ok().message(result);
   }catch(HttpClientErrorException e){
       return BaseResponse.fail().message(e.getResponseBodyAsString());
   }
  }
 
Example #4
Source File: AuthRequests.java    From restful-booker-platform with GNU General Public License v3.0 6 votes vote down vote up
public boolean postCheckAuth(String tokenValue){
    Token token = new Token(tokenValue);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<Token> httpEntity = new HttpEntity<>(token, requestHeaders);

    try{
        ResponseEntity<String> response = restTemplate.exchange(host + "/auth/validate", HttpMethod.POST, httpEntity, String.class);
        return response.getStatusCodeValue() == 200;
    } catch (HttpClientErrorException e){
        return false;
    }
}
 
Example #5
Source File: StatelessTestAction.java    From jsets-shiro-demo with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/hmac_post")
  public @ResponseBody BaseResponse hmacPost(
  		@RequestParam(name="apiName") String apiName
  		,@RequestParam(name="parameter1") String parameter1
	,@RequestParam(name="parameter2") String parameter2
	,@RequestParam(name="hmac_app_id") String hmac_app_id
	,@RequestParam(name="hmac_timestamp") long hmac_timestamp
	,@RequestParam(name="hmac_digest") String hmac_digest
	,HttpServletRequest request) {
  	
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
form.add("parameter1", parameter1); 
form.add("parameter2", parameter2); 
   form.add("hmac_app_id", hmac_app_id); 
   form.add("hmac_timestamp", hmac_timestamp); 
   form.add("hmac_digest", hmac_digest); 
   try{
   	String restPostUrl = request.getRequestURL().toString().replace("stateless/hmac_post", "");
   	restPostUrl += "hmac_api/"+apiName;
   	RestTemplate restTemplate = new RestTemplate();
   	String result = restTemplate.postForObject(restPostUrl, form, String.class);
       return BaseResponse.ok().message(result);
   }catch(HttpClientErrorException e){
       return BaseResponse.fail().message(e.getResponseBodyAsString());
   }
  }
 
Example #6
Source File: UserDashboard.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private void tryToGetUserProfile(ModelAndView mv, String token) {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", "Bearer " + token);
    String endpoint = "http://localhost:8080/api/profile";

    try {
        RequestEntity<Object> request = new RequestEntity<>(
            headers, HttpMethod.GET, URI.create(endpoint));

        ResponseEntity<UserProfile> userProfile = restTemplate.exchange(request, UserProfile.class);

        if (userProfile.getStatusCode().is2xxSuccessful()) {
            mv.addObject("profile", userProfile.getBody());
        } else {
            throw new RuntimeException("it was not possible to retrieve user profile");
        }
    } catch (HttpClientErrorException e) {
        throw new RuntimeException("it was not possible to retrieve user profile");
    }
}
 
Example #7
Source File: CustomRemoteTokenServices.java    From microservice-integration with MIT License 6 votes vote down vote up
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    @SuppressWarnings("rawtypes")
    Map map = new HashMap();
    try {
        map = restTemplate.exchange(path, HttpMethod.POST,
                new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
    } catch (HttpClientErrorException e1) {
        logger.error("catch token exception when check token!", e1);
        map.put(ERROR, e1.getStatusCode());

    } catch (HttpServerErrorException e2) {
        logger.error("catch no permission exception when check token!", e2);
        map.put(ERROR, e2.getStatusCode());

    } catch (Exception e) {
        logger.error("catch common exception when check token!", e);
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> result = map;
    return result;
}
 
Example #8
Source File: AbstractV2RegistryService.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private Manifest getManifest(String name, String reference) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(
            new MediaType("application", "vnd.docker.distribution.manifest.v2+json"),
            new MediaType("application", "vnd.docker.distribution.manifest.v2+prettyjws")
    ));
    HttpEntity entity = new HttpEntity<>(headers);
    URI uri = forName(name).path("/manifests/").path(reference).build().toUri();
    try {
        ResponseEntity<Manifest> exchange = getRestTemplate().exchange(uri, HttpMethod.GET, entity, Manifest.class);
        return exchange.getBody();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        }
        log.error("can't fetch manifest from {} by {}", uri, e.getMessage());
        throw e;
    }
}
 
Example #9
Source File: TelemetrySender.java    From spring-data-cosmosdb with MIT License 6 votes vote down vote up
private ResponseEntity<String> executeRequest(final TelemetryEventData eventData) {
    final HttpHeaders headers = new HttpHeaders();

    headers.add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON.toString());

    try {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpEntity<String> body = new HttpEntity<>(MAPPER.writeValueAsString(eventData), headers);

        return restTemplate.exchange(TELEMETRY_TARGET_URL, HttpMethod.POST, body, String.class);
    } catch (JsonProcessingException | HttpClientErrorException ignore) {
        log.warn("Failed to exchange telemetry request, {}.", ignore.getMessage());
    }

    return null;
}
 
Example #10
Source File: RESTClient.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Make a PUT request to a REST service
 * 
 * @param path
 *            the unique portion of the requested REST service URL
 * @param token
 *            not used yet
 * 
 * @param entity
 *            entity used for update
 * 
 * @throws NoSessionException
 */
public void putJsonRequestWHeaders(String path, String token, Object entity) {
    
    if (token != null) {
        URLBuilder url = null;
        if (!path.startsWith("http")) {
            url = new URLBuilder(getSecurityUrl());
            url.addPath(path);
        } else {
            url = new URLBuilder(path);
        }
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);
        headers.add("Content-Type", "application/json");
        HttpEntity requestEntity = new HttpEntity(entity, headers);
        LOGGER.debug("Updating API at: {}", url);
        try {
            template.put(url.toString(), requestEntity);
        } catch (HttpClientErrorException e) {
            LOGGER.debug("Catch HttpClientException: {}", e.getStatusCode());
        }
    }
}
 
Example #11
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 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 (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> createUsersWithListInputWithHttpInfo(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 createUsersWithListInput");
    }
    
    String path = apiClient.expandPath("/user/createWithList", 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<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #12
Source File: AbstractZosmfService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Method handles exception from REST call to z/OSMF into internal exception. It convert original exception into
 * custom one with better messages and types for subsequent treatment.
 *
 * @param url URL of invoked REST endpoint
 * @param re original exception
 * @return translated exception
 */
protected RuntimeException handleExceptionOnCall(String url, RuntimeException re) {
    if (re instanceof ResourceAccessException) {
        apimlLog.log("org.zowe.apiml.security.serviceUnavailable", url, re.getMessage());
        return new ServiceNotAccessibleException("Could not get an access to z/OSMF service.");
    }

    if (re instanceof HttpClientErrorException.Unauthorized) {
        return new BadCredentialsException("Username or password are invalid.");
    }

    if (re instanceof RestClientException) {
        apimlLog.log("org.zowe.apiml.security.generic", re.getMessage(), url);
        return new AuthenticationServiceException("A failure occurred when authenticating.", re);
    }

    return re;
}
 
Example #13
Source File: AuthRequests.java    From restful-booker-platform with GNU General Public License v3.0 6 votes vote down vote up
public boolean postCheckAuth(String tokenValue){
    Token token = new Token(tokenValue);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<Token> httpEntity = new HttpEntity<>(token, requestHeaders);

    try{
        ResponseEntity<String> response = restTemplate.exchange(host + "/auth/validate", HttpMethod.POST, httpEntity, String.class);
        return response.getStatusCodeValue() == 200;
    } catch (HttpClientErrorException e){
        return false;
    }
}
 
Example #14
Source File: AuthRequests.java    From restful-booker-platform with GNU General Public License v3.0 6 votes vote down vote up
public boolean postCheckAuth(String tokenValue){
    Token token = new Token(tokenValue);

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    HttpEntity<Token> httpEntity = new HttpEntity<Token>(token, requestHeaders);

    try{
        ResponseEntity<String> response = restTemplate.exchange(host + "/auth/validate", HttpMethod.POST, httpEntity, String.class);
        return response.getStatusCodeValue() == 200;
    } catch (HttpClientErrorException e){
        return false;
    }
}
 
Example #15
Source File: WorkbasketAccessItemControllerIntTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@Test
void testThrowsExceptionIfInvalidFilterIsUsed() {
  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_WORKBASKET_ACCESS_ITEMS)
                  + "?sort-by=workbasket-key&order=asc&page=1&page-size=9&invalid=user-1-1",
              HttpMethod.GET,
              restHelper.defaultRequest(),
              WORKBASKET_ACCESS_ITEM_PAGE_MODEL_TYPE);
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .hasMessageContaining("[invalid]")
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example #16
Source File: TaskCommentControllerIntTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@Disabled("Disabled until Authorization check is up!")
@Test
void should_FailToCreateTaskComment_When_TaskIsNotVisible() {

  TaskCommentRepresentationModel taskCommentRepresentationModelToCreate =
      new TaskCommentRepresentationModel();
  taskCommentRepresentationModelToCreate.setTaskId("TKI:000000000000000000000000000000000000");
  taskCommentRepresentationModelToCreate.setTextField("newly created task comment");

  ThrowingCallable httpCall =
      () -> {
        template.exchange(
            restHelper.toUrl(
                Mapping.URL_TASK_GET_POST_COMMENTS, "TKI:000000000000000000000000000000000000"),
            HttpMethod.POST,
            new HttpEntity<>(
                taskCommentRepresentationModelToCreate, restHelper.getHeadersUser_1_1()),
            ParameterizedTypeReference.forType(TaskCommentRepresentationModel.class));
      };
  assertThatThrownBy(httpCall)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.FORBIDDEN);
}
 
Example #17
Source File: OAuth2TokenEndpointClientAdapter.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Sends a refresh grant to the token endpoint using the current refresh token to obtain new tokens.
 *
 * @param refreshTokenValue the refresh token to use to obtain new tokens.
 * @return the new, refreshed access token.
 */
@Override
public OAuth2AccessToken sendRefreshGrant(String refreshTokenValue) {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "refresh_token");
    params.add("refresh_token", refreshTokenValue);
    HttpHeaders headers = new HttpHeaders();
    addAuthentication(headers, params);
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
    log.debug("contacting OAuth2 token endpoint to refresh OAuth2 JWT tokens");
    ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity,
                                                                                  OAuth2AccessToken.class);
    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        log.debug("failed to refresh tokens: {}", responseEntity.getStatusCodeValue());
        throw new HttpClientErrorException(responseEntity.getStatusCode());
    }
    OAuth2AccessToken accessToken = responseEntity.getBody();
    log.info("refreshed OAuth2 JWT cookies using refresh_token grant");
    return accessToken;
}
 
Example #18
Source File: SmartlingClient.java    From mojito with Apache License 2.0 6 votes vote down vote up
public void deleteFile(String projectId, String fileUri) {

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("fileUri", fileUri);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        try {
            Response response = oAuth2RestTemplate.postForObject(API_FILES_DELETE, requestEntity, Response.class, projectId);
            throwExceptionOnError(response, ERROR_CANT_DELETE_FILE, fileUri);
        } catch(HttpClientErrorException e) {
            throw wrapIntoSmartlingException(e, ERROR_CANT_DELETE_FILE, fileUri);
        }
    }
 
Example #19
Source File: PetApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * uploads an image
 * 
 * <p><b>200</b> - successful operation
 * @param petId ID of pet to update (required)
 * @param additionalMetadata Additional data to pass to server (optional)
 * @param file file to upload (optional)
 * @return ResponseEntity&lt;ModelApiResponse&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(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 = apiClient.expandPath("/pet/{petId}/uploadImage", 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 (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, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #20
Source File: WorkbasketControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void testThrowsExceptionIfInvalidFilterIsUsed() {
  ThrowingCallable httpCall =
      () ->
          TEMPLATE.exchange(
              restHelper.toUrl(Mapping.URL_WORKBASKET) + "?invalid=PERSONAL",
              HttpMethod.GET,
              restHelper.defaultRequest(),
              WORKBASKET_SUMMARY_PAGE_MODEL_TYPE);
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .hasMessageContaining("[invalid]")
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example #21
Source File: ProjectGenerationControllerIntegrationTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
private void assertUsingStyleIsFailingForUrl(String url) {
	assertThatExceptionOfType(HttpClientErrorException.class)
			.isThrownBy(() -> getRestTemplate().getForEntity(createUrl(url), byte[].class)).satisfies((ex) -> {
				assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
				assertStandardErrorBody(ex.getResponseBodyAsString(),
						"Dependencies must be specified using 'dependencies'");
			});
}
 
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: GdaxExchangeImpl.java    From gdax-java with MIT License 5 votes vote down vote up
@Override
public <T, R> T post(String resourcePath,  ParameterizedTypeReference<T> responseType, R jsonObj) {
    String jsonBody = toJson(jsonObj);

    try {
        ResponseEntity<T> response = restTemplate.exchange(getBaseUrl() + resourcePath,
                HttpMethod.POST,
                securityHeaders(resourcePath, "POST", jsonBody),
                responseType);
        return response.getBody();
    } catch (HttpClientErrorException ex) {
        log.error("POST request Failed for '" + resourcePath + "': " + ex.getResponseBodyAsString());
    }
    return null;
}
 
Example #24
Source File: VaultResponsesUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldBuildExceptionWithPath() {

	HttpStatusCodeException cause = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Bad Request");

	VaultException vaultException = VaultResponses.buildException(cause, "sys/path");
	assertThat(vaultException).hasMessageContaining("Status 400 Bad Request [sys/path];").hasCause(cause);
}
 
Example #25
Source File: TaskControllerIntTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Test
void testThrowsExceptionIfInvalidFilterIsUsed() {
  ThrowingCallable httpCall =
      () ->
          TEMPLATE.exchange(
              restHelper.toUrl(Mapping.URL_TASKS) + "?invalid=VNR",
              HttpMethod.GET,
              restHelper.defaultRequest(),
              TASK_SUMMARY_PAGE_MODEL_TYPE);
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .hasMessageContaining("[invalid]")
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example #26
Source File: PetApi.java    From openapi-generator with Apache License 2.0 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;Set&lt;Pet&gt;&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
@Deprecated
public ResponseEntity<Set<Pet>> findPetsByTagsWithHttpInfo(Set<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("csv".toUpperCase(Locale.ROOT)), "tags", tags));

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

    ParameterizedTypeReference<Set<Pet>> returnType = new ParameterizedTypeReference<Set<Pet>>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #27
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 #28
Source File: FakeClassnameTags123Api.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * To test class name in snake case
 * To test class name in snake case
 * <p><b>200</b> - successful operation
 * @param body client model (required)
 * @return ResponseEntity&lt;Client&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Client> testClassnameWithHttpInfo(Client 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 testClassname");
    }
    
    String path = apiClient.expandPath("/fake_classname_test", 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 = { 
        "application/json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Client> returnType = new ParameterizedTypeReference<Client>() {};
    return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #29
Source File: YarnCloudAppServiceApplication.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
public List<StreamClustersInfoReportData> getClusterInfo(ApplicationId applicationId, String clusterId) {
	List<StreamClustersInfoReportData> data = new ArrayList<StreamClustersInfoReportData>();
	YarnContainerClusterOperations operations = buildClusterOperations(restTemplate, yarnClient, applicationId);

	try {
		ContainerClusterResource response = operations.clusterInfo(clusterId);
		Integer pany = response.getGridProjection().getProjectionData().getAny();
		Map<String, Integer> phosts = response.getGridProjection().getProjectionData().getHosts();
		Map<String, Integer> pracks = response.getGridProjection().getProjectionData().getRacks();
		Integer sany = response.getGridProjection().getSatisfyState().getAllocateData().getAny();
		Map<String, Integer> shosts = response.getGridProjection().getSatisfyState().getAllocateData().getHosts();
		Map<String, Integer> sracks = response.getGridProjection().getSatisfyState().getAllocateData().getRacks();
		List<String> members = new ArrayList<>();
		for (GridMemberResource mr : response.getGridProjection().getMembers()) {
			members.add(mr.getId());
		}

		data.add(new StreamClustersInfoReportData(response.getContainerClusterState().getClusterState().toString(),
				response.getGridProjection().getMembers().size(), pany, phosts, pracks, sany, shosts, sracks, members));
	} catch (YarnContainerClusterClientException e) {
		if (e.getRootCause() instanceof HttpClientErrorException) {
			HttpStatus statusCode = ((HttpClientErrorException)e.getRootCause()).getStatusCode();
			if (statusCode != HttpStatus.NOT_FOUND) {
				throw e;
			}
		}
	}

	return data;
}
 
Example #30
Source File: DefaultFirebaseRealtimeDatabaseRepository.java    From spring-boot-starter-data-firebase with MIT License 5 votes vote down vote up
@Override
public T get(ID id, Object... uriVariables) throws FirebaseRepositoryException {
    ReflectionUtils.makeAccessible(documentId);

    HttpEntity httpEntity = HttpEntityBuilder.create(firebaseObjectMapper, firebaseApplicationService).build();
    T response = restTemplate.exchange(getDocumentPath(id), HttpMethod.GET, httpEntity, documentClass, uriVariables).getBody();
    if (response == null) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
    } else {
        ReflectionUtils.setField(documentId, response, id);
        return response;
    }
}