Example usage for org.springframework.web.client HttpClientErrorException getStatusCode

List of usage examples for org.springframework.web.client HttpClientErrorException getStatusCode

Introduction

In this page you can find the example usage for org.springframework.web.client HttpClientErrorException getStatusCode.

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code.

Usage

From source file:org.alfresco.dropbox.webscripts.GetNode.java

private void syncUpdate(final NodeRef nodeRef, boolean useParent) {
    String currentUser = AuthenticationUtil.getRunAsUser();

    Map<String, NodeRef> syncedUsers = dropboxService.getSyncedUsers(nodeRef);

    if (useParent) {
        syncedUsers = filterMap(nodeRef);
    } else {/*from  w  ww  . ja v a  2 s  . c  o  m*/
        syncedUsers = dropboxService.getSyncedUsers(nodeRef);
    }

    syncedUsers.remove(currentUser);

    for (String key : syncedUsers.keySet()) {
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {
            public Object doWork() throws Exception {
                Metadata metadata = null;
                if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_CONTENT)) {
                    metadata = dropboxService.putFile(nodeRef, true);
                    dropboxService.persistMetadata(metadata, nodeRef);
                } 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().ordinal() == Status.STATUS_FORBIDDEN) {
                            metadata = dropboxService.getMetadata(nodeRef);
                        } else {
                            throw new WebScriptException(hcee.getMessage());
                        }
                    }
                }

                if (metadata != null) {
                    dropboxService.persistMetadata(metadata, nodeRef);
                } else {
                    throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                            "Dropbox metadata maybe out of sync for " + nodeRef);
                }

                return null;
            }
        }, key);
    }
}

From source file:org.starfishrespect.myconsumption.server.business.sensors.flukso.FluksoRetriever.java

/**
 * Tries to retrieve data for the sensor in the given interval and for the
 * given precision. All other retrieve methods use this
 *
 * @param start      start of the interval
 * @param end        end of the interval
 * @param resolution precision wanted./*w w w  .ja v  a  2 s .  c  om*/
 * @return the retrieved data
 * @throws RetrieveException if any error occurs
 */
private SensorData retrieve(Date start, Date end, int resolution) throws RetrieveException {
    SensorData data = new SensorData();
    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() + "?start=" + (start.getTime() / 1000)
            + "&end=" + (end.getTime() / 1000) + "&resolution=" + resolutionParam(resolution) + "&unit=watt";

    try {
        ArrayList<ArrayList> retrieved = restTemplate.exchange(url, HttpMethod.GET, entity, ArrayList.class)
                .getBody();
        boolean valuesFound = false;
        for (ArrayList measurement : retrieved) {
            if (measurement.size() < 2) {
                continue;
            }
            if (!(measurement.get(0) instanceof Integer) || !(measurement.get(1) instanceof Integer)) {
                continue;
            }
            valuesFound = true;
            int timestamp = (Integer) measurement.get(0);
            int value = (Integer) measurement.get(1);
            // timestamp - resolution because timestamp is the end time
            data.addMeasurement(timestamp - resolution, value);
        }
        if (!valuesFound) {
            data.setMayHaveMoreData(false);
        }
    } catch (HttpClientErrorException httpException) {
        throw new RequestException(httpException.getStatusCode().value(), "Cannot retrieve data.");
    } catch (ResourceAccessException resourceException) {
        throw new RetrieveException("Resource exceptions");
    } catch (RestClientException restException) {
        throw new InvalidDataException("Non-valid data");
    }

    return data;
}

From source file:br.com.modoagil.asr.rest.support.RESTErrorHandler.java

/**
 * Manipula exceo para status HTTP {@code 4xx}, exceo do cliente
 *
 * @param ex/* www .  ja v  a 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:de.zib.gndms.gndmc.dspace.Test.SliceClientTest.java

@Test(groups = { "sliceServiceTest" })
public void testCreateSubspace() {
    final String mode = "CREATE";

    ResponseEntity<Facets> subspace = null;
    try {// w w  w.j  a  va  2  s .  c  o  m
        subspace = subspaceClient.createSubspace(subspaceId, subspaceConfig, admindn);

        Assert.assertNotNull(subspace);
        Assert.assertEquals(subspace.getStatusCode(), HttpStatus.CREATED);
    } catch (HttpClientErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.UNAUTHORIZED))
            throw e;
    }

    final ResponseEntity<Facets> res = subspaceClient.listAvailableFacets(subspaceId, admindn);
    Assert.assertNotNull(res);
    Assert.assertEquals(res.getStatusCode(), HttpStatus.OK);
}

From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java

/**
 * This test is designed to test having a bad client Id.
 *//*w ww . ja va  2  s . c om*/
@Test
public void testBadClientId() {
    OAuth2RestTemplate restTemplate = AuthenticationUtil.getClientCredentialsWithBadClientId();
    try {
        restTemplate.getAccessToken();
        fail("Expected OAuth2AccessDeniedException, but none was thrown");
    } catch (OAuth2AccessDeniedException ex) {
        if (ex.getCause() instanceof HttpClientErrorException) {
            HttpClientErrorException clientException = (HttpClientErrorException) ex.getCause();
            assertEquals(HttpStatus.UNAUTHORIZED, clientException.getStatusCode());
        } else if (ex.getCause() instanceof ResourceAccessException) {
            fail("It appears that the server may not be running. Please start it before running tests");
        } else {
            fail(String.format("Expected HttpClientErrorException. Got %s",
                    ex.getCause().getClass().getName()));
        }
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
}

From source file:de.zib.gndms.gndmc.dspace.Test.SliceClientTest.java

@Test(groups = { "sliceServiceTest" }, dependsOnMethods = { "testCreateSubspace" })
public void testCreateSliceKind() {
    try {//from w  w w. j ava2  s .  c o  m
        final ResponseEntity<Specifier<Void>> sliceKind = subspaceClient.createSliceKind(subspaceId,
                sliceKindId, sliceKindConfig, admindn);
        Assert.assertNotNull(sliceKind);
        Assert.assertEquals(sliceKind.getStatusCode(), HttpStatus.CREATED);
    } catch (HttpClientErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.PRECONDITION_FAILED)) // already exists from last test?
            throw e;
    }

    final ResponseEntity<List<Specifier<Void>>> listResponseEntity = subspaceClient.listSliceKinds(subspaceId,
            admindn);
    final List<Specifier<Void>> specifierList = listResponseEntity.getBody();

    for (Specifier<Void> s : specifierList) {
        if (!s.getUriMap().containsKey(UriFactory.SLICE_KIND))
            continue;
        if (s.getUriMap().get(UriFactory.SLICE_KIND).equals(sliceKindId))
            return;
    }

    throw new IllegalStateException(
            "The created SliceKind " + sliceKindId + " could not be found in SliceKindListing");
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.CloudFoundryService.java

public void deleteUIServiceInstance(String uiServiceGuid) {
    try {/*  w  w w.ja v a 2  s.  c o  m*/
        execute(DELETE_SERVICE_URL, HttpMethod.DELETE, "", cfApiEndpoint, uiServiceGuid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            LOGGER.warn("GearPump UI instance with GUID {} doesn't exist. Skipping.", uiServiceGuid);
        } else {
            LOGGER.debug("Cannot delete GearPump UI instance with GUID {} - rethrowing excepiton.",
                    uiServiceGuid);
            throw e;
        }
    }
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.CloudFoundryService.java

private String deleteUaaClient(String clientId, String token) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION_HEADER, token);
    headers.add(CONTENT_TYPE_HEADER, "application/json");

    try {//from  w  w w.  j ava2  s  . c  o m
        LOGGER.debug("Deleting UAA client: {}", clientId);
        return executeWithHeaders(DELETE_UAA_CLIENT_URL, HttpMethod.DELETE, "", headers, uaaApiEndpoint,
                clientId).getBody();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            LOGGER.debug("Cannot delete UAA client: {}. It is not exists.", clientId);
        } else {
            LOGGER.debug("Cannot delete UAA client: {} Error: {}", clientId, e.getStatusText());
            throw e;
        }
    }
    return null;
}

From source file:de.zib.gndms.gndmc.dspace.Test.SliceClientTest.java

@Test(groups = { "sliceServiceTest" }, dependsOnMethods = { "testFileTransfer" })
public void testDeleteSlice() {
    {// ww w.  j  a v a2s .  c  o  m
        final ResponseEntity<Specifier<Facets>> responseEntity = sliceClient.deleteSlice(subspaceId,
                sliceKindId, sliceId, admindn);

        Assert.assertNotNull(responseEntity);
        Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);

        // wait for task to finish
        AbstractTaskFlowExecClient.waitForFinishOrFail(responseEntity.getBody(), taskClient, 500, admindn,
                "DELETESLICEWID");
    }

    // check for nonexistance of slice
    {
        try {
            final ResponseEntity<Facets> responseEntity = sliceClient.listSliceFacets(subspaceId, sliceKindId,
                    sliceId, admindn);

            Assert.assertNotNull(responseEntity);
            Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.NOT_FOUND);
        } catch (HttpClientErrorException e) {
            Assert.assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND);
        }
    }
}