Java Code Examples for org.mozilla.javascript.Scriptable#get()
The following examples show how to use
org.mozilla.javascript.Scriptable#get() .
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: ScriptValuesAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 6 votes |
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 2
Source File: JsFunction.java From spork with Apache License 2.0 | 6 votes |
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 3
Source File: ScriptValuesAddedFunctions.java From hop with Apache License 2.0 | 6 votes |
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 4
Source File: RhinoWorkerUtils.java From pushfish-android with BSD 2-Clause "Simplified" License | 6 votes |
public static Map<String, Object> toMap(Scriptable obj) { Map<String, Object> map = new LinkedHashMap<String, Object>(); for (Object id : obj.getIds()) { String key; Object value; if (id instanceof String) { key = (String) id; value = obj.get(key, obj); } else if (id instanceof Integer) { key = id.toString(); value = obj.get((Integer) id, obj); } else { throw new IllegalArgumentException(String.format("Unexpected key type: %s (value: %s)", id.getClass().getName(), id)); } map.put(key, toJavaValue(value)); } return map; }
Example 5
Source File: JSEngine.java From NewFastFrame with Apache License 2.0 | 6 votes |
/** * 执行JS */ public String runScript(String functionParams, String methodName) { Context rhino = Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(this, scope)); ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(JSEngine.class.getClassLoader(), scope)); rhino.evaluateString(scope, sb.toString(), JSEngine.class.getName(), 1, null); Function function = (Function) scope.get(methodName, scope); Object result = function.call(rhino, scope, scope, new Object[]{functionParams}); if (result instanceof String) { return (String) result; } else if (result instanceof NativeJavaObject) { return (String) ((NativeJavaObject) result).getDefaultValue(String.class); } else if (result instanceof NativeObject) { return (String) ((NativeObject) result).getDefaultValue(String.class); } return result.toString();//(String) function.call(rhino, scope, scope, functionParams); } finally { Context.exit(); } }
Example 6
Source File: CipherManager.java From YTPlayer with GNU General Public License v3.0 | 6 votes |
private static String RhinoEngine(String s) { Context rhino = Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); rhino.evaluateString(scope, cachedDechiperFunction, "JavaScript", 1, null); Object obj = scope.get("decipher", scope); if (obj instanceof Function) { Function jsFunction = (Function) obj; Object jsResult = jsFunction.call(rhino, scope, scope, new Object[]{s}); String result = Context.toString(jsResult); return result ; } } finally { Context.exit(); } return s; }
Example 7
Source File: RhinoWorkerUtils.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 6 votes |
public static Map<String, Object> toMap(Scriptable obj) { Map<String, Object> map = new LinkedHashMap<String, Object>(); for (Object id : obj.getIds()) { String key; Object value; if (id instanceof String) { key = (String) id; value = obj.get(key, obj); } else if (id instanceof Integer) { key = id.toString(); value = obj.get((Integer) id, obj); } else { throw new IllegalArgumentException(String.format("Unexpected key type: %s (value: %s)", id.getClass().getName(), id)); } map.put(key, toJavaValue(value)); } return map; }
Example 8
Source File: ScriptableParameter.java From birt with Eclipse Public License 1.0 | 5 votes |
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 9
Source File: Context.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
public void dumpScope(final Scriptable scope, String pad) { java.lang.Object[] ids = scope.getIds(); for (Object id : ids) { Object o = null; if (id instanceof String) { o = scope.get((String) id, scope); LOGGER.debug(pad + id + "=" + o + " (" + o.getClass().getCanonicalName() + ")"); } else { o = scope.get((int) id, scope); LOGGER.debug(pad + id + "=" + o + " (" + o.getClass().getCanonicalName() + ")"); } if (o instanceof Scriptable) dumpScope((Scriptable) o, pad + " "); else if (o instanceof NativeObject) { for (Map.Entry<Object, Object> item : ((NativeObject) o) .entrySet()) { LOGGER.debug(pad + " " + item.getKey() + "=" + item.getValue() + " (" + item.getValue().getClass().getCanonicalName() + ")"); } } } }
Example 10
Source File: ScriptValuesAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 5 votes |
public static double getProcessCount( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { if ( ArgList.length == 1 ) { try { Object scmO = actualObject.get( "_step_", actualObject ); StepInterface scm = (StepInterface) Context.jsToJava( scmO, StepInterface.class ); String strType = Context.toString( ArgList[0] ).toLowerCase(); if ( strType.equals( "i" ) ) { return scm.getLinesInput(); } else if ( strType.equals( "o" ) ) { return scm.getLinesOutput(); } else if ( strType.equals( "r" ) ) { return scm.getLinesRead(); } else if ( strType.equals( "u" ) ) { return scm.getLinesUpdated(); } else if ( strType.equals( "w" ) ) { return scm.getLinesWritten(); } else if ( strType.equals( "e" ) ) { return scm.getLinesRejected(); } else { return 0; } } catch ( Exception e ) { // throw Context.reportRuntimeError(e.toString()); return 0; } } else { throw Context.reportRuntimeError( "The function call getProcessCount requires 1 argument." ); } }
Example 11
Source File: JsonExtensionNotificationDataConverterTest.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
@Test public void testConvertApplicationLastResultComplexSemanticInterpretation() throws Exception { final JsonExtensionNotificationDataConverter converter = new JsonExtensionNotificationDataConverter(); final List<LastResult> list = new java.util.ArrayList<LastResult>(); final Context context = Context.enter(); context.setLanguageVersion(Context.VERSION_1_6); final Scriptable scope = context.initStandardObjects(); context.evaluateString(scope, "var out = new Object();", "expr", 1, null); context.evaluateString(scope, "var out = new Object();", "expr", 1, null); context.evaluateString(scope, "out.order = new Object();", "expr", 1, null); context.evaluateString(scope, "out.order.topping = 'Salami';", "expr", 1, null); context.evaluateString(scope, "out.order.size = 'medium';", "expr", 1, null); context.evaluateString(scope, "out.date = 'now';", "expr", 1, null); final Object out = scope.get("out", scope); final LastResult result = new LastResult("yes", .75f, "voice", out); list.add(result); final String json = (String) converter .convertApplicationLastResult(list); Assert.assertEquals("vxml.input = {\"utterance\":\"yes\"," + "\"confidence\":0.75,\"interpretation\":{\"order\":" + "{\"topping\":\"Salami\",\"size\":\"medium\"}," + "\"date\":\"now\"},\"mode\":\"voice\"}", json); }
Example 12
Source File: JsFunction.java From spork with Apache License 2.0 | 5 votes |
@Override public Object exec(Tuple tuple) throws IOException { Schema inputSchema = this.getInputSchema(); if (LOG.isDebugEnabled()) { LOG.debug( "CALL " + stringify(outputSchema) + " " + functionName + " " + stringify(inputSchema)); } // UDF always take a tuple: unwrapping when not necessary to simplify UDFs if (inputSchema.size() == 1 && inputSchema.getField(0).type == DataType.TUPLE) { inputSchema = inputSchema.getField(0).schema; } Scriptable params = pigTupleToJS(tuple, inputSchema, 0); Object[] passedParams = new Object[inputSchema.size()]; for (int j = 0; j < passedParams.length; j++) { passedParams[j] = params.get(inputSchema.getField(j).alias, params); } Object result = jsScriptEngine.jsCall(functionName, passedParams); if (LOG.isDebugEnabled()) { LOG.debug( "call "+functionName+"("+Arrays.toString(passedParams)+") => "+toString(result)); } // We wrap the result with an object in the following cases: // 1. Result is not an object type. // 2. OutputSchema is a tuple type. if (!(result instanceof NativeObject) || outputSchema.getField(0).type == DataType.TUPLE) { Scriptable wrapper = jsScriptEngine.jsNewObject(); wrapper.put(outputSchema.getField(0).alias, wrapper, result); result = wrapper; } Tuple evalTuple = jsToPigTuple((Scriptable)result, outputSchema, 0); Object eval = outputSchema.size() == 1 ? evalTuple.get(0) : evalTuple; LOG.debug(eval); return eval; }
Example 13
Source File: JsFunction.java From spork with Apache License 2.0 | 5 votes |
private Tuple jsToPigTuple(Scriptable object, Schema schema, int depth) throws FrontendException, ExecException { debugConvertJSToPig(depth, "Tuple", object, schema); Tuple t = TupleFactory.getInstance().newTuple(schema.size()); for (int i = 0; i < schema.size(); i++) { FieldSchema field = schema.getField(i); if (object.has(field.alias, jsScriptEngine.getScope())) { Object attr = object.get(field.alias, object); Object value; if (field.type == DataType.BAG) { value = jsToPigBag((Scriptable)attr, field.schema, depth + 1); } else if (field.type == DataType.TUPLE) { value = jsToPigTuple((Scriptable)attr, field.schema, depth + 1); } else if (field.type == DataType.MAP) { value = jsToPigMap((Scriptable)attr, field.schema, depth + 1); } else if (attr instanceof NativeJavaObject) { value = ((NativeJavaObject)attr).unwrap(); } else if (attr instanceof Undefined) { value = null; } else { value = attr; } t.set(i, value); } else { if (LOG.isDebugEnabled()) { LOG.debug("X( "+field.alias+" NOT FOUND"); } } } debugReturn(depth, t); return t; }
Example 14
Source File: KeyValueSerializer.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
/** * Serializes the given object by appending the known values to the current * object prefix into pairs. * * @param object * the object to serialize * @param prefix * the current object prefix. * @param pairs * currently serialized values */ private void serialize(final Scriptable object, final String prefix, final Collection<KeyValuePair> pairs) { final Object[] ids = ScriptableObject.getPropertyIds(object); for (Object id : ids) { final String key = id.toString(); final Object value = object.get(key, object); if (value instanceof ScriptableObject) { final ScriptableObject scriptable = (ScriptableObject) value; final String subprefix; if (prefix.isEmpty()) { subprefix = key; } else { subprefix = prefix + "." + key; } serialize(scriptable, subprefix, pairs); } else if (value != null) { final StringBuilder str = new StringBuilder(); str.append(prefix); str.append("."); str.append(key); final KeyValuePair pair = new KeyValuePair(str.toString(), value.toString()); pairs.add(pair); } } }
Example 15
Source File: ScriptValuesAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 5 votes |
public static String getEnvironmentVar( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { String sRC = ""; if ( ArgList.length == 1 ) { try { String sArg1 = Context.toString( ArgList[0] ); // PDI-1276 Function getEnvironmentVar() does not work for user defined variables. // check if the system property exists, and if it does not, try getting a Kettle var instead if ( System.getProperties().containsValue( sArg1 ) ) { sRC = System.getProperty( sArg1, "" ); } else { 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] ); sRC = scm.getVariable( sArg1, "" ); } else { // running in test mode, return "" sRC = ""; } } } catch ( Exception e ) { sRC = ""; } } else { throw Context.reportRuntimeError( "The function call getEnvironmentVar requires 1 argument." ); } return sRC; }
Example 16
Source File: Utils.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
public static void dumpScope(final Scriptable scope, String pad) { java.lang.Object[] ids = scope.getIds(); for (Object id : ids) { Object o = null; if (id instanceof String) { o = scope.get((String) id, scope); Logger.getRootLogger().debug( pad + id + "=" + o + " (" + o.getClass().getCanonicalName() + ")"); } else { o = scope.get((int) id, scope); Logger.getRootLogger().debug( pad + id + "=" + o + " (" + o.getClass().getCanonicalName() + ")"); } if (o instanceof Scriptable) dumpScope((Scriptable) o, pad + " "); else if (o instanceof NativeObject) { for (Map.Entry<Object, Object> item : ((NativeObject) o) .entrySet()) { Logger.getRootLogger().debug( pad + " " + item.getKey() + "=" + item.getValue() + " (" + item.getValue().getClass() .getCanonicalName() + ")"); } } } }
Example 17
Source File: ScriptValuesAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 5 votes |
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; }
Example 18
Source File: ScriptValuesAddedFunctions.java From hop with Apache License 2.0 | 5 votes |
public static double getProcessCount( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { if ( ArgList.length == 1 ) { try { Object scmO = actualObject.get( "_transform_", actualObject ); ITransform scm = (ITransform) Context.jsToJava( scmO, ITransform.class ); String strType = Context.toString( ArgList[ 0 ] ).toLowerCase(); if ( strType.equals( "i" ) ) { return scm.getLinesInput(); } else if ( strType.equals( "o" ) ) { return scm.getLinesOutput(); } else if ( strType.equals( "r" ) ) { return scm.getLinesRead(); } else if ( strType.equals( "u" ) ) { return scm.getLinesUpdated(); } else if ( strType.equals( "w" ) ) { return scm.getLinesWritten(); } else if ( strType.equals( "e" ) ) { return scm.getLinesRejected(); } else { return 0; } } catch ( Exception e ) { // throw Context.reportRuntimeError(e.toString()); return 0; } } else { throw Context.reportRuntimeError( "The function call getProcessCount requires 1 argument." ); } }
Example 19
Source File: ScriptValuesAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 4 votes |
@SuppressWarnings( "unused" ) public static Object fireToDB( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { Object oRC = new Object(); if ( ArgList.length == 2 ) { try { Object scmO = actualObject.get( "_step_", actualObject ); ScriptValuesMod scm = (ScriptValuesMod) Context.jsToJava( scmO, ScriptValuesMod.class ); String strDBName = Context.toString( ArgList[0] ); String strSQL = Context.toString( ArgList[1] ); DatabaseMeta ci = DatabaseMeta.findDatabase( scm.getTransMeta().getDatabases(), strDBName ); if ( ci == null ) { throw Context.reportRuntimeError( "Database connection not found: " + strDBName ); } ci.shareVariablesWith( scm ); Database db = new Database( scm, ci ); db.setQueryLimit( 0 ); try { if ( scm.getTransMeta().isUsingUniqueConnections() ) { synchronized ( scm.getTrans() ) { db.connect( scm.getTrans().getTransactionId(), scm.getPartitionID() ); } } else { db.connect( scm.getPartitionID() ); } ResultSet rs = db.openQuery( strSQL ); ResultSetMetaData resultSetMetaData = rs.getMetaData(); int columnCount = resultSetMetaData.getColumnCount(); if ( rs != null ) { List<Object[]> list = new ArrayList<Object[]>(); while ( rs.next() ) { Object[] objRow = new Object[columnCount]; for ( int i = 0; i < columnCount; i++ ) { objRow[i] = rs.getObject( i + 1 ); } list.add( objRow ); } Object[][] resultArr = new Object[list.size()][]; list.toArray( resultArr ); db.disconnect(); return resultArr; } } catch ( Exception er ) { throw Context.reportRuntimeError( er.toString() ); } } catch ( Exception e ) { throw Context.reportRuntimeError( e.toString() ); } } else { throw Context.reportRuntimeError( "The function call fireToDB requires 2 arguments." ); } return oRC; }
Example 20
Source File: Context.java From JVoiceXML with GNU Lesser General Public License v2.1 | 4 votes |
/** * Updates the parent scope: * <ul> * <li>rules.rulename</li> * <li>rules.latest()</li> * <li>meta.rulename</li> * <li>meta.current()</li> * </ul> * * @param context * @param parentScope * @param ruleScope * @param out */ private void updateParentScope(org.mozilla.javascript.Context context, Scriptable parentScope, Scriptable ruleScope, Object out) { // Setup rules Scriptable ruleObject = (Scriptable) parentScope.get("rules", parentScope); ruleObject.put(ruleName, ruleObject, out); // sets rules.rulename context.evaluateString(parentScope, getRulesLastestScript(ruleName), "Context:rules.Latest", 0, null); // sets rules.latest() // Setup meta // meta.rulename will be set based on the match in the current context // meta.current() will be set based on the current value if the parent // context plus the value coming out of the rule context String ruleMetaCurrent = (String) context.evaluateString(ruleScope, "meta.current().text;", "Context:rule get meta", 0, null); // LOGGER.debug("ruleMetaCurrent="+ruleMetaCurrent); // LOGGER.debug("about to execute: "+"meta."+ruleName+"=function() {return {text:'"+ruleMetaCurrent+"', score:1.0}};"); context.evaluateString(parentScope, "meta." + ruleName + "=function() {return {text:'" + ruleMetaCurrent + "', score:1.0};};", "Context:rule set meta." + ruleName, 0, null); if (ruleMetaCurrent.length() > 0) { String parentMetaCurrent = (String) context.evaluateString( parentScope, "meta.current().text;", "Context:parent get meta", 0, null); if (parentMetaCurrent.length() == 0) { context.evaluateString(parentScope, "meta.current=function() {return {text:'" + ruleMetaCurrent + "', score:1.0};};", "AddToMatchedText:set meta1", 0, null); } else { context.evaluateString(parentScope, "meta.current=function() {return {text:'" + parentMetaCurrent + " " + ruleMetaCurrent + "', score:1.0};};", "AddToMatchedText:set meta1", 0, null); } } }