@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(); }
@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(); }
@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); }
@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; }
@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; }
/** * {@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 public void testFilterUnknownMethod() throws Exception { when(mockContext.getMethod()).thenReturn("FOO"); final WebAcFilter filter = new WebAcFilter(emptyList(), mockAccessControlService); assertThrows(NotAllowedException.class, () -> filter.filter(mockContext)); }
/** * 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")); } }
@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(); }
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); } }
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(); }
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); }
@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"); } }
@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 } }
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); } }
@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); }
@Override protected ApiErrorResponse toApiErrorResponse(NotAllowedException exception) { return new ApiErrorResponse( "This resource does not support this HTTP verb.", getCode() ); }
@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(); }
@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 APIError convert(NotAllowedException exception) { return super.convert(exception); }
private Supplier<NotAllowedException> _getNotAllowedExceptionSupplier( String method, String path) { return () -> new NotAllowedException( method + " method is not allowed for path " + path); }
@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(); }
@Test public void notAllowedException() { exit.expectSystemExitWithStatus(ReturnCode.ERROR_DOWN.getCode()); regular.handle(new NotAllowedException("Testing exception")); }
@Test public void notAllowedExceptionFaultTolerant() { exit.expectSystemExitWithStatus(ReturnCode.OK.getCode()); faultTolerant.handle(new NotAllowedException("Testing exception")); }
@Test public void notAllowedException() { handler.handle(new NotAllowedException("Testing exception")); Assertions.assertThat(Events.getFired()).first().isInstanceOf(RemoteOperationFailedEvent.class); }
@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(); }
@Override public Response toResponse(NotAllowedException exception) { return Response.status(Response.Status.METHOD_NOT_ALLOWED).build(); }
/** * 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(); }
@Override public Response toResponse(NotAllowedException exception) { return ExceptionMapperUtils.buildResponse(exception, Response.Status.METHOD_NOT_ALLOWED); }
@GET public EmptyTest exception() { throw new NotAllowedException("not allowed"); }
@Test(expected = NotAllowedException.class) public void get_method_without_primary_key_not_allowed() { RestTest.target(getPort(), "whois/ripe/route6") .request() .get(String.class); }
@Test(expected = NotAllowedException.class) public void delete_method_without_primary_key_not_allowed() { RestTest.target(getPort(), "whois/test/person") .request() .delete(String.class); }