javax.ws.rs.NotAllowedException Java Examples

The following examples show how to use javax.ws.rs.NotAllowedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientErrorExceptionMapper.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: BaseExceptionMapper.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #3
Source File: PostHandler.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #4
Source File: BaseExceptionMapper.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: AllExceptionMapper.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #6
Source File: NotAllowedExceptionMapper.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * {@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();
}
 
Example #7
Source File: ClassFactoryTest.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@Test
void inheritedTypeAreCompatibleTest() {

    Type type = ClassFactory.getGenericType(WebApplicationExceptionHandler.class);
    ClassFactory.checkIfCompatibleType(WebApplicationException.class, type, "Fail");
    ClassFactory.checkIfCompatibleType(NotAllowedException.class, type, "Fail");
}
 
Example #8
Source File: ODataExceptionMapperImplTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #9
Source File: ODataExceptionMapperImpl.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #10
Source File: ExceptionResourceIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #11
Source File: ExceptionResourceIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #12
Source File: ExceptionResourceIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #13
Source File: ExceptionResourceIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #14
Source File: BadRequestTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * 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"));
    }
}
 
Example #15
Source File: JAXRSClientServerUserResourceDefaultTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #16
Source File: NotAllowedExceptionMapper.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #17
Source File: NotAllowedExceptionMapper.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #18
Source File: NotAllowedExceptionMapper.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse( NotAllowedException e ) {
    return toResponse( METHOD_NOT_ALLOWED, e );
}
 
Example #19
Source File: NotAllowedExceptionResourceTest.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
@GET
public EmptyTest exception() {
    throw new NotAllowedException("not allowed");
}
 
Example #20
Source File: NotAllowedExceptionMapper.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse(NotAllowedException exception) {
    return ExceptionMapperUtils.buildResponse(exception, Response.Status.METHOD_NOT_ALLOWED);
}
 
Example #21
Source File: WebApplicationExceptionMapper.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@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();
  }
}
 
Example #22
Source File: NotAllowedExceptionMapper.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@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();
}