@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); }
@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(); }
@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)); } }
/** * 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); } }
@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()); }
@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); } }
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()); } }
@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()); } } }
@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; }
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(); }
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); } }); }); }
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); } } }
/** * 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; }
/** * 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()); }
@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)) )); }
@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() )); }
@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 )); }
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; }
/** * 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; }
@Reference( cardinality = MULTIPLE, policyOption = GREEDY, target = "(liferay.apio.architect.exception.mapper=true)" ) public void setExceptionMapper( ServiceReference<ExceptionMapper> serviceReference, ExceptionMapper exceptionMapper) { _exceptionMappers.add(exceptionMapper); }
@SuppressWarnings("unused") public void unsetExceptionMapper( ServiceReference<ExceptionMapper> serviceReference, ExceptionMapper exceptionMapper) { _exceptionMappers.remove(exceptionMapper); }
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()); }
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()); }
@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()); } }
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); }
Optional<ExceptionMapper> getExceptionMapper(Throwable throwable) { return exceptionMappers.entrySet(). stream(). filter(entry -> entry.getKey().isAssignableFrom(throwable.getClass())). findFirst(). flatMap(entry -> Optional.ofNullable(entry.getValue())); }
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); } }); }
@Reference( name = "exception-mapper", service = ExceptionMapper.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, unbind = "removeExceptionMapper" ) protected void addExceptionMapper(ExceptionMapper exceptionMapper, Map properties) { }
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)); } }
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)); } }
@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); }
private void removeExceptionMappers(Set<Object> items) { for (Iterator<Object> i = items.iterator(); i.hasNext();) { Object o = i.next(); if (o instanceof ExceptionMapper) i.remove(); } }
public DelayedTenacityConfiguredBundle(TenacityBundleConfigurationFactory<BreakerboxServiceConfiguration> tenacityBundleConfigurationFactory, Optional<HystrixCommandExecutionHook> hystrixCommandExecutionHook, Iterable<ExceptionMapper<? extends Throwable>> exceptionMappers, boolean usingTenacityCircuitBreakerHealthCheck, boolean usingAdminPort) { super(tenacityBundleConfigurationFactory, hystrixCommandExecutionHook, exceptionMappers, usingTenacityCircuitBreakerHealthCheck, usingAdminPort); }
@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); }
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; }
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; }
@Test public void shouldBuild() { TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder.newBuilder() .configurationFactory(CONFIGURATION_FACTORY) .build(); assertThat(bundle) .isEqualTo(new TenacityConfiguredBundle<>( CONFIGURATION_FACTORY, Optional.empty(), Collections.<ExceptionMapper<? extends Throwable>>emptyList())); }
@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)) )); }
@Override public Response toResponse(final RepositoryRuntimeException e) { final Throwable cause = e.getCause(); @SuppressWarnings("unchecked") final ExceptionMapper<Throwable> exceptionMapper = (ExceptionMapper<Throwable>) providers.getExceptionMapper(cause.getClass()); if (exceptionMapper != null) { return exceptionMapper.toResponse(cause); } LOGGER.error("Caught a repository exception: {}", e.getMessage()); debugException(this, cause, LOGGER); return serverError().entity(getStackTraceAsString(e)).type(TEXT_PLAIN_WITH_CHARSET).build(); }