org.mozilla.javascript.NativeJavaObject Java Examples

The following examples show how to use org.mozilla.javascript.NativeJavaObject. 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: WorkflowConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #2
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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())));
}
 
Example #3
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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())));

}
 
Example #4
Source File: RhinoClientScopeSynchronizer.java    From elasticshell with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #5
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #6
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #7
Source File: RhinoValueConverter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Object convert( final Object o ) {
  if ( o instanceof NativeJavaObject ) {
    final NativeJavaObject object = (NativeJavaObject) o;
    return object.unwrap();
  }
  if ( o instanceof NativeArray ) {
    final NativeArray array = (NativeArray) o;
    final Object[] result = new Object[(int) array.getLength()];
    for ( final Object val : array.getIds() ) {
      final int index = (Integer) val;
      result[index] = array.get( index, null );
    }
    return result;
  }
  return null;
}
 
Example #8
Source File: RhinoExpression.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Evaluates the defined expression. If an exception or an evaluation error occures, the evaluation returns null and
 * the error is logged. The current datarow and a copy of the expressions properties are set to script-internal
 * variables. Changes to the properties will not alter the expressions original properties and will be lost when the
 * evaluation is finished.
 * <p/>
 * Expressions do not maintain a state and no assumptions about the order of evaluation can be made.
 *
 * @return the evaluated value or null.
 */
public Object getValue() {
  if ( expression == null ) {
    return null;
  }

  LegacyDataRowWrapper wrapper = null;
  try {
    final ContextFactory contextFactory = new ContextFactory();
    final Context context = contextFactory.enterContext();
    final Scriptable scope = context.initStandardObjects();
    wrapper = initializeScope( scope );

    final Object o = context.evaluateString( scope, expression, getName(), 1, null );
    if ( o instanceof NativeJavaObject ) {
      final NativeJavaObject object = (NativeJavaObject) o;
      return object.unwrap();
    }
    return o;
  } finally {
    if ( wrapper != null ) {
      wrapper.setParent( null );
    }
    Context.exit();
  }
}
 
Example #9
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: JsValue.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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$
}
 
Example #11
Source File: CelosWorkflowConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #12
Source File: DynamicTextItemExecutor.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: WorkflowConfigurationParserTest.java    From celos with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #14
Source File: DataFrameAdapter.java    From joinery with GNU General Public License v3.0 6 votes vote down vote up
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));
}
 
Example #15
Source File: PacScriptParser.java    From SmartZPN with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
    }
}
 
Example #16
Source File: JSEngine.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
/**
 * 执行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 #17
Source File: JsFunction.java    From spork with 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 #18
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testHiveInputOnlyDbName() throws Exception {

    String js = "ci.hiveInput(\"dbname\")";

    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.assertNull(hiveTableDeployer.getTableName());
    Assert.assertNull(hiveTableDeployer.getTableCreationScriptFile());
    Assert.assertNull(hiveTableDeployer.getDataFileCreator());
}
 
Example #19
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonCompare2() throws IOException {
    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.jsonCompare(ci.fixDirFromResource(\"stuff\"), ci.fixDirFromResource(\"stuff\"), [\"path1\", \"path2\"])"), "string");

    JsonContentsComparer comparer = (JsonContentsComparer) creatorObj.unwrap();
    Assert.assertEquals(comparer.getIgnorePaths(), new HashSet(Lists.newArrayList("path1", "path2")));
}
 
Example #20
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test(expected = JavaScriptException.class)
public void testJsonCompareFails() throws IOException {
    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.jsonCompare(ci.fixDirFromResource(\"stuff\"))"), "string");

    JsonContentsComparer comparer = (JsonContentsComparer) creatorObj.unwrap();
    Assert.assertEquals(comparer.getIgnorePaths(), new HashSet(Lists.newArrayList("path1", "path2")));
}
 
Example #21
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test(expected = JavaScriptException.class)
public void testRecursiveFsObjectComparer1() throws IOException {
    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.plainCompare()"), "string");
    RecursiveFsObjectComparer creator = (RecursiveFsObjectComparer) creatorObj.unwrap();
}
 
Example #22
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonToAvro() throws Exception {

    String jsonStr = "{\"visitor\":{\"com.collective.pythia.avro.Visitor\":{\"cookie_id\":\"133263e9e100000\",\"segments\":[],\"edges\":{},\"behaviors\":{},\"birthdate\":0,\"association_ids\":{}}},\"events\":[{\"cookie_id\":\"133263e9e100000\",\"tstamp\":1403721385042,\"edge\":\"batchimport\",\"changes\":{\"com.collective.pythia.avro.Command\":{\"operation\":\"REMOVE\",\"association_id\":null,\"network\":\"et\",\"segments\":[49118]}}},{\"cookie_id\":\"133263e9e100000\",\"tstamp\":1403721385042,\"edge\":\"batchimport\",\"changes\":{\"com.collective.pythia.avro.Command\":{\"operation\":\"ADD\",\"association_id\":null,\"network\":\"et\",\"segments\":[49117]}}}]}";
    String schemaStr = "{\"type\":\"record\",\"name\":\"ConsolidatedEvent\",\"namespace\":\"com.collective.pythia.avro\",\"fields\":[{\"name\":\"visitor\",\"type\":[\"null\",{\"type\":\"record\",\"name\":\"Visitor\",\"fields\":[{\"name\":\"cookie_id\",\"type\":\"string\"},{\"name\":\"segments\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"record\",\"name\":\"Segment\",\"fields\":[{\"name\":\"id\",\"type\":\"int\"},{\"name\":\"expiration\",\"type\":\"long\",\"default\":0}]}},\"default\":[]},{\"name\":\"edges\",\"type\":{\"type\":\"map\",\"values\":\"long\"},\"default\":{}},{\"name\":\"behaviors\",\"type\":{\"type\":\"map\",\"values\":{\"type\":\"map\",\"values\":\"int\"},\"default\":{}},\"doc\":\"Map of net.context to map of YYYYMMDD->number_of_hits\",\"default\":{}},{\"name\":\"birthdate\",\"type\":\"long\"},{\"name\":\"association_ids\",\"type\":{\"type\":\"map\",\"values\":\"string\"},\"default\":{}}]}],\"default\":null},{\"name\":\"events\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"record\",\"name\":\"ProfileEvent\",\"fields\":[{\"name\":\"cookie_id\",\"type\":\"string\"},{\"name\":\"tstamp\",\"type\":\"long\"},{\"name\":\"edge\",\"type\":\"string\"},{\"name\":\"changes\",\"type\":[{\"type\":\"record\",\"name\":\"Hit\",\"fields\":[{\"name\":\"daystamp\",\"type\":\"string\"},{\"name\":\"context\",\"type\":\"string\"},{\"name\":\"type\",\"type\":{\"type\":\"enum\",\"name\":\"HitType\",\"symbols\":[\"ADX\",\"RETARGET\"]}},{\"name\":\"count\",\"type\":\"int\",\"default\":1}]},{\"type\":\"record\",\"name\":\"Command\",\"fields\":[{\"name\":\"operation\",\"type\":{\"type\":\"enum\",\"name\":\"OperationType\",\"symbols\":[\"ADD\",\"REPLACE\",\"UPDATE\",\"REMOVE\"]}},{\"name\":\"association_id\",\"type\":[\"null\",\"string\"],\"default\":null},{\"name\":\"network\",\"type\":\"string\"},{\"name\":\"segments\",\"type\":{\"type\":\"array\",\"items\":\"int\"},\"default\":[]}]}]}]}},\"default\":[]}]}";

    String js = "" +
            "ci.jsonToAvro(" +
            "    ci.fixDir({ avroFile1: ci.fixFile('" + jsonStr + "'), avroFile2: ci.fixFile('" + jsonStr + "')})," +
            "    ci.fixFile('" + schemaStr + "')" +
            ");";

    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
    ConversionCreator<FixDir, FixDir> converter = (ConversionCreator) creatorObj.unwrap();

    Assert.assertEquals(converter.getDescription(null), "[avroFile1, avroFile2]");
    FixDir fixDir = converter.create(null);

    Assert.assertEquals(fixDir.getChildren().size(), 2);

    AvroToJsonConverter avroToJsonConverter = new AvroToJsonConverter();
    FixFile jsonFF = avroToJsonConverter.convert(null, new FixFile(fixDir.getChildren().get("avroFile1").asFile().getContent()));
    String jsonIsBack = IOUtils.toString(jsonFF.getContent());
    Assert.assertEquals(jsonIsBack, jsonStr);


    FixFile jsonFF2 = avroToJsonConverter.convert(null, new FixFile(fixDir.getChildren().get("avroFile2").asFile().getContent()));
    String jsonIsBack2 = IOUtils.toString(jsonFF2.getContent());
    Assert.assertEquals(jsonIsBack2, jsonStr);

}
 
Example #23
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testFixTableComparerOrdered() throws IOException {
    String js =
            "var table1 = ci.fixTable([\"col1\", \"col2\"], [[\"row1\", \"row2\"],[\"row11\", \"row22\"]]);" +
                    "var table2 = ci.fixTable([\"col1\", \"col2\"], [[\"row1\", \"row2\"],[\"row11\", \"row22\"]]);" +
                    "ci.fixTableCompare(table1, table2, true, true);";

    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
    FixTableComparer comparer = (FixTableComparer) creatorObj.unwrap();
    Assert.assertEquals(true, comparer.isColumnNamesOrdered());
    Assert.assertEquals(true, comparer.isRespectRowOrder());

}
 
Example #24
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testFixTableComparerNotOrdered() throws IOException {
    String js =
            "var table1 = ci.fixTable([\"col1\", \"col2\"], [[\"row1\", \"row2\"],[\"row11\", \"row22\"]]);" +
                    "var table2 = ci.fixTable([\"col1\", \"col2\"], [[\"row1\", \"row2\"],[\"row11\", \"row22\"]]);" +
                    "ci.fixTableCompare(table1, table2);";

    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
    FixTableComparer comparer = (FixTableComparer) creatorObj.unwrap();
    Assert.assertEquals(false, comparer.isColumnNamesOrdered());
    Assert.assertEquals(false, comparer.isRespectRowOrder());
}
 
Example #25
Source File: JavaScriptEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * This is used by an application to evaluate a string containing
 * some expression.
 */
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;
}
 
Example #26
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpandJsonNoFields() throws IOException {
    String js = "ci.expandJson(ci.tableToJson(ci.hiveTable(\"dbname\", \"tablename\")))";

    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
    ConversionCreator creator = (ConversionCreator) creatorObj.unwrap();
    Assert.assertEquals(JsonExpandConverter.class, creator.getFixObjectConverter().getClass());
}
 
Example #27
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpandJson() throws IOException {
    String js = "ci.expandJson(ci.tableToJson(ci.hiveTable(\"dbname\", \"tablename\")), [\"field1\", \"field2\"])";

    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
    ConversionCreator creator = (ConversionCreator) creatorObj.unwrap();
    Assert.assertEquals(JsonExpandConverter.class, creator.getFixObjectConverter().getClass());
}
 
Example #28
Source File: JavaScriptFunctionsTest.java    From celos with Apache License 2.0 5 votes vote down vote up
private Object runJS(String js) throws Exception {
    WorkflowConfigurationParser parser = createParser();
    // Evaluate JS function call
    Object jsResult = parser.evaluateReader(new StringReader(js), "string", new MemoryStateDatabase().openConnection());
    if (jsResult instanceof NativeJavaObject) {
        return ((NativeJavaObject) jsResult).unwrap();
    } else {
        return jsResult;
    }
}
 
Example #29
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testHiveTable() throws IOException {
    String js = "ci.hiveTable(\"dbname\", \"tablename\")";

    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader(js), "string");
    OutputFixTableFromHiveCreator creator = (OutputFixTableFromHiveCreator) creatorObj.unwrap();
    TestRun testRun = mock(TestRun.class);
    doReturn(UUID.nameUUIDFromBytes("fake".getBytes())).when(testRun).getTestUUID();
    Assert.assertEquals("Hive table celosci_dbname_144c9def_ac04_369c_bbfa_d8efaa8ea194.tablename", creator.getDescription(testRun));
}
 
Example #30
Source File: TestConfigurationParserTest.java    From celos with Apache License 2.0 5 votes vote down vote up
@Test
public void testAvroToJson() throws IOException {
    TestConfigurationParser parser = new TestConfigurationParser();

    NativeJavaObject creatorObj = (NativeJavaObject) parser.evaluateTestConfig(new StringReader("ci.avroToJson(\"1\")"), "string");

    ConversionCreator converter = (ConversionCreator) creatorObj.unwrap();

    Assert.assertTrue(converter.getFixObjectConverter() instanceof FixDirRecursiveConverter);
    FixDirRecursiveConverter fixDirRecursiveConverter = (FixDirRecursiveConverter) converter.getFixObjectConverter();
    Assert.assertTrue(fixDirRecursiveConverter.getFixFileConverter() instanceof AvroToJsonConverter);
    Assert.assertTrue(converter.getCreator() instanceof OutputFixDirFromHdfsCreator);
}