Java Code Examples for org.springframework.web.client.HttpClientErrorException

The following examples show how to use org.springframework.web.client.HttpClientErrorException. 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
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 2
Source Project: jsets-shiro-demo   Source File: StatelessTestAction.java    License: 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 3
Source Project: jsets-shiro-demo   Source File: StatelessTestAction.java    License: 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 4
Source Project: cubeai   Source File: OAuth2AuthenticationServiceTest.java    License: Apache License 2.0 6 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 5
Source Project: OAuth-2.0-Cookbook   Source File: UserDashboard.java    License: 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 6
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 7
Source Project: haven-platform   Source File: AbstractV2RegistryService.java    License: 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 8
Source Project: spring-data-cosmosdb   Source File: TelemetrySender.java    License: 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 9
Source Project: mojito   Source File: SmartlingClient.java    License: 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 10
Source Project: taskana   Source File: TaskCommentControllerIntTest.java    License: 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 11
Source Project: secure-data-service   Source File: RESTClient.java    License: 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 12
Source Project: openapi-generator   Source File: UserApi.java    License: 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 13
Source Project: api-layer   Source File: AbstractZosmfService.java    License: 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 14
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 15
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 16
@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 17
Source Project: tutorials   Source File: OAuth2TokenEndpointClientAdapter.java    License: 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 Project: x-pipe   Source File: RetryNTimesTest.java    License: 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 19
Source Project: tutorials   Source File: PetApi.java    License: MIT License 5 votes vote down vote up
/**
 * Add a new pet to the store
 * 
 * <p><b>405</b> - Invalid input
 * @param body Pet object that needs to be added to the store
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void addPet(Pet 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 addPet");
    }
    
    String path = UriComponentsBuilder.fromPath("/pet").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 = { 
        "application/json", "application/xml"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 20
Source Project: mojito   Source File: SmartlingClient.java    License: Apache License 2.0 5 votes vote down vote up
public void createBindings(Bindings bindings, String projectId) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    HttpEntity<Bindings> requestEntity = new HttpEntity<>(bindings, headers);
    try {
        String s = oAuth2RestTemplate.postForObject(API_BINDINGS, requestEntity, String.class, projectId);
        logger.debug("create binding: {}", s);
    } catch(HttpClientErrorException e) {
        throw wrapIntoSmartlingException(e, ERROR_CANT_CREATE_BINDINGS, objectMapper.writeValueAsStringUnchecked(bindings));
    }
}
 
Example 21
@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;
    }
}
 
Example 22
@Test
void testFailOnImportDuplicates() throws Exception {
  ClassificationRepresentationModel classification =
      this.getClassificationWithKeyAndDomain("L110105", "DOMAIN_A");

  TaskanaPagedModel<ClassificationRepresentationModel> clList =
      new TaskanaPagedModel<>(
          TaskanaPagedModelKeys.CLASSIFICATIONS, Arrays.asList(classification, classification));

  assertThatThrownBy(() -> importRequest(clList))
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(ex -> ((HttpClientErrorException) ex).getStatusCode())
      .isEqualTo(HttpStatus.CONFLICT);
}
 
Example 23
Source Project: apollo   Source File: NamespaceControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void create() {
  try {
    NamespaceDTO namespaceDTO = new NamespaceDTO();
    namespaceDTO.setClusterName("cluster");
    namespaceDTO.setNamespaceName("invalid name");
    namespaceDTO.setAppId("whatever");
    restTemplate.postForEntity(
        url("/apps/{appId}/clusters/{clusterName}/namespaces"),
        namespaceDTO, NamespaceDTO.class, namespaceDTO.getAppId(), namespaceDTO.getClusterName());
    Assert.fail("Should throw");
  } catch (HttpClientErrorException e) {
    Assert.assertThat(new String(e.getResponseBodyAsByteArray()), containsString(InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
  }
}
 
Example 24
Source Project: gdax-java   Source File: GdaxExchangeImpl.java    License: 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 25
@Test
void should_returnBadRequest_ifAccessIdIsOrganizationalGroup() {
  String parameters = "?access-id=cn=organisationseinheit ksc,cn=organisation,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 26
@Test
public void preFlightRequestWithCorsRejected() throws Exception {
	try {
		this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
		performOptions("/cors-restricted", this.headers, String.class);
		fail();
	}
	catch (HttpClientErrorException e) {
		assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
	}
}
 
Example 27
Source Project: apollo   Source File: CtripUserServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = HttpClientErrorException.class)
public void testSearchUsersWithError() throws Exception {
  when(restTemplate.exchange(eq(someUserServiceUrl), eq(HttpMethod.POST), any(HttpEntity.class),
      eq(someResponseType)))
      .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

  String someKeyword = "someKeyword";
  int someOffset = 0;
  int someLimit = 10;

  ctripUserService.searchUsers(someKeyword, someOffset, someLimit);
}
 
Example 28
Source Project: api-framework   Source File: Booking.java    License: MIT License 5 votes vote down vote up
public static ResponseEntity<String> getBooking(int id, MediaType accept) throws HttpClientErrorException {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Collections.singletonList(accept));

    HttpEntity<String> httpEntity = new HttpEntity<String>(requestHeaders);

    return restTemplate.exchange(baseUrl + "/booking/" + Integer.toString(id), HttpMethod.GET, httpEntity, String.class);
}
 
Example 29
Source Project: cubeai   Source File: AbilityService.java    License: Apache License 2.0 5 votes vote down vote up
public ResponseEntity<String> apiGateway(String url, String requestBody, MultiValueMap<String,String> requestHeader) {
    log.debug("Start API forwarding");

    try {
        HttpEntity<String> httpEntity = new HttpEntity<>(requestBody, requestHeader);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // 直接使用RestTemplate的POST方法时,字符串默认使用“ISO-8859-1”编码,需要转换
        ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
        return ResponseEntity.status(response.getStatusCodeValue()).body(response.getBody());
    } catch(HttpClientErrorException e) {
        return ResponseEntity.status(e.getStatusCode()).body(e.getResponseBodyAsString());
    }
}
 
Example 30
Source Project: tutorials   Source File: UserApi.java    License: MIT License 5 votes vote down vote up
/**
 * Updated user
 * This can only be done by the logged in user.
 * <p><b>400</b> - Invalid user supplied
 * <p><b>404</b> - User not found
 * @param username name that need to be updated (required)
 * @param body Updated user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> updateUserWithHttpInfo(String username, User body) throws RestClientException {
    Object postBody = body;

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

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

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("username", username);
    String path = apiClient.expandPath("/user/{username}", 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 = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = {
        "application/json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}