public String evaluate(String url, String host) { Object result = ""; try { Context ctx = Context.enter(); result = ctx.evaluateString(scope, "FindProxyForURL (\"" + url + "\",\"" + host + "\")", "check", 0, null); } catch (Exception e) { Engine.logProxyManager.error("(PacManager) Failed to evaluate .pac for " + url + " from " + host, e); } finally { Context.exit(); } if (result instanceof NativeJavaObject) { result = ((NativeJavaObject) result).unwrap(); } Engine.logProxyManager.debug("(PacManager) evaluate " + url + " from " + host + " : " + result); return result.toString(); }
@Override protected boolean stepExecute(Context javascriptContext, Scriptable scope) throws EngineException { variables.clear(); if (isEnabled()) { for (RequestableVariable var : getParentSequence().getAllVariables()) { try { //evaluate(javascriptContext, scope, var.getName(), "expression", true); evaluated = scope.get(var.getName(), scope); if (evaluated != null && !(evaluated instanceof Undefined)) { if (evaluated instanceof NativeJavaObject) { evaluated = ((NativeJavaObject) evaluated).unwrap(); } variables.put(var.getName(), evaluated); } } catch (Exception e) { evaluated = null; Engine.logBeans.warn(e.getMessage()); } } return super.stepExecute(javascriptContext, scope); } return false; }
/** * 执行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(); } }
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 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 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 static Scriptable jsFunction_join(final Context ctx, final Scriptable object, final Object[] args, final Function func) { final DataFrame<Object> other = DataFrameAdapter.class.cast(args[0]).df; final JoinType type = args.length > 1 && args[1] instanceof NativeJavaObject ? JoinType.class.cast(Context.jsToJava(args[1], JoinType.class)) : null; if (args.length > 1 && args[args.length - 1] instanceof Function) { @SuppressWarnings("unchecked") final KeyFunction<Object> f = (KeyFunction<Object>)Context.jsToJava(args[args.length - 1], KeyFunction.class); if (type != null) { return new DataFrameAdapter(object, cast(object).df.join(other, type, f)); } return new DataFrameAdapter(object, cast(object).df.join(other, f)); } if (type != null) { return new DataFrameAdapter(object, cast(object).df.join(other, type)); } return new DataFrameAdapter(object, cast(object).df.join(other)); }
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; }
private boolean isSupportedType( Object obValue ) { if ( obValue instanceof Scriptable ) { if ( obValue instanceof IdScriptableObject ) { IdScriptableObject jsObject = ( (IdScriptableObject) obValue ); if ( jsObject.getClassName( ).equals( "Date" ) ) { return true; } return false; } else if ( obValue instanceof NativeJavaObject ) { return true; } return false; } return IOUtil.getTypeIndex( obValue ) != -1; }
public String getTypeName( ) { if ( reservedValueType != null ) { return reservedValueType; } Object valObj = value; if ( value instanceof NativeJavaObject ) { valObj = ( (NativeJavaObject) value ).unwrap( ); } if ( valObj != null ) { return convertArrayTypeName( valObj.getClass( ), isPrimitive ); } return "null"; //$NON-NLS-1$ }
@Test public void testFixDir() throws Exception { String js = "" + "ci.fixDir({" + " file1: ci.fixFile('123')," + " file2: ci.fixFile('234')" + "})"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); FixDirHierarchyCreator creator = (FixDirHierarchyCreator) creatorObj.unwrap(); FixDir fixDir = creator.create(null); Assert.assertEquals(fixDir.getChildren().size(), 2); Assert.assertTrue(IOUtils.contentEquals(fixDir.getChildren().get("file1").asFile().getContent(), new ByteArrayInputStream("123".getBytes()))); Assert.assertTrue(IOUtils.contentEquals(fixDir.getChildren().get("file2").asFile().getContent(), new ByteArrayInputStream("234".getBytes()))); }
@Test public void testFixDirWithFixDir() throws Exception { String js = "" + "ci.fixDir({" + " file0: ci.fixFile('012')," + " dir1: ci.fixDir({" + " file1: ci.fixFile('123')," + " file2: ci.fixFile('234')" + " })" + "})"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); FixDirHierarchyCreator creator = (FixDirHierarchyCreator) creatorObj.unwrap(); FixDir fixDir = creator.create(null); Assert.assertEquals(fixDir.getChildren().size(), 2); Assert.assertTrue(IOUtils.contentEquals(fixDir.getChildren().get("file0").asFile().getContent(), new ByteArrayInputStream("012".getBytes()))); FixDir fixDir2 = (FixDir) fixDir.getChildren().get("dir1"); Assert.assertEquals(fixDir2.getChildren().size(), 2); Assert.assertTrue(IOUtils.contentEquals(fixDir2.getChildren().get("file1").asFile().getContent(), new ByteArrayInputStream("123".getBytes()))); Assert.assertTrue(IOUtils.contentEquals(fixDir2.getChildren().get("file2").asFile().getContent(), new ByteArrayInputStream("234".getBytes()))); }
@Test public void testFixTableFromTSV() throws Exception { String js = "ci.fixTableFromTsv(ci.fixFile(\"A\\tB\\n1\\t2\\n11\\t22\"))"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); FileFixTableCreator creator = (FileFixTableCreator) creatorObj.unwrap(); TestRun testRun = mock(TestRun.class); FixTable t = creator.create(testRun); FixTable.FixRow r1 = t.getRows().get(0); FixTable.FixRow r2 = t.getRows().get(1); Assert.assertEquals("1", r1.getCells().get("A")); Assert.assertEquals("2", r1.getCells().get("B")); Assert.assertEquals("11", r2.getCells().get("A")); Assert.assertEquals("22", r2.getCells().get("B")); }
@Test public void testHiveInput() throws Exception { String tableCreationScript = "table creation script"; String js = "ci.hiveInput(\"dbname\", \"tablename\", ci.fixFile(\"" + tableCreationScript + "\"))"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); HiveTableDeployer hiveTableDeployer = (HiveTableDeployer) creatorObj.unwrap(); FixFile tableCreationFile = hiveTableDeployer.getTableCreationScriptFile().create(null); Assert.assertEquals(hiveTableDeployer.getDatabaseName(), new DatabaseName("dbname")); Assert.assertEquals(hiveTableDeployer.getTableName(), "tablename"); Assert.assertEquals(IOUtils.toString(tableCreationFile.getContent()), tableCreationScript); Assert.assertNull(hiveTableDeployer.getDataFileCreator()); }
@Test public void testHiveInputWithData() throws Exception { String tableCreationScript = "table creation script"; String js = "var table = ci.fixTable([\"col1\", \"col2\"], [[\"row1\", \"row2\"],[\"row11\", \"row22\"]]);" + "ci.hiveInput(\"dbname\", \"tablename\", ci.fixFile(\"" + tableCreationScript + "\"), table)"; TestConfigurationParser parser = new TestConfigurationParser(); NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string"); HiveTableDeployer hiveTableDeployer = (HiveTableDeployer) creatorObj.unwrap(); Assert.assertEquals(hiveTableDeployer.getDatabaseName(), new DatabaseName("dbname")); Assert.assertEquals(hiveTableDeployer.getTableName(), "tablename"); FixFile tableCreationFile = hiveTableDeployer.getTableCreationScriptFile().create(null); Assert.assertEquals(IOUtils.toString(tableCreationFile.getContent()), tableCreationScript); Assert.assertEquals(hiveTableDeployer.getDataFileCreator().getClass(), StringArrayFixTableCreator.class); }
@Test public void testTakesDefaultUsername() throws Exception { URL resource = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/defaults-oozie-props"); File defaults = new File(resource.toURI()); WorkflowConfigurationParser parser = new WorkflowConfigurationParser(defaults, ImmutableMap.of("var1", "val1")); String func = "function (slotId) {" + " return {" + " \"oozie.wf.application.path\": \"/workflow.xml\"," + " \"inputDir\": \"/input\"," + " \"outputDir\": \"/output\"" + " }" + " }"; String str = "importDefaults(\"test\"); celos.makePropertiesGen(" + func + "); "; NativeJavaObject jsResult = (NativeJavaObject) parser.evaluateReader(new StringReader(str), "string", new MemoryStateDatabase().openConnection()); PropertiesGenerator generator = (PropertiesGenerator) jsResult.unwrap(); Assert.assertEquals(generator.getProperties(null).get("user.name").asText(), "default"); }
@Test public void testTakesChangesUsername() throws Exception { URL resource = Thread.currentThread().getContextClassLoader().getResource("com/collective/celos/defaults-oozie-props"); File defaults = new File(resource.toURI()); WorkflowConfigurationParser parser = new WorkflowConfigurationParser(defaults, ImmutableMap.of("CELOS_USER_JS_VAR", "nameIsChanged")); String func = "function (slotId) {" + " return {" + " \"oozie.wf.application.path\": \"/workflow.xml\"," + " \"inputDir\": \"/input\"," + " \"outputDir\": \"/output\"" + " }" + " }"; String str = "importDefaults(\"test\"); celos.makePropertiesGen(" + func + "); "; NativeJavaObject jsResult = (NativeJavaObject) parser.evaluateReader(new StringReader(str), "string", new MemoryStateDatabase().openConnection()); PropertiesGenerator generator = (PropertiesGenerator) jsResult.unwrap(); Assert.assertEquals(generator.getProperties(null).get("user.name").asText(), "nameIsChanged"); }
@Override protected void registerIndexAndTypes(InternalIndexClient indexClient, InternalTypeClient... typeClients) { //We are in a different thread, therefore we cannot rely on the current shell context but we need to create a new one Context context = Context.enter(); try { //register index NativeJavaObject indexNativeJavaObject = new RhinoCustomNativeJavaObject(shellNativeClient.getParentScope(), indexClient, InternalIndexClient.class); indexNativeJavaObject.setPrototype(context.newObject(shellNativeClient.getParentScope())); if (typeClients != null) { //register types for (InternalTypeClient typeClient : typeClients) { NativeJavaObject typeNativeJavaObject = new RhinoCustomNativeJavaObject(shellNativeClient.getParentScope(), typeClient, InternalTypeClient.class); ScriptableObject.putProperty(indexNativeJavaObject, typeClient.typeName(), typeNativeJavaObject); } } logger.trace("Adding index {} to shell native client", indexClient.indexName()); ScriptableObject.putProperty(shellNativeClient, indexClient.indexName(), indexNativeJavaObject); } finally { Context.exit(); } }
/** * {@inheritDoc} */ @Override public Object convertValueForScript(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass) { if (!(value instanceof CharSequence)) { throw new IllegalArgumentException("value must be a CharSequence"); } final NativeJavaObject nativeJavaObject = new NativeJavaObject(DUMMY_SCOPE, value, value.getClass()); final ProxyFactory proxyFactory = new ConstructorArgumentAwareProxyFactory(new Object[] { DUMMY_SCOPE, value, value.getClass() }, new Class<?>[] { Scriptable.class, Object.class, Class.class }); proxyFactory.addAdvice(AdapterObjectInterceptor.getInstance()); proxyFactory.addAdvice(NativeStringEmulatingInterceptor.getInstance()); proxyFactory.setInterfaces(ClassUtils.collectInterfaces(nativeJavaObject, Arrays.<Class<?>> asList(AdapterObject.class))); proxyFactory.setTarget(nativeJavaObject); proxyFactory.setProxyTargetClass(true); final Object result = proxyFactory.getProxy(); return result; }
/** * {@inheritDoc} */ @Override public boolean isSupported(final Object workValue) { final boolean supported; if (workValue instanceof NativeJavaObject) { final Object unwrapped = ((NativeJavaObject) workValue).unwrap(); supported = unwrapped instanceof Collection<?>; } else { supported = false; } return supported; }
/** * {@inheritDoc} */ @Override public Collection<?> convert(final Object workValue) { final Collection<?> converted; if (workValue instanceof NativeJavaObject) { final Object unwrapped = ((NativeJavaObject) workValue).unwrap(); converted = unwrapped instanceof Collection<?> ? (Collection<?>) unwrapped : Collections.emptySet(); } else { converted = Collections.emptySet(); } return converted; }
protected Object convertForNativeJavaMethod(final AdapterObject object) { final Object result; final Object baseObject = object.getBackingObject(); if (this.nativeObjectCache != null && this.nativeObjectCache.containsKey(baseObject)) { final NativeJavaObject nativeObject = this.nativeObjectCache.get(baseObject); result = nativeObject; } else { result = baseObject; } return result; }
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; }
public static List<String> toStringList(Object ob) { List<String> list; if (ob != null) { if (ob instanceof NativeJavaObject) { NativeJavaObject nativeJavaObject = (NativeJavaObject) ob; list = toStringList(nativeJavaObject.unwrap()); } else if (ob instanceof NativeJavaArray) { Object object = ((NativeJavaArray) ob).unwrap(); list = toStringList(object); } else if (ob.getClass().isArray()) { list = toStringList(Arrays.asList((Object[]) ob)); } else if (ob instanceof NativeArray) { NativeArray array = (NativeArray) ob; list = new ArrayList<String>((int) array.getLength()); for (java.util.Iterator<?> i = array.iterator(); i.hasNext();) { list.add(toString(i.next())); } } else if (ob instanceof Collection<?>) { Collection<?> collection = GenericUtils.cast(ob); list = new ArrayList<String>(collection.size()); for (Object o : collection) { list.add(toString(o)); } } else { list = Arrays.asList(toString(ob)); } } else { list = Collections.emptyList(); } return list; }
private void createStepNodeSingleValue(Document doc, Element stepNode, String key, Object value) { if (value instanceof NativeJavaObject) { value = ((NativeJavaObject) value).unwrap(); } if (value instanceof XMLVector) { XMLVector<Object> nodeValues = GenericUtils.cast(value); for (Object object : nodeValues) { createStepNodeSingleValue(doc, stepNode, key, object); } } else if (value.getClass().isArray()) { int len = Array.getLength(value); for (int i = 0; i < len ; i++) { createStepNodeSingleValue(doc, stepNode, key, Array.get(value, i)); } } else { Element var = doc.createElement(key.toString()); stepNode.appendChild(var); // Structured variable if (value instanceof NodeList) { NodeList valueNodeList = (NodeList) value; int nlLen = valueNodeList.getLength(); Document document = stepNode.getOwnerDocument(); for (int i = 0; i < nlLen; i++) { Node nodeVarPart = valueNodeList.item(i); if (!nodeVarPart.getOwnerDocument().equals(document)) nodeVarPart = document.importNode(nodeVarPart, true); var.appendChild(nodeVarPart); } } else { String nodeValue = value.toString(); Node text = doc.createTextNode(nodeValue); var.appendChild(text); } } }
public void testAccessingFields() { Object result = runScript(importClass + "PrivateAccessClass.staticPackagePrivateInt"); assertEquals(new Integer(0), result); result = runScript(importClass + "PrivateAccessClass.staticPrivateInt"); assertEquals(new Integer(1), result); result = runScript(importClass + "PrivateAccessClass.staticProtectedInt"); assertEquals(new Integer(2), result); result = runScript(importClass + "new PrivateAccessClass().packagePrivateString"); assertEquals("package private", ((NativeJavaObject) result).unwrap()); result = runScript(importClass + "new PrivateAccessClass().privateString"); assertEquals("private", ((NativeJavaObject) result).unwrap()); result = runScript(importClass + "new PrivateAccessClass().protectedString"); assertEquals("protected", ((NativeJavaObject) result).unwrap()); result = runScript(importClass + "new PrivateAccessClass.PrivateNestedClass().packagePrivateInt"); assertEquals(new Integer(0), result); result = runScript(importClass + "new PrivateAccessClass.PrivateNestedClass().privateInt"); assertEquals(new Integer(1), result); result = runScript(importClass + "new PrivateAccessClass.PrivateNestedClass().protectedInt"); assertEquals(new Integer(2), result); }
private Object doContextAction(ContextAction action) { try { return contextFactory.call(action); } catch (JavaScriptException ex) { System.out.println("Script stack trace: " + ex.getScriptStackTrace()); Object value = ex.getValue(); if (value instanceof NativeJavaObject) { Object wrapped = ((NativeJavaObject) value).unwrap(); if (wrapped instanceof Throwable) { throw new JavascriptPassThroughException((Throwable) wrapped, ex.getScriptStackTrace()); } } throw ex; } }
public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class staticType) { if (javaObject instanceof Map) { Map map = (Map) javaObject; return new ScriptableMap(scope, map); } else if (javaObject instanceof List) { List list = (List) javaObject; return new ScriptableList(scope, list); } else { return new NativeJavaObject(scope, javaObject, staticType); } }
public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class staticType) { if (javaObject instanceof Map) { return new NativeMapAdapter(scope, javaObject, staticType); } else if (javaObject instanceof List) { return new NativeListAdapter(scope, javaObject, staticType); } else { return new NativeJavaObject(scope, javaObject, staticType); } }
public static boolean toBoolean(Object value) { if (value == null) { return false; } else if (value instanceof Undefined) { return false; } else if (value instanceof Number) { return ((Number)value).intValue() != 0; } else if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else if (value instanceof NativeJavaObject) { return toBoolean(((NativeJavaObject) value).unwrap()); } else { return true; } }
/** * This is used by an application to evaluate a string containing * some expression. */ @Override public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException { String scriptText = oscript.toString(); Object retval = null; Context cx; try { cx = Context.enter(); cx.setOptimizationLevel(-1); cx.setGeneratingDebug(false); cx.setGeneratingSource(false); cx.setOptimizationLevel(0); cx.setDebugger(null, null); retval = cx.evaluateString(global, scriptText, source, lineNo, null); if (retval instanceof NativeJavaObject) { retval = ((NativeJavaObject) retval).unwrap(); } } catch (Throwable t) { // includes JavaScriptException, rethrows Errors handleError(t); } finally { Context.exit(); } return retval; }
@Override public void accept(String inputText) { if (inputText == null || inputText.isEmpty()) { return; } Object result = SCAppMacroRuntime.getMacroRuntime().execute(new Macro(inputText)); if ((result instanceof NativeJavaObject) && ((NativeJavaObject) result).unwrap() == ConsoleBridge.CONSOLE_LOG_INVOKED) { // do nothing } else { ConsoleBridge.log(new Object[]{result}); } }