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.jcr.util.NodeTypes;
38  import info.magnolia.jcr.util.PropertyUtil;
39  
40  import java.io.IOException;
41  import java.io.InputStream;
42  import java.net.MalformedURLException;
43  import java.net.URL;
44  import java.net.URLConnection;
45  import java.net.URLStreamHandler;
46  import java.util.Calendar;
47  
48  import javax.inject.Provider;
49  import javax.jcr.Node;
50  import javax.jcr.RepositoryException;
51  import javax.jcr.Session;
52  
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  import groovy.lang.GroovyResourceLoader;
57  
58  /**
59   * A {@link GroovyResourceLoader} implementation which is able to load Groovy source from a given repository.
60   * <strong>Warning:</strong> this is based on URLs objects. It uses a custom "protocol", but this is only
61   * supported in as far as the URL object instance is passed around. Using the URL's string representation
62   * outside the context of this class will invariably fail, unless {@link info.magnolia.module.groovy.support.classes.MgnlGroovyResourceLoader.MagnoliaStreamHandler} is passed too.
63   */
64  class MgnlGroovyResourceLoader implements GroovyResourceLoader {
65  
66      private static final Logger log = LoggerFactory.getLogger(MgnlGroovyResourceLoader.class);
67      private static final String PROTOCOL = "magnolia-repository://";
68  
69      private final GroovyResourceLoader delegate;
70      private final Provider<Context> provider;
71      private final String workspaceName;
72  
73      MgnlGroovyResourceLoader(GroovyResourceLoader delegate, Provider<Context> provider, String workspaceName) {
74          this.delegate = delegate;
75          this.provider = provider;
76          this.workspaceName = workspaceName;
77      }
78  
79      /**
80       * @deprecated since 2.4.4 please use {@link #MgnlGroovyResourceLoader(GroovyResourceLoader, Provider, String)} instead.
81       */
82      @Deprecated
83      MgnlGroovyResourceLoader(GroovyResourceLoader delegate, Context context, String repoName) throws UnsupportedOperationException {
84          throw new UnsupportedOperationException();
85      }
86  
87      @Override
88      public URL loadGroovySource(String name) throws MalformedURLException {
89          final URL url = loadGroovySourceFromRepository(name);
90          if (url == null) {
91              return delegate.loadGroovySource(name);
92          }
93          return url;
94      }
95  
96      /**
97       * Returns a URL <em>only if</em> the path to the source exits <strong>AND</strong> is <strong>NOT</strong> deleted <strong>AND</strong> the enabled flag is <code>true</code>.
98       * In all other cases it <strong>must</strong> return <code>null</code>
99       */
100     private URL loadGroovySourceFromRepository(String name) throws MalformedURLException {
101         if (name.startsWith("[") || name.contains("$")) {
102             // we don't even try loading array classes or nested classes.
103             // see java.lang.Class#forName()
104             log.debug("Skipping {}, array or nested class.", name);
105             return null;
106         }
107 
108         final String path = "/" + name.replace('.', '/');
109         try {
110             final Session session = provider.get().getJCRSession(workspaceName);
111             if (!session.nodeExists(path)) {
112                 return null;
113             }
114             final Node node = session.getNode(path);
115             if (NodeTypes.Deleted.getDeleted(node) == null && PropertyUtil.getBoolean(node, "enabled", false)) {
116                 return new URL(null, PROTOCOL + session.getWorkspace().getName() + path, new MagnoliaStreamHandler(session));
117             } else {
118                 return null;
119             }
120         } catch (RepositoryException e) {
121             return null;
122         }
123     }
124 
125     /**
126      * Magnolia Stream Handler.
127      */
128     protected static class MagnoliaStreamHandler extends URLStreamHandler {
129         private final Session session;
130 
131         public MagnoliaStreamHandler(Session session) {
132             this.session = session;
133         }
134 
135         @Override
136         protected URLConnection openConnection(URL u) throws IOException {
137             if (!"magnolia-repository".equals(u.getProtocol())) {
138                 throw new IllegalStateException("Unsupported protocol: " + u.getProtocol() + " (only supports \"magnolia-repository\")");
139             }
140             return new MagnoliaURLConnection(u, session);
141         }
142     }
143 
144     /**
145      * Magnolia URL Connection.
146      */
147     protected static class MagnoliaURLConnection extends URLConnection {
148         private final Node node;
149 
150         public MagnoliaURLConnection(URL u, Session session) throws IOException {
151             super(u);
152             // final String repository = u.getHost();
153             final String path = u.getPath();
154 
155             try {
156                 this.node = session.getNode(path);
157             } catch (RepositoryException e) {
158                 throw new IOException("Can't get " + path + " from the " + session.getWorkspace().getName() + " workspace: " + e.getClass().getSimpleName() + ": " + e.getMessage());
159             }
160         }
161 
162         @Override
163         public void connect() throws IOException {
164             // Nothing to do here.
165             // I'm assuming this could be needed for connections that can timeout, and/or when the URL object is
166             // used long after it's been instantiated. In our specific case, we know for a fact that it's used
167             // immediately, and not kept around, which is why we fetch the node from the repository straight from
168             // the constructor of this class.
169         }
170 
171         @Override
172         public InputStream getInputStream() throws IOException {
173             // TODO - double check "enabled" flag ?
174             try {
175                 return node.getProperty("text").getBinary().getStream();
176             } catch (RepositoryException e) {
177                 throw new IOException(e);
178             }
179         }
180 
181         @Override
182         public long getLastModified() {
183             try {
184                 Calendar date = NodeTypes.LastModified.getLastModified(node);
185                 return date.getTimeInMillis();
186             } catch (RepositoryException e) {
187                 return 0;
188             }
189 
190         }
191     }
192 }