Example #1
0
 public void testParameterEdit() throws Exception {
   ConfigurationContext configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
   AxisConfiguration axisConfig = configCtx.getAxisConfiguration();
   Parameter parameter = new Parameter();
   parameter.setValue("true");
   parameter.setName("enableMTOM");
   axisConfig.addParameter(parameter);
   parameter.setValue("true");
   AxisServiceGroup serviceGroup = new AxisServiceGroupImpl();
   serviceGroup.setName("testServiceGroup");
   AxisService service = new AxisService();
   service.setName("service");
   serviceGroup.addService(service);
   axisConfig.addServiceGroup(serviceGroup);
   parameter = serviceGroup.getParameter("enableMTOM");
   parameter.setValue("true");
   Parameter para2 = serviceGroup.getParameter("enableMTOM");
   assertEquals(para2.getValue(), "true");
   Parameter test = new Parameter();
   test.setName("test");
   test.setValue("test");
   serviceGroup.addParameter(test);
   Parameter para = serviceGroup.getParameter("test");
   assertNotNull(para);
   assertEquals(para.getValue(), "test");
   para.setValue("newValue");
   para = serviceGroup.getParameter("test");
   assertNotNull(para);
   assertEquals(para.getValue(), "newValue");
 }
Example #2
0
  @Test
  public void testAsString() {
    Parameter p = new Parameter();
    assertTrue(p.asString().equals("name=null,value=null"));

    p.setName("bob");
    assertTrue(p.asString().equals("name=bob,value=null"));

    p.setValue("val");
    assertTrue(p.asString().equals("name=bob,value=val"));

    p.setName(null);
    assertTrue(p.asString().equals("name=null,value=val"));
  }
 public void test_Parameter_setName() {
   String name = "Forward_Michaelis_Menten_Constant";
   P.setName(name);
   assertTrue(P.getName().equals(name));
   assertEquals(true, P.isSetName());
   if (P.getName() == name) ;
   {
   }
   P.setName(P.getName());
   assertTrue(P.getName().equals(name));
   P.setName("");
   assertEquals(false, P.isSetName());
   if (P.getName() != null) ;
   {
   }
 }
Example #4
0
 public void testNodeAttributeEvent() {
   TestAttributeListener l = new TestAttributeListener();
   Node test = Node.ROOT_NODE.newInstance(testLibrary, "test");
   test.addNodeAttributeListener(l);
   // Setting the name to itself does not trigger an event.
   test.setName("test");
   assertEquals(0, l.nameCounter);
   test.setName("newname");
   assertEquals(1, l.nameCounter);
   Parameter p1 = test.addParameter("p1", Parameter.Type.FLOAT);
   assertEquals(1, l.parameterCounter);
   p1.setName("parameter1");
   assertEquals(2, l.parameterCounter);
   // TODO: These trigger ParameterAttributeChanged
   // p1.setBoundingMethod(Parameter.BoundingMethod.HARD);
   // assertEquals(3, l.parameterCounter);
   // p1.setMinimumValue(0F);
   // assertEquals(4, l.parameterCounter);
   // Changing the value does not trigger the event.
   // The event only happens for metadata, not data.
   // If you want to catch that, use DirtyListener.
   p1.setValue(20F);
   assertEquals(2, l.parameterCounter);
   test.removeParameter("parameter1");
   assertEquals(3, l.parameterCounter);
 }
Example #5
0
 public static Parameter createInputParameter(String name, String datatype) {
   Parameter param = new Parameter();
   param.setInput(true);
   param.setName(name);
   param.setDataType(datatype);
   return param;
 }
  private void generateEvent(final Event event) throws Exception {
    final ClassWriter classWriter =
        new ClassWriter(
            this,
            getSrcGeneratedDirectory(),
            GeneratorHelper.getEventPackage(domain),
            GeneratorHelper.getEventClassName(event));

    if (event.getParameter() != null) {
      for (final Parameter parameter : event.getParameter()) {
        classWriter.addClassMembers(parameter);
      }
    }

    classWriter.addExtend(GeneratorHelper.getBusinessEventExtends(event));

    // Constant
    classWriter.addConstants(
        "public static final com.ponysdk.core.event.Event.Type<"
            + GeneratorHelper.getHandlerClassName(event)
            + "> TYPE = new com.ponysdk.core.event.Event.Type<"
            + GeneratorHelper.getHandlerClassName(event)
            + ">();");

    // Build constructor
    final Parameter sourceComponentParameter = new Parameter();
    sourceComponentParameter.setName("sourceComponent");
    sourceComponentParameter.setClazz("java.lang.Object");
    final List<Parameter> superConstructorParameters = new ArrayList<Parameter>();
    superConstructorParameters.add(sourceComponentParameter);

    final List<Parameter> constructorParameters = new ArrayList<Parameter>(event.getParameter());
    constructorParameters.add(0, sourceComponentParameter);

    final Constructor constructor =
        new Constructor(constructorParameters, superConstructorParameters);
    classWriter.addConstructor(constructor);

    // Build methods
    classWriter.addLine("@Override");
    classWriter.addLine(
        "protected void dispatch(" + GeneratorHelper.getHandlerClassName(event) + " handler) {");
    classWriter.addLine("   handler.on" + event.getName() + "(this);");
    classWriter.addLine("}");
    classWriter.addNewLine();

    classWriter.addLine("@Override");
    classWriter.addLine(
        "public com.ponysdk.core.event.Event.Type<"
            + GeneratorHelper.getHandlerClassName(event)
            + "> getAssociatedType() {");
    classWriter.addLine("   return TYPE;");
    classWriter.addLine("}");

    // Adding
    classWriter.setGenerateGetter(true);
    classWriter.generateContentAndStore();
  }
Example #7
0
  @Test
  public void testGettersAndSetters() {
    Parameter p = new Parameter();
    assertTrue(p.getName() == null);
    assertTrue(p.getValue() == null);

    p.setName("bob");
    p.setValue("val");
    assertTrue(p.getName().equals("bob"));
    assertTrue(p.getValue().equals("val"));
  }
  private ClassWriter generatePushCommandX(final Pushmethod method, final String type)
      throws Exception {
    final String className =
        method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1) + "Command";
    final ClassWriter classWriter =
        new ClassWriter(
            this, getSrcGeneratedDirectory(), GeneratorHelper.getCommandPackage(domain), className);

    final Parameter pushListener = new Parameter();
    pushListener.setName("listener");
    pushListener.setClazz("com.ponysdk.core.command.PushListener<" + type + ">");

    final List<Parameter> parameters = method.getParameter();

    final List<Parameter> clonedParameters = new ArrayList<Parameter>(parameters);
    clonedParameters.add(pushListener);

    final Constructor constructor = new Constructor();
    constructor.setConstructorParameters(clonedParameters);
    constructor.setSuperConstructorParameters(Arrays.asList(pushListener));

    classWriter.addConstructor(constructor);

    for (final Parameter param : parameters) {
      classWriter.addClassMembers(param);
    }
    classWriter.addConstants(
        "private static " + GeneratorHelper.getServiceFullClassName(domain) + " service;");

    final StringBuilder template = new StringBuilder();
    template.append("@Override\n");
    template.append("public com.ponysdk.core.event.HandlerRegistration execute(){\n");
    template.append("   if (service == null) {\n");
    template.append(
        "       service = com.ponysdk.core.service.PonyServiceRegistry.getPonyService("
            + GeneratorHelper.getServiceFullClassName(domain)
            + ".class);");
    template.append("   }\n");
    if (method.getParameter().isEmpty())
      template.append("   return service.%1$sRegistration(this);\n");
    else template.append("   return service.%1$sRegistration(%2$s,this);\n");
    template.append("}\n");

    classWriter.addMethod(
        template.toString(),
        method.getName(),
        GeneratorHelper.getParameterNamesToString(method.getParameter()));

    return classWriter;
  }
Example #9
0
 public Parameter clone() {
   Parameter clone = null;
   try {
     clone = this.getClass().newInstance();
     clone.setParameterList(parameterList);
     clone.setName(getName());
     clone.setValue(value);
   } catch (InstantiationException exception) {
     exception.printStackTrace();
   } catch (IllegalAccessException exception) {
     exception.printStackTrace();
   }
   return clone;
   // Parameter clone = new DefaultParameter(this.processor, this.name);
 }
Example #10
0
 Parameter lookupComponentParameter(String name) {
   Parameter param = null;
   List<Parameter> c = components.get(currentComponent);
   if (c == null) {
     param = new Parameter();
     param.setName(name);
     List<Parameter> l = new ArrayList<Parameter>();
     l.add(param);
     components.put(currentComponent, l);
     return param;
   }
   for (Parameter p : c) {
     if (p.getName().equals(name)) {
       param = p;
       break;
     }
   }
   return param;
 }
Example #11
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here
    Model model;
    String insertstmt;
    String insertmodel = "",
        insertspecies = "",
        insertcompartment = "",
        insertfunction = "",
        insertunitdef = "",
        insertunits = "",
        insertreaction = "",
        insertreactant = "",
        insertproduct = "";
    String insertmodifier = "",
        insertklaw = "",
        insertrules = "",
        insertconstraint = "",
        insertdelay = "",
        inserttrigger = "",
        insertevent = "",
        inserteventassign = "",
        insertparameter = "";
    String insertstatement = "";
    String server, user, password, dbname, filepath;

    String Filedata = "";

    String cwd = System.getProperty("user.dir");

    if (args.length == 0) {
      server = "localhost";
      user = "******";
      password = "******";
      dbname = "sbmldb2";

      /**
       * Path to extract the SBML files from database, where cwd is
       * "github\db2sbml\dbtosbml_standalone_Project\dbtosbml" so add a folder in this directory and
       * mention folder name instead of extractedbm folder
       */
      filepath = cwd + "\\extractedbm\\";
    } else {
      server = args[0];
      user = args[1];
      password = args[2];
      dbname = args[3];
      filepath = args[4];
    }

    try {
      Filedata = readFileAsString(cwd + "\\sbmldbschema.sql");
    } catch (Exception e) {
      e.printStackTrace();
    }

    Mysqlconn sql = new Mysqlconn(server, user, password, dbname);
    // String modelids.getId() = "MorrisonAllegra" ;

    ASTNode math = null;
    int level = 0, version = 0;

    ArrayList<modellist> modelidlist = sql.getmodels();
    insertstatement =
        "LOCK TABLES `model` WRITE,`species` WRITE,`compartment` WRITE,`functiondefinition` WRITE,";
    insertstatement =
        insertstatement
            + "`listofunitdefinitions` WRITE,`listofunits` WRITE,`reaction` WRITE,`simplespeciesreference` WRITE,";
    insertstatement =
        insertstatement
            + "`modifierspeciesreference` WRITE,`kineticlaw` WRITE,`parameter` WRITE,`sbmlconstraint` WRITE,";
    insertstatement =
        insertstatement
            + "`event` WRITE,`sbmltrigger` WRITE,`delay` WRITE,`eventassignment` WRITE,`rules` WRITE"
            + ";";

    for (modellist modelids : modelidlist) {

      ArrayList<modellist> modellevel = sql.getmodeldetails(modelids.getId());

      for (modellist modellv : modellevel) {
        level = modellv.getlevel();
        version = modellv.getversion();
      }

      SBMLDocument doc = new SBMLDocument(level, version);

      ArrayList<modellist> modellists = sql.getmodeldetails(modelids.getId());

      if (!modellists.isEmpty())
        insertmodel =
            insertmodel
                + "\nInsert Into model (id, name,SBML_level,version,notes,annotation) Values";
      for (modellist models : modellists) {
        insertmodel =
            insertmodel
                + "(\'"
                + models.getId()
                + "\',\'"
                + models.getName()
                + "\',"
                + models.getlevel()
                + ","
                + models.getversion()
                + ",\'"
                + models.getnotes()
                + "\',\'"
                + models.getannotation().toString()
                + "\'),";
        model = doc.createModel(models.getId());
        model.setName(models.getName());
        // System.out.println("model : " + models.getId());
        // model.setNotes(models.getnotes());  // there is some null exception is command line run
        // but run perfectly from netbeans so ommented out
        if (!models.getannotation().equals("")) {
          Annotation annot = new Annotation(models.getannotation().toString());
          model.setAnnotation(annot);
        }
        doc.setModel(model);
      }
      if (!modellists.isEmpty()) {
        insertmodel = insertmodel.substring(0, insertmodel.length() - 1);
        insertmodel = insertmodel + ';';
      }
      //   insertmodel = insertmodel + "\nUNLOCK TABLES;";
      //  System.out.println(insertmodel);

      ArrayList<SpeciesList> specieslist = sql.getspecies(modelids.getId());

      if (!specieslist.isEmpty())
        insertspecies =
            insertspecies
                + "\nInsert Into species (id, name, compartment, initialAmount, initialConcentration,substanceUnits,hasOnlySubstanceUnits,boundaryCondition,constant,conversionFactor,model_id,annotation) Values";
      for (SpeciesList species : specieslist) {
        insertspecies =
            insertspecies
                + "(\'"
                + species.getId()
                + "\',\'"
                + species.getName()
                + "\',\'"
                + species.getcompartment()
                + "\',"
                + species.getia()
                + ","
                + species.getic()
                + ",\'"
                + species.getsu()
                + "\',"
                + species.gethosu()
                + ","
                + species.getbc()
                + ","
                + species.getconstant()
                + ","
                + species.getcf()
                + ",\'"
                + modelids.getId()
                + "\',\'"
                + species.getannotation()
                + "\'),";
        Species sp = doc.getModel().createSpecies(species.getId());
        sp.setName(species.getName());
        sp.setCompartment(species.getcompartment());
        sp.setConstant(species.getconstant());
        sp.setInitialAmount(species.getia());
        sp.setInitialConcentration(species.getic());
        sp.setHasOnlySubstanceUnits(species.gethosu());
        if (doc.getModel().getLevel() == 3) sp.setConversionFactor(species.getcf());
        sp.setBoundaryCondition(species.getbc());
        sp.setSubstanceUnits(species.getsu());
        if (!species.getannotation().equals("")) {
          Annotation annot = new Annotation(species.getannotation().toString());
          sp.setAnnotation(annot);
        }
        // doc.getModel().addSpecies(sp) ;
      }
      if (!specieslist.isEmpty()) {
        insertspecies = insertspecies.substring(0, insertspecies.length() - 1);
        insertspecies = insertspecies + ';';
      }

      ArrayList<CompartmentList> complist = sql.getcompartments(modelids.getId());

      if (!complist.isEmpty())
        insertcompartment =
            insertcompartment
                + "\nInsert Into compartment (id, name,constant,model_id,spacialDimensions,size,units) Values";

      for (CompartmentList comp : complist) {
        insertcompartment =
            insertcompartment
                + "(\'"
                + comp.getId()
                + "\',\'"
                + comp.getName()
                + "\',"
                + comp.getconstant()
                + ",\'"
                + modelids.getId()
                + "\',"
                + comp.getspatialdimensions()
                + ","
                + comp.getsize()
                + ","
                + comp.getunits()
                + "\'),";
        Compartment c = doc.getModel().createCompartment(comp.getId());
        c.setName(comp.getName());
        c.setConstant(comp.getconstant());
        c.setSize(comp.getsize());
        c.setSpatialDimensions(comp.getspatialdimensions());
        if (comp.getspatialdimensions() != 0) c.setUnits(comp.getunits());
        // doc.getModel().addSpecies(sp) ;
      }
      if (!complist.isEmpty()) {
        insertcompartment = insertcompartment.substring(0, insertcompartment.length() - 1);
        insertcompartment = insertcompartment + ';';
      }

      ArrayList<functionList> funclist = sql.getfunctions(modelids.getId());

      if (!funclist.isEmpty())
        insertfunction =
            insertfunction + "\nInsert Into functiondefinition (id, xmlns,model_id) Values";

      for (functionList func : funclist) {
        insertfunction =
            insertfunction
                + "(\'"
                + func.getId()
                + "\',\'"
                + func.getxmlns()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        FunctionDefinition fd = doc.getModel().createFunctionDefinition(func.getId());

        try {
          math = ASTNode.parseFormula(func.getxmlns());
          fd.setMath(math);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (!funclist.isEmpty()) {
        insertfunction = insertfunction.substring(0, insertfunction.length() - 1);
        insertfunction = insertfunction + ';';
      }

      ArrayList<unitList> unitlist = sql.getunitlist(modelids.getId());

      if (!unitlist.isEmpty())
        insertunitdef =
            insertunitdef + "\nInsert Into listofunitdefinitions (id,name,model_id) Values";

      for (unitList units : unitlist) {
        insertunitdef =
            insertunitdef
                + "(\'"
                + units.getId()
                + "\',\'"
                + units.getName()
                + "\',\'"
                + modelids.getId()
                + "\'),";

        UnitDefinition ud = doc.getModel().createUnitDefinition(units.getId());
        ud.setName(units.getName());
        ArrayList<unitList> unitdeflist = sql.getunitdef(units.getId());

        if (!unitdeflist.isEmpty())
          insertunits =
              insertunits
                  + "\nInsert Into listofunits (listofunitdefinitions_id,kind, scale,exponent,multiplier) Values";

        for (unitList unitdef : unitdeflist) {
          insertunits =
              insertunits
                  + "(\'"
                  + units.getId()
                  + "\',\'"
                  + unitdef.getkind()
                  + "\',"
                  + unitdef.getscale()
                  + ","
                  + unitdef.getexponent()
                  + ","
                  + unitdef.getmultiplier()
                  + "),";
          Unit u = ud.createUnit(Unit.Kind.valueOf(unitdef.getkind()));
          u.setScale(unitdef.getscale());
          u.setExponent(unitdef.getexponent());
          u.setMultiplier(unitdef.getmultiplier());
        }
        // doc.getModel().addSpecies(sp) ;
        if (!unitdeflist.isEmpty()) {
          insertunits = insertunits.substring(0, insertunits.length() - 1);
          insertunits = insertunits + ';';
        }
      }
      if (!unitlist.isEmpty()) {
        insertunitdef = insertunitdef.substring(0, insertunitdef.length() - 1);
        insertunitdef = insertunitdef + ';';
      }

      ArrayList<reactionList> reactionlist = sql.getreactons(modelids.getId());

      if (!reactionlist.isEmpty())
        insertreaction =
            insertreaction
                + "\nInsert Into reaction (id,name, reversible,fast,model_id,compartment,annotation) Values";

      for (reactionList reaction : reactionlist) {
        insertreaction =
            insertreaction
                + "(\'"
                + reaction.getId()
                + "\',\'"
                + reaction.getName()
                + "\',"
                + reaction.getreversible()
                + ","
                + reaction.getfast()
                + ",\'"
                + modelids.getId()
                + "\',\'"
                + reaction.getcompartment()
                + "\',\'"
                + reaction.getannotation()
                + "\'),";
        Reaction rn = doc.getModel().createReaction(reaction.getId());
        rn.setName(reaction.getName());
        if (doc.getModel().getLevel() == 3) rn.setCompartment(reaction.getcompartment());
        rn.setFast(reaction.getfast());
        rn.setReversible(reaction.getreversible());
        if (!reaction.getannotation().equals("")) {
          Annotation annot = new Annotation(reaction.getannotation().toString());
          rn.setAnnotation(annot);
        }

        ArrayList<reactionList> reactantlist = sql.getreactants(reaction.getId());

        if (!reactantlist.isEmpty())
          insertreactant =
              insertreactant
                  + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,speciestype,constant) Values";
        for (reactionList reactant : reactantlist) {
          insertreactant =
              insertreactant
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + reactant.getspecies()
                  + "\',\'"
                  + reactant.getsboTerm()
                  + "\',"
                  + reactant.getstoichometry()
                  + ","
                  + reactant.getconstant()
                  + ",\'reactants\'),";
          SpeciesReference rt = new SpeciesReference();
          rt.setName(reactant.getspecies());
          rt.setSpecies(reactant.getspecies());
          // rt.setSBOTerm(reactant.getsboTerm());
          rt.setStoichiometry(reactant.getstoichometry());
          //    rt.setConstant(reactant.getconstant());
          rn.addReactant(rt);
        }
        if (!reactantlist.isEmpty()) {
          insertreactant = insertreactant.substring(0, insertreactant.length() - 1);
          insertreactant = insertreactant + ';';
        }

        ArrayList<reactionList> productlist = sql.getproducts(reaction.getId());

        if (!productlist.isEmpty())
          insertproduct =
              insertproduct
                  + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,constant,speciestype) Values";
        for (reactionList product : productlist) {
          insertproduct =
              insertproduct
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + product.getspecies()
                  + "\',\'"
                  + product.getsboTerm()
                  + "\',"
                  + product.getstoichometry()
                  + ","
                  + product.getconstant()
                  + ",\'products\'),";
          SpeciesReference pr = new SpeciesReference();
          pr.setName(product.getspecies());
          pr.setSpecies(product.getspecies());
          //   pr.setSBOTerm(product.getsboTerm());
          pr.setStoichiometry(product.getstoichometry());
          //    pr.setConstant(product.getconstant());
          rn.addProduct(pr);
        }
        if (!productlist.isEmpty()) {
          insertproduct = insertproduct.substring(0, insertproduct.length() - 1);
          insertproduct = insertproduct + ';';
        }

        ArrayList<reactionList> modifierlist = sql.getmodifiers(reaction.getId());

        if (!modifierlist.isEmpty())
          insertmodifier =
              insertmodifier
                  + "\nInsert Into modifierspeciesreference (reaction_id,species, sboTerm,speciestype) Values";
        for (reactionList modifier : modifierlist) {
          insertmodifier =
              insertmodifier
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + modifier.getspecies()
                  + "\',\'"
                  + modifier.getsboTerm()
                  + "\',\'modifiers\'),";
          ModifierSpeciesReference m = new ModifierSpeciesReference();
          m.setName(modifier.getspecies());
          m.setSpecies(modifier.getspecies());
          //    m.setSBOTerm(modifier.getsboTerm());
          rn.addModifier(m);
        }
        if (!modifierlist.isEmpty()) {
          insertmodifier = insertmodifier.substring(0, insertmodifier.length() - 1);
          insertmodifier = insertmodifier + ';';
        }

        ArrayList<reactionList> klawlist = sql.getkineticlaws(reaction.getId());

        if (!klawlist.isEmpty())
          insertklaw =
              insertklaw + "\nInsert Into kineticlaw (reaction_id,kid, math,annotation) Values";
        for (reactionList klaw : klawlist) {
          insertklaw =
              insertklaw
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + klaw.getId()
                  + "\',\'"
                  + klaw.getmath()
                  + "\',\'"
                  + klaw.getannotation()
                  + "\'),";
          KineticLaw kl = rn.createKineticLaw();
          try {
            math = ASTNode.parseFormula(klaw.getmath());
            kl.setMath(math);
            if (!klaw.getannotation().equals("")) {
              Annotation annot = new Annotation(klaw.getannotation().toString());
              kl.setAnnotation(annot);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!klawlist.isEmpty()) {
          insertklaw = insertklaw.substring(0, insertklaw.length() - 1);
          insertklaw = insertklaw + ';';
        }
      }
      if (!reactionlist.isEmpty()) {
        insertreaction = insertreaction.substring(0, insertreaction.length() - 1);
        insertreaction = insertreaction + ';';
      }

      ArrayList<parameterList> paralist = sql.getparameters(modelids.getId());

      if (!paralist.isEmpty())
        insertparameter =
            insertparameter
                + "\nInsert Into parameter (id,name,value,units,constant,model_id) Values";

      for (parameterList para : paralist) {
        insertparameter =
            insertparameter
                + "(\'"
                + para.getId()
                + "\',\'"
                + para.getName()
                + "\',"
                + para.getvalue()
                + ","
                + para.getunits()
                + ","
                + para.getconstant()
                + ",\'"
                + modelids.getId()
                + "\'),";
        Parameter par = doc.getModel().createParameter(para.getId());
        par.setName(para.getId());
        par.setConstant(para.getconstant());
        par.setUnits(para.getunits());
        par.setValue(para.getvalue());
      }
      if (!paralist.isEmpty()) {
        insertparameter = insertparameter.substring(0, insertparameter.length() - 1);
        insertparameter = insertparameter + ';';
      }

      ArrayList<constraintList> conslist = sql.getconstraints(modelids.getId());

      if (!conslist.isEmpty())
        insertconstraint =
            insertconstraint + "\nInsert Into sbmlconstraint (math,message,model_id) Values";

      for (constraintList constraint : conslist) {
        insertconstraint =
            insertconstraint
                + "(\'"
                + constraint.getmath()
                + "\',\'"
                + constraint.getmessage()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        Constraint cons = doc.getModel().createConstraint();
        try {
          math = ASTNode.parseFormula(constraint.getmath());
          cons.setMath(math);
          cons.setMessage(constraint.getmessage());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (!conslist.isEmpty()) {
        insertconstraint = insertconstraint.substring(0, insertconstraint.length() - 1);
        insertconstraint = insertconstraint + ';';
      }

      ArrayList<eventsList> eventlist = sql.getevents(modelids.getId());

      if (!eventlist.isEmpty())
        insertevent =
            insertevent + "\nInsert Into event (id,name,UseValuesFromTriggerTime,model_id) Values";

      for (eventsList events : eventlist) {
        insertevent =
            insertevent
                + "(\'"
                + events.getId()
                + "\',\'"
                + events.getName()
                + "\',"
                + events.getuservalues()
                + ",\'"
                + modelids.getId()
                + "\'),";
        Event ev = doc.getModel().createEvent(events.getId());
        ev.setName(events.getName());
        // ev.setUseValuesFromTriggerTime(events.getuservalues());

        ArrayList<eventsList> triggerlist = sql.gettriggers(events.getId());

        if (!triggerlist.isEmpty())
          inserttrigger =
              inserttrigger
                  + "\nInsert Into sbmltrigger (event_id,initialvalue,persisent,math) Values";
        for (eventsList triggers : triggerlist) {
          Trigger tr = doc.getModel().createTrigger();
          try {
            math = ASTNode.parseFormula(triggers.getmath());
            tr.setMath(math);
            tr.setInitialValue(triggers.getinitialval());
            tr.setPersistent(triggers.getpersistent());
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!triggerlist.isEmpty()) {
          inserttrigger = inserttrigger.substring(0, insertmodel.length() - 1);
          inserttrigger = inserttrigger + ';';
        }

        ArrayList<eventsList> delaylist = sql.getdelays(events.getId());

        if (!delaylist.isEmpty())
          insertdelay = insertdelay + "\nInsert Into delay (event_id,math) Values";
        for (eventsList delays : delaylist) {
          Delay d = doc.getModel().createDelay();
          try {
            math = ASTNode.parseFormula(delays.getmath());
            d.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!delaylist.isEmpty()) {
          insertdelay = insertdelay.substring(0, insertdelay.length() - 1);
          insertdelay = insertdelay + ';';
        }

        ArrayList<eventsList> evasslist = sql.geteventassignments(events.getId());

        if (!evasslist.isEmpty())
          inserteventassign =
              inserteventassign + "\nInsert Into eventassignment (event_id,variable,math) Values";
        for (eventsList evassign : evasslist) {
          EventAssignment ea = doc.getModel().createEventAssignment();
          try {
            math = ASTNode.parseFormula(evassign.getmath());
            ea.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!evasslist.isEmpty()) {
          inserteventassign = inserteventassign.substring(0, inserteventassign.length() - 1);
          inserteventassign = inserteventassign + ';';
        }
      }
      if (!eventlist.isEmpty()) {
        insertevent = insertevent.substring(0, insertevent.length() - 1);
        insertevent = insertevent + ';';
      }

      ArrayList<ruleslist> rulelist = sql.getrules(modelids.getId());

      if (!rulelist.isEmpty())
        insertrules = insertrules + "\nInsert Into rules (id,math,ruletype,model_id) Values";
      for (ruleslist rules : rulelist) {
        insertrules =
            insertrules
                + "(\'"
                + rules.getId()
                + "\',\'"
                + rules.getmath()
                + "\',\'"
                + rules.getruletype()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        if (rules.getruletype().equals("assignmentrule")) {
          Rule r = doc.getModel().createAssignmentRule();
          r.setMetaId(rules.getId());
          try {
            math = ASTNode.parseFormula(rules.getmath());
            r.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      if (!rulelist.isEmpty()) {
        insertrules = insertrules.substring(0, insertrules.length() - 1);
        insertrules = insertrules + ';';
      }

      SBMLWriter writer = new SBMLWriter();
      try {
        String Path = filepath + modelids.getId() + ".xml";
        writer.write(doc, Path);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(Path);
        Element root = document.getDocumentElement();
        Element newdataset = document.createElement("dataset");
        root.appendChild(newdataset);

        ArrayList<dataset> datasetlist = sql.getdataset(modelids.getId());
        for (dataset ds : datasetlist) {
          // System.out.println(ds.getexpcond());

          Element name = document.createElement("experimentalcondition");
          name.setAttribute("bioelement", ds.getbioel());
          name.setAttribute("name", ds.getName());
          name.setAttribute("descr", ds.getdescr());
          name.setAttribute("expcond", ds.getexpcond());
          name.setAttribute("value", String.valueOf(ds.getvalue()));
          name.setAttribute("type", ds.gettype());
          name.setAttribute("uri", ds.geturi());
          newdataset.appendChild(name);
        }

        root.appendChild(newdataset);
        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        StreamResult result = new StreamResult(filepath + modelids.getId() + "d.xml");
        transformer.transform(source, result);
        System.out.println(
            "Files : "
                + modelids.getId()
                + ".xml and "
                + modelids.getId()
                + "d.xml have been generated successfully !!!");

      } catch (Exception e) {
        e.printStackTrace();
      }

      insertstatement =
          insertstatement
              + "\n\n"
              + insertmodel
              + "\n"
              + insertspecies
              + "\n"
              + insertcompartment
              + "\n"
              + insertfunction;
      insertstatement =
          insertstatement
              + "\n"
              + insertparameter
              + "\n"
              + insertreaction
              + "\n"
              + insertreactant
              + "\n"
              + insertproduct;
      insertstatement =
          insertstatement
              + "\n"
              + insertmodifier
              + "\n"
              + insertklaw
              + "\n"
              + insertunitdef
              + "\n"
              + insertunits;
      insertstatement =
          insertstatement
              + "\n"
              + insertrules
              + "\n"
              + insertconstraint
              + "\n"
              + insertevent
              + "\n"
              + inserttrigger
              + "\n"
              + insertdelay
              + "\n"
              + inserteventassign;

      insertcompartment = "";
      insertmodel = "";
      insertspecies = "";

      // System.out.println("document : " + doc);
    }
    insertstatement = insertstatement + "\nUNLOCK TABLES;";
    Filedata = Filedata + "\n\n\n" + insertstatement;

    try {
      wrtireStringToFile(Filedata, filepath + "sbmldb.sql");
    } catch (IOException e) {
      e.printStackTrace();
    }
    // System.out.println(insertstatement);
  }
Example #12
0
  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {

    tags.add(qName);
    if (debug) {
      System.out.println("Start Element: " + qName + " parent: " + getParent());
    }
    dumpAttrs(attributes);
    lastText = "";

    if (qName.equalsIgnoreCase("object")
        && (getParent().equals("model") || getParent().equals("component"))) {
      pushHandler(new ObjectHandler(isService));
    } else if (qName.equalsIgnoreCase(ParamHandler.TOP_TAG)
        && getParent().equals("object")
        && !isAnyChildOf("profile")) {
      ObjectHandler oh = (ObjectHandler) getHandler();
      pushHandler(new ParamHandler((oh != null ? oh.getParam().getName() : "")));
    } else if (qName.equalsIgnoreCase(DatatypeHandler.TOP_TAG)
        && getParent().equals("dm:document")) {
      pushHandler(new DatatypeHandler());
    } else if (qName.equalsIgnoreCase(BibiliographyHandler.TOP_TAG)
        && getParent().equals("dm:document")) {
      pushHandler(new BibiliographyHandler());
    } else if (qName.equalsIgnoreCase("component")) {
      if (getParent().equals("import")) {
        String n = attributes.getValue("name");
        dumpTags();
        if (n != null) {
          // TODO really import or maybe do nothing
        }
      } else if (getParent().equals("model")) {
        dumpTags();
        String path = attributes.getValue("path");
        String ref = attributes.getValue("ref");
        if (ref != null && path != null) {
          List<Parameter> cs = components.get(ref);
          if (cs != null) {
            for (Parameter p : cs) {
              // copy parameters
              Parameter pc = p.clone();
              pc.setName(path + pc.getName());
              Parameter.Add(pc);
            }
          }
        }
      } else {
        dumpTags();
        currentComponent = attributes.getValue("name");
        pushHandler(new ComponentHandler());
      }
    } else if (qName.equalsIgnoreCase("model")) {
      try {
        isService = attributes.getValue("isService").equals("true");
      } catch (NullPointerException e) {
      }
      Model.setName(attributes.getValue("name"));
    } else if (qName.equalsIgnoreCase("import")) {
      String fname = attributes.getValue("file");
      InputStream is = streamProvider.getStream(dirDefault + fname);
      if (is == null) {
        String fnameBase = fname.substring(0, fname.length() - 4);
        fname = fnameBase + "-0.xml";
        is = streamProvider.getStream(dirDefault + fname);
      }

      try {
        Parse(is, fname);
      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("EXCEPTION: (import " + fname + ") " + e.getMessage());
      }
    } else if (qName.equalsIgnoreCase("profile")) {
      pushHandler(new NullHandler(qName));
    } else if (getParent().equals("")) {
      handlers.clear();
    } else {
    }

    DefaultHandler h = getHandler();
    if (h != null) {
      h.startElement(uri, localName, qName, attributes);
    }
  }
  private ClassWriter generateCommandX(final Method method, final String resultClass)
      throws Exception {
    final String className =
        method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1) + "Command";

    final ClassWriter classWriter =
        new ClassWriter(
            this, getSrcGeneratedDirectory(), GeneratorHelper.getCommandPackage(domain), className);

    final Constructor constructor = new Constructor();
    final Parameter eventBusParameter = new Parameter();
    eventBusParameter.setName("eventBus");
    eventBusParameter.setClazz("com.ponysdk.core.event.EventBus");

    final List<Parameter> parameters = method.getParameter();
    final List<Parameter> clonedParameters = new ArrayList<Parameter>();
    for (final Parameter parameter : parameters) {
      final Parameter clonedParameter = new Parameter();
      clonedParameter.setClazz(parameter.getClazz());
      clonedParameter.setName(parameter.getName());
      clonedParameter.setCollection(parameter.getCollection());
      clonedParameters.add(clonedParameter);
    }

    final Constructor constructor2 = new Constructor();
    constructor2.setConstructorParameters(new ArrayList<Parameter>(clonedParameters));

    clonedParameters.add(0, eventBusParameter);
    constructor.setConstructorParameters(clonedParameters);
    constructor.setSuperConstructorParameters(Arrays.asList(eventBusParameter));

    classWriter.addConstructor(constructor);
    classWriter.addConstructor(constructor2);

    for (final Parameter param : parameters) {
      classWriter.addClassMembers(param);
    }
    classWriter.addConstants(
        "private static " + GeneratorHelper.getServiceFullClassName(domain) + " service;");

    final StringBuilder template = new StringBuilder();
    template.append("@Override\n");
    if (resultClass.equals("void") && method.getReturn().getValue() == null) {
      template.append("protected java.lang.Void  execute0() throws Exception {\n");
    } else {
      template.append("protected " + resultClass + " execute0() throws Exception {\n");
    }
    template.append("   if (service == null) {\n");
    template.append(
        "       service = com.ponysdk.core.service.PonyServiceRegistry.getPonyService("
            + GeneratorHelper.getServiceFullClassName(domain)
            + ".class);");
    template.append("   }\n");
    if (resultClass.equals("void") && method.getReturn().getValue() == null) {
      template.append("	service.%1$s(%2$s);\n");
      template.append("	return null;\n");
    } else {
      template.append("	return service.%1$s(%2$s);\n");
    }
    template.append("}\n");

    classWriter.addMethod(
        template.toString(),
        method.getName(),
        GeneratorHelper.getParameterNamesToString(method.getParameter()));

    return classWriter;
  }
  private void generateCRUDMethos() throws Exception {
    // Insert CRUD methods
    if (domain.getService() != null && domain.getService().getCrudmethod() != null) {
      // Return
      final Return crudReturn = new Return();
      crudReturn.setClazz(domain.getService().getCrudmethod().getClazz());
      // Parameters
      final Parameter crudParameter = new Parameter();
      crudParameter.setClazz(domain.getService().getCrudmethod().getClazz());
      crudParameter.setName(GeneratorHelper.getFirstCharToLower(domain.getName()));
      final Parameter crudIDParameter = new Parameter();
      crudIDParameter.setClazz("long");
      crudIDParameter.setName(GeneratorHelper.getFirstCharToLower(domain.getName()) + "ID");

      // Add CRUD methods
      final Method createMethod =
          createCRUDMethod("create" + domain.getName(), crudParameter, crudReturn);
      final Method readMethod =
          createCRUDMethod("read" + domain.getName(), crudIDParameter, crudReturn);
      final Method updateMethod =
          createCRUDMethod("update" + domain.getName(), crudParameter, crudReturn);
      final Method deleteMethod =
          createCRUDMethod("delete" + domain.getName(), crudIDParameter, new Return());

      // Create the implementation class of these CRUD methods if the HibernateDAO is set
      if (domain.getService().getDao() != null) {
        final ClassWriter classWriter =
            new ClassWriter(
                this,
                getSrcGeneratedDirectory(),
                GeneratorHelper.getServerServicePackage(domain),
                GeneratorHelper.getServiceImplClassName(domain));

        classWriter.addImplements(GeneratorHelper.getServiceClassName(domain));
        classWriter.setGenerateGetter(true);
        classWriter.setGenerateSetter(true);

        // Add static logger
        classWriter.addConstants(
            "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("
                + GeneratorHelper.getServiceImplClassName(domain)
                + ".class);");

        // Add service HibernateDAO object
        final Parameter daoParameter = new Parameter();
        daoParameter.setClazz(
            GeneratorHelper.getDAOPackage(domain) + "." + GeneratorHelper.getDAOClassName(domain));
        daoParameter.setName(
            GeneratorHelper.getFirstCharToLower(GeneratorHelper.getDAOClassName(domain)));
        classWriter.addClassMembers(daoParameter);

        for (final Method method : domain.getService().getMethod()) {
          final String resultClass = GeneratorHelper.getClassName(method.getReturn());

          classWriter.addNewLine();
          classWriter.addLine("@Override");
          classWriter.addLine(
              "public "
                  + resultClass
                  + " "
                  + method.getName()
                  + "("
                  + GeneratorHelper.getParameterToString(method.getParameter())
                  + ") throws Exception {");
          if (!"void".equals(resultClass)) {
            classWriter.addLine("   return null;");
          }
          classWriter.addLine("}");
        }

        final String domainClass = domain.getName();
        final String domainDAOParameter =
            GeneratorHelper.getFirstCharToLower(GeneratorHelper.getDAOClassName(domain));
        final String domainParameter = GeneratorHelper.getFirstCharToLower(domain.getName());
        final String domainParameterID = domainParameter + "ID";

        /*
         * CRUD method implementation
         */

        // Create
        classWriter.addLine("@Override");
        classWriter.addLine(
            "public "
                + GeneratorHelper.getClassName(createMethod.getReturn())
                + " "
                + createMethod.getName()
                + " ("
                + GeneratorHelper.getParameterToString(createMethod.getParameter())
                + ")  throws Exception {");
        classWriter.addLine("   " + domainDAOParameter + ".beginTransaction();");
        classWriter.addLine("   try {");
        classWriter.addLine("       " + domainDAOParameter + ".save(" + domainParameter + ");");
        classWriter.addLine("       " + domainDAOParameter + ".commit();");
        classWriter.addLine("   } catch (final Exception e) {");
        classWriter.addLine(
            "       log.error(\"final Cannot create " + domainClass + " in database\", e);");
        classWriter.addLine("       " + domainDAOParameter + ".rollback();");
        classWriter.addLine(
            "       throw new Exception(\"Cannot create " + domainClass + " in database\", e);");
        classWriter.addLine("   }");
        classWriter.addLine("   return " + domainParameter + ";");
        classWriter.addLine("}");

        // Read
        classWriter.addLine("@Override");
        classWriter.addLine(
            "public "
                + GeneratorHelper.getClassName(createMethod.getReturn())
                + " "
                + readMethod.getName()
                + " ("
                + GeneratorHelper.getParameterToString(readMethod.getParameter())
                + ")  throws Exception {");
        classWriter.addLine(
            "   "
                + GeneratorHelper.getClassName(createMethod.getReturn())
                + " "
                + domainParameter
                + " = null;");
        classWriter.addLine("   " + domainDAOParameter + ".beginTransaction();");
        classWriter.addLine("   try {");
        classWriter.addLine(
            "       "
                + domainParameter
                + " = "
                + domainDAOParameter
                + ".findById("
                + domainParameterID
                + ");");
        classWriter.addLine("       " + domainDAOParameter + ".commit();");
        classWriter.addLine("   } catch (final Exception e) {");
        classWriter.addLine(
            "       log.error(\"final Cannot find " + domain.getName() + " in database\", e);");
        classWriter.addLine("       " + domainDAOParameter + ".rollback();");
        classWriter.addLine(
            "       throw new Exception(\"Cannot find " + domain.getName() + " in database\", e);");
        classWriter.addLine("   }");
        classWriter.addLine("   return " + domainParameter + ";");
        classWriter.addLine("}");

        // Update
        classWriter.addLine("@Override");
        classWriter.addLine(
            "public "
                + GeneratorHelper.getClassName(updateMethod.getReturn())
                + " "
                + updateMethod.getName()
                + " ("
                + GeneratorHelper.getParameterToString(updateMethod.getParameter())
                + ")  throws Exception {");
        classWriter.addLine("   " + domainDAOParameter + ".beginTransaction();");
        classWriter.addLine("   try {");
        classWriter.addLine(
            "       " + domainDAOParameter + ".saveOrUpdate(" + domainParameter + ");");
        classWriter.addLine("       " + domainDAOParameter + ".commit();");
        classWriter.addLine("   } catch (final Exception e) {");
        classWriter.addLine(
            "       log.error(\"final Cannot update " + domainClass + " in database\", e);");
        classWriter.addLine("       " + domainDAOParameter + ".rollback();");
        classWriter.addLine(
            "       throw new Exception(\"Cannot update " + domainClass + " in database\", e);");
        classWriter.addLine("   }");
        classWriter.addLine("   return " + domainParameter + ";");
        classWriter.addLine("}");

        // Delete
        classWriter.addLine("@Override");
        classWriter.addLine(
            "public "
                + GeneratorHelper.getClassName(deleteMethod.getReturn())
                + " "
                + deleteMethod.getName()
                + " ("
                + GeneratorHelper.getParameterToString(deleteMethod.getParameter())
                + ")  throws Exception {");
        classWriter.addLine("   " + domainDAOParameter + ".beginTransaction();");
        classWriter.addLine("   try {");
        classWriter.addLine(
            "       "
                + GeneratorHelper.getClassName(createMethod.getReturn())
                + " "
                + domainParameter
                + " = "
                + domainDAOParameter
                + ".findById("
                + domainParameterID
                + ");");
        classWriter.addLine("       " + domainDAOParameter + ".delete(" + domainParameter + ");");
        classWriter.addLine("       " + domainDAOParameter + ".commit();");
        classWriter.addLine("   } catch (final Exception e) {");
        classWriter.addLine(
            "       log.error(\"final Cannot delete " + domain.getName() + " in database\", e);");
        classWriter.addLine("       " + domainDAOParameter + ".rollback();");
        classWriter.addLine(
            "       throw new Exception(\"Cannot delete "
                + domain.getName()
                + " in database\", e);");
        classWriter.addLine("   }");
        classWriter.addLine("}");

        classWriter.generateContentAndStore();
      }

      domain.getService().getMethod().add(createMethod);
      domain.getService().getMethod().add(readMethod);
      domain.getService().getMethod().add(updateMethod);
      domain.getService().getMethod().add(deleteMethod);
    }
  }
  /*
   * Services : MongoDBDAO
   */
  private void generateMongoDBDAO(final Dao dao) throws Exception {
    final ClassWriter classWriter =
        new ClassWriter(
            this,
            getSrcGeneratedDirectory(),
            GeneratorHelper.getDAOPackage(domain),
            GeneratorHelper.getDAOClassName(domain));

    classWriter.addImport("com.fasterxml.jackson.databind.ObjectMapper");
    classWriter.addImport("com.mongodb.BasicDBObject");
    classWriter.addImport("com.mongodb.DBCollection");
    classWriter.addImport("com.mongodb.DBObject");
    classWriter.addImport("com.mongodb.DBCursor");
    classWriter.addImport("java.util.List");
    classWriter.addImport("java.util.ArrayList");

    classWriter.addExtend("com.ponysdk.mongodb.dao.MongoDAO");

    // Add static logger
    classWriter.addConstants(
        "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("
            + GeneratorHelper.getDAOClassName(domain)
            + ".class);");

    // Create constructor
    final List<Parameter> parameters = new ArrayList<Parameter>();
    final Parameter sessionFactoryParameter = new Parameter();
    sessionFactoryParameter.setName("sessionFactory");
    sessionFactoryParameter.setClazz("org.hibernate.SessionFactory");
    // parameters.add(sessionFactoryParameter);
    final Constructor constructor = new Constructor(parameters, parameters);
    classWriter.addConstructor(constructor);

    // Create findById method
    classWriter.addNewLine();
    classWriter.addLine("final public " + dao.getClazz() + " findById(final long id) {");
    classWriter.addLine("   if (log.isDebugEnabled()) {");
    classWriter.addLine(
        "       log.debug(\"getting " + domain.getName() + " instance with id: \" + id);");
    classWriter.addLine("   }");
    classWriter.addNewLine();
    classWriter.addLine("   try {");

    classWriter.addLine(
        "       DBCollection collection = db.getCollection(\""
            + domain.getName().toLowerCase()
            + "\");");
    classWriter.addLine("       BasicDBObject basicDBObject = new BasicDBObject(\"id\"," + "id);");
    classWriter.addLine("       final DBObject foundInstance = collection.findOne(basicDBObject);");
    classWriter.addLine("       " + dao.getClazz() + " instance = null;");
    classWriter.addLine("       return toModel(foundInstance);");
    classWriter.addLine("   } catch (final Exception re) {");
    classWriter.addLine("       log.error(\"getting " + domain.getName() + " by id failed\", re);");
    classWriter.addLine("       throw new RuntimeException(re);");
    classWriter.addLine("   }");
    classWriter.addLine("}");

    classWriter.addLine("private " + dao.getClazz() + " toModel(DBObject dbObject) {");
    classWriter.addLine("   if (dbObject == null) return null;");
    classWriter.addLine("   final ObjectMapper mapper = new ObjectMapper();");
    classWriter.addLine("   try{");
    classWriter.addLine(
        "       "
            + dao.getClazz()
            + " model = mapper.readValue(dbObject.toString(), "
            + dao.getClazz()
            + ".class);");
    classWriter.addLine("       model.setID(dbObject.get(\"_id\"));");
    classWriter.addLine("       return model;");
    classWriter.addLine("   } catch (final Exception e) {");
    classWriter.addLine("       log.error(\"toModel " + domain.getName() + " failed\", e);");
    classWriter.addLine("       throw new RuntimeException(e);");
    classWriter.addLine("   }");
    classWriter.addLine("}");

    // Create findAll method
    classWriter.addNewLine();
    classWriter.addLine("@SuppressWarnings(\"unchecked\")");
    classWriter.addLine("public java.util.List<" + dao.getClazz() + "> findAll() {");
    classWriter.addLine("   if (log.isDebugEnabled()) {");
    classWriter.addLine("       log.debug(\"finding all " + domain.getName() + "\");");
    classWriter.addLine("   }");
    classWriter.addNewLine();
    classWriter.addLine("   DBCursor cursor = null;");
    classWriter.addLine("   try {");
    classWriter.addLine(
        "       DBCollection collection = db.getCollection(\""
            + domain.getName().toLowerCase()
            + "\");");
    classWriter.addLine("       cursor = collection.find();");
    classWriter.addLine(
        "       List<" + dao.getClazz() + "> result = new ArrayList<" + dao.getClazz() + ">();");
    classWriter.addLine("       while(cursor.hasNext()){");
    classWriter.addLine("           result.add(toModel(cursor.next()));");
    classWriter.addLine("       }");
    classWriter.addLine("       return result;");
    classWriter.addLine("   } catch (final RuntimeException re) {");
    classWriter.addLine("       log.error(\"finding all " + domain.getName() + " failed\", re);");
    classWriter.addLine("       throw re;");
    classWriter.addLine("   } finally{");
    classWriter.addLine("       cursor.close();");
    classWriter.addLine("   }");
    classWriter.addLine("}");

    // Create find by query method
    classWriter.addNewLine();
    classWriter.addLine("@SuppressWarnings(\"unchecked\")");
    classWriter.addLine("@Override");
    classWriter.addLine("public java.util.List<" + dao.getClazz() + "> find(Object query) {");
    classWriter.addLine("   if (log.isDebugEnabled()) {");
    classWriter.addLine("       log.debug(\"finding " + domain.getName() + "  by query\");");
    classWriter.addLine("   }");
    classWriter.addNewLine();
    classWriter.addLine("   DBCursor cursor = null;");
    classWriter.addLine("   try {");
    classWriter.addLine(
        "       DBCollection collection = db.getCollection(\""
            + domain.getName().toLowerCase()
            + "\");");
    classWriter.addLine("       cursor = collection.find((DBObject)query);");
    classWriter.addLine(
        "       List<" + dao.getClazz() + "> result = new ArrayList<" + dao.getClazz() + ">();");
    classWriter.addLine("       while(cursor.hasNext()){");
    classWriter.addLine("           result.add(toModel(cursor.next()));");
    classWriter.addLine("       }");
    classWriter.addLine("       return result;");
    classWriter.addLine("   } catch (final RuntimeException re) {");
    classWriter.addLine("       log.error(\"find " + domain.getName() + " failed\", re);");
    classWriter.addLine("       throw re;");
    classWriter.addLine("   } finally{");
    classWriter.addLine("       cursor.close();");
    classWriter.addLine("   }");
    classWriter.addLine("}");

    classWriter.generateContentAndStore();
  }
  private void generateHibernateDAO(final Dao dao) throws Exception {
    final ClassWriter classWriter =
        new ClassWriter(
            this,
            getSrcGeneratedDirectory(),
            GeneratorHelper.getDAOPackage(domain),
            GeneratorHelper.getDAOClassName(domain));

    classWriter.addExtend("com.ponysdk.hibernate.dao.HibernateDAO");

    // Add static logger
    classWriter.addConstants(
        "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger("
            + GeneratorHelper.getDAOClassName(domain)
            + ".class);");

    // Create constructor
    final List<Parameter> parameters = new ArrayList<Parameter>();
    final Parameter sessionFactoryParameter = new Parameter();
    sessionFactoryParameter.setName("sessionFactory");
    sessionFactoryParameter.setClazz("org.hibernate.SessionFactory");
    parameters.add(sessionFactoryParameter);
    final Constructor constructor = new Constructor(parameters, parameters);
    classWriter.addConstructor(constructor);

    // Create findById method
    classWriter.addNewLine();
    classWriter.addLine("final public " + dao.getClazz() + " findById(final long id) {");
    classWriter.addLine("   if (log.isDebugEnabled()) {");
    classWriter.addLine(
        "       log.debug(\"getting " + domain.getName() + " instance with id: \" + id);");
    classWriter.addLine("   }");
    classWriter.addNewLine();
    classWriter.addLine("   try {");
    classWriter.addLine(
        "       "
            + dao.getClazz()
            + " instance = ("
            + dao.getClazz()
            + ") sessionFactory.getCurrentSession().get("
            + dao.getClazz()
            + ".class, id);");
    classWriter.addLine("       return instance;");
    classWriter.addLine("   } catch (final RuntimeException re) {");
    classWriter.addLine("       log.error(\"getting " + domain.getName() + " by id failed\", re);");
    classWriter.addLine("       throw re;");
    classWriter.addLine("   }");
    classWriter.addLine("}");

    // Create findAll method
    classWriter.addNewLine();
    classWriter.addLine("@SuppressWarnings(\"unchecked\")");
    classWriter.addLine("public java.util.List<" + dao.getClazz() + "> findAll() {");
    classWriter.addLine("   if (log.isDebugEnabled()) {");
    classWriter.addLine(
        "       log.debug(\"finding " + domain.getName() + " instance by example\");");
    classWriter.addLine("   }");
    classWriter.addNewLine();
    classWriter.addLine("   try {");
    classWriter.addLine(
        "       final java.util.List<"
            + dao.getClazz()
            + "> results = sessionFactory.getCurrentSession().createQuery(\"FROM "
            + domain.getName()
            + "\").list();");
    classWriter.addLine("       return results;");
    classWriter.addLine("   } catch (final RuntimeException re) {");
    classWriter.addLine("       log.error(\"finding all " + domain.getName() + " failed\", re);");
    classWriter.addLine("       throw re;");
    classWriter.addLine("   }");
    classWriter.addLine("}");

    classWriter.generateContentAndStore();
  }