public SheetJSFile read_file(String filename) throws IOException, ObjectNotFoundException { /* open file */ String d = JSHelper.read_file(filename); /* options argument */ NativeObject q = (NativeObject)this.cx.evaluateString(this.scope, "q = {'type':'binary'};", "<cmd>", 2, null); /* set up function arguments */ Object functionArgs[] = {d, q}; /* call read -> wb workbook */ Function readfunc = (Function)JSHelper.get_object("XLSX.read",this.scope); NativeObject wb = (NativeObject)readfunc.call(this.cx, this.scope, this.nXLSX, functionArgs); return new SheetJSFile(wb, this); }
@Override public void put(String name, Scriptable start, Object value) { if (name.equals("__proxy__")) { NativeObject proxy = (NativeObject) value; Object getter = proxy.get("get", start); if (getter instanceof NativeFunction) { mGetter = (NativeFunction) getter; } Object setter = proxy.get("set", start); if (setter instanceof NativeFunction) { mSetter = (NativeFunction) setter; } } else if (mSetter != null) { mSetter.call(Context.getCurrentContext(), start, start, new Object[]{name, value}); } else { super.put(name, start, value); } }
public NativeObject getPreferences(String userName, String preferenceFilter) { // It's a tad unusual to return a NativeObject like this - at least within Alfresco. // But we can't change it to e.g. a ScriptableHashMap as the API is published. Map<String, Serializable> prefs = this.preferenceService.getPreferences(userName, preferenceFilter); NativeObject result = new NativeObjectDV(); for (Map.Entry<String, Serializable> entry : prefs.entrySet()) { String key = entry.getKey(); String[] keys; int colonIndex = key.indexOf(":"); if (colonIndex > -1) { keys = key.substring(0, colonIndex).replace(".", "+").split("\\+"); keys[keys.length - 1] = keys[keys.length - 1].concat(key.substring(colonIndex)); } else { keys = key.replace(".", "+").split("\\+"); } setPrefValue(keys, entry.getValue(), result); } return result; }
private void getPrefValues(NativeObject currentObject, String currentKey, Map<String, Serializable> values) { Object[] ids = currentObject.getIds(); for (Object id : ids) { String key = getAppendedKey(currentKey, id.toString()); Object value = currentObject.get(id.toString(), currentObject); if (value instanceof NativeObject) { getPrefValues((NativeObject)value, key, values); } else { values.put(key, (Serializable)value); } } }
/** * 执行JS * * @param js js代码 * @param functionName js方法名称 * @param functionParams js方法参数 * @return */ public static String runScript(Context context, String js, String functionName, Object[] functionParams) { org.mozilla.javascript.Context rhino = org.mozilla.javascript.Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); ScriptableObject.putProperty(scope, "javaContext", org.mozilla.javascript.Context.javaToJS(context, scope)); ScriptableObject.putProperty(scope, "javaLoader", org.mozilla.javascript.Context.javaToJS(context.getClass().getClassLoader(), scope)); rhino.evaluateString(scope, js, context.getClass().getSimpleName(), 1, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(rhino, scope, scope, 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 { org.mozilla.javascript.Context.exit(); } }
@Nullable private List<KeyEntry> getKeyEntries(Map.Entry<Object, Object> entry) { if (!(entry.getValue() instanceof NativeArray)) { return null; } NativeArray nativeArray = (NativeArray) entry.getValue(); if (nativeArray.isEmpty()) { return null; } List<KeyEntry> keyList = new ArrayList<>(); final int size = nativeArray.size(); for (int i = 0; i < size; i++) { NativeObject elem = (NativeObject) nativeArray.get(i); keyList.add(new KeyEntry( Context.toString(elem.get("text")), (int) Context.toNumber(elem.get("keyCode")), Context.toBoolean(elem.get("enabled")), Context.toBoolean(elem.get("isFunKey")) )); } return keyList; }
static public Map<String,Object> deserialize(NativeObject object) { HashMap<String,Object> map = new HashMap<>(); for (Object key : object.keySet()) { Object value = object.get(key); if (value == null) { map.put(key.toString(), null); } else if (value instanceof Number) { map.put(key.toString(), value); } else if (value instanceof Boolean) { map.put(key.toString(), value); } else if (value instanceof NativeObject) { map.put(key.toString(), deserialize((NativeObject)value)); } else if (value instanceof NativeArray) { NativeArray array = (NativeArray)value; Object[] a = new Object[(int)array.getLength()]; for (int i = 0; i < array.getLength(); ++i) { Object o = array.get(i); a[i] = deserialize(o); } map.put(key.toString(), a); } else { map.put(key.toString(), value.toString()); } } return map; }
static Object deserialize(Object value) { if (value == null) { return null; } else if (value instanceof Number) { return value; } else if (value instanceof Boolean) { return value; } else if (value instanceof NativeObject) { return deserialize((NativeObject)value); } else if (value instanceof NativeArray) { NativeArray array = (NativeArray)value; Object[] a = new Object[(int)array.getLength()]; for (int i = 0; i < array.getLength(); ++i) { Object o = array.get(i); a[i] = deserialize(o); } return a; } else { return value.toString(); } }
public String runScript(String js, String functionName, Object[] functionParams) { Context rhino = Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(mActivity.getContext(), scope)); ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(ChapterActivity.class.getClassLoader(), scope)); rhino.evaluateString(scope, js, "ChapterActivity", 1, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(rhino, scope, scope, 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(); } }
public SheetJS() throws Exception { this.cx = Context.enter(); this.scope = this.cx.initStandardObjects(); /* boilerplate */ cx.setOptimizationLevel(-1); String s = "var global = (function(){ return this; }).call(null);"; cx.evaluateString(scope, s, "<cmd>", 1, null); /* eval library */ s = new Scanner(SheetJS.class.getResourceAsStream("/dist/xlsx.full.min.js")).useDelimiter("\\Z").next(); //s = new Scanner(new File("xlsx.full.min.js")).useDelimiter("\\Z").next(); cx.evaluateString(scope, s, "<cmd>", 1, null); /* grab XLSX variable */ Object XLSX = scope.get("XLSX", scope); if(XLSX == Scriptable.NOT_FOUND) throw new Exception("XLSX not found"); this.nXLSX = (NativeObject)XLSX; }
public String runScript(String js, String functionName, Object[] functionParams) { Context rhino = Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(MainActivity.this, scope)); ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(MainActivity.class.getClassLoader(), scope)); rhino.evaluateString(scope, js, "MainActivity", 1, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(rhino, scope, scope, 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(); } finally { Context.exit(); } }
private List<MappingAssertionStatement> generateAssertionStatements(Object compiledJavascriptObject) { List<MappingAssertionStatement> assertionStatements = new ArrayList<MappingAssertionStatement>(); if (compiledJavascriptObject != null && compiledJavascriptObject instanceof NativeArray) { NativeArray array = (NativeArray) compiledJavascriptObject; for (Object object : array) { NativeObject nativeObject = (NativeObject) object; String actualValuePath = (String) nativeObject .get("actualValuePath"); Object actualValue = nativeObject.get("actualValue"); String operator = (String) nativeObject.get("operator"); Object expectedValue = nativeObject.get("expectedValue"); if (expectedValue instanceof NativeArray) { NativeArray expectedValueNativeArray = (NativeArray) expectedValue; expectedValue = expectedValueNativeArray.toArray(); } assertionStatements.add(new MappingAssertionStatement( actualValuePath, actualValue, operator, expectedValue)); } } return assertionStatements; }
public List<MappingAssertionStatement> getAssertionStatementMetadataList() { if (this.compiledJavascriptObject != null && this.compiledJavascriptObject instanceof NativeArray) { NativeArray array = (NativeArray) this.compiledJavascriptObject; for (Object object : array) { NativeObject nativeObject = (NativeObject) object; String actualValuePath = (String) nativeObject .get("actualValuePath"); Object actualValue = nativeObject.get("actualValue"); String operator = (String) nativeObject.get("operator"); Object expectedValue = nativeObject.get("expectedValue"); this.assertionStatementMetadataList.add(new MappingAssertionStatement( actualValuePath, actualValue, operator, expectedValue)); } } return this.assertionStatementMetadataList; }
private String runScript(String js, String functionName, Object[] functionParams) { Context rhino = Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); rhino.evaluateString(scope, js, "JavaScript", js.split("\n").length, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(rhino, scope, scope, 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(); } finally { Context.exit(); } }
public Object evaluate(EActivityDef activityDef, String formula) { Context context = Context.enter(); Scriptable adScope = getScriptableActivityDictionary(context); Scriptable scope = new NativeObject(); scope.setParentScope(adScope); ScriptableActivityDef scriptableActivityDef = new ScriptableActivityDef(activityDef); scriptableActivityDef.setParentScope(scope); try { return evaluateString(formula, context, scriptableActivityDef); } finally { Context.exit(); } }
@Initialize public void init() { _contextFactory = new ContextFactory(); final Context context = _contextFactory.enterContext(); try { _script = context.compileString(sourceCode, this.getClass().getSimpleName(), 1, null); _sharedScope = context.initStandardObjects(); JavaScriptUtils.addToScope(_sharedScope, new JavaScriptLogger(), "logger", "log"); JavaScriptUtils.addToScope(_sharedScope, System.out, "out"); _script.exec(context, _sharedScope); _transformerObj = (NativeObject) _sharedScope.get("transformerObj"); if (_transformerObj == null) { throw new IllegalStateException("Required JS object 'transformerObj' not found!"); } _initializeFunction = (Function) _transformerObj.get("initialize"); _transformFunction = (Function) _transformerObj.get("transform"); _closeFunction = (Function) _transformerObj.get("close"); _initializeFunction.call(context, _sharedScope, _sharedScope, new Object[0]); } finally { Context.exit(); } }
@Initialize public void init() { _contextFactory = new ContextFactory(); Context context = _contextFactory.enterContext(); try { _script = context.compileString(sourceCode, this.getClass().getSimpleName(), 1, null); _sharedScope = context.initStandardObjects(); JavaScriptUtils.addToScope(_sharedScope, logger, "logger", "log"); JavaScriptUtils.addToScope(_sharedScope, System.out, "out"); _script.exec(context, _sharedScope); _transformerObj = (NativeObject) _sharedScope.get("transformerObj"); if (_transformerObj == null) { throw new IllegalStateException("Required JS object 'transformerObj' not found!"); } _initializeFunction = (Function) _transformerObj.get("initialize"); _transformFunction = (Function) _transformerObj.get("transform"); _closeFunction = (Function) _transformerObj.get("close"); _initializeFunction.call(context, _sharedScope, _sharedScope, new Object[0]); } finally { Context.exit(); } }
/** * javascript helper for binding parameters. * See: {@link Pig#bind(Map)} * @param o a javascript object to be converted into a Map * @return the bound script * @throws IOException if {@link Pig#bind(Map)} throws an IOException */ public BoundScript bind(Object o) throws IOException { NativeObject vars = (NativeObject)o; Map<String, Object> params = new HashMap<String, Object>(); Object[] ids = vars.getIds(); for (Object id : ids) { if (id instanceof String) { String name = (String) id; Object value = vars.get(name, vars); if (!(value instanceof NativeFunction) && value != null) { params.put(name, value.toString()); } } } return pig.bind(params); }
@Override protected void configure() { Multibinder<Command> multiBinder = Multibinder.newSetBinder(binder(), Command.class); multiBinder.addBinding().to(ExitCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HelpCommand.class).asEagerSingleton(); multiBinder.addBinding().to(PrintCommand.class).asEagerSingleton(); multiBinder.addBinding().to(SaveCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HistoryCommand.class).asEagerSingleton(); multiBinder.addBinding().to(VersionCommand.class).asEagerSingleton(); multiBinder.addBinding().to(LoadCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HttpGetCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HttpHeadCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HttpPostCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HttpPutCommand.class).asEagerSingleton(); multiBinder.addBinding().to(HttpDeleteCommand.class).asEagerSingleton(); //Rhino specific commands multiBinder.addBinding().to(new TypeLiteral<ToJsonCommand<Object>>() {}).asEagerSingleton(); multiBinder.addBinding().to(new TypeLiteral<TransportClientCommand<RhinoClientNativeJavaObject>>(){}).asEagerSingleton(); multiBinder.addBinding().to(new TypeLiteral<NodeClientCommand<RhinoClientNativeJavaObject>>(){}).asEagerSingleton(); multiBinder.addBinding().to(new TypeLiteral<LocalNodeCommand<RhinoClientNativeJavaObject, NativeObject, Object>>(){}).asEagerSingleton(); bind(RhinoCommandRegistrar.class).asEagerSingleton(); }
@Override protected void configure() { bind(ScriptLoader.class).to(RhinoScriptLoader.class).asEagerSingleton(); bind(new TypeLiteral<JsonToString<NativeObject>>() {}).to(RhinoJsonToString.class).asEagerSingleton(); bind(new TypeLiteral<StringToJson<Object>>(){}).to(RhinoStringToJson.class).asEagerSingleton(); bind(Unwrapper.class).to(RhinoUnwrapper.class).asEagerSingleton(); bind(new TypeLiteral<ShellScope<RhinoShellTopLevel>>(){}).to(RhinoShellScope.class).asEagerSingleton(); bind(ScriptExecutor.class).to(RhinoScriptExecutor.class).asEagerSingleton(); bind(InputAnalyzer.class).to(RhinoInputAnalyzer.class).asEagerSingleton(); bind(Shell.class).to(RhinoShell.class).asEagerSingleton(); bind(new TypeLiteral<ClientScopeSynchronizerFactory<RhinoClientNativeJavaObject>>(){}) .to(RhinoClientScopeSynchronizerFactory.class).asEagerSingleton(); bind(new TypeLiteral<ClientWrapper<RhinoClientNativeJavaObject, NativeObject, Object>>(){}) .to(RhinoClientWrapper.class).asEagerSingleton(); bind(new TypeLiteral<ClientFactory<RhinoClientNativeJavaObject>>() {}) .to(new TypeLiteral<DefaultClientFactory<RhinoClientNativeJavaObject, NativeObject, Object>>() {}) .asEagerSingleton(); bind(new TypeLiteral<NodeFactory<RhinoClientNativeJavaObject, NativeObject, Object>>(){}) .to(new TypeLiteral<DefaultNodeFactory<RhinoClientNativeJavaObject, NativeObject, Object>>() {}) .asEagerSingleton(); }
/** * * {@inheritDoc} */ @Override public int getForJavaConversionConfidence(final Class<?> valueInstanceClass, final Class<?> expectedClass) { final int confidence; // in Rhino 1.7, NativeObject implements Map which makes things difficult if (Map.class.isAssignableFrom(valueInstanceClass) && !NativeObject.class.isAssignableFrom(valueInstanceClass) && (expectedClass.isAssignableFrom(Map.class) || expectedClass.equals(valueInstanceClass))) { confidence = LOW_CONFIDENCE; } else { confidence = LOWEST_CONFIDENCE; } return confidence; }
/** * {@inheritDoc} */ @Override public boolean canConvertValueForJava(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { // in Rhino 1.7, NativeObject implements Map which makes things difficult boolean canConvert = value instanceof Map<?, ?> && !(value instanceof NativeObject) && (expectedClass.isAssignableFrom(Map.class) || expectedClass.equals(value.getClass())); final Map<?, ?> map = (Map<?, ?>) value; for (final Object key : map.keySet()) { final Object valueForKey = map.get(key); canConvert = canConvert && globalDelegate.canConvertValueForJava(key) && globalDelegate.canConvertValueForJava(valueForKey); } return canConvert; }
public void setPreferences(String userName, NativeObject preferences) { Map<String, Serializable> values = new HashMap<String, Serializable>(10); getPrefValues(preferences, null, values); this.preferenceService.setPreferences(userName, values); }
public static String toString(Object ob) { String parameterToString; if (ob != null) { if (ob instanceof NativeObject) { NativeObject nativeObject = (NativeObject) ob; parameterToString = nativeToString(nativeObject); } else if (ob instanceof NativeJavaObject) { NativeJavaObject nativeJavaObject = (NativeJavaObject) ob; parameterToString = toString(nativeJavaObject.unwrap()); } else if (ob instanceof NativeJavaArray || ob instanceof NativeArray || ob.getClass().isArray() || ob instanceof Collection<?>) { parameterToString = toStringList(ob).toString(); } else if (ob instanceof NodeList) { parameterToString = ""; NodeList nl = (NodeList) ob; for (int i = 0; i < nl.getLength(); i++) { parameterToString += nodeToString(nl.item(i)); } } else if (ob instanceof Node) { parameterToString = nodeToString((Node)ob); } else { parameterToString = ob.toString(); } } else { parameterToString = null; } return parameterToString; }
@Test @SuppressWarnings({ "serial", "unchecked" }) public void shouldParseJsonObject() throws Exception { String json = "{" + "\"bool\" : false, " + "\"str\" : \"xyz\", " + "\"obj\" : {\"a\":1} " + "}"; NativeObject actual = (NativeObject) parser.parseValue(json); assertEquals(false, actual.get("bool", actual)); assertEquals("xyz", actual.get("str", actual)); NativeObject innerObj = (NativeObject) actual.get("obj", actual); assertEquals(1, innerObj.get("a", innerObj)); }
public void sendEvent(String name, NativeObject obj) { //get all matching listeners and send event for (int i = 0; i < eventsList.size(); i++) { if (name.equals(eventsList.get(i).name)) { eventsList.get(i).cb.event(obj); } } }
/** * Start an activity * * @param params * @throws JSONException * * @advanced * @status TODO */ @ProtoMethod public void startActivity(NativeObject params) throws JSONException { Intent intent = new Intent(); JSONObject jsonParams = new JSONObject(params); String action = (String) jsonParams.get("action"); intent.setAction(action); JSONObject extras = (JSONObject) jsonParams.get("extras"); Iterator<String> iterator = extras.keys(); while(iterator.hasNext()) { String key = iterator.next(); String value = (String) extras.get(key); MLog.d("qq", key + " " + value); intent.putExtra(key, value); } String data = (String) jsonParams.get("data"); intent.setData(Uri.parse(data)); String type = (String) jsonParams.get("type"); intent.setType(type); MLog.d("qq", action + " " + data + " " + type); JSONObject component = (JSONObject) jsonParams.get("component"); intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity")); // JSONArray flags = (JSONArray) jsonParams.get("flags"); // intent.setFlags(flags); getContext().startActivity(intent); // getActivity().startActivityForResult(); }
public void setAnObject(NativeObject obj) { for (Map.Entry<Object, Object> entry : obj.entrySet()) { String key = (String) entry.getKey(); Object o = entry.getValue(); MLog.d(TAG, "setAnObject -> " + key + " " + o); } MLog.d(TAG, "q --> " + obj.get("q")); }
@Nullable private KeyboardEntry update(Object[] params) { Object result = mUpdateFunction.call(mRhino, mEngineScope, mEngineScope, params); if (!(result instanceof NativeObject)) { return null; } return parseResult((NativeObject) result); }
private KeyboardEntry parseResult(NativeObject nativeObject) { List<List<KeyEntry>> keyboard = new ArrayList<>(5); int index = 0; String presetNumber = null; KeyboardType keyboardType = null; NumberType presetNumberType = NumberType.AUTO_DETECT; int numberLength = 0; int numberLimitLength = 0; NumberType detectedNumberType = NumberType.AUTO_DETECT; Set<Map.Entry<Object, Object>> entrySet = nativeObject.entrySet(); for (Map.Entry<Object, Object> entry : entrySet) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); if ("index".equals(key)) { index = (int) Context.toNumber(value); } else if ("presetNumber".equals(key)) { presetNumber = Context.toString(value); } else if ("keyboardType".equals(key)) { keyboardType = KeyboardType.values()[(int) Context.toNumber(value)]; } else if ("numberType".equals(key)) { presetNumberType = NumberType.values()[(int) Context.toNumber(value)]; } else if ("numberLength".equals(key)) { numberLength = (int) Context.toNumber(value); } else if ("numberLimitLength".equals(key)) { numberLimitLength = (int) Context.toNumber(value); } else if (key.startsWith("row")) { List<KeyEntry> keyList = getKeyEntries(entry); if (keyList == null) { continue; } keyboard.add(keyList); } else if ("detectedNumberType".equals(key)) { detectedNumberType = NumberType.values()[(int) Context.toNumber(value)]; } } return new KeyboardEntry(index, presetNumber, keyboardType, presetNumberType, numberLength, numberLimitLength, keyboard, detectedNumberType); }