com.sun.faces.spi.InjectionProviderFactory Maven / Gradle / Ivy
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.spi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Enumeration;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.URL;
import java.net.URLConnection;
import javax.faces.context.ExternalContext;
import javax.servlet.ServletContext;
import com.sun.faces.RIConstants;
import com.sun.faces.config.WebConfiguration;
import com.sun.faces.config.WebConfiguration.WebContextInitParameter;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.Util;
import com.sun.faces.vendor.WebContainerInjectionProvider;
import java.util.Collections;
/**
* A factory for creating InjectionProvider
* instances.
*/
public class InjectionProviderFactory {
/**
* Our no-op InjectionProvider
.
*/
private static final InjectionProvider NOOP_PROVIDER =
new NoopInjectionProvider();
private static final InjectionProvider GENERIC_WEB_PROVIDER =
new WebContainerInjectionProvider();
private static final String INJECTION_SERVICE =
"META-INF/services/com.sun.faces.spi.injectionprovider";
/**
* The system property that will be checked for alternate
* InjectionProvider
implementations.
*/
private static final String INJECTION_PROVIDER_PROPERTY =
RIConstants.FACES_PREFIX + "InjectionProvider";
private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger();
private static final String[] EMPTY_ARRAY = new String[] {};
/**
* Creates a new instance of the class specified by the
* com.sun.faces.InjectionProvider
system property.
* If this propery is not defined, then a default, no-op,
* InjectionProvider
will be returned.
*
* @param extContext ExteranlContext for the current request
*
* @return an implementation of the InjectionProvider
* interfaces
*/
public static InjectionProvider createInstance(ExternalContext extContext) {
String providerClass = findProviderClass(extContext);
InjectionProvider provider =
getProviderInstance(providerClass, extContext);
if (!NoopInjectionProvider.class.equals(provider.getClass())
&& !WebContainerInjectionProvider.class.equals(provider.getClass())) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"jsf.spi.injection.provider_configured",
new Object[]{provider.getClass().getName()});
}
return provider;
} else if (WebContainerInjectionProvider.class.equals(provider.getClass())) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("jsf.core.injection.provider_generic_web_configured");
}
return provider;
} else {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, "jsf.spi.injection.no_injection");
}
return provider;
}
}
private static InjectionProvider getProviderInstance(String className,
ExternalContext extContext) {
InjectionProvider provider = NOOP_PROVIDER;
if (className != null) {
try {
Class> clazz = Util.loadClass(className, InjectionProviderFactory.class);
if (implementsInjectionProvider(clazz)) {
try {
Constructor ctor = clazz.getConstructor(ServletContext.class);
return (InjectionProvider)
ctor.newInstance((ServletContext) extContext.getContext());
} catch (NoSuchMethodException nsme) {
return (InjectionProvider) clazz.newInstance();
} catch (InvocationTargetException ite) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider_cannot_instantiate",
new Object[]{className});
LOGGER.log(Level.SEVERE, "", ite);
}
}
} else {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider_not_implemented",
new Object[]{ className });
}
}
} catch (ClassNotFoundException cnfe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider_not_found",
new Object[]{ className });
}
} catch (InstantiationException ie) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider_cannot_instantiate",
new Object[]{className});
LOGGER.log(Level.SEVERE, "", ie);
}
} catch (IllegalAccessException iae) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider_cannot_instantiate",
new Object[]{className});
LOGGER.log(Level.SEVERE, "", iae);
}
}
}
// We weren't able to find a configured provider - check
// to see if the PostConstruct and PreDestroy annotations
// are available. If they are, then default to the
// WebContainerInjectionProvider, otherwise, use
// NoopInjectionProvider
if (NOOP_PROVIDER.equals(provider)) {
try {
if (Util.loadClass("javax.annotation.PostConstruct", null) != null
&& Util.loadClass("javax.annotation.PreDestroy", null) != null) {
provider = GENERIC_WEB_PROVIDER;
}
} catch (Exception e) {
provider = NOOP_PROVIDER;
}
}
return provider;
}
/**
*
Determine if the specified class implements the
* InjectionProvider
interfaces.
* @param clazz the class in question
* @return true
if clazz
implements
* the InjectionProvider
interface
*/
private static boolean implementsInjectionProvider(Class> clazz) {
return InjectionProvider.class.isAssignableFrom(clazz);
}
/**
* Determine if the specified class extends the
* DiscoverableInjectionProvider
interfaces.
* @param clazz the class in question
* @return true
if clazz
implements
* the InjectionProvider
interface
*/
private static boolean extendsDiscoverableInjectionProvider(Class> clazz) {
return DiscoverableInjectionProvider.class.isAssignableFrom(clazz);
}
/**
* Attempt to find an InjectionProvider
based on the following
* algorithm:
*
* - Check for an explicit configuration within the web.xml using
* the key
com.sun.faces.injectionProvider
. If found,
* return the value.
* - Check for a system property keyed by
com.sun.faces.InjectionProvider
.
* If found, return the value.
* - Check for entries within
META-INF/services/com.sun.faces.injectionprovider
.
* If entries are found and the entries extend DiscoverableInjectionProvider
,
* invoke isInjectionFeatureAvailable(String)
passing in the configured
* delegate. If isInjectionFeatureAvailable(String)
returns true
* return the service entry.
* - If no
InjectionProviders are found, return null
* Tries to find a provider class in a web context parameter. If not
* present it tries to find it as a System property. If still not found
* returns null.
*
*
* @param extContext The ExternalContext for this request
* @return The provider class name specified in the container configuration,
* or null
if not found.
*/
private static String findProviderClass(ExternalContext extContext) {
WebConfiguration webConfig = WebConfiguration.getInstance(extContext);
String provider = webConfig.getOptionValue(WebContextInitParameter.InjectionProviderClass);
if (provider != null) {
return provider;
} else {
provider = System.getProperty(INJECTION_PROVIDER_PROPERTY);
}
if (provider != null) {
return provider;
} else {
String[] serviceEntries = getServiceEntries();
if (serviceEntries.length > 0) {
for (int i = 0; i < serviceEntries.length; i++) {
provider = getProviderFromEntry(serviceEntries[i]);
if (provider != null) {
break;
}
}
} else {
return provider;
}
}
return provider;
}
private static String getProviderFromEntry(String entry) {
if (entry == null) {
return null;
}
String[] parts = Util.split(entry, ":");
if (parts.length != 2) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.invalid_service_entry",
new Object[] { entry });
}
return null;
}
try {
Class> clazz = Util.loadClass(parts[0], null);
if (extendsDiscoverableInjectionProvider(clazz)) {
if (DiscoverableInjectionProvider.isInjectionFeatureAvailable(parts[1])) {
return parts[0];
}
} else {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider.entry_not_discoverable",
new Object[] { parts[0] });
}
return null;
}
} catch (ClassNotFoundException cnfe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.injection.provider_not_found",
new Object[] { parts[0] });
}
return null;
}
return null;
}
private static String[] getServiceEntries() {
List results = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
return EMPTY_ARRAY;
}
Enumeration urls = null;
try {
urls = loader.getResources(INJECTION_SERVICE);
} catch (IOException ioe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
ioe.toString(),
ioe);
}
}
if (urls != null) {
InputStream input = null;
BufferedReader reader = null;
while (urls.hasMoreElements()) {
try {
if (results == null) {
results = new ArrayList();
}
URL url = urls.nextElement();
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
input = conn.getInputStream();
if (input != null) {
try {
reader =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
} catch (Exception e) {
reader =
new BufferedReader(new InputStreamReader(input));
}
for (String line = reader.readLine();
line != null;
line = reader.readLine()) {
results.add(line.trim());
}
}
} catch (Exception e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"jsf.spi.provider.cannot_read_service",
new Object[] { INJECTION_SERVICE });
LOGGER.log(Level.SEVERE,
e.toString(),
e);
}
} finally {
if (input != null) {
try {
input.close();
} catch (Exception ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception ignored) {
}
}
}
}
}
return ((results != null && !results.isEmpty())
? results.toArray(new String[results.size()])
: EMPTY_ARRAY);
}
/**
* A no-op implementation of InjectionProvider
which will
* be used when the #INJECTION_PROVIDER_PROPERTY is not specified or
* is invalid.
*/
private static final class NoopInjectionProvider implements InjectionProvider, AnnotationScanner {
/**
* This is a no-op.
* @param managedBean target ManagedBean
*/
public void inject(Object managedBean) { }
public Map> getAnnotatedClassesInCurrentModule(ServletContext extContext) throws InjectionProviderException {
return Collections.emptyMap();
}
/**
* This is a no-op.
* @param managedBean target ManagedBean
*/
public void invokePreDestroy(Object managedBean) { }
/**
* This is a no-op.
* @param managedBean target ManagedBean
*/
public void invokePostConstruct(Object managedBean)
throws InjectionProviderException { }
}
} // END InjectionProviderFactory