@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);
}
java类javax.ws.rs.ext.ExceptionMapper的实例源码
Jersey2BackstopperConfigHelperTest.java 文件源码
项目:backstopper
阅读 25
收藏 0
点赞 0
评论 0
MinijaxApplication.java 文件源码
项目:minijax
阅读 31
收藏 0
点赞 0
评论 0
@SuppressWarnings({ "unchecked", "rawtypes" })
private Response toResponse(final MinijaxRequestContext context, final Exception ex) {
final MinijaxResourceMethod rm = context.getResourceMethod();
final List<MediaType> mediaTypes;
if (rm != null) {
mediaTypes = rm.getProduces();
} else {
mediaTypes = context.getAcceptableMediaTypes();
}
for (final MediaType mediaType : mediaTypes) {
final ExceptionMapper mapper = providers.getExceptionMapper(ex.getClass(), mediaType);
if (mapper != null) {
return mapper.toResponse(ex);
}
}
return ExceptionUtils.toWebAppException(ex).getResponse();
}
MinijaxProviders.java 文件源码
项目:minijax
阅读 27
收藏 0
点赞 0
评论 0
@SuppressWarnings("unchecked")
public void register(final Class<?> c) {
if (MessageBodyReader.class.isAssignableFrom(c)) {
readers.add((Class<MessageBodyReader<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Consumes.class)));
}
if (MessageBodyWriter.class.isAssignableFrom(c)) {
writers.add((Class<MessageBodyWriter<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
}
if (ExceptionMapper.class.isAssignableFrom(c)) {
exceptionMappers.add((Class<ExceptionMapper<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
}
if (ParamConverterProvider.class.isAssignableFrom(c)) {
paramConverterProviders.add((ParamConverterProvider) application.get(c));
}
}
AbstractLdapBatchTask.java 文件源码
项目:plugin-id
阅读 24
收藏 0
点赞 0
评论 0
/**
* Process the entries
*/
private void doBatch() {
for (final B importEntry : task.getEntries()) {
// Override previous status
importEntry.setStatus(null);
importEntry.setStatusText(null);
try {
doBatch(importEntry);
// Success
importEntry.setStatus(Boolean.TRUE);
log.info("Import of {} succeed", importEntry);
} catch (final Exception ne) {
// The entry creation failed : entity itself of group membership
log.info("Import of {} failed : {}", importEntry, ne.getMessage());
importEntry.setStatus(Boolean.FALSE);
final ExceptionMapper<Throwable> mapper = jaxrsFactory.createExceptionMapper(ne.getClass(), null);
importEntry.setStatusText(mapper == null ? ne.getMessage() : mapper.toResponse(ne).getEntity().toString());
}
task.getStatus().setDone(task.getStatus().getDone() + 1);
}
}
UserFullLdapTaskTest.java 文件源码
项目:plugin-id
阅读 29
收藏 0
点赞 0
评论 0
@Test
public void configureMessage() throws IllegalArgumentException, IllegalAccessException {
final ServerProviderFactory instance = ServerProviderFactory.getInstance();
@SuppressWarnings("unchecked")
final List<ProviderInfo<ExceptionMapper<?>>> object = (List<ProviderInfo<ExceptionMapper<?>>>) FieldUtils
.getField(ServerProviderFactory.class, "exceptionMappers", true).get(instance);
final FailSafeExceptionMapper provider = new FailSafeExceptionMapper();
object.add(new ProviderInfo<>(provider, null, true));
final JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
FieldUtils.getField(FailSafeExceptionMapper.class, "jacksonJsonProvider", true).set(provider, jacksonJsonProvider);
final UserImportEntry entry = Mockito.mock(UserImportEntry.class);
Mockito.when(entry.getId()).thenThrow(new RuntimeException());
final BatchTaskVo<UserImportEntry> importTask = new BatchTaskVo<>();
importTask.setEntries(Collections.singletonList(entry));
task.configure(importTask);
task.jaxrsFactory = instance;
task.run();
Assert.assertEquals(Boolean.TRUE, importTask.getStatus().getStatus());
Assert.assertEquals(1, importTask.getStatus().getDone());
Assert.assertEquals(1, importTask.getStatus().getEntries());
}
RestfulExceptionMapper.java 文件源码
项目:crudlet
阅读 29
收藏 0
点赞 0
评论 0
@Override
public Response toResponse(Exception ex) {
if (Options.RETURN_EXCEPTION_BODY) {
if (ex instanceof PersistenceException) {
Throwable cause = ex.getCause();
if (cause != null) { // The type of this exception is determined at runtime
cause = cause.getCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
return new RestErrorBuilder(cause).createResponse();
}
}
}
}
ExceptionMapper exceptionMapper = providers.getExceptionMapper(ex.getClass());
if (exceptionMapper == null || exceptionMapper == this) {
return Response.serverError().build();
}
else {
return exceptionMapper.toResponse(ex);
}
}
EJBExceptionMapper.java 文件源码
项目:resteasy-examples
阅读 24
收藏 0
点赞 0
评论 0
public Response toResponse(EJBException exception)
{
if (exception.getCausedByException() == null)
{
return Response.serverError().build();
}
Class cause = exception.getCausedByException().getClass();
ExceptionMapper mapper = providers.getExceptionMapper(cause);
if (mapper == null)
{
return Response.serverError().build();
}
else
{
return mapper.toResponse(exception.getCausedByException());
}
}
EJBExceptionMapper.java 文件源码
项目:resteasy-examples
阅读 23
收藏 0
点赞 0
评论 0
public Response toResponse(EJBException exception)
{
if (exception.getCausedByException() == null)
{
return Response.serverError().build();
}
Class cause = exception.getCausedByException().getClass();
ExceptionMapper mapper = providers.getExceptionMapper(cause);
if (mapper == null)
{
return Response.serverError().build();
}
else
{
return mapper.toResponse(exception.getCausedByException());
}
}
EJBExceptionMapper.java 文件源码
项目:omakase
阅读 20
收藏 0
点赞 0
评论 0
@SuppressWarnings("unchecked")
@Override
public Response toResponse(EJBException exception) {
if (exception.getCausedByException() == null) {
LOGGER.error(exception.getMessage(), exception);
return Responses.errorResponse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(), "Internal Server Error", exception, LOGGER.isInfoEnabled());
} else {
Class cause = exception.getCausedByException().getClass();
ExceptionMapper mapper = providers.getExceptionMapper(cause);
if (mapper == null) {
LOGGER.error(exception.getMessage(), exception);
return Responses.errorResponse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(), "Internal Server Error", exception, LOGGER.isInfoEnabled());
} else {
return mapper.toResponse(exception.getCausedByException());
}
}
}
RESTAppBase.java 文件源码
项目:r01fb
阅读 24
收藏 0
点赞 0
评论 0
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
// rest Resources
Set<Class<? extends RESTResource>> restResourceTypes = this.getRESTResourceTypes();
if (CollectionUtils.hasData(restResourceTypes)) s.addAll(restResourceTypes);
// Request received objects mappers: transforms Java->XML for REST methods param types
Set<Class<? extends MessageBodyReader<?>>> reqReceivedTypesMappers = this.getRequestReceivedTypesMappers();
if (CollectionUtils.hasData(reqReceivedTypesMappers)) s.addAll(reqReceivedTypesMappers);
// Response sent objects mappers: transforms Java->XML for REST methods return types
Set<Class<? extends MessageBodyWriter<?>>> respSentTypesMappers = this.getResponseSentTypesMappers();
if (CollectionUtils.hasData(respSentTypesMappers)) s.addAll(respSentTypesMappers);
// Exception Mappers
Set<Class<? extends ExceptionMapper<?>>> expsMappers = this.getExceptionsMappers();
if (CollectionUtils.hasData(expsMappers)) s.addAll(expsMappers);
return s;
}
SpringMicroservicesRunner.java 文件源码
项目:msf4j
阅读 24
收藏 0
点赞 0
评论 0
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();
}
MicroservicesRegistryImpl.java 文件源码
项目:msf4j
阅读 26
收藏 0
点赞 0
评论 0
public void addExceptionMapper(ExceptionMapper... mapper) {
Arrays.stream(mapper).forEach(em -> {
Arrays.stream(em.getClass().getMethods()).
filter(method -> "toResponse".equals(method.getName()) && method.getParameterCount() == 1 &&
!Throwable.class.getName().equals(method.getParameterTypes()[0].getTypeName())).
findAny().
ifPresent(method -> {
try {
exceptionMappers.put(Class.forName(method.getParameterTypes()[0].getTypeName(), false,
em.getClass().getClassLoader()), em);
} catch (ClassNotFoundException e) {
log.error("Could not load class", e);
}
});
});
}
MSF4JHttpConnectorListener.java 文件源码
项目:msf4j
阅读 28
收藏 0
点赞 0
评论 0
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.addHttpContent(new DefaultLastHttpContent());
request.respond(response);
} catch (ServerConnectorException e) {
log.error("Error while sending the response.", e);
}
}
}
RESTEasyUtil.java 文件源码
项目:switchyard
阅读 24
收藏 0
点赞 0
评论 0
/**
* Finds the RESTEasy providers parameter and return its value as map of classes with its generic types.
*
* @param contextParams the map of all context parameters
* @return a Map of RESTEasy exception-provider classes
*/
public static Map<Class<?>, Class<?>> getExceptionProviderMap(Map<String, String> contextParams) {
Map<Class<?>, Class<?>> providerMap = new HashMap<Class<?>, Class<?>>();
List<String> providers = getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS);
if (providers != null) {
for (String provider : providers) {
Class<?> providerClass = Classes.forName(provider.trim());
if (providerClass != null) {
Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ExceptionMapper.class)[0];
Class<?> exceptionClass = Types.getRawType(exceptionType);
providerMap.put(exceptionClass, providerClass);
}
}
}
return providerMap;
}
LinkRestBuilder.java 文件源码
项目:link-rest
阅读 20
收藏 0
点赞 0
评论 0
/**
* Maps an ExceptionMapper for a given type of Exceptions. While this method
* can be used for arbitrary exceptions, it is most useful to override the
* default exception handlers defined in LinkRest for the following
* exceptions: {@link LinkRestException}, {@link CayenneRuntimeException},
* {@link ValidationException}.
*
* @since 1.1
*/
public <E extends Throwable> LinkRestBuilder mapException(Class<? extends ExceptionMapper<E>> mapper) {
for (Type t : mapper.getGenericInterfaces()) {
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
if (ExceptionMapper.class.equals(pt.getRawType())) {
Type[] args = pt.getActualTypeArguments();
exceptionMappers.put((Class<?>) args[0], mapper);
return this;
}
}
}
throw new IllegalArgumentException("Failed to register ExceptionMapper: " + mapper.getName());
}
TenacityConfiguredBundleBuilderTest.java 文件源码
项目:tenacity
阅读 22
收藏 0
点赞 0
评论 0
@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))
));
}
TenacityConfiguredBundleBuilderTest.java 文件源码
项目:tenacity
阅读 30
收藏 0
点赞 0
评论 0
@Test
public void withExecutionMappers() throws Exception {
final HystrixCommandExecutionHook hook = new ExceptionLoggingCommandHook();
final TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder
.newBuilder()
.configurationFactory(CONFIGURATION_FACTORY)
.commandExecutionHook(hook)
.build();
assertThat(bundle)
.isEqualTo(new TenacityConfiguredBundle<>(
CONFIGURATION_FACTORY,
Optional.of(hook),
Collections.<ExceptionMapper<? extends Throwable>>emptyList()
));
}
TenacityConfiguredBundleBuilderTest.java 文件源码
项目:tenacity
阅读 25
收藏 0
点赞 0
评论 0
@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
));
}
SamlProxyApplication.java 文件源码
项目:verify-hub
阅读 24
收藏 0
点赞 0
评论 0
public List<Class<? extends ExceptionMapper<?>>> getExceptionMappers() {
List<Class<? extends ExceptionMapper<?>>> classes = new ArrayList<>();
classes.add(NoKeyConfiguredForEntityExceptionMapper.class);
classes.add(SamlProxySamlTransformationErrorExceptionMapper.class);
classes.add(SamlProxyApplicationExceptionMapper.class);
classes.add(SamlProxyExceptionMapper.class);
return classes;
}
MinijaxProviders.java 文件源码
项目:minijax
阅读 26
收藏 0
点赞 0
评论 0
/**
* Get an exception mapping provider for a particular class of exception.
*
* This is non-standard (i.e., not in the official JAX-RS spec), but there is evidence that
* it will be in a future version: https://github.com/jax-rs/api/issues/328 ("JAX_RS_SPEC-323").
*
* @param type
* @param mediaType
* @return
*/
@SuppressWarnings("unchecked")
public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(final Class<T> type, final MediaType mediaType) {
for (final Class<? extends ExceptionMapper<?>> exceptionMapperClass : exceptionMappers.get(mediaType)) {
final ParameterizedType parameterizedType = (ParameterizedType) exceptionMapperClass.getGenericInterfaces()[0];
final Class<? extends Exception> exClass = (Class<? extends Exception>) parameterizedType.getActualTypeArguments()[0];
if (exClass.isAssignableFrom(type)) {
return (ExceptionMapper<T>) application.get(exceptionMapperClass);
}
}
return null;
}
ApioApplication.java 文件源码
项目:com-liferay-apio-architect
阅读 27
收藏 0
点赞 0
评论 0
@Reference(
cardinality = MULTIPLE, policyOption = GREEDY,
target = "(liferay.apio.architect.exception.mapper=true)"
)
public void setExceptionMapper(
ServiceReference<ExceptionMapper> serviceReference,
ExceptionMapper exceptionMapper) {
_exceptionMappers.add(exceptionMapper);
}
ApioApplication.java 文件源码
项目:com-liferay-apio-architect
阅读 20
收藏 0
点赞 0
评论 0
@SuppressWarnings("unused")
public void unsetExceptionMapper(
ServiceReference<ExceptionMapper> serviceReference,
ExceptionMapper exceptionMapper) {
_exceptionMappers.remove(exceptionMapper);
}
GatewayRequestObjectHandlerIntTest.java 文件源码
项目:jrestless
阅读 22
收藏 0
点赞 0
评论 0
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());
}
FnFutureRequestHandlerTest.java 文件源码
项目:jrestless
阅读 19
收藏 0
点赞 0
评论 0
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());
}
UncheckedExecutionExceptionMapper.java 文件源码
项目:emodb
阅读 22
收藏 0
点赞 0
评论 0
@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());
}
}
AbstractExceptionMapperTestHelper.java 文件源码
项目:FinanceAnalytics
阅读 106
收藏 0
点赞 0
评论 0
protected void init(ExceptionMapper<?> mapper, MediaType mediaType) throws Exception {
HttpHeaders headers = mock(HttpHeaders.class);
when(headers.getAcceptableMediaTypes()).thenReturn(Arrays.asList(mediaType));
Field field = AbstractExceptionMapper.class.getDeclaredField("_headers");
field.setAccessible(true);
field.set(mapper, headers);
}
MicroservicesRegistryImpl.java 文件源码
项目:msf4j
阅读 25
收藏 0
点赞 0
评论 0
Optional<ExceptionMapper> getExceptionMapper(Throwable throwable) {
return exceptionMappers.entrySet().
stream().
filter(entry -> entry.getKey().isAssignableFrom(throwable.getClass())).
findFirst().
flatMap(entry -> Optional.ofNullable(entry.getValue()));
}
MicroservicesRegistryImpl.java 文件源码
项目:msf4j
阅读 27
收藏 0
点赞 0
评论 0
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);
}
});
}
MicroservicesServerSC.java 文件源码
项目:msf4j
阅读 31
收藏 0
点赞 0
评论 0
@Reference(
name = "exception-mapper",
service = ExceptionMapper.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
unbind = "removeExceptionMapper"
)
protected void addExceptionMapper(ExceptionMapper exceptionMapper, Map properties) {
}
MicroservicesServerSC.java 文件源码
项目:msf4j
阅读 27
收藏 0
点赞 0
评论 0
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));
}
}