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.view.facelets.impl;
20  
21  import java.io.FileNotFoundException;
22  import java.io.IOException;
23  import java.lang.reflect.Method;
24  import java.net.URL;
25  import java.net.URLConnection;
26  import java.util.HashMap;
27  import java.util.Map;
28  import java.util.logging.Level;
29  import java.util.logging.Logger;
30  import java.util.regex.Pattern;
31  
32  import javax.el.ELException;
33  import javax.faces.FacesException;
34  import javax.faces.FactoryFinder;
35  import javax.faces.view.facelets.FaceletCache;
36  import javax.faces.view.facelets.FaceletCacheFactory;
37  import javax.faces.view.facelets.FaceletContext;
38  import javax.faces.view.facelets.FaceletException;
39  import javax.faces.view.facelets.FaceletHandler;
40  import javax.faces.view.facelets.ResourceResolver;
41  
42  import org.apache.myfaces.shared.resource.ResourceLoaderUtils;
43  import org.apache.myfaces.view.facelets.AbstractFaceletCache;
44  import org.apache.myfaces.view.facelets.Facelet;
45  import org.apache.myfaces.view.facelets.FaceletFactory;
46  import org.apache.myfaces.view.facelets.compiler.Compiler;
47  import org.apache.myfaces.view.facelets.util.ParameterCheck;
48  
49  /**
50   * Default FaceletFactory implementation.
51   * 
52   * @author Jacob Hookom
53   * @version $Id: DefaultFaceletFactory.java 1470662 2013-04-22 19:04:45Z lu4242 $
54   */
55  public final class DefaultFaceletFactory extends FaceletFactory
56  {
57      private static final long INFINITE_DELAY = -1;
58      private static final long NO_CACHE_DELAY = 0;
59      
60      //protected final Log log = LogFactory.getLog(DefaultFaceletFactory.class);
61      protected final Logger log = Logger.getLogger(DefaultFaceletFactory.class.getName());
62  
63      private URL _baseUrl;
64  
65      private Compiler _compiler;
66      
67      //private Map<String, DefaultFacelet> _facelets;
68      
69      //private Map<String, DefaultFacelet> _viewMetadataFacelets;
70      
71      private Map<String, DefaultFacelet> _compositeComponentMetadataFacelets;
72  
73      private long _refreshPeriod;
74  
75      private Map<String, URL> _relativeLocations;
76  
77      private javax.faces.view.facelets.ResourceResolver _resolver;
78      
79      private FaceletCache<Facelet> _faceletCache;
80      private AbstractFaceletCache<Facelet> _abstractFaceletCache;
81      
82      public DefaultFaceletFactory(Compiler compiler, ResourceResolver resolver) throws IOException
83      {
84          this(compiler, resolver, -1);
85      }
86  
87      public DefaultFaceletFactory(Compiler compiler, ResourceResolver resolver, long refreshPeriod)
88      {
89          ParameterCheck.notNull("compiler", compiler);
90          ParameterCheck.notNull("resolver", resolver);
91  
92          _compiler = compiler;
93  
94          //_facelets = new HashMap<String, DefaultFacelet>();
95          
96          //_viewMetadataFacelets = new HashMap<String, DefaultFacelet>();
97          
98          _compositeComponentMetadataFacelets = new HashMap<String, DefaultFacelet>();
99  
100         _relativeLocations = new HashMap<String, URL>();
101 
102         _resolver = resolver;
103 
104         _baseUrl = resolver.resolveUrl("/");
105 
106         _refreshPeriod = refreshPeriod < 0 ? INFINITE_DELAY : refreshPeriod * 1000;
107         
108         // facelet cache. Lookup here, because after all this is a "part" of the facelet factory implementation.
109         FaceletCacheFactory cacheFactory
110                 = (FaceletCacheFactory) FactoryFinder.getFactory(FactoryFinder.FACELET_CACHE_FACTORY);
111         _faceletCache = (FaceletCache<Facelet>) cacheFactory.getFaceletCache();
112         
113         FaceletCache.MemberFactory<Facelet> faceletFactory = new FaceletCache.MemberFactory<Facelet>()
114         {
115             public Facelet newInstance(URL url) throws IOException
116             {
117                 return _createFacelet(url);
118             }
119         };
120         FaceletCache.MemberFactory<Facelet> viewMetadataFaceletFactory = new FaceletCache.MemberFactory<Facelet>()
121         {
122             public Facelet newInstance(URL url) throws IOException
123             {
124                 return _createViewMetadataFacelet(url);
125             }
126         };
127         
128         if (_faceletCache instanceof AbstractFaceletCache)
129         {
130             _abstractFaceletCache = (AbstractFaceletCache<Facelet>) _faceletCache;
131             
132             FaceletCache.MemberFactory<Facelet> compositeComponentMetadataFaceletFactory = 
133                 new FaceletCache.MemberFactory<Facelet>()
134             {
135                 public Facelet newInstance(URL url) throws IOException
136                 {
137                     return _createCompositeComponentMetadataFacelet(url);
138                 }
139             };
140 
141             try
142             {
143                 Method setMemberFactoriesMethod = AbstractFaceletCache.class.getDeclaredMethod("setMemberFactories",
144                         new Class[]{FaceletCache.MemberFactory.class, FaceletCache.MemberFactory.class, 
145                                     FaceletCache.MemberFactory.class});
146                 setMemberFactoriesMethod.setAccessible(true);
147                 setMemberFactoriesMethod.invoke(_faceletCache, faceletFactory, viewMetadataFaceletFactory, 
148                     compositeComponentMetadataFaceletFactory);
149             } 
150             catch (Exception e)
151             {
152                 throw new FacesException(
153                     "Cannot call setMemberFactories method, Initialization of FaceletCache failed.",
154                                          e);
155             }   
156         }
157         else
158         {
159             // Note that FaceletCache.setMemberFactories method is protected, and this is the place where call
160             // this method has sense, because DefaultFaceletFactory is the responsible to create Facelet instances.
161             // The only way to do it is using reflection, and it has sense, because in this way it is possible to
162             // setup a java SecurityManager that prevents call this method (because it is protected, and to do that
163             // the code first check for "suppressAccessChecks" permission).
164             try
165             {
166                 Method setMemberFactoriesMethod = FaceletCache.class.getDeclaredMethod("setMemberFactories",
167                         new Class[]{FaceletCache.MemberFactory.class, FaceletCache.MemberFactory.class});
168                 setMemberFactoriesMethod.setAccessible(true);
169                 setMemberFactoriesMethod.invoke(_faceletCache, faceletFactory, viewMetadataFaceletFactory);
170             } 
171             catch (Exception e)
172             {
173                 throw new FacesException(
174                     "Cannot call setMemberFactories method, Initialization of FaceletCache failed.",
175                                          e);
176             }            
177         }
178 
179         if (log.isLoggable(Level.FINE))
180         {
181             log.fine("Using ResourceResolver: " + _resolver);
182             log.fine("Using Refresh Period: " + _refreshPeriod);
183         }
184     }
185 
186     /**
187      * Compiler this factory uses
188      * 
189      * @return final Compiler instance
190      */
191     public Compiler getCompiler()
192     {
193         return _compiler;
194     }
195 
196     /*
197      * (non-Javadoc)
198      * 
199      * @see org.apache.myfaces.view.facelets.FaceletFactory#getFacelet(java.lang.String)
200      */
201     @Override
202     public Facelet getFacelet(String uri) throws IOException, FaceletException, FacesException, ELException
203     {
204         URL url = (URL) _relativeLocations.get(uri);
205         if (url == null)
206         {
207             url = resolveURL(_baseUrl, uri);
208             if (url != null)
209             {
210                 Map<String, URL> newLoc = new HashMap<String, URL>(_relativeLocations);
211                 newLoc.put(uri, url);
212                 _relativeLocations = newLoc;
213             }
214             else
215             {
216                 throw new IOException("'" + uri + "' not found.");
217             }
218         }
219         return this.getFacelet(url);
220     }
221 
222     /**
223      * Create a Facelet from the passed URL. This method checks if the cached Facelet needs to be refreshed before
224      * returning. If so, uses the passed URL to build a new instance;
225      * 
226      * @param url
227      *            source url
228      * @return Facelet instance
229      * @throws IOException
230      * @throws FaceletException
231      * @throws FacesException
232      * @throws ELException
233      */
234     @Override
235     public Facelet getFacelet(URL url) throws IOException, FaceletException, FacesException, ELException
236     {
237         return _faceletCache.getFacelet(url);
238     }
239     
240     
241     @Override
242     public Facelet getFacelet(FaceletContext ctx, URL url) 
243             throws IOException, FaceletException, FacesException, ELException
244     {
245         if (_abstractFaceletCache != null)
246         {
247             return _abstractFaceletCache.getFacelet(ctx, url);
248         }
249         else
250         {
251             return _faceletCache.getFacelet(url);
252         }
253     }
254 
255     public long getRefreshPeriod()
256     {
257         return _refreshPeriod;
258     }
259 
260     /**
261      * Resolves a path based on the passed URL. If the path starts with '/', then resolve the path against
262      * {@link javax.faces.context.ExternalContext#getResource(java.lang.String)
263      * javax.faces.context.ExternalContext#getResource(java.lang.String)}. Otherwise create a new URL via
264      * {@link URL#URL(java.net.URL, java.lang.String) URL(URL, String)}.
265      * 
266      * @param source
267      *            base to resolve from
268      * @param path
269      *            relative path to the source
270      * @return resolved URL
271      * @throws IOException
272      */
273     public URL resolveURL(URL source, String path) throws IOException
274     {
275         if (path.startsWith("/"))
276         {
277             URL url = _resolver.resolveUrl(path);
278             if (url == null)
279             {
280                 throw new FileNotFoundException(path + " Not Found in ExternalContext as a Resource");
281             }
282             return url;
283         }
284         else
285         {
286             return new URL(source, path);
287         }
288     }
289 
290     /**
291      * Template method for determining if the Facelet needs to be refreshed.
292      * 
293      * @param facelet
294      *            Facelet that could have expired
295      * @return true if it needs to be refreshed
296      */
297     protected boolean needsToBeRefreshed(DefaultFacelet facelet)
298     {
299         // if set to 0, constantly reload-- nocache
300         if (_refreshPeriod == NO_CACHE_DELAY)
301         {
302             return true;
303         }
304 
305         // if set to -1, never reload
306         if (_refreshPeriod == INFINITE_DELAY)
307         {
308             return false;
309         }
310 
311         long target = facelet.getCreateTime() + _refreshPeriod;
312         if (System.currentTimeMillis() > target)
313         {
314             // Should check for file modification
315 
316             try
317             {
318                 URLConnection conn = facelet.getSource().openConnection();
319                 long lastModified = ResourceLoaderUtils.getResourceLastModified(conn);
320 
321                 return lastModified == 0 || lastModified > target;
322             }
323             catch (IOException e)
324             {
325                 throw new FaceletException("Error Checking Last Modified for " + facelet.getAlias(), e);
326             }
327         }
328 
329         return false;
330     }
331 
332     /**
333      * Uses the internal Compiler reference to build a Facelet given the passed URL.
334      * 
335      * @param url
336      *            source
337      * @return a Facelet instance
338      * @throws IOException
339      * @throws FaceletException
340      * @throws FacesException
341      * @throws ELException
342      */
343     private DefaultFacelet _createFacelet(URL url) throws IOException, FaceletException, FacesException, ELException
344     {
345         if (log.isLoggable(Level.FINE))
346         {
347             log.fine("Creating Facelet for: " + url);
348         }
349 
350         String alias = "/" + _removeFirst(url.getFile(), _baseUrl.getFile());
351         try
352         {
353             FaceletHandler h = _compiler.compile(url, alias);
354             DefaultFacelet f = new DefaultFacelet(this, _compiler.createExpressionFactory(), url, alias, alias, h);
355             return f;
356         }
357         catch (FileNotFoundException fnfe)
358         {
359             throw new FileNotFoundException("Facelet " + alias + " not found at: " + url.toExternalForm());
360         }
361     }
362     
363     /**
364      * @since 2.0
365      * @param url
366      * @return
367      * @throws IOException
368      * @throws FaceletException
369      * @throws FacesException
370      * @throws ELException
371      */
372     private DefaultFacelet _createViewMetadataFacelet(URL url)
373             throws IOException, FaceletException, FacesException, ELException
374     {
375         if (log.isLoggable(Level.FINE))
376         {
377             log.fine("Creating Facelet used to create View Metadata for: " + url);
378         }
379 
380         // The alias is used later for informative purposes, so we append 
381         // some prefix to identify later where the errors comes from.
382         String faceletId = "/"+ _removeFirst(url.getFile(), _baseUrl.getFile());
383         String alias = "/viewMetadata" + faceletId;
384         try
385         {
386             FaceletHandler h = _compiler.compileViewMetadata(url, alias);
387             DefaultFacelet f = new DefaultFacelet(this, _compiler.createExpressionFactory(), url, alias, 
388                     faceletId, h);
389             return f;
390         }
391         catch (FileNotFoundException fnfe)
392         {
393             throw new FileNotFoundException("Facelet " + alias + " not found at: " + url.toExternalForm());
394         }
395 
396     }
397     
398     /**
399      * @since 2.0.1
400      * @param url
401      * @return
402      * @throws IOException
403      * @throws FaceletException
404      * @throws FacesException
405      * @throws ELException
406      */
407     private DefaultFacelet _createCompositeComponentMetadataFacelet(URL url)
408             throws IOException, FaceletException, FacesException, ELException
409     {
410         if (log.isLoggable(Level.FINE))
411         {
412             log.fine("Creating Facelet used to create Composite Component Metadata for: " + url);
413         }
414 
415         // The alias is used later for informative purposes, so we append 
416         // some prefix to identify later where the errors comes from.
417         String alias = "/compositeComponentMetadata/" + _removeFirst(url.getFile(), _baseUrl.getFile());
418         try
419         {
420             FaceletHandler h = _compiler.compileCompositeComponentMetadata(url, alias);
421             DefaultFacelet f = new DefaultFacelet(this, _compiler.createExpressionFactory(), url, alias,
422                     alias, h, true);
423             return f;
424         }
425         catch (FileNotFoundException fnfe)
426         {
427             throw new FileNotFoundException("Facelet " + alias + " not found at: " + url.toExternalForm());
428         }
429     }
430 
431     /**
432      * Works in the same way as getFacelet(String uri), but redirect
433      * to getViewMetadataFacelet(URL url)
434      * @since 2.0
435      */
436     @Override
437     public Facelet getViewMetadataFacelet(String uri) throws IOException
438     {
439         URL url = (URL) _relativeLocations.get(uri);
440         if (url == null)
441         {
442             url = resolveURL(_baseUrl, uri);
443             if (url != null)
444             {
445                 Map<String, URL> newLoc = new HashMap<String, URL>(_relativeLocations);
446                 newLoc.put(uri, url);
447                 _relativeLocations = newLoc;
448             }
449             else
450             {
451                 throw new IOException("'" + uri + "' not found.");
452             }
453         }
454         return this.getViewMetadataFacelet(url);
455     }
456 
457     /**
458      * @since 2.0
459      */
460     @Override
461     public Facelet getViewMetadataFacelet(URL url) throws IOException,
462             FaceletException, FacesException, ELException
463     {
464         if (_abstractFaceletCache != null)
465         {
466             return _abstractFaceletCache.getViewMetadataFacelet(url);
467         }
468         else
469         {
470             return _faceletCache.getViewMetadataFacelet(url);
471         }
472     }
473     
474     /**
475      * Works in the same way as getFacelet(String uri), but redirect
476      * to getViewMetadataFacelet(URL url)
477      * @since 2.0.1
478      */
479     @Override
480     public Facelet getCompositeComponentMetadataFacelet(String uri) throws IOException
481     {
482         URL url = (URL) _relativeLocations.get(uri);
483         if (url == null)
484         {
485             url = resolveURL(_baseUrl, uri);
486             if (url != null)
487             {
488                 Map<String, URL> newLoc = new HashMap<String, URL>(_relativeLocations);
489                 newLoc.put(uri, url);
490                 _relativeLocations = newLoc;
491             }
492             else
493             {
494                 throw new IOException("'" + uri + "' not found.");
495             }
496         }
497         return this.getCompositeComponentMetadataFacelet(url);
498     }
499 
500     /**
501      * @since 2.0.1
502      */
503     @Override
504     public Facelet getCompositeComponentMetadataFacelet(URL url) throws IOException,
505             FaceletException, FacesException, ELException
506     {
507         if (_abstractFaceletCache != null)
508         {
509             return _abstractFaceletCache.getCompositeComponentMetadataFacelet(url);
510         }
511         else
512         {
513             ParameterCheck.notNull("url", url);
514 
515             String key = url.toString();
516 
517             DefaultFacelet f = _compositeComponentMetadataFacelets.get(key);
518 
519             if (f == null || this.needsToBeRefreshed(f))
520             {
521                 f = this._createCompositeComponentMetadataFacelet(url);
522                 if (_refreshPeriod != NO_CACHE_DELAY)
523                 {
524                     Map<String, DefaultFacelet> newLoc
525                             = new HashMap<String, DefaultFacelet>(_compositeComponentMetadataFacelets);
526                     newLoc.put(key, f);
527                     _compositeComponentMetadataFacelets = newLoc;
528                 }
529             }
530             return f;
531         }
532     }
533 
534     /**
535      * Removes the first appearance of toRemove in string.
536      *
537      * Works just like string.replaceFirst(toRemove, ""), except that toRemove
538      * is not treated as a regex (which could cause problems with filenames).
539      *
540      * @param string
541      * @param toRemove
542      * @return
543      */
544     private String _removeFirst(String string, String toRemove)
545     {
546         // do exactly what String.replaceFirst(toRemove, "") internally does,
547         // except treating the search as literal text and not as regex
548 
549         return Pattern.compile(toRemove, Pattern.LITERAL).matcher(string).replaceFirst("");
550     }
551 
552 }