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.cloudfoundry.runtime.CloudServicesScannerTest.java

/**
 * Verifies that service scan will create beans for bound services when we
 * do not have services of all types deployed
 *
 * @throws IOException//ww w  .  j av a 2  s  . com
 */
@SuppressWarnings("unchecked")
@Test
public void serviceScanMissingSomeServices() throws IOException {
    List<String> serviceNames = createServicesMinusMongo();
    createAndStartApp("cf-runtime-test-app", serviceNames);
    assertTrue("Test application is not available",
            testAppCreator.isAppAvailable(computeAppUrl(), 500l, 120000l));
    Map<String, Object> cloudProps = restTemplate.getForObject(computeAppUrl() + "/properties", Map.class);
    assertFalse(cloudProps.isEmpty());
    // Check for 404s on rest of dependencies
    restTemplate.getForObject(computeAppUrl() + "/mysql", String.class);
    restTemplate.getForObject(computeAppUrl() + "/redis/class", String.class);
    restTemplate.getForObject(computeAppUrl() + "/rabbit", String.class);
    restTemplate.getForObject(computeAppUrl() + "/postgres", String.class);
    try {
        restTemplate.getForObject(computeAppUrl() + "/mongo", String.class);
        fail("Mongo service bean should not be created");
    } catch (HttpClientErrorException e) {
        if (!(e.getStatusCode().equals(HttpStatus.NOT_FOUND))) {
            fail("Expected a 404 when looking for mongo service bean.  Got: " + e);
        }
    }
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.FilesDownloader.java

public Path download(String resourcePath, Path destinationFilePath) throws IOException {

    basicAuthRestTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());

    String resourceUrl = serverUrl + resourcePath;

    LOGGER.info("Downloading " + resourceUrl);

    try {//from  w w w  .j  a  va2s .  c om
        ResponseEntity<byte[]> response = basicAuthRestTemplate.exchange(resourceUrl, HttpMethod.GET,
                HttpCommunication.basicAuthRequest(basicAuthToken), byte[].class);
        return Files.write(destinationFilePath, response.getBody());

    } catch (HttpClientErrorException e) {
        String errorMessage = prepareErrorMessage(e.getStatusCode(), resourceUrl);
        LOGGER.error(errorMessage);
        throw new IOException(errorMessage, e);
    }
}

From source file:org.wheelmap.android.net.ApiKeyExecutor.java

@Override
protected void checkApiCallClientErrors(HttpClientErrorException e) throws RestServiceException {
    HttpStatus status = e.getStatusCode();
    if (status.value() == statusAuthFailed) {
        Log.e(getTag(), "authorization failed - email or password not valid");
        processException(RestServiceException.ERROR_AUTHORIZATION_ERROR, e, false);
    } else if (status.value() == statusOSMFailed) {
        Log.e(getTag(), "osm failed");
        processException(RestServiceException.ERROR_NOT_OSM_CONNECTED, e, false);
    }/*from  www .j  a  v  a  2 s .c  o  m*/
}

From source file:org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.java

@Override
public String fetch(int id) {
    String path = String.format("/schemas/ids/%d", id);
    HttpHeaders headers = new HttpHeaders();
    headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json",
            "application/vnd.schemaregistry+json", "application/json"));
    headers.add("Content-Type", "application/vnd.schemaregistry.v1+json");
    HttpEntity<String> request = new HttpEntity<>("", headers);
    try {// ww w  .ja  v a  2  s.  c  o m
        ResponseEntity<Map> response = this.template.exchange(this.endpoint + path, HttpMethod.GET, request,
                Map.class);
        return (String) response.getBody().get("schema");
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new SchemaNotFoundException(String.format("Could not find schema with id: %s", id));
        } else {
            throw e;
        }
    }
}

From source file:org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.java

@Override
public String fetch(SchemaReference schemaReference) {
    String path = String.format("/subjects/%s/versions/%d", schemaReference.getSubject(),
            schemaReference.getVersion());
    HttpHeaders headers = new HttpHeaders();
    headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json",
            "application/vnd.schemaregistry+json", "application/json"));
    headers.add("Content-Type", "application/vnd.schemaregistry.v1+json");
    HttpEntity<String> request = new HttpEntity<>("", headers);
    try {//  w w w.j a  v a  2  s.c o m
        ResponseEntity<Map> response = this.template.exchange(this.endpoint + path, HttpMethod.GET, request,
                Map.class);
        return (String) response.getBody().get("schema");
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new SchemaNotFoundException(
                    String.format("Could not find schema for reference: %s", schemaReference));
        } else {
            throw e;
        }
    }
}

From source file:com.tikal.tallerWeb.data.access.rest.AutoDAOImp.java

public void guardar(Auto dato) {
    // como no tengo idea si es nuevo o no primero se intenta como si ya existiera, si regresa 404 se crea.
    try {//ww w. j a  v a  2  s . co  m
        Map<String, Object> map = new HashMap<>();
        map.put("numeroSerie", dato.getNumeroSerie());
        //            factory.getTemplate().postForLocation(factory.getRootUlr() + "/autos/{numeroSerie}", dato, map);
    } catch (HttpClientErrorException ex) {
        HttpStatus status = ex.getStatusCode();
        if (status != HttpStatus.NOT_FOUND) {
            throw ex;
        }
        //            URI resource = factory.getTemplate().postForLocation(factory.getRootUlr() + "/autos", dato);
        //            String[] uri = StringUtils.split(resource.toString(), '/');
        //            String id = uri[uri.length - 1];
        //            dato.setNumeroSerie(id);
    }
}

From source file:org.cloudfoundry.runtime.test.util.ApplicationCreator.java

/**
 * Periodically performs a GET against the specified URL via RestTemplate to
 * check for app availability./*from  ww  w.  j  ava 2 s .  c  o m*/
 *
 * @param urlToCheck
 *            A RESTful URL belonging to the app we are status-ing
 * @param retryInterval
 *            The interval in milliseconds to wait between pinging the URL
 * @param timeout
 *            The timeout for checking the URL
 * @return false if the GET is not successful within the default timeout (2
 *         minutes)
 */
public boolean isAppAvailable(final String urlToCheck, final long retryInterval, final long timeout) {
    SpinBarrier waitForAppStart = new SpinBarrier(timeout, retryInterval, new SpinBarrierCondition() {
        @Override
        public boolean evaluate() {
            try {
                restTemplate.getForObject(urlToCheck, String.class);
                return true;
            } catch (HttpClientErrorException e) {
                if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
                    return false;
                }
                throw e;
            }
        }
    });
    return waitForAppStart.waitFor();
}

From source file:org.ow2.proactive.scheduling.api.graphql.service.AuthenticationService.java

private String getLoginFromSessionId(String sessionId) {
    try {//  w w w.ja  v a  2 s. c om

        String login = restTemplate.getForObject(schedulerLoginFetchUrl + sessionId, String.class);

        if (!Strings.isNullOrEmpty(login)) {
            return login;
        }

        throw new MissingSessionIdException();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new InvalidSessionIdException();
        } else {
            throw e;
        }
    }
}

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

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

    ResponseEntity<Facets> subspace = null;
    try {/*from w  ww  . j  a v  a2s. 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.springsource.greenhouse.AbstractGreenhouseActivity.java

protected void processException(Exception e) {
    if (e != null) {
        if (e instanceof ResourceAccessException) {
            displayNetworkError();/*from  w  w  w.j a v a2  s  .com*/
        } else if (e instanceof HttpClientErrorException) {
            HttpClientErrorException httpError = (HttpClientErrorException) e;
            if (httpError.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                displayAuthorizationError();
            }
        }
    }
}