Java Code Examples for org.mozilla.javascript.Context#javaToJS()
The following examples show how to use
org.mozilla.javascript.Context#javaToJS() .
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: BaseScript.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
protected void executeScript( final Map<String, Object> params ) { final Context cx = Context.getCurrentContext(); // env.js has methods that pass the 64k Java limit, so we can't compile // to bytecode. Interpreter mode to the rescue! cx.setOptimizationLevel( -1 ); cx.setLanguageVersion( Context.VERSION_1_7 ); final Object wrappedParams; if ( params != null ) { wrappedParams = Context.javaToJS( params, scope ); } else { wrappedParams = Context.javaToJS( new HashMap<String, Object>(), scope ); } try { ScriptableObject.defineProperty( scope, "params", wrappedParams, 0 ); cx.evaluateReader( scope, new FileReader( source ), this.source, 1, null ); } catch ( IOException ex ) { logger.error( "Failed to read " + source + ": " + ex.toString() ); } }
Example 2
Source File: JsRuntimeReplFactoryBuilder.java From stetho with MIT License | 6 votes |
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 3
Source File: JsRuntimeRepl.java From stetho with MIT License | 6 votes |
@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); }
Example 4
Source File: BaseScope.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
public static Object _loadSvg( final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj ) { final String file = args[ 0 ].toString(); try { final BaseScope scope = (BaseScope) thisObj; final String parser = "org.apache.xerces.parsers.SAXParser"; //XMLResourceDescriptor.getXMLParserClassName(); final SAXSVGDocumentFactory f = new SAXSVGDocumentFactory( parser ); final String uri = "file:" + scope.basePath + "/" + file; final SVGOMDocument doc = (SVGOMDocument) f.createDocument( uri ); // Initialize the CSS Engine for the document final SVGDOMImplementation impl = (SVGDOMImplementation) SVGDOMImplementation.getDOMImplementation(); final UserAgent userAgent = new UserAgentAdapter(); final BridgeContext ctx = new BridgeContext( userAgent, new DocumentLoader( userAgent ) ); doc.setCSSEngine( impl.createCSSEngine( doc, ctx ) ); return Context.javaToJS( doc, scope ); } catch ( Exception e ) { e.printStackTrace(); logger.error( e ); return Context.getUndefinedValue(); } }
Example 5
Source File: NativeFinanceTest.java From birt with Eclipse Public License 1.0 | 6 votes |
@Test public void testIrr( ) { //use double array to test this case double a[] = new double[]{-70000, 12000, 15000}; Object jsNumber=Context.javaToJS(a,scope); ScriptableObject.putProperty(scope,"array",jsNumber); String script4="Finance.irr( array, -0.6 )"; double value4 = eval( script4 ); assertEquals( -0.44, value4, 0.01 ); String script1 = "var array=new Array(6);array[0]=-70000;array[1]=12000;" + "array[2]=15000;array[3]=18000;array[4]=21000;array[5]=26000;" + "Finance.irr( array, 0.01)"; double value1 = eval( script1 ); assertEquals( 0.0866, value1, 0.0001 ); String script2 = "var array=new Array(5);array[0]=-70000;array[1]=12000;array[2]=15000;array[3]=18000;array[4]=21000;Finance.irr(array, -0.1 )"; double value2 = eval( script2 ); assertEquals( -0.021244848273899997, value2, Double.MIN_VALUE ); String script3 = "var array=new Array(3);array[0]=-70000;array[1]=12000;array[2]=15000;Finance.irr(array, -0.6 )"; double value3 = eval( script3 ); assertEquals( -0.44, value3, 0.01 ); assertFalse( hasException ); }
Example 6
Source File: AbstractScriptHandler.java From birt with Eclipse Public License 1.0 | 6 votes |
/** * Registers a new variable to current JavaScript context. If the name * already exists, it'll be overwritten. * * @param sVarName * @throws ChartException */ public final void registerVariable( String sVarName, Object var ) throws ChartException { Context.enter( ); try { final Object oConsole = Context.javaToJS( var, scope ); scope.put( sVarName, scope, oConsole ); } finally { Context.exit( ); } }
Example 7
Source File: JsFunction.java From spork with Apache License 2.0 | 5 votes |
/** * converts a tuple to javascript object based on a schema * @param tuple the tuple to convert * @param schema the schema to use for conversion * @param depth call depth used for debugging messages * @return the resulting javascript object */ @SuppressWarnings("unchecked") private Scriptable pigTupleToJS(Tuple tuple, Schema schema, int depth) throws FrontendException, ExecException { debugConvertPigToJS(depth, "Tuple", tuple, schema); Scriptable object = null; if (tuple != null) { object = jsScriptEngine.jsNewObject(); for (int i = 0; i < schema.size(); i++) { FieldSchema field = schema.getField(i); Object value; if (field.type == DataType.BAG) { value = pigBagToJS((DataBag)tuple.get(i), field.schema, depth + 1); } else if (field.type == DataType.TUPLE) { value = pigTupleToJS((Tuple)tuple.get(i), field.schema, depth + 1); } else if (field.type == DataType.MAP) { value = pigMapToJS((Map<String, Object>)tuple.get(i), field.schema, depth + 1); } else { debugConvertPigToJS(depth+1, "value", tuple.get(i), field.schema); value = Context.javaToJS(tuple.get(i), jsScriptEngine.getScope()); debugReturn(depth + 1, value); } object.put(field.alias, object, value); } } debugReturn(depth, object); return object; }
Example 8
Source File: BaseScript.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
public void initializeObjects() { final Context context = ContextFactory.getGlobal().enterContext(); try { final Object wrappedFactory = Context.javaToJS( new DatasourceFactory(), scope ); ScriptableObject.putProperty( scope, "datasourceFactory", wrappedFactory ); } finally { context.exit(); } }
Example 9
Source File: JavascriptContext.java From birt with Eclipse Public License 1.0 | 5 votes |
/** * @param name * the name of a property * @param value * the value of a property */ public void setAttribute( String name, Object value ) { value = wrap(scope, name, value); Object jsValue = Context.javaToJS( value, scope ); scope.put( name, scope, jsValue ); }
Example 10
Source File: TestConfigurationParser.java From celos with Apache License 2.0 | 5 votes |
Object evaluateTestConfig(Reader reader, String desc) throws IOException { Global scope = jsConfigParser.createGlobalScope(); Object wrappedContext = Context.javaToJS(this, scope); Map jsProperties = Maps.newHashMap(); jsProperties.put("testConfigurationParser", wrappedContext); jsConfigParser.putPropertiesInScope(jsProperties, scope); InputStream scripts = getClass().getResourceAsStream("celos-ci-scripts.js"); jsConfigParser.evaluateReader(scope, new InputStreamReader(scripts), "celos-ci-scripts.js"); return jsConfigParser.evaluateReader(scope, reader, desc); }
Example 11
Source File: AbstractScriptHandler.java From birt with Eclipse Public License 1.0 | 5 votes |
/** * 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 12
Source File: JSAcceptFacet.java From emissary with Apache License 2.0 | 5 votes |
/** * Make a scope in the current context with our required global variables in it * * @param ctx the current Rhino context * @return the new scope */ protected Scriptable makeAcceptFacetScope(final Context ctx) { final Scriptable scope = ctx.initStandardObjects(); final Object jsLogger = Context.javaToJS(this.scriptLogger, scope); ScriptableObject.putProperty(scope, "logger", jsLogger); final Object jsOut = Context.javaToJS(System.out, scope); ScriptableObject.putProperty(scope, "out", jsOut); return scope; }
Example 13
Source File: JSLintValidator.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
Object javaToJS(Object o, Scriptable scope) { Class<?> cls = o.getClass(); if (cls.isArray()) { return new NativeArray((Object[]) o); } return Context.javaToJS(o, scope); }
Example 14
Source File: RhinoExpression.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
protected LegacyDataRowWrapper initializeScope( final Scriptable scope ) { final LegacyDataRowWrapper dataRowWrapper = new LegacyDataRowWrapper(); dataRowWrapper.setParent( getRuntime().getDataRow() ); final Object wrappedDataRow = Context.javaToJS( dataRowWrapper, scope ); ScriptableObject.putProperty( scope, "dataRow", wrappedDataRow ); // NON-NLS return dataRowWrapper; }
Example 15
Source File: WorkflowConfigurationParser.java From celos with Apache License 2.0 | 4 votes |
Object evaluateReader(Reader r, String fileName, StateDatabaseConnection connection) throws Exception { Global scope = jsConfigParser.createGlobalScope(); Object wrappedThis = Context.javaToJS(this, scope); Map jsProperties = Maps.newHashMap(additionalJsVariables); jsProperties.put("celosWorkflowConfigurationParser", wrappedThis); jsProperties.put("celosConnection", connection); jsConfigParser.putPropertiesInScope(jsProperties, scope); InputStream scripts = WorkflowConfigurationParser.class.getResourceAsStream(CELOS_SCRIPTS_FILENAME); jsConfigParser.evaluateReader(scope, new InputStreamReader(scripts), CELOS_SCRIPTS_FILENAME); return jsConfigParser.evaluateReader(scope, r, fileName); }
Example 16
Source File: JsXMLHttpRequest.java From cxf with Apache License 2.0 | 4 votes |
private void throwError(String errorName) { LOG.info("Javascript throw: " + errorName); throw new JavaScriptException(Context.javaToJS(errorName, getParentScope()), "XMLHttpRequest", 0); }
Example 17
Source File: JavascriptContext.java From birt with Eclipse Public License 1.0 | 4 votes |
private Object javaToJs( Object value, Scriptable scope ) { return Context.javaToJS( value, scope ); }
Example 18
Source File: NativeDateTimeSpanTest.java From birt with Eclipse Public License 1.0 | 4 votes |
@Test public void testSubTime( ) { Calendar dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 1, 44 ); Date date1 = dateCal.getTime( ); Object jsNumber1 = Context.javaToJS( date1, scope ); ScriptableObject.putProperty( scope, "date1", jsNumber1 ); String script1 = "DateTimeSpan.subTime(date1,-1,-1,-1);"; Object value1 = eval( script1 ); Calendar cal = getCalendarInstance( ); cal.setTime( (Date) value1 ); assertEquals( 2008, cal.get( Calendar.YEAR ) ); assertEquals( 8, cal.get( Calendar.MONTH ) ); assertEquals( 13, cal.get( Calendar.DATE ) ); assertEquals( 21, cal.get( Calendar.HOUR_OF_DAY ) ); assertEquals( 2, cal.get( Calendar.MINUTE ) ); assertEquals( 45, cal.get( Calendar.SECOND ) ); System.out.println( "1" ); /* * More than 24 hours */ String script2 = "DateTimeSpan.subTime(date1,-25,-1,-1);"; Object value2 = eval( script2 ); cal = getCalendarInstance( ); cal.setTime( (Date) value2 ); assertEquals( 2008, cal.get( Calendar.YEAR ) ); assertEquals( 8, cal.get( Calendar.MONTH ) ); assertEquals( 14, cal.get( Calendar.DATE ) ); assertEquals( 21, cal.get( Calendar.HOUR_OF_DAY ) ); assertEquals( 2, cal.get( Calendar.MINUTE ) ); assertEquals( 45, cal.get( Calendar.SECOND ) ); System.out.println( "2" ); /* * Add negtive arguments. */ String script5 = "DateTimeSpan.subTime(date1,1,1,1);"; Object value5 = eval( script5 ); cal = getCalendarInstance( ); cal.setTime( (Date) value5 ); assertEquals( 2008, cal.get( Calendar.YEAR ) ); assertEquals( 8, cal.get( Calendar.MONTH ) ); assertEquals( 13, cal.get( Calendar.DATE ) ); assertEquals( 19, cal.get( Calendar.HOUR_OF_DAY ) ); assertEquals( 0, cal.get( Calendar.MINUTE ) ); assertEquals( 43, cal.get( Calendar.SECOND ) ); System.out.println( "5" ); String script6 = "DateTimeSpan.subTime(date1,1,1,61);"; Object value6 = eval( script6 ); cal = getCalendarInstance( ); cal.setTime( (Date) value6 ); assertEquals( 2008, cal.get( Calendar.YEAR ) ); assertEquals( 8, cal.get( Calendar.MONTH ) ); assertEquals( 13, cal.get( Calendar.DATE ) ); assertEquals( 18, cal.get( Calendar.HOUR_OF_DAY ) ); assertEquals( 59, cal.get( Calendar.MINUTE ) ); assertEquals( 43, cal.get( Calendar.SECOND ) ); System.out.println( "6" ); }
Example 19
Source File: JavascriptTestUtilities.java From cxf with Apache License 2.0 | 4 votes |
public Object javaToJS(Object value) { return Context.javaToJS(value, rhinoScope); }
Example 20
Source File: NativeDateTimeSpanTest.java From birt with Eclipse Public License 1.0 | 4 votes |
@Test public void testSeconds( ) { /* * Just one second. */ Calendar dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 1, 44 ); Date date1 = dateCal.getTime( ); Object jsNumber1 = Context.javaToJS( date1, scope ); ScriptableObject.putProperty( scope, "date1", jsNumber1 ); dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 1, 45 ); Date date2 = dateCal.getTime( ); Object jsNumber2 = Context.javaToJS( date2, scope ); ScriptableObject.putProperty( scope, "date2", jsNumber2 ); String script1 = "DateTimeSpan.seconds(date1,date2)"; Object value1 = eval( script1 ); if ( value1 instanceof Integer ) assertEquals( 1, ( (Integer) value1 ).intValue( ) ); /* * Just one second off one minute */ dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 1, 45 ); Date date3 = dateCal.getTime( ); Object jsNumber3 = Context.javaToJS( date3, scope ); ScriptableObject.putProperty( scope, "date3", jsNumber3 ); dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 2, 44 ); Date date4 = dateCal.getTime( ); Object jsNumber4 = Context.javaToJS( date4, scope ); ScriptableObject.putProperty( scope, "date4", jsNumber4 ); String script2 = "DateTimeSpan.seconds(date3,date4)"; Object value2 = eval( script2 ); if ( value2 instanceof Integer ) assertEquals( 59, ( (Integer) value2 ).intValue( ) ); /* * Just one second over one minute */ dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 1, 45 ); Date date5 = dateCal.getTime( ); Object jsNumber5 = Context.javaToJS( date5, scope ); ScriptableObject.putProperty( scope, "date5", jsNumber5 ); dateCal = getCalendarInstance( ); dateCal.set( 2008, 8, 13, 20, 2, 46 ); Date date6 = dateCal.getTime( ); Object jsNumber6 = Context.javaToJS( date6, scope ); ScriptableObject.putProperty( scope, "date6", jsNumber6 ); String script3 = "DateTimeSpan.seconds(date5,date6)"; Object value3 = eval( script3 ); if ( value3 instanceof Integer ) assertEquals( 61, ( (Integer) value3 ).intValue( ) ); /* * In leap year */ dateCal = getCalendarInstance( ); dateCal.set( 2008, 1, 28, 20, 1, 45 ); Date date7 = dateCal.getTime( ); Object jsNumber7 = Context.javaToJS( date7, scope ); ScriptableObject.putProperty( scope, "date7", jsNumber7 ); dateCal = getCalendarInstance( ); dateCal.set( 2008, 2, 1, 20, 1, 45 ); Date date8 = dateCal.getTime( ); Object jsNumber8 = Context.javaToJS( date8, scope ); ScriptableObject.putProperty( scope, "date8", jsNumber8 ); String script4 = "DateTimeSpan.seconds(date7,date8)"; Object value4 = eval( script4 ); if ( value4 instanceof Integer ) assertEquals( 172800, ( (Integer) value4 ).intValue( ) ); /* * In the same hour, and the first second is more than the second one. */ dateCal = getCalendarInstance( ); dateCal.set( 2008, 1, 28, 20, 6, 45 ); Date date9 = dateCal.getTime( ); Object jsNumber9 = Context.javaToJS( date9, scope ); ScriptableObject.putProperty( scope, "date9", jsNumber9 ); dateCal = getCalendarInstance( ); dateCal.set( 2008, 1, 28, 21, 5, 40 ); Date date10 = dateCal.getTime( ); Object jsNumber10 = Context.javaToJS( date10, scope ); ScriptableObject.putProperty( scope, "date10", jsNumber10 ); String script5 = "DateTimeSpan.seconds(date9,date10)"; Object value5 = eval( script5 ); if ( value5 instanceof Integer ) assertEquals( 3535, ( (Integer) value5 ).intValue( ) ); }