类javax.ws.rs.ext.ExceptionMapper源码实例Demo

下面列出了怎么用javax.ws.rs.ext.ExceptionMapper的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: joyrpc   文件: RestServer.java
/**
 * 启动前钩子
 *
 * @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;
}
 
@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
            ));
}
 
@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);
}
 
源代码4 项目: msf4j   文件: SpringMicroservicesRunner.java
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();
    }
 
源代码5 项目: msf4j   文件: MSF4JHttpConnectorListener.java
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);
        }
    }
}
 
源代码6 项目: pnc   文件: EJBExceptionMapper.java
@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();
    }
}
 
@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))
            ));
}
 
源代码8 项目: cxf   文件: ProviderFactoryTest.java
@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()));
}
 
源代码9 项目: cxf   文件: ProviderFactoryTest.java
@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));
}
 
源代码10 项目: everrest   文件: RequestHandlerImpl.java
@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);
    }
}
 
源代码11 项目: everrest   文件: RequestHandlerImplTest.java
@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());
}
 
源代码12 项目: everrest   文件: ProviderBinderTest.java
@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());
    }
}
 
private void testException(String resource, Class<? extends ExceptionMapper<?>> exceptionMapper) {
	DefaultGatewayRequest request = new DefaultGatewayRequestBuilder()
			.httpMethod("GET")
			.resource(resource)
			.build();

	GatewayResponse response = handler.handleRequest(request, context);
	assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode());
	assertEquals(exceptionMapper.getSimpleName(), response.getBody());
}
 
源代码14 项目: jrestless   文件: FnFutureRequestHandlerTest.java
private void testException(String resource, Class<? extends ExceptionMapper<?>> exceptionMapper) {
    InputEvent inputEvent = new DefaultInputEvent()
            .setReqUrlAndRoute(DOMAIN_WITH_SCHEME + resource, resource)
            .setMethod("GET")
            .getInputEvent();

    FnRequestHandler.WrappedOutput wrappedOutput = handler.handleTestRequest(inputEvent);
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), wrappedOutput.getStatusCode());
    assertEquals(exceptionMapper.getSimpleName(), wrappedOutput.getBody());
}
 
源代码15 项目: emodb   文件: UncheckedExecutionExceptionMapper.java
@SuppressWarnings("unchecked")
@Override
public Response toResponse(UncheckedExecutionException e) {
    ExceptionMapper mapper = _providers.getExceptionMapper(e.getCause().getClass());
    if (mapper == null) {
        return null;
    } else if (mapper instanceof LoggingExceptionMapper) {
        return mapper.toResponse(e);
    } else {
        return mapper.toResponse(e.getCause());
    }
}
 
@Override
public Response toResponse(final TransactionalException ejbException) {
    final Throwable cause = ejbException.getCause();
    if (cause != null) {
        final Class causeClass = cause.getClass();
        final ExceptionMapper exceptionMapper = providers.getExceptionMapper(causeClass);
        if (exceptionMapper == null) {
            return defaultResponse(cause);
        }
        return exceptionMapper.toResponse(cause);
    }
    return defaultResponse(ejbException);
}
 
@Test
public void shouldUseExceptionMapper() {
    final TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder
            .newBuilder()
            .configurationFactory(CONFIGURATION_FACTORY)
            .addExceptionMapper(new TenacityExceptionMapper(429))
            .build();

    assertThat(bundle)
            .isEqualTo(new TenacityConfiguredBundle<>(
                    CONFIGURATION_FACTORY,
                    Optional.empty(),
                    ImmutableList.<ExceptionMapper<? extends Throwable>>of(new TenacityExceptionMapper(429))
            ));
}
 
源代码18 项目: msf4j   文件: MicroservicesRegistryImpl.java
Optional<ExceptionMapper> getExceptionMapper(Throwable throwable) {
    return exceptionMappers.entrySet().
            stream().
            filter(entry -> entry.getKey().isAssignableFrom(throwable.getClass())).
            findFirst().
            flatMap(entry -> Optional.ofNullable(entry.getValue()));
}
 
源代码19 项目: msf4j   文件: MicroservicesRegistryImpl.java
public void removeExceptionMapper(ExceptionMapper em) {
    Arrays.stream(em.getClass().getMethods()).
            filter(method -> method.getName().equals("toResponse") && method.getParameterCount() == 1).
            findAny().
            ifPresent(method -> {
                try {
                    exceptionMappers.remove(Class.forName(method.getGenericParameterTypes()[0].getTypeName(),
                            false, em.getClass().getClassLoader()));
                } catch (ClassNotFoundException e) {
                    log.error("Could not load class", e);
                }
            });
}
 
源代码20 项目: msf4j   文件: MicroservicesServerSC.java
protected void removeExceptionMapper(ExceptionMapper exceptionMapper, Map properties) {
    Object channelId = properties.get(MSF4JConstants.CHANNEL_ID);
    Map<String, MicroservicesRegistryImpl> microservicesRegistries =
            DataHolder.getInstance().getMicroservicesRegistries();
    if (channelId != null) {
        microservicesRegistries.get(channelId.toString()).removeExceptionMapper(exceptionMapper);
    } else {
        microservicesRegistries.values().forEach(registry -> registry.removeExceptionMapper(exceptionMapper));
    }
}
 
源代码21 项目: msf4j   文件: MicroservicesServerSC.java
private void addExceptionMapperToRegistry(ExceptionMapper exceptionMapper, Object channelId) {
    Map<String, MicroservicesRegistryImpl> microservicesRegistries =
            DataHolder.getInstance().getMicroservicesRegistries();
    if (channelId != null) {
        MicroservicesRegistryImpl microservicesRegistry = microservicesRegistries.get(channelId.toString());
        if (microservicesRegistry == null) {
            throw new RuntimeException("Couldn't found the registry for channel ID " + channelId);
        }
        microservicesRegistry.addExceptionMapper(exceptionMapper);
    } else {
        microservicesRegistries.values().forEach(registry -> registry.addExceptionMapper(exceptionMapper));
    }
}
 
源代码22 项目: robe   文件: ExceptionMapperBinder.java
@Override
    protected void configure() {
        bind(new LoggingExceptionMapper<Throwable>() {
        }).to(ExceptionMapper.class);
        bind(new JerseyViolationExceptionMapper()).to(ExceptionMapper.class);
        bind(new JsonProcessingExceptionMapper(isShowDetails())).to(ExceptionMapper.class);
        bind(new EarlyEofExceptionMapper()).to(ExceptionMapper.class);
//        bind(new EmptyOptionalExceptionMapper()).to(ExceptionMapper.class);
    }
 
源代码23 项目: agrest   文件: AgBuilder.java
private void loadExceptionMapperFeature(Collection<Feature> collector, Injector i) {

        i.getInstance(Key.getMapOf(String.class, ExceptionMapper.class))
                .values()
                .forEach(em -> collector.add(c -> {
                    c.register(em);
                    return true;
                }));
    }
 
源代码24 项目: agrest   文件: AgCayenneModule.java
@Override
public void configure(Binder binder) {
    binder.bind(CayenneEntityCompiler.class).to(CayenneEntityCompiler.class);
    binder.bindList(AgEntityCompiler.class).insertBefore(CayenneEntityCompiler.class, PojoEntityCompiler.class);
    binder.bind(ICayennePersister.class).toInstance(persister);

    // delete stages
    binder.bind(DeleteProcessorFactory.class).toProvider(CayenneDeleteProcessorFactoryProvider.class);
    binder.bind(CayenneDeleteStartStage.class).to(CayenneDeleteStartStage.class);
    binder.bind(CayenneDeleteStage.class).to(CayenneDeleteStage.class);

    // update stages
    binder.bind(UpdateProcessorFactoryFactory.class)
            .toProvider(CayenneUpdateProcessorFactoryFactoryProvider.class);
    binder.bind(CayenneUpdateStartStage.class).to(CayenneUpdateStartStage.class);
    binder.bind(CayenneApplyServerParamsStage.class)
            .to(CayenneApplyServerParamsStage.class);
    binder.bind(CayenneCreateStage.class).to(CayenneCreateStage.class);
    binder.bind(CayenneUpdateStage.class).to(CayenneUpdateStage.class);
    binder.bind(CayenneCreateOrUpdateStage.class).to(CayenneCreateOrUpdateStage.class);
    binder.bind(CayenneIdempotentCreateOrUpdateStage.class).to(CayenneIdempotentCreateOrUpdateStage.class);
    binder.bind(CayenneIdempotentFullSyncStage.class).to(CayenneIdempotentFullSyncStage.class);
    binder.bind(CayenneOkResponseStage.class).to(CayenneOkResponseStage.class);
    binder.bind(CayenneCreatedResponseStage.class).to(CayenneCreatedResponseStage.class);

    binder.bindMap(ExceptionMapper.class)
            .put(CayenneRuntimeException.class.getName(), CayenneRuntimeExceptionMapper.class)
            .put(ValidationException.class.getName(), ValidationExceptionMapper.class);

    // unrelate stages
    binder.bind(UnrelateProcessorFactory.class).toProvider(CayenneUnrelateProcessorFactoryProvider.class);
    binder.bind(CayenneUnrelateStartStage.class).to(CayenneUnrelateStartStage.class);
    binder.bind(CayenneUnrelateDataStoreStage.class).to(CayenneUnrelateDataStoreStage.class);
}
 
源代码25 项目: tenacity   文件: TenacityConfiguredBundle.java
public TenacityConfiguredBundle(
        TenacityBundleConfigurationFactory<T> tenacityBundleConfigurationFactory,
        Optional<HystrixCommandExecutionHook> hystrixCommandExecutionHook,
        Iterable<ExceptionMapper<? extends Throwable>> exceptionMappers,
        boolean usingTenacityCircuitBreakerHealthCheck,
        boolean usingAdminPort) {
    this.exceptionMappers = exceptionMappers;
    this.tenacityBundleConfigurationFactory = checkNotNull(tenacityBundleConfigurationFactory);
    this.executionHook = hystrixCommandExecutionHook;
    this.usingTenacityCircuitBreakerHealthCheck = usingTenacityCircuitBreakerHealthCheck;
    this.usingAdminPort = usingAdminPort;
}
 
源代码26 项目: cxf   文件: JAXRSServerFactoryBeanTest.java
@Test
public void testRegisterProviders() {
    JAXRSServerFactoryBean bean = new JAXRSServerFactoryBean();
    bean.setAddress("http://localhost:8080/rest");
    bean.setStart(false);
    bean.setResourceClasses(BookStore.class);
    List<Object> providers = new ArrayList<>();
    Object provider1 = new CustomExceptionMapper();
    providers.add(provider1);
    Object provider2 = new RuntimeExceptionMapper();
    providers.add(provider2);
    bean.setProviders(providers);
    Server s = bean.create();

    ServerProviderFactory factory =
        (ServerProviderFactory)s.getEndpoint().get(ServerProviderFactory.class.getName());

    ExceptionMapper<Exception> mapper1 =
        factory.createExceptionMapper(Exception.class, new MessageImpl());
    assertNotNull(mapper1);
    ExceptionMapper<RuntimeException> mapper2 =
        factory.createExceptionMapper(RuntimeException.class, new MessageImpl());
    assertNotNull(mapper2);
    assertNotSame(mapper1, mapper2);
    assertSame(provider1, mapper1);
    assertSame(provider2, mapper2);


}
 
@Test
public void testExceptionMapperInHierarchy() {
    ExceptionMapper<?> exceptionMapper = pf.createExceptionMapper(IllegalArgumentException.class,
            new MessageImpl());
    Assert.assertNotNull(exceptionMapper);
    Assert.assertEquals("Wrong mapper found for IllegalArgumentException",
            IllegalArgumentExceptionMapper.class, exceptionMapper.getClass());
}
 
@Test
public void testSimpleExceptionMapperWhenHierarchyPresent() {
    ExceptionMapper<?> exceptionMapper = pf.createExceptionMapper(IllegalStateException.class,
            new MessageImpl());
    Assert.assertNotNull(exceptionMapper);
    Assert.assertEquals("Wrong mapper found for IllegalStateException",
            IllegalStateExceptionMapper.class, exceptionMapper.getClass());
}
 
源代码29 项目: cxf   文件: ProviderFactoryTest.java
@Test
public void testRegisterInFeature() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    final Object provider = new WebApplicationExceptionMapper();
    pf.registerUserProvider((Feature) context -> {
        context.register(provider);
        return true;
    });
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
    assertSame(provider, em);
}
 
源代码30 项目: cxf   文件: ProviderFactoryTest.java
@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);
}
 
 类所在包
 类方法
 同包方法