Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode toString.

Prototype

public abstract String toString();

Source Link

Usage

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void convertForEachIterateOverFieldEmpty() throws IOException {
    String json = "{\"rdbms\":{\"dialect\":\"oracle\",\"SQLMapping\": {\"columnToFieldMap\":[{\"table\":\"t\",\"column\":\"c\",\"field\":\"f\"}], \"joins\" :[{\"tables\":[{\"name\":\"n\",\"alias\":\"a\"}],\"joinTablesStatement\" : \"x\", \"projectionMappings\": [{\"column\":\"c\",\"field\":\"f\",\"sort\":\"s\"}]}]},\"delete\":{\"expressions\":[{\"foreach\":{\"expressions\":[{\"statement\":{\"sql\":\"X\",\"type\":\"select\"}}]}}]},\"fetch\":{\"expressions\":[{\"foreach\":{\"expressions\":[{\"statement\":{\"sql\":\"X\",\"type\":\"select\"}}]}}]},\"insert\":{\"expressions\":[{\"foreach\":{\"expressions\":[{\"statement\":{\"sql\":\"X\",\"type\":\"select\"}}]}}]},\"save\":{\"expressions\":[{\"foreach\":{\"expressions\":[{\"statement\":{\"sql\":\"X\",\"type\":\"select\"}}]}}]},\"update\":{\"expressions\":[{\"foreach\":{\"expressions\":[{\"statement\":{\"sql\":\"X\",\"type\":\"select\"}}]}}]}}}";

    JsonNode rJSON = p.newNode();
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    ForEach forEach = new ForEach();
    ArrayList<Expression> el = new ArrayList<Expression>();
    Statement es = new Statement();
    es.setSQL("X");
    es.setType("select");
    el.add(es);//w  ww.j ava 2  s. co m
    forEach.setExpressions(el);
    forEach.setIterateOverField(Path.EMPTY);
    Assert.assertEquals(el, forEach.getExpressions());
    expressionList.add(forEach);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    com.redhat.lightblue.util.Error xe = null;
    try {
        cut.convert(p, rJSON, r);
    } catch (com.redhat.lightblue.util.Error ex) {
        xe = ex;
    } catch (Throwable exx) {
        exx.printStackTrace();
    } finally {
        Assert.assertNotNull(xe);
    }
    Assert.assertEquals("{}", rJSON.toString());
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void convertAndParseIfFieldCheckValues() throws IOException {
    String json = "{\"rdbms\":{\"dialect\":\"oracle\",\"SQLMapping\": {\"columnToFieldMap\":[{\"table\":\"t\",\"column\":\"c\",\"field\":\"f\"}], \"joins\" :[{\"tables\":[{\"name\":\"n\",\"alias\":\"a\"}],\"joinTablesStatement\" : \"x\", \"projectionMappings\": [{\"column\":\"c\",\"field\":\"f\",\"sort\":\"s\"}]}]},\"delete\":{\"expressions\":[{\"if\":{\"fieldCheckValues\":{\"field\":\"*\",\"values\":[\"1\",\"2\"],\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"fetch\":{\"expressions\":[{\"if\":{\"fieldCheckValues\":{\"field\":\"*\",\"values\":[\"1\",\"2\"],\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"insert\":{\"expressions\":[{\"if\":{\"fieldCheckValues\":{\"field\":\"*\",\"values\":[\"1\",\"2\"],\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"save\":{\"expressions\":[{\"if\":{\"fieldCheckValues\":{\"field\":\"*\",\"values\":[\"1\",\"2\"],\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"update\":{\"expressions\":[{\"if\":{\"fieldCheckValues\":{\"field\":\"*\",\"values\":[\"1\",\"2\"],\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}}}";
    JsonNode rJSON = p.newNode();
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    Conditional e4 = new Conditional();
    IfFieldCheckValues pe = new IfFieldCheckValues();
    pe.setOp("eq");
    pe.setField(Path.ANYPATH);/*from ww w . j  ava  2  s  .c  o  m*/
    ArrayList<String> arl = new ArrayList<String>();
    arl.add("1");
    arl.add("2");
    pe.setValues(arl);
    e4.setIf(pe);
    Then then = new Then();
    ArrayList<Expression> expressions2 = new ArrayList<Expression>();
    Statement e5 = new Statement();
    e5.setType("delete");
    e5.setSQL("DELETE FROM somewhere WHERE someColumn=someValue");
    expressions2.add(e5);
    then.setExpressions(expressions2);
    e4.setThen(then);
    expressionList.add(e4);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    cut.convert(p, rJSON, r);

    assertEqualJson(json, rJSON.toString());
    Object ro = cut.parse("rdbms", p, JsonUtils.json(json).get("rdbms"));
    JsonNode roJSON = p.newNode();
    cut.convert(p, roJSON, ro);
    assertEqualJson(json, roJSON.toString());
    assertEqualJson(roJSON.toString(), rJSON.toString());
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void convertAndParseBindingsFieldsReq() throws IOException {
    String json = "{\"rdbms\":{\"dialect\":\"oracle\",\"SQLMapping\": {\"columnToFieldMap\":[{\"table\":\"t\",\"column\":\"c\",\"field\":\"f\"}], \"joins\" :[{\"tables\":[{\"name\":\"n\",\"alias\":\"a\"}],\"joinTablesStatement\" : \"x\", \"projectionMappings\": [{\"column\":\"c\",\"field\":\"f\",\"sort\":\"s\"}]}]},\"delete\":{\"bindings\":{\"in\":[{\"column\":\"col\"}]},\"expressions\":[{\"statement\":{\"sql\":\"REQ EXPRESSION\",\"type\":\"select\"}}]},\"fetch\":{\"bindings\":{\"in\":[{\"column\":\"col\"}]},\"expressions\":[{\"statement\":{\"sql\":\"REQ EXPRESSION\",\"type\":\"select\"}}]},\"insert\":{\"bindings\":{\"in\":[{\"column\":\"col\"}]},\"expressions\":[{\"statement\":{\"sql\":\"REQ EXPRESSION\",\"type\":\"select\"}}]},\"save\":{\"bindings\":{\"in\":[{\"column\":\"col\"}]},\"expressions\":[{\"statement\":{\"sql\":\"REQ EXPRESSION\",\"type\":\"select\"}}]},\"update\":{\"bindings\":{\"in\":[{\"column\":\"col\"}]},\"expressions\":[{\"statement\":{\"sql\":\"REQ EXPRESSION\",\"type\":\"select\"}}]}}}";

    JsonNode rJSON = p.newNode();
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();

    //With just In  bindings
    Bindings b = new Bindings();
    ArrayList<InOut> inList = new ArrayList<InOut>();
    InOut e = new InOut();
    e.setColumn("col");
    inList.add(e);/* ww w  .j ava2s  .  c  o  m*/
    b.setInList(inList);

    o.setBindings(b);
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    Statement e1 = new Statement();
    e1.setSQL("REQ EXPRESSION");
    e1.setType("select");
    expressionList.add(e1);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));

    com.redhat.lightblue.util.Error xe = null;
    try {
        cut.convert(p, rJSON, r);
    } catch (com.redhat.lightblue.util.Error ex) {
        xe = ex;
    } catch (Throwable exx) {
        exx.printStackTrace();
    } finally {
        Assert.assertNotNull(xe);
    }
    Assert.assertEquals("{}", rJSON.toString());

    com.redhat.lightblue.util.Error error = null;
    try {
        Object ro = cut.parse("rdbms", p, JsonUtils.json(json).get("rdbms"));
    } catch (com.redhat.lightblue.util.Error ex) {
        error = ex;
    } catch (Throwable exx) {
        exx.printStackTrace();
    } finally {
        Assert.assertNotNull(error);
    }
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void convertAndParseElseIf() throws IOException {
    String json = "{\"rdbms\":{\"dialect\":\"oracle\",\"SQLMapping\": {\"columnToFieldMap\":[{\"table\":\"t\",\"column\":\"c\",\"field\":\"f\"}], \"joins\" :[{\"tables\":[{\"name\":\"n\",\"alias\":\"a\"}],\"joinTablesStatement\" : \"x\", \"projectionMappings\": [{\"column\":\"c\",\"field\":\"f\",\"sort\":\"s\"}]}]},\"delete\":{\"expressions\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}],\"elseIf\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}]},\"fetch\":{\"expressions\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}],\"elseIf\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}]},\"insert\":{\"expressions\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}],\"elseIf\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}]},\"save\":{\"expressions\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}],\"elseIf\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}]},\"update\":{\"expressions\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}],\"elseIf\":[{\"if\":{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}]}}}";

    JsonNode rJSON = p.newNode();
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    Conditional e4 = new Conditional();
    IfFieldCheckValue anIf = new IfFieldCheckValue();
    anIf.setOp("eq");
    anIf.setField(new Path("abc"));
    anIf.setValue("123");
    e4.setIf(anIf);/*from w ww  . j  a  va2s .c  o  m*/
    Then then = new Then();
    ArrayList<Expression> expressions2 = new ArrayList<Expression>();
    Statement e5 = new Statement();
    e5.setType("delete");
    e5.setSQL("DELETE FROM somewhere WHERE someColumn=someValue");
    expressions2.add(e5);
    then.setExpressions(expressions2);
    e4.setThen(then);
    ArrayList<ElseIf> arrayList = new ArrayList<ElseIf>();
    final ElseIf elseIf = new ElseIf();
    elseIf.setIf(anIf);
    elseIf.setThen(then);
    arrayList.add(elseIf);
    e4.setElseIfList(arrayList);
    expressionList.add(e4);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    cut.convert(p, rJSON, r);
    assertEqualJson(json, rJSON.toString());

    Object ro = cut.parse("rdbms", p, JsonUtils.json(json).get("rdbms"));
    JsonNode roJSON = p.newNode();
    cut.convert(p, roJSON, ro);
    assertEqualJson(json, roJSON.toString());
    assertEqualJson(roJSON.toString(), rJSON.toString());
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void convertAndParseIfNot() throws IOException {
    String json = "{\"rdbms\":{\"dialect\":\"oracle\",\"SQLMapping\": {\"columnToFieldMap\":[{\"table\":\"t\",\"column\":\"c\",\"field\":\"f\"}], \"joins\" :[{\"tables\":[{\"name\":\"n\",\"alias\":\"a\"}],\"joinTablesStatement\" : \"x\", \"projectionMappings\": [{\"column\":\"c\",\"field\":\"f\",\"sort\":\"s\"}]}]},\"delete\":{\"expressions\":[{\"if\":{\"not\":{\"and\":[{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"lt\"}}]}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"fetch\":{\"expressions\":[{\"if\":{\"not\":{\"and\":[{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"lt\"}}]}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"insert\":{\"expressions\":[{\"if\":{\"not\":{\"and\":[{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"lt\"}}]}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"save\":{\"expressions\":[{\"if\":{\"not\":{\"and\":[{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"lt\"}}]}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]},\"update\":{\"expressions\":[{\"if\":{\"not\":{\"and\":[{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"eq\"}},{\"fieldCheckValue\":{\"field\":\"abc\",\"value\":\"123\",\"op\":\"lt\"}}]}},\"then\":[{\"statement\":{\"sql\":\"DELETE FROM somewhere WHERE someColumn=someValue\",\"type\":\"delete\"}}]}]}}}";

    JsonNode rJSON = p.newNode();
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");
    Operation o = new Operation();
    ArrayList<Expression> expressionList = new ArrayList<Expression>();
    Conditional e4 = new Conditional();
    IfNot ifNot = new IfNot();
    IfAnd ifAnd = new IfAnd();
    IfFieldCheckValue anIf = new IfFieldCheckValue();
    anIf.setOp("eq");
    anIf.setField(new Path("abc"));
    anIf.setValue("123");
    IfFieldCheckValue anIf2 = new IfFieldCheckValue();
    anIf2.setOp("lt");
    anIf2.setField(new Path("abc"));
    anIf2.setValue("123");
    List asList = Arrays.asList(anIf, anIf2);
    ifAnd.setConditions(asList);//from w  w w  . j a va  2  s.co  m
    List l = Arrays.asList(ifAnd);
    ifNot.setConditions(l);
    e4.setIf(ifNot);
    Then then = new Then();
    ArrayList<Expression> expressions2 = new ArrayList<Expression>();
    Statement e5 = new Statement();
    e5.setType("delete");
    e5.setSQL("DELETE FROM somewhere WHERE someColumn=someValue");
    expressions2.add(e5);
    then.setExpressions(expressions2);
    e4.setThen(then);
    expressionList.add(e4);
    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    cut.convert(p, rJSON, r);

    assertEqualJson(json, rJSON.toString());
    Object ro = cut.parse("rdbms", p, JsonUtils.json(json).get("rdbms"));
    JsonNode roJSON = p.newNode();
    cut.convert(p, roJSON, ro);
    assertEqualJson(json, roJSON.toString());
    assertEqualJson(roJSON.toString(), rJSON.toString());
}

From source file:com.redhat.lightblue.metadata.rdbms.parser.RDBMSPropertyParserImplTest.java

@Test
public void convertTest() throws IOException, JSONException {
    JsonNode parent = p.newNode();
    RDBMS r = new RDBMS();
    r.setDialect("oracle");
    r.setSQLMapping(new SQLMapping());
    r.getSQLMapping().setJoins(new ArrayList<Join>());
    r.getSQLMapping().getJoins().add(new Join());
    r.getSQLMapping().getJoins().get(0).setJoinTablesStatement("x");
    r.getSQLMapping().getJoins().get(0).setProjectionMappings(new ArrayList<ProjectionMapping>());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().add(new ProjectionMapping());
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setColumn("c");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setField("f");
    r.getSQLMapping().getJoins().get(0).getProjectionMappings().get(0).setSort("s");
    r.getSQLMapping().getJoins().get(0).setTables(new ArrayList<Table>());
    r.getSQLMapping().getJoins().get(0).getTables().add(new Table());
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setAlias("a");
    r.getSQLMapping().getJoins().get(0).getTables().get(0).setName("n");
    r.getSQLMapping().setColumnToFieldMap(new ArrayList<ColumnToField>());
    r.getSQLMapping().getColumnToFieldMap().add(new ColumnToField());
    r.getSQLMapping().getColumnToFieldMap().get(0).setColumn("c");
    r.getSQLMapping().getColumnToFieldMap().get(0).setField("f");
    r.getSQLMapping().getColumnToFieldMap().get(0).setTable("t");

    Operation o = new Operation();
    Bindings b = new Bindings();
    ArrayList<InOut> inList = new ArrayList<InOut>();
    InOut e = new InOut();
    e.setColumn("col");
    e.setField(new Path("pat"));
    inList.add(e);/* w w  w  .j ava  2 s  .  c  om*/
    b.setInList(inList);
    o.setBindings(b);
    ArrayList<Expression> expressionList = new ArrayList<Expression>();

    Statement e1 = new Statement();
    e1.setSQL("SELECT * FROM TABLE1");
    e1.setType("select");
    expressionList.add(e1);

    For e2 = new For();
    e2.setLoopTimes(1);
    e2.setLoopCounterVariableName("i");
    ArrayList<Expression> expressions = new ArrayList<Expression>();
    expressions.add(e1);
    ForEach e3 = new ForEach();
    ArrayList<Expression> expressions1 = new ArrayList<Expression>();
    expressions1.add(e1);
    e3.setExpressions(expressions1);
    e3.setIterateOverField(new Path("j"));
    expressions.add(e3);
    e2.setExpressions(expressions);
    expressionList.add(e2);

    Conditional e4 = new Conditional();
    IfFieldCheckValue anIf = new IfFieldCheckValue();
    anIf.setOp("eq");
    anIf.setField(new Path("abc"));
    anIf.setValue("123");
    e4.setIf(anIf);
    Then then = new Then();
    ArrayList<Expression> expressions2 = new ArrayList<Expression>();
    Statement e5 = new Statement();
    e5.setType("delete");
    e5.setSQL("DELETE FROM somewhere WHERE someColumn=someValue");
    expressions2.add(e5);
    then.setExpressions(expressions2);
    e4.setThen(then);
    expressionList.add(e4);

    o.setExpressionList(expressionList);
    r.setDelete(duplicate("delete", o));
    r.setFetch(duplicate("fetch", o));
    r.setInsert(duplicate("insert", o));
    r.setSave(duplicate("save", o));
    r.setUpdate(duplicate("update", o));
    cut.convert(p, parent, r);

    System.out.println(parent.toString());
    assertEqualJson(expectedJSON, parent.toString());
}

From source file:com.marklogic.client.impl.JerseyServices.java

@Override
public EvalResultIterator postEvalInvoke(RequestLogger reqlog, String code, String modulePath,
        ServerEvaluationCallImpl.Context context, Map<String, Object> variables,
        EditableNamespaceContext namespaces, Transaction transaction) throws ResourceNotFoundException,
        ResourceNotResendableException, ForbiddenUserException, FailedRequestException {
    String formUrlEncodedPayload;
    String path;//from  w  ww  .  j a  v a2  s.  c o  m
    RequestParameters params = new RequestParameters();
    try {
        StringBuffer sb = new StringBuffer();
        if (context == ServerEvaluationCallImpl.Context.ADHOC_XQUERY) {
            path = "eval";
            sb.append("xquery=");
            sb.append(URLEncoder.encode(code, "UTF-8"));
        } else if (context == ServerEvaluationCallImpl.Context.ADHOC_JAVASCRIPT) {
            path = "eval";
            sb.append("javascript=");
            sb.append(URLEncoder.encode(code, "UTF-8"));
        } else if (context == ServerEvaluationCallImpl.Context.INVOKE) {
            path = "invoke";
            sb.append("module=");
            sb.append(URLEncoder.encode(modulePath, "UTF-8"));
        } else {
            throw new IllegalStateException("Invalid eval context: " + context);
        }
        if (variables != null && variables.size() > 0) {
            int i = 0;
            for (String name : variables.keySet()) {
                String namespace = "";
                String localname = name;
                if (namespaces != null) {
                    for (String prefix : namespaces.keySet()) {
                        if (name != null && prefix != null && name.startsWith(prefix + ":")) {
                            localname = name.substring(prefix.length() + 1);
                            namespace = namespaces.get(prefix);
                        }
                    }
                }
                // set the variable namespace
                sb.append("&evn" + i + "=");
                sb.append(URLEncoder.encode(namespace, "UTF-8"));
                // set the variable localname
                sb.append("&evl" + i + "=");
                sb.append(URLEncoder.encode(localname, "UTF-8"));

                String value;
                String type = null;
                Object valueObject = variables.get(name);
                if (valueObject == null) {
                    value = "null";
                    type = "null-node()";
                } else if (valueObject instanceof JacksonHandle || valueObject instanceof JacksonParserHandle) {
                    JsonNode jsonNode = null;
                    if (valueObject instanceof JacksonHandle) {
                        jsonNode = ((JacksonHandle) valueObject).get();
                    } else if (valueObject instanceof JacksonParserHandle) {
                        jsonNode = ((JacksonParserHandle) valueObject).get().readValueAs(JsonNode.class);
                    }
                    value = jsonNode.toString();
                    type = getJsonType(jsonNode);
                } else if (valueObject instanceof AbstractWriteHandle) {
                    value = HandleAccessor.contentAsString((AbstractWriteHandle) valueObject);
                    HandleImplementation valueBase = HandleAccessor.as((AbstractWriteHandle) valueObject);
                    Format format = valueBase.getFormat();
                    //TODO: figure out what type should be
                    // I see element() and document-node() are two valid types
                    if (format == Format.XML) {
                        type = "document-node()";
                    } else if (format == Format.JSON) {
                        JsonNode jsonNode = new JacksonParserHandle().getMapper().readTree(value);
                        type = getJsonType(jsonNode);
                    } else if (format == Format.TEXT) {
                        /* Comment next line until 32608 is resolved
                        type = "text()";
                        // until then, use the following line */
                        type = "xs:untypedAtomic";
                    } else if (format == Format.BINARY) {
                        throw new UnsupportedOperationException("Binary format is not supported for variables");
                    } else {
                        throw new UnsupportedOperationException(
                                "Undefined format is not supported for variables. "
                                        + "Please set the format on your handle for variable " + name + ".");
                    }
                } else if (valueObject instanceof String || valueObject instanceof Boolean
                        || valueObject instanceof Number) {
                    value = valueObject.toString();
                    // when we send type "xs:untypedAtomic" via XDBC, the server attempts to intelligently decide
                    // how to cast the type
                    type = "xs:untypedAtomic";
                } else {
                    throw new IllegalArgumentException("Variable with name=" + name + " is of unsupported type"
                            + valueObject.getClass() + ". Supported types are String, Boolean, Number, "
                            + "or AbstractWriteHandle");
                }

                // set the variable value
                sb.append("&evv" + i + "=");
                sb.append(URLEncoder.encode(value, "UTF-8"));
                // set the variable type
                sb.append("&evt" + i + "=" + type);
                i++;
            }
        }
        formUrlEncodedPayload = sb.toString();
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("UTF-8 is unsupported", e);
    } catch (IOException e) {
        throw new MarkLogicIOException(e);
    }
    StringHandle input = new StringHandle(formUrlEncodedPayload)
            .withMimetype("application/x-www-form-urlencoded");
    return new JerseyEvalResultIterator(postIteratedResourceImpl(DefaultJerseyResultIterator.class, reqlog,
            path, transaction, params, input));
}

From source file:com.microsoft.azure.vmagent.AzureVMManagementServiceDelegate.java

public static AzureVMDeploymentInfo createDeployment(final AzureVMAgentTemplate template,
        final int numberOfAgents, TokenCache tokenCache,
        AzureVMAgentCleanUpTask.DeploymentRegistrar deploymentRegistrar)
        throws AzureCloudException, IOException {

    InputStream embeddedTemplate = null;
    try {//from   w w w . j  a  va2 s .c o m
        LOGGER.log(Level.INFO,
                "AzureVMManagementServiceDelegate: createDeployment: Initializing deployment for agentTemplate {0}",
                template.getTemplateName());

        final Azure azureClient = tokenCache.getAzureClient();

        final Date timestamp = new Date(System.currentTimeMillis());
        final String deploymentName = AzureUtil.getDeploymentName(template.getTemplateName(), timestamp);
        final String vmBaseName = AzureUtil.getVMBaseName(template.getTemplateName(), deploymentName,
                template.getOsType(), numberOfAgents);
        final String locationName = getLocationName(template.getLocation());
        final String storageAccountName = template.getStorageAccountName();
        if (!template.getResourceGroupName().matches(Constants.DEFAULT_RESOURCE_GROUP_PATTERN)) {
            LOGGER.log(Level.SEVERE,
                    "AzureVMManagementServiceDelegate: createDeployment: ResourceGroup Name {0} is invalid. It should be 1-64 alphanumeric characters",
                    new Object[] { template.getResourceGroupName() });
            throw new Exception("ResourceGroup Name is invalid");
        }
        final String resourceGroupName = template.getResourceGroupName();
        LOGGER.log(Level.INFO,
                "AzureVMManagementServiceDelegate: createDeployment: Creating a new deployment {0} with VM base name {1}",
                new Object[] { deploymentName, vmBaseName });

        createAzureResourceGroup(azureClient, locationName, resourceGroupName);
        //For blob endpoint url in arm template, it's different based on different environments
        //So create StorageAccount and get suffix 
        createStorageAccount(azureClient, storageAccountName, locationName, resourceGroupName);
        StorageAccount storageAccount = getStorageAccount(azureClient, storageAccountName, resourceGroupName);
        String blobEndpointSuffix = getBlobEndpointSuffixForTemplate(storageAccount);
        final boolean useCustomScriptExtension = template.getOsType().equals(Constants.OS_TYPE_WINDOWS)
                && !StringUtils.isBlank(template.getInitScript())
                && template.getAgentLaunchMethod().equals(Constants.LAUNCH_METHOD_JNLP);

        // check if a custom image id has been provided otherwise work with publisher and offer
        if (template.getImageReferenceType().equals(IMAGE_CUSTOM_REFERENCE)) {
            if (useCustomScriptExtension) {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template {0}",
                        EMBEDDED_TEMPLATE_IMAGE_WITH_SCRIPT_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_IMAGE_WITH_SCRIPT_FILENAME);
            } else {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template (with script) {0}",
                        EMBEDDED_TEMPLATE_IMAGE_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_IMAGE_FILENAME);
            }
        } else {
            if (useCustomScriptExtension) {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template (with script) {0}",
                        EMBEDDED_TEMPLATE_WITH_SCRIPT_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_WITH_SCRIPT_FILENAME);
            } else {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template {0}",
                        EMBEDDED_TEMPLATE_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_FILENAME);
            }
        }

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode tmp = mapper.readTree(embeddedTemplate);

        // Add count variable for loop....
        final ObjectNode count = mapper.createObjectNode();
        count.put("type", "int");
        count.put("defaultValue", numberOfAgents);
        ObjectNode.class.cast(tmp.get("parameters")).replace("count", count);

        ObjectNode.class.cast(tmp.get("variables")).put("vmName", vmBaseName);
        ObjectNode.class.cast(tmp.get("variables")).put("location", locationName);
        ObjectNode.class.cast(tmp.get("variables")).put("jenkinsTag", Constants.AZURE_JENKINS_TAG_VALUE);
        ObjectNode.class.cast(tmp.get("variables")).put("resourceTag",
                deploymentRegistrar.getDeploymentTag().get());

        if (StringUtils.isNotBlank(template.getImagePublisher())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imagePublisher", template.getImagePublisher());
        }

        if (StringUtils.isNotBlank(template.getImageOffer())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imageOffer", template.getImageOffer());
        }

        if (StringUtils.isNotBlank(template.getImageSku())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imageSku", template.getImageSku());
        }

        if (StringUtils.isNotBlank(template.getOsType())) {
            ObjectNode.class.cast(tmp.get("variables")).put("osType", template.getOsType());
        }

        if (StringUtils.isNotBlank(template.getImage())) {
            ObjectNode.class.cast(tmp.get("variables")).put("image", template.getImage());
        }

        // If using the custom script extension (vs. SSH) to startup the powershell scripts,
        // add variables for that and upload the init script to the storage account
        if (useCustomScriptExtension) {
            ObjectNode.class.cast(tmp.get("variables")).put("jenkinsServerURL",
                    Jenkins.getInstance().getRootUrl());
            // Calculate the client secrets.  The secrets are based off the machine name,
            ArrayNode clientSecretsNode = ObjectNode.class.cast(tmp.get("variables")).putArray("clientSecrets");
            for (int i = 0; i < numberOfAgents; i++) {
                clientSecretsNode
                        .add(JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(String.format("%s%d", vmBaseName, i)));
            }
            // Upload the startup script to blob storage
            String scriptName = String.format("%s%s", deploymentName, "init.ps1");
            String scriptUri = uploadCustomScript(template, scriptName, tokenCache);
            ObjectNode.class.cast(tmp.get("variables")).put("startupScriptURI", scriptUri);
            ObjectNode.class.cast(tmp.get("variables")).put("startupScriptName", scriptName);

            List<StorageAccountKey> storageKeys = azureClient.storageAccounts()
                    .getByGroup(template.getResourceGroupName(), storageAccountName).getKeys();
            if (storageKeys.isEmpty()) {
                throw new AzureCloudException("AzureVMManagementServiceDelegate: createDeployment: "
                        + "Exception occured while fetching the storage account key");
            }
            String storageAccountKey = storageKeys.get(0).value();

            final ObjectNode storageAccountKeyNode = mapper.createObjectNode();
            storageAccountKeyNode.put("type", "secureString");
            storageAccountKeyNode.put("defaultValue", storageAccountKey);

            // Add the storage account key
            ObjectNode.class.cast(tmp.get("parameters")).replace("storageAccountKey", storageAccountKeyNode);
        }

        ObjectNode.class.cast(tmp.get("variables")).put("vmSize", template.getVirtualMachineSize());
        // Grab the username/pass
        StandardUsernamePasswordCredentials creds = template.getVMCredentials();

        ObjectNode.class.cast(tmp.get("variables")).put("adminUsername", creds.getUsername());
        ObjectNode.class.cast(tmp.get("variables")).put("adminPassword", creds.getPassword().getPlainText());

        if (StringUtils.isNotBlank(storageAccountName)) {
            ObjectNode.class.cast(tmp.get("variables")).put("storageAccountName", storageAccountName);
        }

        if (StringUtils.isNotBlank(blobEndpointSuffix)) {
            ObjectNode.class.cast(tmp.get("variables")).put("blobEndpointSuffix", blobEndpointSuffix);
        }

        // Network properties.  If the vnet name isn't blank then
        // then subnet name can't be either (based on verification rules)
        if (StringUtils.isNotBlank(template.getVirtualNetworkName())) {
            ObjectNode.class.cast(tmp.get("variables")).put("virtualNetworkName",
                    template.getVirtualNetworkName());
            ObjectNode.class.cast(tmp.get("variables")).put("subnetName", template.getSubnetName());
        } else {
            AddDefaultVNetResourceNode(tmp, mapper);
        }

        if (!template.getUsePrivateIP()) {
            AddPublicIPResourceNode(tmp, mapper);
        }

        if (StringUtils.isNotBlank(template.getNsgName())) {
            AddNSGNode(tmp, mapper, template.getNsgName());
        }

        // Register the deployment for cleanup
        deploymentRegistrar.registerDeployment(template.getAzureCloud().name, template.getResourceGroupName(),
                deploymentName);
        // Create the deployment
        azureClient.deployments().define(deploymentName)
                .withExistingResourceGroup(template.getResourceGroupName()).withTemplate(tmp.toString())
                .withParameters("{}").withMode(DeploymentMode.INCREMENTAL).beginCreate();
        return new AzureVMDeploymentInfo(deploymentName, vmBaseName, numberOfAgents);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "AzureVMManagementServiceDelegate: deployment: Unable to deploy", e);
        // Pass the info off to the template so that it can be queued for update.
        template.handleTemplateProvisioningFailure(e.getMessage(), FailureStage.PROVISIONING);
        throw new AzureCloudException(e);
    } finally {
        if (embeddedTemplate != null)
            embeddedTemplate.close();
    }
}

From source file:com.microsoft.azure.AzureVMManagementServiceDelegate.java

/**
 * Creates a new deployment of VMs based on the provided template
 *
 * @param template Template to deploy//from   ww  w . j  a va2s.com
 * @param numberOfAgents Number of agents to create
 * @return The base name for the VMs that were created
 * @throws AzureCloudException
 * @throws java.io.IOException
 */
public static AzureVMDeploymentInfo createDeployment(final AzureVMAgentTemplate template,
        final int numberOfAgents) throws AzureCloudException, IOException {

    InputStream embeddedTemplate = null;
    InputStream fragmentStream = null;
    try {
        LOGGER.log(Level.INFO,
                "AzureVMManagementServiceDelegate: createDeployment: Initializing deployment for agentTemplate {0}",
                template.getTemplateName());

        Configuration config = ServiceDelegateHelper.getConfiguration(template);
        final ResourceManagementClient client = ServiceDelegateHelper.getResourceManagementClient(config);

        final Date timestamp = new Date(System.currentTimeMillis());
        final String deploymentName = AzureUtil.getDeploymentName(template.getTemplateName(), timestamp);
        final String vmBaseName = AzureUtil.getVMBaseName(template.getTemplateName(), deploymentName,
                template.getOsType(), numberOfAgents);
        final String locationName = getLocationName(template.getLocation());
        if (!template.getResourceGroupName().matches(Constants.DEFAULT_RESOURCE_GROUP_PATTERN)) {
            LOGGER.log(Level.SEVERE,
                    "AzureVMManagementServiceDelegate: createDeployment: ResourceGroup Name {0} is invalid. It should be 1-64 alphanumeric characters",
                    new Object[] { template.getResourceGroupName() });
            throw new Exception("ResourceGroup Name is invalid");
        }
        final String resourceGroupName = template.getResourceGroupName();
        LOGGER.log(Level.INFO,
                "AzureVMManagementServiceDelegate: createDeployment: Creating a new deployment {0} with VM base name {1}",
                new Object[] { deploymentName, vmBaseName });

        client.getResourceGroupsOperations().createOrUpdate(resourceGroupName, new ResourceGroup(locationName));

        final Deployment deployment = new Deployment();
        final DeploymentProperties properties = new DeploymentProperties();
        deployment.setProperties(properties);

        final boolean useCustomScriptExtension = template.getOsType().equals(Constants.OS_TYPE_WINDOWS)
                && !StringUtils.isBlank(template.getInitScript())
                && template.getAgentLaunchMethod().equals(Constants.LAUNCH_METHOD_JNLP);

        // check if a custom image id has been provided otherwise work with publisher and offer
        if (template.getImageReferenceType().equals(IMAGE_CUSTOM_REFERENCE)) {
            if (useCustomScriptExtension) {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template {0}",
                        EMBEDDED_TEMPLATE_IMAGE_WITH_SCRIPT_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_IMAGE_WITH_SCRIPT_FILENAME);
            } else {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template (with script) {0}",
                        EMBEDDED_TEMPLATE_IMAGE_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_IMAGE_FILENAME);
            }
        } else {
            if (useCustomScriptExtension) {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template (with script) {0}",
                        EMBEDDED_TEMPLATE_WITH_SCRIPT_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_WITH_SCRIPT_FILENAME);
            } else {
                LOGGER.log(Level.INFO,
                        "AzureVMManagementServiceDelegate: createDeployment: Use embedded deployment template {0}",
                        EMBEDDED_TEMPLATE_FILENAME);
                embeddedTemplate = AzureVMManagementServiceDelegate.class
                        .getResourceAsStream(EMBEDDED_TEMPLATE_FILENAME);
            }
        }

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode tmp = mapper.readTree(embeddedTemplate);

        // Add count variable for loop....
        final ObjectNode count = mapper.createObjectNode();
        count.put("type", "int");
        count.put("defaultValue", numberOfAgents);
        ObjectNode.class.cast(tmp.get("parameters")).replace("count", count);

        ObjectNode.class.cast(tmp.get("variables")).put("vmName", vmBaseName);
        ObjectNode.class.cast(tmp.get("variables")).put("location", locationName);

        if (StringUtils.isNotBlank(template.getImagePublisher())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imagePublisher", template.getImagePublisher());
        }

        if (StringUtils.isNotBlank(template.getImageOffer())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imageOffer", template.getImageOffer());
        }

        if (StringUtils.isNotBlank(template.getImageSku())) {
            ObjectNode.class.cast(tmp.get("variables")).put("imageSku", template.getImageSku());
        }

        if (StringUtils.isNotBlank(template.getOsType())) {
            ObjectNode.class.cast(tmp.get("variables")).put("osType", template.getOsType());
        }

        if (StringUtils.isNotBlank(template.getImage())) {
            ObjectNode.class.cast(tmp.get("variables")).put("image", template.getImage());
        }

        // If using the custom script extension (vs. SSH) to startup the powershell scripts,
        // add variables for that and upload the init script to the storage account
        if (useCustomScriptExtension) {
            ObjectNode.class.cast(tmp.get("variables")).put("jenkinsServerURL",
                    Jenkins.getInstance().getRootUrl());
            // Calculate the client secrets.  The secrets are based off the machine name, 
            ArrayNode clientSecretsNode = ObjectNode.class.cast(tmp.get("variables")).putArray("clientSecrets");
            for (int i = 0; i < numberOfAgents; i++) {
                clientSecretsNode
                        .add(JnlpSlaveAgentProtocol.SLAVE_SECRET.mac(String.format("%s%d", vmBaseName, i)));
            }
            // Upload the startup script to blob storage
            String scriptName = String.format("%s%s", deploymentName, "init.ps1");
            String scriptUri = uploadCustomScript(template, scriptName);
            ObjectNode.class.cast(tmp.get("variables")).put("startupScriptURI", scriptUri);
            ObjectNode.class.cast(tmp.get("variables")).put("startupScriptName", scriptName);

            String storageAccountKey = ServiceDelegateHelper.getStorageManagementClient(config)
                    .getStorageAccountsOperations()
                    .listKeys(template.getResourceGroupName(), template.getStorageAccountName())
                    .getStorageAccountKeys().getKey1();

            final ObjectNode storageAccountKeyNode = mapper.createObjectNode();
            storageAccountKeyNode.put("type", "secureString");
            storageAccountKeyNode.put("defaultValue", storageAccountKey);

            // Add the storage account key
            ObjectNode.class.cast(tmp.get("parameters")).replace("storageAccountKey", storageAccountKeyNode);
        }

        ObjectNode.class.cast(tmp.get("variables")).put("vmSize", template.getVirtualMachineSize());
        // Grab the username/pass
        StandardUsernamePasswordCredentials creds = AzureUtil.getCredentials(template.getCredentialsId());

        ObjectNode.class.cast(tmp.get("variables")).put("adminUsername", creds.getUsername());
        ObjectNode.class.cast(tmp.get("variables")).put("adminPassword", creds.getPassword().getPlainText());

        if (StringUtils.isNotBlank(template.getStorageAccountName())) {
            ObjectNode.class.cast(tmp.get("variables")).put("storageAccountName",
                    template.getStorageAccountName());
        }

        // Network properties.  If the vnet name isn't blank then
        // then subnet name can't be either (based on verification rules)
        if (StringUtils.isNotBlank(template.getVirtualNetworkName())) {
            ObjectNode.class.cast(tmp.get("variables")).put("virtualNetworkName",
                    template.getVirtualNetworkName());
            ObjectNode.class.cast(tmp.get("variables")).put("subnetName", template.getSubnetName());
        } else {
            // Add the definition of the vnet and subnet into the template
            final String virtualNetworkName = Constants.DEFAULT_VNET_NAME;
            final String subnetName = Constants.DEFAULT_SUBNET_NAME;
            ObjectNode.class.cast(tmp.get("variables")).put("virtualNetworkName", virtualNetworkName);
            ObjectNode.class.cast(tmp.get("variables")).put("subnetName", subnetName);

            // Read the vnet fragment
            fragmentStream = AzureVMManagementServiceDelegate.class
                    .getResourceAsStream(VIRTUAL_NETWORK_TEMPLATE_FRAGMENT_FILENAME);

            final JsonNode virtualNetworkFragment = mapper.readTree(fragmentStream);
            // Add the virtual network fragment
            ArrayNode.class.cast(tmp.get("resources")).add(virtualNetworkFragment);

            // Because we created/updated this in the template, we need to add the appropriate
            // dependsOn node to the networkInterface
            // Microsoft.Network/virtualNetworks/<vnet name>
            // Find the network interfaces node
            ArrayNode resourcesNodes = ArrayNode.class.cast(tmp.get("resources"));
            Iterator<JsonNode> resourcesNodesIter = resourcesNodes.elements();
            while (resourcesNodesIter.hasNext()) {
                JsonNode resourcesNode = resourcesNodesIter.next();
                JsonNode typeNode = resourcesNode.get("type");
                if (typeNode == null || !typeNode.asText().equals("Microsoft.Network/networkInterfaces")) {
                    continue;
                }
                // Find the dependsOn node
                ArrayNode dependsOnNode = ArrayNode.class.cast(resourcesNode.get("dependsOn"));
                // Add to the depends on node.
                dependsOnNode
                        .add("[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]");
                break;
            }
        }

        // Deployment ....
        properties.setMode(DeploymentMode.Incremental);
        properties.setTemplate(tmp.toString());

        // Register the deployment for cleanup
        AzureVMAgentCleanUpTask.registerDeployment(template.getAzureCloud().name,
                template.getResourceGroupName(), deploymentName);
        // Create the deployment
        client.getDeploymentsOperations().createOrUpdate(template.getResourceGroupName(), deploymentName,
                deployment);

        return new AzureVMDeploymentInfo(deploymentName, vmBaseName, numberOfAgents);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "AzureVMManagementServiceDelegate: deployment: Unable to deploy", e);
        // Pass the info off to the template so that it can be queued for update.
        template.handleTemplateProvisioningFailure(e.getMessage(), FailureStage.PROVISIONING);
        throw new AzureCloudException(e);
    } finally {
        if (embeddedTemplate != null)
            embeddedTemplate.close();
        if (fragmentStream != null)
            fragmentStream.close();
    }
}