List of usage examples for org.springframework.web.client HttpClientErrorException getMessage
@Override
@Nullable
public String getMessage()
From source file:uk.ac.ebi.ep.ebeye.EbeyeRestService.java
private EbeyeSearchResult getEbeyeSearchResult(String url) throws InterruptedException, ExecutionException { HttpMethod method = HttpMethod.GET;//from w w w .java2s .c o m // Define response type Class<EbeyeSearchResult> responseType = EbeyeSearchResult.class; // Define headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<EbeyeSearchResult> requestEntity = new HttpEntity<>(headers); ListenableFuture<ResponseEntity<EbeyeSearchResult>> future = asyncRestTemplate.exchange(url, method, requestEntity, responseType); try { ResponseEntity<EbeyeSearchResult> results = future.get(); return results.getBody(); } catch (HttpClientErrorException ex) { LOGGER.error(ex.getMessage(), ex); } return null; }
From source file:fi.okm.mpass.idp.authn.impl.AbstractSpringSocialOAuth2Identity.java
/** * Returns Access Grant if user is known, otherwise null. * /*www. jav a2s . co m*/ * @param httpRequest * the request * @return Access Grant * @throws SocialUserAuthenticationException * if the operation fails. */ public AccessGrant getAccessGrant(HttpServletRequest httpRequest) throws SocialUserAuthenticationException { log.trace("Entering"); AccessGrant accessGrant = null; try { String authorizationCode = getAuthorizationCode(httpRequest); if (authorizationCode == null) { return null; } validateState(httpRequest); accessGrant = oauthOperations.exchangeForAccess(authorizationCode, httpRequest.getRequestURL().toString(), null); } catch (HttpClientErrorException e) { log.trace("Leaving"); log.error("Something bad happened " + e.getMessage()); throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION); } log.trace("Leaving"); return accessGrant; }
From source file:br.com.modoagil.asr.rest.support.RESTErrorHandler.java
/** * Manipula exceo para status HTTP {@code 4xx}, exceo do cliente * * @param ex/*from w ww . j a va 2 s. c om*/ * {@link HttpClientErrorException} * @return resposta ao cliente */ @ResponseBody @ExceptionHandler(HttpClientErrorException.class) public Response<E> processHttpClientErrorException(final HttpClientErrorException ex) { this.logger.info("handleHttpClientErrorException - Catching: " + ex.getClass().getSimpleName(), ex); return new ResponseBuilder<E>().success(false).message(ex.getMessage()).status(ex.getStatusCode()).build(); }
From source file:com.epl.ticketws.services.QueryService.java
public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) { try {/*from w w w. j av a 2 s . c o m*/ URI uri = new URL(url).toURI(); long timestamp = new Date().getTime(); HttpMethod httpMethod; if (method.equalsIgnoreCase("post")) { httpMethod = HttpMethod.POST; } else { httpMethod = HttpMethod.GET; } String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters); // logger.info("String to sign: " + stringToSign); String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license); // logger.info("Authorization string: " + authorization); // Setting Headers HttpHeaders headers = new HttpHeaders(); if (accept.equalsIgnoreCase("json")) { headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); } else { headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); } headers.add("Authorization", authorization); headers.add("OB_DATE", "" + timestamp); headers.add("OB_Terminal", terminal); headers.add("OB_User", user); headers.add("OB_Channel", channel); headers.add("OB_POS", pos); headers.add("Content-Type", "application/x-www-form-urlencoded"); HttpEntity<String> entity; if (httpMethod == HttpMethod.POST) { // Adding post parameters to POST body String parameterStringBody = getParametersAsString(parameters); entity = new HttpEntity<String>(parameterStringBody, headers); // logger.info("POST Body: " + parameterStringBody); } else { entity = new HttpEntity<String>(headers); } RestTemplate restTemplate = new RestTemplate( new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new LoggingRequestInterceptor()); restTemplate.setInterceptors(interceptors); // Converting to UTF-8. OB Rest replies in windows charset. //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(UTF_8))); if (accept.equalsIgnoreCase("json")) { restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter()); } else { restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter()); } ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc); if (!response.getStatusCode().is2xxSuccessful()) throw new HttpClientErrorException(response.getStatusCode()); return response.getBody(); } catch (HttpClientErrorException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (MalformedURLException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (SignatureException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return null; }
From source file:com.sastix.cms.common.client.exception.CommonExceptionHandler.java
/** * This default implementation throws a {@link HttpClientErrorException} if the response status code * is {@link HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException} * if it is {@link HttpStatus.Series#SERVER_ERROR}, * and a {@link RestClientException} in other cases. *///from www .j a v a 2 s. c om @Override public void handleError(ClientHttpResponse response) throws IOException, RestClientException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: final byte[] responseBody = getResponseBody(response); final Charset charset = getCharset(response); final String statusText = response.getStatusText(); final HttpHeaders httpHeaders = response.getHeaders(); final RestErrorDTO errorDTO; try { errorDTO = objectMapper.readValue(new String(responseBody, charset), RestErrorDTO.class); LOG.error("Exception: " + errorDTO.toString()); } catch (final Exception e) { //Wasn't able to map String on ErrorDTO. //It is an Unknown Exception //Throw Default Exception final HttpClientErrorException clientErrorException = new HttpClientErrorException(statusCode, statusText, httpHeaders, responseBody, charset); LOG.error("Unknown Exception: " + clientErrorException.getMessage()); throw clientErrorException; } if (exceptionClasses.containsKey(errorDTO.getException())) { throw (exceptionClasses.get(errorDTO.getException())).create(errorDTO.getMessage()); } else { throw new HttpClientErrorException(statusCode, statusText, httpHeaders, responseBody, charset); } case SERVER_ERROR: throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); default: throw new RestClientException("Unknown status code [" + statusCode + "]"); } }
From source file:org.openmhealth.shim.OAuth1ShimBase.java
@Override @SuppressWarnings("unchecked") public AuthorizationRequestParameters getAuthorizationRequestParameters(String username, Map<String, String> additionalParameters) throws ShimException { String stateKey = OAuth1Utils.generateStateKey(); AccessParameters accessParams = accessParametersRepo.findByUsernameAndShimKey(username, getShimKey(), new Sort(DESC, "dateCreated")); if (accessParams != null && accessParams.getAccessToken() != null) { return AuthorizationRequestParameters.authorized(); }//from www. ja va2s . com HttpRequestBase tokenRequest = null; try { String callbackUrl = shimServerConfig.getCallbackUrl(getShimKey(), stateKey); Map<String, String> requestTokenParameters = new HashMap<>(); requestTokenParameters.put("oauth_callback", callbackUrl); String initiateAuthUrl = getBaseRequestTokenUrl(); tokenRequest = getRequestTokenRequest(initiateAuthUrl, null, null, requestTokenParameters); HttpResponse httpResponse = httpClient.execute(tokenRequest); Map<String, String> tokenParameters = OAuth1Utils.parseRequestTokenResponse(httpResponse); String token = tokenParameters.get(OAuth.OAUTH_TOKEN); String tokenSecret = tokenParameters.get(OAuth.OAUTH_TOKEN_SECRET); if (tokenSecret == null) { throw new ShimException("Request token could not be retrieved"); } URL authorizeUrl = signUrl(getBaseAuthorizeUrl(), token, tokenSecret, null); System.out.println("The authorization url is: "); System.out.println(authorizeUrl); /** * Build the auth parameters entity to return */ AuthorizationRequestParameters parameters = new AuthorizationRequestParameters(); parameters.setUsername(username); parameters.setRedirectUri(callbackUrl); parameters.setStateKey(stateKey); parameters.setAuthorizationUrl(authorizeUrl.toString()); parameters.setRequestParams(tokenParameters); /** * Store the parameters in a repo. */ authorizationRequestParametersRepo.save(parameters); return parameters; } catch (HttpClientErrorException e) { e.printStackTrace(); throw new ShimException("HTTP Error: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new ShimException("Unable to initiate OAuth1 authorization, could not parse token parameters"); } finally { if (tokenRequest != null) { tokenRequest.releaseConnection(); } } }
From source file:es.onebox.rest.utils.service.QueryService.java
/** * Main method to perform request to Onebox REST API. * * @param authenticationForm/*w w w .ja v a 2 s . c om*/ * @param queryForm * @return Response form request */ public ResponseDTO query(AuthenticationForm authenticationForm, QueryForm queryForm) { ResponseDTO responseDTO = new ResponseDTO(); Exception ex = null; try { URL url = new URL(queryForm.getUrl()); URI uri = url.toURI(); Date date = new Date(); long timestamp = date.getTime(); HttpMethod httpMethod; if (queryForm.getMethod().equalsIgnoreCase("post")) { httpMethod = HttpMethod.POST; } else { httpMethod = HttpMethod.GET; } // Getting String to encode with HMAC-SHA1 // First step in the signing algorithm String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, queryForm); logger.info("String to sign: " + stringToSign); // Encoding String // This is the actual authorization string that will be sent in the request String authorization = generate_HMAC_SHA1_Signature(stringToSign, authenticationForm.getPassword() + authenticationForm.getLicense()); logger.info("Authorization string: " + authorization); // Adding to return object responseDTO.setDate(date); responseDTO.setStringToSign(stringToSign); responseDTO.setAuthorization(authorization); // Setting Headers HttpHeaders headers = new HttpHeaders(); if (queryForm.getAccept().equals("json")) { headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); } else { headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); } headers.add("Authorization", authorization); headers.add("OB_DATE", "" + timestamp); headers.add("OB_Terminal", authenticationForm.getTerminal()); headers.add("OB_User", authenticationForm.getUser()); headers.add("OB_Channel", authenticationForm.getChannelId()); headers.add("OB_POS", authenticationForm.getPos()); // Adding Headers to return object responseDTO.setHttpHeaders(headers); HttpEntity<String> entity; if (httpMethod == HttpMethod.POST) { // Adding post parameters to POST body String parameterStringBody = queryForm.getParametersAsString(); entity = new HttpEntity<String>(parameterStringBody, headers); logger.info("POST Body: " + parameterStringBody); } else { entity = new HttpEntity<String>(headers); } // Creating rest client RestTemplate restTemplate = new RestTemplate(); // Converting to UTF-8. OB Rest replies in windows charset. restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // Performing request to Onebox REST API ResponseEntity<String> result = restTemplate.exchange(uri, httpMethod, entity, String.class); // TODO this functionlity is to map response to objetcs. It is not finished. Only placed here for POC /* if (queryForm.getMapResponse().booleanValue()) { ResponseEntity<EventSearchBean> event = restTemplate.exchange(uri, httpMethod, entity, EventSearchBean.class); } */ // Adding response to return object responseDTO.setResponseEntity(result); logger.debug(result.toString()); } catch (HttpClientErrorException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (MalformedURLException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (SignatureException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (URISyntaxException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (Exception e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.authentication")); } finally { if (ex != null && ex instanceof HttpServerErrorException) { HttpServerErrorException e2 = (HttpServerErrorException) ex; ResponseEntity<String> responseEntity = new ResponseEntity<String>(e2.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); List<String> ob_error_codes = e2.getResponseHeaders().get("OB_Error_Code"); String ob_error_code; ResponseErrorCodesEnum ob_error = null; if (ob_error_codes != null && ob_error_codes.size() == 1) { ob_error_code = ob_error_codes.get(0); try { ob_error = ResponseErrorCodesEnum.valueOf("ERROR_" + ob_error_code); } catch (Exception e) { logger.error("API ERROR CODE NOT DEFINED: " + "ERROR_" + ob_error_code); } responseDTO.setObResponseErrorCode(ob_error); } responseDTO.setResponseEntity(responseEntity); } } return responseDTO; }
From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java
public String createOrcid(String email, String givenNames, String familyName) throws OrcidException, OrcidEmailExistsException, OrcidHttpException { String newOrcid = null;//from w w w.ja v a 2 s.com log.debug("Creating ORCID..."); log.debug("email: " + email); log.debug("givenNames: " + givenNames); log.debug("familyName: " + familyName); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/xml"); headers.set("Content-Type", "application/vdn.orcid+xml"); headers.set("Authorization", "Bearer " + orcidCreateToken); OrcidMessage message = new OrcidMessage(); message.setEmail(email); message.setGivenNames(givenNames); message.setFamilyName(familyName); message.setMessageVersion(orcidMessageVersion); //TODO Affiliation should be set based on organization once faculty from more than one organization are processed message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT); message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER); message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER); message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO); message.setAffiliationOrganizationAddressCountry(OrcidMessage.US); message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER); message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD); HttpEntity entity = new HttpEntity(message, headers); log.debug("Configured RestTemplate Message Converters..."); List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters(); for (HttpMessageConverter<?> converter : converters) { log.debug("converter: " + converter); log.debug("supported media types: " + converter.getSupportedMediaTypes()); log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): " + converter.canWrite(String.class, MediaType.APPLICATION_XML)); log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): " + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML)); } log.debug("Request headers: " + headers); HttpStatus responseStatusCode = null; String responseBody = null; try { if (useTestHttpProxy.equalsIgnoreCase("TRUE")) { log.info("Using HTTP ***TEST*** proxy..."); System.setProperty("http.proxyHost", testHttpProxyHost); System.setProperty("http.proxyPort", testHttpProxyPort); log.info("http.proxyHost: " + System.getProperty("http.proxyHost")); log.info("http.proxyPort: " + System.getProperty("http.proxyPort")); } ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity, String.class); responseStatusCode = responseEntity.getStatusCode(); responseBody = responseEntity.getBody(); HttpHeaders responseHeaders = responseEntity.getHeaders(); URI locationURI = responseHeaders.getLocation(); String uriString = locationURI.toString(); newOrcid = extractOrcid(uriString); log.debug("HTTP response status code: " + responseStatusCode); log.debug("HTTP response headers: " + responseHeaders); log.debug("HTTP response body: " + responseBody); log.debug("HTTP response location: " + locationURI); log.debug("New ORCID: " + newOrcid); } catch (HttpClientErrorException e) { if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { log.debug(e.getStatusCode()); log.debug(e.getResponseBodyAsString()); log.debug(e.getMessage()); throw new OrcidEmailExistsException(e); } OrcidHttpException ohe = new OrcidHttpException(e); ohe.setStatusCode(e.getStatusCode()); throw ohe; } return newOrcid; }
From source file:org.alfresco.dropbox.service.action.DropboxUpdateAction.java
private void add(NodeRef nodeRef) { Metadata metadata = null;/* www.j a v a2 s . c om*/ if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_CONTENT)) { // TODO if this is marked for overwrite...and the file does not // exist...will it bomb? metadata = dropboxService.putFile(nodeRef, true); logger.debug("Dropbox: Add: putFile: " + nodeRef.toString()); } else if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_FOLDER)) { // If this is a folder, we need to try and create the folder in // Dropbox for the user. If the folder already exists a 403 // status error is returned, at which point, we get the metadata for // the folder and then update the node with the metadata. try { metadata = dropboxService.createFolder(nodeRef); logger.debug("Dropbox: Add: createFolder: " + nodeRef.toString()); } catch (HttpClientErrorException hcee) { if (hcee.getStatusCode().value() == Status.STATUS_FORBIDDEN) { metadata = dropboxService.getMetadata(nodeRef); } else { throw new ActionServiceException(hcee.getMessage()); } } } if (metadata != null) { dropboxService.persistMetadata(metadata, nodeRef); } if (nodeService.hasAspect(nodeRef, DropboxConstants.Model.ASPECT_SYNC_IN_PROGRESS)) { nodeService.removeAspect(nodeRef, DropboxConstants.Model.ASPECT_SYNC_IN_PROGRESS); } }
From source file:com.companyname.plat.commons.client.HttpRestfulClient.java
public Object getObject(Map<String, String> params, Class clz) { RestTemplate restTemplate = new RestTemplate(); try {/* w ww. j a va 2s.c o m*/ ResponseEntity<Object> entity = restTemplate.exchange(getEndPoint(), HttpMethod.GET, getHttpRequest(params), clz); setResponseStatus(entity.getStatusCode().toString()); return entity.getBody(); } catch (HttpClientErrorException ex) { if (HttpStatus.UNAUTHORIZED == ex.getStatusCode()) { System.out .println("Unauthorized call to " + this.getEndPoint() + "\nWrong login and/or password (\"" + this.getUserName() + "\" / \"" + this.getPassword() + "\")"); System.out.println("Cause: \n" + ex.getMessage()); } } return null; }