Java Code Examples for org.mozilla.javascript.Scriptable

The following examples show how to use org.mozilla.javascript.Scriptable. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: birt   Source File: PreparedDummyQuery.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public IExecutorHelper getExecutorHelper( ) throws DataException
{
	return new IExecutorHelper( ) {
		
		/*
		 * @see org.eclipse.birt.data.engine.impl.IExecutorHelper#getParent()
		 */
		public IExecutorHelper getParent( )
		{
			return null;
		}

		/*
		 * @see org.eclipse.birt.data.engine.impl.IExecutorHelper#getJSRowObject()
		 */
		public Scriptable getScriptable( )
		{
			return resultIterator.getJSDummyRowObject( );
		}
	};
}
 
Example 2
Source Project: birt   Source File: AggregateCalculator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void calculateArguments( int aggrIndex, Scriptable scope,ScriptContext cx,
		AggrExprInfo aggrInfo, boolean newGroup, IParameterDefn[] argDefs )
		throws DataException
{
	if ( aggrInfo.args == null || aggrInfo.args.length == 0 )
	{
		aggrArgs[aggrIndex] = null;
	}
	else
	{
		for ( int i = 0; i < argDefs.length; i++ )
		{
			// Note that static arguments only need to be calculated
			// once at the start of the iteration
			if ( !argDefs[i].isOptional( ) || newGroup )
			{
				aggrArgs[aggrIndex][i] = ExprEvaluateUtil.evaluateCompiledExpression( aggrInfo.args[i],
						odiResult,
						scope,
						cx);
			}
		}
	}
}
 
Example 3
Source Project: spork   Source File: JsFunction.java    License: Apache License 2.0 6 votes vote down vote up
private Object jsToPigMap(Scriptable object, Schema schema, int depth) {
    debugConvertJSToPig(depth, "Map", object, schema);
    Map<String, Object> map = new HashMap<String, Object>();
    Object[] ids = object.getIds();
    for (Object id : ids) {
        if (id instanceof String) {
            String name = (String) id;
            Object value = object.get(name, object);
            if (value instanceof NativeJavaObject) {
                value = ((NativeJavaObject)value).unwrap();
            } else if (value instanceof Undefined) {
                value = null;
            }
            map.put(name, value);
        }
    }
    debugReturn(depth, map);
    return map;
}
 
Example 4
Source Project: hop   Source File: ScriptValuesAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static int indexOf( Context actualContext, Scriptable actualObject, Object[] ArgList,
                           Function FunctionContext ) {

  int returnIndex = -1;

  if ( ArgList.length == 2 || ArgList.length == 3 ) {
    if ( !isNull( ArgList ) && !isUndefined( ArgList ) ) {
      String string = Context.toString( ArgList[ 0 ] );
      String subString = Context.toString( ArgList[ 1 ] );

      int fromIndex = 0;
      if ( ArgList.length == 3 ) {
        fromIndex = (int) Math.round( Context.toNumber( ArgList[ 2 ] ) );
      }
      returnIndex = string.indexOf( subString, fromIndex );
    }
  } else {
    throw Context.reportRuntimeError( "The function call indexOf requires 2 or 3 arguments" );
  }
  return returnIndex;
}
 
Example 5
Source Project: JsDroidCmd   Source File: NativeArrayBuffer.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                         Scriptable thisObj, Object[] args)
{
    if (!f.hasTag(CLASS_NAME)) {
        return super.execIdCall(f, cx, scope, thisObj, args);
    }
    int id = f.methodId();
    switch (id) {
    case ConstructorId_isView:
        return (isArg(args, 0) && (args[0] instanceof NativeArrayBufferView));

    case Id_constructor:
        int length = isArg(args, 0) ? ScriptRuntime.toInt32(args[0]) : 0;
        return new NativeArrayBuffer(length);

    case Id_slice:
        NativeArrayBuffer self = realThis(thisObj, f);
        int start = isArg(args, 0) ? ScriptRuntime.toInt32(args[0]) : 0;
        int end = isArg(args, 1) ? ScriptRuntime.toInt32(args[1]) : self.buffer.length;
        return self.slice(start, end);
    }
    throw new IllegalArgumentException(String.valueOf(id));
}
 
Example 6
Source Project: birt   Source File: JSFacttableFilterEvalHelper.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Object get( String levelName, Scriptable scope )
{
	try
	{
		if( this.levelAttrMap.containsKey( levelName ))
			return this.levelAttrMap.get( levelName );
		else
		{
			this.levelAttrMap.put( levelName,
					new DummyLevelAttrObject( host, dimName, levelName ) );
			return this.levelAttrMap.get( levelName );
		}
	}
	catch ( Exception e )
	{
		return null;
	}
}
 
Example 7
Source Project: birt   Source File: CubeQueryExecutor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 
 * @param outResults
 * @param defn
 * @param session
 * @param scope
 * @param context
 * @throws DataException 
 */
public CubeQueryExecutor( IBaseQueryResults outResults, ICubeQueryDefinition defn, DataEngineSession session, Scriptable scope,
		DataEngineContext context ) throws DataException
{
	this.defn = defn;
	this.scope = scope;
	this.context = context;
	this.session = session;
	DataEngineThreadLocal.getInstance( ).getPathManager( ).setTempPath( session.getTempDir( ) );
	this.outResults = outResults;
	this.dimensionFilterEvalHelpers = new ArrayList<IJSFilterHelper> ();
	this.dimensionSimpleFilter = new ArrayList<SimpleLevelFilter> ();
	this.aggrMeasureFilterEvalHelpers = new ArrayList<IAggrMeasureFilterEvalHelper>();
	this.aggrFilterEvalHelpersOnCubeOperator = new ArrayList<IAggrMeasureFilterEvalHelper>();
	this.advancedFacttableBasedFilterEvalHelper = new ArrayList<IJSFacttableFilterEvalHelper>();
	if ( !(context.getMode( ) == DataEngineContext.MODE_PRESENTATION
			&& defn.getQueryResultsID( ) != null) )
	{
		//query execution result will be loaded directly from document
		//needless to populate filer helpers
		populateFilterHelpers();
	}
}
 
Example 8
Source Project: carbon-apimgt   Source File: SAMLSSORelyingPartyObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check if the browser session is valid. If user is log out from any sso service provider,
 * user session is invalidated.
 *
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @return
 * @throws ScriptException
 */
public static boolean jsFunction_isSessionAuthenticated(Context cx, Scriptable thisObj,
                                                        Object[] args,
                                                        Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Session id is missing.");
    }
    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    if (relyingPartyObject.isSessionIdExists((String) args[0])) {
        if (log.isDebugEnabled()) {
            log.debug("Browser session is valid..");
        }
        return true;
    }
    return false;

}
 
Example 9
/**
 * 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;
}
 
Example 10
Source Project: astor   Source File: JsTestsBase.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void runJsTest(Context cx, Scriptable shared, String name, String source) {
    // create a lightweight top-level scope
    Scriptable scope = cx.newObject(shared);
    scope.setPrototype(shared);
    System.out.print(name + ": ");
    Object result;
    try {
        result = cx.evaluateString(scope, source, "jstest input", 1, null);
    } catch (RuntimeException e) {
        System.out.println("FAILED");
        throw e;
    }
    assertTrue(result != null);
    assertTrue("success".equals(result));
    System.out.println("passed");
}
 
Example 11
Source Project: hop   Source File: ScriptValuesAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static String rpad( Context actualContext, Scriptable actualObject, Object[] ArgList,
                           Function FunctionContext ) {
  try {
    if ( ArgList.length == 3 ) {
      if ( isNull( ArgList, new int[] { 0, 1, 2 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1, 2 } ) ) {
        return (String) Context.getUndefinedValue();
      }
      String valueToPad = Context.toString( ArgList[ 0 ] );
      String filler = Context.toString( ArgList[ 1 ] );
      int size = (int) Context.toNumber( ArgList[ 2 ] );

      while ( valueToPad.length() < size ) {
        valueToPad = valueToPad + filler;
      }
      return valueToPad;
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( "The function call rpad requires 3 arguments." );
  }
  return null;
}
 
Example 12
Source Project: cxf   Source File: DocLitBareClientTest.java    License: Apache License 2.0 6 votes vote down vote up
private Void compliantNoArgsCaller(Context context) {
    LOG.info("About to call compliantNoArgs " + getAddress());
    Notifier notifier =
        testUtilities.rhinoCallConvert("compliantNoArgsTest", Notifier.class,
                                       testUtilities.javaToJS(getAddress()));

    boolean notified = notifier.waitForJavascript(1000 * 10);
    assertTrue(notified);
    Integer errorStatus = testUtilities.rhinoEvaluateConvert("globalErrorStatus", Integer.class);
    assertNull(errorStatus);
    String errorText = testUtilities.rhinoEvaluateConvert("globalErrorStatusText", String.class);
    assertNull(errorText);

    //This method returns a String
    Scriptable response = (Scriptable)testUtilities.rhinoEvaluate("globalResponseObject");
    String item = testUtilities.rhinoCallMethodConvert(String.class, response, "getStringItem");
    assertEquals("horsefeathers", item);
    return null;
}
 
Example 13
Source Project: hop   Source File: ScriptValuesAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static Object fileExists( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                 Function FunctionContext ) {
  try {
    if ( ArgList.length == 1 && !isNull( ArgList[ 0 ] ) && !isUndefined( ArgList[ 0 ] ) ) {
      if ( ArgList[ 0 ].equals( null ) ) {
        return null;
      }
      File file = new File( Context.toString( ArgList[ 0 ] ) );
      return Boolean.valueOf( file.isFile() );
    } else {
      throw Context.reportRuntimeError( "The function call fileExists requires 1 valid argument." );
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( e.toString() );
  }
}
 
Example 14
Source Project: birt   Source File: QueryResults.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Object get( String name, Scriptable scope )
{
	if( ScriptConstants.OUTER_RESULT_KEYWORD.equalsIgnoreCase( name ) )
	{
		if( this.parentHelper == null )
		{
			throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.NO_OUTER_RESULTS_EXIST ) );
		}
		else
			return this.parentHelper.getScriptable( );
	}
	try
	{
		return this.currentIterator.getValue( name );
	}
	catch ( BirtException e )
	{
		return e;
	}
}
 
Example 15
Source Project: astor   Source File: StackTraceTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void runWithExpectedStackTrace(final String _source, final String _expectedStackTrace)
{
       final ContextAction action = new ContextAction() {
       	public Object run(Context cx) {
       		final Scriptable scope = cx.initStandardObjects();
       		try {
       			cx.evaluateString(scope, _source, "test.js", 0, null);
       		}
       		catch (final JavaScriptException e)
       		{
       			assertEquals(_expectedStackTrace, e.getScriptStackTrace());
       			return null;
       		}
       		throw new RuntimeException("Exception expected!");
       	}
       };
       Utils.runWithOptimizationLevel(action, -1);
}
 
Example 16
Source Project: hop   Source File: ScriptValuesAddedFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static String replace( Context actualContext, Scriptable actualObject, Object[] ArgList,
                              Function FunctionContext ) {
  try {
    if ( ArgList.length >= 2 && ( ArgList.length - 1 ) % 2 == 0 ) {
      if ( isNull( ArgList, new int[] { 0, 1 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1 } ) ) {
        return (String) Context.getUndefinedValue();
      }
      String objForReplace = Context.toString( ArgList[ 0 ] );
      for ( int i = 1; i < ArgList.length - 1; i = i + 2 ) {
        objForReplace =
          objForReplace.replaceAll( Context.toString( ArgList[ i ] ), Context.toString( ArgList[ i + 1 ] ) );
      }
      return objForReplace;
    } else {
      throw Context.reportRuntimeError( "The function call replace is not valid (wrong number of arguments)" );
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( "Function call replace is not valid : " + e.getMessage() );
  }
}
 
Example 17
Source Project: cxf   Source File: DocLitWrappedClientTest.java    License: Apache License 2.0 6 votes vote down vote up
public static Scriptable testBean1ToJS(JavascriptTestUtilities testUtilities,
                                       Context context,
                                       TestBean1 b1) {
    if (b1 == null) {
        return null; // black is always in fashion. (Really, we can be called with a null).
    }
    Scriptable rv = context.newObject(testUtilities.getRhinoScope(),
                                      "org_apache_cxf_javascript_testns_testBean1");
    testUtilities.rhinoCallMethod(rv, "setStringItem", testUtilities.javaToJS(b1.stringItem));
    testUtilities.rhinoCallMethod(rv, "setIntItem", testUtilities.javaToJS(b1.intItem));
    testUtilities.rhinoCallMethod(rv, "setLongItem", testUtilities.javaToJS(b1.longItem));
    testUtilities.rhinoCallMethod(rv, "setBase64Item", testUtilities.javaToJS(b1.base64Item));
    testUtilities.rhinoCallMethod(rv, "setOptionalIntItem", testUtilities.javaToJS(b1.optionalIntItem));
    testUtilities.rhinoCallMethod(rv, "setOptionalIntArrayItem",
                                  testUtilities.javaToJS(b1.optionalIntArrayItem));
    testUtilities.rhinoCallMethod(rv, "setDoubleItem", testUtilities.javaToJS(b1.doubleItem));
    testUtilities.rhinoCallMethod(rv, "setBeanTwoItem", testBean2ToJS(testUtilities,
                                                                      context, b1.beanTwoItem));
    testUtilities.rhinoCallMethod(rv, "setBeanTwoNotRequiredItem",
                                  testBean2ToJS(testUtilities, context, b1.beanTwoNotRequiredItem));
    return rv;
}
 
Example 18
/**
 * {@inheritDoc}
 */
@Override
public Collection<KeyValuePair> serialize(final DataModel model,
        final String name, final Object value) throws SemanticError {
    final Collection<KeyValuePair> pairs = new java.util.ArrayList<KeyValuePair>();
    if (value instanceof Scriptable) {
        final Scriptable scriptable = (Scriptable) value;
        serialize(scriptable, name, pairs);
    } else {
        final KeyValuePair pair;
        if (value == null) {
            pair = new KeyValuePair(name, "");
        } else {
            pair = new KeyValuePair(name, value.toString());
        }
        pairs.add(pair);
    }
    return pairs;
}
 
Example 19
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 20
Source Project: commons-bsf   Source File: JavaScriptEngine.java    License: 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 21
Source Project: stetho   Source File: JsRuntimeReplFactoryBuilder.java    License: MIT License 6 votes vote down vote up
private void importVariables(@NonNull ScriptableObject scope) throws StethoJsException {
  // Define the variables
  for (Map.Entry<String, Object> entrySet : mVariables.entrySet()) {
    String varName = entrySet.getKey();
    Object varValue = entrySet.getValue();
    try {
      Object jsValue;
      if (varValue instanceof Scriptable || varValue instanceof Undefined) {
        jsValue = varValue;
      } else {
        jsValue = Context.javaToJS(varValue, scope);
      }
      ScriptableObject.putProperty(scope, varName, jsValue);
    } catch (Exception e) {
      throw new StethoJsException(e, "Failed to setup variable: %s", varName);
    }
  }
}
 
Example 22
Source Project: birt   Source File: ReportDesign.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Object call( Context cx, Scriptable scope, Scriptable thisObj,
		java.lang.Object[] args )
{
	Object[] convertedArgs = JavascriptEvalUtil
			.convertToJavaObjects( args );

	try
	{
		if ( convertedArgs.length == 2 )
			report.setUserProperty( (String) convertedArgs[0],
					(String) convertedArgs[1] );
		else if ( convertedArgs.length == 3 )
			report.setUserProperty( (String) convertedArgs[0],
					convertedArgs[1], (String) convertedArgs[2] );

	}
	catch ( SemanticException e )
	{
		throw new WrappedException( e );
	}

	return null;
}
 
Example 23
Source Project: birt   Source File: JSFacttableFilterEvalHelper.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Object get( String dimName, Scriptable scope )
{
	try
	{
		if( this.dimLevMap.containsKey( dimName ))
			return this.dimLevMap.get( dimName );
		else
		{
			this.dimLevMap.put( dimName, new DummyLevelObject(this, dimName) );
			return this.dimLevMap.get( dimName );
		}
	}
	catch ( Exception e )
	{
		return null;
	}
}
 
Example 24
Source Project: astor   Source File: Bug421071Test.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() {
    Context context = factory.enterContext();
    try {
        // Run each script in its own scope, to keep global variables
        // defined in each script separate
        Scriptable threadScope = context.newObject(globalScope);
        threadScope.setPrototype(globalScope);
        threadScope.setParentScope(null);
        script.exec(context, threadScope);
    } catch (Exception ee) {
        ee.printStackTrace();
    } finally {
        Context.exit();
    }
}
 
Example 25
Source Project: birt   Source File: ScriptableParameter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public Object get( String name, Scriptable scope )
{
	ParameterAttribute parameter = getParameterAttribute( name );
	if ( FIELD_VALUE.equals( name ) )
	{
		return parameter.getValue( );
	}
	else if ( FIELD_DISPLAY_TEXT.equals( name ) )
	{
		return parameter.getDisplayText( );
	}
	Object value = parameter.getValue( );
	Scriptable jsValue = Context.toObject( value, scope );
	Scriptable prototype = jsValue.getPrototype( );
	if( prototype != null )
	{
		Object property = jsValue.getPrototype( ).get( name, jsValue );
		if ( property instanceof Callable )
		{
			Callable callable = (Callable) property;
			return new JsValueCallable( callable, jsValue );
		}
		return jsValue.get( name, jsValue );
	}
	else
	{
		return jsValue.get( name, jsValue );
	}
}
 
Example 26
Source Project: JsDroidCmd   Source File: JsGlobal.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
		Object[] args) {
	String obj = Context.toString(args[0]);
	if (getJsAppInterface() != null) {
		getJsAppInterface().input(obj);
	}
	return Input.input(obj);
}
 
Example 27
Source Project: birt   Source File: DataAdapterUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
JSResultIteratorObject( ILinkedResult it, Scriptable scope )
{
	this.it = it;
	this.scope = scope;
	if ( it.getCurrentResultType( ) == ILinkedResult.TYPE_TABLE )
		this.currentIterator = (IResultIterator) it.getCurrentResult( );
}
 
Example 28
Source Project: birt   Source File: DimensionJSObjectPopulator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param scope
 * @param dimensionName
 * @param levelNames
 */
public DimensionJSObjectPopulator( Scriptable scope, String dimensionName,
		List levelNames )
{
	this.scope = scope;
	this.dimensionName = dimensionName;
	this.levelNames = levelNames;
}
 
Example 29
Source Project: hop   Source File: ScriptValuesAddedFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static String getDigitsOnly( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                    Function FunctionContext ) {
  if ( ArgList.length == 1 ) {
    return Const.getDigitsOnly( Context.toString( ArgList[ 0 ] ) );
  } else {
    throw Context.reportRuntimeError( "The function call getDigitsOnly requires 1 argument." );

  }
}
 
Example 30
Source Project: pentaho-kettle   Source File: ScriptValuesAddedFunctions.java    License: 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 ) {
    // System.out.println(e.toString());
  }
}