Big honkin' merge from head. Sheesh!

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/BRANCHES/WCM-DEV2/root@3617 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Britt Park
2006-08-27 01:01:30 +00:00
parent e2c66899cc
commit 8031cc6574
322 changed files with 20776 additions and 6550 deletions

View File

@@ -0,0 +1,334 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
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.namespace.QName;
import org.mozilla.javascript.Scriptable;
/**
* Scripted Action service for describing and executing actions against Nodes.
*
* @author davidc
*/
public final class Actions implements Scopeable
{
/** Repository Service Registry */
private ServiceRegistry services;
/** Root scope for this object */
private Scriptable scope;
/**
* Constructor
*
* @param services repository service registry
*/
public Actions(ServiceRegistry services)
{
this.services = services;
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
/**
* 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;
}
public String[] jsGet_registered()
{
return getRegistered();
}
/**
* 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(action, actionDef);
scriptAction.setScope(scope);
}
return scriptAction;
}
/**
* Scriptable Action
*
* @author davidc
*/
public final 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 */
private Action action;
private ActionDefinition actionDef;
private ScriptableParameterMap<String, Serializable> parameters = null;
/**
* Construct
*
* @param action Alfresco action
*/
public ScriptAction(Action action, ActionDefinition actionDef)
{
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();
}
public String jsGet_name()
{
return 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;
}
public Map<String, Serializable> jsGet_parameters()
{
return getParameters();
}
/**
* Execute action
*
* @param node the node to execute action upon
*/
@SuppressWarnings("synthetic-access")
public void execute(Node node)
{
if (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);
}
}
services.getActionService().executeAction(action, node.getNodeRef());
}
/**
* 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(services.getNamespaceService());
}
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))
{
return QName.createQName((String)value, services.getNamespaceService());
}
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);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -28,18 +28,16 @@ import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.ScriptException;
import org.alfresco.service.cmr.repository.ScriptService;
import org.alfresco.service.cmr.repository.TemplateImageResolver;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ImporterTopLevel;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Wrapper;
/**
* Implementation of the ScriptService using the Rhino JavaScript engine.
@@ -50,30 +48,18 @@ public class RhinoScriptService implements ScriptService
{
private static final Logger logger = Logger.getLogger(RhinoScriptService.class);
/** The permission-safe node service */
private NodeService nodeService;
/** The Content Service to use */
private ContentService contentService;
/** Repository Service Registry */
private ServiceRegistry services;
/**
* Set the node service
* Set the Service Registry
*
* @param nodeService The permission-safe node service
* @param service registry
*/
public void setNodeService(NodeService nodeService)
public void setServiceRegistry(ServiceRegistry services)
{
this.nodeService = nodeService;
}
/**
* Set the content service
*
* @param contentService The ContentService to use
*/
public void setContentService(ContentService contentService)
{
this.contentService = contentService;
this.services = services;
}
/**
@@ -87,6 +73,11 @@ public class RhinoScriptService implements ScriptService
throw new IllegalArgumentException("Script ClassPath is mandatory.");
}
if (logger.isDebugEnabled())
{
logger.debug("Executing script: " + scriptClasspath);
}
Reader reader = null;
try
{
@@ -123,10 +114,15 @@ public class RhinoScriptService implements ScriptService
throw new IllegalArgumentException("Script NodeRef is mandatory.");
}
if (logger.isDebugEnabled())
{
logger.debug("Executing script: " + scriptRef.toString());
}
Reader reader = null;
try
{
if (this.nodeService.exists(scriptRef) == false)
if (this.services.getNodeService().exists(scriptRef) == false)
{
throw new AlfrescoRuntimeException("Script Node does not exist: " + scriptRef);
}
@@ -135,7 +131,7 @@ public class RhinoScriptService implements ScriptService
{
contentProp = ContentModel.PROP_CONTENT;
}
ContentReader cr = this.contentService.getReader(scriptRef, contentProp);
ContentReader cr = this.services.getContentService().getReader(scriptRef, contentProp);
if (cr == null || cr.exists() == false)
{
throw new AlfrescoRuntimeException("Script Node content not found: " + scriptRef);
@@ -168,6 +164,11 @@ public class RhinoScriptService implements ScriptService
throw new IllegalArgumentException("Script argument is mandatory.");
}
if (logger.isDebugEnabled())
{
logger.debug("Executing script:\n" + script);
}
Reader reader = null;
try
{
@@ -207,18 +208,35 @@ public class RhinoScriptService implements ScriptService
{
// The easiest way to embed Rhino is just to create a new scope this way whenever
// you need one. However, initStandardObjects is an expensive method to call and it
// allocates a fair amount of memory. ImporterTopLevel provides a scope allowing
// the import of java classes and packages.
Scriptable topLevelScope = new ImporterTopLevel(cx);
// allocates a fair amount of memory.
Scriptable scope = cx.initStandardObjects();
scope.setParentScope(topLevelScope);
// there's always a model, if only to hold the util objects
if (model == null)
{
model = new HashMap<String, Object>();
}
// add useful util objects
model.put("actions", new Actions(services));
model.put("logger", new ScriptLogger());
// insert supplied object model into root of the default scope
if (model != null)
{
for (String key : model.keySet())
{
Object jsObject = Context.javaToJS(model.get(key), scope);
// set the root scope on appropriate objects
// this is used to allow native JS object creation etc.
Object obj = model.get(key);
if (obj instanceof Scopeable)
{
((Scopeable)obj).setScope(scope);
}
// convert/wrap each object to JavaScript compatible
Object jsObject = Context.javaToJS(obj, scope);
// insert into the root scope ready for access by the script
ScriptableObject.putProperty(scope, key, jsObject);
}
}
@@ -226,6 +244,12 @@ public class RhinoScriptService implements ScriptService
// execute the script
Object result = cx.evaluateReader(scope, reader, "AlfrescoScript", 1, null);
// extract java object result if wrapped by rhinoscript
if (result instanceof Wrapper)
{
result = ((Wrapper)result).unwrap();
}
return result;
}
catch (Throwable err)
@@ -234,7 +258,7 @@ public class RhinoScriptService implements ScriptService
}
finally
{
cx.exit();
Context.exit();
if (logger.isDebugEnabled())
{
@@ -317,7 +341,6 @@ public class RhinoScriptService implements ScriptService
model.put("space", new Node(space, services, resolver));
}
// add other useful util objects
model.put("search", new Search(services, companyHome.getStoreRef(), resolver));
return model;

View File

@@ -17,14 +17,13 @@
package org.alfresco.repo.jscript;
import java.io.InputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.dictionary.DictionaryComponent;
import org.alfresco.repo.dictionary.DictionaryDAO;
import org.alfresco.repo.dictionary.M2Model;
@@ -33,7 +32,6 @@ import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.transaction.TransactionUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
@@ -267,7 +265,114 @@ public class RhinoScriptTest extends TestCase
});
}
public void testScriptActions()
{
TransactionUtil.executeInUserTransaction(
transactionService,
new TransactionUtil.TransactionWork<Object>()
{
public Object doWork() throws Exception
{
StoreRef store = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "rhino_" + System.currentTimeMillis());
NodeRef root = nodeService.getRootNode(store);
try
{
// create a content object
ChildAssociationRef childRef = nodeService.createNode(
root,
BaseNodeServiceTest.ASSOC_TYPE_QNAME_TEST_CHILDREN,
QName.createQName(BaseNodeServiceTest.NAMESPACE, "script_content"),
BaseNodeServiceTest.TYPE_QNAME_TEST_CONTENT,
null);
NodeRef contentNodeRef = childRef.getChildRef();
ContentWriter writer = contentService.getWriter(
contentNodeRef,
BaseNodeServiceTest.PROP_QNAME_TEST_CONTENT,
true);
writer.setMimetype("application/x-javascript");
writer.putContent(TESTSCRIPT1);
// create an Alfresco scriptable Node object
// the Node object is a wrapper similar to the TemplateNode concept
Map<String, Object> model = new HashMap<String, Object>();
model.put("doc", new Node(childRef.getChildRef(), serviceRegistry, null));
model.put("root", new Node(root, serviceRegistry, null));
// execute to add aspect via action
Object result = scriptService.executeScript(TESTSCRIPT_CLASSPATH2, model);
System.out.println("Result from TESTSCRIPT_CLASSPATH2: " + result.toString());
assertTrue((Boolean)result); // we know the result is a boolean
// ensure aspect has been added via script
assertTrue(nodeService.hasAspect(childRef.getChildRef(), ContentModel.ASPECT_LOCKABLE));
}
catch (Throwable err)
{
err.printStackTrace();
fail(err.getMessage());
}
return null;
}
});
}
public void xtestScriptActionsMail()
{
TransactionUtil.executeInUserTransaction(
transactionService,
new TransactionUtil.TransactionWork<Object>()
{
public Object doWork() throws Exception
{
StoreRef store = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "rhino_" + System.currentTimeMillis());
NodeRef root = nodeService.getRootNode(store);
try
{
// create a content object
ChildAssociationRef childRef = nodeService.createNode(
root,
BaseNodeServiceTest.ASSOC_TYPE_QNAME_TEST_CHILDREN,
QName.createQName(BaseNodeServiceTest.NAMESPACE, "script_content"),
BaseNodeServiceTest.TYPE_QNAME_TEST_CONTENT,
null);
NodeRef contentNodeRef = childRef.getChildRef();
ContentWriter writer = contentService.getWriter(
contentNodeRef,
BaseNodeServiceTest.PROP_QNAME_TEST_CONTENT,
true);
writer.setMimetype("application/x-javascript");
writer.putContent(TESTSCRIPT1);
// create an Alfresco scriptable Node object
// the Node object is a wrapper similar to the TemplateNode concept
Map<String, Object> model = new HashMap<String, Object>();
model.put("doc", new Node(childRef.getChildRef(), serviceRegistry, null));
model.put("root", new Node(root, serviceRegistry, null));
// execute to add aspect via action
Object result = scriptService.executeScript(TESTSCRIPT_CLASSPATH3, model);
System.out.println("Result from TESTSCRIPT_CLASSPATH3: " + result.toString());
assertTrue((Boolean)result); // we know the result is a boolean
}
catch (Throwable err)
{
err.printStackTrace();
fail(err.getMessage());
}
return null;
}
});
}
private static final String TESTSCRIPT_CLASSPATH1 = "org/alfresco/repo/jscript/test_script1.js";
private static final String TESTSCRIPT_CLASSPATH2 = "org/alfresco/repo/jscript/test_script2.js";
private static final String TESTSCRIPT_CLASSPATH3 = "org/alfresco/repo/jscript/test_script3.js";
private static final String TESTSCRIPT1 =
"var id = root.id;\r\n" +

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
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 global scope
*/
void setScope(Scriptable scope);
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.repo.jscript;
import org.apache.log4j.Logger;
/**
* @author Kevin Roast
*/
public final class ScriptLogger
{
private static final Logger logger = Logger.getLogger(ScriptLogger.class);
public boolean isLoggingEnabled()
{
return logger.isDebugEnabled();
}
public boolean jsGet_isLoggingEnabled()
{
return isLoggingEnabled();
}
public void log(String str)
{
logger.debug(str);
}
}

View File

@@ -16,17 +16,21 @@
*/
package org.alfresco.repo.jscript;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.alfresco.service.namespace.NamespacePrefixResolver;
import org.alfresco.service.namespace.QNameMap;
import org.mozilla.javascript.Scriptable;
/**
* @author Kevin Roast
*/
public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
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()
*/
@@ -56,7 +60,14 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public Object get(int index, Scriptable start)
{
return null;
Object value = null;
int i=0;
Iterator itrValues = this.values().iterator();
while (i++ <= index && itrValues.hasNext())
{
value = itrValues.next();
}
return value;
}
/**
@@ -73,16 +84,17 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public boolean has(int index, Scriptable start)
{
return false;
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(name, value);
put((K)name, (V)value);
}
/**
@@ -90,6 +102,7 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public void put(int index, Scriptable start, Object value)
{
// TODO: implement?
}
/**
@@ -106,6 +119,17 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
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;
}
}
}
/**
@@ -113,7 +137,7 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public Scriptable getPrototype()
{
return null;
return this.prototype;
}
/**
@@ -121,6 +145,7 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public void setPrototype(Scriptable prototype)
{
this.prototype = prototype;
}
/**
@@ -128,7 +153,7 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public Scriptable getParentScope()
{
return null;
return this.parentScope;
}
/**
@@ -136,6 +161,7 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public void setParentScope(Scriptable parent)
{
this.parentScope = parent;
}
/**
@@ -143,7 +169,7 @@ public class ScriptableHashMap<K,V> extends HashMap implements Scriptable
*/
public Object[] getIds()
{
return null;
return keySet().toArray();
}
/**

View File

@@ -17,9 +17,6 @@
package org.alfresco.repo.jscript;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
@@ -28,7 +25,6 @@ import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.repository.TemplateImageResolver;
import org.alfresco.service.cmr.repository.TemplateNode;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchService;
@@ -37,6 +33,7 @@ import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mozilla.javascript.Scriptable;
/**
* Search component for use by the ScriptService.
@@ -51,7 +48,7 @@ import org.dom4j.io.SAXReader;
*
* @author Kevin Roast
*/
public final class Search
public final class Search implements Scopeable
{
private static Log logger = LogFactory.getLog(Search.class);
@@ -59,6 +56,9 @@ public final class Search
private StoreRef storeRef;
private TemplateImageResolver imageResolver;
/** Root scope for this object */
private Scriptable scope;
/**
* Constructor
@@ -72,6 +72,48 @@ public final class Search
this.imageResolver = imageResolver;
}
/**
* @see org.alfresco.repo.jscript.Scopeable#setScope(org.mozilla.javascript.Scriptable)
*/
public void setScope(Scriptable scope)
{
this.scope = scope;
}
/**
* Find a single Node by the Node reference
*
* @param ref The NodeRef of the Node to find
*
* @return the Node if found or null if failed to find
*/
public Node findNode(NodeRef ref)
{
return findNode(ref.toString());
}
/**
* Find a single Node by the Node reference
*
* @param ref The fully qualified NodeRef in String format
*
* @return the Node if found or null if failed to find
*/
public Node findNode(String ref)
{
String query = ref.replace(":", "\\:");
query = query.replace("/", "\\/");
Node[] result = query("ID:" + query);
if (result.length == 1)
{
return result[0];
}
else
{
return null;
}
}
/**
* Execute a Lucene search
*
@@ -171,7 +213,8 @@ public final class Search
for (ResultSetRow row: results)
{
NodeRef nodeRef = row.getNodeRef();
nodes[count++] = new Node(nodeRef, services, this.imageResolver);
nodes[count] = new Node(nodeRef, services, this.imageResolver, this.scope);
count++;
}
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright (C) 2005 Alfresco, Inc.
*
* Licensed under the Mozilla Public License version 1.1
* with a permitted attribution clause. You may obtain a
* copy of the License at
*
* http://www.alfresco.org/legal/license.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.alfresco.repo.jscript;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Wrapper;
/**
* Value conversion allowing safe usage of values in Script and Java.
*/
public class ValueConverter
{
/**
* 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
*/
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 Node(((NodeRef)value), services, null, 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;
Object val = ScriptRuntime.newObject(
Context.getCurrentContext(), scope, "Date", new Object[] {date.getTime()});
value = (Serializable)val;
}
else if (value instanceof Collection)
{
// recursively convert each value in the collection
Collection<Serializable> collection = (Collection<Serializable>)value;
Serializable[] array = new Serializable[collection.size()];
int index = 0;
for (Serializable obj : collection)
{
array[index++] = convertValueForScript(services, scope, qname, obj);
}
value = array;
}
// 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)
{
if (value == null)
{
return null;
}
else if (value instanceof Node)
{
// convert back to NodeRef
value = ((Node)value).getNodeRef();
}
else if (value instanceof Wrapper)
{
// unwrap a Java object from a JavaScript wrapper
// recursively call this method to convert the unwrapped value
value = convertValueForRepo((Serializable)((Wrapper)value).unwrap());
}
else if (value instanceof ScriptableObject)
{
// a scriptable object will probably indicate a multi-value property
// set using a JavaScript Array object
ScriptableObject values = (ScriptableObject)value;
if (value instanceof NativeArray)
{
// convert JavaScript array of values to a List of Serializable objects
Object[] propIds = values.getIds();
List<Serializable> propValues = new ArrayList<Serializable>(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
Serializable val = (Serializable)values.get((Integer)propId, values);
// recursively call this method to convert the value
propValues.add(convertValueForRepo(val));
}
}
value = (Serializable)propValues;
}
else
{
// TODO: add code here to use the dictionary and convert to correct value type
Object javaObj = Context.jsToJava(value, Date.class);
if (javaObj instanceof Serializable)
{
value = (Serializable)javaObj;
}
}
}
else if (value instanceof Serializable[])
{
// convert back a list of Java values
Serializable[] array = (Serializable[])value;
ArrayList<Serializable> list = new ArrayList<Serializable>(array.length);
for (int i=0; i<array.length; i++)
{
list.add(convertValueForRepo(array[i]));
}
value = list;
}
return value;
}
}

View File

@@ -0,0 +1,9 @@
// create add action
var addAspectAction = actions.create("add-features");
addAspectAction.parameters["aspect-name"] = "cm:lockable";
// execute action against passed in node
addAspectAction.execute(doc);
// return
true;

View File

@@ -0,0 +1,13 @@
// create mail action
var mail = actions.create("mail");
mail.parameters.to = "davidc@alfresco.com";
mail.parameters.subject = "Hello from JavaScript";
mail.parameters.from = "david.caruana@alfresco.org";
mail.parameters.template = root.childByNamePath("Company Home/Data Dictionary/Email Templates/notify_user_email.ftl");
mail.parameters.text = "some text, in case template is not found";
// execute action against passed in node
mail.execute(doc);
// return
true;