List of usage examples for org.springframework.web.client HttpClientErrorException getStatusCode
public HttpStatus getStatusCode()
From source file:spring.AbstractAuthorizationCodeProviderTests.java
@Test @OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false) public void testUnauthenticatedAuthorizationRespondsUnauthorized() throws Exception { AccessTokenRequest request = context.getAccessTokenRequest(); request.setCurrentUri("http://anywhere"); request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); try {//from w w w . j a v a2s .co m String code = getAccessTokenProvider().obtainAuthorizationCode(context.getResource(), request); assertNotNull(code); fail("Expected UserRedirectRequiredException"); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); } }
From source file:org.alfresco.dropbox.service.action.DropboxUpdateAction.java
private void add(NodeRef nodeRef) { Metadata metadata = null;//ww w. j a va 2 s . c o m 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:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java
@Test public void testClientIdMustBeConsistent() throws Exception { webDriver.get(baseUrl + "/logout.do"); HttpHeaders headers = getAppBasicAuthHttpHeaders(); Map<String, String> requestBody = new HashMap<>(); requestBody.put("username", testAccounts.getUserName()); requestBody.put("password", testAccounts.getPassword()); ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("scope", "openid").queryParam("client_id", "stealer_of_codes") .queryParam("code", autologinCode).build().toUriString(); try {/*from ww w. ja v a 2s . co m*/ restOperations.exchange(authorizeUrl, HttpMethod.GET, null, Void.class); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); } }
From source file:com.tikinou.schedulesdirect.ClientUtils.java
public int retryConnection(SchedulesDirectClient client, AuthenticatedBaseCommandParameter params, HttpClientErrorException ex, int numRetries) throws Exception { numRetries--;//from w w w . j a va 2 s . c o m if (numRetries < 0) throw ex; if (ex.getStatusCode() == HttpStatus.FORBIDDEN) { client.getCredentials().resetTokenInfo(); params.setToken(null); client.connect(client.getCredentials(), false); params.setToken(client.getCredentials().getToken()); } return numRetries; }
From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java
/** * Test secure endpoint without authentication *//* www. ja v a 2 s.c o m*/ @Test public void testSecureEndpointNoAuthentication() { RestTemplate restTemplate = new RestTemplate(); try { restTemplate.getForEntity(SECURE_ENDPOINT, String.class); fail("Exception expected. None was thrown."); } catch (HttpClientErrorException ex) { assertEquals(ex.getStatusCode(), HttpStatus.UNAUTHORIZED); } catch (ResourceAccessException ex) { fail("It appears that the server may not be running. Please start it before running tests"); } catch (Exception ex) { fail(ex.getMessage()); } }
From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java
/** * Test authentication failure to method secure endpoint that requires only authentication * using no authentication//from w w w .j a v a 2 s . c o m */ @Test public void testClientCredentialsMethodNotLoggedIn() { RestTemplate restTemplate = new RestTemplate(); try { restTemplate.getForEntity(METHOD_SECURE_ENDPOINT, String.class); fail("Expected exception. None was thrown."); } catch (HttpClientErrorException ex) { assertEquals(ex.getStatusCode(), HttpStatus.UNAUTHORIZED); } catch (ResourceAccessException ex) { fail("It appears that the server may not be running. Please start it before running tests"); } catch (Exception ex) { fail(ex.getMessage()); } }
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 ww w.java 2s . c om*/ 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:com.compomics.colims.core.service.impl.UniProtServiceImpl.java
@Override public Map<String, String> getUniProtByAccession(String accession) throws RestClientException, IOException { Map<String, String> uniProt = new HashMap<>(); try {//from w w w . j a va 2s. co m // Set XML content type explicitly to force response in XML (If not spring gets response in JSON) HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML)); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); ResponseEntity<String> response = restTemplate.exchange(UNIPROT_BASE_URL + "/" + accession + ".xml", HttpMethod.GET, entity, String.class); String responseBody = response.getBody(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(responseBody)); Document document = (Document) builder.parse(is); document.getDocumentElement().normalize(); NodeList recommendedName = document.getElementsByTagName("recommendedName"); Node node = recommendedName.item(0); Element element = (Element) node; if (element.getElementsByTagName("fullName").item(0).getTextContent() != null && !element.getElementsByTagName("fullName").item(0).getTextContent().equals("")) { uniProt.put("description", element.getElementsByTagName("fullName").item(0).getTextContent()); } NodeList organism = document.getElementsByTagName("organism"); node = organism.item(0); element = (Element) node; if (element.getElementsByTagName("name").item(0).getTextContent() != null && !element.getElementsByTagName("name").item(0).getTextContent().equals("")) { uniProt.put("species", element.getElementsByTagName("name").item(0).getTextContent()); } NodeList dbReference = document.getElementsByTagName("dbReference"); node = dbReference.item(0); element = (Element) node; if (element.getAttribute("id") != null && !element.getAttribute("id").equals("")) { uniProt.put("taxid", element.getAttribute("id")); } } catch (HttpClientErrorException ex) { LOGGER.error(ex.getMessage(), ex); //ignore the exception if the namespace doesn't correspond to an ontology if (!ex.getStatusCode().equals(HttpStatus.NOT_FOUND)) { throw ex; } } catch (ParserConfigurationException | SAXException ex) { java.util.logging.Logger.getLogger(UniProtServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return uniProt; }
From source file:org.starfishrespect.myconsumption.server.business.sensors.flukso.FluksoRetriever.java
/** * Retrieves the parameters of the sensor from the API * * @return The parameters of this sensor * @throws RetrieveException if any error occurs *///from w ww.j ava2 s .com private FluksoParams retrieveParams() throws RetrieveException { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); headers.set("X-Version", "1.0"); headers.set("X-Token", sensor.getToken()); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); String url = "https://api.flukso.net/sensor/" + sensor.getFluksoId() + "?param=all"; try { FluksoParams params = restTemplate.exchange(url, HttpMethod.GET, entity, FluksoParams.class).getBody(); } catch (ResourceAccessException e) { throw new RetrieveException("Unknown retrieve exceptions"); } catch (HttpClientErrorException httpError) { int errorCode = httpError.getStatusCode().value(); switch (httpError.getStatusCode().value()) { case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_BAD_REQUEST: throw new RequestException(errorCode, "Bad sensor id or token"); case HttpStatus.SC_NOT_FOUND: throw new RequestException(errorCode, "API not found"); case HttpStatus.SC_INTERNAL_SERVER_ERROR: throw new ServerException(errorCode, "Resource not found"); default: throw new RetrieveException("Unknown retrieve exceptions"); } } return params; }
From source file:org.kaaproject.kaa.sandbox.web.services.CacheServiceImpl.java
private void retryRestCall(RestCall restCall, int maxRetries, long retryInterval, HttpStatus... acceptedErrorStatuses) throws SandboxServiceException { int retryCount = 0; while (retryCount++ < maxRetries) { try {/* ww w . j a v a 2 s.com*/ restCall.executeRestCall(); return; } catch (HttpClientErrorException httpClientError) { boolean accepted = false; for (HttpStatus acceptedStatus : acceptedErrorStatuses) { if (httpClientError.getStatusCode() == acceptedStatus) { accepted = true; break; } } if (accepted) { try { Thread.sleep(retryInterval); } catch (InterruptedException e) { } } else { throw Utils.handleException(httpClientError); } } catch (Exception e) { throw Utils.handleException(e); } } }