List of usage examples for org.springframework.web.client HttpServerErrorException getResponseBodyAsString
public String getResponseBodyAsString()
From source file:com.bose.aem.spring.config.ConfigServicePropertySourceLocator.java
@Override public org.springframework.core.env.PropertySource<?> locate( org.springframework.core.env.Environment environment) { ConfigClientProperties client = this.defaults.override(environment); CompositePropertySource composite = new CompositePropertySource("configService"); RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(client) : this.restTemplate; Exception error = null;/* ww w . ja v a 2s . c o m*/ String errorBody = null; //logger.info("Fetching config from server at: " + client.getRawUri()); try { String[] labels = new String[] { "" }; if (StringUtils.hasText(client.getLabel())) { labels = StringUtils.commaDelimitedListToStringArray(client.getLabel()); } // Try all the labels until one works for (String label : labels) { Environment result = getRemoteEnvironment(restTemplate, client.getRawUri(), client.getName(), client.getProfile(), label.trim()); if (result != null) { // logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s", // result.getName(), // result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()), // result.getLabel(), result.getVersion())); for (PropertySource source : result.getPropertySources()) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) source.getSource(); composite.addPropertySource(new MapPropertySource(source.getName(), map)); } return composite; } } } catch (HttpServerErrorException e) { error = e; if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) { errorBody = e.getResponseBodyAsString(); } } catch (Exception e) { error = e; } if (client != null && client.isFailFast()) { throw new IllegalStateException( "Could not locate PropertySource and the fail fast property is set, failing", error); } // logger.warn("Could not locate PropertySource: " // + (errorBody == null ? error == null ? "label not found" : error.getMessage() : errorBody)); return null; }
From source file:com.alexshabanov.springrestapi.ControllerMockTest.java
@Test public void shouldGetInternalServerError() throws IOException { doThrow(UnsupportedOperationException.class).when(profileController).deleteProfile(id); when(profileController.handleUnsupportedOperationException()).thenReturn(errorDesc); try {/*from w w w.j av a2 s . co m*/ restClient.delete(path(CONCRETE_PROFILE_RESOURCE), id); fail(); } catch (HttpServerErrorException e) { assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, e.getStatusCode()); final ErrorDesc actual = getObjectMapper().reader(ErrorDesc.class) .readValue(e.getResponseBodyAsString()); assertEquals(errorDesc, actual); } }
From source file:info.raack.appliancelabeler.service.OAuthRequestProcessor.java
public <T, S> S processRequest(String uri, OAuthSecurityContext context, ResponseHandler<T, S> handler) throws OAuthUnauthorizedException { logger.debug("Attempting to request " + uri); String responseString = null; InputStream xmlInputStream = null; try {//from w w w . j a va 2 s . com if (context != null) { // set the current authentication context OAuthSecurityContextHolder.setContext(context); } // use the normal request processor for the currently logged in user byte[] bytes = oAuthRestTemplate.getForObject(URI.create(uri), byte[].class); responseString = new String(bytes); //logger.debug(new String(bytes)); xmlInputStream = new ByteArrayInputStream(bytes); //logger.debug("response: " + new String(bytes)); synchronized (this) { try { T item = (T) ((JAXBElement) u1.unmarshal(xmlInputStream)).getValue(); return handler.extractValue(item); } catch (Exception e) { // don't do anything if we can't unmarshall with the teds.xsd - try the other one try { xmlInputStream.close(); } catch (Exception e2) { } xmlInputStream = new ByteArrayInputStream(bytes); } T item = (T) ((JAXBElement) u2.unmarshal(xmlInputStream)).getValue(); return handler.extractValue(item); } } catch (HttpClientErrorException e2) { // if unauthorized - our credentials are bad or have been revoked - throw exception up the stack if (e2.getStatusCode() == HttpStatus.UNAUTHORIZED) { throw new OAuthUnauthorizedException(); } else { throw new RuntimeException( "Unknown remote server error " + e2.getStatusCode() + " (" + e2.getStatusText() + ") returned when requesting " + uri + "; " + e2.getResponseBodyAsString()); } } catch (HttpServerErrorException e3) { throw new RuntimeException( "Unknown remote server error " + e3.getStatusCode() + " (" + e3.getStatusText() + ") returned when requesting " + uri + "; " + e3.getResponseBodyAsString()); } catch (Exception e) { throw new RuntimeException( "Could not request " + uri + (responseString != null ? " response was " + responseString : ""), e); } finally { try { if (xmlInputStream != null) { xmlInputStream.close(); } } catch (Exception e) { } } }
From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java
private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException { targetURL = livyURL + targetURL;//from w ww.jav a 2 s. co m LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); headers.add("X-Requested-By", "zeppelin"); for (Map.Entry<String, String> entry : customHeaders.entrySet()) { headers.add(entry.getKey(), entry.getValue()); } ResponseEntity<String> response = null; try { if (method.equals("POST")) { HttpEntity<String> entity = new HttpEntity<>(jsonData, headers); response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class); } else if (method.equals("GET")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class); } else if (method.equals("DELETE")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class); } } catch (HttpClientErrorException e) { response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString())); } catch (RestClientException e) { // Exception happens when kerberos is enabled. if (e.getCause() instanceof HttpClientErrorException) { HttpClientErrorException cause = (HttpClientErrorException) e.getCause(); if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) { throw new SessionNotFoundException(cause.getResponseBodyAsString()); } throw new LivyException(cause.getResponseBodyAsString() + "\n" + ExceptionUtils.getFullStackTrace(ExceptionUtils.getRootCause(e))); } if (e instanceof HttpServerErrorException) { HttpServerErrorException errorException = (HttpServerErrorException) e; String errorResponse = errorException.getResponseBodyAsString(); if (errorResponse.contains("Session is in state dead")) { throw new SessionDeadException(); } throw new LivyException(errorResponse, e); } throw new LivyException(e); } if (response == null) { throw new LivyException("No http response returned"); } LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(), response.getBody()); if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) { return response.getBody(); } else if (response.getStatusCode().value() == 404) { if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) { throw new SessionNotFoundException(response.getBody()); } else { throw new APINotFoundException( "No rest api found for " + targetURL + ", " + response.getStatusCode()); } } else { String responseString = response.getBody(); if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) { return responseString; } throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); } }
From source file:org.springframework.cloud.config.client.AbstractConfigServicePropertyLocator.java
@Override public PropertySource<?> locate(Environment environment) { final ConfigClientProperties client = defaults.override(environment); final CompositePropertySource composite = new CompositePropertySource("configService"); Exception error;/*from w w w. j av a 2 s .co m*/ String errorBody = null; try { return tryLocating(client, composite, environment); } catch (HttpServerErrorException e) { error = e; if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) { errorBody = e.getResponseBodyAsString(); } } catch (Exception e) { error = e; } if (client != null && client.isFailFast()) { throw new IllegalStateException( "Could not locate PropertySource and the fail fast property is set, failing", error); } logger.error("Could not locate PropertySource: " + (errorBody == null ? error.getMessage() : errorBody)); return null; }
From source file:org.springframework.cloud.config.client.ConfigServicePropertySourceLocator.java
@Override @Retryable(interceptor = "configServerRetryInterceptor") public org.springframework.core.env.PropertySource<?> locate( org.springframework.core.env.Environment environment) { ConfigClientProperties properties = this.defaultProperties.override(environment); CompositePropertySource composite = new CompositePropertySource("configService"); RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(properties) : this.restTemplate; Exception error = null;//w w w . ja v a2 s. c om String errorBody = null; logger.info("Fetching config from server at: " + properties.getRawUri()); try { String[] labels = new String[] { "" }; if (StringUtils.hasText(properties.getLabel())) { labels = StringUtils.commaDelimitedListToStringArray(properties.getLabel()); } String state = ConfigClientStateHolder.getState(); // Try all the labels until one works for (String label : labels) { Environment result = getRemoteEnvironment(restTemplate, properties, label.trim(), state); if (result != null) { logger.info(String.format( "Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s", result.getName(), result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()), result.getLabel(), result.getVersion(), result.getState())); for (PropertySource source : result.getPropertySources()) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) source.getSource(); composite.addPropertySource(new MapPropertySource(source.getName(), map)); } if (StringUtils.hasText(result.getState()) || StringUtils.hasText(result.getVersion())) { HashMap<String, Object> map = new HashMap<>(); putValue(map, "config.client.state", result.getState()); putValue(map, "config.client.version", result.getVersion()); composite.addFirstPropertySource(new MapPropertySource("configClient", map)); } return composite; } } } catch (HttpServerErrorException e) { error = e; if (MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) { errorBody = e.getResponseBodyAsString(); } } catch (Exception e) { error = e; } if (properties.isFailFast()) { throw new IllegalStateException( "Could not locate PropertySource and the fail fast property is set, failing", error); } logger.warn("Could not locate PropertySource: " + (errorBody == null ? error == null ? "label not found" : error.getMessage() : errorBody)); return null; }
From source file:org.springframework.web.client.RestTemplateIntegrationTests.java
@Test public void serverError() { try {/*from w ww .j a va 2 s . c om*/ template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null); fail("HttpServerErrorException expected"); } catch (HttpServerErrorException ex) { assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode()); assertNotNull(ex.getStatusText()); assertNotNull(ex.getResponseBodyAsString()); } }