Here are the examples of the java api org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
63 Examples
19
View Source File : StatusResultMatchers.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* replacedert the response status code is {@code HttpStatus.SERVICE_UNAVAILABLE} (503).
*/
public ResultMatcher isServiceUnavailable() {
return matcher(HttpStatus.SERVICE_UNAVAILABLE);
}
19
View Source File : ResponseEntity.java
License : GNU General Public License v3.0
Project Creator : silently9527
License : GNU General Public License v3.0
Project Creator : silently9527
public static ResponseEnreplacedy failure(String message) {
ResponseEnreplacedy responseEnreplacedy = new ResponseEnreplacedy();
responseEnreplacedy.put(SUCCESSFUL_KEY, false);
responseEnreplacedy.put(RESPONSE_CODE_KEY, HttpStatus.SERVICE_UNAVAILABLE.value());
responseEnreplacedy.put(MESSAGE_KEY, message);
return responseEnreplacedy;
}
19
View Source File : CartController.java
License : Apache License 2.0
Project Creator : making
License : Apache License 2.0
Project Creator : making
@ExceptionHandler(RuntimeException.clreplaced)
Rendering handleException(RuntimeException e, Cart cart) {
return Rendering.view("shopping-cart").status(HttpStatus.SERVICE_UNAVAILABLE).modelAttribute("error", "Cart is currently unavailable. Retry later. Sorry for the inconvenience.").build();
}
19
View Source File : ChaosMonkeyRestEndpoint.java
License : Apache License 2.0
Project Creator : codecentric
License : Apache License 2.0
Project Creator : codecentric
@GetMapping("/status")
public ResponseEnreplacedy<String> getStatus() {
if (this.chaosMonkeySettings.getChaosMonkeyProperties().isEnabled()) {
return ResponseEnreplacedy.status(HttpStatus.OK).body("Ready to be evil!");
} else {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body("You switched me off!");
}
}
19
View Source File : ChannelsController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
private ResponseEnreplacedy<?> disconnect(@RequestBody @Valid DisconnectChannelRequestPayload requestPayload) {
final String channelId = requestPayload.getChannelId().toString();
final Channel channel = stores.getChannelsStore().get(channelId);
if (channel == null) {
return ResponseEnreplacedy.notFound().build();
}
if (channel.getConnectionState().equals(ChannelConnectionState.DISCONNECTED)) {
return ResponseEnreplacedy.accepted().body(new EmptyResponsePayload());
}
channel.setConnectionState(ChannelConnectionState.DISCONNECTED);
channel.setToken(null);
try {
stores.storeChannel(channel);
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
return ResponseEnreplacedy.ok(new EmptyResponsePayload());
}
18
View Source File : DefaultErrorViewResolverTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void resolveWhenSeries5xxTemplateMatchShouldReturnTemplate() {
given(this.templateAvailabilityProvider.isTemplateAvailable(eq("error/5xx"), any(Environment.clreplaced), any(ClreplacedLoader.clreplaced), any(ResourceLoader.clreplaced))).willReturn(true);
ModelAndView resolved = this.resolver.resolveErrorView(this.request, HttpStatus.SERVICE_UNAVAILABLE, this.model);
replacedertThat(resolved.getViewName()).isEqualTo("error/5xx");
}
18
View Source File : CloudFoundryAuthorizationExceptionTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void statusCodeForServiceUnavailableReasonShouldBe503() {
replacedertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
18
View Source File : GracefulShutdownWithWaitIT.java
License : Apache License 2.0
Project Creator : timpeeters
License : Apache License 2.0
Project Creator : timpeeters
@Test
public void test() throws ExecutionException, InterruptedException {
stopSpringBootApp();
Thread.sleep(2000);
replacedertThat(sendRequest("/actuator/health").get().getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
}
18
View Source File : SpringCloudCircuitBreakerResilience4JFilterFactoryTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Test
public void r4jFilterServiceUnavailable() {
testClient.get().uri("/delay/3").header("Host", "www.sccbfailure.org").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
18
View Source File : MyRESTController.java
License : Apache License 2.0
Project Creator : redhat-scholars
License : Apache License 2.0
Project Creator : redhat-scholars
@RequestMapping(method = RequestMethod.GET, value = "/alive")
public ResponseEnreplacedy<String> alive() {
if (!dead) {
return ResponseEnreplacedy.status(HttpStatus.OK).body("It's Alive! (Frankenstein)\n");
} else {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body("All dead, not mostly dead (Princess Bride)");
}
}
18
View Source File : MyRESTController.java
License : Apache License 2.0
Project Creator : redhat-scholars
License : Apache License 2.0
Project Creator : redhat-scholars
@RequestMapping(method = RequestMethod.GET, value = "/health")
public ResponseEnreplacedy<String> health() {
if (behave) {
return ResponseEnreplacedy.status(HttpStatus.OK).body("I am fine, thank you\n");
} else {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body("Bad");
}
}
18
View Source File : SurveyRestServiceImpl.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
public RestResult<Void> saveFallback(SurveyResource surveyResource, Throwable e) {
/*
* Hystrix command will time out on first request due to the time it
* takes to initialise.
*
* A solution to this will be covered under IFS-4163
*/
if (e.getClreplaced().equals(HystrixTimeoutException.clreplaced)) {
return RestResult.restSuccess();
}
return RestResult.restFailure(HttpStatus.SERVICE_UNAVAILABLE);
}
18
View Source File : WebMessageUtils.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
public static WebMessage serviceUnavailable(String message, String devMessage) {
return createWebMessage(message, devMessage, Status.ERROR, HttpStatus.SERVICE_UNAVAILABLE);
}
18
View Source File : WebMessageUtils.java
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
License : BSD 3-Clause "New" or "Revised" License
Project Creator : dhis2
public static WebMessage serviceUnavailable(String message) {
return createWebMessage(message, Status.ERROR, HttpStatus.SERVICE_UNAVAILABLE);
}
18
View Source File : ReservationClientApplication.java
License : Apache License 2.0
Project Creator : cloud-native-java
License : Apache License 2.0
Project Creator : cloud-native-java
@Bean
WebClient webClient(LoadBalancerExchangeFilterFunction eff) {
ExchangeFilterFunction fallback = (clientRequest, exchangeFunction) -> {
try {
return eff.filter(clientRequest, exchangeFunction);
} catch (Exception e) {
return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE).build());
}
};
return WebClient.builder().filter(fallback).build();
}
18
View Source File : ChannelsController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
private ResponseEnreplacedy<?> connectChannel(Channel channel, String name, String imageUrl) {
try {
List<Metadata> metadataList = new ArrayList<>();
metadataList.add(newChannelMetadata(channel.getId(), MetadataKeys.ChannelKeys.NAME, name));
if (imageUrl != null) {
metadataList.add(newChannelMetadata(channel.getId(), MetadataKeys.ChannelKeys.IMAGE_URL, imageUrl));
}
final ChannelContainer container = ChannelContainer.builder().channel(channel).metadataMap(MetadataMap.from(metadataList)).build();
stores.storeChannelContainer(container);
return ResponseEnreplacedy.ok(fromChannelContainer(container));
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
}
18
View Source File : ChannelsController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
@PostMapping("/channels.google.connect")
ResponseEnreplacedy<?> connect(@RequestBody @Valid ConnectChannelRequestPayload requestPayload) {
final String gbmId = requestPayload.getGbmId();
final String sourceIdentifier = "google";
final String channelId = UUIDv5.fromNamespaceAndName(sourceIdentifier, gbmId).toString();
try {
List<Metadata> metadataList = new ArrayList<>();
metadataList.add(newChannelMetadata(channelId, MetadataKeys.ChannelKeys.NAME, requestPayload.getName()));
if (requestPayload.getImageUrl() != null) {
metadataList.add(newChannelMetadata(channelId, MetadataKeys.ChannelKeys.IMAGE_URL, requestPayload.getImageUrl()));
}
final ChannelContainer container = ChannelContainer.builder().channel(Channel.newBuilder().setId(channelId).setConnectionState(ChannelConnectionState.CONNECTED).setSource(sourceIdentifier).setSourceChannelId(gbmId).build()).metadataMap(MetadataMap.from(metadataList)).build();
stores.storeChannelContainer(container);
return ResponseEnreplacedy.ok(fromChannelContainer(container));
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
}
18
View Source File : ChannelsController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
@PostMapping("/channels.google.disconnect")
ResponseEnreplacedy<?> disconnect(@RequestBody @Valid DisconnectChannelRequestPayload requestPayload) {
final String channelId = requestPayload.getChannelId().toString();
final Channel channel = stores.getChannelsStore().get(channelId);
if (channel == null) {
return ResponseEnreplacedy.notFound().build();
}
if (channel.getConnectionState().equals(ChannelConnectionState.DISCONNECTED)) {
return ResponseEnreplacedy.accepted().body(new EmptyResponsePayload());
}
channel.setConnectionState(ChannelConnectionState.DISCONNECTED);
channel.setToken(null);
try {
stores.storeChannel(channel);
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
return ResponseEnreplacedy.ok(new EmptyResponsePayload());
}
17
View Source File : HeapDumpWebEndpointWebIntegrationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void invokeWhenNotAvailableShouldReturnServiceUnavailableStatus() {
this.endpoint.setAvailable(false);
client.get().uri("/actuator/heapdump").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
}
17
View Source File : FeignBlockingLoadBalancerClientTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Test
void shouldRespondWithServiceUnavailableIfInstanceNotFound() throws IOException {
Request request = testRequest();
Response response = feignBlockingLoadBalancerClient.execute(request, new Request.Options());
replacedertThat(response.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
replacedertThat(response.body().toString()).isEqualTo("Load balancer does not contain an instance for the service test");
}
17
View Source File : RecommendationController.java
License : Apache License 2.0
Project Creator : redhat-scholars
License : Apache License 2.0
Project Creator : redhat-scholars
private ResponseEnreplacedy<String> doMisbehavior() {
logger.debug(String.format("Misbehaving %d", count));
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body(String.format("recommendation misbehavior from '%s'\n", HOSTNAME));
}
17
View Source File : RestClientRetryTest.java
License : MIT License
Project Creator : polysantiago
License : MIT License
Project Creator : polysantiago
@Test
public void testRetry() throws Exception {
server.expect(requestTo(defaultUrl())).andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.SERVICE_UNAVAILABLE));
server.expect(requestTo(defaultUrl())).andExpect(method(HttpMethod.GET)).andRespond(withSuccess());
fooClient.foo();
}
17
View Source File : EurekaLoadBalancingExchangeFilterFunction.java
License : Apache License 2.0
Project Creator : Netflix
License : Apache License 2.0
Project Creator : Netflix
private Mono<ClientResponse> doFailOnNoInstance(URI eurekaUri) {
return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE).body("Server pool empty for eurekaUri=" + eurekaUri).build());
}
17
View Source File : CircuitBreakerManager.java
License : Apache License 2.0
Project Creator : getheimdall
License : Apache License 2.0
Project Creator : getheimdall
public <T> T failsafe(Callable<T> callable, String url) {
CircuitBreakerHolder circuitBreakerHolder = getCircuitHolder(url, middlewareCircuits);
CircuitBreaker circuitBreaker = circuitBreakerHolder.getCircuitBreaker();
if (circuitBreaker.isOpen()) {
return Failsafe.with(circuitBreaker).withFallback(() -> {
String body = logAndCreateBody("CircuitBreaker ENABLED | URL: {0}, Exception: {1}", url, circuitBreakerHolder.getMessage());
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE.value()).header(ConstantsContext.CIRCUIT_BREAKER_ENABLED, "enabled").body(body);
}).get(callable);
}
return Failsafe.with(circuitBreaker).onFailure((ignored, throwable) -> circuitBreakerHolder.setThrowable(throwable)).get(callable);
}
17
View Source File : ServiceResponseUtil.java
License : Apache License 2.0
Project Creator : arohou
License : Apache License 2.0
Project Creator : arohou
@NonNull
public static ResponseEnreplacedy<String> interpretResult(@NonNull final ResourceAccessException exception, @NonNull final String serviceName) {
Clreplaced<? extends Throwable> rootCauseClreplaced = exception.getRootCause().getClreplaced();
String errorMessage = "Cannot validate as " + serviceName + " is not responding";
if (rootCauseClreplaced == SocketTimeoutException.clreplaced) {
errorMessage = "Timeout while communicating with " + serviceName;
} else if (rootCauseClreplaced == UnknownHostException.clreplaced) {
errorMessage = "Error while communicating with " + serviceName + " (unknown host)";
}
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body(errorMessage);
}
17
View Source File : TppErrorMessageWriter.java
License : Apache License 2.0
Project Creator : adorsys
License : Apache License 2.0
Project Creator : adorsys
public void writeServiceUnavailableError(HttpServletResponse response, String message) {
try {
log.warn("ResourceAccessException handled with message: {}", message);
response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
xs2aObjectMapper.writeValue(response.getWriter(), new ServiceUnavailableError());
} catch (IOException e) {
log.info(" Writing to the httpServletResponse failed.");
}
}
16
View Source File : HealthWebEndpointResponseMapperTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void mapDetailsWithAuthorizedUserInvokeSupplier() {
HealthWebEndpointResponseMapper mapper = createMapper(ShowDetails.WHEN_AUTHORIZED);
Supplier<Health> supplier = mockSupplier();
given(supplier.get()).willReturn(Health.down().build());
SecurityContext securityContext = mockSecurityContext("ACTUATOR");
WebEndpointResponse<Health> response = mapper.mapDetails(supplier, securityContext);
replacedertThat(response.getStatus()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
replacedertThat(response.getBody().getStatus()).isEqualTo(Status.DOWN);
verify(supplier).get();
verify(securityContext).isUserInRole("ACTUATOR");
}
16
View Source File : HealthEndpointWebIntegrationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void whenHealthIsDown503ResponseIsReturned() {
HealthIndicatorRegistry registry = context.getBean(HealthIndicatorRegistry.clreplaced);
registry.register("charlie", () -> Health.down().build());
try {
client.get().uri("/actuator/health").exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("status").isEqualTo("DOWN").jsonPath("details.alpha.status").isEqualTo("UP").jsonPath("details.bravo.status").isEqualTo("UP").jsonPath("details.charlie.status").isEqualTo("DOWN");
} finally {
registry.unregister("charlie");
}
}
16
View Source File : AbstractInstancesProxyControllerIntegrationTest.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
@Test
public void should_return_status_503_404() {
// 503 on invalid instance
client.get().uri("/instances/{instanceId}/actuator/info", "UNKNOWN").accept(ACTUATOR_V2_MEDIATYPE).exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
// 404 on non-existent endpoint
client.get().uri("/instances/{instanceId}/actuator/not-exist", instanceId).accept(ACTUATOR_V2_MEDIATYPE).exchange().expectStatus().isEqualTo(HttpStatus.NOT_FOUND);
}
16
View Source File : ResponseEntity.java
License : GNU General Public License v3.0
Project Creator : silently9527
License : GNU General Public License v3.0
Project Creator : silently9527
public static ResponseEnreplacedy failure(BindingResult result) {
ResponseEnreplacedy responseEnreplacedy = new ResponseEnreplacedy();
StringBuilder message = new StringBuilder();
final List<FieldError> fieldErrors = result.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
final String defaultMessage = fieldError.getDefaultMessage();
message.append(defaultMessage).append(";");
}
if (message.length() > 0) {
message.deleteCharAt(message.length() - 1);
}
responseEnreplacedy.put(SUCCESSFUL_KEY, false);
responseEnreplacedy.put(RESPONSE_CODE_KEY, HttpStatus.SERVICE_UNAVAILABLE.value());
responseEnreplacedy.put(MESSAGE_KEY, message);
return responseEnreplacedy;
}
16
View Source File : GlobalExceptionHandler.java
License : Mozilla Public License 2.0
Project Creator : scotiabank
License : Mozilla Public License 2.0
Project Creator : scotiabank
@ExceptionHandler(TimeoutException.clreplaced)
public ResponseEnreplacedy<ExceptionResult> resolveGenericException(TimeoutException exception) {
log.error("An error occured", exception);
String message = "Timeout has occured";
ExceptionResult result = ExceptionResult.builder().status(HttpStatus.SERVICE_UNAVAILABLE).timeStamp(ZonedDateTime.now()).message(message).build();
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body(result);
}
16
View Source File : ErrorController.java
License : Apache License 2.0
Project Creator : rodrigoserracoelho
License : Apache License 2.0
Project Creator : rodrigoserracoelho
private ResponseEnreplacedy<CapiRestException> buildResponse(HttpServletRequest request) {
String routeId = request.getHeader(Constants.ROUTE_ID_HEADER);
CapiRestException capiRestException = new CapiRestException();
String errorMessage = request.getHeader(Constants.REASON_MESSAGE_HEADER);
if (routeId != null) {
RunningApi runningApi = runningApiManager.getRunningApi(routeId);
if (runningApi.getSuspensionMessage() != null) {
errorMessage = runningApi.getSuspensionMessage();
}
runningApiManager.blockApi(routeId);
}
if (Boolean.parseBoolean(request.getHeader(Constants.ERROR_API_SHOW_TRACE_ID))) {
capiRestException.setZipkinTraceID(request.getHeader(Constants.TRACE_ID_HEADER));
}
if (Boolean.parseBoolean(request.getHeader(Constants.ERROR_API_SHOW_INTERNAL_ERROR_MESSAGE))) {
capiRestException.setInternalExceptionMessage(request.getHeader(Constants.CAPI_INTERNAL_ERROR));
capiRestException.setException(request.getHeader(Constants.CAPI_INTERNAL_ERROR_CLreplaced_NAME));
}
if (errorMessage != null) {
capiRestException.setErrorMessage(errorMessage);
} else {
capiRestException.setErrorMessage("There was an exception connecting to your api");
}
if (request.getHeader(Constants.REASON_CODE_HEADER) != null) {
int returnedCode = Integer.parseInt(request.getHeader(Constants.REASON_CODE_HEADER));
capiRestException.setErrorCode(returnedCode);
} else {
capiRestException.setErrorCode(HttpStatus.SERVICE_UNAVAILABLE.value());
}
capiRestException.setRouteID(request.getHeader(Constants.ROUTE_ID_HEADER));
return new ResponseEnreplacedy<>(capiRestException, HttpStatus.valueOf(capiRestException.getErrorCode()));
}
16
View Source File : FibonacciRestController.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
@ExceptionHandler(UnsupportedOperationException.clreplaced)
public void unsupportedException(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(), "This feature is currently unavailable");
}
16
View Source File : ObservedPositionHeadersTest.java
License : Apache License 2.0
Project Creator : luontola
License : Apache License 2.0
Project Creator : luontola
@Test
public void sends_error_503_Service_Unavailable_if_read_model_is_not_up_to_date() {
var response = restTemplate.exchange("/readModelNotUpToDate", HttpMethod.GET, new HttpEnreplacedy<>(new HttpHeaders()), String.clreplaced);
replacedertThat(response.getStatusCode(), is(HttpStatus.SERVICE_UNAVAILABLE));
}
16
View Source File : ErrorControllerAdvice.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
// 503
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@ExceptionHandler(value = { ServiceUnavailableException.clreplaced })
public ModelAndView defaultErrorHandler(HttpServletRequest req, ServiceUnavailableException e) {
LOG.debug("ErrorController defaultErrorHandler", e);
return createErrorModelAndViewWithStatusAndView(e, req, emptyList(), HttpStatus.SERVICE_UNAVAILABLE, "content/service-problems");
}
15
View Source File : HystrixFallbackHandler.java
License : GNU General Public License v3.0
Project Creator : raven-im
License : GNU General Public License v3.0
Project Creator : raven-im
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
serverRequest.attribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR).ifPresent(originalUrls -> log.error("gateway execution request:{} fail,hystrix service degrade", originalUrls));
return ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(result));
}
15
View Source File : TimeoutDeferredResultProcessingInterceptor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception {
HttpServletResponse servletResponse = request.getNativeResponse(HttpServletResponse.clreplaced);
if (!servletResponse.isCommitted()) {
servletResponse.sendError(HttpStatus.SERVICE_UNAVAILABLE.value());
}
return false;
}
15
View Source File : TimeoutCallableProcessingInterceptor.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
@Override
public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) throws Exception {
HttpServletResponse servletResponse = request.getNativeResponse(HttpServletResponse.clreplaced);
if (!servletResponse.isCommitted()) {
servletResponse.sendError(HttpStatus.SERVICE_UNAVAILABLE.value());
}
return CallableProcessingInterceptor.RESPONSE_HANDLED;
}
15
View Source File : SurveyController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@PostMapping("/{compereplacedionId}/feedback")
public String submitFeedback(HttpServletRequest request, @ModelAttribute("form") @Valid FeedbackForm feedbackForm, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("compereplacedionId") long compereplacedionId, @RequestParam(value = "type", defaultValue = "APPLICATION_SUBMISSION") String surveyType, Model model) {
Supplier<String> failureView = () -> viewFeedback(feedbackForm, bindingResult, surveyType, compereplacedionId, model);
Supplier<String> successView = () -> navigationUtils.getRedirectToLandingPageUrl(request);
SurveyResource surveyResource = getSurveyResource(feedbackForm, compereplacedionId, surveyType);
return validationHandler.failNowOrSucceedWith(failureView, () -> {
RestResult<Void> sendResult = surveyRestService.save(surveyResource);
if (sendResult.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE)) {
return serviceUnavailable();
}
return validationHandler.addAnyErrors(error(removeDuplicates(sendResult.getErrors()))).failNowOrSucceedWith(failureView, successView);
});
}
15
View Source File : PlayerControllerTest.java
License : MIT License
Project Creator : henriquels25
License : MIT License
Project Creator : henriquels25
@IntegrationTest
void shouldReturn503WhenTeamServiceIsUnavailable() {
when(playerOperations.create(diegoWithId(null))).thenReturn(Mono.error(TeamServiceUnavailableException::new));
webTestClient.post().uri("/players").bodyValue(diegoWithId(null)).exchange().expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE).expectBody().jsonPath("$.code").isEqualTo("team_api_unavailable").jsonPath("$.description").isEqualTo("Teams API is not available");
}
15
View Source File : ChaosMonkeyRequestScopeRestEndpointIntegration.java
License : Apache License 2.0
Project Creator : codecentric
License : Apache License 2.0
Project Creator : codecentric
@Test
void getStatusIsDisabled() {
chaosMonkeySettings.getChaosMonkeyProperties().setEnabled(false);
ResponseEnreplacedy<String> result = testRestTemplate.getForEnreplacedy(baseUrl + "/status", String.clreplaced);
replacedertEquals(HttpStatus.SERVICE_UNAVAILABLE, result.getStatusCode());
replacedertEquals("You switched me off!", result.getBody());
}
15
View Source File : FileController.java
License : Apache License 2.0
Project Creator : chengdedeng
License : Apache License 2.0
Project Creator : chengdedeng
@RequestMapping(value = "{first:\\w{1,3}}/{second:\\w{1,3}}/{name:.+}", method = { RequestMethod.GET })
public void download(@PathVariable String first, @PathVariable String second, @PathVariable String name, @RequestHeader(required = false) String range, HttpServletRequest request, HttpServletResponse response) {
String path = first + File.separator + second + File.separator + name;
try {
FileService.getFile(clusterProperties, path, request, response);
} catch (Exception e) {
response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
response.setHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
logger.error("download file:{}", path, e);
}
}
14
View Source File : AbstractInstancesProxyController.java
License : Apache License 2.0
Project Creator : SpringCloud
License : Apache License 2.0
Project Creator : SpringCloud
protected Mono<ClientResponse> forward(String instanceId, URI uri, HttpMethod method, HttpHeaders headers, Supplier<BodyInserter<?, ? super ClientHttpRequest>> bodyInserter) {
log.trace("Proxy-Request for instance {} with URL '{}'", instanceId, uri);
return registry.getInstance(InstanceId.of(instanceId)).flatMap(instance -> forward(instance, uri, method, headers, bodyInserter)).switchIfEmpty(Mono.fromSupplier(() -> ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE, strategies).build()));
}
14
View Source File : TaskRelocationExceptionHandler.java
License : Apache License 2.0
Project Creator : Netflix
License : Apache License 2.0
Project Creator : Netflix
@ExceptionHandler(value = { RelocationWorkflowException.clreplaced })
@Order(Ordered.HIGHEST_PRECEDENCE)
protected ResponseEnreplacedy<Object> handleRelocationWorkflowException(RelocationWorkflowException ex, WebRequest request) {
switch(ex.getErrorCode()) {
case NotReady:
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).body("Not ready yet");
case StoreError:
default:
return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
}
14
View Source File : CircuitBreakerManager.java
License : Apache License 2.0
Project Creator : getheimdall
License : Apache License 2.0
Project Creator : getheimdall
public <T> T failsafe(Callable<T> callable, Long operationId, String operationPath) {
CircuitBreakerHolder circuitBreakerHolder = getCircuitHolder(operationId, circuits);
CircuitBreaker circuitBreaker = circuitBreakerHolder.getCircuitBreaker();
if (circuitBreaker.isOpen()) {
return Failsafe.with(circuitBreaker).withFallback(() -> {
String body = logAndCreateBody("CircuitBreaker ENABLED | Operation: {0}, Exception: {1}", operationPath, circuitBreakerHolder.getMessage());
RequestContext context = RequestContext.getCurrentContext();
context.setSendZuulResponse(false);
context.setResponseStatusCode(HttpStatus.SERVICE_UNAVAILABLE.value());
context.setResponseBody(body);
context.addZuulResponseHeader(ConstantsContext.CIRCUIT_BREAKER_ENABLED, "enabled");
context.getResponse().setContentType(MediaType.APPLICATION_JSON_VALUE);
}).get(callable);
}
return Failsafe.with(circuitBreaker).onFailure((ignored, throwable) -> circuitBreakerHolder.setThrowable(throwable)).get(callable);
}
14
View Source File : WebhookController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
@PostMapping("/facebook")
ResponseEnreplacedy<Void> accept(@RequestBody String event) {
String requestId = UUID.randomUUID().toString();
try {
ProducerRecord<String, String> record = new ProducerRecord<>(sourceFacebookEvents, requestId, event);
producer.send(record).get();
return ResponseEnreplacedy.ok().build();
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
}
14
View Source File : ChannelsController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
@PostMapping("/channels.chatplugin.connect")
ResponseEnreplacedy<?> connect(@RequestBody @Valid ConnectChannelRequestPayload requestPayload) {
final String sourceChannelId = requestPayload.getName();
final String sourceIdentifier = "chatplugin";
final String channelId = UUIDv5.fromNamespaceAndName(sourceIdentifier, sourceChannelId).toString();
List<Metadata> metadataList = new ArrayList<>();
metadataList.add(newChannelMetadata(channelId, MetadataKeys.ChannelKeys.NAME, requestPayload.getName()));
if (requestPayload.getImageUrl() != null) {
metadataList.add(newChannelMetadata(channelId, MetadataKeys.ChannelKeys.IMAGE_URL, requestPayload.getImageUrl()));
}
final ChannelContainer container = ChannelContainer.builder().channel(Channel.newBuilder().setId(channelId).setConnectionState(ChannelConnectionState.CONNECTED).setSource(sourceIdentifier).setSourceChannelId(sourceChannelId).build()).metadataMap(MetadataMap.from(metadataList)).build();
try {
stores.storeChannelContainer(container);
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
return ResponseEnreplacedy.ok(fromChannelContainer(container));
}
13
View Source File : SampleWebMustacheApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void test503HtmlResource() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
HttpEnreplacedy<String> requestEnreplacedy = new HttpEnreplacedy<>(headers);
ResponseEnreplacedy<String> enreplacedy = this.restTemplate.exchange("/serviceUnavailable", HttpMethod.GET, requestEnreplacedy, String.clreplaced);
replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
replacedertThat(enreplacedy.getBody()).contains("I'm a 503");
}
13
View Source File : ChannelsController.java
License : Apache License 2.0
Project Creator : airyhq
License : Apache License 2.0
Project Creator : airyhq
@PostMapping("/channels.update")
ResponseEnreplacedy<?> updateChannel(@RequestBody @Valid UpdateChannelRequestPayload requestPayload) {
final String channelId = requestPayload.getChannelId().toString();
final ChannelContainer container = stores.getChannel(channelId);
if (container == null) {
return ResponseEnreplacedy.status(HttpStatus.NOT_FOUND).body(new EmptyResponsePayload());
}
final MetadataMap metadataMap = container.getMetadataMap();
if (requestPayload.getName() != null) {
metadataMap.put(MetadataKeys.ChannelKeys.NAME, newChannelMetadata(channelId, MetadataKeys.ChannelKeys.NAME, requestPayload.getName()));
}
if (requestPayload.getImageUrl() != null) {
metadataMap.put(MetadataKeys.ChannelKeys.IMAGE_URL, newChannelMetadata(channelId, MetadataKeys.ChannelKeys.IMAGE_URL, requestPayload.getImageUrl()));
}
try {
stores.storeMetadataMap(metadataMap);
return ResponseEnreplacedy.ok(fromChannelContainer(container));
} catch (Exception e) {
return ResponseEnreplacedy.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
}
12
View Source File : EurekaLoadBalancingExchangeFilterFunction.java
License : Apache License 2.0
Project Creator : Netflix
License : Apache License 2.0
Project Creator : Netflix
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
URI eurekaUri;
try {
eurekaUri = EurekaUris.failIfEurekaUriInvalid(request.url());
} catch (IllegalArgumentException e) {
logger.warn(e.getMessage());
logger.debug("Stack trace", e);
return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE).body(e.getMessage()).build());
}
return loadBalancer.chooseNext(eurekaUri).map(instance -> doExecute(instance, request, next)).orElseGet(() -> doFailOnNoInstance(eurekaUri));
}
See More Examples