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);
}
}
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();
}
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);
}
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;
}
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);
}
Aggregations