Search in sources :

Example 36 with RestClientException

use of org.springframework.web.client.RestClientException in project perun by CESNET.

the class PerunCLI method call.

private static void call(PerunCommand command, String[] cliArgs) throws ParseException {
    // prepare CLI options
    // first options common to all commands
    Options options = new Options();
    options.addOption(Option.builder(PERUN_URL_OPTION).required(false).hasArg().longOpt(PERUN_URL_VARIABLE).desc("Perun base URL").build());
    options.addOption(Option.builder(PERUN_USER_OPTION).required(false).hasArg().longOpt(PERUN_USER_VARIABLE).desc("HTTP Basic Auth user/password").build());
    options.addOption(Option.builder(DEBUG_OPTION).required(false).hasArg(false).longOpt("debug").desc("debugging output").build());
    options.addOption(Option.builder(HELP_OPTION).required(false).hasArg(false).longOpt("help").desc("print options").build());
    // then options specific to the command
    command.addOptions(options);
    // parse options
    CommandLine commandLine;
    try {
        commandLine = new DefaultParser().parse(options, cliArgs);
    } catch (MissingOptionException ex) {
        printHelp(command, options);
        return;
    }
    if (commandLine.hasOption(HELP_OPTION)) {
        printHelp(command, options);
        return;
    }
    if (commandLine.hasOption(DEBUG_OPTION)) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        ch.qos.logback.classic.Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.DEBUG);
    }
    // find URL
    String perunUrl = System.getenv(PERUN_URL_VARIABLE);
    if (commandLine.hasOption(PERUN_URL_OPTION)) {
        perunUrl = commandLine.getOptionValue(PERUN_URL_OPTION);
    }
    if (perunUrl == null)
        perunUrl = "https://perun.cesnet.cz/krb/rpc";
    // find user and password
    String user = System.getenv(PERUN_USER_VARIABLE);
    if (commandLine.hasOption(PERUN_USER_OPTION)) {
        user = commandLine.getOptionValue(PERUN_USER_OPTION);
    }
    PerunRPC perunRPC;
    if (user == null) {
        perunRPC = new PerunRPC(perunUrl, null, null, new KerberosRestTemplate(null, "-"));
    } else {
        int slash = user.indexOf('/');
        if (slash == -1) {
            System.err.println("the username and password must be separated by the '/' character");
            System.exit(1);
        }
        String username = user.substring(0, slash);
        String password = user.substring(slash + 1);
        perunRPC = new PerunRPC(perunUrl, username, password);
    }
    // execute the command
    HttpClientErrorException hce = null;
    try {
        command.executeCommand(new CommandContext(perunRPC, commandLine));
    } catch (HttpClientErrorException e1) {
        // normal RestTemplate throws this exception on status 400
        hce = e1;
    } catch (RestClientException e2) {
        if (e2.getCause() instanceof HttpClientErrorException) {
            // KerberosRestTemplate throws the exception wrapped
            hce = (HttpClientErrorException) e2.getCause();
        } else {
            // something other went wrong
            throw e2;
        }
    }
    if (hce != null) {
        PerunException pe = PerunException.to(hce);
        System.err.println(pe.getMessage());
        System.exit(1);
    }
}
Also used : Options(org.apache.commons.cli.Options) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) PerunException(cz.metacentrum.perun.openapi.PerunException) LoggerContext(ch.qos.logback.classic.LoggerContext) PerunRPC(cz.metacentrum.perun.openapi.PerunRPC) CommandLine(org.apache.commons.cli.CommandLine) KerberosRestTemplate(org.springframework.security.kerberos.client.KerberosRestTemplate) RestClientException(org.springframework.web.client.RestClientException) MissingOptionException(org.apache.commons.cli.MissingOptionException) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 37 with RestClientException

use of org.springframework.web.client.RestClientException in project spring-boot-admin by codecentric.

the class DefaultApplicationRegistratorTest method register_should_return_false_when_failed.

@Test
public void register_should_return_false_when_failed() {
    ApplicationRegistrator registrator = new DefaultApplicationRegistrator(() -> this.application, this.registrationClient, new String[] { "http://sba:8080/instances", "http://sba2:8080/instances" }, true);
    when(this.registrationClient.register(any(), eq(this.application))).thenThrow(new RestClientException("Error"));
    assertThat(registrator.register()).isFalse();
    assertThat(registrator.register()).isFalse();
    assertThat(registrator.getRegisteredId()).isNull();
}
Also used : RestClientException(org.springframework.web.client.RestClientException) Test(org.junit.jupiter.api.Test)

Example 38 with RestClientException

use of org.springframework.web.client.RestClientException in project open-kilda by telstra.

the class TraffExamServiceImpl method initializePools.

@PostConstruct
void initializePools() {
    baseUrl = labEndpoint + "/api/" + topology.getLabId() + "/traffgen/";
    hostsPool = new ConcurrentHashMap<>();
    for (TraffGen traffGen : topology.getActiveTraffGens()) {
        URI controlEndpoint;
        try {
            controlEndpoint = new URI(traffGen.getControlEndpoint());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(String.format("Invalid traffGen(%s) REST endpoint address \"%s\": %s", traffGen.getName(), traffGen.getControlEndpoint(), e.getMessage()), e);
        }
        UUID id = UUID.randomUUID();
        Host host = new Host(id, traffGen.getIfaceName(), controlEndpoint, traffGen.getName());
        try {
            restTemplate.headForHeaders(makeHostUri(host).path("endpoint").build());
        } catch (RestClientException ex) {
            throw new IllegalArgumentException(String.format("The traffGen(%s) REST endpoint address \"%s\" can't be reached: %s", traffGen.getName(), traffGen.getControlEndpoint(), ex.getMessage()), ex);
        }
        hostsPool.put(id, host);
    }
    TraffGenConfig config = topology.getTraffGenConfig();
    Inet4Network network;
    try {
        network = new Inet4Network((Inet4Address) Inet4Address.getByName(config.getAddressPoolBase()), config.getAddressPoolPrefixLen());
    } catch (Inet4ValueException | UnknownHostException e) {
        throw new InputMismatchException(String.format("Invalid traffGen address pool \"%s:%s\": %s", config.getAddressPoolBase(), config.getAddressPoolPrefixLen(), e));
    }
    addressPool = new Inet4NetworkPool(network, 30);
}
Also used : Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) Host(org.openkilda.testing.service.traffexam.model.Host) URISyntaxException(java.net.URISyntaxException) InputMismatchException(java.util.InputMismatchException) URI(java.net.URI) TraffGen(org.openkilda.testing.model.topology.TopologyDefinition.TraffGen) Inet4Network(org.openkilda.testing.service.traffexam.networkpool.Inet4Network) Inet4ValueException(org.openkilda.testing.service.traffexam.networkpool.Inet4ValueException) RestClientException(org.springframework.web.client.RestClientException) TraffGenConfig(org.openkilda.testing.model.topology.TopologyDefinition.TraffGenConfig) Inet4NetworkPool(org.openkilda.testing.service.traffexam.networkpool.Inet4NetworkPool) UUID(java.util.UUID) PostConstruct(javax.annotation.PostConstruct)

Example 39 with RestClientException

use of org.springframework.web.client.RestClientException 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 40 with RestClientException

use of org.springframework.web.client.RestClientException 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)

Aggregations

RestClientException (org.springframework.web.client.RestClientException)43 HttpHeaders (org.springframework.http.HttpHeaders)12 HttpEntity (org.springframework.http.HttpEntity)11 IOException (java.io.IOException)9 RestTemplate (org.springframework.web.client.RestTemplate)9 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)8 Test (org.junit.Test)5 JsonParseException (com.fasterxml.jackson.core.JsonParseException)4 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)4 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)4 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)4 URI (java.net.URI)3 List (java.util.List)3 Test (org.junit.jupiter.api.Test)3 JSONObject (com.alibaba.fastjson.JSONObject)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 RealNameAuthentication (com.itrus.portal.db.RealNameAuthentication)2 RealNameAuthenticationExample (com.itrus.portal.db.RealNameAuthenticationExample)2 GitHubDTO (com.nixmash.blog.jpa.dto.GitHubDTO)2