org.mozilla.javascript.Script类的使用及代码示例

x33g5p2x  于2022-01-30 转载在 JavaScript  
字(12.8k)|赞(0)|评价(0)|浏览(302)

本文整理了Java中org.mozilla.javascript.Script类的一些代码示例,展示了Script类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Script类的具体详情如下:
包路径:org.mozilla.javascript.Script
类名称:Script

Script介绍

[英]All compiled scripts implement this interface.

This class encapsulates script execution relative to an object scope.
[中]所有编译的脚本都实现了这个接口。
此类封装相对于对象范围的脚本执行。

代码示例

代码示例来源:origin: pentaho/pentaho-kettle

jsscope = jscx.initStandardObjects( null, false );
try {
 jscx.setOptimizationLevel( Integer.valueOf( transMeta.environmentSubstitute( optimizationLevel ) ) );
} catch ( NumberFormatException nfe ) {
 error_message =
  Scriptable jsR = Context.toObject( jsScripts[i].getScript(), jsscope );
  jsscope.put( jsScripts[i].getScriptName(), jsscope, jsR );
   jsscript.exec( jscx, jsscope );

代码示例来源:origin: pentaho/pentaho-kettle

String optimizationLevelAsString = environmentSubstitute( meta.getOptimizationLevel() );
 if ( !Utils.isEmpty( Const.trim( optimizationLevelAsString ) ) ) {
  data.cx.setOptimizationLevel( Integer.parseInt( optimizationLevelAsString.trim() ) );
  logBasic( BaseMessages.getString( PKG, "ScriptValuesMod.Optimization.Level", environmentSubstitute( meta
   .getOptimizationLevel() ) ) );
 } else {
  data.cx.setOptimizationLevel( Integer.parseInt( ScriptValuesMetaMod.OPTIMIZATION_LEVEL_DEFAULT ) );
  logBasic( BaseMessages.getString(
   PKG, "ScriptValuesMod.Optimization.UsingDefault", ScriptValuesMetaMod.OPTIMIZATION_LEVEL_DEFAULT ) );
data.scope = data.cx.initStandardObjects( null, false );
   Script startScript = data.cx.compileString( strStartScript, "trans_Start", 1, null );
   startScript.exec( data.cx, data.scope );
   if ( log.isDetailed() ) {
    logDetailed( ( "Start Script found!" ) );
data.script.exec( data.cx, data.scope );

代码示例来源:origin: PeterKnego/LeanEngine-Server

@POST
@Path("/{scriptName}")
public String scriptPOST(@PathParam("scriptName") String scriptName, String code) throws LeanException {
  //todo resolve Script name
  Context ctx = Context.enter();
  try {
    ScriptableObject scope = ctx.initStandardObjects();
    Script script = ctx.compileString(code, "<code>", 1, null);
    Object result = script.exec(ctx, scope);
    if (result == null || !result.getClass().equals(NativeObject.class)) {
      throw new LeanException(LeanException.Error.ScriptOutputError, scriptName);
    }
    return toJSON((NativeObject) result).toString();
  } catch (RhinoException ex) {
    throw new LeanException(LeanException.Error.ScriptExecutionError, scriptName, ex);
  } finally {
    Context.exit();
  }
}

代码示例来源:origin: tv.cntt/rhinocoffeescript

public static String compile(String coffeeScript) throws ScriptException {
    Context ctx = Context.enter();
    try {
      Scriptable scope  = ctx.initStandardObjects();
      Script     script = (Script) new CoffeeScript();
      script.exec(ctx, scope);

      NativeObject obj  = (NativeObject) scope.get("CoffeeScript", scope);
      Function     fun  = (Function) obj.get("compile", scope);
      Object       opts = ctx.evaluateString(scope, "({bare: true})", null, 1, null);

      String javaScript = (String) fun.call(ctx, scope, obj, new Object[] {coffeeScript, opts});
      return javaScript;
    } catch (JavaScriptException e) {
      // Extract line and column of the error location in the CoffeeScript.
      // The below code is guessed from:
      // - Experimenting http://coffeescript.org/ with Chrome JavaScript Console
      // - https://code.google.com/p/wiquery/source/browse/trunk/src/main/java/org/mozilla/javascript/NativeError.java?spec=svn1010&r=1010
      Scriptable syntaxError = (Scriptable) e.getValue();
      Scriptable location    = (Scriptable) ScriptableObject.getProperty(syntaxError, "location");
      Double     firstLine   = (Double) ScriptableObject.getProperty(location, "first_line");
      Double     firstColumn = (Double) ScriptableObject.getProperty(location, "first_column");

      throw new ScriptException("CoffeeScript syntax error", "", firstLine.intValue(), firstColumn.intValue());
    } finally {
      Context.exit();
    }
  }
}

代码示例来源:origin: org.apache.cocoon/cocoon-expression-language-impl

public Object evaluate(ObjectModel objectModel) throws ExpressionException {
  Context ctx = Context.enter();
  try {
    Scriptable scope = ctx.newObject(getScope(rootScope));
    // Populate the scope
    Iterator iter = objectModel.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      String key = (String) entry.getKey();
      Object value = entry.getValue();
      scope.put(key, scope, Context.toObject(value, scope));
    }
    Object result = this.script.exec(ctx, scope);
    return unwrap(result);
  } finally {
    Context.exit();
  }
}

代码示例来源:origin: org.seasar.mayaa/mayaa

public Object execute(Object[] args) {
  Context cx = RhinoUtil.enter();
  Object ret = null;
  try {
    compileFromSource(cx, getSource());
    Object jsRet = _rhinoScript.exec(cx, RhinoUtil.getScope());
    ret = RhinoUtil.convertResult(cx, getExpectedClass(), jsRet);
  } catch (WrappedException e) {
    RhinoUtil.removeWrappedException(e);
  } finally {
    Context.exit();
  }
  return ret;
}

代码示例来源:origin: RPTools/maptool

public static synchronized void init() throws IOException {
  if (jsScope != null)
    return;
  try {
    Context jsContext = ContextFactory.getGlobal().enterContext();
    jsContext.setClassShutter(new SecurityClassShutter());
    jsScope = jsContext.initStandardObjects(null, true);
    Object o = Context.javaToJS(new TokenApi(), jsScope);
    ScriptableObject.putProperty(jsScope, "rptools_global_tokens", o);
    for (String script : JAVASCRIPT_FILES) {
      Reader reader = new InputStreamReader(ScriptManager.class.getClassLoader().getResourceAsStream(script));
      Script compiled = jsContext.compileReader(reader, script, 1, null);
      compiled.exec(jsContext, jsScope);
    }
    // jsScope.sealObject();
  } finally {
    Context.exit();
  }
}

代码示例来源:origin: datacleaner/DataCleaner

@Override
public Object[] transform(final InputRow inputRow) {
  final Context context = _contextFactory.enterContext();
  try {
    // this scope is local to the execution of a single row
    final Scriptable scope = context.newObject(_sharedScope);
    scope.setPrototype(_sharedScope);
    scope.setParentScope(null);
    JavaScriptUtils.addToScope(scope, inputRow, columns, "values");
    Object result = _script.exec(context, scope);
    // String stringResult = Context.toString(result);
    if (result == null) {
      result = null;
    } else if (returnType == ReturnType.NUMBER) {
      result = Context.toNumber(result);
    } else if (returnType == ReturnType.BOOLEAN) {
      result = Context.toBoolean(result);
    } else {
      result = Context.toString(result);
    }
    return new Object[] { result };
  } finally {
    Context.exit();
  }
}

代码示例来源:origin: pentaho/pentaho-kettle

Script endScript = data.cx.compileString( strEndScript, "trans_End", 1, null );
 endScript.exec( data.cx, data.scope );
 if ( log.isDetailed() ) {
  logDetailed( ( "End Script found!" ) );
Context.exit();

代码示例来源:origin: eBay/YiDB

public Object call() throws ExpressionParseException {
    Object result = null;
    try {
      final Script script = ((RhinoExpression) theExpression).getCompiledExpression();
      final Context rhinoContext = Context.enter();
      final Scriptable scope = new RhinoScriptObject(theContext);
      scope.setPrototype(parentScope);
      scope.setParentScope(null);
      result = script.exec(rhinoContext, scope);
    } catch (ExpressionParseException e) {
      throw new ExpressionParseException(MessageFormat.format("" + e.getMessage()
          + "\n Failed to parse script:{0}", theExpression.getStringExpression()), e);
    } finally {
      Context.exit();
    }
    return result;
  }
};

代码示例来源:origin: datacleaner/DataCleaner

@Override
public Category categorize(final InputRow inputRow) {
  final Context context = _contextFactory.enterContext();
  try {
    // this scope is local to the execution of a single row
    final Scriptable scope = context.newObject(_sharedScope);
    scope.setPrototype(_sharedScope);
    scope.setParentScope(null);
    JavaScriptUtils.addToScope(scope, inputRow, columns, "values");
    final Object result = _script.exec(context, scope);
    final boolean booleanResult = Context.toBoolean(result);
    if (booleanResult) {
      return JavaScriptFilter.Category.VALID;
    }
    return JavaScriptFilter.Category.INVALID;
  } finally {
    Context.exit();
  }
}

代码示例来源:origin: stackoverflow.com

Script script = cx.compileString(scriptText, "<command>", 1, null);
if (script != null) {
  script.exec(cx, getShellScope()); // <- just an eval
}

代码示例来源:origin: apache/cxf

private Object[] compileScript(Context cx, String scriptStr, Scriptable scriptScope, File f) {
  int opt = cx.getOptimizationLevel();
  cx.setOptimizationLevel(-1);
  Script script = cx.compileString(scriptStr, f.getName(), 1, null);
  script.exec(cx, scriptScope);
  Object[] ids = scriptScope.getIds();
  cx.setOptimizationLevel(opt);
  script = cx.compileString(scriptStr, f.getName(), 1, null);
  script.exec(cx, scriptScope);
  return ids;
}

代码示例来源:origin: rhino/js

/**
 * Evaluate a JavaScript source string.
 *
 * The provided source name and line number are used for error messages
 * and for producing debug information.
 *
 * @param scope the scope to execute in
 * @param source the JavaScript source
 * @param sourceName a string describing the source, such as a filename
 * @param lineno the starting line number
 * @param securityDomain an arbitrary object that specifies security
 *        information about the origin or owner of the script. For
 *        implementations that don't care about security, this value
 *        may be null.
 * @return the result of evaluating the string
 * @see org.mozilla.javascript.SecurityController
 */
public final Object evaluateString(Scriptable scope, String source,
                  String sourceName, int lineno,
                  Object securityDomain)
{
  Script script = compileString(source, sourceName, lineno,
                 securityDomain);
  if (script != null) {
    return script.exec(this, scope);
  } else {
    return null;
  }
}

代码示例来源:origin: geogebra/geogebra

public Object run(Context cx)
  {
    ScriptableObject global = getGlobal(cx);
    // get the command line arguments and define "arguments"
    // array in the top-level object
    Object[] argsCopy = new Object[args.length];
    System.arraycopy(args, 0, argsCopy, 0, args.length);
    Scriptable argsObj = cx.newArray(global, argsCopy);
    global.defineProperty("arguments", argsObj,
               ScriptableObject.DONTENUM);
    script.exec(cx, global);
    return null;
  }
});

代码示例来源:origin: geogebra/geogebra

private Scriptable executeModuleScript(Context cx, String id,
    Scriptable exports, ModuleScript moduleScript, boolean isMain)
{
  final ScriptableObject moduleObject = (ScriptableObject)cx.newObject(
      nativeScope);
  URI uri = moduleScript.getUri();
  URI base = moduleScript.getBase();
  defineReadOnlyProperty(moduleObject, "id", id);
  if(!sandboxed) {
    defineReadOnlyProperty(moduleObject, "uri", uri.toString());
  }
  final Scriptable executionScope = new ModuleScope(nativeScope, uri, base);
  // Set this so it can access the global JS environment objects.
  // This means we're currently using the "MGN" approach (ModuleScript
  // with Global Natives) as specified here:
  // <http://wiki.commonjs.org/wiki/Modules/ProposalForNativeExtension>
  executionScope.put("exports", executionScope, exports);
  executionScope.put("module", executionScope, moduleObject);
  moduleObject.put("exports", moduleObject, exports);
  install(executionScope);
  if(isMain) {
    defineReadOnlyProperty(this, "main", moduleObject);
  }
  executeOptionalScript(preExec, cx, executionScope);
  moduleScript.getScript().exec(cx, executionScope);
  executeOptionalScript(postExec, cx, executionScope);
  return ScriptRuntime.toObject(cx, nativeScope,
      ScriptableObject.getProperty(moduleObject, "exports"));
}

代码示例来源:origin: rhino/js

throws IOException
Script script = compileReader(scope, in, sourceName, lineno,
               securityDomain);
if (script != null) {
  return script.exec(this, scope);
} else {
  return null;

代码示例来源:origin: dk.eobjects.datacleaner/DataCleaner-core

@Override
protected boolean isValid(Row row) throws Exception {
  Map<String, Object> values = new ScriptAccessColumnMap(_columns, row,
      _evaluatedColumns);
  Scriptable scope = _context.newObject(_standardObjectsScope);
  scope.setPrototype(_standardObjectsScope);
  scope.setParentScope(null);
  Object wrappedValues = Context.javaToJS(values, scope);
  ScriptableObject.putProperty(scope, "values", wrappedValues);
  Object result = _script.exec(_context, scope);
  if (result instanceof Boolean) {
    return (Boolean) result;
  }
  throw new IllegalStateException(
      "Javascript expression did not return a boolean");
}

代码示例来源:origin: ro.isdc.wro4j/rhino

static void evalInlineScript(Context cx, String scriptText) {
  try {
    Script script = cx.compileString(scriptText, "<command>", 1, null);
    if (script != null) {
      script.exec(cx, getShellScope());
    }
  } 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;
  }
}

代码示例来源:origin: javanna/elasticshell

public Object execute(CompilableSource source) {
  try {
    logger.debug("Compiling source {}", source.getSource());
    Script script = compile(source);
    if (script != null) {
      logger.debug("Executing compiled script");
      Object result = script.exec(Context.getCurrentContext(), shellScope.get());
      logger.debug("Returned object [{}]", result);
      if(result instanceof Undefined) {
        return null;
      }
      return result;
    }
  } catch(RhinoException rex) {
    logger.error(rex.getMessage(), rex);
    Context.reportError(rex.details(), null, rex.lineNumber(), rex.lineSource(), rex.columnNumber());
  } catch(VirtualMachineError ex) {
    logger.error(ex.getMessage(), ex);
    String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
    Context.reportError(msg);
  } catch(Throwable t) {
    logger.error(t.getMessage(), t);
    String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", t.toString());
    Context.reportError(msg);
  }
  return null;
}

相关文章