Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2009 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.picocontainer.Startable;
  
  import java.net.URI;
  import java.net.URL;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Set;
  
  import javax.jcr.Node;
  import javax.jcr.Session;
  import javax.ws.rs.POST;
  import javax.ws.rs.Path;

Author(s):
Andrey Parfonov
Version:
$Id: GroovyScript2RestLoader.java 34445 2009-07-24 07:51:18Z dkatayev $
  
  @SuppressWarnings("deprecation")
 @Path("script/groovy")
 public class GroovyScript2RestLoader extends BaseGroovyScriptManager implements Startable
 {
    protected static class InnerGroovyJaxrsPublisher extends GroovyJaxrsPublisher
    {
       public InnerGroovyJaxrsPublisher(ResourceBinder binderGroovyScriptInstantiator instantiator,
          GroovyClassLoaderProvider classLoaderProvider)
       {
          super(binderinstantiatorclassLoaderProvider);
       }
    }

   
Logger.
 
    static final Log LOG = ExoLogger.getLogger("exo.jcr.component.ext.GroovyScript2RestLoader");

   
Default node types for Groovy scripts.
 
    private static final String DEFAULT_NODETYPE = "exo:groovyResourceContainer";

   
Service name.
 
    private static final String SERVICE_NAME = "GroovyScript2RestLoader";
 
    private static final int DELAYED_AUTOLOAD_TIMEOUT = 20000; // 20 sec
 
   
See InitParams.
 
    protected InitParams initParams;

   
See RepositoryService.
 
    protected RepositoryService repositoryService;

   
See ConfigurationManager.
 
See RegistryService.
 
    protected RegistryService registryService;

   
See SessionProviderService
 
Keeps configuration for observation listener.
 
 
    //protected GroovyJaxrsPublisher groovyPublisher;
 
 
See ResourceBinder.
 
    private ResourceBinder binder;

   
Node type for Groovy scripts.
 
    private String nodeType;

   

Parameters:
binder binder for RESTful services
groovyScriptInstantiator instantiate groovy scripts
repositoryService See RepositoryService
sessionProviderService See SessionProviderService
configurationManager for solve resource loading issue in common way
params initialized parameters
 
    public GroovyScript2RestLoader(ResourceBinder binderGroovyScriptInstantiator groovyScriptInstantiator,
       RepositoryService repositoryServiceThreadLocalSessionProviderService sessionProviderService,
       ConfigurationManager configurationManagerorg.exoplatform.services.jcr.ext.resource.jcr.Handler jcrUrlHandler,
       InitParams params)
    {
       this(bindergroovyScriptInstantiatorrepositoryServicesessionProviderServiceconfigurationManagernull,
          new InnerGroovyJaxrsPublisher(bindergroovyScriptInstantiatornew JcrGroovyClassLoaderProvider()),
          jcrUrlHandlerparams);
    }

   

Parameters:
binder binder for RESTful services
groovyScriptInstantiator instantiates Groovy scripts
repositoryService See RepositoryService
sessionProviderService See SessionProviderService
configurationManager for solve resource loading issue in common way
registryService See RegistryService
params initialized parameters
 
    public GroovyScript2RestLoader(ResourceBinder binderGroovyScriptInstantiator groovyScriptInstantiator,
       RepositoryService repositoryServiceThreadLocalSessionProviderService sessionProviderService,
       ConfigurationManager configurationManagerRegistryService registryService,
       org.exoplatform.services.jcr.ext.resource.jcr.Handler jcrUrlHandlerInitParams params)
    {
       this(bindergroovyScriptInstantiatorrepositoryServicesessionProviderServiceconfigurationManager,
          registryServicenew InnerGroovyJaxrsPublisher(bindergroovyScriptInstantiator,
             new JcrGroovyClassLoaderProvider()), jcrUrlHandlerparams);
    }
 
    public GroovyScript2RestLoader(ResourceBinder binderGroovyScriptInstantiator groovyScriptInstantiator,
       RepositoryService repositoryServiceThreadLocalSessionProviderService sessionProviderService,
       ConfigurationManager configurationManagerRegistryService registryServiceGroovyJaxrsPublisher groovyPublisher,
       org.exoplatform.services.jcr.ext.resource.jcr.Handler jcrUrlHandlerInitParams params)
    {
       super(groovyPublisher);
       this. = binder;
       this. = repositoryService;
       this. = configurationManager;
       this. = registryService;
       this. = sessionProviderService;
       this. = groovyPublisher;
       this. = params;
    }

   
Get node type for store scripts, may throw IllegalStateException if nodeType not initialized yet.

Returns:
return node type
 
    public String getNodeType()
    {
       if ( == null)
       {
          throw new IllegalStateException("Node type not initialized, yet. ");
       }
       return ;
    }

   

See also:
org.picocontainer.Startable.start()
 
    public void start()
    {
       if ( != null &&  != null && !.getForceXMLConfigurationValue())
       {
          SessionProvider sessionProvider = SessionProvider.createSystemProvider();
          try
          {
             readParamsFromRegistryService(sessionProvider);
          }
          catch (Exception e)
          {
             readParamsFromFile();
             try
             {
                writeParamsToRegistryService(sessionProvider);
             }
             catch (Exception exc)
             {
                .error("Cannot write init configuration to RegistryService."exc);
             }
          }
          finally
          {
             sessionProvider.close();
          }
       }
       else
       {
          readParamsFromFile();
       }
 
       // Add script from configuration files to JCR.
       addScripts();
 
       if ( != null && .size() > 0)
       {
          try
          {
             Set<URLrepos = new HashSet<URL>();
             for (GroovyScriptAddRepoPlugin pl : )
             {
                repos.addAll(pl.getRepositories());
             }
                new JcrGroovyResourceLoader(repos.toArray(new URL[repos.size()])));
          }
          catch (MalformedURLException e)
          {
             .error("Unable add groovy script repository. "e);
          }
       }
 
       if ( != null)
       {
          try
          {
             // Deploy auto-load scripts and start Observation Listeners.
             final String repositoryName = getWorkingRepositoryName();
 
             List<StringworkspaceNames = .getWorkspaces();
 
             final ManageableRepository repository = .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<StringdelayedWorkspacePublishing = new HashSet<String>();
 
             for (String workspaceName : workspaceNames)
             {
                Session session = repository.getSystemSession(workspaceName);
                try
                {
                   autoLoadScripts(session);
                }
                catch (IndexOfflineRepositoryException e)
                {
                   delayedWorkspacePublishing.add(workspaceName);
                }
                finally
                {
                   session.logout();
                }
 
                session
                   .getWorkspace()
                   .getObservationManager()
                   .addEventListener(new GroovyScript2RestUpdateListener(repositoryworkspaceNamethis),
                      . | . | ."/"truenull,
                      new String[]{getNodeType()}, false);
             }
             if (!delayedWorkspacePublishing.isEmpty())
             {
                .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()
                {
                   public void run()
                   {
                      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);
                               try
                               {
                                  autoLoadScripts(session);
                               }
                               finally
                               {
                                  session.logout();
                               }
 
                               // if no exception, then remove item from set
                               iterator.remove();
                            }
                            catch (IndexOfflineRepositoryException e)
                            {
                               //it's okay. Retrying;
                            }
                            catch (Exception e)
                            {
                               // skip
                               .error(e);
                            }
                         }
                         try
                         {
                            Thread.sleep();
                         }
                         catch (InterruptedException e)
                         {
                            // skip
                         }
                      }
                   }
                }, "GrooveSrciptDelayedAutoLoader-" + repositoryName).start();
             }
          }
          catch (Exception e)
          {
             .error("Error occurs "e);
          }
       }
 
       // Finally bind this object as RESTful service.
       // NOTE this service does not implement ResourceContainer, as usually
       // done for this type of services. It can't be binded in common way cause
       // to dependencies problem. And in other side not possible to use third
       // part which can be injected by GroovyScript2RestLoader.
       .addResource(thisnull);
    }
 
    private void autoLoadScripts(Session sessionthrows RepositoryException
    {
       String workspaceName = session.getWorkspace().getName();
       String repositoryName = getWorkingRepositoryName();
 
       String xpath = "//element(*, " + getNodeType() + ")[@exo:autoload='true']";
       Query query = session.getWorkspace().getQueryManager().createQuery(xpath.);
 
       QueryResult result = query.execute();
       NodeIterator nodeIterator = result.getNodes();
       while (nodeIterator.hasNext())
       {
          Node node = nodeIterator.nextNode();
 
          if (node.getPath().startsWith("/jcr:system"))
          {
             continue;
          }
 
          try
          {
             .publishPerRequest(node.getProperty("jcr:data").getStream(), new NodeScriptKey(
                repositoryNameworkspaceNamenode), null);
          }
          catch (CompilationFailedException e)
          {
             .error(e.getMessage(), e);
          }
          catch (ResourcePublicationException e)
          {
             .error(e.getMessage(), e);
          }
       }
    }

   

See also:
org.picocontainer.Startable.stop()
 
    public void stop()
    {
       // nothing to do!
    }
 
    public void addPlugin(ComponentPlugin cp)
    {
       if (cp instanceof GroovyScript2RestLoaderPlugin)
       {
          if ( == null)
          {
              = new ArrayList<GroovyScript2RestLoaderPlugin>();
          }
       }
       if (cp instanceof GroovyScriptAddRepoPlugin)
       {
          if ( == null)
          {
              = new ArrayList<GroovyScriptAddRepoPlugin>();
          }
       }
    }

   
Add scripts that specified in configuration.
 
    protected void addScripts()
    {
       if ( == null || .size() == 0)
       {
          return;
       }
       for (GroovyScript2RestLoaderPlugin loadPlugin : )
       {
          // If no one script configured then skip this item,
          // there is no reason to do anything.
          if (loadPlugin.getXMLConfigs().size() == 0)
          {
             continue;
          }
 
          Session session = null;
          try
          {
             ManageableRepository repository = .getRepository(loadPlugin.getRepository());
             String workspace = loadPlugin.getWorkspace();
             session = repository.getSystemSession(workspace);
             String nodeName = loadPlugin.getNode();
             Node node = null;
             try
             {
                node = (Node)session.getItem(nodeName);
             }
             catch (PathNotFoundException e)
             {
                StringTokenizer tokens = new StringTokenizer(nodeName"/");
                node = session.getRootNode();
                while (tokens.hasMoreTokens())
                {
                   String t = tokens.nextToken();
                   if (node.hasNode(t))
                   {
                      node = node.getNode(t);
                   }
                   else
                   {
                      node = node.addNode(t"nt:folder");
                   }
                }
             }
 
             for (XMLGroovyScript2Rest xg : loadPlugin.getXMLConfigs())
             {
                String scriptName = xg.getName();
                if (node.hasNode(scriptName))
                {
                   .warn("Node '" + node.getPath() + "/" + scriptName + "' already exists. ");
                   continue;
                }
 
                createScript(nodescriptNamexg.isAutoload(), .getInputStream(xg.getPath()));
             }
             session.save();
          }
          catch (Exception e)
          {
             .error("Failed add scripts. "e);
          }
          finally
          {
             if (session != null)
             {
                session.logout();
             }
          }
       }
    }

   
Create JCR node.

Parameters:
parent parent node
name name of node to be created
stream data stream for property jcr:data
Returns:
newly created node
Throws:
Exception if any errors occurs
 
    protected Node createScript(Node parentString nameboolean autoloadInputStream streamthrows Exception
    {
       Node scriptFile = parent.addNode(name"nt:file");
       Node script = scriptFile.addNode("jcr:content"getNodeType());
       script.setProperty("exo:autoload"autoload);
       script.setProperty("jcr:mimeType""script/groovy");
       script.setProperty("jcr:lastModified", Calendar.getInstance());
       script.setProperty("jcr:data"stream);
       return scriptFile;
    }

   
Read parameters from RegistryService.

Parameters:
sessionProvider the SessionProvider
Throws:
RepositoryException
PathNotFoundException
 
    protected void readParamsFromRegistryService(SessionProvider sessionProviderthrows PathNotFoundException,
    {
       if (.isDebugEnabled())
       {
          .debug("<<< Read init parametrs from registry service.");
       }
 
 
       String entryPath = . + "/" +  + "/" + "nodeType";
       RegistryEntry registryEntry = .getEntry(sessionProviderentryPath);
       Document doc = registryEntry.getDocument();
       Element element = doc.getDocumentElement();
        = getAttributeSmart(element"value");
 
       entryPath = . + "/" +  + "/" + "repository";
       registryEntry = .getEntry(sessionProviderentryPath);
       doc = registryEntry.getDocument();
       element = doc.getDocumentElement();
 
       entryPath = . + "/" +  + "/" + "workspaces";
       registryEntry = .getEntry(sessionProviderentryPath);
       doc = registryEntry.getDocument();
       element = doc.getDocumentElement();
       String workspaces = getAttributeSmart(element"value");
 
       String ws[] = workspaces.split(";");
       List<StringwsList = new ArrayList<String>();
       for (String w : ws)
       {
          wsList.add(w);
       }
 
 
       .info("NodeType from RegistryService: " + getNodeType());
       .info("Repository name from RegistryService: "
             : "not configured, will be used the current one"));
 
       .info("List of workspaces from RegistryService: " + .getWorkspaces());
    }

   
Write parameters to RegistryService.

Parameters:
sessionProvider the SessionProvider
Throws:
ParserConfigurationException
SAXException
IOException
RepositoryException
 
    protected void writeParamsToRegistryService(SessionProvider sessionProviderthrows IOExceptionSAXException,
    {
       if (.isDebugEnabled())
       {
          .debug(">>> Save init parametrs in registry service.");
       }
 
       Document doc;
       try
       {
          doc = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction<Document>()
          {
             public Document run() throws ParserConfigurationException
             {
                return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
             }
          });
       }
       catch (PrivilegedActionException e)
       {
          throw (ParserConfigurationException)e.getCause();
       }
 
       Element root = doc.createElement();
       doc.appendChild(root);
 
       Element element = doc.createElement("nodeType");
       setAttributeSmart(element"value"getNodeType());
       root.appendChild(element);
 
       StringBuffer sb = new StringBuffer();
       for (String workspace : .getWorkspaces())
       {
          if (sb.length() > 0)
          {
             sb.append(';');
          }
          sb.append(workspace);
       }
       element = doc.createElement("workspaces");
       setAttributeSmart(element"value"sb.toString());
       root.appendChild(element);
 
       element = doc.createElement("repository");
       root.appendChild(element);
 
       RegistryEntry serviceEntry = new RegistryEntry(doc);
       .createEntry(sessionProvider.serviceEntry);
    }

   
Get attribute value.

Parameters:
element The element to get attribute value
attr The attribute name
Returns:
Value of attribute if present and null in other case
 
    protected String getAttributeSmart(Element elementString attr)
    {
       return element.hasAttribute(attr) ? element.getAttribute(attr) : null;
    }

   
Set attribute value. If value is null the attribute will be removed.

Parameters:
element The element to set attribute value
attr The attribute name
value The value of attribute
 
    protected void setAttributeSmart(Element elementString attrString value)
    {
       if (value == null)
       {
          element.removeAttribute(attr);
       }
       else
       {
          element.setAttribute(attrvalue);
       }
    }

   
Read parameters from file.
 
    protected void readParamsFromFile()
    {
       if ( != null)
       {
           =
             .getValuesParam("nodetype") != null ? .getValueParam("nodetype").getValue()
                : ;
 
          ObjectParameter param = .getObjectParam("observation.config");
       }
       else
       {
           = ;
       }
 
       .info("NodeType from configuration file: " + getNodeType());
       if ( != null)
       {
          .info("Repository name from configuration file: "
                .getRepository() : "not configured, will be used the current one"));
 
          .info("List of workspaces from configuration file: " + .getWorkspaces());
       }
    }
 
    ////////////////////////////////////////////////////////////////////////////////////
 
   
This method is useful for clients that can send script in request body without form-data. At required to set specific Content-type header 'script/groovy'.

Parameters:
stream the stream that contains groovy source code
uriInfo see UriInfo
repository repository name
workspace workspace name
path path to resource to be created
Returns:
Response with status 'created'
 
    @POST
    @Consumes({"script/groovy"})
    @Path("add/{repository}/{workspace}/{path:.*}")
    public Response addScript(InputStream stream, @Context UriInfo uriInfo, @PathParam("repository"String repository,
       @PathParam("workspace"String workspace, @PathParam("path"String path)
    {
       Session ses = null;
       try
       {
          ses =
             .getSessionProvider(null).getSession(workspace,
                .getRepository(repository));
          Node node = (Node)ses.getItem(getPath(path));
          createScript(nodegetName(path), falsestream);
          ses.save();
          URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repositoryworkspacepath);
          return Response.created(location).build();
       }
       catch (PathNotFoundException e)
       {
          String msg = "Path " + path + " does not exists";
          .error(msg);
          return Response.status(..).entity(msg).entity(.).build();
       }
       catch (Exception e)
       {
          .error(e.getMessage(), e);
          return Response.status(..).entity(e.getMessage())
             .type(.).build();
       }
       finally
       {
          if (ses != null)
          {
             ses.logout();
          }
       }
    }

   
This method is useful for clients that send scripts as file in 'multipart/*' request body.
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.

Parameters:
items iterator FileItem
uriInfo see UriInfo
repository repository name
workspace workspace name
path path to resource to be created
Returns:
Response with status 'created'
 
    @POST
    @Consumes({"multipart/*"})
    @Path("add/{repository}/{workspace}/{path:.*}")
    public Response addScript(Iterator<FileItemitems, @Context UriInfo uriInfo,
       @PathParam("repository"String repository, @PathParam("workspace"String workspace,
       @PathParam("path"String path)
    {
       Session ses = null;
       try
       {
          ses =
             .getSessionProvider(null).getSession(workspace,
                .getRepository(repository));
          Node node = (Node)ses.getItem(getPath(path));
          InputStream stream = null;
          boolean autoload = false;
          while (items.hasNext())
          {
             FileItem fitem = items.next();
             if (fitem.isFormField() && fitem.getFieldName() != null
                && fitem.getFieldName().equalsIgnoreCase("autoload"))
             {
                autoload = Boolean.valueOf(fitem.getString());
             }
             else if (!fitem.isFormField())
             {
                stream = fitem.getInputStream();
             }
          }
 
          createScript(nodegetName(path), autoloadstream);
          ses.save();
          URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repositoryworkspacepath);
          return Response.created(location).build();
       }
       catch (PathNotFoundException e)
       {
          String msg = "Path " + path + " does not exists";
          .error(msg);
          return Response.status(..).entity(msg).entity(.).build();
       }
       catch (Exception e)
       {
          .error(e.getMessage(), e);
          return Response.status(..).entity(e.getMessage())
             .type(.).build();
       }
       finally
       {
          if (ses != null)
          {
             ses.logout();
          }
       }
    }

   
Check is specified source script contains valid Groovy source code.

Parameters:
name script name. This name will be used by GroovyClassLoader to identify script, e.g. specified name will be used in error message in compilation of Groovy fails. If this parameter is null then GroovyClassLoader will use automatically generated name
script Groovy source stream
sources locations (string representation of URL) of source folders that should be add in class path when compile Groovy script. NOTE To be able load Groovy source files from specified folders the following rules must be observed:
  • Groovy source files must be located in folder with respect to package structure
  • Name of Groovy source files must be the same as name of class located in file
  • Groovy source file must have extension '.groovy'

Example: If source stream that we want validate contains the following code:
           package c.b.a
           
           import a.b.c.A
           
           class B extends A {
           // Do something.
           }
 
Assume we store dependencies in JCR then URL of folder with Groovy sources may be like this: jcr://repository/workspace#/groovy-library. Then absolute path to JCR node that contains Groovy source must be as following: /groovy-library/a/b/c/A.groovy
files locations (string representation of URL) of source files that should be add in class path when compile Groovy script. Each location must point directly to file that contains Groovy source. Source file can have any name and extension
Returns:
Response with corresponded status. 200 if source code is valid
 
    @POST
    @Consumes({"script/groovy"})
    @Path("validate{name:.*}")
    public Response validateScript(@PathParam("name"String namefinal InputStream script,
       @QueryParam("sources"List<Stringsources, @QueryParam("file"List<Stringfiles)
    {
       try
       {
          validateScript(namescriptcreateSourceFolders(sources), createSourceFiles(files));
          return Response.ok().build();
       }
       catch (MalformedScriptException e)
       {
          .error(e.getMessage(), e);
          return Response.status(..).entity(e.getMessage()).type(.).build();
       }
       catch (MalformedURLException e)
       {
          .error(e.getMessage(), e);
          return Response.status(..).entity(e.getMessage()).type(.).build();
       }
    }

   
Check is specified source script contains valid Groovy source code.

Parameters:
name script name. This name will be used by GroovyClassLoader to identify script, e.g. specified name will be used in error message in compilation of Groovy fails. If this parameter is null then GroovyClassLoader will use automatically generated name
script Groovy source stream
src set of folders that contains Groovy source files that should be add in class-path when validate script, see SourceFolder.getPath(). NOTE To be able load Groovy source files from specified folders the following rules must be observed:
  • Groovy source files must be located in folder with respect to package structure
  • Name of Groovy source files must be the same as name of class located in file
  • Groovy source file must have extension '.groovy'
files set of groovy source files that should be add in class-path when validate script. Each item must point directly to file that contains Groovy source, see SourceFile.getPath() . Source file can have any name and extension
Throws:
MalformedScriptException if script contains not valid source code
 
    public void validateScript(String nameInputStream scriptSourceFolder[] srcSourceFile[] files)
       throws MalformedScriptException
    {
       if (name != null && name.length() > 0 && name.startsWith("/"))
       {
          name = name.substring(1);
       }
       .validateResource(scriptnamesrcfiles);
    }

   
This method is useful for clients that can send script in request body without form-data. At required to set specific Content-type header 'script/groovy'.

Parameters:
stream the stream that contains groovy source code
uriInfo see UriInfo
repository repository name
workspace workspace name
path path to resource to be created
Returns:
Response with status 'created'
 
    @POST
    @Consumes({"script/groovy"})
    @Path("update/{repository}/{workspace}/{path:.*}")
    public Response updateScript(InputStream stream, @Context UriInfo uriInfo,
       @PathParam("repository"String repository, @PathParam("workspace"String workspace,
       @PathParam("path"String path)
    {
       Session ses = null;
       try
       {
          ses =
             .getSessionProvider(null).getSession(workspace,
                .getRepository(repository));
          Node node = (Node)ses.getItem("/" + path);
          node.getNode("jcr:content").setProperty("jcr:data"stream);
          ses.save();
          URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repositoryworkspacepath);
          return Response.created(location).build();
       }
       catch (PathNotFoundException e)
       {
          String msg = "Path " + path + " does not exists";
          .error(msg);
          return Response.status(..).entity(msg).entity(.).build();
       }
       catch (Exception e)
       {
          .error(e.getMessage(), e);
          return Response.status(..).entity(e.getMessage())
             .type(.).build();
       }
       finally
       {
          if (ses != null)
          {
             ses.logout();
          }
       }
   }

   
This method is useful for clients that send scripts as file in 'multipart/*' request body.
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.

Parameters:
items iterator FileItem
uriInfo see UriInfo
repository repository name
workspace workspace name
path path to resource to be created
Returns:
Response with status 'created'
   @POST
   @Consumes({"multipart/*"})
   @Path("update/{repository}/{workspace}/{path:.*}")
   public Response updateScript(Iterator<FileItemitems, @Context UriInfo uriInfo,
      @PathParam("repository"String repository, @PathParam("workspace"String workspace,
      @PathParam("path"String path)
   {
      Session ses = null;
      try
      {
         FileItem fitem = items.next();
         InputStream stream = null;
         if (!fitem.isFormField())
         {
            stream = fitem.getInputStream();
         }
         ses =
            .getSessionProvider(null).getSession(workspace,
               .getRepository(repository));
         Node node = (Node)ses.getItem("/" + path);
         node.getNode("jcr:content").setProperty("jcr:data"stream);
         ses.save();
         URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repositoryworkspacepath);
         return Response.created(location).build();
      }
      catch (PathNotFoundException e)
      {
         String msg = "Path " + path + " does not exists";
         .error(msg);
         return Response.status(..).entity(msg).entity(.).build();
      }
      catch (Exception e)
      {
         .error(e.getMessage(), e);
         return Response.status(..).entity(e.getMessage())
            .type(.).build();
      }
      finally
      {
         if (ses != null)
         {
            ses.logout();
         }
      }
   }

   
Deploy groovy script as REST service. If this property set to 'true' then script will be deployed as REST service if 'false' the script will be undeployed. NOTE is script already deployed and state is true script will be re-deployed.

Parameters:
repository repository name
workspace workspace name
path the path to JCR node that contains groovy script to be deployed
state true if resource should be loaded and false otherwise. If this attribute is not present in HTTP request then it will be considered as true
sources locations (string representation of URL) of source folders that should be add in class path when compile Groovy script. NOTE To be able load Groovy source files from specified folders the following rules must be observed:
  • Groovy source files must be located in folder with respect to package structure
  • Name of Groovy source files must be the same as name of class located in file
  • Groovy source file must have extension '.groovy'

Example: If source stream that we want validate contains the following code:
           package c.b.a
           
           import a.b.c.A
           
           class B extends A {
           // Do something.
           }
 
Assume we store dependencies in JCR then URL of folder with Groovy sources may be like this: jcr://repository/workspace#/groovy-library. Then absolute path to JCR node that contains Groovy source must be as following: /groovy-library/a/b/c/A.groovy
files locations (string representation of URL) of source files that should be add in class path when compile Groovy script. Each location must point directly to file that contains Groovy source. Source file can have any name and extension
properties optional properties to be applied to loaded resource. Ignored if state parameter is false
   @POST
   @Path("load/{repository}/{workspace}/{path:.*}")
   @RolesAllowed({"administrators"})
   public Response load(@PathParam("repository"String repository, @PathParam("workspace"String workspace,
      @PathParam("path"String path, @DefaultValue("true") @QueryParam("state"boolean state,
      @QueryParam("sources"List<Stringsources, @QueryParam("file"List<Stringfiles,
      MultivaluedMap<StringStringproperties)
   {
      try
      {
         return load(repositoryworkspacepathstatepropertiescreateSourceFolders(sources),
            createSourceFiles(files));
      }
      catch (MalformedURLException e)
      {
         .error(e.getMessage(), e);
         return Response.status(..).entity(e.getMessage()).type(.).build();
      }
   }

   
Deploy groovy script as REST service. If this property set to 'true' then script will be deployed as REST service if 'false' the script will be undeployed. NOTE is script already deployed and state is true script will be re-deployed.

Parameters:
repository repository name
workspace workspace name
path the path to JCR node that contains groovy script to be deployed
state true if resource should be loaded and false otherwise. If this attribute is not present in HTTP request then it will be considered as true
properties optional properties to be applied to loaded resource. Ignored if state parameter is false
src set of folders that contains Groovy source files that should be add in class-path when compile file located at path . NOTE To be able load Groovy source files from specified folders the following rules must be observed:
  • Groovy source files must be located in folder with respect to package structure
  • Name of Groovy source files must be the same as name of class located in file
  • Groovy source file must have extension '.groovy'
files set of groovy source files that should be add in class-path when compile file located at path. Each item must point directly to file that contains Groovy source, see SourceFile.getPath() . Source file can have any name and extension
   public Response load(String repositoryString workspaceString pathboolean state,
      MultivaluedMap<StringStringpropertiesSourceFolder[] srcSourceFile[] files)
   {
      Session ses = null;
      try
      {
         ses =
            .getSessionProvider(null).getSession(workspace,
               .getRepository(repository));
         Node script = ((Node)ses.getItem("/" + path)).getNode("jcr:content");
         ResourceId key = new NodeScriptKey(repositoryworkspacescript);
         if (state)
         {
            .unpublishResource(key);
            .publishPerRequest(script.getProperty("jcr:data").getStream(), keypropertiessrcfiles);
         }
         else
         {
            if (null == .unpublishResource(key))
            {
               return Response.status(..).entity(
                  "Can't unbind script " + path + ", not bound or has wrong mapping to the resource class ").type(
                  .).build();
            }
         }
         return Response.status(..).build();
      }
      catch (CompilationFailedException e)
      {
         return Response.status(..).entity(e.getMessage()).type(.).build();
      }
      catch (ResourcePublicationException e)
      {
         return Response.status(..).entity(e.getMessage()).type(.).build();
      }
      catch (PathNotFoundException e)
      {
         String msg = "Path " + path + " does not exists";
         .error(msg);
         return Response.status(..).entity(msg).type(.).build();
      }
      catch (Exception e)
      {
         .error(e.getMessage(), e);
         return Response.status(..).entity(e.getMessage())
            .type(.).build();
      }
      finally
      {
         if (ses != null)
         {
            ses.logout();
         }
      }
   }

   
Remove node that contains groovy script.

Parameters:
repository repository name
workspace workspace name
path JCR path to node that contains script
   @POST
   @Path("delete/{repository}/{workspace}/{path:.*}")
   public Response deleteScript(@PathParam("repository"String repository, @PathParam("workspace"String workspace,
      @PathParam("path"String path)
   {
      Session ses = null;
      try
      {
         ses =
            .getSessionProvider(null).getSession(workspace,
               .getRepository(repository));
         ses.getItem("/" + path).remove();
         ses.save();
         return Response.status(..).build();
      }
      catch (PathNotFoundException e)
      {
         String msg = "Path " + path + " does not exists";
         .error(msg);
         return Response.status(..).entity(msg).entity(.).build();
      }
      catch (Exception e)
      {
         .error(e.getMessage(), e);
         return Response.status(..).entity(e.getMessage())
            .type(.).build();
      }
      finally
      {
         if (ses != null)
         {