View Javadoc
1   /**
2    * This file Copyright (c) 2010-2017 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 info.magnolia.context.Context;
37  import info.magnolia.module.groovy.support.HierarchyManagerProvider;
38  import info.magnolia.objectfactory.ClassFactory;
39  import info.magnolia.objectfactory.DefaultClassFactory;
40  import info.magnolia.objectfactory.ReloadableClassFactory;
41  
42  import org.codehaus.groovy.control.CompilationFailedException;
43  import org.slf4j.Logger;
44  import org.slf4j.LoggerFactory;
45  
46  import groovy.lang.GroovyClassLoader;
47  import groovy.lang.GroovyObject;
48  
49  /**
50   * A {@link info.magnolia.objectfactory.ClassFactory} which attempts to load classes using a
51   * {@link groovy.lang.GroovyClassLoader} if they were not found using a delegate (which is a
52   * {@link info.magnolia.objectfactory.DefaultClassFactory} by default).
53   *
54   * <p>A little bit of background:<br>
55   * When loading classes via the GroovyClassLoader, we loose control on where classes
56   * are loaded from. The GroovyClassLoader will always first attempt to load any given
57   * class via its parent*. This is actually the expected behaviour from regular ClassLoader
58   * implementations. As long as we first try loading our classes via the DefaultClassFactory,
59   * we're fine, we keep control of the order in which ClassLoaders are poked for classes.
60   * By default, the GroovyClassLoader uses the current thread's ContextClassLoader, while
61   * we first use the caller's ClassLoader, *then* the thread's.<br>
62   * Any class/script loaded via the GroovyClassLoader and using classes that haven't been
63   * loaded yet will thus see those classes loaded via the current thread's ContextClassLoader.
64   * If this were to become an issue, we'd probably need to create something along the lines of
65   * a ClassFactoryAwareClassLoader, and give that as a parent to the GroovyClassLoader.</p>
66   */
67  public class GroovyClassFactory implements ReloadableClassFactory {
68      private final static Logger log = LoggerFactory.getLogger(GroovyClassFactory.class);
69  
70      private final ClassFactory delegate;
71      private final GroovyClassLoader gcl;
72  
73      public GroovyClassFactory() {
74          // Using the SystemContext to load classes of the repository, by default.
75          // Since the forName() method will attempt to load any class via the DefaultClassFactory *first*,
76          // we should hopefully have a SystemContext implementation ready by the time we need to access the repository.
77          // (and the repository should be ready by then too)
78          this(new DefaultClassFactory());
79      }
80  
81      public GroovyClassFactory(ClassFactory delegate) {
82          this.delegate = delegate;
83          this.gcl = new MgnlGroovyClassLoader();
84      }
85  
86      /**
87       * @deprecated since 2.4.3 please use {@link #GroovyClassFactory()} instead.
88       */
89      @Deprecated
90      public GroovyClassFactory(ClassFactory delegate, HierarchyManagerProvider hmp) {
91          this(delegate);
92      }
93  
94      /**
95       * @deprecated since 2.4.4 please use {@link #GroovyClassFactory()} instead.
96       */
97      @Deprecated
98      public GroovyClassFactory(ClassFactory delegate, Context context) {
99          this(delegate);
100     }
101 
102     @Override
103     public <C> Class<C> forName(String className) throws ClassNotFoundException {
104         try {
105             return delegate.forName(className);
106         } catch (ClassNotFoundException e) {
107             try {
108                 return gcl.loadClass(className, true, false);
109             } catch (CompilationFailedException compilationException) {
110                 // TODO - would be nice to get the precise location of the source script ...
111                 log.error("Could not compile {} with Groovy:\n{}", className, compilationException.getMessage());
112                 throw new ClassNotFoundException("Could not compile " + className + " with Groovy", compilationException);
113             }
114         }
115     }
116 
117     @Override
118     public <T> T newInstance(Class<T> c, Object... objects) {
119         final Class<T> klass = recompileClassIfNeeded(c);
120         return delegate.newInstance(klass, objects);
121     }
122 
123     @Override
124     public <T> T newInstance(Class<T> c, Class<?>[] argTypes, Object... params) {
125         final Class<T> klass = recompileClassIfNeeded(c);
126         return delegate.newInstance(klass, argTypes, params);
127     }
128 
129     // TODO - shouldn't this move to the ResourceLoader ?
130     private <T> Class<T> recompileClassIfNeeded(Class<T> c) {
131         Class<T> klass = c;
132         if (GroovyObject.class.isAssignableFrom(c)) {
133             log.debug("{} is a Groovy object, so check if a newer source is available", c.getName());
134             try {
135                 klass = gcl.loadClass(c.getName(), true, false);
136             } catch (ClassNotFoundException e) {
137                 log.warn(e.getMessage());
138                 klass = c;
139             }
140         }
141         return klass;
142     }
143 
144     @Override
145     public <T> Class<T> reload(Class<T> c) throws ClassNotFoundException {
146         return recompileClassIfNeeded(c);
147     }
148 }