Java 类javax.ws.rs.ServiceUnavailableException 实例源码
项目:reactive-data
文件:DefaultAsyncResponse.java
@Override
public boolean setTimeout(long time, TimeUnit unit) {
ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
es.schedule(new Runnable() {
@Override
public void run() {
if(!isDone())
{
//even if there is an exception, it will be silently ignored
resume(new ServiceUnavailableException("Timed-out"));
}
}
}, time, unit);
es.shutdown();
return true;
}
项目:microbule
文件:AbstractErrorResponseStrategyTest.java
@Test
public void testCreateException() {
assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class);
assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class);
assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class);
assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class);
assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class);
assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class);
assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class);
assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class);
assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class);
assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class);
assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class);
assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class);
assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class);
}
项目:javaone2015-cloudone
文件:SpaceObjectResource.java
@GET
@Path("events")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput events() {
final EventOutput eventOutput = new EventOutput();
if (!broadcaster.add(eventOutput)) {
// 503 -> 5s delayed client reconnect attempt.
throw new ServiceUnavailableException(5L);
}
try {
eventOutput.write(event());
} catch (final IOException ioe) {
// NO-OP.
}
return eventOutput;
}
项目:pay-publicapi
文件:AccountAuthenticator.java
@Override
public Optional<Account> authenticate(String bearerToken) throws AuthenticationException {
Response response = client.target(publicAuthUrl).request()
.header(AUTHORIZATION, "Bearer " + bearerToken)
.accept(MediaType.APPLICATION_JSON)
.get();
if (response.getStatus() == OK.getStatusCode()) {
JsonNode responseEntity = response.readEntity(JsonNode.class);
String accountId = responseEntity.get("account_id").asText();
String tokenType = Optional.ofNullable(responseEntity.get("token_type"))
.map(JsonNode::asText).orElse(CARD.toString());
TokenPaymentType tokenPaymentType = fromString(tokenType);
return Optional.of(new Account(accountId, tokenPaymentType));
} else if (response.getStatus() == UNAUTHORIZED.getStatusCode()) {
response.close();
return Optional.empty();
} else {
response.close();
logger.warn("Unexpected status code " + response.getStatus() + " from auth.");
throw new ServiceUnavailableException();
}
}
项目:bouncestorage
文件:MigrationPolicyTest.java
@Test
public void testOverwriteWhileMigrating() throws Exception {
String blobName = UtilsTest.createRandomBlobName();
int size = 10 * 1024 * 1024;
Blob oldBlob = UtilsTest.makeBlob(policy, blobName, ByteSource.wrap(new byte[size]));
Blob newBlob = UtilsTest.makeBlob(policy, blobName, ByteSource.empty());
policy.getSource().putBlob(containerName, oldBlob);
BounceService.BounceTaskStatus status = bounceService.bounce(containerName);
// sleep a little to wait for migration to start
Utils.waitUntil(() -> status.getTotalObjectCount() == 1);
assertThat(status.getMovedObjectCount()).isEqualTo(0);
assertThatThrownBy(() -> policy.putBlob(containerName, newBlob))
.isInstanceOf(ServiceUnavailableException.class);
status.future().get();
assertStatus(status, status::getMovedObjectCount).isEqualTo(1);
}
项目:sinavi-jfw
文件:ServiceUnavailableExceptionMapper.java
/**
* {@inheritDoc}
*/
@Override
public Response toResponse(final ServiceUnavailableException exception) {
if (L.isDebugEnabled()) {
L.debug(R.getString("D-REST-JERSEY-MAPPER#0011"));
}
ErrorMessage error = ErrorMessages.create(exception)
.id()
.code(ErrorCode.SERVICE_UNAVAILABLE.code())
.resolve()
.get();
L.error(error.log(), exception);
return Response.status(exception.getResponse().getStatusInfo())
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
项目:devicehive-java-server
文件:CommonHandlers.java
@HiveWebsocketAuth
@PreAuthorize("permitAll")
public void processLogin(JsonObject request, WebSocketSession session) throws IOException {
JwtRequestVO loginRequest = new JwtRequestVO();
if (request.get("login") != null) {
loginRequest.setLogin(request.get("login").getAsString());
}
if (request.get("password") != null) {
loginRequest.setPassword(request.get("password").getAsString());
}
String loginRequestStr = gson.toJson(loginRequest);
JwtTokenVO jwtToken = null;
try {
jwtToken = httpRestHelper.post(authBaseUrl + "/token", loginRequestStr, JwtTokenVO.class, null);
} catch (ServiceUnavailableException e) {
throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
}
WebSocketResponse response = new WebSocketResponse();
response.addValue("accessToken", jwtToken.getAccessToken());
response.addValue("refreshToken", jwtToken.getRefreshToken());
clientHandler.sendMessage(request, response, session);
}
项目:devicehive-java-server
文件:CommonHandlers.java
@HiveWebsocketAuth
@PreAuthorize("isAuthenticated() and hasPermission(null, 'MANAGE_TOKEN')")
public void processTokenCreate(JsonObject request, WebSocketSession session) throws IOException {
JsonObject payload = request.get(Constants.PAYLOAD).getAsJsonObject();
if (payload == null) {
logger.warn("JwtToken: payload was not found");
throw new HiveException(Messages.PAYLOAD_NOT_FOUND, SC_BAD_REQUEST);
}
hiveValidator.validate(payload);
String jwtTokenStr = (String) session.getAttributes().get(WebSocketAuthenticationManager.SESSION_ATTR_JWT_TOKEN);
JwtTokenVO jwtToken = null;
try {
jwtToken = httpRestHelper.post(authBaseUrl + "/token/create", payload.toString(), JwtTokenVO.class, jwtTokenStr);
} catch (ServiceUnavailableException e) {
throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
}
WebSocketResponse response = new WebSocketResponse();
response.addValue("accessToken", jwtToken.getAccessToken());
response.addValue("refreshToken", jwtToken.getRefreshToken());
clientHandler.sendMessage(request, response, session);
}
项目:devicehive-java-server
文件:CommonHandlers.java
@HiveWebsocketAuth
@PreAuthorize("permitAll")
public void processRefresh(JsonObject request, WebSocketSession session) throws IOException {
if (request.get("refreshToken") == null) {
logger.warn("JwtToken: payload was not found");
throw new HiveException(Messages.PAYLOAD_NOT_FOUND, SC_BAD_REQUEST);
}
JwtRefreshTokenVO refreshTokenVO = new JwtRefreshTokenVO();
refreshTokenVO.setRefreshToken(request.get("refreshToken").getAsString());
String refreshTokenStr = gson.toJson(refreshTokenVO);
JwtTokenVO jwtToken = null;
try {
jwtToken = httpRestHelper.post(authBaseUrl + "/token/refresh", refreshTokenStr, JwtTokenVO.class, null);
} catch (ServiceUnavailableException e) {
throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
}
WebSocketResponse response = new WebSocketResponse();
response.addValue("accessToken", jwtToken.getAccessToken());
clientHandler.sendMessage(request, response, session);
}
项目:rest-jersey-utils
文件:RFCExceptionMapper0Test.java
@Test
public void testToResponseServer() throws Exception {
Response r = uut.toResponse(new ServiceUnavailableException());
assertEquals(503, r.getStatus());
assertEquals(new SimpleExceptionJson("Service Unavailable", 503, "HTTP 503 Service Unavailable"),
r.getEntity());
}
项目:incubator-pulsar
文件:BaseResource.java
public PulsarAdminException getApiException(Throwable e) {
if (e instanceof ServiceUnavailableException) {
if (e.getCause() instanceof java.net.ConnectException) {
return new ConnectException(e.getCause());
} else {
return new HttpErrorException(e);
}
} else if (e instanceof WebApplicationException) {
// Handle 5xx exceptions
if (e instanceof ServerErrorException) {
ServerErrorException see = (ServerErrorException) e;
return new ServerSideErrorException(see);
}
// Handle 4xx exceptions
ClientErrorException cee = (ClientErrorException) e;
int statusCode = cee.getResponse().getStatus();
switch (statusCode) {
case 401:
case 403:
return new NotAuthorizedException(cee);
case 404:
return new NotFoundException(cee);
case 405:
return new NotAllowedException(cee);
case 409:
return new ConflictException(cee);
case 412:
return new PreconditionFailedException(cee);
default:
return new PulsarAdminException(cee);
}
} else {
return new PulsarAdminException(e);
}
}
项目:reactive-data
文件:AsyncEventReceiverBean.java
/**
* Check if the message processing is done
* @param id
* @return
*/
synchronized int getResponseCode(String id)
{
if(hzService.contains(id, WebbitRestServerBean.ASYNC_REST_EVENT_RESPONSE_MAP))
{
String resp = (String) hzService.get(id, WebbitRestServerBean.ASYNC_REST_EVENT_RESPONSE_MAP);
if(resp != null)
{
if(resp.contains(WebbitRestServerBean.ASYNC_REST_RESPONSE_PROCESS_ERR))
{
if(resp.contains(ServiceUnavailableException.class.getName()))
{
return HttpResponseStatus.SERVICE_UNAVAILABLE.getCode();
}
else
{
return HttpResponseStatus.INTERNAL_SERVER_ERROR.getCode();
}
}
else
{
return HttpResponseStatus.OK.getCode();
}
}
}
if(hzService.contains(id, WebbitRestServerBean.ASYNC_REST_EVENT_MAP))
{
return HttpResponseStatus.NO_CONTENT.getCode();//response not yet ready
}
return HttpResponseStatus.NOT_FOUND.getCode();
}
项目:microbule
文件:CircuitBreakerFilterTest.java
@Test(expected = ServiceUnavailableException.class)
public void testOpeningCircuitBreaker() {
final HelloService proxy = createProxy();
for (int i = 0; i < 20; ++i) {
try {
proxy.sayHello("Dr. Evil");
} catch (InternalServerErrorException e) {
// Ignore!
}
}
proxy.sayHello("Microbule");
}
项目:r360-java
文件:GeocodingRequest.java
/**
* Private method to help validate and parse a request response.
*
* @param response object to be validated
* @param parser the parser that is executed if no errors occurred
* @param <T> the return type of the response, e.g. {@link AuthenticationResponse} or {@link GeocodingResponse}
* @return interpreted/parsed response of type T
* @throws Route360ClientException when an unexpected error occurs during request
*/
private <T> T validateResponse(final Response response, final Function<String,T> parser) throws Route360ClientException {
// compare the HTTP status codes, NOT the route 360 code
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
// parse the results
String jsonString = response.readEntity(String.class);
return parser.apply(jsonString);
} else if(response.getStatus() == Response.Status.SERVICE_UNAVAILABLE.getStatusCode() )
throw new ServiceUnavailableException(); // Some clients (e.g. jBoss) return SERVICE_UNAVAILABLE while others will wait
else
throw new Route360ClientException("Request failed with response: \n" + response.readEntity(String.class));
}
项目:pipeline
文件:EventResource.java
@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput fetch(
@HeaderParam(SseFeature.LAST_EVENT_ID_HEADER) String lastEventId) {
if (!Strings.isNullOrEmpty(lastEventId)) {
LOGGER.debug("Found Last-Event-ID header: {}", lastEventId);
}
final EventOutput output = new EventOutput();
if (!broadcaster.add(output)) {
throw new ServiceUnavailableException(RETRY_AFTER.toSeconds());
}
return output;
}
项目:blaze-storage
文件:ResponseObjectInvocation.java
private static <T> T handleErrorStatus(Response response) {
final int status = response.getStatus();
switch (status) {
case 400:
throw new BadRequestException(response);
case 401:
throw new NotAuthorizedException(response);
case 404:
throw new NotFoundException(response);
case 405:
throw new NotAllowedException(response);
case 406:
throw new NotAcceptableException(response);
case 415:
throw new NotSupportedException(response);
case 500:
throw new InternalServerErrorException(response);
case 503:
throw new ServiceUnavailableException(response);
default:
break;
}
if (status >= 400 && status < 500){
throw new ClientErrorException(response);
} else if (status >= 500) {
throw new ServerErrorException(response);
}
throw new WebApplicationException(response);
}
项目:gondola
文件:DemoResources.java
@PUT
public void putEntry(String value, @PathParam("key") String key) {
try {
service.putValue(key, value);
} catch (DemoService.NotLeaderException e) {
throw new ServiceUnavailableException();
} catch (Throwable t) {
logger.error("Server Error", t);
throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, t);
}
}
项目:dropwizard-raml-view
文件:ApiResource.java
@GET
@Produces(MediaType.TEXT_HTML)
public ApiView get() {
try {
return new ApiView(RamlModel.create(specificationFile, configuration));
} catch (RamlValidationException e) {
LOGGER.error("RAML specification is invalid.", e);
throw new ServiceUnavailableException("RAML specification has errors. See log for details.");
}
}
项目:bouncestorage
文件:ReconcileLockerTest.java
@Test
public void testReadWrite() {
ReconcileLocker.LockKey lock1 = reconcileLocker.lockObject("container", "key", false);
assertThatThrownBy(() -> reconcileLocker.lockObject("container", "key", true))
.isInstanceOf(ServiceUnavailableException.class);
lock1.close();
assertThat(reconcileLocker.size()).isEqualTo(0);
}
项目:bouncestorage
文件:ReconcileLockerTest.java
@Test
public void testWriteRead() {
ReconcileLocker.LockKey lock1 = reconcileLocker.lockObject("container", "key", true);
assertThatThrownBy(() -> reconcileLocker.lockObject("container", "key", false))
.isInstanceOf(ServiceUnavailableException.class);
lock1.close();
assertThat(reconcileLocker.size()).isEqualTo(0);
}
项目:bouncestorage
文件:ReconcileLockerTest.java
@Test
public void testWriteWrite() {
ReconcileLocker.LockKey lock1 = reconcileLocker.lockObject("container", "key", true);
assertThatThrownBy(() -> reconcileLocker.lockObject("container", "key", true))
.isInstanceOf(ServiceUnavailableException.class);
lock1.close();
assertThat(reconcileLocker.size()).isEqualTo(0);
}
项目:anythingworks
文件:JaxrsExceptionTranslator.java
@NotNull @Override
public Exception translate(@NotNull Throwable t) throws WebApplicationException {
/*
* Impl notes:
*
* If we get here then it means that an exception was thrown in internal code.
*
* The user's web service input data was accepted already. Therefore we can't blame him anymore.
* Some of these exceptions are likely caused by the input parameters.
*
* Either the params should not have been accepted in the first place, or
* the combination hit a scenario on the server for which it was not prepared.
* Both cases need fixing.
*
*
*/
String message = exceptionMessageMaker.make(t);
if (t instanceof IllegalArgumentException
|| t instanceof NullPointerException
|| t instanceof IllegalStateException
|| t instanceof UnsupportedOperationException
|| t instanceof AssertionError) {
throw new InternalServerErrorException(message, t);
} else if (t instanceof OutOfMemoryError) {
throw new ServiceUnavailableException(message, 120L);
} else {//includes RuntimeException, Exception, Error, Throwable:
throw new InternalServerErrorException(message, t);
}
}
项目:OsuCelebrity
文件:TwitchApiImpl.java
/**
* Performs a call and rewraps JAX-RS IOExceptions into {@link ServiceUnavailableException}.
* @throws WebApplicationException all IOExceptions are wrapped in
*/
public static <T> T rewrapIoExceptions(Supplier<T> call) throws WebApplicationException {
try {
return call.get();
} catch (ProcessingException e) {
Throwable cause = e.getCause();
if (cause == null) {
throw e;
}
if (!(cause instanceof IOException)) {
throw e;
}
throw new ServiceUnavailableException(e.getMessage());
}
}
项目:whois
文件:WhoisRestServiceTestIntegration.java
@Test(expected = ServiceUnavailableException.class)
public void maintenance_mode_readonly_update() {
maintenanceMode.set("READONLY,READONLY");
RestTest.target(getPort(), "whois/test/person/PP1-TEST")
.request(MediaType.APPLICATION_XML)
.put(Entity.entity(map(PAULETH_PALTHEN), MediaType.APPLICATION_XML), String.class);
}
项目:whois
文件:WhoisRestServiceTestIntegration.java
@Test(expected = ServiceUnavailableException.class)
public void maintenance_mode_none_update() {
maintenanceMode.set("NONE,NONE");
RestTest.target(getPort(), "whois/test/person/PP1-TEST")
.request(MediaType.APPLICATION_XML)
.put(Entity.entity(map(PAULETH_PALTHEN), MediaType.APPLICATION_XML), String.class);
}
项目:devicehive-java-server
文件:PluginResourceImpl.java
@Override
public void register(PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization,
@Suspended final AsyncResponse asyncResponse) {
hiveValidator.validate(pluginUpdate);
try {
HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
pluginRegisterService.register(principal.getUser().getId(), pluginReqisterQuery, pluginUpdate, authorization)
.thenAccept(asyncResponse::resume
);
} catch (ServiceUnavailableException e) {
logger.warn(HEALTH_CHECK_FAILED);
asyncResponse.resume(ResponseFactory.response(BAD_REQUEST,
new ErrorResponse(BAD_REQUEST.getStatusCode(), HEALTH_CHECK_FAILED)));
}
}
项目:devicehive-java-server
文件:PluginRegisterService.java
private JwtTokenVO createPluginTokens(String topicName, String authorization) {
JwtPluginPayload jwtPluginPayload = new JwtPluginPayload(Collections.singleton(MANAGE_PLUGIN.getId()), topicName, null, null);
JwtTokenVO jwtToken = null;
try {
jwtToken = httpRestHelper.post(authBaseUrl + "/token/plugin/create", gson.toJson(jwtPluginPayload), JwtTokenVO.class, authorization);
} catch (ServiceUnavailableException e) {
logger.warn("Service is not available");
throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
}
return jwtToken;
}
项目:core-command-client
文件:CmdClientTest.java
@Test(expected = ServiceUnavailableException.class)
public void testGet() {
client.get(id, commandId);
}
项目:core-command-client
文件:CmdClientTest.java
@Test(expected = ServiceUnavailableException.class)
public void testPut() {
client.put(id, commandId, "{\"temp\":72}");
}
项目:com-liferay-apio-architect
文件:ServiceUnavailableExceptionConverter.java
@Override
public APIError convert(ServiceUnavailableException exception) {
return super.convert(exception);
}
项目:Peking-University-Open-Research-Data-Platform
文件:Access.java
@Path("datafile/{fileId}/metadata")
@GET
@Produces({"text/xml"})
public String tabularDatafileMetadata(@PathParam("fileId") Long fileId, @QueryParam("exclude") String exclude, @QueryParam("include") String include, @Context HttpHeaders header, @Context HttpServletResponse response) throws NotFoundException, ServiceUnavailableException /*, PermissionDeniedException, AuthorizationRequiredException*/ {
return tabularDatafileMetadataDDI(fileId, exclude, include, header, response);
}
项目:Peking-University-Open-Research-Data-Platform
文件:Access.java
@Path("datafile/{fileId}/metadata/ddi")
@GET
@Produces({"text/xml"})
public String tabularDatafileMetadataDDI(@PathParam("fileId") Long fileId, @QueryParam("exclude") String exclude, @QueryParam("include") String include, @Context HttpHeaders header, @Context HttpServletResponse response) throws NotFoundException, ServiceUnavailableException /*, PermissionDeniedException, AuthorizationRequiredException*/ {
String retValue = "";
DataFile dataFile = null;
//httpHeaders.add("Content-disposition", "attachment; filename=\"dataverse_files.zip\"");
//httpHeaders.add("Content-Type", "application/zip; name=\"dataverse_files.zip\"");
response.setHeader("Content-disposition", "attachment; filename=\"dataverse_files.zip\"");
dataFile = dataFileService.find(fileId);
if (dataFile == null) {
throw new NotFoundException();
}
String fileName = dataFile.getFileMetadata().getLabel().replaceAll("\\.tab$", "-ddi.xml");
response.setHeader("Content-disposition", "attachment; filename=\""+fileName+"\"");
response.setHeader("Content-Type", "application/xml; name=\""+fileName+"\"");
ByteArrayOutputStream outStream = null;
outStream = new ByteArrayOutputStream();
try {
ddiExportService.exportDataFile(
fileId,
outStream,
exclude,
include);
retValue = outStream.toString();
} catch (Exception e) {
// For whatever reason we've failed to generate a partial
// metadata record requested.
// We return Service Unavailable.
throw new ServiceUnavailableException();
}
response.setHeader("Access-Control-Allow-Origin", "*");
return retValue;
}
项目:Peking-University-Open-Research-Data-Platform
文件:Meta.java
@Path("datafile/{fileId}")
@GET
@Produces({"text/xml"})
public String datafile(@PathParam("fileId") Long fileId, @QueryParam("exclude") String exclude, @QueryParam("include") String include, @Context HttpHeaders header, @Context HttpServletResponse response) throws NotFoundException, ServiceUnavailableException /*, PermissionDeniedException, AuthorizationRequiredException*/ {
String retValue = "";
DataFile dataFile = null;
//httpHeaders.add("Content-disposition", "attachment; filename=\"dataverse_files.zip\"");
//httpHeaders.add("Content-Type", "application/zip; name=\"dataverse_files.zip\"");
response.setHeader("Content-disposition", "attachment; filename=\"dataverse_files.zip\"");
dataFile = datafileService.find(fileId);
if (dataFile == null) {
throw new NotFoundException();
}
String fileName = dataFile.getFileMetadata().getLabel().replaceAll("\\.tab$", "-ddi.xml");
response.setHeader("Content-disposition", "attachment; filename=\""+fileName+"\"");
response.setHeader("Content-Type", "application/xml; name=\""+fileName+"\"");
ByteArrayOutputStream outStream = null;
outStream = new ByteArrayOutputStream();
try {
ddiExportService.exportDataFile(
fileId,
outStream,
exclude,
include);
retValue = outStream.toString();
} catch (Exception e) {
// For whatever reason we've failed to generate a partial
// metadata record requested.
// We return Service Unavailable.
throw new ServiceUnavailableException();
}
response.setHeader("Access-Control-Allow-Origin", "*");
return retValue;
}
项目:robozonky
文件:TokenBasedAccess.java
private ZonkyApiToken getToken() {
return tokenSupplier.get()
.orElseThrow(() -> new ServiceUnavailableException("No API token available, authentication failed."));
}
项目:dmaap-framework
文件:DMaaPWebExceptionMapper.java
@Override
public Response toResponse(WebApplicationException ex) {
LOGGER.info("Reached WebException Mapper");
/**
* Resource Not Found
*/
if(ex instanceof NotFoundException)
{
errRes = new ErrorResponse(HttpStatus.SC_NOT_FOUND,DMaaPResponseCode.RESOURCE_NOT_FOUND.getResponseCode(),msgs.getNotFound());
LOGGER.info(errRes.toString());
return Response.status(errRes.getHttpStatusCode()).entity(errRes).type(MediaType.APPLICATION_JSON)
.build();
}
if(ex instanceof InternalServerErrorException)
{
errRes = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(),msgs.getServerUnav());
LOGGER.info(errRes.toString());
return Response.status(errRes.getHttpStatusCode()).entity(errRes).type(MediaType.APPLICATION_JSON)
.build();
}
if(ex instanceof NotAuthorizedException)
{
errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED,DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(),msgs.getAuthFailure());
LOGGER.info(errRes.toString());
return Response.status(errRes.getHttpStatusCode()).entity(errRes).type(MediaType.APPLICATION_JSON)
.build();
}
if(ex instanceof BadRequestException)
{
errRes = new ErrorResponse(HttpStatus.SC_BAD_REQUEST,DMaaPResponseCode.INCORRECT_JSON.getResponseCode(),msgs.getBadRequest());
LOGGER.info(errRes.toString());
return Response.status(errRes.getHttpStatusCode()).entity(errRes).type(MediaType.APPLICATION_JSON)
.build();
}
if(ex instanceof NotAllowedException)
{
errRes = new ErrorResponse(HttpStatus.SC_METHOD_NOT_ALLOWED,DMaaPResponseCode.METHOD_NOT_ALLOWED.getResponseCode(),msgs.getMethodNotAllowed());
LOGGER.info(errRes.toString());
return Response.status(errRes.getHttpStatusCode()).entity(errRes).type(MediaType.APPLICATION_JSON)
.build();
}
if(ex instanceof ServiceUnavailableException)
{
errRes = new ErrorResponse(HttpStatus.SC_SERVICE_UNAVAILABLE,DMaaPResponseCode.SERVER_UNAVAILABLE.getResponseCode(),msgs.getServerUnav());
LOGGER.info(errRes.toString());
return Response.status(errRes.getHttpStatusCode()).entity(errRes).type(MediaType.APPLICATION_JSON)
.build();
}
return Response.serverError().build();
}
项目:r360-java
文件:GeocodingRequestTest.java
@Test(expected = ServiceUnavailableException.class)
public void testServiceUnavailableResponse() throws Route360ClientException {
when(sampleResponse.getStatus()).thenReturn(Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
new GeocodingRequest(mockClient).get(batch2[0]);
}
项目:pay-publicapi
文件:AccountAuthenticatorTest.java
@Test(expected = ServiceUnavailableException.class)
public void shouldThrow_ifUnknownResponse() throws AuthenticationException {
when(mockResponse.getStatus()).thenReturn(NOT_FOUND.getStatusCode());
accountAuthenticator.authenticate(bearerToken);
}
项目:digdag
文件:ServerGracefulShutdownIT.java
@Test
public void gracefulShutdown()
throws Exception
{
Id attemptId = startSleepTask();
server.terminateProcess();
Instant terminateStartedAt = Instant.now();
// server started termination but it should be alive at most 5 seconds.
int aliveCount = 0;
while (true) {
Instant loopStartedAt = Instant.now();
if (loopStartedAt.isAfter(terminateStartedAt.plus(Duration.ofMinutes(10)))) {
throw new IllegalStateException("Server didn't shutdown within 10 minutes");
}
try {
client.getSessionAttempt(attemptId);
aliveCount++;
}
catch (Exception ex) {
// if REST API fails, the cause should be 503 Service Unavailable or
// connection refused.
if (ex instanceof ProcessingException) {
assertThat(ex.getCause(), instanceOf(ConnectException.class));
break;
}
else {
assertThat(ex, instanceOf(ServiceUnavailableException.class));
break;
}
}
// sleep for 1 second
long sleepMillis = Duration.between(Instant.now(), loopStartedAt.plusSeconds(1)).toMillis();
if (sleepMillis > 0) {
Thread.sleep(sleepMillis);
}
}
// all running tasks should be done
assertThat(Files.exists(root().resolve("done.out")), is(true));
// but waiting tasks should not start
assertThat(Files.exists(root().resolve("after_sleep.out")), is(false));
// REST API should be alive for a while
assertThat(aliveCount, greaterThan(3));
assertThat(server.outUtf8(), containsString("Waiting for completion of 2 running tasks..."));
assertThat(server.outUtf8(), containsString("Closing HTTP listening sockets"));
TestUtils.expect(Duration.ofMinutes(5), () -> !server.isProcessAlive());
assertThat(server.outUtf8(), containsString("Shutting down HTTP worker threads"));
assertThat(server.outUtf8(), containsString("Shutting down system"));
assertThat(server.outUtf8(), containsString("Shutdown completed"));
}
项目:dropwizard-raml-view
文件:ApiResource.java
@Path("/raw")
@Produces("text/plain")
public String getRaw(){
throw new ServiceUnavailableException("This resource is currently not available due to pending work on the RAML Parser third party library.");
}
项目:bouncestorage
文件:MigrationPolicy.java
@Override
public BounceResult reconcileObject(String container, BounceStorageMetadata sourceObject, StorageMetadata
destinationObject) {
if ((sourceObject == null) && (destinationObject == null)) {
throw new AssertionError("At least one of source or destination objects must be non-null");
}
String blobName = sourceObject == null ? destinationObject.getName() : sourceObject.getName();
logger.debug("reconciling {}", blobName);
if (sourceObject.getRegions().equals(DESTINATION)) {
return BounceResult.NO_OP;
}
try (ReconcileLocker.LockKey ignored = reconcileLocker.lockObject(container, blobName, true)) {
if (sourceObject.getRegions().equals(SOURCE)) {
return moveObject(container, sourceObject);
}
BlobMetadata sourceMeta = getSource().blobMetadata(container, blobName);
BlobMetadata destinationMeta = getDestination().blobMetadata(container, blobName);
if (sourceMeta == null && destinationMeta != null) {
return BounceResult.NO_OP;
} else if (sourceMeta != null && destinationMeta == null) {
return moveObject(container, sourceMeta);
} else {
if (!sourceMeta.getSize().equals(destinationMeta.getSize()) ||
sourceMeta.getLastModified().compareTo(destinationMeta.getLastModified()) > 0) {
logger.warn("Different objects with the same name: {}", sourceMeta.getName());
return BounceResult.NO_OP;
} else {
getSource().removeBlob(container, sourceMeta.getName());
return BounceResult.REMOVE;
}
}
} catch (ServiceUnavailableException e) {
// not able to lock key, another PUT is in operation, so we can just skip
// this. note that we should not delete the object from source store,
// because the PUT may fail
return BounceResult.NO_OP;
}
}