List of usage examples for org.springframework.web.client HttpClientErrorException getStatusCode
public HttpStatus getStatusCode()
From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java
/** * Get a connection to the Google APIs. Will attempt to refresh tokens if they are invalid. If unable to refresh return a * GoogleDocsRefreshTokenException.//w w w . j a v a 2 s . c o m * * @return * @throws GoogleDocsAuthenticationException * @throws GoogleDocsRefreshTokenException * @throws GoogleDocsServiceException */ private Connection<Google> getConnection() throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException { Connection<Google> connection = null; // OAuth credentials for the current user, if the exist OAuth2CredentialsInfo credentialInfo = oauth2CredentialsStoreService .getPersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM); if (credentialInfo != null) { log.debug("OAuth Access Token Exists: " + credentialInfo.getOAuthAccessToken()); AccessGrant accessGrant = new AccessGrant(credentialInfo.getOAuthAccessToken()); try { log.debug("Attempt to create OAuth Connection"); connection = connectionFactory.createConnection(accessGrant); } catch (HttpClientErrorException hcee) { log.debug(hcee.getResponseBodyAsString()); if (hcee.getStatusCode().value() == HttpStatus.SC_UNAUTHORIZED) { try { accessGrant = refreshAccessToken(); connection = connectionFactory.createConnection(accessGrant); } catch (GoogleDocsRefreshTokenException gdrte) { throw gdrte; } catch (GoogleDocsServiceException gdse) { throw gdse; } } else { throw new GoogleDocsServiceException(hcee.getMessage(), hcee, hcee.getStatusCode().value()); } } catch (HttpServerErrorException hsee) { throw new GoogleDocsServiceException(hsee.getMessage(), hsee, hsee.getStatusCode().value()); } } log.debug("Connection Created"); return connection; }
From source file:org.apache.zeppelin.livy.BaseLivyInterprereter.java
private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException { targetURL = livyURL + targetURL;/* w w w.j ava2 s . c om*/ LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData); RestTemplate restTemplate = getRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); headers.add("X-Requested-By", "zeppelin"); ResponseEntity<String> response = null; try { if (method.equals("POST")) { HttpEntity<String> entity = new HttpEntity<>(jsonData, headers); response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class); } else if (method.equals("GET")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class); } else if (method.equals("DELETE")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class); } } catch (HttpClientErrorException e) { response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString())); } if (response == null) { throw new LivyException("No http response returned"); } LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(), response.getBody()); if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) { return response.getBody(); } else if (response.getStatusCode().value() == 404) { if (response.getBody().matches("\"Session '\\d+' not found.\"")) { throw new SessionNotFoundException(response.getBody()); } else { throw new APINotFoundException( "No rest api found for " + targetURL + ", " + response.getStatusCode()); } } else { String responseString = response.getBody(); if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) { return responseString; } throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); } }
From source file:org.apache.zeppelin.livy.LivyHelper.java
protected String executeHTTP(String targetURL, String method, String jsonData, String paragraphId) throws Exception { LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData); RestTemplate restTemplate = getRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); headers.add("X-Requested-By", "zeppelin"); ResponseEntity<String> response = null; try {/* w w w.j a va2 s . co m*/ if (method.equals("POST")) { HttpEntity<String> entity = new HttpEntity<>(jsonData, headers); response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class); paragraphHttpMap.put(paragraphId, response); } else if (method.equals("GET")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class); paragraphHttpMap.put(paragraphId, response); } else if (method.equals("DELETE")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class); } } catch (HttpClientErrorException e) { response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString())); } if (response == null) { return null; } if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201 || response.getStatusCode().value() == 404) { return response.getBody(); } else { String responseString = response.getBody(); if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) { return responseString; } LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); throw new Exception(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); } }
From source file:org.apereo.portal.events.tincan.providers.DefaultTinCanAPIProvider.java
/** * Initialize the API. Just sends an initialization event to the LRS provider. * This uses the activities/state API to do the initial test. *//*from ww w . j ava 2 s. c o m*/ @Override public void init() { loadConfig(); if (!isEnabled()) { return; } try { String actorStr = format(ACTOR_FORMAT, actorName, actorEmail); // Setup GET params... List<BasicNameValuePair> getParams = new ArrayList<>(); getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId)); getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr)); getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId)); Object body = null; if (formEncodeActivityData) { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED); map.add(activitiesFormParamName, json); body = map; } else { // just post a simple: {"status": "started"} record to the states API to verify // the service is up. Map<String, String> data = new HashMap<String, String>(); data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED); body = data; } ResponseEntity<Object> response = sendRequest(STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body, Object.class); if (response.getStatusCode().series() != Series.SUCCESSFUL) { logger.error("LRS provider for URL " + LRSUrl + " it not configured properly, or is offline. Disabling provider."); } // todo: Need to think through a strategy for handling errors submitting // to the LRS. } catch (HttpClientErrorException e) { // log some additional info in this case... logger.error("LRS provider for URL " + LRSUrl + " failed to contact LRS for initialization. Disabling provider.", e); logger.error(" Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString()); enabled = false; } catch (Exception e) { logger.error("LRS provider for URL " + LRSUrl + " failed to contact LRS for initialization. Disabling provider", e); enabled = false; } }
From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java
@Test public void testInvalidSaml2Bearer() throws Exception { SamlIdentityProviderDefinition idpDef = createLocalSamlIdpDefinition(IDP_ENTITY_ID, "uaa"); @SuppressWarnings("unchecked") IdentityProvider<SamlIdentityProviderDefinition> provider = IntegrationTestUtils.createIdentityProvider( "Local SAML IdP", IDP_ENTITY_ID, true, this.baseUrl, this.serverRunning, idpDef); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>(); postBody.add("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer"); postBody.add("client_id", "oauth_showcase_saml2_bearer"); postBody.add("client_secret", "secret"); postBody.add("assertion", "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDI6QXNzZXJ0aW9uIHhtbG5zOnNhbWwyPS" + "J1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIiBJRD0iXzBkNzhhYTdhLTY4MzctNDUyNi1iNTk4" + "LTliZGE0MTI5NTE0YiIgSXNzdWVJbnN0YW50PSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIFZlcnNpb249IjIuMC" + "IgeG1sbnM6eHM9Imh0dHA6Ly93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HRwOi8vd3d3LnczLm9yZy8yMD" + "AxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LndyaXRlPC9zYW1sMjpBdHRy" + "aWJ1dGVWYWx1ZT48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1" + "hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LnJlYWQ8L3NhbWwyOkF0dHJpYnV0" + "ZVZhbHVlPjwvc2FtbDI6QXR0cmlidXRlPjwvc2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdXRoblN0YX" + "RlbWVudCBBdXRobkluc3RhbnQ9IjIwMTYtMTEtMjJUMjI6MDI6MzAuMjk5WiIgU2Vzc2lvbk5vdE9uT3JBZnRlcj0i" + "MjAxNi0xMi0yMlQyMjowMjozMC4yOTlaIj48c2FtbDI6QXV0aG5Db250ZXh0PjxzYW1sMjpBdXRobkNvbnRleHRDbG" + "Fzc1JlZj51cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZDwvc2FtbDI6QXV0aG5D" + "b250ZXh0Q2xhc3NSZWY-PC9zYW1sMjpBdXRobkNvbnRleHQ-PC9zYW1sMjpBdXRoblN0YXRlbWVudD48L3NhbWwyOk" + "Fzc2VydGlvbj4"); try {//www . j a v a 2 s .com restOperations.exchange(baseUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class); } catch (HttpClientErrorException he) { Assert.assertEquals(HttpStatus.UNAUTHORIZED, he.getStatusCode()); } provider.setActive(false); IntegrationTestUtils.updateIdentityProvider(this.baseUrl, this.serverRunning, provider); }
From source file:org.cloudfoundry.identity.uaa.login.EmailResetPasswordService.java
@Override public void forgotPassword(String email) { String subject = getSubjectText(); String htmlContent = null;/*from w w w . j av a2s . c om*/ String userId = null; try { ResponseEntity<Map<String, String>> response = passwordResetEndpoints.resetPassword(email); if (response.getStatusCode() == HttpStatus.CONFLICT) { //TODO - file story to refactor and not swallow all errors below htmlContent = getResetUnavailableEmailHtml(email); userId = response.getBody().get("user_id"); } else if (response.getStatusCode() == HttpStatus.NOT_FOUND) { //TODO noop - previous implementation just logged an error } else { userId = response.getBody().get("user_id"); htmlContent = getCodeSentEmailHtml(response.getBody().get("code"), email); } } catch (HttpClientErrorException e) { if (e.getStatusCode() == HttpStatus.CONFLICT) { htmlContent = getResetUnavailableEmailHtml(email); try { Map<String, String> body = new ObjectMapper().readValue(e.getResponseBodyAsString(), new TypeReference<Map<String, String>>() { }); userId = body.get("user_id"); } catch (IOException ioe) { logger.error("Bad response from UAA", ioe); } } else { logger.info("Exception raised while creating password reset for " + email, e); } } catch (IOException e) { logger.error("Exception raised while creating password reset for " + email, e); } if (htmlContent != null && userId != null) { messageService.sendMessage(userId, email, MessageType.PASSWORD_RESET, subject, htmlContent); } }
From source file:org.opentestsystem.authoring.testspecbank.client.TestSpecBankClient.java
@Override public Optional<ValidationError> deleteTestSpecification(final String testSpecificationKey) { Optional<ValidationError> maybeValidationError = Optional.empty(); final URI uri = UriComponentsBuilder .fromUriString(String.format("%stestSpecification/%s", baseUri, testSpecificationKey)).build() .toUri();// w w w . j a va 2s . c o m try { tsbOauthRestTemplate.delete(uri); } catch (final HttpClientErrorException hce) { LOGGER.error("Error deleting {0} test specification: ", hce); if (hce.getStatusCode() == HttpStatus.UNPROCESSABLE_ENTITY) { try { // The NoContentResponseResource contains an array of ValidationErrors. If we got to this point, // the TestSpecificationController#deleteTestSpecification endpoint will have returned a // NoContentResponseResource with a single ValidationError describing what went wrong. final NoContentResponseResource response = objectMapper.readValue(hce.getResponseBodyAsString(), NoContentResponseResource.class); maybeValidationError = Optional.of(response.getErrors()[0]); } catch (final Exception mapEx) { LOGGER.error(String.format("Error mapping response %s to ValidationError: ", hce.getResponseBodyAsString()), mapEx); final String errorMessage = mapEx.getMessage() == null ? mapEx.getClass().getName() : mapEx.getMessage(); maybeValidationError = Optional.of(new ValidationError("mapping exception", errorMessage)); } } else { maybeValidationError = Optional.of(new ValidationError("client exception", hce.getMessage())); } } catch (final Exception e) { LOGGER.error("Error deleting {0} test specification: ", e); maybeValidationError = Optional.of(new ValidationError("server exception", e.getMessage())); } return maybeValidationError; }
From source file:org.springframework.cloud.config.client.ConfigServicePropertySourceLocator.java
private Environment getRemoteEnvironment(RestTemplate restTemplate, ConfigClientProperties properties, String label, String state) { String path = "/{name}/{profile}"; String name = properties.getName(); String profile = properties.getProfile(); String token = properties.getToken(); String uri = properties.getRawUri(); Object[] args = new String[] { name, profile }; if (StringUtils.hasText(label)) { args = new String[] { name, profile, label }; path = path + "/{label}"; }//from w w w .j a v a 2 s . c o m ResponseEntity<Environment> response = null; try { HttpHeaders headers = new HttpHeaders(); if (StringUtils.hasText(token)) { headers.add(TOKEN_HEADER, token); } if (StringUtils.hasText(state)) { //TODO: opt in to sending state? headers.add(STATE_HEADER, state); } final HttpEntity<Void> entity = new HttpEntity<>((Void) null, headers); response = restTemplate.exchange(uri + path, HttpMethod.GET, entity, Environment.class, args); } catch (HttpClientErrorException e) { if (e.getStatusCode() != HttpStatus.NOT_FOUND) { throw e; } } if (response == null || response.getStatusCode() != HttpStatus.OK) { return null; } Environment result = response.getBody(); return result; }
From source file:org.springframework.data.document.couchdb.core.CouchTemplate.java
public <T> T findOne(String id, Class<T> targetClass) { Assert.state(defaultDocumentUrl != null, "defaultDatabaseUrl must be set to use this method"); try {/* w ww . ja va 2 s .c om*/ return restOperations.getForObject(defaultDocumentUrl, targetClass, id); //TODO check this exception translation and centralize. } catch (HttpClientErrorException clientError) { if (clientError.getStatusCode() == HttpStatus.NOT_FOUND) { throw new DocumentRetrievalFailureException(defaultDocumentUrl + "/" + id); } throw new CouchUsageException(clientError); } catch (HttpServerErrorException serverError) { throw new CouchServerResourceUsageException(serverError); } catch (RestClientException otherError) { throw new UncategorizedCouchDataAccessException(otherError); } }
From source file:org.springframework.data.document.couchdb.core.CouchTemplate.java
public <T> T findOne(URI uri, Class<T> targetClass) { Assert.state(uri != null, "uri must be set to use this method"); try {/*from w ww .j av a 2 s.c o m*/ return restOperations.getForObject(uri, targetClass); //TODO check this exception translation and centralize. } catch (HttpClientErrorException clientError) { if (clientError.getStatusCode() == HttpStatus.NOT_FOUND) { throw new DocumentRetrievalFailureException(uri.getPath()); } throw new CouchUsageException(clientError); } catch (HttpServerErrorException serverError) { throw new CouchServerResourceUsageException(serverError); } catch (RestClientException otherError) { throw new UncategorizedCouchDataAccessException(otherError); } }