public void testCustomContextFactory() { ContextFactory factory = new MyFactory(); Context cx = factory.enterContext(); try { Scriptable globalScope = cx.initStandardObjects(); // Test that FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME is enabled /* TODO(stevey): fix this functionality in parser Object result = cx.evaluateString(globalScope, "var obj = {};" + "function obj.foo() { return 'bar'; }" + "obj.foo();", "test source", 1, null); assertEquals("bar", result); */ } catch (RhinoException e) { fail(e.toString()); } finally { Context.exit(); } }
public static void init(Context cx, Scriptable scope, boolean sealed) { NativeRegExp proto = new NativeRegExp(); proto.re = (RECompiled)compileRE(cx, "", null, false); proto.activatePrototypeMap(MAX_PROTOTYPE_ID); proto.setParentScope(scope); proto.setPrototype(getObjectPrototype(scope)); NativeRegExpCtor ctor = new NativeRegExpCtor(); // Bug #324006: ECMA-262 15.10.6.1 says "The initial value of // RegExp.prototype.constructor is the builtin RegExp constructor." proto.defineProperty("constructor", ctor, ScriptableObject.DONTENUM); ScriptRuntime.setFunctionProtoAndParent(ctor, scope); ctor.setImmunePrototypeProperty(proto); if (sealed) { proto.sealObject(); ctor.sealObject(); } defineProperty(scope, "RegExp", ctor, ScriptableObject.DONTENUM); }
public static void processFileNoThrow(Context cx, Scriptable scope, String filename) { try { processFile(cx, scope, filename); } catch (IOException ioex) { Context.reportError(ToolErrorReporter.getMessage( "msg.couldnt.read.source", filename, ioex.getMessage())); exitCode = EXITCODE_FILE_NOT_FOUND; } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); Context.reportError(msg); exitCode = EXITCODE_RUNTIME_ERROR; } }
public void helper(String source) { Context cx = Context.enter(); Context.ClassShutterSetter setter = cx.getClassShutterSetter(); try { Scriptable globalScope = cx.initStandardObjects(); if (setter == null) { setter = classShutterSetter; } else { classShutterSetter = setter; } setter.setClassShutter(new OpaqueShutter()); cx.evaluateString(globalScope, source, "test source", 1, null); } finally { setter.setClassShutter(null); Context.exit(); } }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { for (FunctionStatement function : getFunctions()) { if (function.getName().equals(functionName)) { Scriptable curScope = javascriptContext.initStandardObjects(); curScope.setParentScope(scope); boolean ret = function.execute(javascriptContext, curScope); Object returnedValue = function.getReturnedValue(); if (returnedValue != null) { ReturnStatement.returnLoop(this.parent, returnedValue); } return ret; } } } } return false; }
/** * 执行JS * * @param js js代码 * @param functionName js方法名称 * @param functionParams js方法参数 * @return */ public static String runScript(Context context, String js, String functionName, Object[] functionParams) { org.mozilla.javascript.Context rhino = org.mozilla.javascript.Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); ScriptableObject.putProperty(scope, "javaContext", org.mozilla.javascript.Context.javaToJS(context, scope)); ScriptableObject.putProperty(scope, "javaLoader", org.mozilla.javascript.Context.javaToJS(context.getClass().getClassLoader(), scope)); rhino.evaluateString(scope, js, context.getClass().getSimpleName(), 1, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(rhino, scope, scope, functionParams); if (result instanceof String) { return (String) result; } else if (result instanceof NativeJavaObject) { return (String) ((NativeJavaObject) result).getDefaultValue(String.class); } else if (result instanceof NativeObject) { return (String) ((NativeObject) result).getDefaultValue(String.class); } return result.toString();//(String) function.call(rhino, scope, scope, functionParams); } finally { org.mozilla.javascript.Context.exit(); } }
@Override protected boolean stepExecute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.stepExecute(javascriptContext, scope)) { DatabaseObject parentStep = this.parent; while (parentStep != null) { if (parentStep instanceof FunctionStep) { FunctionStep functionStep = (FunctionStep)parentStep; functionStep.setReturnedValue(this.evaluated); functionStep.bContinue = false; return true; } else { if (parentStep instanceof StepWithExpressions) ((StepWithExpressions)parentStep).bContinue = false; parentStep = parentStep.getParent(); } } sequence.skipNextSteps(true); return true; } } return false; }
/** * Get active workflow instances this node belongs to * * @return the active workflow instances this node belongs to */ public Scriptable getActiveWorkflows() { if (this.activeWorkflows == null) { WorkflowService workflowService = this.services.getWorkflowService(); List<WorkflowInstance> workflowInstances = workflowService.getWorkflowsForContent(this.nodeRef, true); Object[] jsWorkflowInstances = new Object[workflowInstances.size()]; int index = 0; for (WorkflowInstance workflowInstance : workflowInstances) { jsWorkflowInstances[index++] = new JscriptWorkflowInstance(workflowInstance, this.services, this.scope); } this.activeWorkflows = Context.getCurrentContext().newArray(this.scope, jsWorkflowInstances); } return this.activeWorkflows; }
private static FunctionObject getFunctionObject( Class aClass, String methodName, Scriptable scriptable ) { Hashtable functionMap = (Hashtable) _classFunctionMaps.get( aClass ); if (functionMap == null) { _classFunctionMaps.put( aClass, functionMap = new Hashtable() ); } Object result = functionMap.get( methodName ); if (result == NO_SUCH_PROPERTY) return null; if (result != null) return (FunctionObject) result; Method[] methods = aClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().equalsIgnoreCase( methodName )) { FunctionObject function = new FunctionObject( methodName, method, scriptable ); functionMap.put( methodName, function ); return function; } } functionMap.put( methodName, NO_SUCH_PROPERTY ); return null; }
public String migrateSourceXpathFor620(String xpath) { Context javascriptContext = null; Scriptable scope = null; try { javascriptContext = org.mozilla.javascript.Context.enter(); scope = javascriptContext.initStandardObjects(); String filePath = evaluateDataFileName(javascriptContext, scope); xpath = migrateSourceXpathFor620(filePath, xpath); if (xpath.startsWith("/")) { xpath = xpath.replaceFirst("/", "./"); } } catch (Exception e) {} finally { org.mozilla.javascript.Context.exit(); javascriptContext = null; scope = null; } return xpath; }
private static Test createTest(final File testDir, final String name) { return new TestCase(name) { @Override public int countTestCases() { return 1; } @Override public void runBare() throws Throwable { final Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); final Scriptable scope = cx.initStandardObjects(); ScriptableObject.putProperty(scope, "print", new Print(scope)); createRequire(testDir, cx, scope).requireMain(cx, "program"); } finally { Context.exit(); } } }; }
/** * Constructs a scriptable object representing a user. * * @param userName The username * @param personNodeRef The NodeRef * @param serviceRegistry A ServiceRegistry instance * @param scope Script scope * @since 4.0 */ public ScriptUser(String userName, NodeRef personNodeRef, ServiceRegistry serviceRegistry, Scriptable scope) { this.serviceRegistry = serviceRegistry; this.authorityService = serviceRegistry.getAuthorityService(); this.personService = serviceRegistry.getPersonService(); this.scope = scope; this.personNodeRef = personNodeRef == null ? personService.getPerson(userName) : personNodeRef; this.userName = userName; this.shortName = authorityService.getShortName(userName); NodeService nodeService = serviceRegistry.getNodeService(); String firstName = (String)nodeService.getProperty(this.personNodeRef, ContentModel.PROP_FIRSTNAME); String lastName = (String)nodeService.getProperty(this.personNodeRef, ContentModel.PROP_LASTNAME); this.displayName = this.fullName = (firstName != null ? firstName : "") + (lastName != null ? (' ' + lastName) : ""); }
/** * List the open invitations for this web site. * props specifies optional properties to be searched. * * @param props inviteeUserName * * @return the invitations */ public ScriptInvitation<?>[] listInvitations(Scriptable props) { InvitationSearchCriteriaImpl crit = new InvitationSearchCriteriaImpl(); crit.setResourceName(getShortName()); crit.setResourceType(Invitation.ResourceType.WEB_SITE); if (props.has("inviteeUserName", props)) { crit.setInvitee((String)props.get("inviteeUserName", props)); } if (props.has("invitationType", props)) { String invitationType = (String)props.get("invitationType", props); crit.setInvitationType(InvitationType.valueOf(invitationType)); } List<Invitation> invitations = invitationService.searchInvitation(crit); ScriptInvitation<?>[] ret = new ScriptInvitation[invitations.size()]; int i = 0; for(Invitation item : invitations) { ret[i++] = scriptInvitationFactory.toScriptInvitation(item); } return ret; }
@Override public Serializable convertValueForScript(ServiceRegistry serviceRegistry, Scriptable theScope, QName qname, Serializable value) { // ALF-14863: If script-node is used outside of Script-call (eg. Activiti evaluating an expression that contains variables of type ScriptNode) // a scope should be created solely for this conversion. The scope will ALWAYS be set when value-conversion is called from the // ScriptProcessor ensureScopePresent(); if (theScope == null) { theScope = scope; } if (value instanceof NodeRef) { return new ActivitiScriptNode(((NodeRef)value), serviceRegistry); } else if (value instanceof Date) { return value; } else { return super.convertValueForScript(serviceRegistry, theScope, qname, value); } }
/** * Constructor to create a new instance of this class from an * existing instance of WorkflowNode from the CMR workflow * object model * * @param workflowNode CMR workflow node object to create * new <code>JscriptWorkflowNode</code> from * @param scope root scripting scope for this newly instantiated object * @param serviceRegistry service registry object */ public JscriptWorkflowNode(WorkflowNode workflowNode, Scriptable scope, ServiceRegistry serviceRegistry) { this.name = workflowNode.name; this.title = workflowNode.title; this.description = workflowNode.description; this.isTaskNode = workflowNode.isTaskNode; this.transitions = new ArrayList<JscriptWorkflowTransition>(); WorkflowTransition[] cmrWorkflowTransitions = workflowNode.transitions; for (WorkflowTransition cmrWorkflowTransition : cmrWorkflowTransitions) { transitions.add(new JscriptWorkflowTransition(cmrWorkflowTransition)); } this.scope = scope; this.serviceRegistry = serviceRegistry; }
static public Scriptable copyScope(Context context, Scriptable scope) { Scriptable scopeCopy = context.initStandardObjects(); for (Object id : scope.getIds()) { scopeCopy.put(id.toString(), scopeCopy, scope.get(id.toString(), scope)); } return scopeCopy; }
@Override public Object get(String name, Scriptable start) { Object value = super.get(name, start); if (value != null && value != UniqueTag.NOT_FOUND && !value.equals(org.mozilla.javascript.Context.getUndefinedValue())) { return value; } value = mProperties.get(name); if (value != null) return value; return UniqueTag.NOT_FOUND; }
@Override protected boolean stepExecute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (getSequence().context != null) { evaluate(javascriptContext, scope, expression); return super.stepExecute(javascriptContext, scope); } } return false; }
@Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!f.hasTag(REGEXP_TAG)) { return super.execIdCall(f, cx, scope, thisObj, args); } int id = f.methodId(); switch (id) { case Id_compile: return realThis(thisObj, f).compile(cx, scope, args); case Id_toString: case Id_toSource: return realThis(thisObj, f).toString(); case Id_exec: return realThis(thisObj, f).execSub(cx, scope, args, MATCH); case Id_test: { Object x = realThis(thisObj, f).execSub(cx, scope, args, TEST); return Boolean.TRUE.equals(x) ? Boolean.TRUE : Boolean.FALSE; } case Id_prefix: return realThis(thisObj, f).execSub(cx, scope, args, PREFIX); } throw new IllegalArgumentException(String.valueOf(id)); }
public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { evaluate(javascriptContext, scope, expression, "ContextAddTextNode", true); scope.put("__tmp__ContextAddTextNode", scope, evaluated); evaluate(javascriptContext, scope, "context.addTextNodeUnderRoot('"+tagname+"',__tmp__ContextAddTextNode)", "ContextSet", true); scope.delete("__tmp__ContextAddTextNode"); return true; } } return false; }
private Require getSandboxedRequire(Context cx, Scriptable scope, boolean sandboxed) throws URISyntaxException { return new Require(cx, cx.initStandardObjects(), new StrongCachingModuleScriptProvider( new UrlModuleSourceProvider(Collections.singleton( getDirectory()), null)), null, null, true); }
@Override protected void addToScope(Scriptable scope, NodeList nodeList) { if (nodeList != null) { String nodeValue = null; if (nodeList.getLength() > 0) { Node node = nodeList.item(0); nodeValue = node.getNodeValue(); if (node instanceof Element) nodeValue = ((Element) node).getTextContent(); } scope.put(getVariableName(), scope, nodeValue); } }
static boolean hasNamedProperty( Object element, String javaPropertyName, Scriptable scriptable ) { Method getter = getPropertyGetter( element.getClass(), javaPropertyName ); if (getter != NO_SUCH_PROPERTY) { return true; } else { Object function = getFunctionObject( element.getClass(), javaPropertyName, scriptable ); return function != null; } }
/** * @see BaseFunction#call(Context, Scriptable, Scriptable, Object[]) * @param cx * @param scope * @param thisObj * @param args * @return */ @Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (args.length < 2) { return Context.getUndefinedValue(); } if (!(args[0] instanceof String) || !(args[1] instanceof String)) { return Context.getUndefinedValue(); } String configKey = (String) args[0]; String configValue = (String) args[1]; return Config.getConfig().setConfig(configKey, configValue, false); }
/** * 检测 c:import * * @param url */ public static void checkJstlImport(String url) { if (url != null && !url.startsWith("/") && url.contains("://")) { JSContext cx = JSContextFactory.enterAndInitContext(); Scriptable params = cx.newObject(cx.getScope()); params.put("url", params, url); params.put("function", params, "jstl_import"); HookHandler.doCheck(CheckParameter.Type.INCLUDE, params); } }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { returnLoop(this.parent, this.evaluated); return true; } } return false; }
private void assertEvaluates(final Object expected, final String source) { final ContextAction action = new ContextAction() { public Object run(Context cx) { final Scriptable scope = cx.initStandardObjects(); final Object rep = cx.evaluateString(scope, source, "test.js", 0, null); assertEquals(expected, rep); return null; } }; Utils.runWithAllOptimizationLevels(action); }
public Object get( String propertyName, Scriptable scriptable ) { Object result = super.get( propertyName, scriptable ); if (result != NOT_FOUND) return result; Object namedProperty = ScriptingSupport.getNamedProperty( this, propertyName, scriptable ); if (namedProperty != NOT_FOUND) return namedProperty; Node namedItem = namedItem( propertyName ); return namedItem == null ? NOT_FOUND : namedItem; }
public boolean hasInstance(Scriptable value) { if (!(value instanceof Wrapper)) return false; Object instance = ((Wrapper)value).unwrap(); return Map.class.isInstance(instance); }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { reset(); if (isEnabled()) { if (super.execute(javascriptContext, scope)) { return executeNextStatement(javascriptContext, scope); } } return false; }
public void jsFunction_include(final Scriptable scope, String scriptName) throws Exception { final Context cx = Context.getCurrentContext(); if (scriptName.charAt(0) != '/') { // relative script name -- resolve it against currently executing // script's directory String pathPrefix = currentScriptDirectory; while (scriptName.startsWith("../")) { final int lastSlash = pathPrefix.lastIndexOf('/'); if (lastSlash == -1) { throw new FileNotFoundException("script:" + currentScriptDirectory + '/' + scriptName); } scriptName = scriptName.substring(3); pathPrefix = pathPrefix.substring(0, lastSlash); } scriptName = pathPrefix + '/' + scriptName; } else { // strip off leading slash scriptName = scriptName.substring(1); } final Script script = scriptStorage.getScript(scriptName); if (script == null) { throw new FileNotFoundException("script:" + scriptName); } try { final String oldScriptDirectory = currentScriptDirectory; currentScriptDirectory = getDirectoryForScript(scriptName); try { script.exec(cx, scope); } finally { currentScriptDirectory = oldScriptDirectory; } } finally { } }
@Override protected boolean stepExecute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.stepExecute(javascriptContext, scope)) { try { evaluate(javascriptContext, scope, getContextName(), "contextName", true); if (evaluated instanceof org.mozilla.javascript.Undefined) { throw new Exception("Step "+ getName() +" has none context name defined." ); } if (evaluated != null) { // contextID = JSESSIONID_contexName String contextID = sequence.getSessionId() + "_" + evaluated.toString(); if (contextID.equals(sequence.context.contextID)) { throw new Exception("The removal of current sequence's context is forbidden."); } Engine.logBeans.debug("(RemoveContextStep) Removing context \""+ contextID +"\""); Engine.theApp.contextManager.remove(contextID); return true; } } catch (Exception e) { evaluated = null; Engine.logBeans.warn(e.getMessage()); } } } return false; }
protected boolean stepExecute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled && sequence.isRunning()) { if (Engine.logBeans.isDebugEnabled()) Engine.logBeans.debug("Executing step named '"+ this +"' ("+ this.getName() +")"); Long key = new Long(priority); // We fire engine events only in studio mode. if (Engine.isStudioMode()) { Step loadedStep = (Step) sequence.loadedSteps.get(key).getOriginal(); Engine.theApp.fireObjectDetected(new EngineEvent(loadedStep)); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans.trace("(Step) Step reached before its execution \"" + getName() + "\" ( "+ this+" ["+ hashCode() +"] )."); Engine.theApp.fireStepReached(new EngineEvent(loadedStep)); } // Generates execution ID executeTimeID = getExecuteTimeID(); // Adds step's reference to executed steps executedSteps.put(key, executeTimeID); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans.trace("Step copy ["+executeTimeID+"] contains "+ executedSteps.size() + " executed steps."); // Adds step's reference to sequence copies sequence.addCopy(executeTimeID, this); sequence.setCurrentStep(this); sequence.appendStepNode(this); return true; } return false; }
/** * New script group * @param fullName String * @param displayName String * @param serviceRegistry ServiceRegistry * @param authorityService AuthorityService * @param scope Scriptable */ private ScriptGroup(String fullName, String displayName, ServiceRegistry serviceRegistry, AuthorityService authorityService, Scriptable scope) { this.authorityService = authorityService; this.serviceRegistry = serviceRegistry; this.fullName = fullName; this.scope = scope; shortName = authorityService.getShortName(fullName); this.displayName = displayName; }
protected boolean executeNextStep(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (hasSteps()) { for (int i=0; i<numberOfSteps(); i++) { if (bContinue && sequence.isRunning()) executeNextStep((Step)getSteps().get(i), javascriptContext, scope); else break; } } return true; } return false; }
@Override public void put(String name, Scriptable start, Object value) { if (this == thePrototypeInstance) super.put(name, start, value); else System.getProperties().put(name, ScriptRuntime.toString(value)); }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { HtmlTransaction htmlTransaction = (HtmlTransaction)getParentTransaction(); HtmlConnector htmlConnector = (HtmlConnector)htmlTransaction.getParent(); NavigationBarEvent evt; if(action.equalsIgnoreCase(NavigationBarEvent.ACTION_GOTO)){ evaluate(javascriptContext, scope, jsUrl, "jsUrl", false); String url = evaluated.toString(); evt = new NavigationBarEvent(action, url); }else{ evt = new NavigationBarEvent(action); } HtmlParser htmlParser = htmlConnector.getHtmlParser(); boolean success = htmlParser.dispatchEvent(evt, htmlTransaction.context, trigger.getTrigger()); if(!success) Engine.logBeans.debug("NavigationBarStatement has failed"); success = true; //TODO: �a boucle � false return success; } } return false; }
/** * Constructor * * @param siteInfo site information */ /*package*/ Site(SiteInfo siteInfo, ServiceRegistry serviceRegistry, SiteService siteService, Scriptable scope) { this.serviceRegistry = serviceRegistry; this.siteService = siteService; this.siteInfo = siteInfo; this.scope = scope; this.invitationService = serviceRegistry.getInvitationService(); NodeService nodeService = serviceRegistry.getNodeService(); PersonService personService = serviceRegistry.getPersonService(); this.scriptInvitationFactory = new ScriptInvitationFactory(invitationService, nodeService, personService); }