下面列出了org.springframework.web.client.DefaultResponseErrorHandler#org.springframework.web.client.HttpServerErrorException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) {
if (logger.isDebugEnabled()) {
logger.debug("Executing SockJS Info request, url=" + infoUrl);
}
HttpHeaders infoRequestHeaders = new HttpHeaders();
if (headers != null) {
infoRequestHeaders.putAll(headers);
}
ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
if (response.getStatusCode() != HttpStatus.OK) {
if (logger.isErrorEnabled()) {
logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
}
throw new HttpServerErrorException(response.getStatusCode());
}
if (logger.isTraceEnabled()) {
logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
}
String result = response.getBody();
return (result != null ? result : "");
}
@Override
public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR send, url=" + url);
}
ResponseEntity<String> response = executeSendRequestInternal(url, headers, message);
if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
if (logger.isErrorEnabled()) {
logger.error("XHR send request (url=" + url + ") failed: " + response);
}
throw new HttpServerErrorException(response.getStatusCode());
}
if (logger.isTraceEnabled()) {
logger.trace("XHR send request (url=" + url + ") response: " + response);
}
}
@Test
public void connectFailure() throws Exception {
final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
RestOperations restTemplate = mock(RestOperations.class);
given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);
final CountDownLatch latch = new CountDownLatch(1);
connect(restTemplate).addCallback(
new ListenableFutureCallback<WebSocketSession>() {
@Override
public void onSuccess(WebSocketSession result) {
}
@Override
public void onFailure(Throwable ex) {
if (ex == expected) {
latch.countDown();
}
}
}
);
verifyNoMoreInteractions(this.webSocketHandler);
}
@Test
public void testBrokerFileHostNotExist() {
try {
HttpHeaders headers = new HttpHeaders();
headers.add("file_host", "not_exist");
HttpEntity<?> requestEntity = new HttpEntity<>(headers);
this.restTemplate.exchange(this.url + "/weevent-broker/admin/getVersion",
HttpMethod.GET,
requestEntity,
String.class,
new HashMap<>());
Assert.fail();
} catch (HttpServerErrorException.ServiceUnavailable e) {
//503 Service Unavailable
Assert.assertTrue(true);
}
}
@Override
public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) {
if (logger.isDebugEnabled()) {
logger.debug("Executing SockJS Info request, url=" + infoUrl);
}
HttpHeaders infoRequestHeaders = new HttpHeaders();
if (headers != null) {
infoRequestHeaders.putAll(headers);
}
ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
if (response.getStatusCode() != HttpStatus.OK) {
if (logger.isErrorEnabled()) {
logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
}
throw new HttpServerErrorException(response.getStatusCode());
}
if (logger.isTraceEnabled()) {
logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
}
String result = response.getBody();
return (result != null ? result : "");
}
@Override
public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR send, url=" + url);
}
ResponseEntity<String> response = executeSendRequestInternal(url, headers, message);
if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
if (logger.isErrorEnabled()) {
logger.error("XHR send request (url=" + url + ") failed: " + response);
}
throw new HttpServerErrorException(response.getStatusCode());
}
if (logger.isTraceEnabled()) {
logger.trace("XHR send request (url=" + url + ") response: " + response);
}
}
@Test
public void connectFailure() throws Exception {
final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
RestOperations restTemplate = mock(RestOperations.class);
given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);
final CountDownLatch latch = new CountDownLatch(1);
connect(restTemplate).addCallback(
new ListenableFutureCallback<WebSocketSession>() {
@Override
public void onSuccess(WebSocketSession result) {
}
@Override
public void onFailure(Throwable ex) {
if (ex == expected) {
latch.countDown();
}
}
}
);
verifyNoMoreInteractions(this.webSocketHandler);
}
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
AuthenticationRequest request = new AuthenticationRequest();
request.setUsername(name);
request.setPassword(password);
try {
Map<String, Object> params = service.login(request);
if (params != null) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("USER"));
Authentication auth = new UsernamePasswordAuthenticationToken(
name, password, grantedAuths);
return auth;
} else {
throw new BadCredentialsException("Username not found");
}
} catch (HttpServerErrorException e) {
throw new BadCredentialsException("Login failed!");
}
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
if (!model.containsAttribute("login")) {
model.addAttribute("login", new AuthenticationRequest());
}
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
try {
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
User user = userService.getUser(currentUserName);
model.addAttribute("user", user);
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
}
return "index";
}
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
public String accounts(Model model) {
logger.debug("/accounts");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("accounts: User logged in: " + currentUserName);
try {
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving accounts: " + e.getMessage());
model.addAttribute("accountsRetrievalError",e.getMessage());
}
}
return "accounts";
}
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
logger.debug("/trade.GET");
//model.addAttribute("marketSummary", marketService.getMarketSummary());
model.addAttribute("search", new Search());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
model.addAttribute("order", new Order());
try {
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
}
return "trade";
}
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
logger.debug("/portfolio");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("portfolio: User logged in: " + currentUserName);
//TODO: add account summary.
try {
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving portfolfio: " + e.getMessage());
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("order", new Order());
}
return "portfolio";
}
/**
* Verifies JWT token validity and returns JWT token data
*
* @param token JWT token to be validated
* @return JWT token data as {@link QueryResponse}
*/
public QueryResponse query(String token) {
GatewayConfigProperties gatewayConfigProperties = gatewayClient.getGatewayConfigProperties();
String uri = String.format("%s://%s%s", gatewayConfigProperties.getScheme(),
gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayQueryEndpoint());
String cookie = String.format("%s=%s", authConfigurationProperties.getCookieProperties().getCookieName(), token);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.COOKIE, cookie);
try {
ResponseEntity<QueryResponse> response = restTemplate.exchange(
uri,
HttpMethod.GET,
new HttpEntity<>(headers),
QueryResponse.class);
return response.getBody();
} catch (HttpClientErrorException | ResourceAccessException | HttpServerErrorException e) {
responseHandler.handleBadResponse(e, ErrorType.TOKEN_NOT_VALID,
"Can not access Gateway service. Uri '{}' returned: {}", uri, e.getMessage());
}
return null;
}
/**
* This default implementation throws a {@link HttpClientErrorException} if the response status code
* is {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}, a {@link HttpServerErrorException}
* if it is {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR},
* and a {@link RestClientException} in other cases.
*/
@Override
public void handleError(ClientHttpResponse response) throws IOException {
HttpStatus statusCode = getHttpStatusCode(response);
switch (statusCode.series()) {
case CLIENT_ERROR:
throw new HttpClientErrorException(statusCode, response.getStatusText(),
response.getHeaders(), getResponseBody(response), getCharset(response));
case SERVER_ERROR:
throw new HttpServerErrorException(statusCode, response.getStatusText(),
response.getHeaders(), getResponseBody(response), getCharset(response));
default:
throw new UnknownHttpStatusCodeException(statusCode.value(), response.getStatusText(),
response.getHeaders(), getResponseBody(response), getCharset(response));
}
}
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
if (headers.getContentType() == null) {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
@SuppressWarnings("rawtypes")
Map map = new HashMap();
try {
map = restTemplate.exchange(path, HttpMethod.POST,
new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
} catch (HttpClientErrorException e1) {
logger.error("catch token exception when check token!", e1);
map.put(ERROR, e1.getStatusCode());
} catch (HttpServerErrorException e2) {
logger.error("catch no permission exception when check token!", e2);
map.put(ERROR, e2.getStatusCode());
} catch (Exception e) {
logger.error("catch common exception when check token!", e);
}
@SuppressWarnings("unchecked")
Map<String, Object> result = map;
return result;
}
@Override
@SuppressWarnings("deprecation")
public String executeInfoRequest(URI infoUrl, HttpHeaders headers) {
if (logger.isDebugEnabled()) {
logger.debug("Executing SockJS Info request, url=" + infoUrl);
}
HttpHeaders infoRequestHeaders = new HttpHeaders();
infoRequestHeaders.putAll(getRequestHeaders());
if (headers != null) {
infoRequestHeaders.putAll(headers);
}
ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
if (response.getStatusCode() != HttpStatus.OK) {
if (logger.isErrorEnabled()) {
logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
}
throw new HttpServerErrorException(response.getStatusCode());
}
if (logger.isTraceEnabled()) {
logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
}
return response.getBody();
}
@Override
public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR send, url=" + url);
}
ResponseEntity<String> response = executeSendRequestInternal(url, headers, message);
if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
if (logger.isErrorEnabled()) {
logger.error("XHR send request (url=" + url + ") failed: " + response);
}
throw new HttpServerErrorException(response.getStatusCode());
}
if (logger.isTraceEnabled()) {
logger.trace("XHR send request (url=" + url + ") response: " + response);
}
}
@Test
public void connectFailure() throws Exception {
final HttpServerErrorException expected = new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR);
RestOperations restTemplate = mock(RestOperations.class);
given(restTemplate.execute((URI) any(), eq(HttpMethod.POST), any(), any())).willThrow(expected);
final CountDownLatch latch = new CountDownLatch(1);
connect(restTemplate).addCallback(
new ListenableFutureCallback<WebSocketSession>() {
@Override
public void onSuccess(WebSocketSession result) {
}
@Override
public void onFailure(Throwable ex) {
if (ex == expected) {
latch.countDown();
}
}
}
);
verifyNoMoreInteractions(this.webSocketHandler);
}
@Test
void shouldTranslateExceptionOnTokenRenewal() {
when(this.clientAuthentication.login())
.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofMinutes(5)));
when(this.restOperations.postForObject(anyString(), any(HttpEntity.class), any()))
.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Some server error"));
AtomicReference<AuthenticationErrorEvent> listener = new AtomicReference<>();
this.sessionManager.addErrorListener(listener::set);
this.sessionManager.getSessionToken();
this.sessionManager.renewToken();
assertThat(listener.get().getException()).isInstanceOf(VaultTokenRenewalException.class)
.hasCauseInstanceOf(HttpServerErrorException.class)
.hasMessageContaining("Cannot renew token: Status 500 Some server error");
}
@Test
@SuppressWarnings("unchecked")
void shouldNotThrowExceptionsOnRevokeErrors() {
when(this.clientAuthentication.login()).thenReturn(LoginToken.of("login"));
when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any()))
.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
this.sessionManager.renewToken();
this.sessionManager.destroy();
verify(this.restOperations).postForObject(eq("auth/token/revoke-self"),
eq(new HttpEntity<>(VaultHttpHeaders.from(LoginToken.of("login")))), any(Class.class));
verify(this.listener).onAuthenticationEvent(any(AfterLoginEvent.class));
verify(this.listener).onAuthenticationEvent(any(BeforeLoginTokenRevocationEvent.class));
verifyNoMoreInteractions(this.listener);
verify(this.errorListener).onAuthenticationError(any(LoginTokenRevocationFailedEvent.class));
}
@Test
@SuppressWarnings("unchecked")
void shouldNotReScheduleTokenRenewalAfterFailedRenewal() {
when(this.clientAuthentication.login())
.thenReturn(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));
when(this.restOperations.postForObject(anyString(), any(), ArgumentMatchers.<Class>any()))
.thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
this.sessionManager.getSessionToken();
verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
runnableCaptor.getValue().run();
verify(this.taskScheduler, times(1)).schedule(any(Runnable.class), any(Trigger.class));
}
/**
* HTTPステータスコード:5xx(サーバエラー)に対応した例外をスローします。ステータスコードと例外の対応は以下のとおりです。
* @param statusCode HTTPステータス
* @param response HTTPレスポンス
* @throws IOException I/O例外
*/
protected void handleServerError(HttpStatus statusCode, ClientHttpResponse response) throws IOException {
switch (statusCode) {
case INTERNAL_SERVER_ERROR:
if (L.isDebugEnabled()) {
L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0011"),
Maps.hash("status", statusCode.toString())
.map("message", getResponseBodyAsString(response))));
}
throw new InternalServerErrorException(response.getHeaders(), getResponseBody(response), getCharset(response));
case SERVICE_UNAVAILABLE:
if (L.isDebugEnabled()) {
L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0012"),
Maps.hash("status", statusCode.toString())
.map("message", getResponseBodyAsString(response))));
}
throw new ServiceUnavailableException(response.getHeaders(), getResponseBody(response), getCharset(response));
default:
if (L.isDebugEnabled()) {
L.debug(Strings.substitute(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0013"),
Maps.hash("status", statusCode.toString())
.map("message", getResponseBodyAsString(response))));
}
throw new HttpServerErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response));
}
}
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
AuthenticationRequest request = new AuthenticationRequest();
request.setUsername(name);
request.setPassword(password);
try {
Map<String, Object> params = service.login(request);
if (params != null) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("USER"));
Authentication auth = new UsernamePasswordAuthenticationToken(
name, password, grantedAuths);
return auth;
} else {
throw new BadCredentialsException("Username not found");
}
} catch (HttpServerErrorException e) {
throw new BadCredentialsException("Login failed!");
}
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
if (!model.containsAttribute("login")) {
model.addAttribute("login", new AuthenticationRequest());
}
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("account",accountService.getAccount(currentUserName));
}
return "index";
}
/**
* Check the response result of the invocation
*
* @param response
* @return
* @throws Throwable
*/
protected InputStream checkResponse(HttpResponse response) throws Throwable {
InputStream ris = null;
if (null != response
&& null != response.getEntity()) {
int code = response.getStatusLine().getStatusCode();
// get the body input stream
ris = response.getEntity().getContent();
// check if the result of the call matches the expected one
if (code == _endpopoint.getExpected()) {
if (_debug) {
logger.info("returned status: {}",response.getStatusLine().getStatusCode());
}
} else {
if (_debug) {
String body = IOUtils.toString(ris, "UTF-8");
logger.info("unexpected status: {} \n Body: {}",response.getStatusLine().getStatusCode(),body);
}
throw new HttpServerErrorException(HttpStatus.valueOf(code), "Unexpected HTTP status returned: " + code);
}
}
return ris;
}
@RequestMapping(value = "/order", method = RequestMethod.POST)
public String buy(Model model, @ModelAttribute("order") Order order) {
model.addAttribute("search", new Search());
// buy the order after setting attributes not set by the UI.
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("/order ORDER: " + order);
order.setAccountId(currentUserName);
order.setCompletionDate(new Date());
Order result = marketService.sendOrder(order);
model.addAttribute("savedOrder", result);
model.addAttribute("order", new Order());
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
} else {
//should never get here!!!
}
return "trade";
}
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
logger.debug("/portfolio");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("portfolio: User logged in: " + currentUserName);
//TODO: add account summary.
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving portfolfio: " + e.getMessage());
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("order", new Order());
}
return "portfolio";
}
@Override
public void onBegin(Response response) {
if (response.getStatus() != 200) {
HttpStatus status = HttpStatus.valueOf(response.getStatus());
response.abort(new HttpServerErrorException(status, "Unexpected XHR receive status"));
}
}
@Test
public void connectInfoRequestFailure() throws URISyntaxException {
HttpServerErrorException exception = new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE);
given(this.infoReceiver.executeInfoRequest(any(), any())).willThrow(exception);
this.sockJsClient.doHandshake(handler, URL).addCallback(this.connectCallback);
verify(this.connectCallback).onFailure(exception);
assertFalse(this.webSocketTransport.invoked());
assertFalse(this.xhrTransport.invoked());
}
@Test(expected = HttpServerErrorException.class)
public void sendMessageError() throws Exception {
TestXhrTransport transport = new TestXhrTransport();
transport.sendMessageResponseToReturn = new ResponseEntity<>(HttpStatus.BAD_REQUEST);
URI url = new URI("https://example.com");
transport.executeSendRequest(url, new HttpHeaders(), new TextMessage("payload"));
}