View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.spi.impl;
20  
21  import java.lang.reflect.InvocationTargetException;
22  import java.security.AccessController;
23  import java.security.PrivilegedActionException;
24  import java.util.Iterator;
25  import java.util.List;
26  import java.util.logging.Level;
27  import java.util.logging.Logger;
28  
29  import javax.faces.FacesException;
30  import javax.faces.context.ExternalContext;
31  import javax.faces.context.FacesContext;
32  import javax.naming.Context;
33  import javax.naming.InitialContext;
34  import javax.naming.NamingException;
35  
36  import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFWebConfigParam;
37  import org.apache.myfaces.shared.util.ClassUtils;
38  import org.apache.myfaces.spi.InjectionProvider;
39  import org.apache.myfaces.spi.InjectionProviderFactory;
40  import org.apache.myfaces.spi.ServiceProviderFinderFactory;
41  
42  /**
43   * 
44   * 
45   */
46  public class DefaultInjectionProviderFactory extends InjectionProviderFactory
47  {
48      //private static Log log = LogFactory.getLog(DefaultLifecycleProviderFactory.class);
49      private static Logger log = Logger.getLogger(DefaultInjectionProviderFactory.class.getName());
50  
51      /**
52       * Define the class implementing InjectionProvider interface to handle PostConstruct 
53       * and PreDestroy annotations.
54       * 
55       * <p>This also can be configured using a SPI entry (/META-INF/services/...).
56       * </p>
57       */
58      public static final String INJECTION_PROVIDER_INSTANCE_KEY
59              = InjectionProvider.class.getName() + ".INJECTION_PROVIDER_INSTANCE";
60  
61      @JSFWebConfigParam(name="org.apache.myfaces.spi.InjectionProvider", since="2.2")
62      public static final String INJECTION_PROVIDER = InjectionProvider.class.getName();
63  
64  
65      public DefaultInjectionProviderFactory()
66      {
67      }
68  
69      @Override
70      public InjectionProvider getInjectionProvider(ExternalContext externalContext)
71      {
72          InjectionProvider lifecycleProvider = null;
73          if (externalContext == null)
74          {
75              // Really in jsf 2.0, this will not happen, because a Startup/Shutdown
76              // FacesContext and ExternalContext are provided on initialization and shutdown,
77              // and in other scenarios the real FacesContext/ExternalContext is provided.
78              log.info("No ExternalContext using fallback InjectionProvider.");
79              lifecycleProvider = resolveFallbackInjectionProvider();
80          }
81          else
82          {
83              lifecycleProvider = (InjectionProvider)
84                      externalContext.getApplicationMap().get(INJECTION_PROVIDER_INSTANCE_KEY);
85          }
86          if (lifecycleProvider == null)
87          {
88              if (!resolveInjectionProviderFromExternalContext(externalContext))
89              {
90                  if (!resolveInjectionProviderFromService(externalContext))
91                  {
92                      lifecycleProvider = resolveFallbackInjectionProvider();
93                      externalContext.getApplicationMap().put(INJECTION_PROVIDER_INSTANCE_KEY, lifecycleProvider);
94                  }
95                  else
96                  {
97                      //Retrieve it because it was resolved
98                      lifecycleProvider = (InjectionProvider)
99                              externalContext.getApplicationMap().get(INJECTION_PROVIDER_INSTANCE_KEY);
100                 }
101             }
102             else
103             {
104                 //Retrieve it because it was resolved
105                 lifecycleProvider = (InjectionProvider)
106                         externalContext.getApplicationMap().get(INJECTION_PROVIDER_INSTANCE_KEY);
107             }
108             log.info("Using InjectionProvider "+ lifecycleProvider.getClass().getName());
109         }
110         return lifecycleProvider;
111     }
112 
113     @Override
114     public void release()
115     {
116     }
117 
118 
119 
120     private boolean resolveInjectionProviderFromExternalContext(ExternalContext externalContext)
121     {
122         try
123         {
124             String lifecycleProvider = externalContext.getInitParameter(INJECTION_PROVIDER);
125             if (lifecycleProvider != null)
126             {
127 
128                 Object obj = createClass(lifecycleProvider, externalContext);
129 
130                 if (obj instanceof InjectionProvider)
131                 {
132                     externalContext.getApplicationMap().put(INJECTION_PROVIDER_INSTANCE_KEY, obj);
133                     return true;
134                 }
135             }
136         }
137         catch (ClassNotFoundException e)
138         {
139             log.log(Level.SEVERE, "", e);
140         }
141         catch (InstantiationException e)
142         {
143             log.log(Level.SEVERE, "", e);
144         }
145         catch (IllegalAccessException e)
146         {
147             log.log(Level.SEVERE, "", e);
148         }
149         catch (InvocationTargetException e)
150         {
151             log.log(Level.SEVERE, "", e);
152         }
153         return false;
154     }
155 
156 
157     private boolean resolveInjectionProviderFromService(
158             ExternalContext externalContext)
159     {
160         boolean returnValue = false;
161         final ExternalContext extContext = externalContext;
162         try
163         {
164             if (System.getSecurityManager() != null)
165             {
166                 returnValue = AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<Boolean>()
167                         {
168                             public Boolean run() throws ClassNotFoundException,
169                                     NoClassDefFoundError,
170                                     InstantiationException,
171                                     IllegalAccessException,
172                                     InvocationTargetException,
173                                     PrivilegedActionException
174                             {
175                                 List<String> classList
176                                         = ServiceProviderFinderFactory.getServiceProviderFinder(extContext).
177                                                                        getServiceProviderList(INJECTION_PROVIDER);
178                                 Iterator<String> iter = classList.iterator();
179                                 while (iter.hasNext())
180                                 {
181                                     String className = iter.next();
182                                     Object obj = createClass(className,extContext);
183                                     if (InjectionProvider.class.isAssignableFrom(obj.getClass()))
184                                     {
185                                         InjectionProvider discoverableInjectionProvider =
186                                                 (InjectionProvider) obj;
187                                         if (discoverableInjectionProvider.isAvailable())
188                                         {
189                                             extContext.getApplicationMap().put(INJECTION_PROVIDER_INSTANCE_KEY,
190                                                                                discoverableInjectionProvider);
191                                             return true;
192                                         }
193                                     }
194                                 }
195                                 return false;
196                             }
197                         });
198             }
199             else
200             {
201                 List<String> classList = ServiceProviderFinderFactory.getServiceProviderFinder(extContext).
202                         getServiceProviderList(INJECTION_PROVIDER);
203                 Iterator<String> iter = classList.iterator();
204                 while (iter.hasNext())
205                 {
206                     String className = iter.next();
207                     Object obj = createClass(className,extContext);
208                     if (InjectionProvider.class.isAssignableFrom(obj.getClass()))
209                     {
210                         InjectionProvider discoverableInjectionProvider
211                                 = (InjectionProvider) obj;
212                         if (discoverableInjectionProvider.isAvailable())
213                         {
214                             extContext.getApplicationMap().put(INJECTION_PROVIDER_INSTANCE_KEY,
215                                                                discoverableInjectionProvider);
216                             return (Boolean) true;
217                         }
218                     }
219                 }
220             }
221         }
222         catch (ClassNotFoundException e)
223         {
224             // ignore
225         }
226         catch (NoClassDefFoundError e)
227         {
228             // ignore
229         }
230         catch (InstantiationException e)
231         {
232             log.log(Level.SEVERE, "", e);
233         }
234         catch (IllegalAccessException e)
235         {
236             log.log(Level.SEVERE, "", e);
237         }
238         catch (InvocationTargetException e)
239         {
240             log.log(Level.SEVERE, "", e);
241         }
242         catch (PrivilegedActionException e)
243         {
244             throw new FacesException(e);
245         }
246         return returnValue;
247     }
248 
249     private Object createClass(String className, ExternalContext externalContext)
250             throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException
251     {
252         Class<?> clazz = ClassUtils.classForName(className);
253 
254         try
255         {
256             return ClassUtils.newInstance(clazz, new Class<?>[]{ ExternalContext.class }, externalContext);
257         }
258         catch (NoSuchMethodException e)
259         {
260             return ClassUtils.newInstance(clazz);
261         }
262     }
263 
264     private InjectionProvider resolveFallbackInjectionProvider()
265     {
266         return resolveFallbackInjectionProvider(FacesContext.getCurrentInstance().getExternalContext());
267     }
268 
269     private InjectionProvider resolveFallbackInjectionProvider(ExternalContext externalContext)
270     {
271         /* Added entry in META-INF/services/org.apache.myfaces.spi.InjectionProvider to
272          * give precedence to CDI integration instead server integration.
273         if (ExternalSpecifications.isCDIAvailable(externalContext))
274         {
275             try
276             {
277                 Class clazz = ClassUtils.simpleClassForName(
278                     "org.apache.myfaces.cdi.impl.CDIAnnotationInjectionProvider");
279                 return (InjectionProvider) clazz.getConstructor(
280                     ExternalContext.class).newInstance(externalContext);
281             }
282             catch(Exception e)
283             {
284                 //Ignore
285             }
286         }
287         */
288         
289         try
290         {
291             ClassUtils.classForName("javax.annotation.PreDestroy");
292         }
293         catch (ClassNotFoundException e)
294         {
295             // no annotation available don't process annotations
296             return new NoAnnotationInjectionProvider(); 
297         }
298         Context context;
299         try
300         {
301             context = new InitialContext();
302             try
303             {
304                 ClassUtils.classForName("javax.ejb.EJB");
305                 // Asume full JEE 5 container
306                 return new AllAnnotationInjectionProvider(context);
307             }
308             catch (ClassNotFoundException e)
309             {
310                 // something else
311                 return new ResourceAnnotationInjectionProvider(context);
312             }
313         }
314         catch (NamingException e)
315         {
316             // no initial context available no injection
317             log.log(Level.SEVERE, "No InitialContext found. Using NoInjectionAnnotationProcessor.", e);
318             return new NoInjectionAnnotationInjectionProvider();
319         }
320         catch (NoClassDefFoundError e)
321         {
322             //On Google App Engine, javax.naming.Context is a restricted class.
323             //In that case, NoClassDefFoundError is thrown. stageName needs to be configured
324             //below by context parameter.
325             log.log(Level.SEVERE, "No InitialContext class definition found. Using NoInjectionAnnotationProcessor.");
326             return new NoInjectionAnnotationInjectionProvider();
327         }
328     }
329 }