下面列出了org.springframework.http.HttpStatus#SERVICE_UNAVAILABLE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
protected ResponseEntity<String> doGet(final Path filePath, String action) {
if (restClient.isConfigured()) {
final String url = createGetURL(filePath, action);
RestTemplate restTemplate = restClient.getRestTemplate();
return restTemplate.getForEntity(URI.create(url), String.class);
}
return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
}
@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());
}
private HttpStatus getHttpStatusFromErrorType(GlobalBaseException e) {
if (e.getType() == ErrorType.UNKNOWN) {
return HttpStatus.SERVICE_UNAVAILABLE;
} else if (e.getType() == ErrorType.SERVER_ERROR) {
return HttpStatus.INTERNAL_SERVER_ERROR;
} else if (e.getType() == ErrorType.NOT_FOUND) {
return HttpStatus.NOT_FOUND;
} else if (e.getType() == ErrorType.BAD_REQUEST) {
return HttpStatus.BAD_REQUEST;
} else {
return HttpStatus.NOT_IMPLEMENTED;
}
}
@GetMapping("/weather")
public ResponseEntity<String> weather() {
LOGGER.info("Providing today's weather information");
if (isServiceUnavailable()) {
return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
}
LOGGER.info("Today's a sunny day");
return new ResponseEntity<>("Today's a sunny day", HttpStatus.OK);
}
protected ResponseEntity<String> doPost(final Path filePath, WorkspaceResourceEvent actionEvent) {
if (actionEvent == null) {
throw new IllegalArgumentException("actionEvent is null");
}
if (restClient.isConfigured()) {
final String url = createPostURL(actionEvent);
RestTemplate restTemplate = restClient.getRestTemplate();
return restTemplate.postForEntity(URI.create(url), filePath != null ? filePath.toString() : null, String.class);
}
return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
}
@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());
}
@RequestMapping(value = "/health", method = RequestMethod.GET)
public ResponseEntity<String> health() {
log.trace("Health check endpoint invoked");
try {
// Using a single selection query to ensure connection to MongoDB is ok.
List<ImportJob> jobs = jobRepository.findAll(PageRequest.of(0, 10, Sort.by(Sort.Direction.ASC, "name")))
.getContent();
} catch (Exception e) {
log.error("Health check caught an exception: " + e.getMessage(), e);
return new ResponseEntity<String>(HttpStatus.SERVICE_UNAVAILABLE);
}
log.trace("Health check is OK");
return new ResponseEntity<String>(HttpStatus.OK);
}
@ExceptionHandler
public ResponseEntity<?> onReadModelNotUpToDateException(ReadModelNotUpToDateException e) {
return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.SERVICE_UNAVAILABLE;
}
@Override
public int getRawStatusCode() throws IOException {
return HttpStatus.SERVICE_UNAVAILABLE.value();
}
@Override
public String getStatusText() throws IOException {
return HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
if (cause != null && cause.getMessage() != null) {
log.error("服务:{} 异常:{}", route, cause.getMessage());
return new ByteArrayInputStream(cause.getMessage().getBytes());
} else {
log.error("服务:{} 异常:{}", route, "暂不可用, 请稍候再试");
return new ByteArrayInputStream(("service:" + route + " not available, please try again later")
.getBytes
());
}
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
@Override
public ClientHttpResponse fallbackResponse(Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() {
return HttpStatus.SERVICE_UNAVAILABLE;
}
@Override
public int getRawStatusCode() {
return HttpStatus.SERVICE_UNAVAILABLE.value();
}
@Override
public String getStatusText() {
return HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() {
if (cause != null && cause.getMessage() != null) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ByteArrayInputStream(cause.getMessage().getBytes());
} else {
log.error("调用:{} 异常:{}", getRoute(), AUTH_SERVICE_DISABLE);
return new ByteArrayInputStream(AUTH_SERVICE_DISABLE.getBytes());
}
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
@Override
public ClientHttpResponse fallbackResponse(Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() {
return HttpStatus.SERVICE_UNAVAILABLE;
}
@Override
public int getRawStatusCode() {
return HttpStatus.SERVICE_UNAVAILABLE.value();
}
@Override
public String getStatusText() {
return HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() {
if (cause != null && cause.getMessage() != null) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ByteArrayInputStream(cause.getMessage().getBytes());
} else {
log.error("调用:{} 异常:{}", getRoute(), UPMS_SERVICE_DISABLE);
return new ByteArrayInputStream(UPMS_SERVICE_DISABLE.getBytes());
}
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
};
}
@Override
public ClientHttpResponse fallbackResponse(Throwable cause) {
return new ClientHttpResponse() {
@Override
public InputStream getBody() throws IOException {
if (cause != null && cause.getMessage() != null) {
log.error("调用:{} 异常:{}", getRoute(), cause.getMessage());
return new ByteArrayInputStream(cause.getMessage().getBytes());
} else {
log.error("调用:{} 异常:{}", getRoute(), MessageConstant.SYSTEM_AUTH_NOTSUPPORT);
return new ByteArrayInputStream(
MessageConstant.SYSTEM_AUTH_NOTSUPPORT
.getBytes());
}
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.SERVICE_UNAVAILABLE;
}
@Override
public int getRawStatusCode() throws IOException {
return HttpStatus.SERVICE_UNAVAILABLE.value();
}
@Override
public String getStatusText() throws IOException {
return HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase();
}
@Override
public void close() {
}
};
}
@Test(expected = ServiceNotAccessibleException.class)
public void handleBadResponseWithServiceUnavailable() {
HttpServerErrorException exception = new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE, "Authentication service unavailable");
handler.handleBadResponse(exception, null, GENERIC_LOG_MESSAGE, LOG_PARAMETERS);
}
@ExceptionHandler(CmisUnavailableException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public ResponseBody handleCmisUnavailableException(HttpServletRequest request, CmisUnavailableException e) {
ApiResponse response = new ApiResponse(ApiResponse.CMIS_UNREACHABLE);
return handleExceptionInternal(request, e, response);
}
@RequestMapping(value = "/{userId}/lights/{lightId}/state", method = RequestMethod.PUT)
public ResponseEntity<String> stateChange(@PathVariable(value = "lightId") String lightId, @PathVariable(value = "userId") String userId, HttpServletRequest request, @RequestBody String requestString) {
/**
* strangely enough the Echo sends a content type of application/x-www-form-urlencoded even though
* it sends a json object
*/
log.info("hue state change requested: " + userId + " from " + request.getRemoteAddr());
log.info("hue stage change body: " + requestString );
DeviceState state = null;
try {
state = mapper.readValue(requestString, DeviceState.class);
} catch (IOException e) {
log.info("object mapper barfed on input", e);
return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST);
}
DeviceDescriptor device = repository.findOne(lightId);
if (device == null) {
return new ResponseEntity<>(null, null, HttpStatus.NOT_FOUND);
}
String responseString;
String url;
if (state.isOn()) {
responseString = "[{\"success\":{\"/lights/" + lightId + "/state/on\":true}}]";
url = device.getOnUrl();
} else {
responseString = "[{\"success\":{\"/lights/" + lightId + "/state/on\":false}}]";
url = device.getOffUrl();
}
//quick template
url = replaceIntensityValue(url, state.getBri());
String body = replaceIntensityValue(device.getContentBody(), state.getBri());
//make call
if(!doHttpRequest(url, device.getHttpVerb(), device.getContentType(), body)){
return new ResponseEntity<>(null, null, HttpStatus.SERVICE_UNAVAILABLE);
}
HttpHeaders headerMap = new HttpHeaders();
ResponseEntity<String> entity = new ResponseEntity<>(responseString, headerMap, HttpStatus.OK);
return entity;
}
public NotFoundException(String message, Throwable cause) {
this(HttpStatus.SERVICE_UNAVAILABLE, message, cause);
}
public static NotFoundException create(boolean with404, String message) {
HttpStatus httpStatus = with404 ? HttpStatus.NOT_FOUND
: HttpStatus.SERVICE_UNAVAILABLE;
return new NotFoundException(httpStatus, message);
}
public static NotFoundException create(boolean with404, String message,
Throwable cause) {
HttpStatus httpStatus = with404 ? HttpStatus.NOT_FOUND
: HttpStatus.SERVICE_UNAVAILABLE;
return new NotFoundException(httpStatus, message, cause);
}
/**
* コンストラクタです。
* @param responseHeaders レスポンスヘッダー情報
* @param responseBody レスポンスボディ情報
* @param responseCharset レスポンスキャラセット
*/
public ServiceUnavailableException(HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset) {
super(HttpStatus.SERVICE_UNAVAILABLE, HttpStatus.SERVICE_UNAVAILABLE.name(), responseHeaders, responseBody, responseCharset);
}