org.mozilla.javascript.ImporterTopLevel Java Examples

The following examples show how to use org.mozilla.javascript.ImporterTopLevel. 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: JsRuntimeReplFactoryBuilder.java    From stetho with MIT License 6 votes vote down vote up
private @NonNull ScriptableObject initJsScope(@NonNull Context jsContext) {
  // Set the main Rhino goodies
  ImporterTopLevel importerTopLevel = new ImporterTopLevel(jsContext);
  ScriptableObject scope = jsContext.initStandardObjects(importerTopLevel, false);

  ScriptableObject.putProperty(scope, "context", Context.javaToJS(mContext, scope));

  try {
    importClasses(jsContext, scope);
    importPackages(jsContext, scope);
    importConsole(scope);
    importVariables(scope);
    importFunctions(scope);
  } catch (StethoJsException e) {
    String message = String.format("%s\n%s", e.getMessage(), Log.getStackTraceString(e));
    LogUtil.e(e, message);
    CLog.writeToConsole(Console.MessageLevel.ERROR, Console.MessageSource.JAVASCRIPT, message);
  }

  return scope;
}
 
Example #2
Source File: JavaScriptEngine.java    From commons-bsf with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the engine. 
 * Put the manager into the context-manager
 * map hashtable too.
 */
public void initialize(BSFManager mgr, String lang, Vector declaredBeans)
    throws BSFException {
    
    super.initialize(mgr, lang, declaredBeans);

    // Initialize context and global scope object
    try {
        Context cx = Context.enter();
        global = new ImporterTopLevel(cx);
        Scriptable bsf = Context.toObject(new BSFFunctions(mgr, this), global);
        global.put("bsf", global, bsf);

        for(Iterator it = declaredBeans.iterator(); it.hasNext();) {
            declareBean((BSFDeclaredBean) it.next());
        }
    } 
    catch (Throwable t) {

    } 
    finally {
        Context.exit();
    }
}
 
Example #3
Source File: BaseTestCase.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void baseSetUp() throws Exception
{
	// Create test output file
	// We must make sure this folder will be created successfully
	// before we do next job.		
	openOutputFolder();
	openOutputFile();
	
	// Create top-level Javascript scope
	jsContext = Context.enter( );
	jsScope = new ImporterTopLevel(jsContext);
	scriptContext = new ScriptContext().newContext(jsScope);
	
	// Add JS functions testPrint and testPrintln for scripts to write
	// to output file
	jsScope.put("_testCase", jsScope, this );
	jsContext.evaluateString( jsScope,
			"function testPrint(str) { _testCase.testPrint(str); }; " +
			"function testPrintln(str) { _testCase.testPrintln(str); }; "
			, "BaseTestCase.setUp", 1, null );
}
 
Example #4
Source File: MirrorCursorModelTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void mirrorCursorModelSetUp() throws Exception
{
	this.scope = new ImporterTopLevel( );
	DataEngineContext context = DataEngineContext.newInstance( DataEngineContext.DIRECT_PRESENTATION,
			scope,
			null,
			null );
	context.setTmpdir( this.getTempDir( ) );
	de = (DataEngineImpl) DataEngine.newDataEngine( context );
	this.creator = new CubeUtility( );
	creator.createCube( de );
	creator.createCube1( de );
	cube1 = creator.getCube( CubeUtility.cubeName, de );
	cube2 = creator.getCube( CubeUtility.timeCube, de );
}
 
Example #5
Source File: BaseTestCase.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected void setUp( ) throws Exception
{
	super.setUp( );

	// Create test output file
	// We must make sure this folder will be created successfully
	// before we do next job.
	openOutputFolder( );
	openOutputFile( );

	// Create top-level Javascript scope
	jsContext = Context.enter( );
	jsScope = new ImporterTopLevel( jsContext );

	// Add JS functions testPrint and testPrintln for scripts to write
	// to output file
	jsScope.put( "_testCase", jsScope, this );
	jsContext
			.evaluateString(
					jsScope,
					"function testPrint(str) { _testCase.testPrint(str); }; "
							+ "function testPrintln(str) { _testCase.testPrintln(str); }; ",
					"BaseTestCase.setUp", 1, null );
}
 
Example #6
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 #7
Source File: CrosstabScriptHandler.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Initialize the JavaScript context using given parent scope.
 * 
 * @param scPrototype
 *            Parent scope object. If it's null, use default scope.
 */
public void init( Scriptable scPrototype ) throws CrosstabException
{
	final Context cx = Context.enter( );
	try
	{
		if ( scPrototype == null )
		{
			scope = new ImporterTopLevel( cx );
		}
		else
		{
			scope = cx.newObject( scPrototype );
			scope.setPrototype( scPrototype );
		}
	}
	catch ( RhinoException jsx )
	{
		throw convertException( jsx );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #8
Source File: AbstractScriptHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Initialize the JavaScript context using given parent scope.
 * 
 * @param scPrototype
 *            Parent scope object. If it's null, use default scope.
 */
public final void init( Scriptable scPrototype ) throws ChartException
{
	final Context cx = Context.enter( );
	try
	{
		if ( scPrototype == null ) // NO PROTOTYPE
		{
			// scope = cx.initStandardObjects();
			scope = new ImporterTopLevel( cx );
		}
		else
		{
			scope = cx.newObject( scPrototype );
			scope.setPrototype( scPrototype );
			// !don't reset the parent scope here.
			// scope.setParentScope( null );
		}

		// final Scriptable scopePrevious = scope;
		// !deprecated, remove this later. use script context instead.
		// registerExistingScriptableObject( this, "chart" ); //$NON-NLS-1$
		// scope = scopePrevious; // RESTORE

		// !deprecated, remove this later, use logger from script context
		// instead.
		// ADD LOGGING CAPABILITIES TO JAVASCRIPT ACCESS
		final Object oConsole = Context.javaToJS( getLogger( ), scope );
		scope.put( "logger", scope, oConsole ); //$NON-NLS-1$
	}
	catch ( RhinoException jsx )
	{
		throw convertException( jsx );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #9
Source File: AbstractScriptHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The constructor.
 * 
 */
public AbstractScriptHandler( )
{
	final Context cx = Context.enter( );
	try
	{
		// scope = cx.initStandardObjects();
		scope = new ImporterTopLevel( cx );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example #10
Source File: DimensionFilterProcessorTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
@Before
   public void dimensionFilterProcessorSetUp()
{
	cx = new ScriptContext();
	this.baseScope = new ImporterTopLevel( );
	this.cubeQuery = createCubeQueryDefinition( );
}
 
Example #11
Source File: CursorModelTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
@Before
   public void cursorModelSetUp() throws Exception
{
	this.scope = new ImporterTopLevel();
	DataEngineContext context = DataEngineContext.newInstance( DataEngineContext.DIRECT_PRESENTATION,
			scope,
			null,
			null );
	context.setTmpdir( this.getTempDir( ) );
	de = (DataEngineImpl) DataEngine.newDataEngine( context );
	creator = new CubeUtility();
	creator.createCube(de );
	cube = creator.getCube( CubeUtility.cubeName, de );

}
 
Example #12
Source File: MirrorCursorNavigatorTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
@Before
   public void mirrorCursorNavigatorSetUp() throws Exception
{
	this.scope = new ImporterTopLevel( );
	DataEngineContext context = DataEngineContext.newInstance( DataEngineContext.DIRECT_PRESENTATION,
			scope,
			null,
			null );
	context.setTmpdir( this.getTempDir( ) );
	de = (DataEngineImpl) DataEngine.newDataEngine( context );
	creator = new CubeUtility( );
	creator.createCube( de );
	cube = creator.getCube( CubeUtility.cubeName, de );
}
 
Example #13
Source File: CursorNavigatorTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
@Before
   public void cursorNavigatorSetUp() throws Exception
{
	this.scope = new ImporterTopLevel( );
	DataEngineContext context = DataEngineContext.newInstance( DataEngineContext.DIRECT_PRESENTATION,
			scope,
			null,
			null );
	context.setTmpdir( this.getTempDir( ) );
	de = (DataEngineImpl) DataEngine.newDataEngine( context );
	creator = new CubeUtility( );
	creator.createCube( de );
	cube = creator.getCube( CubeUtility.cubeName, de );
}
 
Example #14
Source File: DateTimeCursorTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
@Before
   public void dateTimeCursorSetUp() throws Exception
{
	this.scope = new ImporterTopLevel( );
	DataEngineContext context = DataEngineContext.newInstance( DataEngineContext.DIRECT_PRESENTATION,
			scope,
			null,
			null );
	context.setTmpdir( this.getTempDir( ) );
	de = (DataEngineImpl) DataEngine.newDataEngine( context );
	DateCube util = new DateCube( );
	util.createCube( de );
	cube = util.getCube( DateCube.cubeName, de );
}
 
Example #15
Source File: Runner.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public void run( )
{
	Context cx = Context.enter( );

	vm.attach( cx );

	Scriptable global = new ImporterTopLevel( );

	cx.evaluateString( global,
			"\r\nvar a = 2;\r\n  \r\nvar b = a*2;\r\n",
			"sec1",
			0,
			null );

	cx.evaluateString( global,
			"var a = 'ok';\r\nvar b = a;\r\n",
			"sec2",
			0,
			null );

	cx.evaluateString( global,
			"\r\n\r\nvar a = 2;\r\n\r\n\r\nvar b = a*2;\r\n",
			"sec1",
			0,
			null );

	vm.detach( cx );
}
 
Example #16
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 #17
Source File: CubeAggregationTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public CubeAggregationTest( )
{
	pathName = System.getProperty( "java.io.tmpdir" );
	this.baseScope = new ImporterTopLevel( );
}
 
Example #18
Source File: CubeAggregationTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * add this test for ted 65288, filter refered to mutilple dimensions
 * @throws IOException
 * @throws DataException
 * @throws BirtException
 */
@Test
   public void testCube1AggrFilter10(  ) throws IOException, DataException, BirtException
{
	//query
	CubeQueryExecutorHelper cubeQueryExcutorHelper = new CubeQueryExecutorHelper( 
			CubeQueryExecutorHelper.loadCube( "cube1", documentManager, new StopSign( ) ) );
	//add aggregation filter on level21
	IBinding level21_sum = new Binding( "level21_sum" );
	level21_sum.setAggrFunction( IBuildInAggregation.TOTAL_SUM_FUNC );
	level21_sum.setExpression( new ScriptExpression( "measure[\"measure1\"]" ) );
	level21_sum.addAggregateOn( "dimension[\"dimension2\"][\"level21\"]" );
	cubeQuery.addBinding( level21_sum );
	
	ScriptExpression expr = new ScriptExpression( "dimension[\"dimension2\"][\"level21\"]>1 && dimension[\"dimension3\"][\"level31\"]>1" );
	JSFacttableFilterEvalHelper filterHelper = new JSFacttableFilterEvalHelper( baseScope, cx,
			new FilterDefinition( expr ) , null, null );
	
	
	AggregationDefinition[] aggregations = new AggregationDefinition[1];
	int[] sortType = new int[1];
	sortType[0] = IDimensionSortDefn.SORT_ASC;
	DimLevel[] levelsForFilter = new DimLevel[]{dimLevel21};
	AggregationFunctionDefinition[] funcitons = new AggregationFunctionDefinition[1];

	funcitons[0] = new AggregationFunctionDefinition( "level21_sum", "measure1", null, null, IBuildInAggregation.TOTAL_SUM_FUNC, filterHelper );
	aggregations[0] = new AggregationDefinition( levelsForFilter, sortType, funcitons );
	
	cubeQueryExcutorHelper.setCubeQueryExecutor( new CubeQueryExecutor( null,
			cubeQuery,
			engine.getSession( ),
			new ImporterTopLevel( ),
			engine.getContext( ) ) );
	
	IAggregationResultSet[] resultSet = cubeQueryExcutorHelper.execute( aggregations,
			new StopSign( ) );
	
	for ( int i = 0; i < resultSet.length; i++ )
	{
		resultSet[i].close( );
	}
}
 
Example #19
Source File: JsScriptEngine.java    From spork with Apache License 2.0 4 votes vote down vote up
public JsScriptEngine() {
    Context context = getContext();
    scope = new ImporterTopLevel(context); // so that we can use importPackage()
    context.evaluateString(scope, printSource, "print", 1, null); // so that we can print on std out

}
 
Example #20
Source File: TransformEngineImpl.java    From p3-batchrefine with Apache License 2.0 4 votes vote down vote up
/**
     * This method runs part of the core module controller.js script so that we
     * can register all operations without having to duplicate configuration
     * here.
     */

    public void loadModule(String name, String path, String... initFunctions)
            throws IOException {

        ButterflyModule core = new ButterflyModuleStub(name);
//        File controllerFile = new File(Configurations.get("refine.root",
//                "../OpenRefine"), path);

        String script = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(path));

        if (script == null) {
            fLogger.warn(String.format(
                    "Can't find controller script for module %s at %s -- "
                            + "module may not work as expected.", name,
                    name));
            return;
        }

        // Compiles and "executes" the controller script. The script basically
        // contains function declarations.
        Context context = ContextFactory.getGlobal().enterContext();
        Script controller = context.compileString(
                script, "init.js", 1, null);

        // Initializes the scope.
        ScriptableObject scope = new ImporterTopLevel(context);

        scope.put("module", scope, core);
        controller.exec(context, scope);

        for (String function : initFunctions) {
            // Runs the function that initializes the OperationRegistry.
            try {
                Object fun = context.compileString(function, null, 1, null)
                        .exec(context, scope);
                if (fun != null && fun instanceof Function) {
                    ((Function) fun).call(context, scope, scope,
                            new Object[]{});
                }
            } catch (EcmaError ex) {
                fLogger.error("Error running controller script.", ex);
            }
        }
    }
 
Example #21
Source File: JavascriptEngine.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public JavascriptEngine( JavascriptEngineFactory factory,
		ScriptableObject root ) throws BirtException
{
	this.factory = factory;
	try
	{
		this.context = Context.enter( );
		this.global = new ImporterTopLevel( );
		this.root = root;
		if ( root != null )
		{
			// can not put this object to root, because this object will
			// cache package and classloader information.
			// so we need rewrite this property.
			new LazilyLoadedCtor( global, "Packages",
					"org.mozilla.javascript.NativeJavaTopPackage", false );
			global.exportAsJSClass( 3, global, false );
			global.delete( "constructor" );
			global.setPrototype( root );
		}
		else
		{
			global.initStandardObjects( context, true );
		}
		if ( global
				.get(
						org.eclipse.birt.core.script.functionservice.IScriptFunctionContext.FUNCTION_BEAN_NAME,
						global ) == org.mozilla.javascript.UniqueTag.NOT_FOUND )
		{
			IScriptFunctionContext functionContext = new IScriptFunctionContext( ) {

				public Object findProperty( String name )
				{
					return propertyMap.get( name );
				}
			};

			Object sObj = Context.javaToJS( functionContext, global );
			global
					.put(
							org.eclipse.birt.core.script.functionservice.IScriptFunctionContext.FUNCTION_BEAN_NAME,
							global, sObj );
		}
		initWrapFactory( );
	}
	catch ( Exception ex )
	{
		Context.exit( );
		throw new BirtException( );
	}
}
 
Example #22
Source File: RemoteRunner.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void run( )
{
	try
	{
		System.out.println( "start server" );

		server = new ReportVMServer( );

		Context cx = Context.enter( );

		server.start( 10000, cx );

		System.out.println( "server started" );

		Scriptable global = new ImporterTopLevel( );

		cx.evaluateString( global,
				"var a = 2;\r\nvar b = a*2;\r\n",
				"sec1",
				0,
				null );

		cx.evaluateString( global,
				"var a = 'ok';\r\nvar b = a;\r\n",
				"sec2",
				0,
				null );

		cx.evaluateString( global,
				"\r\nvar a = 2;\r\nvar b = a*2;\r\n",
				"sec1",
				0,
				null );

		server.shutdown( cx );
	}
	catch ( Exception e )
	{
		e.printStackTrace( );
	}
}