下面列出了怎么用javax.ws.rs.ServerErrorException的API类实例代码及写法,或者点击链接到github查看源代码。
public PulsarAdminException getApiException(Response response) {
if (response.getStatusInfo().equals(Response.Status.OK)) {
return null;
}
try {
if (response.getStatus() >= 500) {
throw new ServerErrorException(response);
} else if (response.getStatus() >= 400) {
throw new ClientErrorException(response);
} else {
throw new WebApplicationException(response);
}
} catch (Exception e) {
return getApiException(e);
}
}
@GET
@Produces( {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@ApiOperation(value = "Get all CSARs", response = CsarListDTO.class)
public Response getCsars() {
logger.debug("Invoking getCsars");
try {
final CsarListDTO list = new CsarListDTO();
for (final Csar csarContent : this.storage.findAll()) {
final String id = csarContent.id().csarName();
final CsarDTO csar = new CsarDTO();
csar.setId(id);
csar.setDescription(csarContent.description());
csar.add(Link.fromUri(this.uriInfo.getBaseUriBuilder().path(CsarController.class)
.path(CsarController.class, "getCsar").build(id))
.rel("self").build());
list.add(csar);
}
list.add(Link.fromResource(CsarController.class).rel("self").baseUri(this.uriInfo.getBaseUri()).build());
return Response.ok(list).build();
} catch (Exception e) {
logger.warn("Exception when fetching all CSARs:", e);
throw new ServerErrorException(Response.serverError().build());
}
}
/**
* {@inheritDoc}
*/
@Override
public Response toResponse(final ServerErrorException exception) {
if (L.isDebugEnabled()) {
L.debug(Strings.substitute(R.getString("D-REST-JERSEY-MAPPER#0010"), Maps.hash("statusCode", exception.getResponse().getStatus())));
}
ErrorMessage error = ErrorMessages.create(exception)
.id()
.code(ErrorCode.get(exception.getResponse().getStatus()).code())
.resolve()
.get();
L.error(error.log(), exception);
return Response.status(exception.getResponse().getStatusInfo())
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
public static Class<?> getWebApplicationExceptionClass(Response exResponse,
Class<?> defaultExceptionType) {
int status = exResponse.getStatus();
Class<?> cls = EXCEPTIONS_MAP.get(status);
if (cls == null) {
int family = status / 100;
if (family == 3) {
cls = RedirectionException.class;
} else if (family == 4) {
cls = ClientErrorException.class;
} else if (family == 5) {
cls = ServerErrorException.class;
}
}
return cls == null ? defaultExceptionType : cls;
}
public PulsarAdminException getApiException(Throwable e) {
if (e instanceof PulsarAdminException) {
return (PulsarAdminException) e;
} else if (e instanceof ServiceUnavailableException) {
if (e.getCause() instanceof java.net.ConnectException) {
return new ConnectException(e.getCause());
} else {
return new PulsarAdminException((ServerErrorException) e);
}
} else if (e instanceof WebApplicationException) {
// Handle 5xx exceptions
if (e instanceof ServerErrorException) {
ServerErrorException see = (ServerErrorException) e;
return new ServerSideErrorException(see, e.getMessage());
} else if (e instanceof ClientErrorException) {
// 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((WebApplicationException) e);
}
} else {
return new PulsarAdminException(e);
}
}
@GET
@Path("/api/logs/{attempt_id}/upload_handle")
public DirectUploadHandle getFileHandles(
@PathParam("attempt_id") long attemptId,
@QueryParam("task") String taskName,
@QueryParam("file_time") long unixFileTime,
@QueryParam("node_id") String nodeId)
throws ResourceNotFoundException
{
return tm.begin(() -> {
// TODO null check taskName
// TODO null check nodeId
LogFilePrefix prefix = getPrefix(attemptId);
Optional<DirectUploadHandle> handle = logServer.getDirectUploadHandle(prefix, taskName, Instant.ofEpochSecond(unixFileTime), nodeId);
if (handle.isPresent()) {
return handle.get();
}
else {
throw new ServerErrorException(
Response.status(Response.Status.NOT_IMPLEMENTED)
.type("application/json")
.entity("{\"message\":\"Direct upload handle is not available for this log server implementation\",\"status\":501}")
.build());
}
}, ResourceNotFoundException.class);
}
@Test
public void testServerWebApplicationException() throws Exception {
WebClient wc = WebClient.create("http://localhost:" + PORT + "/bookstore/webappexception");
wc.accept("application/xml");
try {
wc.get(Book.class);
fail("Exception expected");
} catch (ServerErrorException ex) {
assertEquals(500, ex.getResponse().getStatus());
assertEquals("This is a WebApplicationException", ex.getResponse().readEntity(String.class));
}
}
@Test
public void testServerWebApplicationExceptionWithProxy() throws Exception {
BookStore store = JAXRSClientFactory.create("http://localhost:" + PORT, BookStore.class);
try {
store.throwException();
fail("Exception expected");
} catch (ServerErrorException ex) {
assertEquals(500, ex.getResponse().getStatus());
assertEquals("This is a WebApplicationException", ex.getResponse().readEntity(String.class));
}
}
@Test
public void testGetBookWithServerWebApplicationExceptionAndReaderInterceptor() throws Exception {
BookStore client = JAXRSClientFactory
.create("http://localhost:" + PORT, BookStore.class, Collections.singletonList(getReaderInterceptor()));
try {
client.throwException();
fail("Exception expected");
} catch (ServerErrorException ex) {
assertEquals(500, ex.getResponse().getStatus());
assertEquals("This is a WebApplicationException", ex.getResponse().readEntity(String.class));
}
}
public static WebApplicationException toHttpException(Throwable cause, Response response) {
if (response == null) {
throw new WebApplicationException(cause);
}
throw response.getStatus() >= 500 ? new ServerErrorException(response, cause)
: new ClientErrorException(response, cause);
}
/**
* Returns error from unimplemented delete method by trying to call the delete organization endpoint
*/
@Test
public void noOrgDelete() throws IOException {
try {
// attempt to delete default organization
clientSetup.getRestClient().management().orgs().org( clientSetup.getOrganizationName() ).delete();
fail( "Delete is not implemented yet" );
} catch( ServerErrorException see ){
assertEquals( Response.Status.NOT_IMPLEMENTED.getStatusCode(), see.getResponse().getStatus());
}
}
@Test
public void testImpersonationDisabled() {
String impersonatedUserId = adminClient.realm(TEST).users().search("[email protected]", 0, 1).get(0).getId();
try {
log.debug("--Expected javax.ws.rs.WebApplicationException--");
adminClient.realms().realm("test").users().get(impersonatedUserId).impersonate();
} catch (ServerErrorException e) {
assertEquals(Response.Status.NOT_IMPLEMENTED.getStatusCode(), e.getResponse().getStatus());
return;
}
fail("Feature impersonation should be disabled.");
}
/**
* Searches for a suitable {@link javax.mvc.engine.ViewEngine} to process the view. If no engine
* is found, is forwards the request back to the servlet container.
*/
@Override
public void writeTo(Viewable viewable, Class<?> aClass, Type type, Annotation[] annotations, MediaType resolvedMediaType,
MultivaluedMap<String, Object> headers, OutputStream out)
throws IOException, WebApplicationException {
// Find engine for this Viewable
final ViewEngine engine = engineFinder.find(viewable);
if (engine == null) {
throw new ServerErrorException(messages.get("NoViewEngine", viewable), INTERNAL_SERVER_ERROR);
}
// build the full media type (including the charset) and make sure the response header is set correctly
MediaType mediaType = buildMediaTypeWithCharset(resolvedMediaType);
headers.putSingle(HttpHeaders.CONTENT_TYPE, mediaType);
HttpServletRequest request = unwrapOriginalRequest(injectedRequest);
HttpServletResponse response = unwrapOriginalResponse(injectedResponse);
// Create wrapper for response
final ServletOutputStream responseStream = new DelegatingServletOutputStream(out);
final HttpServletResponse responseWrapper = new MvcHttpServletResponse(response, responseStream, mediaType, headers);
// Pass request to view engine
try {
// If no models in viewable, inject via CDI
Models models = viewable.getModels();
if (models == null) {
models = modelsInstance.get();
}
// Bind EL 'mvc' object in models
models.put("mvc", mvc);
// Execute the view engine
eventDispatcher.fireBeforeProcessViewEvent(engine, viewable);
try {
// Process view using selected engine
engine.processView(new ViewEngineContextImpl(viewable.getView(), models, request, responseWrapper,
headers, responseStream, mediaType, uriInfo, resourceInfo, config, mvc.getLocale()));
} finally {
eventDispatcher.fireAfterProcessViewEvent(engine, viewable);
}
} catch (ViewEngineException e) {
throw new ServerErrorException(INTERNAL_SERVER_ERROR, e);
} finally {
responseWrapper.getWriter().flush();
}
}
public final static ServerErrorException serverError(Response.Status status, String code, Throwable t) {
String message = t != null ? t.getMessage() : null;
return serverError(status, code, message, t);
}
public final static ServerErrorException serverError(Response.Status status, String code, String message) {
return serverError(status, code, message, null);
}
public final static ServerErrorException serverError(Response.Status status, String code, String message, Throwable t) {
return new ServerErrorException(Response.status(status)
.type(MediaType.APPLICATION_JSON)
.entity(new ServerError(code, message)).build(), t);
}
@Test
void unavailable() {
final Instant now = Instant.now();
setClock(Clock.fixed(now, Defaults.ZONE_ID));
final Runnable r = mock(Runnable.class);
doThrow(new ClientErrorException(Response.Status.TOO_MANY_REQUESTS)).when(r)
.run();
final PowerTenant t = new TenantBuilder()
.withApi(new ApiProvider(null))
.withSecrets(SecretProvider.inMemory("[email protected]"))
.build(false);
final Skippable s = new Skippable(r, t);
logger.debug("First run.");
s.run();
verify(r, times(1)).run();
assertThat(t.getAvailability()
.isAvailable()).isFalse();
// move one second, make sure it checks again
final int mandatoryDelay = 60;
setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 1)), Defaults.ZONE_ID));
logger.debug("Second run.");
doThrow(ServerErrorException.class).when(r)
.run();
s.run();
verify(r, times(2)).run();
assertThat(t.getAvailability()
.isAvailable()).isFalse();
// but it failed again, exponential backoff in effect
setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 2)), Defaults.ZONE_ID));
logger.debug("Third run.");
doThrow(ResponseProcessingException.class).when(r)
.run();
s.run();
verify(r, times(3)).run();
assertThat(t.getAvailability()
.isAvailable()).isFalse();
setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 3)), Defaults.ZONE_ID));
logger.debug("Fourth run.");
doNothing().when(r)
.run();
s.run();
verify(r, times(3)).run(); // not run as we're in the exponential backoff
assertThat(t.getAvailability()
.isAvailable()).isFalse();
setClock(Clock.fixed(now.plus(Duration.ofSeconds(mandatoryDelay + 4)), Defaults.ZONE_ID));
logger.debug("Fourth run.");
s.run();
verify(r, times(4)).run(); // it was run now
assertThat(t.getAvailability()
.isAvailable()).isTrue();
}
@Test
void scalingUnavailability() {
final Availability a = new AvailabilityImpl(s);
final Instant now = Instant.now();
setClock(Clock.fixed(now, Defaults.ZONE_ID));
final Response r = Response.ok()
.build();
final boolean reg = a.registerException(new ResponseProcessingException(r, UUID.randomUUID()
.toString()));
assertSoftly(softly -> {
softly.assertThat(reg)
.isTrue();
softly.assertThat(a.isAvailable())
.isFalse();
softly.assertThat(a.nextAvailabilityCheck())
.isEqualTo(now.plus(Duration.ofSeconds(MANDATORY_DELAY_IN_SECONDS + 1)));
});
final boolean reg2 = a.registerException(new ClientErrorException(429));
assertSoftly(softly -> {
softly.assertThat(reg2)
.isFalse();
softly.assertThat(a.isAvailable())
.isFalse();
softly.assertThat(a.nextAvailabilityCheck())
.isEqualTo(now.plus(Duration.ofSeconds(MANDATORY_DELAY_IN_SECONDS + 2)));
});
final boolean reg3 = a.registerException(new ServerErrorException(503));
assertSoftly(softly -> {
softly.assertThat(reg3)
.isFalse();
softly.assertThat(a.isAvailable())
.isFalse();
softly.assertThat(a.nextAvailabilityCheck())
.isEqualTo(now.plus(Duration.ofSeconds(MANDATORY_DELAY_IN_SECONDS + 4)));
});
final Optional<Instant> success = a.registerSuccess();
assertSoftly(softly -> {
softly.assertThat(success)
.isPresent();
softly.assertThat(a.isAvailable())
.isTrue();
softly.assertThat(a.nextAvailabilityCheck())
.isEqualTo(now);
});
}
private boolean isServerRelated(RuntimeException e) {
return e instanceof ServerErrorException;
}
public PulsarAdminException(ServerErrorException e) {
super(getReasonFromServer(e), e);
this.httpError = getReasonFromServer(e);
this.statusCode = e.getResponse().getStatus();
}
public PulsarAdminException(ServerErrorException e, String message) {
super(message, e);
this.httpError = getReasonFromServer(e);
this.statusCode = e.getResponse().getStatus();
}
public ServerSideErrorException(ServerErrorException e, String msg) {
super(e, msg);
}
public ServerSideErrorException(ServerErrorException e) {
super(e, "Some error occourred on the server");
}
@GET
@Path("/505")
public EmptyTest error505() {
throw new ServerErrorException(Response.Status.HTTP_VERSION_NOT_SUPPORTED);
}