Search in sources :

Example 76 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project apollo by ctripcorp.

the class ItemService method getNamespaceId.

private long getNamespaceId(NamespaceIdentifier namespaceIdentifier) {
    String appId = namespaceIdentifier.getAppId();
    String clusterName = namespaceIdentifier.getClusterName();
    String namespaceName = namespaceIdentifier.getNamespaceName();
    Env env = namespaceIdentifier.getEnv();
    NamespaceDTO namespaceDTO;
    try {
        namespaceDTO = namespaceAPI.loadNamespace(appId, env, clusterName, namespaceName);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new BadRequestException(String.format("namespace not exist. appId:%s, env:%s, clusterName:%s, namespaceName:%s", appId, env, clusterName, namespaceName));
        }
        throw e;
    }
    return namespaceDTO.getId();
}
Also used : NamespaceDTO(com.ctrip.framework.apollo.common.dto.NamespaceDTO) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) BadRequestException(com.ctrip.framework.apollo.common.exception.BadRequestException) Env(com.ctrip.framework.apollo.portal.environment.Env)

Example 77 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project apollo by ctripcorp.

the class NamespaceControllerWithAuthorizationTest method testCreateAppNamespaceWithoutAuthority.

/**
 * test method {@link NamespaceController#createAppNamespace(String, OpenAppNamespaceDTO)} without
 * authority.
 */
@Test
@Sql(scripts = "/sql/openapi/NamespaceControllerTest.testCreateAppNamespace.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateAppNamespaceWithoutAuthority() {
    final OpenAppNamespaceDTO dto = new OpenAppNamespaceDTO();
    dto.setAppId("consumer-test-app-id-1");
    dto.setName("create-app-namespace-fail");
    dto.setFormat(ConfigFileFormat.Properties.getValue());
    dto.setDataChangeCreatedBy("apollo");
    try {
        restTemplate.exchange(this.url("/openapi/v1/apps/{appId}/appnamespaces"), HttpMethod.POST, new HttpEntity<>(dto, HTTP_HEADERS_WITH_TOKEN), OpenAppNamespaceDTO.class, dto.getAppId());
        fail("should throw");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
        String result = e.getResponseBodyAsString();
        assertTrue(result.contains("org.springframework.security.access.AccessDeniedException"));
    }
    // random app id
    dto.setAppId(UUID.randomUUID().toString());
    try {
        restTemplate.exchange(this.url("/openapi/v1/apps/{appId}/appnamespaces"), HttpMethod.POST, new HttpEntity<>(dto, HTTP_HEADERS_WITH_TOKEN), OpenAppNamespaceDTO.class, dto.getAppId());
        fail("should throw");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
        String result = e.getResponseBodyAsString();
        assertTrue(result.contains("org.springframework.security.access.AccessDeniedException"));
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) OpenAppNamespaceDTO(com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO) Test(org.junit.Test) Sql(org.springframework.test.context.jdbc.Sql)

Example 78 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project webofneeds by researchstudio-sat.

the class LinkedDataRestClient method readResourceData.

protected DatasetResponseWithStatusCodeAndHeaders readResourceData(URI resourceURI, RestTemplate restTemplate, HttpHeaders requestHeaders) {
    assert resourceURI != null : "resource URI must not be null";
    StopWatch sw = new StopWatch();
    sw.start();
    logger.debug("fetching linked data resource: {}", resourceURI);
    // If a RestClientException is thrown here complaining that it can't read a
    // Model with MIME media type text/html,
    // it was probably the wrong resourceURI
    Dataset result;
    int statusCode;
    HttpHeaders responseHeaders;
    try {
        HttpEntity entity = new HttpEntity(null, requestHeaders);
        ResponseEntity<Dataset> response = restTemplate.exchange(resourceURI, HttpMethod.GET, entity, Dataset.class);
        // RestTemplate will automatically follow redirects on HttpGet calls
        statusCode = response.getStatusCode().value();
        responseHeaders = response.getHeaders();
        if (response.getStatusCode().is4xxClientError()) {
            throw new HttpClientErrorException(response.getStatusCode());
        }
        if (response.getStatusCode().is5xxServerError()) {
            throw new HttpServerErrorException(response.getStatusCode());
        }
        result = response.getBody();
    } catch (RestClientException e) {
        // first, let's see if we can answer the request from loaded ontologies:
        logger.debug("Could not fetch {} from the Web, searching fallback in included resources", resourceURI);
        if (e instanceof HttpClientErrorException.NotFound) {
            Optional<Model> fallbackResult = IncludedWonOntologies.get(resourceURI);
            if (fallbackResult.isPresent()) {
                logger.debug("Found fallback resource for {}, returning as result", resourceURI);
                // we want the application to get a (possibly updated) version of this resource
                // eventually, but we
                // also want to avoid to keep making failing requests. We return the fallback
                // result and use
                // a caching period of one hour.
                Dataset dataset = DatasetFactory.createGeneral();
                dataset.setDefaultModel(fallbackResult.get());
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CACHE_CONTROL, "max-age=" + FALLBACK_CACHE_MAX_AGE_SECONDS);
                return new DatasetResponseWithStatusCodeAndHeaders(dataset, 200, headers);
            }
        }
        if (e instanceof HttpClientErrorException.Forbidden) {
            List<String> wwwAuthenticateHeaders = ((HttpClientErrorException.Forbidden) e).getResponseHeaders().get(HttpHeaders.WWW_AUTHENTICATE);
            if (wwwAuthenticateHeaders != null && !wwwAuthenticateHeaders.isEmpty()) {
                String headerValue = wwwAuthenticateHeaders.get(0);
                throw new LinkedDataFetchingException.ForbiddenAuthMethodProvided(resourceURI, String.format("Access to %s was denied (forbidden), but WWW-Authenticate Header indicates how to authorize", resourceURI), e, headerValue);
            } else {
                throw new LinkedDataFetchingException.Forbidden(resourceURI, String.format("Access to %s was denied (forbidden)", resourceURI), e);
            }
        }
        if (e instanceof HttpClientErrorException.Unauthorized) {
            List<String> wwwAuthenticateHeaders = ((HttpClientErrorException.Forbidden) e).getResponseHeaders().get(HttpHeaders.WWW_AUTHENTICATE);
            if (wwwAuthenticateHeaders != null && !wwwAuthenticateHeaders.isEmpty()) {
                String headerValue = wwwAuthenticateHeaders.get(0);
                throw new LinkedDataFetchingException.UnauthorizedAuthMethodProvided(resourceURI, String.format("Access to %s was denied (unauthorized, possibly due to an invalid token), but WWW-Authenticate Header indicates how to authorize", resourceURI), e, headerValue);
            } else {
                throw new LinkedDataFetchingException.Unauthorized(resourceURI, String.format("Access to %s was denied (unauthorized, possibly due to an invalid token)", resourceURI), e);
            }
        }
        if (e instanceof HttpClientErrorException) {
            throw new LinkedDataFetchingException(resourceURI, MessageFormat.format("Caught a HttpClientErrorException exception, for {0}. Underlying error message is: {1}, response Body: {2}", resourceURI, e.getMessage(), ((HttpClientErrorException) e).getResponseBodyAsString()), e, ((HttpClientErrorException) e).getRawStatusCode());
        }
        if (e instanceof HttpServerErrorException) {
            throw new LinkedDataFetchingException(resourceURI, MessageFormat.format("Caught a HttpServerErrorException exception, for {0}. Underlying error message is: {1}, response Body: {2}", resourceURI, e.getMessage(), ((HttpServerErrorException) e).getResponseBodyAsString()), e, ((HttpServerErrorException) e).getRawStatusCode());
        }
        throw new LinkedDataFetchingException(resourceURI, MessageFormat.format("Caught a clientHandler exception, " + "which may indicate that the URI that was accessed isn''t a" + " linked data URI, please check {0}. Underlying error message is: {1}", resourceURI, e.getMessage()), e);
    }
    if (logger.isDebugEnabled()) {
        if (result == null) {
            logger.debug("fetching resulted in null dataset for resource {}", resourceURI);
        } else if (result.getDefaultModel() == null) {
            logger.debug("fetched dataset with empty default model for resource {}", resourceURI);
        } else {
            logger.debug("fetched dataset with {} statements in default model for resource {}", result.getDefaultModel().size(), resourceURI);
        }
    }
    sw.stop();
    logger.debug(LogMarkers.TIMING, "fetching {} took {} millis", resourceURI, sw.getLastTaskTimeMillis());
    return new DatasetResponseWithStatusCodeAndHeaders(result, statusCode, responseHeaders);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) Optional(java.util.Optional) Dataset(org.apache.jena.query.Dataset) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) StopWatch(org.springframework.util.StopWatch) RestClientException(org.springframework.web.client.RestClientException) List(java.util.List)

Example 79 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project webofneeds by researchstudio-sat.

the class AuthEnabledLinkedDataRestClient method readAccessTokens.

public Set<String> readAccessTokens(URI resourceURI, RestTemplate restTemplate, HttpHeaders requestHeaders) {
    assert resourceURI != null : "resource URI must not be null";
    StopWatch sw = new StopWatch();
    sw.start();
    logger.debug("fetching linked data resource: {}", resourceURI);
    // If a RestClientException is thrown here complaining that it can't read a
    // Model with MIME media type text/html,
    // it was probably the wrong resourceURI
    Set<String> result;
    int statusCode;
    HttpHeaders responseHeaders;
    try {
        HttpEntity entity = new HttpEntity(null, requestHeaders);
        ResponseEntity<Set> response = restTemplate.exchange(resourceURI, HttpMethod.GET, entity, Set.class);
        // RestTemplate will automatically follow redirects on HttpGet calls
        statusCode = response.getStatusCode().value();
        responseHeaders = response.getHeaders();
        if (response.getStatusCode().is4xxClientError()) {
            throw new HttpClientErrorException(response.getStatusCode());
        }
        if (response.getStatusCode().is5xxServerError()) {
            throw new HttpServerErrorException(response.getStatusCode());
        }
        result = response.getBody();
    } catch (RestClientException e) {
        // first, let's see if we can answer the request from loaded ontologies:
        if (e instanceof HttpClientErrorException) {
            throw new LinkedDataFetchingException(resourceURI, MessageFormat.format("Caught a HttpClientErrorException exception trying to obtain token from {0}. Underlying error message is: {1}, response Body: {2}", resourceURI, e.getMessage(), ((HttpClientErrorException) e).getResponseBodyAsString()), e, ((HttpClientErrorException) e).getRawStatusCode());
        }
        if (e instanceof HttpServerErrorException) {
            throw new LinkedDataFetchingException(resourceURI, MessageFormat.format("Caught a HttpServerErrorException exception trying to obtain token from {0}. Underlying error message is: {1}, response Body: {2}", resourceURI, e.getMessage(), ((HttpServerErrorException) e).getResponseBodyAsString()), e, ((HttpServerErrorException) e).getRawStatusCode());
        }
        throw new LinkedDataFetchingException(resourceURI, MessageFormat.format("Caught a clientHandler exception trying to obtain token from {0}. Underlying error message is: {1}", resourceURI, e.getMessage()), e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("fetched auth token from {}", resourceURI);
    }
    sw.stop();
    logger.debug(LogMarkers.TIMING, "fetching {} took {} millis", resourceURI, sw.getLastTaskTimeMillis());
    return result;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Set(java.util.Set) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) RestClientException(org.springframework.web.client.RestClientException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) StopWatch(org.springframework.util.StopWatch)

Example 80 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project webofneeds by researchstudio-sat.

the class ActiveMQServiceImpl method getMatcherProtocolTopicNamesWithResource.

public Set<String> getMatcherProtocolTopicNamesWithResource(URI resourceURI) {
    Set<String> activeMQMatcherProtocolTopicNames = new HashSet<>();
    resourceURI = URI.create(resourceURI.toString() + pathInformation);
    for (String s : matcherProtocolTopicList) {
        try {
            Path path = PathParser.parse(s, PrefixMapping.Standard);
            activeMQMatcherProtocolTopicNames.add(RdfUtils.getStringPropertyForPropertyPath(linkedDataSource.getDataForPublicResource(resourceURI), resourceURI, path));
        } catch (HttpClientErrorException e) {
            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                return null;
            } else {
                throw e;
            }
        }
    }
    return activeMQMatcherProtocolTopicNames;
}
Also used : Path(org.apache.jena.sparql.path.Path) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashSet(java.util.HashSet)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)109 HttpHeaders (org.springframework.http.HttpHeaders)31 Test (org.junit.Test)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 HashMap (java.util.HashMap)21 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)21 MediaType (org.springframework.http.MediaType)19 RestTemplate (org.springframework.web.client.RestTemplate)19 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)18 HttpEntity (org.springframework.http.HttpEntity)16 URI (java.net.URI)15 Map (java.util.Map)8 HttpStatus (org.springframework.http.HttpStatus)8 RestClientException (org.springframework.web.client.RestClientException)8 ResourceAccessException (org.springframework.web.client.ResourceAccessException)7 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)6 Date (java.util.Date)5 List (java.util.List)5 OpenAppNamespaceDTO (com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO)4 ArrayList (java.util.ArrayList)4