View Javadoc

1   /**
2    * This file Copyright (c) 2010-2012 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  
38  import info.magnolia.cms.core.HierarchyManager;
39  import info.magnolia.module.groovy.support.HierarchyManagerProvider;
40  
41  import java.io.IOException;
42  import java.net.URL;
43  import java.net.URLConnection;
44  import java.security.CodeSource;
45  
46  import org.apache.commons.lang.StringUtils;
47  import org.codehaus.groovy.ast.ClassNode;
48  import org.codehaus.groovy.control.CompilationFailedException;
49  import org.codehaus.groovy.control.CompilationUnit;
50  import org.codehaus.groovy.control.CompilationUnit.SourceUnitOperation;
51  import org.codehaus.groovy.control.CompilerConfiguration;
52  import org.codehaus.groovy.control.Phases;
53  import org.codehaus.groovy.control.SourceUnit;
54  import org.codehaus.groovy.control.io.URLReaderSource;
55  import org.slf4j.Logger;
56  import org.slf4j.LoggerFactory;
57  
58  /**
59   * Magnolia class loader which extends {@link GroovyClassLoader} and internally uses {@link MgnlGroovyResourceLoader}.
60   * 
61   * @see MgnlGroovyClassLoader#isSourceNewer(URL, Class)
62   * @see MgnlGroovyClassLoader.AddDefaultImportOperation
63   * @see MgnlGroovyClassLoader.PackageAndClassNameConsistencyOperation
64   */
65  public final class MgnlGroovyClassLoader extends GroovyClassLoader {
66      private static final Logger log = LoggerFactory.getLogger(MgnlGroovyClassLoader.class);
67  
68      private static final String SCRIPTS = "scripts";
69  
70      private final HierarchyManagerProvider hmp;
71  
72      private boolean compileTimeChecks;
73  
74      private String path;
75  
76      /**
77       * @param hmp {@link HierarchyManagerProvider} - it must not be null
78       */
79      public MgnlGroovyClassLoader(HierarchyManagerProvider hmp) {
80          if (hmp == null) {
81              throw new IllegalArgumentException("HierarchyManagerProvider can not be null");
82          }
83          this.hmp = hmp;
84          this.setShouldRecompile(true);
85          this.setResourceLoader(new MgnlGroovyResourceLoader(super.getResourceLoader(), hmp, SCRIPTS));
86      }
87  
88      @Override
89      protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource codeSource) {
90          CompilationUnit cu = super.createCompilationUnit(config, codeSource);
91          if (compileTimeChecks) {
92              log.debug("enforcing compile-time checks...");
93              /*
94               * "Generally speaking, there is more type information available later in the phases. If your transformation is concerned with
95               * reading the AST, then a later phase where information is more plentiful might be a good choice. If your transformation is
96               * concerned with writing AST, then an earlier phase where the tree is more sparse might be more convenient."
97               * see http://groovy.codehaus.org/Compiler+Phase+Guide
98               */
99              cu.addPhaseOperation(new PackageAndClassNameConsistencyOperation(hmp, path), Phases.CONVERSION);
100         }
101 
102         cu.addPhaseOperation(new AddDefaultImportOperation(), Phases.CONVERSION);
103         return cu;
104     }
105 
106     /**
107      * <em>Source newer</em> in our case means that the groovy source
108      * representing a certain class in the <em>scripts</em> repository is more recent than that of
109      * the corresponding class currently loaded in this classloader (i.e. it has been changed).
110      * Please note that if source protocol is <em>file</em>, then <strong>recompilation is forced</strong>
111      * otherwise the caller gets the old class in the current classloader which might be the compiled script
112      * from the scripts repository if the latter (the script, that is) was just disabled.
113      */
114     @Override
115     protected boolean isSourceNewer(URL source, Class cls) throws IOException {
116         long lastMod = -1;
117         if ("file".equals(source.getProtocol())) {
118             return true;
119         } else {
120             URLConnection conn = source.openConnection();
121             lastMod = conn.getLastModified();
122             conn.getInputStream().close();
123         }
124         boolean isNewer = lastMod > getTimeStamp(cls);
125         if (isNewer) {
126             log.info("{} source has changed", cls.getName());
127         }
128         return isNewer;
129     }
130 
131     /**
132      * Checks that the given source compiles correctly and, in case of a script which has to act as a
133      * class, that some consistency constraints imposed by our classloading mechanism are enforced. Throws a {@link CompilationFailedException} in case of compilation failure.
134      * For the applied constraints, see {@link PackageAndClassNameConsistencyOperation}
135      * 
136      * @param source - String the Groovy source
137      * @param enforceCompileChecks - boolean if <code>true</code> enforce additional compile time checks
138      * @param path - String the path to the script in the repository. The substring after the last '/' is assumed to be the script name itself. Will be ignored if <em>enforceCompileChecks</em> is <code>false</code>. Cannot be <code>null</code> if <em>enforceCompileChecks</em> is <code>true</code>.
139      */
140     public final void verify(final String source, final boolean enforceCompileChecks, final String path) throws CompilationFailedException {
141         this.compileTimeChecks = enforceCompileChecks;
142         this.path = path;
143         if (compileTimeChecks && path == null) {
144             throw new IllegalArgumentException("When compilation checks are enforced, mgnlPath cannot be null");
145         }
146         parseClass(source);
147 
148     }
149 
150     private static final class AddDefaultImportOperation extends SourceUnitOperation {
151 
152         @Override
153         public void call(SourceUnit source) throws CompilationFailedException {
154             // yes, to import all the classes of a certain package you have to omit the * at the end
155             // see http://jira.codehaus.org/browse/GROOVY-3041
156             log.debug("adding default imports...");
157             source.getAST().addStarImport("info.magnolia.context.");
158             source.getAST().addStarImport("info.magnolia.cms.core.");
159             source.getAST().addStarImport("info.magnolia.cms.util.");
160             source.getAST().addStarImport("info.magnolia.jcr.util.");
161             source.getAST().addStarImport("info.magnolia.module.groovy.support.");
162         }
163     }
164 
165     /**
166      * Checks package and class name consistency on source code during Groovy's
167      * compilation phase. The checks performed are
168      * <ol>
169      * <li>Ensure that the class declares a package, unless it is being saved at root level of the <code>scripts</code> repository
170      * <li>Ensure that the package matches the path to the source in Magnolia's scripts repository
171      * <li>Ensure that the source contains at least one class named as the script itself.
172      * </ol>
173      */
174     private static final class PackageAndClassNameConsistencyOperation extends SourceUnitOperation {
175         private final HierarchyManagerProvider hmp;
176         private final String mgnlPath;
177 
178         public PackageAndClassNameConsistencyOperation(HierarchyManagerProvider hmp, String mgnlPath) {
179             this.hmp = hmp;
180             this.mgnlPath = mgnlPath;
181         }
182 
183         @Override
184         public void call(SourceUnit source) throws CompilationFailedException {
185             final String parentPath = StringUtils.defaultIfEmpty(StringUtils.substringBeforeLast(mgnlPath, "/"), "/");
186             final String scriptName = StringUtils.substringAfterLast(mgnlPath, "/");
187             final boolean isParentRoot = "/".equals(parentPath);
188             String packageName = null;
189 
190             log.debug("parent path is {}, script name is {}, isParentRoot? {}", new Object[] { parentPath, scriptName, isParentRoot });
191 
192             // do the following checks only if the the parent node is other than root
193             if (!isParentRoot) {
194                 if (!source.getAST().hasPackageName()) {
195                     String msg = scriptName + " compilation failed: you must specify a package for your class.";
196                     log.warn(msg);
197                     throw new CompilationFailedException(source.getPhase(), source, new Throwable(msg));
198                 }
199                 packageName = source.getAST().getPackageName();
200                 final String path = "/" + packageName.replace('.', '/');
201                 if (!path.equals(parentPath + "/")) {
202                     String msg = scriptName
203                             + " compilation failed: class package '"
204                             + packageName
205                             + "' does not match parent node  '"
206                             + parentPath
207                             + "' path in the scripts repository";
208                     log.warn(msg);
209                     throw new CompilationFailedException(source.getPhase(), source, new Throwable(msg));
210                 }
211 
212                 final HierarchyManager hm = hmp.getHierarchyManager(SCRIPTS);
213                 if (!hm.isExist(path)) {
214                     String msg = scriptName
215                             + " compilation failed: class package '"
216                             + packageName
217                             + "' does not match an existing '"
218                             + path
219                             + "' path in the scripts repository";
220                     log.warn(msg);
221                     throw new CompilationFailedException(source.getPhase(), source, new Throwable(msg));
222                 }
223             }
224             // we don't need to check that class A used in class B (included via URLReaderSource) declare class A in current script
225             if (source.getSource() instanceof URLReaderSource) {
226                 return;
227             }
228 
229             // now checking that at least one class declared in the source matches the source file name
230             boolean match = false;
231             final String fullyQualifiedClassName = packageName != null ? packageName + scriptName : scriptName;
232             for (ClassNode cn : source.getAST().getClasses()) {
233                 if (fullyQualifiedClassName.equals(cn.getName())) {
234                     log.debug("found a matching class name {}, we can proceed", fullyQualifiedClassName);
235                     match = true;
236                     break;
237                 }
238             }
239             if (!match) {
240                 String msg = fullyQualifiedClassName + " should declare at least one class named " + scriptName;
241                 log.warn(msg);
242                 throw new CompilationFailedException(source.getPhase(), source, new Throwable(msg));
243             }
244         }
245     }
246 }