Merged 5.1.N (5.1.2) to 5.2.N (5.2.1)

125605 rmunteanu: Merged 5.1.1 (5.1.1) to 5.1.N (5.1.2)
      125498 slanglois: MNT-16155 Update source headers - remove svn:eol-style property on Java and JSP source files


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/BRANCHES/DEV/5.2.N/root@125783 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Raluca Munteanu
2016-04-26 13:03:25 +00:00
parent 8674e2bfc8
commit dc6b2852d0
830 changed files with 142585 additions and 142585 deletions

View File

@@ -1,68 +1,68 @@
package org.alfresco.repo.jscript;
import java.util.List;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionDefinition;
import org.alfresco.service.cmr.action.ActionService;
/**
* Scripted Action service for describing and executing actions against Nodes.
*
* @author davidc
*/
public final class Actions extends BaseScopableProcessorExtension
{
/** Repository Service Registry */
private ServiceRegistry services;
/**
* Set the service registry
*
* @param serviceRegistry the service registry
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.services = serviceRegistry;
}
/**
* Gets the list of registered action names
*
* @return the registered action names
*/
public String[] getRegistered()
{
ActionService actionService = services.getActionService();
List<ActionDefinition> defs = actionService.getActionDefinitions();
String[] registered = new String[defs.size()];
int i = 0;
for (ActionDefinition def : defs)
{
registered[i++] = def.getName();
}
return registered;
}
/**
* Create an Action
*
* @param actionName
* the action name
* @return the action
*/
public ScriptAction create(String actionName)
{
ScriptAction scriptAction = null;
ActionService actionService = services.getActionService();
ActionDefinition actionDef = actionService.getActionDefinition(actionName);
if (actionDef != null)
{
Action action = actionService.createAction(actionName);
scriptAction = new ScriptAction(this.services, action, actionDef);
scriptAction.setScope(getScope());
}
return scriptAction;
}
}
package org.alfresco.repo.jscript;
import java.util.List;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionDefinition;
import org.alfresco.service.cmr.action.ActionService;
/**
* Scripted Action service for describing and executing actions against Nodes.
*
* @author davidc
*/
public final class Actions extends BaseScopableProcessorExtension
{
/** Repository Service Registry */
private ServiceRegistry services;
/**
* Set the service registry
*
* @param serviceRegistry the service registry
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.services = serviceRegistry;
}
/**
* Gets the list of registered action names
*
* @return the registered action names
*/
public String[] getRegistered()
{
ActionService actionService = services.getActionService();
List<ActionDefinition> defs = actionService.getActionDefinitions();
String[] registered = new String[defs.size()];
int i = 0;
for (ActionDefinition def : defs)
{
registered[i++] = def.getName();
}
return registered;
}
/**
* Create an Action
*
* @param actionName
* the action name
* @return the action
*/
public ScriptAction create(String actionName)
{
ScriptAction scriptAction = null;
ActionService actionService = services.getActionService();
ActionDefinition actionDef = actionService.getActionDefinition(actionName);
if (actionDef != null)
{
Action action = actionService.createAction(actionName);
scriptAction = new ScriptAction(this.services, action, actionDef);
scriptAction.setScope(getScope());
}
return scriptAction;
}
}

View File

@@ -1,79 +1,79 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.namespace.QName;
import org.springframework.extensions.surf.util.ParameterCheck;
import org.mozilla.javascript.Scriptable;
/**
* Object representing an association
*
* @author Roy Wetherall
*/
public class Association implements Scopeable, Serializable
{
/** Serial version UUID*/
private static final long serialVersionUID = 897788515655487131L;
/** Service registry **/
private ServiceRegistry services;
/** Script scope **/
private Scriptable scope;
/** Association reference **/
private AssociationRef assocRef;
public Association(ServiceRegistry services, AssociationRef assocRef)
{
this(services, assocRef, null);
}
public Association(ServiceRegistry services, AssociationRef assocRef, Scriptable scope)
{
ParameterCheck.mandatory("Service registry", services);
ParameterCheck.mandatory("Association reference", assocRef);
this.services = services;
this.assocRef = assocRef;
if (scope != null)
{
this.scope = scope;
}
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
public AssociationRef getAssociationRef()
{
return this.assocRef;
}
public String getType()
{
return assocRef.getTypeQName().toString();
}
public QName getTypeQName()
{
return assocRef.getTypeQName();
}
public ScriptNode getSource()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, assocRef.getSourceRef());
}
public ScriptNode getTarget()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, assocRef.getTargetRef());
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.namespace.QName;
import org.springframework.extensions.surf.util.ParameterCheck;
import org.mozilla.javascript.Scriptable;
/**
* Object representing an association
*
* @author Roy Wetherall
*/
public class Association implements Scopeable, Serializable
{
/** Serial version UUID*/
private static final long serialVersionUID = 897788515655487131L;
/** Service registry **/
private ServiceRegistry services;
/** Script scope **/
private Scriptable scope;
/** Association reference **/
private AssociationRef assocRef;
public Association(ServiceRegistry services, AssociationRef assocRef)
{
this(services, assocRef, null);
}
public Association(ServiceRegistry services, AssociationRef assocRef, Scriptable scope)
{
ParameterCheck.mandatory("Service registry", services);
ParameterCheck.mandatory("Association reference", assocRef);
this.services = services;
this.assocRef = assocRef;
if (scope != null)
{
this.scope = scope;
}
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
public AssociationRef getAssociationRef()
{
return this.assocRef;
}
public String getType()
{
return assocRef.getTypeQName().toString();
}
public QName getTypeQName()
{
return assocRef.getTypeQName();
}
public ScriptNode getSource()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, assocRef.getSourceRef());
}
public ScriptNode getTarget()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, assocRef.getTargetRef());
}
}

View File

@@ -1,36 +1,36 @@
package org.alfresco.repo.jscript;
import org.alfresco.api.AlfrescoPublicApi;
import org.alfresco.repo.processor.BaseProcessorExtension;
import org.mozilla.javascript.Scriptable;
/**
* Abstract base class for a script implementation that requires a script execution scope.
*
* The scope is local to the currently executing script and therefore a ThreadLocal is required.
*
* @author Kevin Roast
*/
@AlfrescoPublicApi
public class BaseScopableProcessorExtension extends BaseProcessorExtension implements Scopeable
{
private static ThreadLocal<Scriptable> scope = new ThreadLocal<Scriptable>();
/**
* Set the Scriptable global scope
*
* @param scope relative global scope
*/
public void setScope(Scriptable scope)
{
BaseScopableProcessorExtension.scope.set(scope);
}
/**
* @return script global scope
*/
public Scriptable getScope()
{
return BaseScopableProcessorExtension.scope.get();
}
}
package org.alfresco.repo.jscript;
import org.alfresco.api.AlfrescoPublicApi;
import org.alfresco.repo.processor.BaseProcessorExtension;
import org.mozilla.javascript.Scriptable;
/**
* Abstract base class for a script implementation that requires a script execution scope.
*
* The scope is local to the currently executing script and therefore a ThreadLocal is required.
*
* @author Kevin Roast
*/
@AlfrescoPublicApi
public class BaseScopableProcessorExtension extends BaseProcessorExtension implements Scopeable
{
private static ThreadLocal<Scriptable> scope = new ThreadLocal<Scriptable>();
/**
* Set the Scriptable global scope
*
* @param scope relative global scope
*/
public void setScope(Scriptable scope)
{
BaseScopableProcessorExtension.scope.set(scope);
}
/**
* @return script global scope
*/
public Scriptable getScope()
{
return BaseScopableProcessorExtension.scope.get();
}
}

View File

@@ -1,85 +1,85 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import org.alfresco.service.ServiceRegistry;
import org.mozilla.javascript.Scriptable;
/**
* Object representing the behaviour information
*
* @author Roy Wetherall
*/
public class Behaviour implements Scopeable, Serializable
{
/** Serial version UID **/
private static final long serialVersionUID = 1936017361886646100L;
/** Service registry **/
private ServiceRegistry services;
/** Script scope **/
private Scriptable scope;
/** The name of the policy that this behaviour is linked to **/
private String name;
/** The behaviour argument values **/
private Object[] args;
/** Cached js converted argument values **/
private Serializable[] jsArgs;
/**
* Constructor
*
* @param services the service registry
* @param name the name of the policy associated with this behaviour
* @param args the argument values
*/
public Behaviour(ServiceRegistry services, String name, Object[] args)
{
this.services = services;
this.name = name;
this.args = args;
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
/**
* Get the policy name
*
* @return the name of the policy
*/
public String getName()
{
return this.name;
}
/**
* The argument values
*
* @return array containing the argument values
*/
public Serializable[] getArgs()
{
if (this.jsArgs == null)
{
ValueConverter valueConverter = new ValueConverter();
this.jsArgs = new Serializable[args.length];
int index = 0;
for (Object arg : this.args)
{
this.jsArgs[index] = valueConverter.convertValueForScript(services, this.scope, null, (Serializable)arg);
index ++;
}
}
return this.jsArgs;
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import org.alfresco.service.ServiceRegistry;
import org.mozilla.javascript.Scriptable;
/**
* Object representing the behaviour information
*
* @author Roy Wetherall
*/
public class Behaviour implements Scopeable, Serializable
{
/** Serial version UID **/
private static final long serialVersionUID = 1936017361886646100L;
/** Service registry **/
private ServiceRegistry services;
/** Script scope **/
private Scriptable scope;
/** The name of the policy that this behaviour is linked to **/
private String name;
/** The behaviour argument values **/
private Object[] args;
/** Cached js converted argument values **/
private Serializable[] jsArgs;
/**
* Constructor
*
* @param services the service registry
* @param name the name of the policy associated with this behaviour
* @param args the argument values
*/
public Behaviour(ServiceRegistry services, String name, Object[] args)
{
this.services = services;
this.name = name;
this.args = args;
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
/**
* Get the policy name
*
* @return the name of the policy
*/
public String getName()
{
return this.name;
}
/**
* The argument values
*
* @return array containing the argument values
*/
public Serializable[] getArgs()
{
if (this.jsArgs == null)
{
ValueConverter valueConverter = new ValueConverter();
this.jsArgs = new Serializable[args.length];
int index = 0;
for (Object arg : this.args)
{
this.jsArgs[index] = valueConverter.convertValueForScript(services, this.scope, null, (Serializable)arg);
index ++;
}
}
return this.jsArgs;
}
}

View File

@@ -1,186 +1,186 @@
package org.alfresco.repo.jscript;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.template.TemplateNode;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.TemplateImageResolver;
import org.alfresco.service.cmr.search.CategoryService;
import org.alfresco.service.namespace.QName;
/**
* Category Nodes from the classification helper have special support.
*/
public class CategoryTemplateNode extends TemplateNode
{
/**
* Constructor
*
* @param nodeRef NodeRef
* @param services ServiceRegistry
* @param resolver TemplateImageResolver
*/
public CategoryTemplateNode(NodeRef nodeRef, ServiceRegistry services, TemplateImageResolver resolver)
{
super(nodeRef, services, resolver);
}
@Override
public boolean getIsCategory()
{
return true;
}
/**
* @return all the member of a category
*/
public List<TemplateNode> getCategoryMembers()
{
if (getIsCategory())
{
return buildTemplateNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.MEMBERS, CategoryService.Depth.ANY));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* @return all the subcategories of a category
*/
public List<CategoryTemplateNode> getSubCategories()
{
if (getIsCategory())
{
return buildCategoryNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.SUB_CATEGORIES, CategoryService.Depth.ANY));
}
else
{
return Collections.<CategoryTemplateNode>emptyList();
}
}
/**
* @return members and subcategories of a category
*/
public List<TemplateNode> getMembersAndSubCategories()
{
if (getIsCategory())
{
return buildMixedNodeList(services.getCategoryService().getChildren(getNodeRef(), CategoryService.Mode.ALL,
CategoryService.Depth.ANY));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* @return all the immediate member of a category
*/
public List<TemplateNode> getImmediateCategoryMembers()
{
if (getIsCategory())
{
return buildTemplateNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.MEMBERS, CategoryService.Depth.IMMEDIATE));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* @return all the immediate subcategories of a category
*/
public List<CategoryTemplateNode> getImmediateSubCategories()
{
if (getIsCategory())
{
return buildCategoryNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.SUB_CATEGORIES, CategoryService.Depth.IMMEDIATE));
}
else
{
return Collections.<CategoryTemplateNode>emptyList();
}
}
/**
* @return immediate members and subcategories of a category
*/
public List<TemplateNode> getImmediateMembersAndSubCategories()
{
if (getIsCategory())
{
return buildMixedNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.ALL, CategoryService.Depth.IMMEDIATE));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* Support to build node lists from category service API calls.
*
* @param childRefs Collection<ChildAssociationRef>
*
* @return List of TemplateNode
*/
private List<TemplateNode> buildTemplateNodeList(Collection<ChildAssociationRef> childRefs)
{
List<TemplateNode> answer = new ArrayList<TemplateNode>(childRefs.size());
for (ChildAssociationRef ref : childRefs)
{
// create our Node representation from the NodeRef
TemplateNode child = new TemplateNode(ref.getChildRef(), this.services, this.imageResolver);
answer.add(child);
}
return answer;
}
private List<CategoryTemplateNode> buildCategoryNodeList(Collection<ChildAssociationRef> childRefs)
{
List<CategoryTemplateNode> answer = new ArrayList<CategoryTemplateNode>(childRefs.size());
for (ChildAssociationRef ref : childRefs)
{
// create our Node representation from the NodeRef
CategoryTemplateNode child = new CategoryTemplateNode(ref.getChildRef(), this.services, this.imageResolver);
answer.add(child);
}
return answer;
}
private List<TemplateNode> buildMixedNodeList(Collection<ChildAssociationRef> cars)
{
List<TemplateNode> nodes = new ArrayList<TemplateNode>(cars.size());
int i = 0;
for (ChildAssociationRef car : cars)
{
QName type = services.getNodeService().getType(car.getChildRef());
if (services.getDictionaryService().isSubClass(type, ContentModel.TYPE_CATEGORY))
{
nodes.add(new CategoryTemplateNode(car.getChildRef(), this.services, this.imageResolver));
}
else
{
nodes.add(new TemplateNode(car.getChildRef(), this.services, this.imageResolver));
}
}
return nodes;
}
}
package org.alfresco.repo.jscript;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.template.TemplateNode;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.TemplateImageResolver;
import org.alfresco.service.cmr.search.CategoryService;
import org.alfresco.service.namespace.QName;
/**
* Category Nodes from the classification helper have special support.
*/
public class CategoryTemplateNode extends TemplateNode
{
/**
* Constructor
*
* @param nodeRef NodeRef
* @param services ServiceRegistry
* @param resolver TemplateImageResolver
*/
public CategoryTemplateNode(NodeRef nodeRef, ServiceRegistry services, TemplateImageResolver resolver)
{
super(nodeRef, services, resolver);
}
@Override
public boolean getIsCategory()
{
return true;
}
/**
* @return all the member of a category
*/
public List<TemplateNode> getCategoryMembers()
{
if (getIsCategory())
{
return buildTemplateNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.MEMBERS, CategoryService.Depth.ANY));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* @return all the subcategories of a category
*/
public List<CategoryTemplateNode> getSubCategories()
{
if (getIsCategory())
{
return buildCategoryNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.SUB_CATEGORIES, CategoryService.Depth.ANY));
}
else
{
return Collections.<CategoryTemplateNode>emptyList();
}
}
/**
* @return members and subcategories of a category
*/
public List<TemplateNode> getMembersAndSubCategories()
{
if (getIsCategory())
{
return buildMixedNodeList(services.getCategoryService().getChildren(getNodeRef(), CategoryService.Mode.ALL,
CategoryService.Depth.ANY));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* @return all the immediate member of a category
*/
public List<TemplateNode> getImmediateCategoryMembers()
{
if (getIsCategory())
{
return buildTemplateNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.MEMBERS, CategoryService.Depth.IMMEDIATE));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* @return all the immediate subcategories of a category
*/
public List<CategoryTemplateNode> getImmediateSubCategories()
{
if (getIsCategory())
{
return buildCategoryNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.SUB_CATEGORIES, CategoryService.Depth.IMMEDIATE));
}
else
{
return Collections.<CategoryTemplateNode>emptyList();
}
}
/**
* @return immediate members and subcategories of a category
*/
public List<TemplateNode> getImmediateMembersAndSubCategories()
{
if (getIsCategory())
{
return buildMixedNodeList(services.getCategoryService().getChildren(getNodeRef(),
CategoryService.Mode.ALL, CategoryService.Depth.IMMEDIATE));
}
else
{
return Collections.<TemplateNode>emptyList();
}
}
/**
* Support to build node lists from category service API calls.
*
* @param childRefs Collection<ChildAssociationRef>
*
* @return List of TemplateNode
*/
private List<TemplateNode> buildTemplateNodeList(Collection<ChildAssociationRef> childRefs)
{
List<TemplateNode> answer = new ArrayList<TemplateNode>(childRefs.size());
for (ChildAssociationRef ref : childRefs)
{
// create our Node representation from the NodeRef
TemplateNode child = new TemplateNode(ref.getChildRef(), this.services, this.imageResolver);
answer.add(child);
}
return answer;
}
private List<CategoryTemplateNode> buildCategoryNodeList(Collection<ChildAssociationRef> childRefs)
{
List<CategoryTemplateNode> answer = new ArrayList<CategoryTemplateNode>(childRefs.size());
for (ChildAssociationRef ref : childRefs)
{
// create our Node representation from the NodeRef
CategoryTemplateNode child = new CategoryTemplateNode(ref.getChildRef(), this.services, this.imageResolver);
answer.add(child);
}
return answer;
}
private List<TemplateNode> buildMixedNodeList(Collection<ChildAssociationRef> cars)
{
List<TemplateNode> nodes = new ArrayList<TemplateNode>(cars.size());
int i = 0;
for (ChildAssociationRef car : cars)
{
QName type = services.getNodeService().getType(car.getChildRef());
if (services.getDictionaryService().isSubClass(type, ContentModel.TYPE_CATEGORY))
{
nodes.add(new CategoryTemplateNode(car.getChildRef(), this.services, this.imageResolver));
}
else
{
nodes.add(new TemplateNode(car.getChildRef(), this.services, this.imageResolver));
}
}
return nodes;
}
}

View File

@@ -1,95 +1,95 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.springframework.extensions.surf.util.ParameterCheck;
import org.mozilla.javascript.Scriptable;
/**
* Object representing a child association
*
* @author Roy Wetherall
*/
public class ChildAssociation implements Scopeable, Serializable
{
/** Serial version UUID **/
private static final long serialVersionUID = -2122640697340663213L;
/** Service registry **/
private ServiceRegistry services;
/** Script scope **/
private Scriptable scope;
/** Child association reference **/
private ChildAssociationRef childAssocRef;
public ChildAssociation(ServiceRegistry services, ChildAssociationRef childAssocRef)
{
this(services, childAssocRef, null);
}
/**
* Constructor
*
* @param services ServiceRegistry
* @param childAssocRef ChildAssociationRef
* @param scope Scriptable
*/
public ChildAssociation(ServiceRegistry services, ChildAssociationRef childAssocRef, Scriptable scope)
{
ParameterCheck.mandatory("Service registry", services);
ParameterCheck.mandatory("Child association reference", childAssocRef);
this.services = services;
this.childAssocRef = childAssocRef;
if (scope != null)
{
this.scope = scope;
}
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
public ChildAssociationRef getChildAssociationRef()
{
return this.childAssocRef;
}
public String getType()
{
return childAssocRef.getTypeQName().toString();
}
public String getName()
{
return childAssocRef.getQName().toString();
}
public ScriptNode getParent()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, childAssocRef.getParentRef());
}
public ScriptNode getChild()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, childAssocRef.getChildRef());
}
public boolean isPrimary()
{
return this.childAssocRef.isPrimary();
}
public int getNthSibling()
{
return this.childAssocRef.getNthSibling();
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.springframework.extensions.surf.util.ParameterCheck;
import org.mozilla.javascript.Scriptable;
/**
* Object representing a child association
*
* @author Roy Wetherall
*/
public class ChildAssociation implements Scopeable, Serializable
{
/** Serial version UUID **/
private static final long serialVersionUID = -2122640697340663213L;
/** Service registry **/
private ServiceRegistry services;
/** Script scope **/
private Scriptable scope;
/** Child association reference **/
private ChildAssociationRef childAssocRef;
public ChildAssociation(ServiceRegistry services, ChildAssociationRef childAssocRef)
{
this(services, childAssocRef, null);
}
/**
* Constructor
*
* @param services ServiceRegistry
* @param childAssocRef ChildAssociationRef
* @param scope Scriptable
*/
public ChildAssociation(ServiceRegistry services, ChildAssociationRef childAssocRef, Scriptable scope)
{
ParameterCheck.mandatory("Service registry", services);
ParameterCheck.mandatory("Child association reference", childAssocRef);
this.services = services;
this.childAssocRef = childAssocRef;
if (scope != null)
{
this.scope = scope;
}
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
public ChildAssociationRef getChildAssociationRef()
{
return this.childAssocRef;
}
public String getType()
{
return childAssocRef.getTypeQName().toString();
}
public String getName()
{
return childAssocRef.getQName().toString();
}
public ScriptNode getParent()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, childAssocRef.getParentRef());
}
public ScriptNode getChild()
{
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, this.scope, null, childAssocRef.getChildRef());
}
public boolean isPrimary()
{
return this.childAssocRef.isPrimary();
}
public int getNthSibling()
{
return this.childAssocRef.getNthSibling();
}
}

View File

@@ -1,113 +1,113 @@
package org.alfresco.repo.jscript;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.scripts.ScriptException;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* Classpath script location object.
*
* @author Roy Wetherall
*/
public class ClasspathScriptLocation implements ScriptLocation
{
/** Classpath location **/
private final String location;
/**
* Constructor
*
* @param location the classpath location
*/
public ClasspathScriptLocation(String location)
{
ParameterCheck.mandatory("Location", location);
this.location = location;
}
/**
* @see org.alfresco.service.cmr.repository.ScriptLocation#getInputStream()
*/
public InputStream getInputStream()
{
InputStream stream = getClass().getClassLoader().getResourceAsStream(location);
if (stream == null)
{
throw new AlfrescoRuntimeException("Unable to load classpath resource: " + location);
}
return stream;
}
/**
* @see org.alfresco.service.cmr.repository.ScriptLocation#getReader()
*/
public Reader getReader()
{
Reader reader = null;
try
{
InputStream stream = getClass().getClassLoader().getResourceAsStream(location);
if (stream == null)
{
throw new AlfrescoRuntimeException("Unable to load classpath resource: " + location);
}
reader = new InputStreamReader(stream);
}
catch (Throwable err)
{
throw new ScriptException("Failed to load classpath resource '" + location + "': " + err.getMessage(), err);
}
return reader;
}
/**
* @see org.alfresco.service.cmr.repository.ScriptLocation#getPath()
*/
public String getPath()
{
return this.location;
}
public boolean isCachable()
{
return true;
}
public boolean isSecure()
{
return true;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
else if (obj == null || !(obj instanceof ClasspathScriptLocation))
{
return false;
}
ClasspathScriptLocation other = (ClasspathScriptLocation)obj;
return this.location.equals(other.location);
}
@Override
public int hashCode()
{
return 37 * this.location.hashCode();
}
@Override
public String toString()
{
return this.location.toString();
}
}
package org.alfresco.repo.jscript;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.scripts.ScriptException;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* Classpath script location object.
*
* @author Roy Wetherall
*/
public class ClasspathScriptLocation implements ScriptLocation
{
/** Classpath location **/
private final String location;
/**
* Constructor
*
* @param location the classpath location
*/
public ClasspathScriptLocation(String location)
{
ParameterCheck.mandatory("Location", location);
this.location = location;
}
/**
* @see org.alfresco.service.cmr.repository.ScriptLocation#getInputStream()
*/
public InputStream getInputStream()
{
InputStream stream = getClass().getClassLoader().getResourceAsStream(location);
if (stream == null)
{
throw new AlfrescoRuntimeException("Unable to load classpath resource: " + location);
}
return stream;
}
/**
* @see org.alfresco.service.cmr.repository.ScriptLocation#getReader()
*/
public Reader getReader()
{
Reader reader = null;
try
{
InputStream stream = getClass().getClassLoader().getResourceAsStream(location);
if (stream == null)
{
throw new AlfrescoRuntimeException("Unable to load classpath resource: " + location);
}
reader = new InputStreamReader(stream);
}
catch (Throwable err)
{
throw new ScriptException("Failed to load classpath resource '" + location + "': " + err.getMessage(), err);
}
return reader;
}
/**
* @see org.alfresco.service.cmr.repository.ScriptLocation#getPath()
*/
public String getPath()
{
return this.location;
}
public boolean isCachable()
{
return true;
}
public boolean isSecure()
{
return true;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
else if (obj == null || !(obj instanceof ClasspathScriptLocation))
{
return false;
}
ClasspathScriptLocation other = (ClasspathScriptLocation)obj;
return this.location.equals(other.location);
}
@Override
public int hashCode()
{
return 37 * this.location.hashCode();
}
@Override
public String toString()
{
return this.location.toString();
}
}

View File

@@ -1,81 +1,81 @@
package org.alfresco.repo.jscript;
import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.namespace.NamespacePrefixResolver;
import org.alfresco.service.namespace.NamespacePrefixResolverProvider;
import org.alfresco.service.namespace.QName;
/**
* Specialised map class for supporting the initialisation of 'cm:content' properties for JavaScript API
* objects. The JavaScript needs supporting objects to be initialised for certain data-types. If the
* 'cm:content' property is not already initialised then it must be created on demand or it will not be
* available to the users of the API. See AR-1673.
*
* @author Kevin Roast
*/
public class ContentAwareScriptableQNameMap<K,V> extends ScriptableQNameMap<K,V>
{
private ServiceRegistry services;
private ScriptNode factory;
/**
* Constructor
*
* @param factory Factory to provide further ScriptNode objects
* @param services ServiceRegistry
*/
public ContentAwareScriptableQNameMap(final ScriptNode factory, final ServiceRegistry services)
{
super(new NamespacePrefixResolverProvider(){
public NamespacePrefixResolver getNamespacePrefixResolver()
{
return services.getNamespaceService();
}
});
this.services = services;
this.factory = factory;
}
/* (non-Javadoc)
* @see org.alfresco.service.namespace.QNameMap#get(java.lang.Object)
*/
@Override
public Object get(Object name)
{
Object value = super.get(name);
if (value == null)
{
// convert the key to a qname and look up the data-type for the property
QName qname = QName.resolveToQName(getResolver(), name.toString());
PropertyDefinition propDef = this.services.getDictionaryService().getProperty(qname);
if (propDef != null && DataTypeDefinition.CONTENT.equals(propDef.getDataType().getName()))
{
// found a valid cm:content property that is not initialised
String mimetype = null;
if (qname.equals(ContentModel.PROP_CONTENT))
{
String fileName = (String)get("cm:name");
if (fileName != null)
{
// We don't have any content, so just use the filename when
// trying to guess the mimetype for this
mimetype = this.services.getMimetypeService().guessMimetype(fileName);
}
}
ContentData cdata = new ContentData(null, mimetype, 0L, "UTF-8");
// create the JavaScript API object we need
value = factory.new ScriptContentData(cdata, qname);
// and store it so it is available to the API user
put(name, value);
}
}
return value;
}
}
package org.alfresco.repo.jscript;
import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.namespace.NamespacePrefixResolver;
import org.alfresco.service.namespace.NamespacePrefixResolverProvider;
import org.alfresco.service.namespace.QName;
/**
* Specialised map class for supporting the initialisation of 'cm:content' properties for JavaScript API
* objects. The JavaScript needs supporting objects to be initialised for certain data-types. If the
* 'cm:content' property is not already initialised then it must be created on demand or it will not be
* available to the users of the API. See AR-1673.
*
* @author Kevin Roast
*/
public class ContentAwareScriptableQNameMap<K,V> extends ScriptableQNameMap<K,V>
{
private ServiceRegistry services;
private ScriptNode factory;
/**
* Constructor
*
* @param factory Factory to provide further ScriptNode objects
* @param services ServiceRegistry
*/
public ContentAwareScriptableQNameMap(final ScriptNode factory, final ServiceRegistry services)
{
super(new NamespacePrefixResolverProvider(){
public NamespacePrefixResolver getNamespacePrefixResolver()
{
return services.getNamespaceService();
}
});
this.services = services;
this.factory = factory;
}
/* (non-Javadoc)
* @see org.alfresco.service.namespace.QNameMap#get(java.lang.Object)
*/
@Override
public Object get(Object name)
{
Object value = super.get(name);
if (value == null)
{
// convert the key to a qname and look up the data-type for the property
QName qname = QName.resolveToQName(getResolver(), name.toString());
PropertyDefinition propDef = this.services.getDictionaryService().getProperty(qname);
if (propDef != null && DataTypeDefinition.CONTENT.equals(propDef.getDataType().getName()))
{
// found a valid cm:content property that is not initialised
String mimetype = null;
if (qname.equals(ContentModel.PROP_CONTENT))
{
String fileName = (String)get("cm:name");
if (fileName != null)
{
// We don't have any content, so just use the filename when
// trying to guess the mimetype for this
mimetype = this.services.getMimetypeService().guessMimetype(fileName);
}
}
ContentData cdata = new ContentData(null, mimetype, 0L, "UTF-8");
// create the JavaScript API object we need
value = factory.new ScriptContentData(cdata, qname);
// and store it so it is available to the API user
put(name, value);
}
}
return value;
}
}

View File

@@ -1,69 +1,69 @@
package org.alfresco.repo.jscript;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.alfresco.service.cmr.repository.ScriptService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* Quartz job that executes a scheduled JS script.
*
* @author Roy Wetherall
*/
public class ExecuteScriptJob implements Job
{
private static final String PARAM_SCRIPT_LOCATION = "scriptLocation";
private static final String PARAM_SCRIPT_SERVICE = "scriptService";
private static final String PARAM_AUTHENTICATION_COMPONENT = "authenticationComponent";
/**
* Executes the scheduled script
*
* @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
*/
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDataMap jobData = context.getJobDetail().getJobDataMap();
// Get the script service from the job map
Object scriptServiceObj = jobData.get(PARAM_SCRIPT_SERVICE);
if (scriptServiceObj == null || !(scriptServiceObj instanceof ScriptService))
{
throw new AlfrescoRuntimeException(
"ExecuteScriptJob data must contain valid script service");
}
// Get the script location from the job map
Object scriptLocationObj = jobData.get(PARAM_SCRIPT_LOCATION);
if (scriptLocationObj == null || !(scriptLocationObj instanceof ScriptLocation))
{
throw new AlfrescoRuntimeException(
"ExecuteScriptJob data must contain valid script location");
}
// Get the authentication component from the job map
Object authenticationComponentObj = jobData.get(PARAM_AUTHENTICATION_COMPONENT);
if (authenticationComponentObj == null || !(authenticationComponentObj instanceof AuthenticationComponent))
{
throw new AlfrescoRuntimeException(
"ExecuteScriptJob data must contain valid authentication component");
}
// Execute the script as the system user
((AuthenticationComponent)authenticationComponentObj).setSystemUserAsCurrentUser();
try
{
// Execute the script
((ScriptService)scriptServiceObj).executeScript((ScriptLocation)scriptLocationObj, null);
}
finally
{
((AuthenticationComponent)authenticationComponentObj).clearCurrentSecurityContext();
}
}
}
package org.alfresco.repo.jscript;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.alfresco.service.cmr.repository.ScriptService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* Quartz job that executes a scheduled JS script.
*
* @author Roy Wetherall
*/
public class ExecuteScriptJob implements Job
{
private static final String PARAM_SCRIPT_LOCATION = "scriptLocation";
private static final String PARAM_SCRIPT_SERVICE = "scriptService";
private static final String PARAM_AUTHENTICATION_COMPONENT = "authenticationComponent";
/**
* Executes the scheduled script
*
* @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
*/
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDataMap jobData = context.getJobDetail().getJobDataMap();
// Get the script service from the job map
Object scriptServiceObj = jobData.get(PARAM_SCRIPT_SERVICE);
if (scriptServiceObj == null || !(scriptServiceObj instanceof ScriptService))
{
throw new AlfrescoRuntimeException(
"ExecuteScriptJob data must contain valid script service");
}
// Get the script location from the job map
Object scriptLocationObj = jobData.get(PARAM_SCRIPT_LOCATION);
if (scriptLocationObj == null || !(scriptLocationObj instanceof ScriptLocation))
{
throw new AlfrescoRuntimeException(
"ExecuteScriptJob data must contain valid script location");
}
// Get the authentication component from the job map
Object authenticationComponentObj = jobData.get(PARAM_AUTHENTICATION_COMPONENT);
if (authenticationComponentObj == null || !(authenticationComponentObj instanceof AuthenticationComponent))
{
throw new AlfrescoRuntimeException(
"ExecuteScriptJob data must contain valid authentication component");
}
// Execute the script as the system user
((AuthenticationComponent)authenticationComponentObj).setSystemUserAsCurrentUser();
try
{
// Execute the script
((ScriptService)scriptServiceObj).executeScript((ScriptLocation)scriptLocationObj, null);
}
finally
{
((AuthenticationComponent)authenticationComponentObj).clearCurrentSecurityContext();
}
}
}

View File

@@ -1,214 +1,214 @@
package org.alfresco.repo.jscript;
import java.util.Iterator;
import java.util.Map;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Wrapper;
/**
* Wrapper for exposing maps in Rhino scripts.
*
* @author davidc
*/
public class NativeMap implements Scriptable, Wrapper
{
private static final long serialVersionUID = 3664761893203964569L;
private Map<Object, Object> map;
private Scriptable parentScope;
private Scriptable prototype;
/**
* Construct
*
* @param scope Scriptable
* @param map Map<Object, Object>
* @return native map
*/
public static NativeMap wrap(Scriptable scope, Map<Object, Object> map)
{
return new NativeMap(scope, map);
}
/**
* Construct
*
* @param scope Scriptable
* @param map Map<Object, Object>
*/
public NativeMap(Scriptable scope, Map<Object, Object> map)
{
this.parentScope = scope;
this.map = map;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Wrapper#unwrap()
*/
public Object unwrap()
{
return map;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
public String getClassName()
{
return "NativeMap";
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#get(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public Object get(String name, Scriptable start)
{
// get the property from the underlying QName map
if ("length".equals(name))
{
return map.size();
}
else
{
return map.get(name);
}
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#get(int, org.mozilla.javascript.Scriptable)
*/
public Object get(int index, Scriptable start)
{
Object value = null;
int i=0;
Iterator itrValues = map.values().iterator();
while (i++ <= index && itrValues.hasNext())
{
value = itrValues.next();
}
return value;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#has(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public boolean has(String name, Scriptable start)
{
// locate the property in the underlying map
return map.containsKey(name);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#has(int, org.mozilla.javascript.Scriptable)
*/
public boolean has(int index, Scriptable start)
{
return (index >= 0 && map.values().size() > index);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
@SuppressWarnings("unchecked")
public void put(String name, Scriptable start, Object value)
{
map.put(name, value);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#put(int, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(int index, Scriptable start, Object value)
{
// TODO: implement?
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
public void delete(String name)
{
map.remove(name);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#delete(int)
*/
public void delete(int index)
{
int i=0;
Iterator itrKeys = map.keySet().iterator();
while (i <= index && itrKeys.hasNext())
{
Object key = itrKeys.next();
if (i == index)
{
map.remove(key);
break;
}
}
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getPrototype()
*/
public Scriptable getPrototype()
{
return this.prototype;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#setPrototype(org.mozilla.javascript.Scriptable)
*/
public void setPrototype(Scriptable prototype)
{
this.prototype = prototype;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getParentScope()
*/
public Scriptable getParentScope()
{
return this.parentScope;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#setParentScope(org.mozilla.javascript.Scriptable)
*/
public void setParentScope(Scriptable parent)
{
this.parentScope = parent;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getIds()
*/
public Object[] getIds()
{
return map.keySet().toArray();
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getDefaultValue(java.lang.Class)
*/
public Object getDefaultValue(@SuppressWarnings("rawtypes") Class hint)
{
return String.valueOf(map);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#hasInstance(org.mozilla.javascript.Scriptable)
*/
public boolean hasInstance(Scriptable value)
{
if (!(value instanceof Wrapper))
return false;
Object instance = ((Wrapper)value).unwrap();
return Map.class.isInstance(instance);
}
}
package org.alfresco.repo.jscript;
import java.util.Iterator;
import java.util.Map;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Wrapper;
/**
* Wrapper for exposing maps in Rhino scripts.
*
* @author davidc
*/
public class NativeMap implements Scriptable, Wrapper
{
private static final long serialVersionUID = 3664761893203964569L;
private Map<Object, Object> map;
private Scriptable parentScope;
private Scriptable prototype;
/**
* Construct
*
* @param scope Scriptable
* @param map Map<Object, Object>
* @return native map
*/
public static NativeMap wrap(Scriptable scope, Map<Object, Object> map)
{
return new NativeMap(scope, map);
}
/**
* Construct
*
* @param scope Scriptable
* @param map Map<Object, Object>
*/
public NativeMap(Scriptable scope, Map<Object, Object> map)
{
this.parentScope = scope;
this.map = map;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Wrapper#unwrap()
*/
public Object unwrap()
{
return map;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
public String getClassName()
{
return "NativeMap";
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#get(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public Object get(String name, Scriptable start)
{
// get the property from the underlying QName map
if ("length".equals(name))
{
return map.size();
}
else
{
return map.get(name);
}
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#get(int, org.mozilla.javascript.Scriptable)
*/
public Object get(int index, Scriptable start)
{
Object value = null;
int i=0;
Iterator itrValues = map.values().iterator();
while (i++ <= index && itrValues.hasNext())
{
value = itrValues.next();
}
return value;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#has(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public boolean has(String name, Scriptable start)
{
// locate the property in the underlying map
return map.containsKey(name);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#has(int, org.mozilla.javascript.Scriptable)
*/
public boolean has(int index, Scriptable start)
{
return (index >= 0 && map.values().size() > index);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
@SuppressWarnings("unchecked")
public void put(String name, Scriptable start, Object value)
{
map.put(name, value);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#put(int, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(int index, Scriptable start, Object value)
{
// TODO: implement?
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
public void delete(String name)
{
map.remove(name);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#delete(int)
*/
public void delete(int index)
{
int i=0;
Iterator itrKeys = map.keySet().iterator();
while (i <= index && itrKeys.hasNext())
{
Object key = itrKeys.next();
if (i == index)
{
map.remove(key);
break;
}
}
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getPrototype()
*/
public Scriptable getPrototype()
{
return this.prototype;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#setPrototype(org.mozilla.javascript.Scriptable)
*/
public void setPrototype(Scriptable prototype)
{
this.prototype = prototype;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getParentScope()
*/
public Scriptable getParentScope()
{
return this.parentScope;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#setParentScope(org.mozilla.javascript.Scriptable)
*/
public void setParentScope(Scriptable parent)
{
this.parentScope = parent;
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getIds()
*/
public Object[] getIds()
{
return map.keySet().toArray();
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#getDefaultValue(java.lang.Class)
*/
public Object getDefaultValue(@SuppressWarnings("rawtypes") Class hint)
{
return String.valueOf(map);
}
/* (non-Javadoc)
* @see org.mozilla.javascript.Scriptable#hasInstance(org.mozilla.javascript.Scriptable)
*/
public boolean hasInstance(Scriptable value)
{
if (!(value instanceof Wrapper))
return false;
Object instance = ((Wrapper)value).unwrap();
return Map.class.isInstance(instance);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,61 +1,61 @@
package org.alfresco.repo.jscript;
import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* Scripted Presence service for determining online status of People.
*
* @author Mike Hatfield
*/
public final class Presence extends BaseScopableProcessorExtension
{
/** Repository Service Registry */
private ServiceRegistry services;
/**
* Set the service registry
*
* @param serviceRegistry the service registry
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.services = serviceRegistry;
}
/**
* Gets whether the Person has configured Presence parameters
*
* @param person the person to query
*
* @return true if this person is configured for presence
*/
public boolean hasPresence(ScriptNode person)
{
ParameterCheck.mandatory("Person", person);
String presenceProvider = (String)person.getProperties().get(ContentModel.PROP_PRESENCEPROVIDER);
String presenceUsername = (String)person.getProperties().get(ContentModel.PROP_PRESENCEUSERNAME);
return (!"".equals((presenceProvider)) && (!"".equals(presenceUsername)));
}
/**
* Query current online status of given person
*
* @param person the person to query
*
* @return string indicating online presence status
*/
public String getDetails(ScriptNode person)
{
ParameterCheck.mandatory("Person", person);
String presenceProvider = (String)person.getProperties().get(ContentModel.PROP_PRESENCEPROVIDER);
String presenceUsername = (String)person.getProperties().get(ContentModel.PROP_PRESENCEUSERNAME);
String detail = presenceProvider + "|" + presenceUsername;
return detail;
}
}
package org.alfresco.repo.jscript;
import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* Scripted Presence service for determining online status of People.
*
* @author Mike Hatfield
*/
public final class Presence extends BaseScopableProcessorExtension
{
/** Repository Service Registry */
private ServiceRegistry services;
/**
* Set the service registry
*
* @param serviceRegistry the service registry
*/
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.services = serviceRegistry;
}
/**
* Gets whether the Person has configured Presence parameters
*
* @param person the person to query
*
* @return true if this person is configured for presence
*/
public boolean hasPresence(ScriptNode person)
{
ParameterCheck.mandatory("Person", person);
String presenceProvider = (String)person.getProperties().get(ContentModel.PROP_PRESENCEPROVIDER);
String presenceUsername = (String)person.getProperties().get(ContentModel.PROP_PRESENCEUSERNAME);
return (!"".equals((presenceProvider)) && (!"".equals(presenceUsername)));
}
/**
* Query current online status of given person
*
* @param person the person to query
*
* @return string indicating online presence status
*/
public String getDetails(ScriptNode person)
{
ParameterCheck.mandatory("Person", person);
String presenceProvider = (String)person.getProperties().get(ContentModel.PROP_PRESENCEPROVIDER);
String presenceUsername = (String)person.getProperties().get(ContentModel.PROP_PRESENCEUSERNAME);
String detail = presenceProvider + "|" + presenceUsername;
return detail;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,21 +1,21 @@
package org.alfresco.repo.jscript;
import org.mozilla.javascript.Scriptable;
/**
* Interface contract for objects that supporting setting of the global scripting scope.
* This is used to mark objects that are not themselves natively scriptable (i.e. they are
* wrapped Java objects) but need to access the global scope for the purposes of JavaScript
* object creation etc.
*
* @author Kevin Roast
*/
public interface Scopeable
{
/**
* Set the Scriptable global scope
*
* @param scope relative global scope
*/
void setScope(Scriptable scope);
}
package org.alfresco.repo.jscript;
import org.mozilla.javascript.Scriptable;
/**
* Interface contract for objects that supporting setting of the global scripting scope.
* This is used to mark objects that are not themselves natively scriptable (i.e. they are
* wrapped Java objects) but need to access the global scope for the purposes of JavaScript
* object creation etc.
*
* @author Kevin Roast
*/
public interface Scopeable
{
/**
* Set the Scriptable global scope
*
* @param scope relative global scope
*/
void setScope(Scriptable scope);
}

View File

@@ -1,401 +1,401 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.Map;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionDefinition;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Wrapper;
/**
* Scriptable Action
*
* @author davidc
*/
public class ScriptAction implements Serializable, Scopeable
{
private static final long serialVersionUID = 5794161358406531996L;
/** Root scope for this object */
private Scriptable scope;
/** Converter with knowledge of action parameter values */
private ActionValueConverter converter;
/** Action state */
protected Action action;
protected ActionDefinition actionDef;
protected ServiceRegistry services;
private ActionService actionService;
private NamespaceService namespaceService;
private TransactionService transactionService;
private ScriptableParameterMap<String, Serializable> parameters = null;
/**
* Construct
*
* @param action
* Alfresco action
*/
public ScriptAction(ServiceRegistry services, Action action, ActionDefinition actionDef)
{
this.services = services;
this.actionService = services.getActionService();
this.namespaceService = services.getNamespaceService();
this.transactionService = services.getTransactionService();
this.action = action;
this.actionDef = actionDef;
this.converter = new ActionValueConverter();
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
/**
* Returns the action name
*
* @return action name
*/
public String getName()
{
return this.actionDef.getName();
}
/**
* Return all the properties known about this node. The Map returned implements the Scriptable interface to allow access to the properties via JavaScript associative array
* access. This means properties of a node can be access thus: <code>node.properties["name"]</code>
*
* @return Map of properties for this Node.
*/
@SuppressWarnings("synthetic-access")
public Map<String, Serializable> getParameters()
{
if (this.parameters == null)
{
// this Map implements the Scriptable interface for native JS syntax property access
this.parameters = new ScriptableParameterMap<String, Serializable>();
Map<String, Serializable> actionParams = this.action.getParameterValues();
for (Map.Entry<String, Serializable> entry : actionParams.entrySet())
{
String name = entry.getKey();
this.parameters.put(name, converter.convertActionParamForScript(name, entry.getValue()));
}
this.parameters.setModified(false);
}
return this.parameters;
}
/**
* Execute action. The existing transaction will be joined.
*
* @param node
* the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void execute(ScriptNode node)
{
performParamConversionForRepo();
executeImpl(node);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
// Reset the actioned upon node
node.reset();
}
/**
* Execute action. The existing transaction will be joined.
*
* @param node
* the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void executeAsynchronously(ScriptNode node)
{
performParamConversionForRepo();
executeAsynchronouslyImpl(node);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
// Reset the actioned upon node
node.reset();
}
protected void executeImpl(ScriptNode node)
{
actionService.executeAction(action, node.getNodeRef());
}
protected void executeAsynchronouslyImpl(ScriptNode node)
{
actionService.executeAction(action, node.getNodeRef(), true, true);
}
/**
* Execute action, optionally starting a new, potentially read-only transaction.
*
* @param node
* the node to execute action upon
* @param newTxn
* <tt>true</tt> to start a new, isolated transaction
*
* @see RetryingTransactionHelper#doInTransaction(RetryingTransactionCallback, boolean, boolean)
*/
@SuppressWarnings("synthetic-access")
public void execute(final ScriptNode node, boolean readOnly, boolean newTxn)
{
performParamConversionForRepo();
RetryingTransactionCallback<Object> executionActionCallback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
executeImpl(node);
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(
executionActionCallback,
readOnly,
newTxn);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
// Reset the actioned upon node
node.reset();
}
/**
* Execute action. The existing transaction will be joined.
*
* @param nodeRef
* the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void execute(NodeRef nodeRef)
{
performParamConversionForRepo();
actionService.executeAction(action, nodeRef);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
}
/**
* Execute action, optionally starting a new, potentially read-only transaction.
*
* @param nodeRef
* the node to execute action upon
* @param newTxn
* <tt>true</tt> to start a new, isolated transaction
*
* @see RetryingTransactionHelper#doInTransaction(RetryingTransactionCallback, boolean, boolean)
*/
@SuppressWarnings("synthetic-access")
public void execute(final NodeRef nodeRef, boolean readOnly, boolean newTxn)
{
performParamConversionForRepo();
RetryingTransactionCallback<Object> executionActionCallback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
actionService.executeAction(action, nodeRef);
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(
executionActionCallback,
readOnly,
newTxn);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
}
protected void performParamConversionForRepo() {
if (this.parameters != null && this.parameters.isModified())
{
Map<String, Serializable> actionParams = action.getParameterValues();
actionParams.clear();
for (Map.Entry<String, Serializable> entry : this.parameters.entrySet())
{
// perform the conversion from script wrapper object to repo serializable values
String name = entry.getKey();
Serializable value = converter.convertActionParamForRepo(name, entry.getValue());
actionParams.put(name, value);
}
}
}
/**
* Value converter with specific knowledge of action parameters
*
* @author davidc
*/
private class ActionValueConverter extends ValueConverter
{
/**
* Convert Action Parameter for Script usage
*
* @param paramName
* parameter name
* @param value
* value to convert
* @return converted value
*/
@SuppressWarnings("synthetic-access")
public Serializable convertActionParamForScript(String paramName, Serializable value)
{
ParameterDefinition paramDef = actionDef.getParameterDefintion(paramName);
if (paramDef != null && paramDef.getType().equals(DataTypeDefinition.QNAME))
{
return ((QName) value).toPrefixString(namespaceService);
}
else
{
return convertValueForScript(services, scope, null, value);
}
}
/**
* Convert Action Parameter for Java usage
*
* @param paramName
* parameter name
* @param value
* value to convert
* @return converted value
*/
@SuppressWarnings("synthetic-access")
public Serializable convertActionParamForRepo(String paramName, Serializable value)
{
ParameterDefinition paramDef = actionDef.getParameterDefintion(paramName);
if (paramDef != null && paramDef.getType().equals(DataTypeDefinition.QNAME))
{
if (value instanceof Wrapper)
{
// unwrap a Java object from a JavaScript wrapper
// recursively call this method to convert the unwrapped value
return convertActionParamForRepo(paramName, (Serializable) ((Wrapper) value).unwrap());
}
else
{
if (value instanceof String)
{
String stringQName = (String) value;
if (stringQName.startsWith("{"))
{
return QName.createQName(stringQName);
}
else
{
return QName.createQName(stringQName, namespaceService);
}
}
else
{
return value;
}
}
}
else
{
return convertValueForRepo(value);
}
}
}
/**
* Scripted Parameter map with modified flag.
*
* @author davidc
*/
public static final class ScriptableParameterMap<K, V> extends ScriptableHashMap<K, V>
{
private static final long serialVersionUID = 574661815973241554L;
private boolean modified = false;
/**
* Is this a modified parameter map?
*
* @return true => modified
*/
/* package */boolean isModified()
{
return modified;
}
/**
* Set explicitly whether this map is modified
*
* @param modified
* true => modified, false => not modified
*/
/* package */void setModified(boolean modified)
{
this.modified = modified;
}
/*
* (non-Javadoc)
*
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
@Override
public String getClassName()
{
return "ScriptableParameterMap";
}
/*
* (non-Javadoc)
*
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
@Override
public void delete(String name)
{
super.delete(name);
setModified(true);
}
/*
* (non-Javadoc)
*
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
@Override
public void put(String name, Scriptable start, Object value)
{
super.put(name, start, value);
setModified(true);
}
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.Map;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionDefinition;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Wrapper;
/**
* Scriptable Action
*
* @author davidc
*/
public class ScriptAction implements Serializable, Scopeable
{
private static final long serialVersionUID = 5794161358406531996L;
/** Root scope for this object */
private Scriptable scope;
/** Converter with knowledge of action parameter values */
private ActionValueConverter converter;
/** Action state */
protected Action action;
protected ActionDefinition actionDef;
protected ServiceRegistry services;
private ActionService actionService;
private NamespaceService namespaceService;
private TransactionService transactionService;
private ScriptableParameterMap<String, Serializable> parameters = null;
/**
* Construct
*
* @param action
* Alfresco action
*/
public ScriptAction(ServiceRegistry services, Action action, ActionDefinition actionDef)
{
this.services = services;
this.actionService = services.getActionService();
this.namespaceService = services.getNamespaceService();
this.transactionService = services.getTransactionService();
this.action = action;
this.actionDef = actionDef;
this.converter = new ActionValueConverter();
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
/**
* Returns the action name
*
* @return action name
*/
public String getName()
{
return this.actionDef.getName();
}
/**
* Return all the properties known about this node. The Map returned implements the Scriptable interface to allow access to the properties via JavaScript associative array
* access. This means properties of a node can be access thus: <code>node.properties["name"]</code>
*
* @return Map of properties for this Node.
*/
@SuppressWarnings("synthetic-access")
public Map<String, Serializable> getParameters()
{
if (this.parameters == null)
{
// this Map implements the Scriptable interface for native JS syntax property access
this.parameters = new ScriptableParameterMap<String, Serializable>();
Map<String, Serializable> actionParams = this.action.getParameterValues();
for (Map.Entry<String, Serializable> entry : actionParams.entrySet())
{
String name = entry.getKey();
this.parameters.put(name, converter.convertActionParamForScript(name, entry.getValue()));
}
this.parameters.setModified(false);
}
return this.parameters;
}
/**
* Execute action. The existing transaction will be joined.
*
* @param node
* the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void execute(ScriptNode node)
{
performParamConversionForRepo();
executeImpl(node);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
// Reset the actioned upon node
node.reset();
}
/**
* Execute action. The existing transaction will be joined.
*
* @param node
* the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void executeAsynchronously(ScriptNode node)
{
performParamConversionForRepo();
executeAsynchronouslyImpl(node);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
// Reset the actioned upon node
node.reset();
}
protected void executeImpl(ScriptNode node)
{
actionService.executeAction(action, node.getNodeRef());
}
protected void executeAsynchronouslyImpl(ScriptNode node)
{
actionService.executeAction(action, node.getNodeRef(), true, true);
}
/**
* Execute action, optionally starting a new, potentially read-only transaction.
*
* @param node
* the node to execute action upon
* @param newTxn
* <tt>true</tt> to start a new, isolated transaction
*
* @see RetryingTransactionHelper#doInTransaction(RetryingTransactionCallback, boolean, boolean)
*/
@SuppressWarnings("synthetic-access")
public void execute(final ScriptNode node, boolean readOnly, boolean newTxn)
{
performParamConversionForRepo();
RetryingTransactionCallback<Object> executionActionCallback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
executeImpl(node);
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(
executionActionCallback,
readOnly,
newTxn);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
// Reset the actioned upon node
node.reset();
}
/**
* Execute action. The existing transaction will be joined.
*
* @param nodeRef
* the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void execute(NodeRef nodeRef)
{
performParamConversionForRepo();
actionService.executeAction(action, nodeRef);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
}
/**
* Execute action, optionally starting a new, potentially read-only transaction.
*
* @param nodeRef
* the node to execute action upon
* @param newTxn
* <tt>true</tt> to start a new, isolated transaction
*
* @see RetryingTransactionHelper#doInTransaction(RetryingTransactionCallback, boolean, boolean)
*/
@SuppressWarnings("synthetic-access")
public void execute(final NodeRef nodeRef, boolean readOnly, boolean newTxn)
{
performParamConversionForRepo();
RetryingTransactionCallback<Object> executionActionCallback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
actionService.executeAction(action, nodeRef);
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(
executionActionCallback,
readOnly,
newTxn);
// Parameters may have been updated by action execution, so reset cache
this.parameters = null;
}
protected void performParamConversionForRepo() {
if (this.parameters != null && this.parameters.isModified())
{
Map<String, Serializable> actionParams = action.getParameterValues();
actionParams.clear();
for (Map.Entry<String, Serializable> entry : this.parameters.entrySet())
{
// perform the conversion from script wrapper object to repo serializable values
String name = entry.getKey();
Serializable value = converter.convertActionParamForRepo(name, entry.getValue());
actionParams.put(name, value);
}
}
}
/**
* Value converter with specific knowledge of action parameters
*
* @author davidc
*/
private class ActionValueConverter extends ValueConverter
{
/**
* Convert Action Parameter for Script usage
*
* @param paramName
* parameter name
* @param value
* value to convert
* @return converted value
*/
@SuppressWarnings("synthetic-access")
public Serializable convertActionParamForScript(String paramName, Serializable value)
{
ParameterDefinition paramDef = actionDef.getParameterDefintion(paramName);
if (paramDef != null && paramDef.getType().equals(DataTypeDefinition.QNAME))
{
return ((QName) value).toPrefixString(namespaceService);
}
else
{
return convertValueForScript(services, scope, null, value);
}
}
/**
* Convert Action Parameter for Java usage
*
* @param paramName
* parameter name
* @param value
* value to convert
* @return converted value
*/
@SuppressWarnings("synthetic-access")
public Serializable convertActionParamForRepo(String paramName, Serializable value)
{
ParameterDefinition paramDef = actionDef.getParameterDefintion(paramName);
if (paramDef != null && paramDef.getType().equals(DataTypeDefinition.QNAME))
{
if (value instanceof Wrapper)
{
// unwrap a Java object from a JavaScript wrapper
// recursively call this method to convert the unwrapped value
return convertActionParamForRepo(paramName, (Serializable) ((Wrapper) value).unwrap());
}
else
{
if (value instanceof String)
{
String stringQName = (String) value;
if (stringQName.startsWith("{"))
{
return QName.createQName(stringQName);
}
else
{
return QName.createQName(stringQName, namespaceService);
}
}
else
{
return value;
}
}
}
else
{
return convertValueForRepo(value);
}
}
}
/**
* Scripted Parameter map with modified flag.
*
* @author davidc
*/
public static final class ScriptableParameterMap<K, V> extends ScriptableHashMap<K, V>
{
private static final long serialVersionUID = 574661815973241554L;
private boolean modified = false;
/**
* Is this a modified parameter map?
*
* @return true => modified
*/
/* package */boolean isModified()
{
return modified;
}
/**
* Set explicitly whether this map is modified
*
* @param modified
* true => modified, false => not modified
*/
/* package */void setModified(boolean modified)
{
this.modified = modified;
}
/*
* (non-Javadoc)
*
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
@Override
public String getClassName()
{
return "ScriptableParameterMap";
}
/*
* (non-Javadoc)
*
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
@Override
public void delete(String name)
{
super.delete(name);
setModified(true);
}
/*
* (non-Javadoc)
*
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
@Override
public void put(String name, Scriptable start, Object value)
{
super.put(name, start, value);
setModified(true);
}
}
}

View File

@@ -1,173 +1,173 @@
package org.alfresco.repo.jscript;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.repo.policy.BaseBehaviour;
import org.alfresco.repo.policy.PolicyException;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* JavaScript behaviour implementation
*
* @author Roy Wetherall
*/
public class ScriptBehaviour extends BaseBehaviour
{
private ServiceRegistry serviceRegistry;
private ScriptLocation location;
public ScriptBehaviour()
{
super();
}
public ScriptBehaviour(ServiceRegistry serviceRegistry, ScriptLocation location)
{
this(serviceRegistry, location, NotificationFrequency.EVERY_EVENT);
}
public ScriptBehaviour(ServiceRegistry serviceRegistry, ScriptLocation location, NotificationFrequency frequency)
{
super(frequency);
ParameterCheck.mandatory("Location", location);
ParameterCheck.mandatory("ServiceRegistry", serviceRegistry);
this.location = location;
this.serviceRegistry = serviceRegistry;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.serviceRegistry = serviceRegistry;
}
public void setLocation(ScriptLocation location)
{
this.location = location;
}
@Override
public String toString()
{
return "JavaScript behaviour[location = " + this.location.toString() + "]";
}
@SuppressWarnings("unchecked")
public synchronized <T> T getInterface(Class<T> policy)
{
ParameterCheck.mandatory("Policy class", policy);
Object proxy = proxies.get(policy);
if (proxy == null)
{
Method[] policyIFMethods = policy.getMethods();
if (policyIFMethods.length != 1)
{
throw new PolicyException("Policy interface " + policy.getCanonicalName() + " must have only one method");
}
InvocationHandler handler = new JavaScriptInvocationHandler(this);
proxy = Proxy.newProxyInstance(policy.getClassLoader(), new Class[]{policy}, handler);
proxies.put(policy, proxy);
}
return (T)proxy;
}
/**
* JavaScript Invocation Handler
*
* @author Roy Wetherall
*/
private static class JavaScriptInvocationHandler implements InvocationHandler
{
private ScriptBehaviour behaviour;
private JavaScriptInvocationHandler(ScriptBehaviour behaviour)
{
this.behaviour = behaviour;
}
/**
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
// Handle Object level methods
if (method.getName().equals("toString"))
{
return toString();
}
else if (method.getName().equals("hashCode"))
{
return hashCode();
}
else if (method.getName().equals("equals"))
{
if (Proxy.isProxyClass(args[0].getClass()))
{
return equals(Proxy.getInvocationHandler(args[0]));
}
return false;
}
// Delegate to designated method pointer
if (behaviour.isEnabled())
{
try
{
behaviour.disable();
return invokeScript(method, args);
}
finally
{
behaviour.enable();
}
}
return null;
}
private Object invokeScript(Method method, Object[] args)
{
// Build the model
Map<String, Object> model = new HashMap<String, Object>(1);
model.put("behaviour", new org.alfresco.repo.jscript.Behaviour(this.behaviour.serviceRegistry, method.getName(), args));
// Execute the script
return this.behaviour.serviceRegistry.getScriptService().executeScript(this.behaviour.location, model);
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
else if (obj == null || !(obj instanceof JavaScriptInvocationHandler))
{
return false;
}
JavaScriptInvocationHandler other = (JavaScriptInvocationHandler)obj;
return behaviour.location.equals(other.behaviour.location);
}
@Override
public int hashCode()
{
return 37 * behaviour.location.hashCode();
}
@Override
public String toString()
{
return "JavaScriptBehaviour[location=" + behaviour.location.toString() + "]";
}
}
}
package org.alfresco.repo.jscript;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.repo.policy.BaseBehaviour;
import org.alfresco.repo.policy.PolicyException;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ScriptLocation;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* JavaScript behaviour implementation
*
* @author Roy Wetherall
*/
public class ScriptBehaviour extends BaseBehaviour
{
private ServiceRegistry serviceRegistry;
private ScriptLocation location;
public ScriptBehaviour()
{
super();
}
public ScriptBehaviour(ServiceRegistry serviceRegistry, ScriptLocation location)
{
this(serviceRegistry, location, NotificationFrequency.EVERY_EVENT);
}
public ScriptBehaviour(ServiceRegistry serviceRegistry, ScriptLocation location, NotificationFrequency frequency)
{
super(frequency);
ParameterCheck.mandatory("Location", location);
ParameterCheck.mandatory("ServiceRegistry", serviceRegistry);
this.location = location;
this.serviceRegistry = serviceRegistry;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry)
{
this.serviceRegistry = serviceRegistry;
}
public void setLocation(ScriptLocation location)
{
this.location = location;
}
@Override
public String toString()
{
return "JavaScript behaviour[location = " + this.location.toString() + "]";
}
@SuppressWarnings("unchecked")
public synchronized <T> T getInterface(Class<T> policy)
{
ParameterCheck.mandatory("Policy class", policy);
Object proxy = proxies.get(policy);
if (proxy == null)
{
Method[] policyIFMethods = policy.getMethods();
if (policyIFMethods.length != 1)
{
throw new PolicyException("Policy interface " + policy.getCanonicalName() + " must have only one method");
}
InvocationHandler handler = new JavaScriptInvocationHandler(this);
proxy = Proxy.newProxyInstance(policy.getClassLoader(), new Class[]{policy}, handler);
proxies.put(policy, proxy);
}
return (T)proxy;
}
/**
* JavaScript Invocation Handler
*
* @author Roy Wetherall
*/
private static class JavaScriptInvocationHandler implements InvocationHandler
{
private ScriptBehaviour behaviour;
private JavaScriptInvocationHandler(ScriptBehaviour behaviour)
{
this.behaviour = behaviour;
}
/**
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
// Handle Object level methods
if (method.getName().equals("toString"))
{
return toString();
}
else if (method.getName().equals("hashCode"))
{
return hashCode();
}
else if (method.getName().equals("equals"))
{
if (Proxy.isProxyClass(args[0].getClass()))
{
return equals(Proxy.getInvocationHandler(args[0]));
}
return false;
}
// Delegate to designated method pointer
if (behaviour.isEnabled())
{
try
{
behaviour.disable();
return invokeScript(method, args);
}
finally
{
behaviour.enable();
}
}
return null;
}
private Object invokeScript(Method method, Object[] args)
{
// Build the model
Map<String, Object> model = new HashMap<String, Object>(1);
model.put("behaviour", new org.alfresco.repo.jscript.Behaviour(this.behaviour.serviceRegistry, method.getName(), args));
// Execute the script
return this.behaviour.serviceRegistry.getScriptService().executeScript(this.behaviour.location, model);
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
else if (obj == null || !(obj instanceof JavaScriptInvocationHandler))
{
return false;
}
JavaScriptInvocationHandler other = (JavaScriptInvocationHandler)obj;
return behaviour.location.equals(other.behaviour.location);
}
@Override
public int hashCode()
{
return 37 * behaviour.location.hashCode();
}
@Override
public String toString()
{
return "JavaScriptBehaviour[location=" + behaviour.location.toString() + "]";
}
}
}

View File

@@ -1,77 +1,77 @@
package org.alfresco.repo.jscript;
import org.alfresco.repo.processor.BaseProcessorExtension;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Kevin Roast
*/
public final class ScriptLogger extends BaseProcessorExtension
{
private static final Log logger = LogFactory.getLog(ScriptLogger.class);
private static final SystemOut systemOut = new SystemOut();
public boolean isLoggingEnabled()
{
return isDebugLoggingEnabled();
}
public void log(String str)
{
debug(str);
}
public boolean isDebugLoggingEnabled()
{
return logger.isDebugEnabled();
}
public void debug(String str)
{
logger.debug(str);
}
public boolean isInfoLoggingEnabled()
{
return logger.isInfoEnabled();
}
public void info(String str)
{
logger.info(str);
}
public boolean isWarnLoggingEnabled()
{
return logger.isWarnEnabled();
}
public void warn(String str)
{
logger.warn(str);
}
public boolean isErrorLoggingEnabled()
{
return logger.isErrorEnabled();
}
public void error(String str)
{
logger.error(str);
}
public SystemOut getSystem()
{
return systemOut;
}
public static class SystemOut
{
public void out(Object str)
{
System.out.println(str);
}
}
}
package org.alfresco.repo.jscript;
import org.alfresco.repo.processor.BaseProcessorExtension;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Kevin Roast
*/
public final class ScriptLogger extends BaseProcessorExtension
{
private static final Log logger = LogFactory.getLog(ScriptLogger.class);
private static final SystemOut systemOut = new SystemOut();
public boolean isLoggingEnabled()
{
return isDebugLoggingEnabled();
}
public void log(String str)
{
debug(str);
}
public boolean isDebugLoggingEnabled()
{
return logger.isDebugEnabled();
}
public void debug(String str)
{
logger.debug(str);
}
public boolean isInfoLoggingEnabled()
{
return logger.isInfoEnabled();
}
public void info(String str)
{
logger.info(str);
}
public boolean isWarnLoggingEnabled()
{
return logger.isWarnEnabled();
}
public void warn(String str)
{
logger.warn(str);
}
public boolean isErrorLoggingEnabled()
{
return logger.isErrorEnabled();
}
public void error(String str)
{
logger.error(str);
}
public SystemOut getSystem()
{
return systemOut;
}
public static class SystemOut
{
public void out(Object str)
{
System.out.println(str);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,375 +1,375 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.alfresco.repo.nodelocator.CompanyHomeNodeLocator;
import org.alfresco.repo.nodelocator.NodeLocatorService;
import org.alfresco.repo.nodelocator.SharedHomeNodeLocator;
import org.alfresco.repo.nodelocator.SitesHomeNodeLocator;
import org.alfresco.repo.nodelocator.UserHomeNodeLocator;
import org.alfresco.repo.nodelocator.XPathNodeLocator;
import org.alfresco.repo.security.permissions.noop.PermissionServiceNOOPImpl;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.module.ModuleDetails;
import org.alfresco.service.cmr.module.ModuleService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.ScriptPagingDetails;
import org.springframework.extensions.surf.util.I18NUtil;
import org.springframework.extensions.surf.util.ISO8601DateFormat;
/**
* Place for general and miscellaneous utility functions not already found in generic JavaScript.
*
* @author Kevin Roast
*/
public class ScriptUtils extends BaseScopableProcessorExtension
{
private final static String NAMESPACE_BEGIN = "" + QName.NAMESPACE_BEGIN;
/** Services */
protected ServiceRegistry services;
private NodeService unprotNodeService;
/**
* Sets the service registry
*
* @param services the service registry
*/
public void setServiceRegistry(ServiceRegistry services)
{
this.services = services;
}
/**
* @param nodeService the NodeService to set
*/
public void setNodeService(NodeService nodeService)
{
this.unprotNodeService = nodeService;
}
/**
* Function to return the cm:name display path for a node with minimum performance overhead.
*
* @param node ScriptNode
* @return cm:name based human readable display path for the give node.
*/
public String displayPath(ScriptNode node)
{
return this.unprotNodeService.getPath(node.nodeRef).toDisplayPath(
this.unprotNodeService, new PermissionServiceNOOPImpl());
}
/**
* Function to pad a string with zero '0' characters to the required length
*
* @param s String to pad with leading zero '0' characters
* @param len Length to pad to
*
* @return padded string or the original if already at >=len characters
*/
public String pad(String s, int len)
{
String result = s;
for (int i=0; i<(len - s.length()); i++)
{
result = "0" + result;
}
return result;
}
/**
* Gets a JS node object from a string noderef
*
* @param nodeRefString string reference to a node
* @return a JS node object
*/
public ScriptNode getNodeFromString(String nodeRefString)
{
NodeRef nodeRef = new NodeRef(nodeRefString);
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, getScope(), null, nodeRef);
}
/**
* Use the Node Locator Service to find the a node reference from a number of possible locator types.
* This method is responsible for determining the locator type and then calling the Service as the
* Service does not know how to guess which locator to use.
* <p>
* This service supports 'virtual' nodes including the following:
* <p>
* alfresco://company/home The Company Home root node<br>
* alfresco://user/home The User Home node under Company Home<br>
* alfresco://company/shared The Shared node under Company Home<br>
* alfresco://sites/home The Sites home node under Company Home<br>
* workspace://.../... Any standard NodeRef<br>
* /app:company_home/cm:... XPath QName style node reference<br>
*
* @param reference The node reference - See above for list of possible node references supported.
*
* @return ScriptNode representing the node or null if not found
*/
public ScriptNode resolveNodeReference(final String reference)
{
if (reference == null)
{
throw new IllegalArgumentException("Node 'reference' argument is mandatory.");
}
final NodeLocatorService locatorService = this.services.getNodeLocatorService();
NodeRef nodeRef = null;
switch (reference)
{
case "alfresco://company/home":
nodeRef = locatorService.getNode(CompanyHomeNodeLocator.NAME, null, null);
break;
case "alfresco://user/home":
nodeRef = locatorService.getNode(UserHomeNodeLocator.NAME, null, null);
break;
case "alfresco://company/shared":
nodeRef = locatorService.getNode(SharedHomeNodeLocator.NAME, null, null);
break;
case "alfresco://sites/home":
nodeRef = locatorService.getNode(SitesHomeNodeLocator.NAME, null, null);
break;
default:
if (reference.indexOf("://") > 0)
{
NodeRef ref = new NodeRef(reference);
if (this.services.getNodeService().exists(ref) &&
this.services.getPermissionService().hasPermission(ref, PermissionService.READ) == AccessStatus.ALLOWED)
{
nodeRef = ref;
}
}
else if (reference.startsWith("/"))
{
final Map<String, Serializable> params = new HashMap<>(1, 1.0f);
params.put(XPathNodeLocator.QUERY_KEY, reference);
nodeRef = locatorService.getNode(XPathNodeLocator.NAME, null, params);
}
break;
}
return nodeRef != null ? (ScriptNode)new ValueConverter().convertValueForScript(this.services, getScope(), null, nodeRef) : null;
}
/**
* Gets a boolean value from a string
*
* @see Boolean#parseBoolean(String)
*
* @param booleanString boolean string
* @return boolean the boolean value
*/
public boolean toBoolean(String booleanString)
{
return Boolean.parseBoolean(booleanString);
}
/**
* Function to check if a module is installed
*
* @param moduleName module name (e.g. "org.alfresco.module.foo")
* @return boolean true if the module is currently installed
*/
public boolean moduleInstalled(String moduleName)
{
ModuleService moduleService = (ModuleService)this.services.getService(QName.createQName(NamespaceService.ALFRESCO_URI, "ModuleService"));
if (moduleService != null)
{
ModuleDetails moduleDetail = (ModuleDetails)moduleService.getModule(moduleName);
return (moduleDetail != null);
}
return false;
}
/**
* Format timeInMillis to ISO 8601 formatted string
*
* @param timeInMillis long
* @return String
*/
public String toISO8601(long timeInMillis)
{
return ISO8601DateFormat.format(new Date(timeInMillis));
}
/**
* Format date to ISO 8601 formatted string
*
* @param date Date
* @return String
*/
public String toISO8601(Date date)
{
return ISO8601DateFormat.format(date);
}
/**
* Parse date from ISO formatted string
*
* @param isoDateString String
* @return Date
*/
public Date fromISO8601(String isoDateString)
{
return ISO8601DateFormat.parse(isoDateString);
}
/**
* Given a long-form QName string, this method uses the namespace service to create a
* short-form QName string.
*
* @param s Fully qualified QName string
* @return the short form of the QName string, e.g. "cm:content"
*/
public String shortQName(String s)
{
return createQName(s).toPrefixString(services.getNamespaceService());
}
/**
* Given a short-form QName string, this method returns the fully qualified QName string.
*
* @param s Short form QName string, e.g. "cm:content"
* @return Fully qualified QName string
*/
public String longQName(String s)
{
return createQName(s).toString();
}
/**
* Builds a paging object, from the supplied
* Max Items and Skip Count
*/
public ScriptPagingDetails createPaging(int maxItems, int skipCount)
{
return new ScriptPagingDetails(maxItems, skipCount);
}
/**
* Builds a paging object, from the supplied
* Max Items, Skip Count and Query Execution ID
*/
public ScriptPagingDetails createPaging(int maxItems, int skipCount, String queryExecutionId)
{
return new ScriptPagingDetails(maxItems, skipCount, queryExecutionId);
}
/**
* Builds a paging object, from the supplied Args object.
* Requires that the parameters have their standard names,
* i.e. "maxItems" and "skipCount"
*
* @param args Mandatory hash of paging arguments<p>
* Possible arguments include:<p>
* maxItems - max count of items to return, default -1 (all)<br>
* skipCount - number of items to skip, default -1 (none)<br>
* queryId<br>
* queryExecutionId
*/
public ScriptPagingDetails createPaging(Map<String, String> args)
{
int maxItems = -1;
int skipCount = -1;
String queryId = null;
if (args.containsKey("maxItems"))
{
try
{
maxItems = Integer.parseInt(args.get("maxItems"));
}
catch(NumberFormatException e)
{}
}
if (args.containsKey("skipCount"))
{
try
{
skipCount = Integer.parseInt(args.get("skipCount"));
}
catch(NumberFormatException e)
{}
}
if (args.containsKey("queryId"))
{
queryId = args.get("queryId");
}
else if(args.containsKey("queryExecutionId"))
{
queryId = args.get("queryExecutionId");
}
return new ScriptPagingDetails(maxItems, skipCount, queryId);
}
/**
* Helper to create a QName from either a fully qualified or short-name QName string
*
* @param s Fully qualified or short-name QName string
*
* @return QName
*/
private QName createQName(String s)
{
QName qname;
if (s.indexOf(NAMESPACE_BEGIN) != -1)
{
qname = QName.createQName(s);
}
else
{
qname = QName.createQName(s, this.services.getNamespaceService());
}
return qname;
}
/**
* Disable rule execution for this thread
*/
public void disableRules()
{
services.getRuleService().disableRules();
}
/**
* Enable rule execution for this thread
*/
public void enableRules()
{
services.getRuleService().enableRules();
}
/**
* Sets current Locale from string
*/
public void setLocale(String localeStr)
{
Locale newLocale = I18NUtil.parseLocale(localeStr);
I18NUtil.setLocale(newLocale);
}
/**
* Returns current thread's locale
*/
public String getLocale()
{
return I18NUtil.getLocale().toString();
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.alfresco.repo.nodelocator.CompanyHomeNodeLocator;
import org.alfresco.repo.nodelocator.NodeLocatorService;
import org.alfresco.repo.nodelocator.SharedHomeNodeLocator;
import org.alfresco.repo.nodelocator.SitesHomeNodeLocator;
import org.alfresco.repo.nodelocator.UserHomeNodeLocator;
import org.alfresco.repo.nodelocator.XPathNodeLocator;
import org.alfresco.repo.security.permissions.noop.PermissionServiceNOOPImpl;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.module.ModuleDetails;
import org.alfresco.service.cmr.module.ModuleService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.ScriptPagingDetails;
import org.springframework.extensions.surf.util.I18NUtil;
import org.springframework.extensions.surf.util.ISO8601DateFormat;
/**
* Place for general and miscellaneous utility functions not already found in generic JavaScript.
*
* @author Kevin Roast
*/
public class ScriptUtils extends BaseScopableProcessorExtension
{
private final static String NAMESPACE_BEGIN = "" + QName.NAMESPACE_BEGIN;
/** Services */
protected ServiceRegistry services;
private NodeService unprotNodeService;
/**
* Sets the service registry
*
* @param services the service registry
*/
public void setServiceRegistry(ServiceRegistry services)
{
this.services = services;
}
/**
* @param nodeService the NodeService to set
*/
public void setNodeService(NodeService nodeService)
{
this.unprotNodeService = nodeService;
}
/**
* Function to return the cm:name display path for a node with minimum performance overhead.
*
* @param node ScriptNode
* @return cm:name based human readable display path for the give node.
*/
public String displayPath(ScriptNode node)
{
return this.unprotNodeService.getPath(node.nodeRef).toDisplayPath(
this.unprotNodeService, new PermissionServiceNOOPImpl());
}
/**
* Function to pad a string with zero '0' characters to the required length
*
* @param s String to pad with leading zero '0' characters
* @param len Length to pad to
*
* @return padded string or the original if already at >=len characters
*/
public String pad(String s, int len)
{
String result = s;
for (int i=0; i<(len - s.length()); i++)
{
result = "0" + result;
}
return result;
}
/**
* Gets a JS node object from a string noderef
*
* @param nodeRefString string reference to a node
* @return a JS node object
*/
public ScriptNode getNodeFromString(String nodeRefString)
{
NodeRef nodeRef = new NodeRef(nodeRefString);
return (ScriptNode)new ValueConverter().convertValueForScript(this.services, getScope(), null, nodeRef);
}
/**
* Use the Node Locator Service to find the a node reference from a number of possible locator types.
* This method is responsible for determining the locator type and then calling the Service as the
* Service does not know how to guess which locator to use.
* <p>
* This service supports 'virtual' nodes including the following:
* <p>
* alfresco://company/home The Company Home root node<br>
* alfresco://user/home The User Home node under Company Home<br>
* alfresco://company/shared The Shared node under Company Home<br>
* alfresco://sites/home The Sites home node under Company Home<br>
* workspace://.../... Any standard NodeRef<br>
* /app:company_home/cm:... XPath QName style node reference<br>
*
* @param reference The node reference - See above for list of possible node references supported.
*
* @return ScriptNode representing the node or null if not found
*/
public ScriptNode resolveNodeReference(final String reference)
{
if (reference == null)
{
throw new IllegalArgumentException("Node 'reference' argument is mandatory.");
}
final NodeLocatorService locatorService = this.services.getNodeLocatorService();
NodeRef nodeRef = null;
switch (reference)
{
case "alfresco://company/home":
nodeRef = locatorService.getNode(CompanyHomeNodeLocator.NAME, null, null);
break;
case "alfresco://user/home":
nodeRef = locatorService.getNode(UserHomeNodeLocator.NAME, null, null);
break;
case "alfresco://company/shared":
nodeRef = locatorService.getNode(SharedHomeNodeLocator.NAME, null, null);
break;
case "alfresco://sites/home":
nodeRef = locatorService.getNode(SitesHomeNodeLocator.NAME, null, null);
break;
default:
if (reference.indexOf("://") > 0)
{
NodeRef ref = new NodeRef(reference);
if (this.services.getNodeService().exists(ref) &&
this.services.getPermissionService().hasPermission(ref, PermissionService.READ) == AccessStatus.ALLOWED)
{
nodeRef = ref;
}
}
else if (reference.startsWith("/"))
{
final Map<String, Serializable> params = new HashMap<>(1, 1.0f);
params.put(XPathNodeLocator.QUERY_KEY, reference);
nodeRef = locatorService.getNode(XPathNodeLocator.NAME, null, params);
}
break;
}
return nodeRef != null ? (ScriptNode)new ValueConverter().convertValueForScript(this.services, getScope(), null, nodeRef) : null;
}
/**
* Gets a boolean value from a string
*
* @see Boolean#parseBoolean(String)
*
* @param booleanString boolean string
* @return boolean the boolean value
*/
public boolean toBoolean(String booleanString)
{
return Boolean.parseBoolean(booleanString);
}
/**
* Function to check if a module is installed
*
* @param moduleName module name (e.g. "org.alfresco.module.foo")
* @return boolean true if the module is currently installed
*/
public boolean moduleInstalled(String moduleName)
{
ModuleService moduleService = (ModuleService)this.services.getService(QName.createQName(NamespaceService.ALFRESCO_URI, "ModuleService"));
if (moduleService != null)
{
ModuleDetails moduleDetail = (ModuleDetails)moduleService.getModule(moduleName);
return (moduleDetail != null);
}
return false;
}
/**
* Format timeInMillis to ISO 8601 formatted string
*
* @param timeInMillis long
* @return String
*/
public String toISO8601(long timeInMillis)
{
return ISO8601DateFormat.format(new Date(timeInMillis));
}
/**
* Format date to ISO 8601 formatted string
*
* @param date Date
* @return String
*/
public String toISO8601(Date date)
{
return ISO8601DateFormat.format(date);
}
/**
* Parse date from ISO formatted string
*
* @param isoDateString String
* @return Date
*/
public Date fromISO8601(String isoDateString)
{
return ISO8601DateFormat.parse(isoDateString);
}
/**
* Given a long-form QName string, this method uses the namespace service to create a
* short-form QName string.
*
* @param s Fully qualified QName string
* @return the short form of the QName string, e.g. "cm:content"
*/
public String shortQName(String s)
{
return createQName(s).toPrefixString(services.getNamespaceService());
}
/**
* Given a short-form QName string, this method returns the fully qualified QName string.
*
* @param s Short form QName string, e.g. "cm:content"
* @return Fully qualified QName string
*/
public String longQName(String s)
{
return createQName(s).toString();
}
/**
* Builds a paging object, from the supplied
* Max Items and Skip Count
*/
public ScriptPagingDetails createPaging(int maxItems, int skipCount)
{
return new ScriptPagingDetails(maxItems, skipCount);
}
/**
* Builds a paging object, from the supplied
* Max Items, Skip Count and Query Execution ID
*/
public ScriptPagingDetails createPaging(int maxItems, int skipCount, String queryExecutionId)
{
return new ScriptPagingDetails(maxItems, skipCount, queryExecutionId);
}
/**
* Builds a paging object, from the supplied Args object.
* Requires that the parameters have their standard names,
* i.e. "maxItems" and "skipCount"
*
* @param args Mandatory hash of paging arguments<p>
* Possible arguments include:<p>
* maxItems - max count of items to return, default -1 (all)<br>
* skipCount - number of items to skip, default -1 (none)<br>
* queryId<br>
* queryExecutionId
*/
public ScriptPagingDetails createPaging(Map<String, String> args)
{
int maxItems = -1;
int skipCount = -1;
String queryId = null;
if (args.containsKey("maxItems"))
{
try
{
maxItems = Integer.parseInt(args.get("maxItems"));
}
catch(NumberFormatException e)
{}
}
if (args.containsKey("skipCount"))
{
try
{
skipCount = Integer.parseInt(args.get("skipCount"));
}
catch(NumberFormatException e)
{}
}
if (args.containsKey("queryId"))
{
queryId = args.get("queryId");
}
else if(args.containsKey("queryExecutionId"))
{
queryId = args.get("queryExecutionId");
}
return new ScriptPagingDetails(maxItems, skipCount, queryId);
}
/**
* Helper to create a QName from either a fully qualified or short-name QName string
*
* @param s Fully qualified or short-name QName string
*
* @return QName
*/
private QName createQName(String s)
{
QName qname;
if (s.indexOf(NAMESPACE_BEGIN) != -1)
{
qname = QName.createQName(s);
}
else
{
qname = QName.createQName(s, this.services.getNamespaceService());
}
return qname;
}
/**
* Disable rule execution for this thread
*/
public void disableRules()
{
services.getRuleService().disableRules();
}
/**
* Enable rule execution for this thread
*/
public void enableRules()
{
services.getRuleService().enableRules();
}
/**
* Sets current Locale from string
*/
public void setLocale(String localeStr)
{
Locale newLocale = I18NUtil.parseLocale(localeStr);
I18NUtil.setLocale(newLocale);
}
/**
* Returns current thread's locale
*/
public String getLocale()
{
return I18NUtil.getLocale().toString();
}
}

View File

@@ -1,136 +1,136 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.util.ParameterCheck;
import org.mozilla.javascript.Scriptable;
/**
* Scriptable Version
*
* @author davidc
*/
public final class ScriptVersion implements Serializable
{
private static final long serialVersionUID = 3896177303419746778L;
/** Root scope for this object */
private Scriptable scope;
private ServiceRegistry services;
private Version version;
/**
* Construct
*/
public ScriptVersion(Version version, ServiceRegistry services, Scriptable scope)
{
this.version = version;
this.services = services;
this.scope = scope;
}
/**
* Gets the date the version was created
*
* @return the date the version was created
*/
public Date getCreatedDate()
{
return version.getFrozenModifiedDate();
}
/**
* Gets the creator of the version
*
* @return the creator of the version
*/
public String getCreator()
{
return version.getFrozenModifier();
}
/**
* Gets the version label
*
* @return the version label
*/
public String getLabel()
{
return version.getVersionLabel();
}
/**
* Gets the version type
*
* @return "MAJOR", "MINOR"
*/
public String getType()
{
if (version.getVersionType() != null)
{
return version.getVersionType().name();
}
else
{
return "";
}
}
/**
* Gets the version description (or checkin comment)
*
* @return the version description
*/
public String getDescription()
{
String desc = version.getDescription();
return (desc == null) ? "" : desc;
}
/**
* Gets the node ref represented by this version
*
* @return node ref
*/
public NodeRef getNodeRef()
{
return version.getVersionedNodeRef();
}
/**
* Gets the node represented by this version
*
* @return node
*/
public ScriptNode getNode()
{
return new ScriptNode(version.getFrozenStateNodeRef(), services, scope);
}
/**
* Get the map containing the version property values
*
* @return the map containing the version properties
*/
public Map<String, Serializable> getVersionProperties()
{
return version.getVersionProperties();
}
/**
* Gets the value of a named version property.
*
* @param name the name of the property
* @return the value of the property
*/
public Serializable getVersionProperty(String name)
{
ParameterCheck.mandatoryString("name", name);
return version.getVersionProperty(name);
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.version.Version;
import org.alfresco.util.ParameterCheck;
import org.mozilla.javascript.Scriptable;
/**
* Scriptable Version
*
* @author davidc
*/
public final class ScriptVersion implements Serializable
{
private static final long serialVersionUID = 3896177303419746778L;
/** Root scope for this object */
private Scriptable scope;
private ServiceRegistry services;
private Version version;
/**
* Construct
*/
public ScriptVersion(Version version, ServiceRegistry services, Scriptable scope)
{
this.version = version;
this.services = services;
this.scope = scope;
}
/**
* Gets the date the version was created
*
* @return the date the version was created
*/
public Date getCreatedDate()
{
return version.getFrozenModifiedDate();
}
/**
* Gets the creator of the version
*
* @return the creator of the version
*/
public String getCreator()
{
return version.getFrozenModifier();
}
/**
* Gets the version label
*
* @return the version label
*/
public String getLabel()
{
return version.getVersionLabel();
}
/**
* Gets the version type
*
* @return "MAJOR", "MINOR"
*/
public String getType()
{
if (version.getVersionType() != null)
{
return version.getVersionType().name();
}
else
{
return "";
}
}
/**
* Gets the version description (or checkin comment)
*
* @return the version description
*/
public String getDescription()
{
String desc = version.getDescription();
return (desc == null) ? "" : desc;
}
/**
* Gets the node ref represented by this version
*
* @return node ref
*/
public NodeRef getNodeRef()
{
return version.getVersionedNodeRef();
}
/**
* Gets the node represented by this version
*
* @return node
*/
public ScriptNode getNode()
{
return new ScriptNode(version.getFrozenStateNodeRef(), services, scope);
}
/**
* Get the map containing the version property values
*
* @return the map containing the version properties
*/
public Map<String, Serializable> getVersionProperties()
{
return version.getVersionProperties();
}
/**
* Gets the value of a named version property.
*
* @param name the name of the property
* @return the value of the property
*/
public Serializable getVersionProperty(String name)
{
ParameterCheck.mandatoryString("name", name);
return version.getVersionProperty(name);
}
}

View File

@@ -1,198 +1,198 @@
package org.alfresco.repo.jscript;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* @author Kevin Roast
*/
public class ScriptableHashMap<K,V> extends LinkedHashMap<K, V> implements Scriptable
{
private static final long serialVersionUID = 3664761893203964569L;
private Scriptable parentScope;
private Scriptable prototype;
/**
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
public String getClassName()
{
return "ScriptableHashMap";
}
/**
* @see org.mozilla.javascript.Scriptable#get(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public Object get(String name, Scriptable start)
{
// get the property from the underlying QName map
if ("length".equals(name))
{
return this.size();
}
else if ("hasOwnProperty".equals(name))
{
return new Callable()
{
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
{
return (args.length > 0 ? hasOwnProperty(args[0]) : null);
}
};
}
else
{
return get(name);
}
}
/**
* @see org.mozilla.javascript.Scriptable#get(int, org.mozilla.javascript.Scriptable)
*/
public Object get(int index, Scriptable start)
{
Object value = null;
int i=0;
Iterator itrValues = this.values().iterator();
while (i++ <= index && itrValues.hasNext())
{
value = itrValues.next();
}
return value;
}
/**
* ECMAScript 5 hasOwnProperty method support.
*
* @param key Object key to test for
* @return true if found, false otherwise
*/
public boolean hasOwnProperty(Object key)
{
return containsKey(key);
}
/**
* @see org.mozilla.javascript.Scriptable#has(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public boolean has(String name, Scriptable start)
{
// locate the property in the underlying map
return containsKey(name);
}
/**
* @see org.mozilla.javascript.Scriptable#has(int, org.mozilla.javascript.Scriptable)
*/
public boolean has(int index, Scriptable start)
{
return (index >= 0 && this.values().size() > index);
}
/**
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
@SuppressWarnings("unchecked")
public void put(String name, Scriptable start, Object value)
{
// add the property to the underlying QName map
put((K)name, (V)value);
}
/**
* @see org.mozilla.javascript.Scriptable#put(int, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(int index, Scriptable start, Object value)
{
// TODO: implement?
}
/**
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
public void delete(String name)
{
// remove the property from the underlying QName map
remove(name);
}
/**
* @see org.mozilla.javascript.Scriptable#delete(int)
*/
public void delete(int index)
{
int i=0;
Iterator itrKeys = this.keySet().iterator();
while (i <= index && itrKeys.hasNext())
{
Object key = itrKeys.next();
if (i == index)
{
remove(key);
break;
}
}
}
/**
* @see org.mozilla.javascript.Scriptable#getPrototype()
*/
public Scriptable getPrototype()
{
return this.prototype;
}
/**
* @see org.mozilla.javascript.Scriptable#setPrototype(org.mozilla.javascript.Scriptable)
*/
public void setPrototype(Scriptable prototype)
{
this.prototype = prototype;
}
/**
* @see org.mozilla.javascript.Scriptable#getParentScope()
*/
public Scriptable getParentScope()
{
return this.parentScope;
}
/**
* @see org.mozilla.javascript.Scriptable#setParentScope(org.mozilla.javascript.Scriptable)
*/
public void setParentScope(Scriptable parent)
{
this.parentScope = parent;
}
/**
* @see org.mozilla.javascript.Scriptable#getIds()
*/
public Object[] getIds()
{
return keySet().toArray();
}
/**
* @see org.mozilla.javascript.Scriptable#getDefaultValue(java.lang.Class)
*/
public Object getDefaultValue(@SuppressWarnings("rawtypes") Class hint)
{
return this.toString();
}
/**
* @see org.mozilla.javascript.Scriptable#hasInstance(org.mozilla.javascript.Scriptable)
*/
public boolean hasInstance(Scriptable instance)
{
return instance instanceof ScriptableHashMap;
}
}
package org.alfresco.repo.jscript;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* @author Kevin Roast
*/
public class ScriptableHashMap<K,V> extends LinkedHashMap<K, V> implements Scriptable
{
private static final long serialVersionUID = 3664761893203964569L;
private Scriptable parentScope;
private Scriptable prototype;
/**
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
public String getClassName()
{
return "ScriptableHashMap";
}
/**
* @see org.mozilla.javascript.Scriptable#get(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public Object get(String name, Scriptable start)
{
// get the property from the underlying QName map
if ("length".equals(name))
{
return this.size();
}
else if ("hasOwnProperty".equals(name))
{
return new Callable()
{
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
{
return (args.length > 0 ? hasOwnProperty(args[0]) : null);
}
};
}
else
{
return get(name);
}
}
/**
* @see org.mozilla.javascript.Scriptable#get(int, org.mozilla.javascript.Scriptable)
*/
public Object get(int index, Scriptable start)
{
Object value = null;
int i=0;
Iterator itrValues = this.values().iterator();
while (i++ <= index && itrValues.hasNext())
{
value = itrValues.next();
}
return value;
}
/**
* ECMAScript 5 hasOwnProperty method support.
*
* @param key Object key to test for
* @return true if found, false otherwise
*/
public boolean hasOwnProperty(Object key)
{
return containsKey(key);
}
/**
* @see org.mozilla.javascript.Scriptable#has(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public boolean has(String name, Scriptable start)
{
// locate the property in the underlying map
return containsKey(name);
}
/**
* @see org.mozilla.javascript.Scriptable#has(int, org.mozilla.javascript.Scriptable)
*/
public boolean has(int index, Scriptable start)
{
return (index >= 0 && this.values().size() > index);
}
/**
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
@SuppressWarnings("unchecked")
public void put(String name, Scriptable start, Object value)
{
// add the property to the underlying QName map
put((K)name, (V)value);
}
/**
* @see org.mozilla.javascript.Scriptable#put(int, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(int index, Scriptable start, Object value)
{
// TODO: implement?
}
/**
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
public void delete(String name)
{
// remove the property from the underlying QName map
remove(name);
}
/**
* @see org.mozilla.javascript.Scriptable#delete(int)
*/
public void delete(int index)
{
int i=0;
Iterator itrKeys = this.keySet().iterator();
while (i <= index && itrKeys.hasNext())
{
Object key = itrKeys.next();
if (i == index)
{
remove(key);
break;
}
}
}
/**
* @see org.mozilla.javascript.Scriptable#getPrototype()
*/
public Scriptable getPrototype()
{
return this.prototype;
}
/**
* @see org.mozilla.javascript.Scriptable#setPrototype(org.mozilla.javascript.Scriptable)
*/
public void setPrototype(Scriptable prototype)
{
this.prototype = prototype;
}
/**
* @see org.mozilla.javascript.Scriptable#getParentScope()
*/
public Scriptable getParentScope()
{
return this.parentScope;
}
/**
* @see org.mozilla.javascript.Scriptable#setParentScope(org.mozilla.javascript.Scriptable)
*/
public void setParentScope(Scriptable parent)
{
this.parentScope = parent;
}
/**
* @see org.mozilla.javascript.Scriptable#getIds()
*/
public Object[] getIds()
{
return keySet().toArray();
}
/**
* @see org.mozilla.javascript.Scriptable#getDefaultValue(java.lang.Class)
*/
public Object getDefaultValue(@SuppressWarnings("rawtypes") Class hint)
{
return this.toString();
}
/**
* @see org.mozilla.javascript.Scriptable#hasInstance(org.mozilla.javascript.Scriptable)
*/
public boolean hasInstance(Scriptable instance)
{
return instance instanceof ScriptableHashMap;
}
}

View File

@@ -1,178 +1,178 @@
package org.alfresco.repo.jscript;
import org.alfresco.service.namespace.NamespacePrefixResolverProvider;
import org.alfresco.service.namespace.QNameMap;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* @author Kevin Roast
*/
public class ScriptableQNameMap<K,V> extends QNameMap<K,V> implements Scriptable
{
/**
* @param resolver NamespacePrefixResolverProvider
*/
public ScriptableQNameMap(NamespacePrefixResolverProvider resolver)
{
super(resolver);
}
/**
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
public String getClassName()
{
return "ScriptableQNameMap";
}
/**
* @see org.mozilla.javascript.Scriptable#get(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public Object get(String name, Scriptable start)
{
// get the property from the underlying QName map
if ("length".equals(name))
{
return this.size();
}
else if ("hasOwnProperty".equals(name))
{
return new Callable()
{
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
{
return (args.length > 0 ? hasOwnProperty(args[0]) : null);
}
};
}
else
{
return get(name);
}
}
/**
* @see org.mozilla.javascript.Scriptable#get(int, org.mozilla.javascript.Scriptable)
*/
public Object get(int index, Scriptable start)
{
return null;
}
/**
* ECMAScript 5 hasOwnProperty method support.
*
* @param key Object key to test for
* @return true if found, false otherwise
*/
public boolean hasOwnProperty(Object key)
{
return containsKey(key);
}
/**
* @see org.mozilla.javascript.Scriptable#has(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public boolean has(String name, Scriptable start)
{
// locate the property in the underlying QName map
return containsKey(name);
}
/**
* @see org.mozilla.javascript.Scriptable#has(int, org.mozilla.javascript.Scriptable)
*/
public boolean has(int index, Scriptable start)
{
return false;
}
/**
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(String name, Scriptable start, Object value)
{
// add the property to the underlying QName map
put(name, value);
}
/**
* @see org.mozilla.javascript.Scriptable#put(int, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(int index, Scriptable start, Object value)
{
}
/**
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
public void delete(String name)
{
// remove the property from the underlying QName map
remove(name);
}
/**
* @see org.mozilla.javascript.Scriptable#delete(int)
*/
public void delete(int index)
{
}
/**
* @see org.mozilla.javascript.Scriptable#getPrototype()
*/
public Scriptable getPrototype()
{
return null;
}
/**
* @see org.mozilla.javascript.Scriptable#setPrototype(org.mozilla.javascript.Scriptable)
*/
public void setPrototype(Scriptable prototype)
{
}
/**
* @see org.mozilla.javascript.Scriptable#getParentScope()
*/
public Scriptable getParentScope()
{
return null;
}
/**
* @see org.mozilla.javascript.Scriptable#setParentScope(org.mozilla.javascript.Scriptable)
*/
public void setParentScope(Scriptable parent)
{
}
/**
* @see org.mozilla.javascript.Scriptable#getIds()
*/
public Object[] getIds()
{
return keySet().toArray();
}
/**
* @see org.mozilla.javascript.Scriptable#getDefaultValue(java.lang.Class)
*/
public Object getDefaultValue(@SuppressWarnings("rawtypes") Class hint)
{
return toString();
}
/**
* @see org.mozilla.javascript.Scriptable#hasInstance(org.mozilla.javascript.Scriptable)
*/
public boolean hasInstance(Scriptable instance)
{
return instance instanceof ScriptableQNameMap;
}
}
package org.alfresco.repo.jscript;
import org.alfresco.service.namespace.NamespacePrefixResolverProvider;
import org.alfresco.service.namespace.QNameMap;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* @author Kevin Roast
*/
public class ScriptableQNameMap<K,V> extends QNameMap<K,V> implements Scriptable
{
/**
* @param resolver NamespacePrefixResolverProvider
*/
public ScriptableQNameMap(NamespacePrefixResolverProvider resolver)
{
super(resolver);
}
/**
* @see org.mozilla.javascript.Scriptable#getClassName()
*/
public String getClassName()
{
return "ScriptableQNameMap";
}
/**
* @see org.mozilla.javascript.Scriptable#get(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public Object get(String name, Scriptable start)
{
// get the property from the underlying QName map
if ("length".equals(name))
{
return this.size();
}
else if ("hasOwnProperty".equals(name))
{
return new Callable()
{
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
{
return (args.length > 0 ? hasOwnProperty(args[0]) : null);
}
};
}
else
{
return get(name);
}
}
/**
* @see org.mozilla.javascript.Scriptable#get(int, org.mozilla.javascript.Scriptable)
*/
public Object get(int index, Scriptable start)
{
return null;
}
/**
* ECMAScript 5 hasOwnProperty method support.
*
* @param key Object key to test for
* @return true if found, false otherwise
*/
public boolean hasOwnProperty(Object key)
{
return containsKey(key);
}
/**
* @see org.mozilla.javascript.Scriptable#has(java.lang.String, org.mozilla.javascript.Scriptable)
*/
public boolean has(String name, Scriptable start)
{
// locate the property in the underlying QName map
return containsKey(name);
}
/**
* @see org.mozilla.javascript.Scriptable#has(int, org.mozilla.javascript.Scriptable)
*/
public boolean has(int index, Scriptable start)
{
return false;
}
/**
* @see org.mozilla.javascript.Scriptable#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(String name, Scriptable start, Object value)
{
// add the property to the underlying QName map
put(name, value);
}
/**
* @see org.mozilla.javascript.Scriptable#put(int, org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put(int index, Scriptable start, Object value)
{
}
/**
* @see org.mozilla.javascript.Scriptable#delete(java.lang.String)
*/
public void delete(String name)
{
// remove the property from the underlying QName map
remove(name);
}
/**
* @see org.mozilla.javascript.Scriptable#delete(int)
*/
public void delete(int index)
{
}
/**
* @see org.mozilla.javascript.Scriptable#getPrototype()
*/
public Scriptable getPrototype()
{
return null;
}
/**
* @see org.mozilla.javascript.Scriptable#setPrototype(org.mozilla.javascript.Scriptable)
*/
public void setPrototype(Scriptable prototype)
{
}
/**
* @see org.mozilla.javascript.Scriptable#getParentScope()
*/
public Scriptable getParentScope()
{
return null;
}
/**
* @see org.mozilla.javascript.Scriptable#setParentScope(org.mozilla.javascript.Scriptable)
*/
public void setParentScope(Scriptable parent)
{
}
/**
* @see org.mozilla.javascript.Scriptable#getIds()
*/
public Object[] getIds()
{
return keySet().toArray();
}
/**
* @see org.mozilla.javascript.Scriptable#getDefaultValue(java.lang.Class)
*/
public Object getDefaultValue(@SuppressWarnings("rawtypes") Class hint)
{
return toString();
}
/**
* @see org.mozilla.javascript.Scriptable#hasInstance(org.mozilla.javascript.Scriptable)
*/
public boolean hasInstance(Scriptable instance)
{
return instance instanceof ScriptableQNameMap;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,289 +1,289 @@
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QName;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.IdScriptableObject;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Wrapper;
/**
* Value conversion allowing safe usage of values in Script and Java.
*/
public class ValueConverter
{
private static final String TYPE_DATE = "Date";
/**
* Convert an object from any repository serialized value to a valid script object.
* This includes converting Collection multi-value properties into JavaScript Array objects.
*
* @param services Repository Services Registry
* @param scope Scripting scope
* @param qname QName of the property value for conversion
* @param value Property value
*
* @return Value safe for scripting usage
*/
@SuppressWarnings("unchecked")
public Serializable convertValueForScript(ServiceRegistry services, Scriptable scope, QName qname, Serializable value)
{
// perform conversions from Java objects to JavaScript scriptable instances
if (value == null)
{
return null;
}
else if (value instanceof NodeRef)
{
// NodeRef object properties are converted to new Node objects
// so they can be used as objects within a template
value = new ScriptNode(((NodeRef)value), services, scope);
}
else if (value instanceof QName || value instanceof StoreRef)
{
value = value.toString();
}
else if (value instanceof ChildAssociationRef)
{
value = new ChildAssociation(services, (ChildAssociationRef)value, scope);
}
else if (value instanceof AssociationRef)
{
value = new Association(services, (AssociationRef)value, scope);
}
else if (value instanceof Date)
{
// convert Date to JavaScript native Date object
// call the "Date" constructor on the root scope object - passing in the millisecond
// value from the Java date - this will construct a JavaScript Date with the same value
Date date = (Date)value;
try
{
Context.enter();
Object val = ScriptRuntime.newObject(
Context.getCurrentContext(), scope, TYPE_DATE, new Object[] {date.getTime()});
value = (Serializable)val;
}
finally
{
Context.exit();
}
}
else if (value instanceof Collection)
{
// recursively convert each value in the collection
Collection<Serializable> collection = (Collection<Serializable>)value;
Object[] array = new Object[collection.size()];
int index = 0;
for (Serializable obj : collection)
{
array[index++] = convertValueForScript(services, scope, qname, obj);
}
try
{
Context.enter();
// Convert array to a native JavaScript Array
// Note - a scope is usually required for this to work
value = (Serializable)Context.getCurrentContext().newArray(scope, array);
}
finally
{
Context.exit();
}
}
// simple numbers and strings are wrapped automatically by Rhino
return value;
}
/**
* Convert an object from any script wrapper value to a valid repository serializable value.
* This includes converting JavaScript Array objects to Lists of valid objects.
*
* @param value Value to convert from script wrapper object to repo serializable value
*
* @return valid repo value
*/
public Serializable convertValueForRepo(Serializable value)
{
Object converted = convertValueForJava((Object)value);
return converted instanceof Serializable ? (Serializable)converted : value;
}
public final Object convertValueForJava(Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof ScriptNode)
{
// convert back to NodeRef
value = ((ScriptNode)value).getNodeRef();
}
else if (value instanceof ChildAssociation)
{
value = ((ChildAssociation)value).getChildAssociationRef();
}
else if (value instanceof Association)
{
value = ((Association)value).getAssociationRef();
}
else if (value instanceof Wrapper)
{
// unwrap a Java object from a JavaScript wrapper
// recursively call this method to convert the unwrapped value
value = convertValueForJava(((Wrapper)value).unwrap());
}
else if (value instanceof Scriptable)
{
// a scriptable object will probably indicate a multi-value property
// set using a JavaScript Array object
Scriptable values = (Scriptable)value;
if (value instanceof IdScriptableObject)
{
// TODO: add code here to use the dictionary and convert to correct value type
if (TYPE_DATE.equals(((IdScriptableObject)value).getClassName()))
{
value = Context.jsToJava(value, Date.class);
}
else if (value instanceof NativeArray)
{
// convert JavaScript array of values to a List of objects
Object[] propIds = values.getIds();
if (isArray(propIds) == true)
{
List<Object> propValues = new ArrayList<Object>(propIds.length);
for (int i=0; i<propIds.length; i++)
{
// work on each key in turn
Object propId = propIds[i];
// we are only interested in keys that indicate a list of values
if (propId instanceof Integer)
{
// get the value out for the specified key
Object val = values.get((Integer)propId, values);
// recursively call this method to convert the value
propValues.add(convertValueForJava(val));
}
}
value = propValues;
}
else
{
Map<Object, Object> propValues = new HashMap<Object, Object>(propIds.length);
for (Object propId : propIds)
{
// Get the value and add to the map
Object val = values.get(propId.toString(), values);
propValues.put(convertValueForJava(propId), convertValueForJava(val));
}
value = propValues;
}
}
else
{
// convert Scriptable object of values to a Map of objects
Object[] propIds = values.getIds();
Map<String, Object> propValues = new HashMap<String, Object>(propIds.length);
for (int i=0; i<propIds.length; i++)
{
// work on each key in turn
Object propId = propIds[i];
// we are only interested in keys that indicate a list of values
if (propId instanceof String)
{
// get the value out for the specified key
Object val = values.get((String)propId, values);
// recursively call this method to convert the value
propValues.put((String)propId, convertValueForJava(val));
}
}
value = propValues;
}
}
else
{
// convert Scriptable object of values to a Map of objects
Object[] propIds = values.getIds();
Map<String, Object> propValues = new HashMap<String, Object>(propIds.length);
for (int i=0; i<propIds.length; i++)
{
// work on each key in turn
Object propId = propIds[i];
// we are only interested in keys that indicate a list of values
if (propId instanceof String)
{
// get the value out for the specified key
Object val = values.get((String)propId, values);
// recursively call this method to convert the value
propValues.put((String)propId, convertValueForJava(val));
}
}
value = propValues;
}
}
else if (value.getClass().isArray())
{
// convert back a list of Java values
int length = Array.getLength(value);
ArrayList<Object> list = new ArrayList<Object>(length);
for (int i=0; i<length; i++)
{
list.add(convertValueForJava(Array.get(value, i)));
}
value = list;
}
else if (value instanceof CharSequence)
{
// Rhino has some interesting internal classes such as ConsString which cannot be cast to String
// but fortunately are instanceof CharSequence so we can toString() them.
value = value.toString();
}
return value;
}
/**
* Look at the id's of a native array and try to determine whether it's actually an Array or a Hashmap
*
* @param ids id's of the native array
* @return boolean true if it's an array, false otherwise (ie it's a map)
*/
private boolean isArray(Object[] ids)
{
boolean result = true;
for (Object id : ids)
{
if (id instanceof Integer == false)
{
result = false;
break;
}
}
return result;
}
}
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.namespace.QName;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.IdScriptableObject;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Wrapper;
/**
* Value conversion allowing safe usage of values in Script and Java.
*/
public class ValueConverter
{
private static final String TYPE_DATE = "Date";
/**
* Convert an object from any repository serialized value to a valid script object.
* This includes converting Collection multi-value properties into JavaScript Array objects.
*
* @param services Repository Services Registry
* @param scope Scripting scope
* @param qname QName of the property value for conversion
* @param value Property value
*
* @return Value safe for scripting usage
*/
@SuppressWarnings("unchecked")
public Serializable convertValueForScript(ServiceRegistry services, Scriptable scope, QName qname, Serializable value)
{
// perform conversions from Java objects to JavaScript scriptable instances
if (value == null)
{
return null;
}
else if (value instanceof NodeRef)
{
// NodeRef object properties are converted to new Node objects
// so they can be used as objects within a template
value = new ScriptNode(((NodeRef)value), services, scope);
}
else if (value instanceof QName || value instanceof StoreRef)
{
value = value.toString();
}
else if (value instanceof ChildAssociationRef)
{
value = new ChildAssociation(services, (ChildAssociationRef)value, scope);
}
else if (value instanceof AssociationRef)
{
value = new Association(services, (AssociationRef)value, scope);
}
else if (value instanceof Date)
{
// convert Date to JavaScript native Date object
// call the "Date" constructor on the root scope object - passing in the millisecond
// value from the Java date - this will construct a JavaScript Date with the same value
Date date = (Date)value;
try
{
Context.enter();
Object val = ScriptRuntime.newObject(
Context.getCurrentContext(), scope, TYPE_DATE, new Object[] {date.getTime()});
value = (Serializable)val;
}
finally
{
Context.exit();
}
}
else if (value instanceof Collection)
{
// recursively convert each value in the collection
Collection<Serializable> collection = (Collection<Serializable>)value;
Object[] array = new Object[collection.size()];
int index = 0;
for (Serializable obj : collection)
{
array[index++] = convertValueForScript(services, scope, qname, obj);
}
try
{
Context.enter();
// Convert array to a native JavaScript Array
// Note - a scope is usually required for this to work
value = (Serializable)Context.getCurrentContext().newArray(scope, array);
}
finally
{
Context.exit();
}
}
// simple numbers and strings are wrapped automatically by Rhino
return value;
}
/**
* Convert an object from any script wrapper value to a valid repository serializable value.
* This includes converting JavaScript Array objects to Lists of valid objects.
*
* @param value Value to convert from script wrapper object to repo serializable value
*
* @return valid repo value
*/
public Serializable convertValueForRepo(Serializable value)
{
Object converted = convertValueForJava((Object)value);
return converted instanceof Serializable ? (Serializable)converted : value;
}
public final Object convertValueForJava(Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof ScriptNode)
{
// convert back to NodeRef
value = ((ScriptNode)value).getNodeRef();
}
else if (value instanceof ChildAssociation)
{
value = ((ChildAssociation)value).getChildAssociationRef();
}
else if (value instanceof Association)
{
value = ((Association)value).getAssociationRef();
}
else if (value instanceof Wrapper)
{
// unwrap a Java object from a JavaScript wrapper
// recursively call this method to convert the unwrapped value
value = convertValueForJava(((Wrapper)value).unwrap());
}
else if (value instanceof Scriptable)
{
// a scriptable object will probably indicate a multi-value property
// set using a JavaScript Array object
Scriptable values = (Scriptable)value;
if (value instanceof IdScriptableObject)
{
// TODO: add code here to use the dictionary and convert to correct value type
if (TYPE_DATE.equals(((IdScriptableObject)value).getClassName()))
{
value = Context.jsToJava(value, Date.class);
}
else if (value instanceof NativeArray)
{
// convert JavaScript array of values to a List of objects
Object[] propIds = values.getIds();
if (isArray(propIds) == true)
{
List<Object> propValues = new ArrayList<Object>(propIds.length);
for (int i=0; i<propIds.length; i++)
{
// work on each key in turn
Object propId = propIds[i];
// we are only interested in keys that indicate a list of values
if (propId instanceof Integer)
{
// get the value out for the specified key
Object val = values.get((Integer)propId, values);
// recursively call this method to convert the value
propValues.add(convertValueForJava(val));
}
}
value = propValues;
}
else
{
Map<Object, Object> propValues = new HashMap<Object, Object>(propIds.length);
for (Object propId : propIds)
{
// Get the value and add to the map
Object val = values.get(propId.toString(), values);
propValues.put(convertValueForJava(propId), convertValueForJava(val));
}
value = propValues;
}
}
else
{
// convert Scriptable object of values to a Map of objects
Object[] propIds = values.getIds();
Map<String, Object> propValues = new HashMap<String, Object>(propIds.length);
for (int i=0; i<propIds.length; i++)
{
// work on each key in turn
Object propId = propIds[i];
// we are only interested in keys that indicate a list of values
if (propId instanceof String)
{
// get the value out for the specified key
Object val = values.get((String)propId, values);
// recursively call this method to convert the value
propValues.put((String)propId, convertValueForJava(val));
}
}
value = propValues;
}
}
else
{
// convert Scriptable object of values to a Map of objects
Object[] propIds = values.getIds();
Map<String, Object> propValues = new HashMap<String, Object>(propIds.length);
for (int i=0; i<propIds.length; i++)
{
// work on each key in turn
Object propId = propIds[i];
// we are only interested in keys that indicate a list of values
if (propId instanceof String)
{
// get the value out for the specified key
Object val = values.get((String)propId, values);
// recursively call this method to convert the value
propValues.put((String)propId, convertValueForJava(val));
}
}
value = propValues;
}
}
else if (value.getClass().isArray())
{
// convert back a list of Java values
int length = Array.getLength(value);
ArrayList<Object> list = new ArrayList<Object>(length);
for (int i=0; i<length; i++)
{
list.add(convertValueForJava(Array.get(value, i)));
}
value = list;
}
else if (value instanceof CharSequence)
{
// Rhino has some interesting internal classes such as ConsString which cannot be cast to String
// but fortunately are instanceof CharSequence so we can toString() them.
value = value.toString();
}
return value;
}
/**
* Look at the id's of a native array and try to determine whether it's actually an Array or a Hashmap
*
* @param ids id's of the native array
* @return boolean true if it's an array, false otherwise (ie it's a map)
*/
private boolean isArray(Object[] ids)
{
boolean result = true;
for (Object id : ids)
{
if (id instanceof Integer == false)
{
result = false;
break;
}
}
return result;
}
}