Search in sources :

Example 6 with InjectionException

use of javax.enterprise.inject.InjectionException in project minijax by minijax.

the class EntityProvider method getImpl.

@SuppressWarnings("unchecked")
private T getImpl(final MinijaxRequestContext context, final InputStream entityStream) throws IOException {
    if (entityClass == String.class) {
        return (T) IOUtils.toString(entityStream, StandardCharsets.UTF_8);
    }
    if (entityClass == MultivaluedMap.class) {
        return (T) context.getForm().asForm().asMap();
    }
    final MediaType mediaType = consumesTypes != null && !consumesTypes.isEmpty() ? consumesTypes.get(0) : null;
    final MessageBodyReader<T> reader = context.getApplication().getProviders().getMessageBodyReader(entityClass, genericType, annotations, mediaType);
    if (reader != null) {
        final MultivaluedMap<String, String> httpHeaders = context.getHeaders();
        return reader.readFrom(entityClass, genericType, annotations, mediaType, httpHeaders, entityStream);
    }
    throw new InjectionException("Unknown entity type (" + entityClass + ")");
}
Also used : InjectionException(javax.enterprise.inject.InjectionException) MediaType(javax.ws.rs.core.MediaType)

Example 7 with InjectionException

use of javax.enterprise.inject.InjectionException in project tomee by apache.

the class CxfRsHttpListener method deployApplication.

@Override
public void deployApplication(final Application application, final String prefix, final String webContext, final Collection<Object> additionalProviders, final Map<String, EJBRestServiceInfo> restEjbs, final ClassLoader classLoader, final Collection<Injection> injections, final Context context, final WebBeansContext owbCtx, final ServiceConfiguration serviceConfiguration) {
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
    try {
        final ApplicationData applicationData = getApplicationData(application, prefix, additionalProviders);
        logApplication(applicationData);
        if (applicationData.getResources().size() == 0) {
            throw new NoResourcesFoundException(applicationData);
        }
        final JAXRSServerFactoryBean factory = newFactory(prefix, createServiceJmxName(classLoader), createEndpointName(application));
        configureFactory(additionalProviders, serviceConfiguration, factory, owbCtx, application);
        factory.setApplication(application);
        final List<Class<?>> classes = new ArrayList<>();
        for (final Class<?> clazz : application.getClasses()) {
            if (!additionalProviders.contains(clazz) && !clazz.isInterface()) {
                classes.add(clazz);
                final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
                if (restServiceInfo != null) {
                    final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
                    factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
                } else {
                    if (owbCtx != null) {
                        final BeanManagerImpl bm = owbCtx.getBeanManagerImpl();
                        Bean<?> bean = null;
                        if (bm != null && bm.isInUse()) {
                            try {
                                final Set<Bean<?>> beans = bm.getBeans(clazz);
                                bean = bm.resolve(beans);
                            } catch (final InjectionException ie) {
                                final String msg = "Resource class " + clazz.getName() + " can not be instantiated";
                                LOGGER.warning(msg, ie);
                                throw new WebApplicationException(Response.serverError().entity(msg).build());
                            }
                            if (bean != null && isConsideredSingleton(bean.getScope())) {
                                final Object reference = bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean));
                                factory.setResourceProvider(clazz, new CdiSingletonResourceProvider(classLoader, clazz, reference, injections, context, owbCtx));
                                continue;
                            }
                        }
                    }
                    factory.setResourceProvider(clazz, new OpenEJBPerRequestPojoResourceProvider(classLoader, clazz, injections, context, owbCtx));
                }
            }
        }
        for (final Object o : application.getSingletons()) {
            if (!additionalProviders.contains(o)) {
                final Class<?> clazz = realClass(o.getClass());
                classes.add(clazz);
                final EJBRestServiceInfo restServiceInfo = getEjbRestServiceInfo(restEjbs, clazz);
                if (restServiceInfo != null) {
                    final Object proxy = ProxyEJB.subclassProxy(restServiceInfo.context);
                    factory.setResourceProvider(clazz, new NoopResourceProvider(restServiceInfo.context.getBeanClass(), proxy));
                } else {
                    if (owbCtx != null && owbCtx.getBeanManagerImpl().isInUse()) {
                        final CdiSingletonResourceProvider provider = new CdiSingletonResourceProvider(classLoader, clazz, o, injections, context, owbCtx);
                        singletons.add(provider);
                        factory.setResourceProvider(clazz, provider);
                    } else {
                        factory.setResourceProvider(clazz, new SingletonResourceProvider(o));
                    }
                }
            }
        }
        factory.setResourceClasses(classes);
        factory.setInvoker(new AutoJAXRSInvoker(restEjbs));
        injectApplication(application, factory);
        /*
             * During setApplication CXF will inspect the binding annotations
             * on the Application subclass and apply them to every Resource class
             * definition.  This is how global bindings are supported.  Thus, if
             * setApplication is called before we've called setResourceClasses()
             * binding annotations on the Application subclass will not work.
             *
             * Global binding annotations are tested in:
             * com/sun/ts/tests/jaxrs/spec/filter/globalbinding/JAXRSClient#globalBoundResourceTest_from_standalone
             */
        factory.setApplication(application);
        this.context = webContext;
        if (!webContext.startsWith("/")) {
            this.context = "/" + webContext;
        }
        // /webcontext/servlet for event firing
        final Level level = SERVER_IMPL_LOGGER.getLevel();
        try {
            SERVER_IMPL_LOGGER.setLevel(Level.OFF);
        } catch (final UnsupportedOperationException e) {
        // ignore
        }
        try {
            factory.setProvider(new SseContextProvider());
            factory.setProvider(new TomEESseEventSinkContextProvider());
            server = factory.create();
            fixProviders(serviceConfiguration);
            fireServerCreated(oldLoader);
            final ServerProviderFactory spf = ServerProviderFactory.class.cast(server.getEndpoint().get(ServerProviderFactory.class.getName()));
            LOGGER.info("Using readers:");
            for (final Object provider : List.class.cast(Reflections.get(spf, "messageReaders"))) {
                LOGGER.info("     " + ProviderInfo.class.cast(provider).getProvider());
            }
            LOGGER.info("Using writers:");
            for (final Object provider : List.class.cast(Reflections.get(spf, "messageWriters"))) {
                LOGGER.info("     " + ProviderInfo.class.cast(provider).getProvider());
            }
            LOGGER.info("Using exception mappers:");
            for (final Object provider : List.class.cast(Reflections.get(spf, "exceptionMappers"))) {
                LOGGER.info("     " + ProviderInfo.class.cast(provider).getProvider());
            }
        } finally {
            try {
                SERVER_IMPL_LOGGER.setLevel(level);
            } catch (final UnsupportedOperationException e) {
            // ignore
            }
        }
        final int servletIdx = 1 + this.context.substring(1).indexOf('/');
        if (servletIdx > 0) {
            this.servlet = this.context.substring(servletIdx);
            this.context = this.context.substring(0, servletIdx);
        }
        destination = (HttpDestination) server.getDestination();
        final String base;
        if (prefix.endsWith("/")) {
            base = prefix.substring(0, prefix.length() - 1);
        } else if (prefix.endsWith(wildcard)) {
            base = prefix.substring(0, prefix.length() - wildcard.length());
        } else {
            base = prefix;
        }
        // stack info to log to get nice logs
        logEndpoints(application, prefix, restEjbs, factory, base);
    } finally {
        if (oldLoader != null) {
            CxfUtil.clearBusLoader(oldLoader);
        }
    }
}
Also used : ServerProviderFactory(org.apache.cxf.jaxrs.provider.ServerProviderFactory) WebApplicationException(javax.ws.rs.WebApplicationException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) EJBRestServiceInfo(org.apache.openejb.server.rest.EJBRestServiceInfo) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) MBean(org.apache.openejb.api.jmx.MBean) Bean(javax.enterprise.inject.spi.Bean) InjectionException(javax.enterprise.inject.InjectionException) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) SseContextProvider(org.apache.cxf.jaxrs.sse.SseContextProvider) TomEESseEventSinkContextProvider(org.apache.openejb.server.cxf.rs.sse.TomEESseEventSinkContextProvider) ManagedEndpoint(org.apache.cxf.endpoint.ManagedEndpoint) Endpoint(org.apache.cxf.endpoint.Endpoint) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) Level(java.util.logging.Level)

Example 8 with InjectionException

use of javax.enterprise.inject.InjectionException in project tomee by apache.

the class HandlerResolverImpl method buildHandlers.

private List<Handler> buildHandlers(final PortInfo portInfo, final HandlerChainData handlerChain) {
    if (!matchServiceName(portInfo, handlerChain.getServiceNamePattern()) || !matchPortName(portInfo, handlerChain.getPortNamePattern()) || !matchBinding(portInfo, handlerChain.getProtocolBindings())) {
        return Collections.emptyList();
    }
    final List<Handler> handlers = new ArrayList<>(handlerChain.getHandlers().size());
    for (final HandlerData handler : handlerChain.getHandlers()) {
        final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
        if (webBeansContext != null) {
            // cdi
            final BeanManagerImpl bm = webBeansContext.getBeanManagerImpl();
            if (bm.isInUse()) {
                try {
                    final Set<Bean<?>> beans = bm.getBeans(handler.getHandlerClass());
                    final Bean<?> bean = bm.resolve(beans);
                    if (bean != null) {
                        // proxy so faster to do it
                        final boolean normalScoped = bm.isNormalScope(bean.getScope());
                        final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
                        final Handler instance = Handler.class.cast(bm.getReference(bean, bean.getBeanClass(), creationalContext));
                        // hack for destroyHandlers()
                        handlers.add(instance);
                        handlerInstances.add(new InjectionProcessor<Handler>(instance, Collections.<Injection>emptySet(), null) {

                            @Override
                            public void preDestroy() {
                                if (!normalScoped) {
                                    creationalContext.release();
                                }
                            }
                        });
                        continue;
                    }
                } catch (final InjectionException ie) {
                    LOGGER.info(ie.getMessage(), ie);
                }
            }
        }
        try {
            // old way
            final Class<? extends Handler> handlerClass = handler.getHandlerClass().asSubclass(Handler.class);
            final InjectionProcessor<Handler> processor = new InjectionProcessor<>(handlerClass, injections, handler.getPostConstruct(), handler.getPreDestroy(), unwrap(context));
            processor.createInstance();
            processor.postConstruct();
            final Handler handlerInstance = processor.getInstance();
            handlers.add(handlerInstance);
            handlerInstances.add(processor);
        } catch (final Exception e) {
            throw new WebServiceException("Failed to instantiate handler", e);
        }
    }
    return handlers;
}
Also used : WebServiceException(javax.xml.ws.WebServiceException) ArrayList(java.util.ArrayList) LogicalHandler(javax.xml.ws.handler.LogicalHandler) Handler(javax.xml.ws.handler.Handler) Injection(org.apache.openejb.Injection) InjectionProcessor(org.apache.openejb.InjectionProcessor) InjectionException(javax.enterprise.inject.InjectionException) WebServiceException(javax.xml.ws.WebServiceException) Bean(javax.enterprise.inject.spi.Bean) InjectionException(javax.enterprise.inject.InjectionException) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl)

Example 9 with InjectionException

use of javax.enterprise.inject.InjectionException in project camel by apache.

the class CdiCamelBeanPostProcessor method injectFields.

protected void injectFields(final Object bean, final String beanName) {
    ReflectionHelper.doWithFields(bean.getClass(), field -> {
        PropertyInject propertyInject = field.getAnnotation(PropertyInject.class);
        if (propertyInject != null) {
            try {
                injectFieldProperty(field, propertyInject.value(), propertyInject.defaultValue(), propertyInject.context(), bean, beanName);
            } catch (Exception cause) {
                throw new InjectionException("Injection of [" + propertyInject + "] for field [" + field + "] failed!", cause);
            }
        }
        BeanInject beanInject = field.getAnnotation(BeanInject.class);
        if (beanInject != null && getPostProcessorHelper().matchContext(beanInject.context())) {
            try {
                injectFieldBean(field, beanInject.value(), bean, beanName);
            } catch (Exception cause) {
                throw new InjectionException("Injection of [" + beanInject + "] for field [" + field + "] failed!", cause);
            }
        }
        EndpointInject endpointInject = field.getAnnotation(EndpointInject.class);
        if (endpointInject != null) {
            try {
                injectField(field, endpointInject.uri(), endpointInject.ref(), endpointInject.property(), endpointInject.context(), bean, beanName);
            } catch (Exception cause) {
                throw new InjectionException("Injection of [" + endpointInject + "] for field [" + field + "] failed!", cause);
            }
        }
        Produce produce = field.getAnnotation(Produce.class);
        if (produce != null) {
            try {
                injectField(field, produce.uri(), produce.ref(), produce.property(), produce.context(), bean, beanName);
            } catch (Exception cause) {
                throw new InjectionException("Injection of [" + produce + "] for field [" + field + "] failed!", cause);
            }
        }
    });
}
Also used : InjectionException(javax.enterprise.inject.InjectionException) EndpointInject(org.apache.camel.EndpointInject) BeanInject(org.apache.camel.BeanInject) Produce(org.apache.camel.Produce) PropertyInject(org.apache.camel.PropertyInject) UnsatisfiedResolutionException(javax.enterprise.inject.UnsatisfiedResolutionException) InjectionException(javax.enterprise.inject.InjectionException)

Example 10 with InjectionException

use of javax.enterprise.inject.InjectionException in project camel by apache.

the class CamelBeanInjectionTarget method inject.

@Override
public void inject(T instance, CreationalContext<T> ctx) {
    super.inject(instance, ctx);
    try {
        // TODO: see how to retrieve the bean name
        processor.postProcessBeforeInitialization(instance, instance.getClass().getName());
        processor.postProcessAfterInitialization(instance, instance.getClass().getName());
    } catch (Exception cause) {
        throw new InjectionException("Camel annotations post processing of [" + delegate + "] failed!", cause);
    }
}
Also used : InjectionException(javax.enterprise.inject.InjectionException) InjectionException(javax.enterprise.inject.InjectionException)

Aggregations

InjectionException (javax.enterprise.inject.InjectionException)12 UnsatisfiedResolutionException (javax.enterprise.inject.UnsatisfiedResolutionException)3 ArrayList (java.util.ArrayList)2 Bean (javax.enterprise.inject.spi.Bean)2 CamelContext (org.apache.camel.CamelContext)2 Endpoint (org.apache.camel.Endpoint)2 FluentProducerTemplate (org.apache.camel.FluentProducerTemplate)2 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)2 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)2 DefaultCamelContextNameStrategy (org.apache.camel.impl.DefaultCamelContextNameStrategy)2 BeanManagerImpl (org.apache.webbeans.container.BeanManagerImpl)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Annotation (java.lang.annotation.Annotation)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 Level (java.util.logging.Level)1 CreationException (javax.enterprise.inject.CreationException)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 MediaType (javax.ws.rs.core.MediaType)1