[exo-jcr-commits] exo-jcr SVN: r4196 - jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy.

do-not-reply at jboss.org do-not-reply at jboss.org
Thu Mar 31 10:14:00 EDT 2011


Author: nzamosenchuk
Date: 2011-03-31 10:14:00 -0400 (Thu, 31 Mar 2011)
New Revision: 4196

Modified:
   jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
Log:
EXOJCR-577: Handle state when reindexing the worksapce.

Modified: jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
===================================================================
--- jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java	2011-03-31 12:14:39 UTC (rev 4195)
+++ jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java	2011-03-31 14:14:00 UTC (rev 4196)
@@ -32,6 +32,7 @@
 import org.exoplatform.services.jcr.ext.registry.RegistryEntry;
 import org.exoplatform.services.jcr.ext.registry.RegistryService;
 import org.exoplatform.services.jcr.ext.resource.UnifiedNodeReference;
+import org.exoplatform.services.jcr.impl.core.query.lucene.IndexOfflineRepositoryException;
 import org.exoplatform.services.log.ExoLogger;
 import org.exoplatform.services.log.Log;
 import org.exoplatform.services.rest.ext.groovy.GroovyClassLoaderProvider;
@@ -73,6 +74,7 @@
 import javax.jcr.RepositoryException;
 import javax.jcr.Session;
 import javax.jcr.observation.Event;
+import javax.jcr.query.InvalidQueryException;
 import javax.jcr.query.Query;
 import javax.jcr.query.QueryResult;
 import javax.ws.rs.Consumes;
@@ -117,6 +119,8 @@
    /** Service name. */
    private static final String SERVICE_NAME = "GroovyScript2RestLoader";
 
+   private static final int DELAYED_AUTOLOAD_TIMEOUT = 20000; // 20 sec
+
    /** See {@link InitParams}. */
    protected InitParams initParams;
 
@@ -274,50 +278,80 @@
          try
          {
             // Deploy auto-load scripts and start Observation Listeners.
-            String repositoryName = observationListenerConfiguration.getRepository();
+            final String repositoryName = observationListenerConfiguration.getRepository();
             List<String> workspaceNames = observationListenerConfiguration.getWorkspaces();
 
-            ManageableRepository repository = repositoryService.getRepository(repositoryName);
+            final ManageableRepository repository = repositoryService.getRepository(repositoryName);
 
+            // JCR it offers an asynchronous workspace reindexing (since 1.14.0-CR2). But while it
+            // is performed in background queries can't be executed. In this case autoload scripts could only
+            // be loaded after reindexing finished.
+            final Set<String> delayedWorkspacePublishing = new HashSet<String>();
+
             for (String workspaceName : workspaceNames)
             {
                Session session = repository.getSystemSession(workspaceName);
+               try
+               {
+                  autoLoadScripts(session);
+               }
+               catch (IndexOfflineRepositoryException e)
+               {
+                  delayedWorkspacePublishing.add(workspaceName);
+               }
 
-               String xpath = "//element(*, " + getNodeType() + ")[@exo:autoload='true']";
-               Query query = session.getWorkspace().getQueryManager().createQuery(xpath, Query.XPATH);
-
-               QueryResult result = query.execute();
-               NodeIterator nodeIterator = result.getNodes();
-               while (nodeIterator.hasNext())
+               session.getWorkspace().getObservationManager().addEventListener(
+                  new GroovyScript2RestUpdateListener(repositoryName, workspaceName, this, session),
+                  Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED | Event.PROPERTY_REMOVED, "/", true, null,
+                  new String[]{getNodeType()}, false);
+            }
+            if (!delayedWorkspacePublishing.isEmpty())
+            {
+               LOG.warn("The following workspaces are being reindexed now: " + delayedWorkspacePublishing
+                  + ". Groove scripts from those workspaces marked as AutoLoad will be loaded later.");
+               // lauch delayed autoLoad
+               new Thread(new Runnable()
                {
-                  Node node = nodeIterator.nextNode();
-
-                  if (node.getPath().startsWith("/jcr:system"))
+                  public void run()
                   {
-                     continue;
+                     while (true)
+                     {
+                        if (delayedWorkspacePublishing.isEmpty())
+                        {
+                           // finish thread
+                           return;
+                        }
+                        for (Iterator iterator = delayedWorkspacePublishing.iterator(); iterator.hasNext();)
+                        {
+                           String workspaceName = (String)iterator.next();
+                           try
+                           {
+                              Session session = repository.getSystemSession(workspaceName);
+                              autoLoadScripts(session);
+                              // if no exception, then remove item from set
+                              iterator.remove();
+                           }
+                           catch (IndexOfflineRepositoryException e)
+                           {
+                              //it's okay. Retrying;
+                           }
+                           catch (Exception e)
+                           {
+                              // skip
+                              LOG.error(e);
+                           }
+                        }
+                        try
+                        {
+                           Thread.sleep(DELAYED_AUTOLOAD_TIMEOUT);
+                        }
+                        catch (InterruptedException e)
+                        {
+                           // skip
+                        }
+                     }
                   }
-
-                  try
-                  {
-                     groovyPublisher.publishPerRequest(node.getProperty("jcr:data").getStream(), new NodeScriptKey(
-                        repositoryName, workspaceName, node), null);
-                  }
-                  catch (CompilationFailedException e)
-                  {
-                     LOG.error(e.getMessage(), e);
-                  }
-                  catch (ResourcePublicationException e)
-                  {
-                     LOG.error(e.getMessage(), e);
-                  }
-               }
-
-               session
-                  .getWorkspace()
-                  .getObservationManager()
-                  .addEventListener(new GroovyScript2RestUpdateListener(repositoryName, workspaceName, this, session),
-                     Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED | Event.PROPERTY_REMOVED, "/", true, null,
-                     new String[]{getNodeType()}, false);
+               }, "GrooveSrciptDelayedAutoLoader-" + repositoryName).start();
             }
          }
          catch (Exception e)
@@ -334,6 +368,41 @@
       binder.addResource(this, null);
    }
 
+   private void autoLoadScripts(Session session) throws RepositoryException
+   {
+      String workspaceName = session.getWorkspace().getName();
+      String repositoryName = observationListenerConfiguration.getRepository();
+
+      String xpath = "//element(*, " + getNodeType() + ")[@exo:autoload='true']";
+      Query query = session.getWorkspace().getQueryManager().createQuery(xpath, Query.XPATH);
+
+      QueryResult result = query.execute();
+      NodeIterator nodeIterator = result.getNodes();
+      while (nodeIterator.hasNext())
+      {
+         Node node = nodeIterator.nextNode();
+
+         if (node.getPath().startsWith("/jcr:system"))
+         {
+            continue;
+         }
+
+         try
+         {
+            groovyPublisher.publishPerRequest(node.getProperty("jcr:data").getStream(), new NodeScriptKey(
+               repositoryName, workspaceName, node), null);
+         }
+         catch (CompilationFailedException e)
+         {
+            LOG.error(e.getMessage(), e);
+         }
+         catch (ResourcePublicationException e)
+         {
+            LOG.error(e.getMessage(), e);
+         }
+      }
+   }
+
    /**
     * @see org.picocontainer.Startable#stop()
     */
@@ -526,7 +595,8 @@
       Document doc;
       try
       {
-         doc = AccessController.doPrivileged(new PrivilegedExceptionAction<Document>() {
+         doc = AccessController.doPrivileged(new PrivilegedExceptionAction<Document>()
+         {
             public Document run() throws ParserConfigurationException
             {
                return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
@@ -851,7 +921,9 @@
       throws MalformedScriptException
    {
       if (name != null && name.length() > 0 && name.startsWith("/"))
+      {
          name = name.substring(1);
+      }
       groovyPublisher.validateResource(script, name, src, files);
    }
 
@@ -1090,9 +1162,9 @@
          {
             if (null == groovyPublisher.unpublishResource(key))
             {
-               return Response.status(Response.Status.BAD_REQUEST)
-                  .entity("Can't unbind script " + path + ", not bound or has wrong mapping to the resource class ")
-                  .type(MediaType.TEXT_PLAIN).build();
+               return Response.status(Response.Status.BAD_REQUEST).entity(
+                  "Can't unbind script " + path + ", not bound or has wrong mapping to the resource class ").type(
+                  MediaType.TEXT_PLAIN).build();
             }
          }
          return Response.status(Response.Status.NO_CONTENT).build();
@@ -1240,9 +1312,8 @@
             sessionProviderService.getSessionProvider(null).getSession(workspace,
                repositoryService.getRepository(repository));
          Node scriptFile = (Node)ses.getItem("/" + path);
-         return Response.status(Response.Status.OK)
-            .entity(scriptFile.getNode("jcr:content").getProperty("jcr:data").getStream()).type("script/groovy")
-            .build();
+         return Response.status(Response.Status.OK).entity(
+            scriptFile.getNode("jcr:content").getProperty("jcr:data").getStream()).type("script/groovy").build();
       }
       catch (PathNotFoundException e)
       {
@@ -1417,9 +1488,13 @@
             String str = sources.get(i);
             URL url = null;
             if (str.startsWith("jcr://"))
+            {
                url = new URL(null, str, UnifiedNodeReference.getURLStreamHandler());
+            }
             else
+            {
                url = new URL(str);
+            }
             src[i] = new SourceFolder(url);
          }
       }
@@ -1437,9 +1512,13 @@
             String str = files.get(i);
             URL url = null;
             if (str.startsWith("jcr://"))
+            {
                url = new URL(null, str, UnifiedNodeReference.getURLStreamHandler());
+            }
             else
+            {
                url = new URL(str);
+            }
             srcFiles[i] = new SourceFile(url);
          }
       }



More information about the exo-jcr-commits mailing list