[exo-jcr-commits] exo-jcr SVN: r2847 - in jcr/branches/1.12.x/exo.jcr.component.ext/src: main/java/org/exoplatform/services/jcr/ext/resource/jcr and 5 other directories.

do-not-reply at jboss.org do-not-reply at jboss.org
Sun Aug 1 08:44:04 EDT 2010


Author: aparfonov
Date: 2010-08-01 08:44:04 -0400 (Sun, 01 Aug 2010)
New Revision: 2847

Added:
   jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScriptAddRepoPlugin.java
   jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/JcrGroovyResourceLoader.java
Modified:
   jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/JcrURLConnection.java
   jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/jcr/Handler.java
   jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
   jcr/branches/1.12.x/exo.jcr.component.ext/src/main/resources/conf/portal/configuration.xml
   jcr/branches/1.12.x/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java
   jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/conf/standalone/test-configuration.xml
   jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test1.groovy
   jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test2.groovy
Log:
EXOJCR-881

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/JcrURLConnection.java
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/JcrURLConnection.java	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/JcrURLConnection.java	2010-08-01 12:44:04 UTC (rev 2847)
@@ -18,6 +18,8 @@
  */
 package org.exoplatform.services.jcr.ext.resource;
 
+import org.exoplatform.services.jcr.ext.common.SessionProvider;
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.MalformedURLException;
@@ -33,7 +35,7 @@
 public class JcrURLConnection extends URLConnection
 {
 
-   private Session session;
+   private SessionProvider sessionProvider;
 
    private NodeRepresentationService nodeRepresentationService;
 
@@ -41,12 +43,30 @@
 
    private NodeRepresentation nodeRepresentation;
 
-   public JcrURLConnection(UnifiedNodeReference nodeReference, Session session,
+   private Session session;
+
+   private boolean closeSessionProvider;
+
+   public JcrURLConnection(UnifiedNodeReference nodeReference, SessionProvider sessionProvider,
+      NodeRepresentationService nodeRepresentationService, boolean closeSessionProvider) throws MalformedURLException
+   {
+      super(nodeReference.getURL());
+      this.sessionProvider = sessionProvider;
+      this.nodeReference = nodeReference;
+      this.nodeRepresentationService = nodeRepresentationService;
+      this.closeSessionProvider = closeSessionProvider;
+
+      doOutput = false;
+      allowUserInteraction = false;
+      useCaches = false;
+      ifModifiedSince = 0;
+   }
+
+   public JcrURLConnection(UnifiedNodeReference nodeReference, SessionProvider sessionProvider,
       NodeRepresentationService nodeRepresentationService) throws MalformedURLException
    {
-
       super(nodeReference.getURL());
-      this.session = session;
+      this.sessionProvider = sessionProvider;
       this.nodeReference = nodeReference;
       this.nodeRepresentationService = nodeRepresentationService;
 
@@ -68,25 +88,44 @@
 
       try
       {
+         session =
+            sessionProvider.getSession(sessionProvider.getCurrentWorkspace(), sessionProvider.getCurrentRepository());
+
          Node node = null;
          if (nodeReference.isPath())
-            node = session.getRootNode().getNode(nodeReference.getPath().substring(1));
+         {
+            node = (Node)session.getItem(nodeReference.getPath());
+         }
          else if (nodeReference.isIdentitifier())
+         {
             node = session.getNodeByUUID(nodeReference.getIdentitifier().getString());
+         }
          else
+         {
             throw new IllegalArgumentException("Absolute path or Identifier was not found!");
+         }
 
          nodeRepresentation = nodeRepresentationService.getNodeRepresentation(node, "text/xml");
-
          connected = true;
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
          throw new IOException("Connection refused!");
       }
    }
 
+   /**
+    * Close connection to JCR.
+    */
+   public void disconnect()
+   {
+      if (!connected)
+         return;
+      session.logout();
+      connected = false;
+   }
+
    /*
     * (non-Javadoc)
     * @see java.net.URLConnection#getInputStream()
@@ -103,7 +142,7 @@
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
          throw new IOException("can't get input stream");
       }
    }
@@ -148,7 +187,7 @@
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
       }
       return null;
    }
@@ -169,7 +208,7 @@
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
       }
       return -1;
    }
@@ -202,7 +241,7 @@
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
       }
       return null;
    }
@@ -216,11 +255,14 @@
    {
       try
       {
+         if (!connected)
+            connect();
+
          return nodeRepresentation.getLastModified();
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
       }
       return 0;
    }
@@ -281,4 +323,24 @@
       throw new UnsupportedOperationException("protocol doesn't support request properties!");
    }
 
+   @Override
+   protected void finalize() throws Throwable
+   {
+      try
+      {
+         if (closeSessionProvider)
+         {
+            sessionProvider.close();
+         }
+      }
+      catch (Throwable t)
+      {
+         ;
+      }
+      finally
+      {
+         super.finalize();
+      }
+   }
+
 }

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/jcr/Handler.java
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/jcr/Handler.java	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/resource/jcr/Handler.java	2010-08-01 12:44:04 UTC (rev 2847)
@@ -33,11 +33,9 @@
 import java.net.URLConnection;
 import java.net.URLStreamHandler;
 
-import javax.jcr.Session;
-
 /**
  * URLStreamHandler for protocol <tt>jcr://</tt>.
- * 
+ *
  * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
  * @version $Id: $
  */
@@ -48,12 +46,13 @@
     * This is implements as Startable to be independent from other services. It
     * should be guaranty created, and set special system property.
     * Static fields repositoryService, nodeRepresentationService should be
-    * initialized once when Handler created by container. 
+    * initialized once when Handler created by container.
     */
 
    /**
-    * It specifies the package prefix name with should be added in System property
-    * java.protocol.handler.pkgs. Protocol handlers will be in a class called <tt>jcr</tt>.Handler.
+    * It specifies the package prefix name with should be added in System
+    * property java.protocol.handler.pkgs. Protocol handlers will be in a class
+    * called <tt>jcr</tt>.Handler.
     */
    private static final String protocolPathPkg = "org.exoplatform.services.jcr.ext.resource";
 
@@ -106,33 +105,40 @@
          // ThreadLocalSessionProvider or System SessionProvider
          SessionProvider sessionProvider = threadLocalSessionProviderService.getSessionProvider(null);
 
+         boolean closeSessionProvider = false;
          if (sessionProvider == null && ConversationState.getCurrent() != null)
+         {
             sessionProvider =
                (SessionProvider)ConversationState.getCurrent().getAttribute(SessionProvider.SESSION_PROVIDER);
+         }
 
-         // if still not set use anonymous session provider
          if (sessionProvider == null)
+         {
             sessionProvider = SessionProvider.createAnonimProvider();
+            closeSessionProvider = true;
+         }
 
-         ManageableRepository repository;
          String repositoryName = nodeReference.getRepository();
-         if (repositoryName == null || repositoryName.length() == 0)
-            repository = sessionProvider.getCurrentRepository();
-         else
-            repository = repositoryService.getRepository(repositoryName);
+         if (repositoryName != null && repositoryName.length() > 0)
+         {
+            ManageableRepository repository = repositoryService.getRepository(repositoryName);
+            sessionProvider.setCurrentRepository(repository);
+         }
 
          String workspaceName = nodeReference.getWorkspace();
-         if (workspaceName == null || workspaceName.length() == 0)
-            workspaceName = sessionProvider.getCurrentWorkspace();
+         if (workspaceName != null && workspaceName.length() > 0)
+         {
+            sessionProvider.setCurrentWorkspace(workspaceName);
+         }
 
-         Session ses = sessionProvider.getSession(workspaceName, repository);
-         JcrURLConnection conn = new JcrURLConnection(nodeReference, ses, nodeRepresentationService);
+         JcrURLConnection conn =
+            new JcrURLConnection(nodeReference, sessionProvider, nodeRepresentationService, closeSessionProvider);
          return conn;
 
       }
       catch (Exception e)
       {
-         e.printStackTrace();
+         //e.printStackTrace();
          throw new IOException("Open connection to URL '" + url.toString() + "' failed!");
       }
    }

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java	2010-08-01 12:44:04 UTC (rev 2847)
@@ -18,6 +18,9 @@
  */
 package org.exoplatform.services.jcr.ext.script.groovy;
 
+import groovy.lang.GroovyClassLoader;
+import groovy.lang.GroovyCodeSource;
+
 import org.apache.commons.fileupload.FileItem;
 import org.exoplatform.container.component.ComponentPlugin;
 import org.exoplatform.container.configuration.ConfigurationManager;
@@ -42,15 +45,18 @@
 
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.MalformedURLException;
 import java.net.URI;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.StringTokenizer;
 import java.util.regex.Pattern;
 
@@ -78,7 +84,8 @@
 
 /**
  * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
- * @version $Id: GroovyScript2RestLoader.java 34445 2009-07-24 07:51:18Z dkatayev $
+ * @version $Id: GroovyScript2RestLoader.java 34445 2009-07-24 07:51:18Z
+ *          dkatayev $
  */
 @Path("script/groovy")
 public class GroovyScript2RestLoader implements Startable
@@ -126,6 +133,13 @@
    /** Mapping scripts URL (or other key) to classes. */
    protected Map<ScriptKey, Class<?>> scriptsURL2ClassMap = new HashMap<ScriptKey, Class<?>>();
 
+   protected GroovyClassLoader groovyClassLoader;
+
+   protected List<GroovyScriptAddRepoPlugin> addRepoPlugins;
+
+   /** See {@link GroovyScript2RestLoaderPlugin}. */
+   protected List<GroovyScript2RestLoaderPlugin> loadPlugins;
+
    /**
     * @param binder binder for RESTful services
     * @param groovyScriptInstantiator instantiate groovy scripts
@@ -136,10 +150,11 @@
     */
    public GroovyScript2RestLoader(ResourceBinder binder, GroovyScriptInstantiator groovyScriptInstantiator,
       RepositoryService repositoryService, ThreadLocalSessionProviderService sessionProviderService,
-      ConfigurationManager configurationManager, InitParams params)
+      ConfigurationManager configurationManager, org.exoplatform.services.jcr.ext.resource.jcr.Handler jcrUrlHandler,
+      InitParams params)
    {
       this(binder, groovyScriptInstantiator, repositoryService, sessionProviderService, configurationManager, null,
-         params);
+         jcrUrlHandler, params);
    }
 
    /**
@@ -153,7 +168,8 @@
     */
    public GroovyScript2RestLoader(ResourceBinder binder, GroovyScriptInstantiator groovyScriptInstantiator,
       RepositoryService repositoryService, ThreadLocalSessionProviderService sessionProviderService,
-      ConfigurationManager configurationManager, RegistryService registryService, InitParams params)
+      ConfigurationManager configurationManager, RegistryService registryService,
+      org.exoplatform.services.jcr.ext.resource.jcr.Handler jcrUrlHandler, InitParams params)
    {
 
       this.binder = binder;
@@ -168,8 +184,8 @@
    /**
     * Remove script with specified URL from ResourceBinder.
     *
-    * @param url the URL. The <code>url.toString()</code> must be corresponded to
-    *          script class.
+    * @param url the URL. The <code>url.toString()</code> must be corresponded
+    *        to script class.
     * @see GroovyScriptRestLoader#loadScript(URL).
     */
    public void unloadScript(URL url)
@@ -240,8 +256,8 @@
    }
 
    /**
-    * Get node type for store scripts, may throw {@link IllegalStateException} if
-    * <tt>nodeType</tt> not initialized yet.
+    * Get node type for store scripts, may throw {@link IllegalStateException}
+    * if <tt>nodeType</tt> not initialized yet.
     *
     * @return return node type
     */
@@ -260,7 +276,7 @@
     */
    public boolean loadScript(URL url) throws IOException
    {
-      Object resource = groovyScriptInstantiator.instantiateScript(url);
+      Object resource = groovyScriptInstantiator.instantiateScript(new GroovyCodeSource(url), groovyClassLoader);
       if (binder.bind(resource))
       {
          // add mapping script URL to name of class.
@@ -294,7 +310,7 @@
     *
     * @param key the key which must be corresponded to object class name.
     * @param name this name will be passed to compiler to get understandable if
-    *          compilation failed
+    *        compilation failed
     * @param stream the stream which represents groovy script.
     * @return if script loaded false otherwise
     * @throws IOException if script can't be loaded or parsed.
@@ -309,16 +325,16 @@
    /**
     * @param key the key which must be corresponded to object class name
     * @param name this name will be passed to compiler to get understandable if
-    *          compilation failed. This parameter may be set as null then groovy
-    *          compiler will user automatically generated name for script.
-    *          (script000001.groovy)
+    *        compilation failed. This parameter may be set as null then groovy
+    *        compiler will user automatically generated name for script.
+    *        (script000001.groovy)
     * @param stream the stream which represents groovy script.
     * @return if script loaded false otherwise
     * @throws IOException if script can't be loaded or parsed
     */
    public boolean loadScript(ScriptKey key, String name, InputStream stream) throws IOException
    {
-      Object resource = groovyScriptInstantiator.instantiateScript(stream, name);
+      Object resource = groovyScriptInstantiator.instantiateScript(createCodeSource(stream, name), groovyClassLoader);
       if (binder.bind(resource))
       {
          scriptsURL2ClassMap.put(key, resource.getClass());
@@ -336,7 +352,7 @@
     */
    public void start()
    {
-      if (registryService != null && !registryService.getForceXMLConfigurationValue(initParams))
+      if (registryService != null && initParams != null && !registryService.getForceXMLConfigurationValue(initParams))
       {
          SessionProvider sessionProvider = SessionProvider.createSystemProvider();
          try
@@ -368,6 +384,25 @@
       // Add script from configuration files to JCR.
       addScripts();
 
+      ClassLoader cl = getClass().getClassLoader();
+      groovyClassLoader = new GroovyClassLoader(cl);
+      if (addRepoPlugins != null && addRepoPlugins.size() > 0)
+      {
+         try
+         {
+            Set<URL> repos = new HashSet<URL>();
+            for (GroovyScriptAddRepoPlugin pl : addRepoPlugins)
+            {
+               repos.addAll(pl.getRepositories());
+            }
+            groovyClassLoader.setResourceLoader(new JcrGroovyResourceLoader(repos.toArray(new URL[repos.size()])));
+         }
+         catch (MalformedURLException e)
+         {
+            LOG.error("Unable add groovy script repository. ", e);
+         }
+      }
+
       try
       {
 
@@ -426,11 +461,6 @@
    }
 
    /**
-    * See {@link GroovyScript2RestLoaderPlugin}.
-    */
-   protected List<GroovyScript2RestLoaderPlugin> loadPlugins;
-
-   /**
     * @param cp See {@link ComponentPlugin}
     */
    public void addPlugin(ComponentPlugin cp)
@@ -443,8 +473,23 @@
          }
          loadPlugins.add((GroovyScript2RestLoaderPlugin)cp);
       }
+      if (cp instanceof GroovyScriptAddRepoPlugin)
+      {
+         if (addRepoPlugins == null)
+         {
+            addRepoPlugins = new ArrayList<GroovyScriptAddRepoPlugin>();
+         }
+         addRepoPlugins.add((GroovyScriptAddRepoPlugin)cp);
+      }
    }
 
+   private GroovyCodeSource createCodeSource(InputStream in, String name)
+   {
+      GroovyCodeSource gcs = new GroovyCodeSource(in, name, "/groovy/script/jaxrs");
+      gcs.setCachable(false);
+      return gcs;
+   }
+
    /**
     * Add scripts that specified in configuration.
     */
@@ -755,12 +800,10 @@
          }
          if (name == null || name.length() == 0)
          {
-            groovyScriptInstantiator.instantiateScript(script);
+            name = groovyClassLoader.generateScriptName();
          }
-         else
-         {
-            groovyScriptInstantiator.instantiateScript(script, name);
-         }
+
+         groovyScriptInstantiator.instantiateScript(createCodeSource(script, name), groovyClassLoader);
          return Response.status(Response.Status.OK).build();
       }
       catch (Exception e)
@@ -825,10 +868,11 @@
 
    /**
     * This method is useful for clients that send scripts as file in
-    * 'multipart/*' request body. <br/> NOTE even we use iterator item should be
-    * only one, rule one address - one script. This method is created just for
-    * comfort loading script from HTML form. NOT use this script for uploading
-    * few files in body of 'multipart/form-data' or other type of multipart.
+    * 'multipart/*' request body. <br/>
+    * NOTE even we use iterator item should be only one, rule one address - one
+    * script. This method is created just for comfort loading script from HTML
+    * form. NOT use this script for uploading few files in body of
+    * 'multipart/form-data' or other type of multipart.
     *
     * @param items iterator {@link FileItem}
     * @param uriInfo see {@link UriInfo}
@@ -894,10 +938,11 @@
 
    /**
     * This method is useful for clients that send scripts as file in
-    * 'multipart/*' request body. <br/> NOTE even we use iterator item should be
-    * only one, rule one address - one script. This method is created just for
-    * comfort loading script from HTML form. NOT use this script for uploading
-    * few files in body of 'multipart/form-data' or other type of multipart.
+    * 'multipart/*' request body. <br/>
+    * NOTE even we use iterator item should be only one, rule one address - one
+    * script. This method is created just for comfort loading script from HTML
+    * form. NOT use this script for uploading few files in body of
+    * 'multipart/form-data' or other type of multipart.
     *
     * @param items iterator {@link FileItem}
     * @param uriInfo see {@link UriInfo}
@@ -1095,9 +1140,9 @@
     * @param workspace workspace name
     * @param path JCR path to node that contains script
     * @param state value for property exo:autoload, if it is not specified then
-    *          'true' will be used as default. <br /> Example:
-    *          .../scripts/groovy/test1.groovy/load is the same to
-    *          .../scripts/groovy/test1.groovy/load?state=true
+    *        'true' will be used as default. <br />
+    *        Example: .../scripts/groovy/test1.groovy/load is the same to
+    *        .../scripts/groovy/test1.groovy/load?state=true
     */
    @POST
    @Path("autoload/{repository}/{workspace}/{path:.*}")
@@ -1143,7 +1188,8 @@
     *
     * @param repository repository name
     * @param workspace workspace name
-    * @param path the path to JCR node that contains groovy script to be deployed
+    * @param path the path to JCR node that contains groovy script to be
+    *        deployed
     */
    @POST
    @Path("load/{repository}/{workspace}/{path:.*}")
@@ -1210,8 +1256,8 @@
     * @param repository Repository name.
     * @param workspace Workspace name.
     * @param name Additional search parameter. If not emtpy method returns the
-    *          list of script names matching wildcard else returns all the
-    *          scripts found in workspace.
+    *        list of script names matching wildcard else returns all the scripts
+    *        found in workspace.
     * @return
     */
    @POST

Added: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScriptAddRepoPlugin.java
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScriptAddRepoPlugin.java	                        (rev 0)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScriptAddRepoPlugin.java	2010-08-01 12:44:04 UTC (rev 2847)
@@ -0,0 +1,79 @@
+/**
+ * Copyright (C) 2010 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.exoplatform.services.jcr.ext.script.groovy;
+
+import org.exoplatform.container.component.BaseComponentPlugin;
+import org.exoplatform.container.xml.InitParams;
+import org.exoplatform.container.xml.PropertiesParam;
+import org.exoplatform.services.jcr.ext.resource.UnifiedNodeReference;
+import org.exoplatform.services.log.ExoLogger;
+import org.exoplatform.services.log.Log;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public class GroovyScriptAddRepoPlugin extends BaseComponentPlugin
+{
+
+   /** Logger. */
+   private static final Log LOG = ExoLogger.getLogger(GroovyScriptAddRepoPlugin.class);
+
+   private final InitParams params;
+
+   public GroovyScriptAddRepoPlugin(InitParams params)
+   {
+      this.params = params;
+   }
+
+   @SuppressWarnings("unchecked")
+   public Collection<URL> getRepositories()
+   {
+      if (params == null)
+         return Collections.emptyList();
+
+      Set<URL> repos = new HashSet<URL>();
+      Iterator<PropertiesParam> iterator = params.getPropertiesParamIterator();
+      while (iterator.hasNext())
+      {
+         PropertiesParam p = iterator.next();
+         String repository = p.getProperty("repository");
+         String workspace = p.getProperty("workspace");
+         String path = p.getProperty("path");
+         try
+         {
+            repos.add(new UnifiedNodeReference(repository, workspace, path).getURL());
+         }
+         catch (MalformedURLException e)
+         {
+            LOG.error("Failed add groovy script repository. " + e.getMessage());
+         }
+      }
+      return repos;
+   }
+}


Property changes on: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScriptAddRepoPlugin.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Added: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/JcrGroovyResourceLoader.java
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/JcrGroovyResourceLoader.java	                        (rev 0)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/JcrGroovyResourceLoader.java	2010-08-01 12:44:04 UTC (rev 2847)
@@ -0,0 +1,155 @@
+/**
+ * Copyright (C) 2010 eXo Platform SAS.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.exoplatform.services.jcr.ext.script.groovy;
+
+import groovy.lang.GroovyResourceLoader;
+
+import org.exoplatform.services.jcr.ext.resource.JcrURLConnection;
+import org.exoplatform.services.log.ExoLogger;
+import org.exoplatform.services.log.Log;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * @author <a href="mailto:andrew00x at gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+class JcrGroovyResourceLoader implements GroovyResourceLoader
+{
+
+   private static final Log LOG = ExoLogger.getLogger(JcrGroovyResourceLoader.class);
+
+   private int maxEntries = 512;
+
+   private final Map<String, URL> resources = Collections.synchronizedMap(new LinkedHashMap<String, URL>()
+   {
+      protected boolean removeEldestEntry(Entry<String, URL> eldest)
+      {
+         return size() > maxEntries;
+      }
+   });
+
+   private URL[] roots;
+
+   public JcrGroovyResourceLoader(URL[] roots) throws MalformedURLException
+   {
+      this.roots = normalizeJcrURL(roots);
+   }
+
+   /**
+    * {@inheritDoc}
+    */
+   public URL loadGroovySource(String classname) throws MalformedURLException
+   {
+      final String filename = (classname.replace('.', '/') + ".groovy").intern();
+      URL resource = null;
+      synchronized (filename)
+      {
+         resource = resources.get(filename);
+         boolean inCache = resource != null;
+         for (URL root : roots)
+         {
+            if (resource == null)
+            {
+               if ("jcr".equals(root.getProtocol()))
+               {
+                  // In JCR URL path represented by fragment
+                  // jcr://repository/workspace#/path
+                  String ref = root.getRef();
+                  resource = new URL(root, "#" + ref + filename);
+               }
+               else
+               {
+                  resource = new URL(root, filename);
+               }
+            }
+            URLConnection connection = null;
+            try
+            {
+               if (LOG.isDebugEnabled())
+                  LOG.debug("Try to load resource from URL : " + resource);
+
+               connection = resource.openConnection();
+               resource.openStream().close();
+
+               break;
+            }
+            catch (IOException e)
+            {
+               if (LOG.isDebugEnabled())
+                  LOG.debug("Can't open URL : " + resource);
+
+               resource = null;
+            }
+            finally
+            {
+               if (connection != null && resource != null && "jcr".equals(resource.getProtocol()))
+               {
+                  ((JcrURLConnection)connection).disconnect();
+               }
+            }
+         }
+         if (resource != null)
+         {
+            resources.put(filename, resource);
+         }
+         else if (inCache)
+         {
+            // Remove from map if resource is unreachable
+            resources.remove(filename);
+         }
+      }
+      return resource;
+   }
+
+   private static URL[] normalizeJcrURL(URL[] src) throws MalformedURLException
+   {
+      URL[] res = new URL[src.length];
+      for (int i = 0; i < src.length; i++)
+      {
+         if ("jcr".equals(src[i].getProtocol()))
+         {
+            String ref = src[i].getRef();
+            if (ref == null)
+            {
+               ref = "/";
+            }
+            else if (ref.charAt(ref.length() - 1) != '/')
+            {
+               ref = ref + "/";
+            }
+            res[i] = new URL(src[i], "#" + ref);
+         }
+         else
+         {
+            res[i] = src[i];
+         }
+      }
+      return res;
+   }
+
+}


Property changes on: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/JcrGroovyResourceLoader.java
___________________________________________________________________
Name: svn:mime-type
   + text/plain

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/main/resources/conf/portal/configuration.xml
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/main/resources/conf/portal/configuration.xml	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/main/resources/conf/portal/configuration.xml	2010-08-01 12:44:04 UTC (rev 2847)
@@ -165,9 +165,9 @@
       </init-params>
    </component -->
 
-   <!-- component>
+   <component>
       <type>org.exoplatform.services.jcr.ext.resource.jcr.Handler</type>
-   </component -->
+   </component>
 
    <!--  <component>-->
    <!--    <type>org.exoplatform.services.jcr.ext.script.groovy.GroovyScript2RestLoader</type>-->

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java	2010-08-01 12:44:04 UTC (rev 2847)
@@ -64,6 +64,8 @@
 
    private int resourceNumber = 0;
 
+   private Node groovyRepo;
+
    /**
     * {@inheritDoc}
     */
@@ -87,6 +89,10 @@
       script.setProperty("jcr:lastModified", Calendar.getInstance());
       script
          .setProperty("jcr:data", Thread.currentThread().getContextClassLoader().getResourceAsStream("test1.groovy"));
+
+      // repository for groovy dependencies
+      groovyRepo = root.addNode("repo", "nt:folder");
+
       session.save();
    }
 
@@ -286,4 +292,37 @@
       handler.handleRequest(creq, cres);
       assertEquals(200, cres.getStatus());
    }
+
+   public void testGroovyDependency() throws Exception
+   {
+      // Add script in dependency repository
+      Node deps = groovyRepo.addNode("dependencies", "nt:folder");
+      Node dep = deps.addNode("Dep1.groovy", "nt:file");
+      dep = dep.addNode("jcr:content", "nt:resource");
+      dep.setProperty("jcr:mimeType", "script/groovy");
+      dep.setProperty("jcr:lastModified", Calendar.getInstance());
+      dep.setProperty("jcr:data", "package dependencies; class Dep1 { String name = getClass().getName() }");
+
+      session.save();
+
+      script.setProperty("jcr:data", Thread.currentThread().getContextClassLoader().getResourceAsStream(
+         "TestDependency.groovy"));
+
+      session.save();
+
+      // must be rebounded , not created other one
+      assertEquals(resourceNumber + 1, binder.getSize());
+
+      ContainerRequest creq =
+         new ContainerRequest("GET", new URI("/groovy-test-dependency"), new URI(""), null, new InputHeadersMap(
+            new MultivaluedMapImpl()));
+
+      ContainerResponse cres = new ContainerResponse(new DummyContainerResponseWriter());
+
+      handler.handleRequest(creq, cres);
+
+      assertEquals(200, cres.getStatus());
+      assertEquals("dependencies.Dep1", cres.getEntity());
+   }
+
 }

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/conf/standalone/test-configuration.xml
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/conf/standalone/test-configuration.xml	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/conf/standalone/test-configuration.xml	2010-08-01 12:44:04 UTC (rev 2847)
@@ -939,6 +939,23 @@
    </component>
 
    <external-component-plugins>
+      <target-component>org.exoplatform.services.jcr.ext.script.groovy.GroovyScript2RestLoader</target-component>
+      <component-plugin>
+         <name>add groovy repo</name>
+         <set-method>addPlugin</set-method>
+         <type>org.exoplatform.services.jcr.ext.script.groovy.GroovyScriptAddRepoPlugin</type>
+         <init-params>
+            <properties-param>
+               <name>repo1</name>
+               <property name="repository" value="db1"/>
+               <property name="workspace" value="ws"/>
+               <property name="path" value="/repo"/>
+            </properties-param>
+         </init-params>
+      </component-plugin>
+   </external-component-plugins>
+
+   <external-component-plugins>
       <target-component>org.exoplatform.services.naming.InitialContextInitializer</target-component>
       <component-plugin>
          <name>bind.datasource</name>

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test1.groovy
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test1.groovy	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test1.groovy	2010-08-01 12:44:04 UTC (rev 2847)
@@ -14,7 +14,7 @@
   @GET
   @Path("/groovy1/{param}/")
   public String method(@PathParam("param") String name) {
-    def String resp = "Hello from groovy to " + name
+    def resp = "Hello from groovy to " + name
     return resp
   }
   

Modified: jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test2.groovy
===================================================================
--- jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test2.groovy	2010-07-30 15:13:44 UTC (rev 2846)
+++ jcr/branches/1.12.x/exo.jcr.component.ext/src/test/resources/test2.groovy	2010-08-01 12:44:04 UTC (rev 2847)
@@ -14,7 +14,7 @@
   @GET
   @Path("/groovy2/{param}/")
   public String method(@PathParam("param") String name) {
-    def String resp = "Hello from groovy to >>>>> " + name
+    def resp = "Hello from groovy to >>>>> " + name
     return resp
   }
   



More information about the exo-jcr-commits mailing list