javax.ws.rs.ext.ExceptionMapper Java Examples

The following examples show how to use javax.ws.rs.ext.ExceptionMapper. 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: TenacityConfiguredBundleBuilderTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void useAllExceptionMappers() {
    final TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder
            .newBuilder()
            .configurationFactory(CONFIGURATION_FACTORY)
            .mapAllHystrixRuntimeExceptionsTo(429)
            .build();

    assertThat(bundle)
            .isEqualTo(new TenacityConfiguredBundle<>(
                    CONFIGURATION_FACTORY,
                    Optional.empty(),
                    ImmutableList.<ExceptionMapper<? extends Throwable>>of(
                            new TenacityExceptionMapper(429),
                            new TenacityContainerExceptionMapper(429))
            ));
}
 
Example #2
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionMappersHierarchy2() throws Exception {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();

    TestRuntimeExceptionMapper rm = new TestRuntimeExceptionMapper();
    pf.registerUserProvider(rm);
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
    assertTrue(em instanceof WebApplicationExceptionMapper);
    assertSame(rm, pf.createExceptionMapper(RuntimeException.class, new MessageImpl()));

    WebApplicationExceptionMapper wm = new WebApplicationExceptionMapper();
    pf.registerUserProvider(wm);
    assertSame(wm, pf.createExceptionMapper(WebApplicationException.class, new MessageImpl()));
    assertSame(rm, pf.createExceptionMapper(RuntimeException.class, new MessageImpl()));
}
 
Example #3
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionMappersHierarchy3() throws Exception {
    Message m = new MessageImpl();
    m.put("default.wae.mapper.least.specific", true);
    ServerProviderFactory pf = ServerProviderFactory.getInstance();

    TestRuntimeExceptionMapper rm = new TestRuntimeExceptionMapper();
    pf.registerUserProvider(rm);
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, m);
    assertSame(rm, em);
    assertSame(rm, pf.createExceptionMapper(RuntimeException.class, m));

    WebApplicationExceptionMapper wm = new WebApplicationExceptionMapper();
    pf.registerUserProvider(wm);
    assertSame(wm, pf.createExceptionMapper(WebApplicationException.class, m));
    assertSame(rm, pf.createExceptionMapper(RuntimeException.class, m));
}
 
Example #4
Source File: EJBExceptionMapper.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(EJBException exception) {
    Throwable t = exception.getCause();
    ExceptionMapper mapper = providers.getExceptionMapper(t.getClass());
    log.debug(
            "Unwrapping " + t.getClass().getSimpleName()
                    + " from EJBException and passing in it to its appropriate ExceptionMapper");

    if (mapper != null) {
        return mapper.toResponse(t);
    } else {
        log.error("Could not find exception mapper for exception " + t.getClass().getSimpleName(), t);

        Response.ResponseBuilder builder = Response.status(INTERNAL_SERVER_ERROR);
        return builder.entity(new ErrorResponse(exception)).type(MediaType.APPLICATION_JSON).build();
    }
}
 
Example #5
Source File: MSF4JHttpConnectorListener.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private void handleThrowable(MicroservicesRegistryImpl currentMicroservicesRegistry, Throwable throwable,
                             Request request) {
    Optional<ExceptionMapper> exceptionMapper = currentMicroservicesRegistry.getExceptionMapper(throwable);
    if (exceptionMapper.isPresent()) {
        org.wso2.msf4j.Response msf4jResponse = new org.wso2.msf4j.Response(request);
        msf4jResponse.setEntity(exceptionMapper.get().toResponse(throwable));
        msf4jResponse.send();
    } else {
        log.warn("Unmapped exception", throwable);
        try {
            HttpCarbonMessage response = HttpUtil.createTextResponse(
                    javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                    "Exception occurred :" + throwable.getMessage());
            response.setHeader("Content-type", "text/plain");
            response.addHttpContent(new DefaultLastHttpContent());
            request.respond(response);
        } catch (ServerConnectorException e) {
            log.error("Error while sending the response.", e);
        }
    }
}
 
Example #6
Source File: RequestHandlerImpl.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
private void handleInternalException(InternalException internalException, GenericContainerResponse response) {
    LOG.debug("InternalException occurs", internalException);
    ErrorPages errorPages = (ErrorPages)EnvironmentContext.getCurrent().get(ErrorPages.class);

    Throwable cause = internalException.getCause();

    propagateErrorIfHaveErrorPage(internalException, errorPages);
    propagateErrorIfHaveErrorPage(cause, errorPages);

    if (Tracer.isTracingEnabled()) {
        Tracer.trace("InternalException occurs, cause = (%s)", cause);
    }

    ExceptionMapper exceptionMapper = providers.getExceptionMapper(cause.getClass());
    if (exceptionMapper != null) {
        if (Tracer.isTracingEnabled()) {
            Tracer.trace("Found ExceptionMapper for %s = (%s)", cause.getClass(), exceptionMapper);
        }
        response.setResponse(exceptionMapper.toResponse(cause));
    } else {
        throw new UnhandledException(cause);
    }
}
 
Example #7
Source File: SpringMicroservicesRunner.java    From msf4j with Apache License 2.0 6 votes vote down vote up
public void init() {

        for (Map.Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Path.class).entrySet()) {
            log.info("Deploying " + entry.getKey() + " bean as a resource");
            deploy(entry.getValue());
        }

        for (Map.Entry<String, ExceptionMapper> exceptionMapper :
                applicationContext.getBeansOfType(ExceptionMapper.class).entrySet()) {
            log.info("Adding " + exceptionMapper.getKey() + "  ExceptionMapper");
            addExceptionMapper(exceptionMapper.getValue());
        }

        configureTransport(applicationContext.getBeansOfType(ListenerConfiguration.class).values(),
                applicationContext.getBeansOfType(TransportConfig.class).values());

        start();
    }
 
Example #8
Source File: TenacityConfiguredBundleBuilderTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void withTenacityCircuitBreakerHealthCheck() {
    final TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder
            .newBuilder()
            .configurationFactory(CONFIGURATION_FACTORY)
            .withCircuitBreakerHealthCheck()
            .build();

    assertThat(bundle)
            .isEqualTo(new TenacityConfiguredBundle<>(
                    CONFIGURATION_FACTORY,
                    Optional.empty(),
                    Collections.<ExceptionMapper<? extends Throwable>>emptyList(),
                    true,
                    false
            ));
}
 
Example #9
Source File: Jersey2BackstopperConfigHelperTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void backstopperOnlyExceptionMapperFactory_removes_all_exception_mappers_except_Jersey2ApiExceptionHandler()
    throws NoSuchFieldException, IllegalAccessException {
    // given
    AbstractBinder lotsOfExceptionMappersBinder = new AbstractBinder() {
        @Override
        protected void configure() {
            bind(JsonMappingExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
            bind(JsonParseExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
            bind(generateJerseyApiExceptionHandler(projectApiErrors, utils)).to(ExceptionMapper.class);
        }
    };

    ServiceLocator locator = ServiceLocatorUtilities.bind(lotsOfExceptionMappersBinder);

    // when
    BackstopperOnlyExceptionMapperFactory overrideExceptionMapper = new BackstopperOnlyExceptionMapperFactory(locator);

    // then
    Set<Object> emTypesLeft = overrideExceptionMapper.getFieldObj(
        ExceptionMapperFactory.class, overrideExceptionMapper, "exceptionMapperTypes"
    );
    assertThat(emTypesLeft).hasSize(1);
    ServiceHandle serviceHandle = overrideExceptionMapper.getFieldObj(emTypesLeft.iterator().next(), "mapper");
    assertThat(serviceHandle.getService()).isInstanceOf(Jersey2ApiExceptionHandler.class);
}
 
Example #10
Source File: RestServer.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 启动前钩子
 *
 * @param transport
 * @return
 */
protected CompletableFuture<Void> beforeOpen(final ServerTransport transport) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {
        deployment.start();
        ResteasyProviderFactory providerFactory = deployment.getProviderFactory();
        String root = url.getString(REST_ROOT);
        root = REST_ROOT.getValue().equals(root) ? "" : root;
        Map<Class<?>, ExceptionMapper> mapperMap = providerFactory.getExceptionMappers();
        mapperMap.put(ApplicationException.class, ApplicationExceptionMapper.mapper);
        mapperMap.put(ClientErrorException.class, ClientErrorExceptionMapper.mapper);
        mapperMap.put(IllegalArgumentException.class, IllegalArgumentExceptionMapper.mapper);
        transport.setCodec(new ResteasyCodec(root,
                new RequestDispatcher((SynchronousDispatcher) deployment.getDispatcher(), providerFactory, null)));
        result.complete(null);
    } catch (Throwable e) {
        result.completeExceptionally(e);
    }
    return result;
}
 
Example #11
Source File: ProviderBinderTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
@UseDataProvider("exceptionMapperByExceptionType")
public <T extends Throwable> void retrievesExceptionMapperByExceptionType(boolean singletonOrPerRequest,
                                                                          Class<T> errorClass,
                                                                          Object expectedExceptionMapperClassOrInstance) throws Exception {
    if (singletonOrPerRequest == SINGLETON) {
        registerSingletonExceptionMappers();
    } else {
        registerPerRequestExceptionMappers();
    }

    ExceptionMapper<T> exceptionMapper = providers.getExceptionMapper(errorClass);
    if (singletonOrPerRequest == SINGLETON) {
        assertSame(expectedExceptionMapperClassOrInstance, exceptionMapper);
    } else {
        assertNotNull(exceptionMapper);
        assertEquals(expectedExceptionMapperClassOrInstance, exceptionMapper.getClass());
    }
}
 
Example #12
Source File: RequestHandlerImplTest.java    From everrest with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void usesExceptionMapperToConvertCauseOfInternalExceptionToResponse() throws Exception {
    Exception exception = new Exception();
    InternalException internalException = new InternalException(exception);
    doThrow(internalException).when(requestDispatcher).dispatch(request, response);

    ExceptionMapper<Exception> exceptionMapper = mock(ExceptionMapper.class);
    when(exceptionMapper.toResponse(exception)).thenReturn(serverError().entity("response from exception mapper").build());
    when(providers.getExceptionMapper(Exception.class)).thenReturn(exceptionMapper);

    requestHandler.handleRequest(request, response);

    ArgumentCaptor<Response> argumentCaptor = ArgumentCaptor.forClass(Response.class);
    verify(response).setResponse(argumentCaptor.capture());
    assertEquals(INTERNAL_SERVER_ERROR, argumentCaptor.getValue().getStatusInfo());
    assertEquals("response from exception mapper", argumentCaptor.getValue().getEntity());
}
 
Example #13
Source File: EverrestJetty.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isRestResource(Class<?> resourceClass) {
    return resourceClass.isAnnotationPresent(Path.class) ||
           resourceClass.isAnnotationPresent(Provider.class) ||
           resourceClass.isAnnotationPresent(Filter.class) ||
           resourceClass.isAssignableFrom(ExceptionMapper.class) ||
           resourceClass.isAssignableFrom(ContextResolver.class) ||
           resourceClass.isAssignableFrom(MessageBodyReader.class) ||
           resourceClass.isAssignableFrom(MessageBodyWriter.class) ||
           resourceClass.isAssignableFrom(MethodInvokerFilter.class) ||
           resourceClass.isAssignableFrom(RequestFilter.class) ||
           resourceClass.isAssignableFrom(ResponseFilter.class);
}
 
Example #14
Source File: ProviderBinder.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Add singleton ExceptionMapper.
 *
 * @param exceptionMapper
 *         ExceptionMapper instance
 */
@SuppressWarnings({"unchecked"})
public void addExceptionMapper(ExceptionMapper exceptionMapper) {
    try {
        addExceptionMapper(new SingletonObjectFactory(new ProviderDescriptorImpl(exceptionMapper), exceptionMapper));
    } catch (Exception e) {
        LOG.error(String.format("Failed add ExceptionMapper %s. %s", exceptionMapper.getClass().getName(), e.getMessage()), e);
    }
}
 
Example #15
Source File: ProviderFactoryExceptionMapperTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testNearestSuperclassMatch() {
    ExceptionMapper<?> exceptionMapper = pf.createExceptionMapper(NullPointerException.class,
                                                                  new MessageImpl());
    assertEquals("Wrong mapper found for NullPointerException", RuntimeExceptionMapper.class,
                 exceptionMapper.getClass());
}
 
Example #16
Source File: DelayedTenacityConfiguredBundle.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
public DelayedTenacityConfiguredBundle(TenacityBundleConfigurationFactory<BreakerboxServiceConfiguration> tenacityBundleConfigurationFactory,
                                       Optional<HystrixCommandExecutionHook> hystrixCommandExecutionHook,
                                       Iterable<ExceptionMapper<? extends Throwable>> exceptionMappers,
                                       boolean usingTenacityCircuitBreakerHealthCheck,
                                       boolean usingAdminPort) {
    super(tenacityBundleConfigurationFactory, hystrixCommandExecutionHook, exceptionMappers, usingTenacityCircuitBreakerHealthCheck, usingAdminPort);
}
 
Example #17
Source File: RestComponentResolver.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void addPerRequest(Class clazz) {
    if (clazz.getAnnotation(Provider.class) != null) {
        if (ContextResolver.class.isAssignableFrom(clazz)) {
            providers.addContextResolver(clazz);
        }
        if (ExceptionMapper.class.isAssignableFrom(clazz)) {
            providers.addExceptionMapper(clazz);
        }
        if (MessageBodyReader.class.isAssignableFrom(clazz)) {
            providers.addMessageBodyReader(clazz);
        }
        if (MessageBodyWriter.class.isAssignableFrom(clazz)) {
            providers.addMessageBodyWriter(clazz);
        }
    } else if (clazz.getAnnotation(Filter.class) != null) {
        if (MethodInvokerFilter.class.isAssignableFrom(clazz)) {
            providers.addMethodInvokerFilter(clazz);
        }
        if (RequestFilter.class.isAssignableFrom(clazz)) {
            providers.addRequestFilter(clazz);
        }
        if (ResponseFilter.class.isAssignableFrom(clazz)) {
            providers.addResponseFilter(clazz);
        }
    } else if (clazz.getAnnotation(Path.class) != null) {
        resources.addResource(clazz, null);
    }
}
 
Example #18
Source File: ProviderBinder.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T extends Throwable> ExceptionMapper<T> doGetExceptionMapper(Class<T> errorType) {
    ObjectFactory objectFactory = exceptionMappers.get(errorType);
    if (objectFactory == null) {
        Class superclassOfErrorType = errorType.getSuperclass();
        while (objectFactory == null && superclassOfErrorType != Object.class) {
            objectFactory = exceptionMappers.get(superclassOfErrorType);
            superclassOfErrorType = superclassOfErrorType.getSuperclass();
        }
    }
    if (objectFactory == null) {
        return null;
    }
    return (ExceptionMapper<T>)objectFactory.getInstance(ApplicationContext.getCurrent());
}
 
Example #19
Source File: ApplicationProviderBinder.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type) {
    ExceptionMapper<T> exceptionMapper = doGetExceptionMapper(type);
    if (exceptionMapper == null) {
        exceptionMapper = getDefaults().getExceptionMapper(type);
    }
    return exceptionMapper;
}
 
Example #20
Source File: RestComponentResolver.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void addSingleton(Object instance) {
    Class clazz = instance.getClass();
    if (clazz.getAnnotation(Provider.class) != null) {
        if (instance instanceof ContextResolver) {
            providers.addContextResolver((ContextResolver)instance);
        }
        if (instance instanceof ExceptionMapper) {
            providers.addExceptionMapper((ExceptionMapper)instance);
        }
        if (instance instanceof MessageBodyReader) {
            providers.addMessageBodyReader((MessageBodyReader)instance);
        }
        if (instance instanceof MessageBodyWriter) {
            providers.addMessageBodyWriter((MessageBodyWriter)instance);
        }
    } else if (clazz.getAnnotation(Filter.class) != null) {
        if (instance instanceof MethodInvokerFilter) {
            providers.addMethodInvokerFilter((MethodInvokerFilter)instance);
        }
        if (instance instanceof RequestFilter) {
            providers.addRequestFilter((RequestFilter)instance);
        }
        if (instance instanceof ResponseFilter) {
            providers.addResponseFilter((ResponseFilter)instance);
        }
    } else if (clazz.getAnnotation(Path.class) != null) {
        resources.addResource(instance, null);
    }
}
 
Example #21
Source File: ProviderFactoryExceptionMapperTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testExactMatchInSecondPosition() {
    ExceptionMapper<?> exceptionMapper = pf.createExceptionMapper(RuntimeException1.class,
                                                                  new MessageImpl());
    assertEquals("Wrong mapper found for RuntimeException1", RuntimeExceptionMapper1.class,
                 exceptionMapper.getClass());
}
 
Example #22
Source File: ProviderFactoryExceptionMapperTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testExactMatchInFirstPosition() {
    ExceptionMapper<?> exceptionMapper = pf.createExceptionMapper(RuntimeException2.class,
                                                                  new MessageImpl());
    assertEquals("Wrong mapper found for RuntimeException2", RuntimeExceptionMapper2.class,
                 exceptionMapper.getClass());
}
 
Example #23
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexExceptionMapper() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    pf.registerUserProvider(new SecurityExceptionMapper());
    ExceptionMapper<SecurityException> mapper =
        pf.createExceptionMapper(SecurityException.class, new MessageImpl());
    assertTrue(mapper instanceof SecurityExceptionMapper);
    ExceptionMapper<Throwable> mapper2 =
        pf.createExceptionMapper(Throwable.class, new MessageImpl());
    assertNull(mapper2);
}
 
Example #24
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionMappersHierarchy5() throws Exception {
    Message m = new MessageImpl();
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, m);
    assertTrue(em instanceof WebApplicationExceptionMapper);
}
 
Example #25
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionMappersHierarchy4() throws Exception {
    Message m = new MessageImpl();
    m.put("default.wae.mapper.least.specific", true);
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, m);
    assertTrue(em instanceof WebApplicationExceptionMapper);
}
 
Example #26
Source File: EJBExceptionMapper.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(final EJBException ejbException) {
    final Exception cause = ejbException.getCausedByException();
    if (cause != null) {
        final Class causeClass = cause.getClass();
        final ExceptionMapper exceptionMapper = providers.getExceptionMapper(causeClass);
        if (exceptionMapper == null) {
            return defaultResponse(cause);
        }
        return exceptionMapper.toResponse(cause);
    } else if (EJBAccessException.class.isInstance(ejbException)) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
    return defaultResponse(ejbException);
}
 
Example #27
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultUserExceptionMappers() throws Exception {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    ExceptionMapper<?> mapper =
        pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
    assertNotNull(mapper);
    WebApplicationExceptionMapper wm = new WebApplicationExceptionMapper();
    pf.registerUserProvider(wm);
    ExceptionMapper<?> mapper2 =
        pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
    assertNotSame(mapper, mapper2);
    assertSame(wm, mapper2);
}
 
Example #28
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterFeatureInFeature() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    final Object provider = new WebApplicationExceptionMapper();
    pf.registerUserProvider((Feature) context -> {
        context.register((Feature) context2-> {
            context2.register(provider);
            return true;
        });
        return true;
    });
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
    assertSame(provider, em);
}
 
Example #29
Source File: AbstractTenacityPropertyKeys.java    From tenacity with Apache License 2.0 5 votes vote down vote up
public AbstractTenacityPropertyKeys(TenacityPropertyKeyFactory keyFactory,
                                    Iterable<TenacityPropertyKey> keys,
                                    Iterable<ExceptionMapper<? extends Throwable>> exceptionMappers,
                                    Optional<HystrixCommandExecutionHook> executionHook) {
    this.keys = ImmutableList.copyOf(checkNotNull(keys));
    this.keyFactory = checkNotNull(keyFactory);
    this.exceptionMappers = ImmutableList.copyOf(checkNotNull(exceptionMappers));
    this.executionHook = executionHook;
}
 
Example #30
Source File: EndpointConfig.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void registerExceptionMappers() {
    for (ExceptionMapper<?> mapper : exceptionMappers) {
        register(mapper);
    }
    register(WebApplicaitonExceptionMapper.class);
    register(DefaultExceptionMapper.class);
}