org.mozilla.javascript.Context Java Examples

The following examples show how to use org.mozilla.javascript.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NativeFinanceTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void setUp() throws Exception
{
	/*
	 * Creates and enters a Context. The Context stores information about
	 * the execution environment of a script.
	 */

	cx = Context.enter( );
	/*
	 * Initialize the standard objects (Object, Function, etc.) This must be
	 * done before scripts can be executed. Returns a scope object that we
	 * use in later calls.
	 */
	scope = cx.initStandardObjects( );

	new CoreJavaScriptInitializer().initialize( cx, scope );

}
 
Example #2
Source File: NativeJavaMapTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void setUp() throws Exception
{
	/*
	 * Creates and enters a Context. The Context stores information about
	 * the execution environment of a script.
	 */

	cx = Context.enter( );
	/*
	 * Initialize the standard objects (Object, Function, etc.) This must be
	 * done before scripts can be executed. Returns a scope object that we
	 * use in later calls.
	 */
	scope = cx.initStandardObjects( );

	// ScriptableObject.defineClass(scope, NativeNamedList.class);

	registerBeans( );

}
 
Example #3
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testFunctionWithContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        cx.evaluateString(globalScope,
                "function f(a) { return myObject.f(a); }",
                "function test source", 1, null);
        Function f = (Function) globalScope.get("f", globalScope);
        Object[] args = { 7 };
        cx.callFunctionWithContinuations(f, globalScope, args);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        Object applicationState = pending.getApplicationState();
        assertEquals(7, ((Number)applicationState).intValue());
        int saved = (Integer) applicationState;
        Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1);
        assertEquals(8, ((Number)result).intValue());
    } finally {
        Context.exit();
    }
}
 
Example #4
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static void appendToFile( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                 Function FunctionContext ) {

  if ( !isNull( ArgList ) && !isUndefined( ArgList ) ) {
    try {
      FileOutputStream file = new FileOutputStream( Context.toString( ArgList[ 0 ] ), true );
      DataOutputStream out = new DataOutputStream( file );
      out.writeBytes( Context.toString( ArgList[ 1 ] ) );
      out.flush();
      out.close();
    } catch ( Exception er ) {
      throw Context.reportRuntimeError( er.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call appendToFile requires arguments." );
  }
}
 
Example #5
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static Object[] createRowCopy( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                      Function FunctionContext ) {
  if ( ArgList.length == 1 ) {
    try {
      int newSize = (int) Math.round( Context.toNumber( ArgList[ 0 ] ) );

      Object scmO = actualObject.get( "row", actualObject );
      Object[] row = (Object[]) Context.jsToJava( scmO, ( new Object[] {} ).getClass() );

      return RowDataUtil.createResizedCopy( row, newSize );
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "Unable to create a row copy: " + Const.CR + e.toString() );
    }
  } else {
    throw Context
      .reportRuntimeError( "The function call createRowCopy requires a single arguments : the new size of the row" );
  }
}
 
Example #6
Source File: ScriptDialog.java    From hop with Apache License 2.0 6 votes vote down vote up
public static ScriptNode parseVariables( Context cx, Scriptable scope, String source, String sourceName,
                                         int lineno, Object securityDomain ) {
  // Interpreter compiler = new Interpreter();
  CompilerEnvirons evn = new CompilerEnvirons();
  // evn.setLanguageVersion(Context.VERSION_1_5);
  evn.setOptimizationLevel( -1 );
  evn.setGeneratingSource( true );
  evn.setGenerateDebugInfo( true );
  ErrorReporter errorReporter = new ToolErrorReporter( false );
  Parser p = new Parser( evn, errorReporter );
  ScriptNode tree = p.parse( source, "", 0 ); // IOException
  new NodeTransformer().transform( tree );
  // Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
  return tree;
}
 
Example #7
Source File: PrimitiveTypeScopeResolutionTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
private void testWithTwoScopes(final String scriptScope1,
                               final String scriptScope2)
{
	final ContextAction action = new ContextAction()
	{
		public Object run(final Context cx)
		{
	        final Scriptable scope1 = cx.initStandardObjects(
	            new MySimpleScriptableObject("scope1"));
	        final Scriptable scope2 = cx.initStandardObjects(
	            new MySimpleScriptableObject("scope2"));
	        cx.evaluateString(scope2, scriptScope2, "source2", 1, null);

	        scope1.put("scope2", scope1, scope2);

	        return cx.evaluateString(scope1, scriptScope1, "source1", 1,
	                                 null);
		}
	};
	Utils.runWithAllOptimizationLevels(action);
}
 
Example #8
Source File: NativeNamedListTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void setUp() throws Exception
{
	/*
	 * Creates and enters a Context. The Context stores information about
	 * the execution environment of a script.
	 */

	cx = Context.enter( );
	/*
	 * Initialize the standard objects (Object, Function, etc.) This must be
	 * done before scripts can be executed. Returns a scope object that we
	 * use in later calls.
	 */
	scope = cx.initStandardObjects( );

	//ScriptableObject.defineClass(scope, NativeNamedList.class);
	
	registerBeans();

}
 
Example #9
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @return The array of aspects applied to this node as short prefix qname strings
 */
public Scriptable getAspectsShort()
{
    final NamespaceService ns = this.services.getNamespaceService();
    final Map<String, String> cache = new HashMap<String, String>();
    final Set<QName> aspects = getAspectsSet();
    final Object[] result = new Object[aspects.size()];
    int count = 0;
    for (final QName qname : aspects)
    {
        String prefix = cache.get(qname.getNamespaceURI());
        if (prefix == null)
        {
            // first request for this namespace prefix, get and cache result
            Collection<String> prefixes = ns.getPrefixes(qname.getNamespaceURI());
            prefix = prefixes.size() != 0 ? prefixes.iterator().next() : "";
            cache.put(qname.getNamespaceURI(), prefix);
        }
        result[count++] = prefix + QName.NAMESPACE_PREFIX + qname.getLocalName();
    }
    return Context.getCurrentContext().newArray(this.scope, result);
}
 
Example #10
Source File: OIDCRelyingPartyObject.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static String jsFunction_getLoggedInUser(Context cx, Scriptable thisObj,
                                                Object[] args,
                                                Function funObj)
        throws ScriptException {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Session id is missing.");
    }
    OIDCRelyingPartyObject relyingPartyObject = (OIDCRelyingPartyObject) thisObj;
    SessionInfo sessionInfo = relyingPartyObject.getSessionInfo((String) args[0]);
    String loggedInUser = null;
    if (sessionInfo != null && sessionInfo.getLoggedInUser() != null) {
        loggedInUser = sessionInfo.getLoggedInUser();
    }

    return loggedInUser;

}
 
Example #11
Source File: CubeQueryUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 
 * @param expr
 * @param objectName
 * @return
 */
private static String getReferencedScriptObject( String expr,
		String objectName )
{
	if ( expr == null )
		return null;
	try
	{
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr, null, 0 );
		IRFactory ir = new IRFactory( ce );
		ScriptNode script = ir.transformTree( tree );
		return getScriptObjectName( script, objectName );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #12
Source File: RhinoWorkerUtils.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static Scriptable parse(File source, String encoding, Action<Context> contextConfig) {
    Context context = Context.enter();
    if (contextConfig != null) {
        contextConfig.execute(context);
    }

    Scriptable scope = context.initStandardObjects();
    try {
        Reader reader = new InputStreamReader(new FileInputStream(source), encoding);
        try {
            context.evaluateReader(scope, reader, source.getName(), 0, null);
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        Context.exit();
    }

    return scope;
}
 
Example #13
Source File: BIRTExternalContext.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The constructor.
 * 
 * @param context
 */
public BIRTExternalContext( IReportContext context )
{
	this.context = context;

	final Context cx = Context.enter( );

	try
	{
		Scriptable scope = new ImporterTopLevel( cx );

		scriptableContext = cx.getWrapFactory( ).wrapAsJavaObject( cx,
				scope,
				context,
				null );
	}
	catch ( Exception e )
	{
		logger.log( e );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #14
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static Object getNextWorkingDay( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  // (Date dIn){
  if ( ArgList.length == 1 ) {
    try {
      if ( isNull( ArgList[0] ) ) {
        return null;
      } else if ( isUndefined( ArgList[0] ) ) {
        return Context.getUndefinedValue();
      }
      java.util.Date dIn = (java.util.Date) Context.jsToJava( ArgList[0], java.util.Date.class );
      Calendar startDate = Calendar.getInstance();
      startDate.setTime( dIn );
      startDate.add( Calendar.DATE, 1 );
      while ( startDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SATURDAY
        || startDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SUNDAY ) {
        startDate.add( Calendar.DATE, 1 );
      }
      return startDate.getTime();
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call getNextWorkingDay requires 1 argument." );
  }
}
 
Example #15
Source File: SAMLSSORelyingPartyObject.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * @param cx
 * @param args      - args[0]-issuerId, this issuer need to be registered in Identity server.
 * @param ctorObj
 * @param inNewExpr
 * @return
 * @throws ScriptException
 */
public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj,
                                       boolean inNewExpr)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid arguments!, IssuerId is missing in parameters.");
    }

    SAMLSSORelyingPartyObject relyingPartyObject = ssoRelyingPartyMap.get((String) args[0]);
    if (relyingPartyObject == null) {
        synchronized (SAMLSSORelyingPartyObject.class) {
            if (relyingPartyObject == null) {
                relyingPartyObject = new SAMLSSORelyingPartyObject();
                relyingPartyObject.setSSOProperty(SSOConstants.ISSUER_ID, (String) args[0]);
                ssoRelyingPartyMap.put((String) args[0], relyingPartyObject);
            }
        }
    }
    return relyingPartyObject;
}
 
Example #16
Source File: DefineClassTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotatedHostObject() {
    Context cx = Context.enter();
    try {
        Object result = evaluate(cx, "a = new AnnotatedHostObject(); a.initialized;");
        assertEquals(result, Boolean.TRUE);
        assertEquals(evaluate(cx, "a.instanceFunction();"), "instanceFunction");
        assertEquals(evaluate(cx, "a.namedFunction();"), "namedFunction");
        assertEquals(evaluate(cx, "AnnotatedHostObject.staticFunction();"), "staticFunction");
        assertEquals(evaluate(cx, "AnnotatedHostObject.namedStaticFunction();"), "namedStaticFunction");
        assertNull(evaluate(cx, "a.foo;"));
        assertEquals(evaluate(cx, "a.foo = 'foo'; a.foo;"), "FOO");
        assertEquals(evaluate(cx, "a.bar;"), "bar");

        // Setting a property with no setting should be silently
        // ignored in non-strict mode.
        evaluate(cx, "a.bar = 'new bar'");
        assertEquals("bar", evaluate(cx, "a.bar;"));
    } finally {
        Context.exit();
    }
}
 
Example #17
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static String escapeXml( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                Function FunctionContext ) {
  if ( ArgList.length == 1 ) {
    return Const.escapeXml( Context.toString( ArgList[ 0 ] ) );
  } else {
    throw Context.reportRuntimeError( "The function call escapeXml requires 1 argument." );

  }
}
 
Example #18
Source File: JavaScriptSupport.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** Request that a script gets executed
 *  @param script {@link JavaScript}
 *  @param widget Widget that requests execution
 *  @param pvs PVs that are available to the script
 *  @return
 */
public Future<Object> submit(final JavaScript script, final Widget widget, final RuntimePV... pvs)
{
    // Skip script that's already in the queue.
    if (! markAsScheduled(script))
        return null;

    return support.submit(() ->
    {
        // Script may be queued again
        removeScheduleMarker(script);

        final Context thread_context = Context.enter();
        try
        {
            final Scriptable scope = new ImporterTopLevel(thread_context);
            ScriptableObject.putProperty(scope, "widget", Context.javaToJS(widget, scope));
            ScriptableObject.putProperty(scope, "pvs", Context.javaToJS(pvs, scope));
            script.getCode().exec(thread_context, scope);
        }
        catch (final Throwable ex)
        {
            logger.log(Level.WARNING, "Execution of '" + script + "' failed", ex);
        }
        finally
        {
            Context.exit();
        }
        return null;
    });
}
 
Example #19
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Boolean isMailValid( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                   Function FunctionContext ) {
  Boolean isValid;
  if ( ArgList.length == 1 ) {
    try {
      if ( isUndefined( ArgList[ 0 ] ) ) {
        throw new Exception( ArgList[ 0 ] + " is  undefined!" );
      }
      if ( isNull( ArgList[ 0 ] ) ) {
        return Boolean.FALSE;
      }
      if ( Context.toString( ArgList[ 0 ] ).length() == 0 ) {
        return Boolean.FALSE;
      }

      String email = Context.toString( ArgList[ 0 ] );
      if ( email.indexOf( '@' ) == -1 || email.indexOf( '.' ) == -1 ) {
        return Boolean.FALSE;
      }

      isValid = Boolean.TRUE;

    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "Error in isMailValid function: " + e.getMessage() );
    }
    return isValid;
  } else {
    throw Context.reportRuntimeError( "The function call isMailValid is not valid" );
  }
}
 
Example #20
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static void LoadScriptFromTab( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                      Function FunctionContext ) {
  try {
    for ( int i = 0; i < ArgList.length; i++ ) { // don't worry about "undefined" arguments
      String strToLoad = Context.toString( ArgList[ i ] );
      String strScript = actualObject.get( strToLoad, actualObject ).toString();
      actualContext.evaluateString( actualObject, strScript, "_" + strToLoad + "_", 0, null );
    }
  } catch ( Exception e ) {
    // TODO: DON'T EAT EXCEPTION
    // System.out.println(e.toString());
  }
}
 
Example #21
Source File: Bug421071Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private TopLevelScope createGlobalScope() {
    factory = new DynamicScopeContextFactory();
    Context context = factory.enterContext();
    // noinspection deprecation
    TopLevelScope globalScope = new TopLevelScope(context);
    Context.exit();
    return globalScope;
}
 
Example #22
Source File: SandboxingContextFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean hasFeature(final Context cx, final int featureIndex) {
    switch (featureIndex) {
        case Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME:
            return true;
    }
    return super.hasFeature(cx, featureIndex);
}
 
Example #23
Source File: DcJsContextFactory.java    From io with Apache License 2.0 5 votes vote down vote up
@Override
protected final Context makeContext() {
    DcJsContext cx = new DcJsContext();
    cx.setInstructionObserverThreshold(TIMEOUTVALUE / MVALUE);

    // ClassShutterの登録(Javaパッケージ呼び出し制御)
    cx.setClassShutter(new DcClassShutterImpl());

    cx.setWrapFactory(new PrimitiveWrapFactory());

    return cx;
}
 
Example #24
Source File: JavaScriptUtils.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static Long jsToInteger( Object value, Class<?> clazz ) {
  if ( Number.class.isAssignableFrom( clazz ) ) {
    return ( (Number) value ).longValue();
  } else {
    String classType = clazz.getName();
    if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
      return ( new Long( (String) value ) );
    } else if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
      return null;
    } else if ( classType.equalsIgnoreCase( JS_NATIVE_NUM ) ) {
      Number nb = Context.toNumber( value );
      return nb.longValue();
    } else if ( classType.equalsIgnoreCase( JS_NATIVE_JAVA_OBJ ) ) {
      // Is it a Value?
      //
      try {
        Value v = (Value) Context.jsToJava( value, Value.class );
        return v.getInteger();
      } catch ( Exception e2 ) {
        String string = Context.toString( value );
        return Long.parseLong( Const.trim( string ) );
      }
    } else {
      return Long.parseLong( value.toString() );
    }
  }
}
 
Example #25
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static String removeDigits( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  if ( ArgList.length == 1 ) {
    return Const.removeDigits( Context.toString( ArgList[0] ) );
  } else {
    throw Context.reportRuntimeError( "The function call removeDigits requires 1 argument." );

  }
}
 
Example #26
Source File: Config.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
public Object read(Object key) {
	try {
		IConfigService config = ProxyServiceManager.getService(
				JsGlobal.getGlobal().pkg + ".config", IConfigService.class);
		if (config != null) {
			Object ret = config.read(Context.toString(key));
			if (ret != null) {
				return ret.toString();
			}
		}
	} catch (Exception e) {
	}
	return null;
}
 
Example #27
Source File: Rhino.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void putScopeFunction(String name, Object obj, String method, int params) throws ScriptExecException {
    try {
        Context cx = Context.enter();
        cx.setOptimizationLevel(-1); // always interpretive mode                     
        ScriptableObject.putProperty(scope, "__" + name, Context.javaToJS(obj, scope));         
        cx.evaluateString(scope, "function " + name + "(" + createArgs(params) + ") {return __" + name +"." + method + "(" + createArgs(params) + ");}", "<cmd>", 1, null);
    } finally {
        Context.exit();            
    }
}
 
Example #28
Source File: DataFrameAdapter.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
public static Scriptable jsFunction_convert(final Context ctx, final Scriptable object, final Object[] args, final Function func) {
    if (args.length > 0) {
        final Class<?>[] types = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            types[i] = Class.class.cast(Context.jsToJava(args[i], Class.class));
        }
        return new DataFrameAdapter(object, cast(object).df.convert(types));
    }
    return new DataFrameAdapter(object, cast(object).df.convert());
}
 
Example #29
Source File: Bug491621Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Asserts that the value returned by {@link AstRoot#toSource()} after
 * the given input source was parsed equals the specified expected output source.
 *
 * @param source the JavaScript source to be parsed
 * @param expectedOutput the JavaScript source that is expected to be
 *                       returned by {@link AstRoot#toSource()}
 */
private void assertSource(String source, String expectedOutput)
{
    CompilerEnvirons env = new CompilerEnvirons();
    env.setLanguageVersion(Context.VERSION_1_7);
    Parser parser = new Parser(env);
    AstRoot root = parser.parse(source, null, 0);
    Assert.assertEquals(expectedOutput, root.toSource());
}
 
Example #30
Source File: Main.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
static void processFileSecure(Context cx, Scriptable scope,
                              String path, Object securityDomain)
        throws IOException {

    boolean isClass = path.endsWith(".class");
    Object source = readFileOrUrl(path, !isClass);

    byte[] digest = getDigest(source);
    String key = path + "_" + cx.getOptimizationLevel();
    ScriptReference ref = scriptCache.get(key, digest);
    Script script = ref != null ? ref.get() : null;

    if (script == null) {
        if (isClass) {
            script = loadCompiledScript(cx, path, (byte[])source, securityDomain);
        } else {
            String strSrc = (String) source;
            // Support the executable script #! syntax:  If
            // the first line begins with a '#', treat the whole
            // line as a comment.
            if (strSrc.length() > 0 && strSrc.charAt(0) == '#') {
                for (int i = 1; i != strSrc.length(); ++i) {
                    int c = strSrc.charAt(i);
                    if (c == '\n' || c == '\r') {
                        strSrc = strSrc.substring(i);
                        break;
                    }
                }
            }
            script = cx.compileString(strSrc, path, 1, securityDomain);
        }
        scriptCache.put(key, digest, script);
    }

    if (script != null) {
        script.exec(cx, scope);
    }
}