下面列出了怎么用javax.ws.rs.NotAllowedException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Response toResponse(Throwable throwable) {
logger.error("Unexpected", throwable);
String errorMsg;
Response response = null;
if (throwable instanceof NotFoundException) {
errorMsg = "{\"code\":404, \"message\":\"" + throwable.getMessage() + "\"}";
response = Response.status(NOT_FOUND).entity(errorMsg).build();
} else if (throwable instanceof NotAllowedException) {
errorMsg = "{\"code\":405, \"message\":\"" + throwable.getMessage() + "\"}";
response = Response.status(METHOD_NOT_ALLOWED).entity(errorMsg).build();
} else {
errorMsg = "{\"code\":500, \"message\":\"" + throwable.getMessage() + "\"}";
response = Response.status(INTERNAL_SERVER_ERROR).entity(errorMsg).build();
}
return response;
}
@Override
public Response toResponse(Exception e) {
WrapperResponseEntity response = null;
if (e instanceof NotFoundException) {
response = new WrapperResponseEntity(ResponseCode.NOT_FOUND);
} else if (e instanceof NotAllowedException) {
response = new WrapperResponseEntity(ResponseCode.FORBIDDEN);
} else if (e instanceof JsonProcessingException) {
response = new WrapperResponseEntity(ResponseCode.ERROR_JSON);
} else if (e instanceof NotSupportedException) {
response = new WrapperResponseEntity(ResponseCode.UNSUPPORTED_MEDIA_TYPE);
} else {
response = excetionWrapper != null ? excetionWrapper.toResponse(e) : null;
if (response == null)
response = new WrapperResponseEntity(ResponseCode.INTERNAL_SERVER_ERROR);
}
return Response.status(response.httpStatus()).type(MediaType.APPLICATION_JSON)
.entity(response).build();
}
/**
* Initialize the response.
* @param parent the parent resource
* @param child the child resource
* @return a response builder
*/
public ResponseBuilder initialize(final Resource parent, final Resource child) {
if (MISSING_RESOURCE.equals(parent)) {
// Can't POST to a missing resource
throw new NotFoundException();
} else if (DELETED_RESOURCE.equals(parent)) {
// Can't POST to a deleted resource
throw new ClientErrorException(GONE);
} else if (getExtensionGraphName() != null
|| ldpResourceTypes(parent.getInteractionModel()).noneMatch(LDP.Container::equals)) {
// Can't POST to an ACL resource or non-Container
throw new NotAllowedException(GET, Stream.of(HEAD, OPTIONS, PATCH, PUT, DELETE).toArray(String[]::new));
} else if (!MISSING_RESOURCE.equals(child) && !DELETED_RESOURCE.equals(child)) {
throw new ClientErrorException(CONFLICT);
} else if (!supportsInteractionModel(ldpType)) {
throw new BadRequestException("Unsupported interaction model provided", status(BAD_REQUEST)
.link(UnsupportedInteractionModel.getIRIString(), LDP.constrainedBy.getIRIString()).build());
} else if (ldpType.equals(LDP.NonRDFSource) && rdfSyntax != null) {
LOGGER.error("Cannot save {} as a NonRDFSource with RDF syntax", getIdentifier());
throw new BadRequestException("Cannot save resource as a NonRDFSource with RDF syntax");
}
setParent(parent);
return status(CREATED);
}
@Override
public Response toResponse(Exception e) {
WrapperResponseEntity response = null;
if (e instanceof NotFoundException) {
response = new WrapperResponseEntity(ResponseCode.NOT_FOUND);
} else if (e instanceof NotAllowedException) {
response = new WrapperResponseEntity(ResponseCode.FORBIDDEN);
} else if (e instanceof JsonProcessingException) {
response = new WrapperResponseEntity(ResponseCode.ERROR_JSON);
} else if (e instanceof NotSupportedException) {
response = new WrapperResponseEntity(ResponseCode.UNSUPPORTED_MEDIA_TYPE);
} else {
response = excetionWrapper != null ? excetionWrapper.toResponse(e) : null;
if(response == null)response = new WrapperResponseEntity(ResponseCode.INTERNAL_SERVER_ERROR);
}
return Response.status(response.httpStatus()).type(MediaType.APPLICATION_JSON).entity(response).build();
}
/**
* {@inheritDoc}
*/
@Override
public Response toResponse(final NotAllowedException exception) {
if (L.isDebugEnabled()) {
L.debug(R.getString("D-REST-JERSEY-MAPPER#0006"));
}
ErrorMessage error = ErrorMessages.create(exception)
.code(ErrorCode.METHOD_NOT_ALLOWED.code())
.resolve()
.get();
L.warn(error.log(), exception);
return Response.status(exception.getResponse().getStatusInfo())
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
@Override
public Response toResponse(Exception exception) {
logger.error("Error: {}", exception.getMessage());
Response.Status responseCode = Response.Status.INTERNAL_SERVER_ERROR;
String message = exception.getMessage();
if (exception instanceof NotFoundException) {
responseCode = Response.Status.NOT_FOUND;
message = exception.getMessage();
} else if (exception instanceof BadRequestException) {
responseCode = Response.Status.BAD_REQUEST;
message = exception.getMessage();
} else if (exception instanceof NotAllowedException) {
responseCode = Response.Status.METHOD_NOT_ALLOWED;
} else if (exception instanceof WebApplicationException) {
WebApplicationException realException = (WebApplicationException) exception;
int response = realException.getResponse().getStatus();
responseCode = Response.Status.fromStatusCode(response);
}
return ResponseFactory.response(responseCode, new ErrorResponse(responseCode.getStatusCode(), message));
}
@Test
void inheritedTypeAreCompatibleTest() {
Type type = ClassFactory.getGenericType(WebApplicationExceptionHandler.class);
ClassFactory.checkIfCompatibleType(WebApplicationException.class, type, "Fail");
ClassFactory.checkIfCompatibleType(NotAllowedException.class, type, "Fail");
}
@Override
public Response toResponse(final NotAllowedException e) {
final Response.Status error = Response.Status.METHOD_NOT_ALLOWED;
return Response
.status(error)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(convert(e, error.getStatusCode()))
.build();
}
@Override
public Response toResponse(final NotAllowedException e) {
final Response.Status error = Response.Status.METHOD_NOT_ALLOWED;
return Response
.status(error)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(convert(e, error.getStatusCode()))
.build();
}
@Path("{a:.*}")
@DefaultMethod
public Response handle() {
if (HttpMethod.GET.equals(request.getMethod())) {
String id = ui.getPathParameters().getFirst("id");
Book book = books.get(id);
return Response.ok(book, headers.getAcceptableMediaTypes().get(0)).build();
}
throw new NotAllowedException("GET");
}
/**
* Tests the response for a request with a bad method.
*/
@Test
public void badMethod() {
WebTarget wt = target();
try {
wt.path("hosts").request().delete(String.class);
fail("Fetch of non-existent URL did not throw an exception");
} catch (NotAllowedException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 405 Method Not Allowed"));
}
}
@Test
public void testNonExistingEndpoint(){
try {
clientSetup.getRestClient()
.pathResource( getOrgAppPath( "non_existant_delete_endpoint" ) ).delete( );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
@Test
public void testNotImplementedException(){
try {
clientSetup.getRestClient().management().orgs().delete( true );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
@Test
public void testDeleteFromWrongEndpoint(){
try {
clientSetup.getRestClient()
.pathResource( clientSetup.getOrganizationName() + "/" + clientSetup.getAppName() ).delete( );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
@Test
public void testUnsupportedServiceOperation(){
try {
clientSetup.getRestClient()
.pathResource( getOrgAppPath( "users" ) ).delete( );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
private ODataErrorContext createErrorContext(final WebApplicationException exception) {
ODataErrorContext context = new ODataErrorContext();
if (uriInfo != null) {
context.setRequestUri(uriInfo.getRequestUri());
}
if (httpHeaders != null && httpHeaders.getRequestHeaders() != null) {
MultivaluedMap<String, String> requestHeaders = httpHeaders.getRequestHeaders();
Set<Entry<String, List<String>>> entries = requestHeaders.entrySet();
for (Entry<String, List<String>> entry : entries) {
context.putRequestHeader(entry.getKey(), entry.getValue());
}
}
context.setContentType(getContentType().toContentTypeString());
context.setException(exception);
context.setErrorCode(null);
context.setMessage(exception.getMessage());
context.setLocale(DEFAULT_RESPONSE_LOCALE);
context.setHttpStatus(HttpStatusCodes.fromStatusCode(exception.getResponse().getStatus()));
if (exception instanceof NotAllowedException) {
// RFC 2616, 5.1.1: " An origin server SHOULD return the status code
// 405 (Method Not Allowed) if the method is known by the origin server
// but not allowed for the requested resource, and 501 (Not Implemented)
// if the method is unrecognized or not implemented by the origin server."
// Since all recognized methods are handled elsewhere, we unconditionally
// switch to 501 here for not-allowed exceptions thrown directly from
// JAX-RS implementations.
context.setHttpStatus(HttpStatusCodes.NOT_IMPLEMENTED);
context.setMessage("The request dispatcher does not allow the HTTP method used for the request.");
context.setLocale(Locale.ENGLISH);
}
return context;
}
@Test
public void testNotAllowedJaxRsException() throws Exception {
// prepare
String message = "The request dispatcher does not allow the HTTP method used for the request.";
Exception exception = new NotAllowedException(Response.status(Response.Status.METHOD_NOT_ALLOWED).header(HttpHeaders.ALLOW, "GET").build());
// execute
Response response = exceptionMapper.toResponse(exception);
// verify
verifyResponse(response, message, HttpStatusCodes.NOT_IMPLEMENTED);
}
@Override
public Response toResponse(NotAllowedException exception) {
logger.info(String.format("%s. Returning %s response.", exception, Status.METHOD_NOT_ALLOWED));
logger.debug(StringUtils.EMPTY, exception);
return Response.status(Status.METHOD_NOT_ALLOWED).entity(exception.getMessage()).type("text/plain").build();
}
@Override
public Response toResponse(WebApplicationException exception) {
ServiceError error = newDto(ServiceError.class).withMessage(exception.getMessage());
if (exception instanceof BadRequestException) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof ForbiddenException) {
return Response.status(Response.Status.FORBIDDEN)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotFoundException) {
return Response.status(Response.Status.NOT_FOUND)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotAuthorizedException) {
return Response.status(Response.Status.UNAUTHORIZED)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotAcceptableException) {
return Response.status(Status.NOT_ACCEPTABLE)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotAllowedException) {
return Response.status(Status.METHOD_NOT_ALLOWED)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else if (exception instanceof NotSupportedException) {
return Response.status(Status.UNSUPPORTED_MEDIA_TYPE)
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
} else {
return Response.serverError()
.entity(DtoFactory.getInstance().toJson(error))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
@Override
public Response toResponse(NotAllowedException exception) {
return ExceptionMapperUtils.buildResponse(exception, Response.Status.METHOD_NOT_ALLOWED);
}
@GET
public EmptyTest exception() {
throw new NotAllowedException("not allowed");
}
@Override
public Response toResponse( NotAllowedException e ) {
return toResponse( METHOD_NOT_ALLOWED, e );
}