View Javadoc

1   /**
2    * This file Copyright (c) 2010-2010 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.groovy.support.classes;
35  
36  import groovy.lang.GroovyClassLoader;
37  import groovy.lang.GroovyObject;
38  import info.magnolia.module.groovy.support.HierarchyManagerProvider;
39  import info.magnolia.objectfactory.ClassFactory;
40  import info.magnolia.objectfactory.DefaultClassFactory;
41  
42  import org.codehaus.groovy.control.CompilationFailedException;
43  
44  
45  /**
46   * A {@link info.magnolia.objectfactory.ClassFactory} which attempts to load classes using a
47   * {@link groovy.lang.GroovyClassLoader} if they were not found using a delegate (which is a
48   * {@link info.magnolia.objectfactory.DefaultClassFactory} by default).
49   *
50   * A little bit of background:
51   * When loading classes via the GroovyClassLoader, we loose control on where classes
52   * are loaded from. The GroovyClassLoader will always first attempt to load any given
53   * class via its parent*. This is actually the expected behaviour from regular ClassLoader
54   * implementations. As long as we first try loading our classes via the DefaultClassFactory,
55   * we're fine, we keep control of the order in which ClassLoaders are poked for classes.
56   * By default, the GroovyClassLoader uses the current thread's ContextClassLoader, while
57   * we first use the caller's ClassLoader, *then* the thread's.
58   * Any class/script loaded via the GroovyClassLoader and using classes that haven't been
59   * loaded yet will thus see those classes loaded via the current thread's ContextClassLoader.
60   * If this were to become an issue, we'd probably need to create something along the lines of
61   * a ClassFactoryAwareClassLoader, and give that as a parent to the GroovyClassLoader.
62   *
63   * @author gjoseph
64   * @version $Revision: $ ($Author: $)
65   */
66  public class GroovyClassFactory implements ClassFactory {
67      private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GroovyClassFactory.class);
68  
69      private final ClassFactory delegate;
70      private final GroovyClassLoader gcl;
71  
72      public GroovyClassFactory() {
73          // Using the SystemContext to load classes of the repository, by default.
74          // Since the forName() method will attempt to load any class via the DefaultClassFactory *first*,
75          // we should hopefully have a SystemContext implementation ready by the time we need to access the repository.
76          // (and the repository should be ready by then too)
77          this(new DefaultClassFactory(), new HierarchyManagerProvider.SystemContextHierarchyManagerProvider());
78      }
79  
80      public GroovyClassFactory(ClassFactory delegate, HierarchyManagerProvider hmp) {
81          if (hmp == null || delegate == null) {
82              throw new IllegalArgumentException("Delegate ClassFactory and HierarchyManagerProvider can not be null");
83          }
84  
85          this.delegate = delegate;
86          this.gcl = new MgnlGroovyClassLoader(hmp);
87      }
88  
89      public <C> Class<C> forName(String className) throws ClassNotFoundException {
90          try {
91              return delegate.forName(className);
92          } catch (ClassNotFoundException cnfe) {
93              try {
94                  return gcl.loadClass(className, true, false);
95              } catch (CompilationFailedException compilationException) {
96                  // TODO - would be nice to get the precise location of the source script ...
97                  log.error("Could not compile {} with Groovy:\n{}", className, compilationException.getMessage());
98                  throw new ClassNotFoundException("Could not compile " + className + " with Groovy", compilationException);
99              }
100         }
101     }
102 
103     public <T> T newInstance(Class<T> c, Object... objects) {
104         final Class<T> klass = recompileClassIfNeeded(c);
105         return delegate.newInstance(klass, objects);
106     }
107 
108     public <T> T newInstance(Class<T> c, Class<?>[] argTypes, Object... params) {
109        final Class<T> klass = recompileClassIfNeeded(c);
110         return delegate.newInstance(klass, argTypes, params);
111     }
112 
113     // TODO - shouldn't this move to the ResourceLoader ?
114     private <T> Class<T> recompileClassIfNeeded(Class<T> c) {
115         Class<T> klass = c;
116         if (GroovyObject.class.isAssignableFrom(c)) {
117             log.debug("{} is a Groovy object, so check if a newer source is available", c.getName());
118             try {
119                 klass = gcl.loadClass(c.getName(), true, false);
120             }
121             catch (ClassNotFoundException e) {
122                 log.warn(e.getMessage());
123                 klass = c;
124             }
125         }
126         return klass;
127     }
128 }