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