Search in sources :

Example 1 with InjectionProvider

use of com.sun.faces.spi.InjectionProvider in project mojarra by eclipse-ee4j.

the class AbstractConfigProcessor method createInstance.

protected Object createInstance(ServletContext sc, FacesContext facesContext, String className, Class<?> rootType, Object root, Node source, boolean performInjection, boolean[] didPerformInjection) {
    Class<?> clazz;
    Object returnObject = null;
    if (className != null) {
        try {
            clazz = loadClass(sc, facesContext, className, returnObject, null);
            if (clazz != null) {
                if (returnObject == null) {
                    // an object to adapt
                    if (rootType != null && root != null) {
                        Constructor<?> construct = lookupConstructor(clazz, rootType);
                        if (construct != null) {
                            returnObject = construct.newInstance(root);
                        }
                    }
                }
                if (clazz != null && returnObject == null) {
                    returnObject = clazz.newInstance();
                }
                ApplicationInstanceFactoryMetadataMap<String, Object> classMetadataMap = getClassMetadataMap(sc);
                if (classMetadataMap.hasAnnotations(className) && performInjection) {
                    InjectionProvider injectionProvider = (InjectionProvider) facesContext.getAttributes().get(INJECTION_PROVIDER_KEY);
                    try {
                        injectionProvider.inject(returnObject);
                    } catch (InjectionProviderException ex) {
                        LOGGER.log(SEVERE, "Unable to inject instance" + className, ex);
                        throw new FacesException(ex);
                    }
                    try {
                        injectionProvider.invokePostConstruct(returnObject);
                    } catch (InjectionProviderException ex) {
                        LOGGER.log(SEVERE, "Unable to invoke @PostConstruct annotated method on instance " + className, ex);
                        throw new FacesException(ex);
                    }
                    didPerformInjection[0] = true;
                }
            }
        } catch (ClassNotFoundException cnfe) {
            throw new ConfigurationException(buildMessage(format("Unable to find class ''{0}''", className), source), cnfe);
        } catch (NoClassDefFoundError ncdfe) {
            throw new ConfigurationException(buildMessage(format("Class ''{0}'' is missing a runtime dependency: {1}", className, ncdfe.toString()), source), ncdfe);
        } catch (ClassCastException cce) {
            throw new ConfigurationException(buildMessage(format("Class ''{0}'' is not an instance of ''{1}''", className, rootType), source), cce);
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | FacesException e) {
            throw new ConfigurationException(buildMessage(format("Unable to create a new instance of ''{0}'': {1}", className, e.toString()), source), e);
        }
    }
    return returnObject;
}
Also used : InjectionProviderException(com.sun.faces.spi.InjectionProviderException) InjectionProvider(com.sun.faces.spi.InjectionProvider) FacesException(jakarta.faces.FacesException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConfigurationException(com.sun.faces.config.ConfigurationException)

Example 2 with InjectionProvider

use of com.sun.faces.spi.InjectionProvider in project mojarra by eclipse-ee4j.

the class FactoryFinderInstance method injectImplementation.

private void injectImplementation(String implementationName, Object implementation) {
    if (implementation != null) {
        InjectionProvider provider = getInjectionProvider();
        if (provider != null) {
            try {
                provider.inject(implementation);
                provider.invokePostConstruct(implementation);
            } catch (Exception e) {
                throw new FacesException(implementationName, e);
            }
        } else {
            LOGGER.log(SEVERE, "Unable to inject {0} because no InjectionProvider can be found. Does this container implement the Mojarra Injection SPI?", implementation);
        }
    }
}
Also used : InjectionProvider(com.sun.faces.spi.InjectionProvider) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 3 with InjectionProvider

use of com.sun.faces.spi.InjectionProvider in project mojarra by eclipse-ee4j.

the class ConfigManager method initialize.

// ---------------------------------------------------------- Public instance Methods
/**
 * <p>
 * This method bootstraps Faces based on the parsed configuration resources.
 * </p>
 *
 * @param servletContext the <code>ServletContext</code> for the application that requires initialization
 * @param facesContext the involved initialization faces context
 */
public void initialize(ServletContext servletContext, InitFacesContext facesContext) {
    if (!hasBeenInitialized(servletContext)) {
        initializedContexts.add(servletContext);
        initializeConfigProcessers(servletContext, facesContext);
        ExecutorService executor = null;
        try {
            WebConfiguration webConfig = WebConfiguration.getInstance(servletContext);
            boolean validating = webConfig.isOptionEnabled(ValidateFacesConfigFiles);
            if (useThreads(servletContext)) {
                executor = createExecutorService();
            }
            // Obtain and merge the XML and Programmatic documents
            DocumentInfo[] facesDocuments = mergeDocuments(getXMLDocuments(servletContext, getFacesConfigResourceProviders(), executor, validating), getProgrammaticDocuments(getConfigPopulators()));
            FacesConfigInfo lastFacesConfigInfo = new FacesConfigInfo(facesDocuments[facesDocuments.length - 1]);
            facesDocuments = sortDocuments(facesDocuments, lastFacesConfigInfo);
            InjectionProvider containerConnector = InjectionProviderFactory.createInstance(facesContext.getExternalContext());
            facesContext.getAttributes().put(INJECTION_PROVIDER_KEY, containerConnector);
            if (!lastFacesConfigInfo.isWebInfFacesConfig() || !lastFacesConfigInfo.isMetadataComplete()) {
                findAnnotations(facesDocuments, containerConnector, servletContext, facesContext, executor);
            }
            // See if the app is running in a HA enabled env
            if (containerConnector instanceof HighAvailabilityEnabler) {
                ((HighAvailabilityEnabler) containerConnector).enableHighAvailability(servletContext);
            }
            // Process the ordered and merged documents
            // This invokes a chain or processors where each processor grabs its own elements of interest
            // from each document.
            DocumentInfo[] facesDocuments2 = facesDocuments;
            configProcessors.subList(0, 3).stream().forEach(e -> {
                try {
                    e.process(servletContext, facesContext, facesDocuments2);
                } catch (Exception e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
            });
            long parentThreadId = Thread.currentThread().getId();
            ClassLoader parentContextClassLoader = Thread.currentThread().getContextClassLoader();
            ThreadContext threadContext = getThreadContext(containerConnector);
            Object parentWebContext = threadContext != null ? threadContext.getParentWebContext() : null;
            configProcessors.subList(3, configProcessors.size()).stream().forEach(e -> {
                long currentThreadId = Thread.currentThread().getId();
                InitFacesContext initFacesContext = null;
                if (currentThreadId != parentThreadId) {
                    Thread.currentThread().setContextClassLoader(parentContextClassLoader);
                    initFacesContext = InitFacesContext.getInstance(servletContext);
                    if (parentWebContext != null) {
                        threadContext.propagateWebContextToChild(parentWebContext);
                    }
                } else {
                    initFacesContext = facesContext;
                }
                try {
                    e.process(servletContext, initFacesContext, facesDocuments2);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } finally {
                    if (currentThreadId != parentThreadId) {
                        Thread.currentThread().setContextClassLoader(null);
                        if (parentWebContext != null) {
                            threadContext.clearChildContext();
                        }
                    }
                }
            });
            faceletTaglibConfigProcessor.process(servletContext, facesContext, getXMLDocuments(servletContext, getFaceletConfigResourceProviders(), executor, validating));
        } catch (Exception e) {
            // Clear out any configured factories
            releaseFactories();
            Throwable t = e;
            if (!(e instanceof ConfigurationException)) {
                t = new ConfigurationException("CONFIGURATION FAILED! " + t.getMessage(), t);
            }
            throw (ConfigurationException) t;
        } finally {
            if (executor != null) {
                executor.shutdown();
            }
            servletContext.removeAttribute(ANNOTATIONS_SCAN_TASK_KEY);
        }
    }
    DbfFactory.removeSchemaMap(servletContext);
}
Also used : FacesConfigInfo(com.sun.faces.config.manager.FacesConfigInfo) InjectionProvider(com.sun.faces.spi.InjectionProvider) ThreadContext(com.sun.faces.spi.ThreadContext) HighAvailabilityEnabler(com.sun.faces.spi.HighAvailabilityEnabler) NamingException(javax.naming.NamingException) FacesException(jakarta.faces.FacesException) ExecutionException(java.util.concurrent.ExecutionException) ExecutorService(java.util.concurrent.ExecutorService) DocumentInfo(com.sun.faces.config.manager.documents.DocumentInfo)

Example 4 with InjectionProvider

use of com.sun.faces.spi.InjectionProvider in project mojarra by eclipse-ee4j.

the class FactoryFinderInstance method releaseFactories.

void releaseFactories() {
    InjectionProvider provider = getInjectionProvider();
    if (provider != null) {
        lock.writeLock().lock();
        try {
            for (Entry<String, Object> entry : factories.entrySet()) {
                Object curFactory = entry.getValue();
                // and the value is not a string...
                if (!INJECTION_PROVIDER_KEY.equals(entry.getKey()) && curFactory != null && !(curFactory instanceof String)) {
                    try {
                        provider.invokePreDestroy(curFactory);
                    } catch (Exception ex) {
                        logPreDestroyFail(entry.getValue(), ex);
                    }
                }
            }
        } finally {
            factories.clear();
            lock.writeLock().unlock();
        }
    } else {
        LOGGER.log(SEVERE, "Unable to call @PreDestroy annotated methods because no InjectionProvider can be found. Does this container implement the Mojarra Injection SPI?");
    }
}
Also used : InjectionProvider(com.sun.faces.spi.InjectionProvider) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Aggregations

InjectionProvider (com.sun.faces.spi.InjectionProvider)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 FacesException (jakarta.faces.FacesException)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ConfigurationException (com.sun.faces.config.ConfigurationException)1 FacesConfigInfo (com.sun.faces.config.manager.FacesConfigInfo)1 DocumentInfo (com.sun.faces.config.manager.documents.DocumentInfo)1 HighAvailabilityEnabler (com.sun.faces.spi.HighAvailabilityEnabler)1 InjectionProviderException (com.sun.faces.spi.InjectionProviderException)1 ThreadContext (com.sun.faces.spi.ThreadContext)1 ExecutionException (java.util.concurrent.ExecutionException)1 ExecutorService (java.util.concurrent.ExecutorService)1 NamingException (javax.naming.NamingException)1