Java 类javax.ws.rs.NotAllowedException 实例源码

项目:azeroth    文件:BaseExceptionMapper.java   
@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();
}
项目:jeesuite-libs    文件:BaseExceptionMapper.java   
@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();
}
项目: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);
}
项目:gondola    文件:AdminResource.java   
@Path("/setSlave")
@POST
public Map setSlave(@QueryParam("shardId") String shardId, @QueryParam("masterShardId") String masterShardId) {
    if (shardManagerClient == null) {
        throw new NotAllowedException("The operation only supported in multi-shard mode");
    }
    Map<Object, Object> map = new LinkedHashMap<>();
    try {
        shardManagerClient.startObserving(shardId, masterShardId, 5000);
        map.put("success", true);
    } catch (ShardManagerProtocol.ShardManagerException | InterruptedException e) {
        map.put("success", false);
        map.put("reason", e.getMessage());
    }
    return map;
}
项目:gondola    文件:AdminResource.java   
@Path("/unsetSlave")
@POST
public Map unsetSlave(@QueryParam("shardId") String shardId, @QueryParam("masterShardId") String masterShardId) {
    Map<Object, Object> map = new LinkedHashMap<>();
    if (shardManagerClient == null) {
        throw new NotAllowedException("The operation only supported in multi-shard mode");
    }
    try {
        shardManagerClient.stopObserving(shardId, masterShardId, 5000);
        map.put("success", true);
    } catch (ShardManagerProtocol.ShardManagerException | InterruptedException e) {
        map.put("success", false);
        map.put("reason", e.getMessage());
    }
    return map;
}
项目:sinavi-jfw    文件:NotAllowedExceptionMapper.java   
/**
 * {@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();
}
项目:devicehive-java-server    文件:AllExceptionMapper.java   
@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));
}
项目:trellis    文件:WebACFilterTest.java   
@Test
public void testFilterUnknownMethod() throws Exception {
    when(mockContext.getMethod()).thenReturn("FOO");

    final WebAcFilter filter = new WebAcFilter(emptyList(), mockAccessControlService);

    assertThrows(NotAllowedException.class, () -> filter.filter(mockContext));
}
项目:athena    文件:BadRequestTest.java   
/**
 * 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"));
    }
}
项目:coddy    文件:NotAllowedMapper.java   
@Override
public Response toResponse(NotAllowedException e) {
    return Response.status(Response.Status.METHOD_NOT_ALLOWED)
            .entity(new org.crunchytorch.coddy.application.data.Response(e.getMessage()))
            .type(MediaType.APPLICATION_JSON)
            .build();
}
项目:trellis    文件:WebACFilterTest.java   
@Test
public void testFilterUnknownMethod() throws Exception {
    when(mockContext.getMethod()).thenReturn("FOO");

    final WebAcFilter filter = new WebAcFilter(emptyList(), mockAccessControlService);

    assertThrows(NotAllowedException.class, () -> filter.filter(mockContext));
}
项目:robozonky    文件:AppRuntimeExceptionHandler.java   
private static void handleException(final Throwable ex, final boolean faultTolerant) {
    final Throwable cause = ex.getCause();
    if (ex instanceof NotAllowedException || ex instanceof ServerErrorException ||
            cause instanceof SocketException || cause instanceof UnknownHostException) {
        AppRuntimeExceptionHandler.handleZonkyMaintenanceError(ex, faultTolerant);
    } else {
        AppRuntimeExceptionHandler.handleUnexpectedException(ex);
    }
}
项目:robozonky    文件:RuntimeExceptionHandler.java   
private Consumer<Throwable> getHandler(final Throwable t) {
    if (t instanceof ProcessingException || t instanceof NotAllowedException || t instanceof ServerErrorException) {
        return this.getCommunicationFailureHandler();
    } else if (t instanceof WebApplicationException) {
        return this.getRemoteFailureHandler();
    }
    return this.getOtherFailureHandler();
}
项目: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);
}
项目:revoker    文件:OCSPResponderResourceTest.java   
@Test
public void getWithNoDataIsNotAllowed() {
    try {
        resources.client().target("/ocsp/").request().get(OCSPResp.class);
        failBecauseExceptionWasNotThrown(NotAllowedException.class);
    } catch (NotAllowedException e) {
        assertThat(e).hasMessageEndingWith("HTTP 405 Method Not Allowed");
    }
}
项目:lens    文件:ServerModeFilter.java   
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
  switch (LensServices.get().getServiceMode()) {
  case READ_ONLY:
    // Allows all requests on session and only GET everywhere
    if (!requestContext.getUriInfo().getPath().startsWith("session")) {
      if (!requestContext.getMethod().equals("GET")) {
        throw new NotAllowedException("Server is in readonly mode. Request on path:"
          + requestContext.getUriInfo().getPath(), "GET", (String[]) null);
      }
    }
    break;
  case METASTORE_READONLY:
    // Allows GET on metastore and all other requests
    if (requestContext.getUriInfo().getPath().startsWith("metastore")) {
      if (!requestContext.getMethod().equals("GET")) {
        throw new NotAllowedException("Metastore is in readonly mode. Request on path:"
          + requestContext.getUriInfo().getPath(), "GET", (String[]) null);
      }
    }
    break;
  case METASTORE_NODROP:
    // Does not allows DROP on metastore, all other request are allowed
    if (requestContext.getUriInfo().getPath().startsWith("metastore")) {
      if (requestContext.getMethod().equals("DELETE")) {
        throw new NotAllowedException("Metastore is in nodrop mode. Request on path:"
          + requestContext.getUriInfo().getPath(), "GET", new String[]{"PUT", "POST"});
      }
    }
    break;

  case OPEN:
    // nothing to do
  }
}
项目:lens    文件:TestResourceMethodMetrics.java   
private void makeClientError() throws Exception {
  WebTarget dbTarget = target().path("metastore").path("databases/blah");
  try {
    dbTarget.queryParam("sessionid", lensSessionId).request(mediaType).get(APIResult.class);
    fail("Should get 404");
  } catch (NotAllowedException e) {
    // expected
    log.error("Not found excepiton:", e);
  }
}
项目:restful-hub    文件:NotAllowedExceptionMapper.java   
@Override
public Response toResponse(NotAllowedException e) {
    LOGGER.error(e.getLocalizedMessage(), e);
    String message = e.getLocalizedMessage();
    return ErrorBuilder.newBuilder()
            .message(message)
            .error("method_not_allowed", message)
            .build(Response.Status.METHOD_NOT_ALLOWED);
}
项目:jee-rest    文件:NotAllowedExceptionMapper.java   
@Override
protected ApiErrorResponse toApiErrorResponse(NotAllowedException exception) {
    return new ApiErrorResponse(
        "This resource does not support this HTTP verb.", 
        getCode()
    );
}
项目:twister    文件:NotAllowedExceptionMapper.java   
@Override
public Response toResponse(NotAllowedException e) {
    try {
        response.sendRedirect( "/404");
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return Response.status(Response.Status.METHOD_NOT_ALLOWED)
            .entity("No such resource")
            .build();
}
项目:onos    文件:BadRequestTest.java   
/**
 * 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"));
    }
}
项目:usergrid    文件:ExceptionResourceIT.java   
@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());
    }
}
项目:usergrid    文件:ExceptionResourceIT.java   
@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());
    }
}
项目:usergrid    文件:ExceptionResourceIT.java   
@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());
    }
}
项目:usergrid    文件:ExceptionResourceIT.java   
@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());
    }
}
项目:cloud-odata-java    文件:ODataExceptionMapperImpl.java   
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;
}
项目:cloud-odata-java    文件:ODataExceptionMapperImplTest.java   
@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);
}
项目:com-liferay-apio-architect    文件:NotAllowedExceptionConverter.java   
@Override
public APIError convert(NotAllowedException exception) {
    return super.convert(exception);
}
项目:com-liferay-apio-architect    文件:RootEndpointImpl.java   
private Supplier<NotAllowedException> _getNotAllowedExceptionSupplier(
    String method, String path) {

    return () -> new NotAllowedException(
        method + " method is not allowed for path " + path);
}
项目:nifi-registry    文件:NotAllowedExceptionMapper.java   
@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();
}
项目:robozonky    文件:AppRuntimeExceptionHandlerTest.java   
@Test
public void notAllowedException() {
    exit.expectSystemExitWithStatus(ReturnCode.ERROR_DOWN.getCode());
    regular.handle(new NotAllowedException("Testing exception"));
}
项目:robozonky    文件:AppRuntimeExceptionHandlerTest.java   
@Test
public void notAllowedExceptionFaultTolerant() {
    exit.expectSystemExitWithStatus(ReturnCode.OK.getCode());
    faultTolerant.handle(new NotAllowedException("Testing exception"));
}
项目:robozonky    文件:DaemonRuntimeExceptionHandlerTest.java   
@Test
public void notAllowedException() {
    handler.handle(new NotAllowedException("Testing exception"));
    Assertions.assertThat(Events.getFired()).first().isInstanceOf(RemoteOperationFailedEvent.class);
}
项目: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();
}
项目:metadict    文件:NotAllowedExceptionMapper.java   
@Override
public Response toResponse(NotAllowedException exception) {
    return Response.status(Response.Status.METHOD_NOT_ALLOWED).build();
}
项目:fcrepo-storage-policy    文件:FedoraStoragePolicy.java   
/**
 * POST to store nodeType and hint
 *
 * @param request For now, follows pattern: mix:mimeType image/tiff
 *        store-hint
 * @return status
 */

@POST
@Consumes(APPLICATION_FORM_URLENCODED)
@Timed
public Response post(final @PathParam("path") String path,
                     final String request) throws RepositoryException {
    LOGGER.debug("POST Received request param: {}", request);
    final Response.ResponseBuilder response;

    if (!path.equalsIgnoreCase(POLICY_RESOURCE)) {
        throw new NotAllowedException(
                "POST method not allowed on " + getUriInfo().getAbsolutePath() +
                        ", try /policies/fcr:storagepolicy");
    }

    final String[] str = split(request); // simple split for now
    validateArgs(str.length);
    final Node node = getJcrTools().findOrCreateNode(session,
            FEDORA_STORAGE_POLICY_PATH, "test");
    if (isValidNodeTypeProperty(session, str[0]) ||
            isValidConfigurationProperty(str[0])) {
        node.setProperty(str[0], new String[]{str[1] + ":" + str[2]});

        // TODO (for now) instantiate PolicyType based on mix:mimeType
        final StoragePolicy policy = newPolicyInstance(str[0], str[1], str[2]);
        // TODO (for now) based on object comparison using equals()
        if (storagePolicyDecisionPoint.contains(policy)) {
            throw new StoragePolicyTypeException("Property already exists!");
        }
        storagePolicyDecisionPoint.add(policy);
        session.save();
        LOGGER.debug("Saved PDS hint {}", request);

        response = created(getUriInfo().getBaseUriBuilder()
                .path(FedoraStoragePolicy.class)
                .buildFromMap(singletonMap("path", str[0])));
    } else {
        throw new StoragePolicyTypeException(
                "Invalid property type specified: " + str[0]);
    }


    return response.build();
}
项目:hawkular-metrics    文件:NotAllowedExceptionMapper.java   
@Override
public Response toResponse(NotAllowedException exception) {
    return ExceptionMapperUtils.buildResponse(exception, Response.Status.METHOD_NOT_ALLOWED);
}
项目:sinavi-jfw    文件:NotAllowedExceptionResourceTest.java   
@GET
public EmptyTest exception() {
    throw new NotAllowedException("not allowed");
}
项目:whois    文件:WhoisRestServiceTestIntegration.java   
@Test(expected = NotAllowedException.class)
public void get_method_without_primary_key_not_allowed() {
    RestTest.target(getPort(), "whois/ripe/route6")
            .request()
            .get(String.class);
}
项目:whois    文件:WhoisRestServiceTestIntegration.java   
@Test(expected = NotAllowedException.class)
public void delete_method_without_primary_key_not_allowed() {
    RestTest.target(getPort(), "whois/test/person")
            .request()
            .delete(String.class);
}