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

x33g5p2x  于2022-01-18 转载在 JavaScript  
字(12.6k)|赞(0)|评价(0)|浏览(322)

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

Context介绍

[英]This class represents the runtime context of an executing script. Before executing a script, an instance of Context must be created and associated with the thread that will be executing the script. The Context will be used to store information about the executing of the script such as the call stack. Contexts are associated with the current thread using the #call(ContextAction)or #enter() methods.

Different forms of script execution are supported. Scripts may be evaluated from the source directly, or first compiled and then later executed. Interactive execution is also supported.

Some aspects of script execution, such as type conversions and object creation, may be accessed directly through methods of Context.
[中]此类表示正在执行的脚本的运行时上下文。在执行脚本之前,必须创建上下文实例并将其与将执行脚本的线程关联。上下文将用于存储有关脚本执行的信息,如调用堆栈。使用#call(ContextAction)或#enter()方法将上下文与当前线程关联。
支持不同形式的脚本执行。脚本可以直接从源代码进行评估,也可以先编译,然后再执行。还支持交互式执行。
脚本执行的某些方面,例如类型转换和对象创建,可以通过上下文方法直接访问。

代码示例

代码示例来源:origin: apache/incubator-druid

private static Function compile(String function)
{
 final ContextFactory contextFactory = ContextFactory.getGlobal();
 final Context context = contextFactory.enterContext();
 context.setOptimizationLevel(JavaScriptConfig.DEFAULT_OPTIMIZATION_LEVEL);
 final ScriptableObject scope = context.initStandardObjects();
 final org.mozilla.javascript.Function fn = context.compileFunction(scope, function, "fn", 1, null);
 Context.exit();
 return new Function()
 {
  @Override
  public double apply(Object[] args)
  {
   // ideally we need a close() function to discard the context once it is not used anymore
   Context cx = Context.getCurrentContext();
   if (cx == null) {
    cx = contextFactory.enterContext();
   }
   return Context.toNumber(fn.call(cx, scope, scope, args));
  }
 };
}

代码示例来源:origin: apache/incubator-druid

public JavaScriptPredicateFactory(final String script, final ExtractionFn extractionFn)
{
 Preconditions.checkNotNull(script, "script must not be null");
 this.script = script;
 this.extractionFn = extractionFn;
 final Context cx = Context.enter();
 try {
  cx.setOptimizationLevel(9);
  scope = cx.initStandardObjects();
  fnApply = cx.compileFunction(scope, script, "script", 1, null);
 }
 finally {
  Context.exit();
 }
}

代码示例来源:origin: facebook/stetho

@Override
public @Nullable Object evaluate(@NonNull String expression) throws Throwable {
  Object result;
  final Context jsContext = enterJsContext();
  try {
   result = jsContext.evaluateString(mJsScope, expression, "chrome", 1, null);
   // Google chrome automatically saves the last expression to `$_`, we do the same
   Object jsValue = Context.javaToJS(result, mJsScope);
   ScriptableObject.putProperty(mJsScope, "$_", jsValue);
  } finally {
   Context.exit();
  }
  return Context.jsToJava(result, Object.class);
}

代码示例来源:origin: apache/incubator-druid

@Override
 public String apply(Object input)
 {
  // ideally we need a close() function to discard the context once it is not used anymore
  Context cx = Context.getCurrentContext();
  if (cx == null) {
   cx = contextFactory.enterContext();
  }
  final Object res = fn.call(cx, scope, scope, new Object[]{input});
  return res != null ? Context.toString(res) : null;
 }
};

代码示例来源:origin: apache/incubator-druid

@Override
 public Object apply(Object input)
 {
  // ideally we need a close() function to discard the context once it is not used anymore
  Context cx = Context.getCurrentContext();
  if (cx == null) {
   cx = contextFactory.enterContext();
  }
  final Object res = fn.call(cx, scope, scope, new Object[]{input});
  return res != null ? Context.toObject(res, scope) : null;
 }
};

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

jscx = ContextFactory.getGlobal().enterContext();
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 );
  if ( getAddClasses() != null ) {
   for ( int i = 0; i < getAddClasses().length; i++ ) {
    Object jsOut = Context.javaToJS( getAddClasses()[i].getAddObject(), jsscope );
    ScriptableObject.putProperty( jsscope, getAddClasses()[i].getJSName(), jsOut );
  Context.javaToJS( ScriptValuesAddedFunctions.class, jsscope );
  ( (ScriptableObject) jsscope )
   .defineFunctionProperties(
    ScriptValuesAddedFunctions.jsFunctionList, ScriptValuesAddedFunctions.class,
    ScriptableObject.DONTENUM );
  Scriptable jsvalue = Context.toObject( dummyStep, jsscope );
  Scriptable jsRowMeta = Context.toObject( prev, jsscope );
    Scriptable jsarg = Context.toObject( value, jsscope );
    Scriptable jsarg = Context.toObject( valueData, jsscope );

代码示例来源:origin: TeamNewPipe/NewPipeExtractor

private String decryptSignature(String encryptedSig, String decryptionCode) throws DecryptException {
  Context context = Context.enter();
  context.setOptimizationLevel(-1);
  Object result;
  try {
    ScriptableObject scope = context.initStandardObjects();
    context.evaluateString(scope, decryptionCode, "decryptionCode", 1, null);
    Function decryptionFunc = (Function) scope.get("decrypt", scope);
    result = decryptionFunc.call(context, scope, scope, new Object[]{encryptedSig});
  } catch (Exception e) {
    throw new DecryptException("could not get decrypt signature", e);
  } finally {
    Context.exit();
  }
  return result == null ? "" : result.toString();
}

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

Scriptable scope;
cx = ContextFactory.getGlobal().enterContext();
 scope = cx.initStandardObjects( null );
 Long nr = new Long( result.getEntryNr() );
 scope.put( "errors", scope, errors );
 scope.put( "lines_input", scope, lines_input );
 scope.put( "lines_output", scope, lines_output );
 scope.put( "lines_updated", scope, lines_updated );
 scope.put( "lines_rejected", scope, lines_rejected );
  Object res = cx.evaluateString( scope, this.script, "<cmd>", 1, null );
  boolean retval = Context.toBoolean( res );
 return false;
} finally {
 Context.exit();

代码示例来源:origin: EngineHub/WorldEdit

Context cx = factory.enterContext();
ScriptableObject scriptable = new ImporterTopLevel(cx);
Scriptable scope = cx.initStandardObjects(scriptable);
  ScriptableObject.putProperty(scope, entry.getKey(),
      Context.javaToJS(entry.getValue(), scope));
  return cx.evaluateString(scope, script, filename, 1, null);
} catch (Error e) {
  throw new ScriptException(e.getMessage());
  Context.exit();

代码示例来源:origin: facebook/stetho

/**
  * Setups a proper javascript context so that it can run javascript code properly under android.
  * For android we need to disable bytecode generation since the android vms don't understand JVM bytecode.
  * @return a proper javascript context
  */
 static @NonNull Context enterJsContext() {
  final Context jsContext = Context.enter();

  // If we cause the context to throw a runtime exception from this point
  // we need to make sure that exit the context.
  try {
   jsContext.setLanguageVersion(Context.VERSION_1_8);

   // We can't let Rhino to optimize the JS and to use a JIT because it would generate JVM bytecode
   // and android runs on DEX bytecode. Instead we need to go in interpreted mode.
   jsContext.setOptimizationLevel(-1);
  } catch (RuntimeException e) {
   // Something bad happened to the javascript context but it might still be usable.
   // The first thing to do is to exit the context and then propagate the error.
   Context.exit();
   throw e;
  }

  return jsContext;
 }
}

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

String script = "function abc(x,y) {return x+y;}"
    + "function def(u,v) {return u-v;}";
Context context = Context.enter();
try {
  ScriptableObject scope = context.initStandardObjects();
  context.evaluateString(scope, script, "script", 1, null);
  Function fct = (Function)scope.get("abc", scope);
  Object result = fct.call(
      context, scope, scope, new Object[] {2, 3});
  System.out.println(Context.jsToJava(result, int.class));
} finally {
  Context.exit();
}

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

public static String getVariable( Context actualContext, Scriptable actualObject, Object[] ArgList,
 Function FunctionContext ) {
 String sRC = "";
 String sArg1 = "";
 String sArg2 = "";
 if ( ArgList.length == 2 ) {
  try {
   Object scmo = actualObject.get( "_step_", actualObject );
   Object scmO = Context.jsToJava( scmo, StepInterface.class );
   if ( scmO instanceof StepInterface ) {
    StepInterface scm = (StepInterface) Context.jsToJava( scmO, StepInterface.class );
    sArg1 = Context.toString( ArgList[0] );
    sArg2 = Context.toString( ArgList[1] );
    return scm.getVariable( sArg1, sArg2 );
   } else {
    // running via the Test button in a dialog
    sArg2 = Context.toString( ArgList[1] );
    return sArg2;
   }
  } catch ( Exception e ) {
   sRC = "";
  }
 } else {
  throw Context.reportRuntimeError( "The function call getVariable requires 2 arguments." );
 }
 return sRC;
}

代码示例来源:origin: apache/incubator-druid

public boolean applyObject(final Object input)
{
 // one and only one context per thread
 final Context cx = Context.enter();
 try {
  return applyInContext(cx, input);
 }
 finally {
  Context.exit();
 }
}

代码示例来源: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: stackoverflow.com

String script = "function abc(x,y) {return x+y;}";
Context context = Context.enter();
try {
  ScriptableObject scope = context.initStandardObjects();
  Scriptable that = context.newObject(scope);
  Function fct = context.compileFunction(scope, script, "script", 1, null);
  Object result = fct.call(
      context, scope, that, new Object[] {2, 3});
  System.out.println(Context.jsToJava(result, int.class));
} finally {
  Context.exit();
}

代码示例来源:origin: xtuhcy/gecco

@Override
@SuppressWarnings({ "unchecked" })
public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
  Context cx = Context.enter();
  ScriptableObject scope = cx.initSafeStandardObjects();
  String windowScript = "var window = {};var document = {};";
  cx.evaluateString(scope, windowScript, "window", 1, null);
  HtmlParser parser = new HtmlParser(request.getUrl(), response.getContent());
  for (Element ele : parser.$("script")) {
    String sc = ele.html();
    if (StringUtils.isNotEmpty(sc)) {
      try {
        cx.evaluateString(scope, sc, "", 1, null);
      } catch (Exception ex) {
        // ex.printStackTrace();
      }
    }
  }
  Map<String, Object> fieldMap = new HashMap<String, Object>();
  Set<Field> jsVarFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSVar.class));
  for (Field jsVarField : jsVarFields) {
    Object value = injectJsVarField(request, beanMap, jsVarField, cx, scope);
    if(value != null) {
      fieldMap.put(jsVarField.getName(), value);
    }
  }
  beanMap.putAll(fieldMap);
  Context.exit();
}

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

public Object getObject() {
  Scriptable newPackages;
  Context.enter();
  try {
    final String JAVA_PACKAGE = "JavaPackage";
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    // FIXME - NativeJavaPackage is an internal class which we should not use
    newPackages = new NativeJavaPackage( "", cl );
    newPackages.setParentScope( getScope() );
    newPackages.setPrototype( ScriptableObject.getClassPrototype(   getScope(),
                                    JAVA_PACKAGE ) );
    //objectModel.put( "Packages", newPackages );
    //objectModel.put( "java", ScriptableObject.getProperty( getScope(), "java" ) );
  } finally {
    Context.exit();
  }
  return newPackages;
}

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

@BeforeClass
public static void setUp() throws Exception {
 ctx = Context.enter();
 scope = ctx.initStandardObjects();
}

代码示例来源:origin: org.freemarker/freemarker

public Object exec(List arguments) throws TemplateModelException {
    Context cx = Context.getCurrentContext();
    Object[] args = arguments.toArray();
    BeansWrapper wrapper = getWrapper();
    for (int i = 0; i < args.length; i++) {
      args[i] = wrapper.unwrap((TemplateModel) args[i]);
    }
    return wrapper.wrap(((Function) getScriptable()).call(cx, 
        ScriptableObject.getTopLevelScope(fnThis), fnThis, args));
  }
}

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

public String[] getPropertyNames(Object obj) {
  Context.enter();
  try {
    Object[] ids;
    if (obj instanceof ScriptableObject) {
      ids = ((ScriptableObject)obj).getAllIds();
    } else {
      ids = ((Scriptable)obj).getIds();
    }
    String[] result = new String[ids.length];
    for (int i = 0; i < result.length; i++) {
      result[i] = (String)ids[i];
    }
    return result;
  } finally {
    Context.exit();
  }
}

相关文章

Context类方法