Exemplo n.º 1
0
 private QConClass classConstraint() {
   if (i_constraints.size() != 1) {
     return null;
   }
   Constraint constr = singleConstraint();
   if (constr.getClass() != QConClass.class) {
     return null;
   }
   return (QConClass) constr;
 }
Exemplo n.º 2
0
 /* process the list of pending constraints */
 protected void processWorklist() {
   int iter = 0;
   while (!w.isEmpty()) {
     int size = w.size();
     Constraint c = w.removeFirst();
     c.accept(this);
     size -= w.size();
     iter++;
   }
 }
Exemplo n.º 3
0
 /**
  * Helper function. Add a new state, if it does not already exist, and returns its index.
  *
  * @param loc1: Index of location of PTA 1
  * @param loc2: Index of location of PTA 2
  */
 private int addState(int loc1, int loc2) {
   // See if this is a new state
   IndexPair stateNew = new IndexPair(loc1, loc2);
   if (states.add(stateNew)) {
     // If so, add to the explore list
     explore.add(stateNew);
     // Get index of state in state set
     int locNew = states.getIndexOfLastAdd();
     // And add a location to the PTA
     par.addLocation(
         PTA.combineLocationNames(pta1.getLocationName(loc1), pta2.getLocationName(loc2)));
     // Invariant is conjunction of two invariants
     for (Constraint c : pta1.getInvariantConstraints(loc1))
       par.addInvariantCondition(locNew, c.deepCopy().renameClocks(pta1, par));
     for (Constraint c : pta2.getInvariantConstraints(loc2))
       par.addInvariantCondition(locNew, c.deepCopy().renameClocks(pta2, par));
   }
   // Return index of state in state set
   return states.getIndexOfLastAdd();
 }
Exemplo n.º 4
0
  private static final SecurityHandler basicAuth(String realm) {

    OpenfireLoginService l = new OpenfireLoginService();
    l.setName(realm);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] {"jmxweb"});
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName(realm);
    csh.addConstraintMapping(cm);
    csh.setLoginService(l);

    return csh;
  }
Exemplo n.º 5
0
 private Constraint addInterfaceConstraint(ReflectClass claxx) {
   Collection4 classes = stream().classCollection().forInterface(claxx);
   if (classes.size() == 0) {
     QConClass qcc = new QConClass(_trans, null, null, claxx);
     addConstraint(qcc);
     return qcc;
   }
   Iterator4 i = classes.iterator();
   Constraint constr = null;
   while (i.moveNext()) {
     ClassMetadata classMetadata = (ClassMetadata) i.current();
     ReflectClass classMetadataClaxx = classMetadata.classReflector();
     if (classMetadataClaxx != null) {
       if (!classMetadataClaxx.isInterface()) {
         if (constr == null) {
           constr = constrain(classMetadataClaxx);
         } else {
           constr = constr.or(constrain(classMetadata.classReflector()));
         }
       }
     }
   }
   return constr;
 }
Exemplo n.º 6
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);
  }
Exemplo n.º 7
0
  /**
   * Get the decision from the database, given its name
   *
   * @param name the decision name
   */
  public void fromDatabase(String name) {
    String findQuery = "";
    RationaleDB db = RationaleDB.getHandle();
    Connection conn = db.getConnection();

    this.name = name;
    name = RationaleDBUtil.escape(name);

    Statement stmt = null;
    ResultSet rs = null;
    try {
      stmt = conn.createStatement();
      findQuery = "SELECT *  FROM " + "PATTERNDECISIONS where name = '" + name + "'";
      //			***			System.out.println(findQuery);
      rs = stmt.executeQuery(findQuery);

      if (rs.next()) {
        id = rs.getInt("id");
        description = RationaleDBUtil.decode(rs.getString("description"));
        type = (DecisionType) DecisionType.fromString(rs.getString("type"));
        devPhase = (Phase) Phase.fromString(rs.getString("phase"));
        ptype = RationaleElementType.fromString(rs.getString("ptype"));
        parent = rs.getInt("parent");
        //				artifact = rs.getString("artifact");
        //				enabled = rs.getBoolean("enabled");
        status = (DecisionStatus) DecisionStatus.fromString(rs.getString("status"));
        String subdecs = rs.getString("subdecreq");
        if (subdecs.compareTo("Yes") == 0) {
          alts = false;
        } else {
          alts = true;
        }

        try {
          int desID = rs.getInt("designer");
          designer = new Designer();
          designer.fromDatabase(desID);
        } catch (SQLException ex) {
          designer = null; // nothing...
        }
      }
      rs.close();
      // need to read in the rest - recursive routines?
      subDecisions.removeAllElements();
      alternatives.removeAllElements();
      if (!alts) {
        Vector<String> decNames = new Vector<String>();
        findQuery =
            "SELECT name from PATTERNDECISIONS where "
                + "ptype = '"
                + RationaleElementType.DECISION.toString()
                + "' and parent = "
                + new Integer(id).toString();
        //				***					System.out.println(findQuery2);
        rs = stmt.executeQuery(findQuery);
        while (rs.next()) {
          decNames.add(RationaleDBUtil.decode(rs.getString("name")));
        }
        Enumeration decs = decNames.elements();
        while (decs.hasMoreElements()) {
          PatternDecision subDec = new PatternDecision();
          subDec.fromDatabase((String) decs.nextElement());
          subDecisions.add(subDec);
        }

      } else {
        Vector<String> altNames = new Vector<String>();
        findQuery =
            "SELECT name from ALTERNATIVES where "
                + "ptype = '"
                + RationaleElementType.DECISION.toString()
                + "' and parent = "
                + new Integer(id).toString();
        //				***					System.out.println(findQuery2);
        rs = stmt.executeQuery(findQuery);
        while (rs.next()) {
          altNames.add(RationaleDBUtil.decode(rs.getString("name")));
        }
        Enumeration alts = altNames.elements();
        while (alts.hasMoreElements()) {
          Alternative alt = new Alternative();
          alt.fromDatabase((String) alts.nextElement());
          alternatives.add(alt);
        }
      }

      // need to do questions too
      Vector<String> questNames = new Vector<String>();
      findQuery =
          "SELECT name from QUESTIONS where "
              + "ptype = '"
              + RationaleElementType.DECISION.toString()
              + "' and parent = "
              + new Integer(id).toString();
      //			***				System.out.println(findQuery3);
      rs = stmt.executeQuery(findQuery);
      while (rs.next()) {
        questNames.add(RationaleDBUtil.decode(rs.getString("name")));
      }
      Enumeration quests = questNames.elements();
      questions.removeAllElements();
      while (quests.hasMoreElements()) {
        Question quest = new Question();
        quest.fromDatabase((String) quests.nextElement());
        questions.add(quest);
      }

      // no, not last - need history too
      findQuery =
          "SELECT * from HISTORY where ptype = 'Decision' and "
              + "parent = "
              + Integer.toString(id);
      //			***			  System.out.println(findQuery5);
      rs = stmt.executeQuery(findQuery);
      history.removeAllElements();
      while (rs.next()) {
        History nextH = new History();
        nextH.setStatus(rs.getString("status"));
        nextH.setReason(RationaleDBUtil.decode(rs.getString("reason")));
        nextH.dateStamp = rs.getTimestamp("date");
        //				nextH.dateStamp = rs.getDate("date");
        history.add(nextH);
      }

      // now, get our constraints
      findQuery =
          "SELECT * from ConDecRelationships WHERE " + "decision = " + new Integer(id).toString();

      rs = stmt.executeQuery(findQuery);
      constraints.removeAllElements();
      if (rs != null) {
        while (rs.next()) {
          int ontID = rs.getInt("constr");
          Constraint cont = new Constraint();
          cont.fromDatabase(ontID);
          this.addConstraint(cont);
        }
        rs.close();
      }

      // now, candidate patterns
      findQuery =
          "SELECT * from pattern_decision WHERE parentType= 'Decision' and decisionID=" + this.id;
      rs = stmt.executeQuery(findQuery);
      if (rs != null) {
        while (rs.next()) {
          int patternID = rs.getInt("patternID");
          Pattern p = new Pattern();
          p.fromDatabase(patternID);
          this.addCandidatePattern(p);
        }
      }

    } catch (SQLException ex) {
      // handle any errors
      RationaleDB.reportError(ex, "Error in PatternDecision.fromDatabase", findQuery);

    } finally {
      RationaleDB.releaseResources(stmt, rs);
    }
  }
Exemplo n.º 8
0
  /**
   * Save our decision to the database.
   *
   * @param parent - the parent of the decision
   * @param ptype - the parent's type
   * @return the unique ID
   */
  public int toDatabase(int parent, RationaleElementType ptype) {
    RationaleDB db = RationaleDB.getHandle();
    Connection conn = db.getConnection();
    String updateQuery = "";
    int ourid = 0;

    RationaleUpdateEvent l_updateEvent;

    // find out if this requirement is already in the database
    Statement stmt = null;
    ResultSet rs = null;

    String subsReq = "No";
    if (!alts) subsReq = "Yes";

    try {
      stmt = conn.createStatement();

      if (inDatabase(parent, ptype)) {
        // set up Designer update string
        String updateD;
        if (designer == null) updateD = "D.designer = null";
        else updateD = "D.designer = " + designer.getID();

        updateQuery =
            "UPDATE PATTERNDECISIONS D "
                + "SET D.parent = "
                + new Integer(parent).toString()
                + ", D.ptype = '"
                + ptype.toString()
                + "', D.phase = '"
                + devPhase.toString()
                + "', D.description = '"
                + RationaleDBUtil.escape(description)
                + "', D.type = '"
                + type.toString()
                + "', D.name = '"
                + RationaleDBUtil.escape(name)
                + "', D.status = '"
                + status.toString()
                + "', D.subdecreq = '"
                + subsReq
                + "', "
                + updateD
                + " WHERE "
                + "D.id = "
                + this.id
                + " ";
        stmt.execute(updateQuery);

        l_updateEvent = m_eventGenerator.MakeUpdated();
      } else {
        if (!fromXML) id = RationaleDB.findAvailableID("PATTERNDECISIONS");

        String parentSt;
        String parentTSt;

        // now, we have determined that the decision is new
        if ((this.parent < 0) || (ptype == null)) {
          parentSt = "NULL";
          parentTSt = "None";
        } else {
          parentSt = new Integer(this.parent).toString();
          parentTSt = ptype.toString();
        }
        String updateD;
        if (designer == null) updateD = "null";
        else updateD = new Integer(designer.getID()).toString();

        updateQuery =
            "INSERT INTO PATTERNDECISIONS "
                + "(id, name, description, type, status, phase, subdecreq, parent, ptype, designer) "
                + "VALUES ("
                + id
                + ", '"
                + RationaleDBUtil.escape(this.name)
                + "', '"
                + RationaleDBUtil.escape(this.description)
                + "', '"
                + this.type.toString()
                + "', '"
                + this.status.toString()
                + "', '"
                + this.devPhase.toString()
                + "', '"
                + subsReq
                + "', "
                + parentSt
                + ", '"
                + parentTSt
                + "', "
                + updateD
                + ")";

        stmt.execute(updateQuery);

        /*
        //Now, associate with pattern.
        //Get id first
        updateQuery = "SELECT id FROM patterndecisions where name='" +
        RationaleDBUtil.escape(this.name) + "'";
        rs = stmt.executeQuery(updateQuery);

        if (rs.next())
        {
        	ourid = rs.getInt("id");
        	rs.close();
        	//We have found out our ID and the insert is a success.
        	//get association set up.
        	updateQuery = "INSERT into pattern_decision values (" + parent +
        	"ourid" + "DECISION)";
        }

        //And now, we have patternID and patterndecisionID. We can insert into relationship entry
        updateQuery = "INSERT INTO pattern_decision values (" + parentPattern + ", " +
        ourid + ", " + "'Decision')";
        stmt.execute(updateQuery);
        */
        l_updateEvent = m_eventGenerator.MakeCreated();
      }
      // in either case, we want to update any sub-requirements in case
      // they are new!
      // now, we need to get our ID
      updateQuery =
          "SELECT id FROM PATTERNDECISIONS where name='" + RationaleDBUtil.escape(this.name) + "'";
      rs = stmt.executeQuery(updateQuery);

      if (rs.next()) {
        ourid = rs.getInt("id");
        rs.close();
      } else {
        ourid = -1;
      }
      this.id = ourid;

      Enumeration alts = alternatives.elements();
      while (alts.hasMoreElements()) {
        Alternative alt = (Alternative) alts.nextElement();
        //				System.out.println("Saving alternative from decision");
        alt.toDatabase(ourid, RationaleElementType.DECISION);
      }

      Enumeration decs = subDecisions.elements();
      while (decs.hasMoreElements()) {
        Decision dec = (Decision) decs.nextElement();
        dec.toDatabase(ourid, RationaleElementType.DECISION);
      }

      Enumeration quests = questions.elements();
      while (quests.hasMoreElements()) {
        Question quest = (Question) quests.nextElement();
        quest.toDatabase(ourid, RationaleElementType.DECISION);
      }

      // finally, the history

      Enumeration hist = history.elements();
      while (hist.hasMoreElements()) {
        History his = (History) hist.nextElement();
        his.toDatabase(ourid, RationaleElementType.DECISION);
      }

      // need to update our relationships with the constraints
      Enumeration conkids = this.constraints.elements();
      while (conkids.hasMoreElements()) {
        Constraint kid = (Constraint) conkids.nextElement();
        // if the parent ID is not zero, then update the parent-child relationship

        updateQuery =
            "SELECT * from ConDecRelationships WHERE "
                + "constr = "
                + new Integer(kid.getID()).toString()
                + " and decision = "
                + new Integer(ourid).toString();

        rs = stmt.executeQuery(updateQuery.toUpperCase());
        if (rs.next()) {
          rs.close();
        } else {
          String insertRel =
              "INSERT INTO ConDecRelationships (constr, decision) "
                  + "VALUES ("
                  + new Integer(kid.getID()).toString()
                  + ", "
                  + new Integer(ourid).toString()
                  + ")";
          System.out.println(insertRel.toUpperCase());
          stmt.execute(insertRel);
        }
        kid.toDatabase(ourid);
      } // checking parent

      m_eventGenerator.Broadcast(l_updateEvent);
    } catch (SQLException ex) {
      // handle any errors
      RationaleDB.reportError(ex, "Error in PatternDecision.toDatabase", updateQuery);

    } finally {
      RationaleDB.releaseResources(stmt, rs);
    }

    return ourid;
  }
Exemplo n.º 9
0
  /** Construct the parallel composition of two PTAs. */
  public PTA compose(PTA pta1, PTA pta2) {
    Set<String> alpha1, alpha2, alpha1only, alpha2only, sync;
    Transition transition;
    Edge edge;
    double prob;
    IndexPair state;
    int src, dest;

    // Store PTAs locally and create new one to store parallel composition
    this.pta1 = pta1;
    this.pta2 = pta2;
    par = new PTA();

    // New set of clocks is union of sets for two PTAs
    for (String s : pta1.clockNames) {
      par.getOrAddClock(s);
    }
    for (String s : pta2.clockNames) {
      par.getOrAddClock(s);
    }

    // Get alphabets, compute intersection etc.
    alpha1 = pta1.getAlphabet();
    alpha2 = pta2.getAlphabet();
    // System.out.println("alpha1: " + alpha1);
    // System.out.println("alpha2: " + alpha2);
    sync = new LinkedHashSet<String>();
    alpha1only = new LinkedHashSet<String>();
    alpha2only = new LinkedHashSet<String>();
    for (String a : alpha1) {
      if (!("".equals(a)) && alpha2.contains(a)) {
        sync.add(a);
      } else {
        alpha1only.add(a);
      }
    }
    for (String a : alpha2) {
      if (!alpha1.contains(a)) {
        alpha2only.add(a);
      }
    }
    // Explicitly add tau to action lists
    alpha1only.add("");
    alpha2only.add("");
    // System.out.println("alpha1only: " + alpha1only);
    // System.out.println("alpha2only: " + alpha2only);
    // System.out.println("sync: " + sync);

    // Initialise states storage
    states = new IndexedSet<IndexPair>();
    explore = new LinkedList<IndexPair>();
    // Add initial location
    addState(0, 0);
    src = -1;
    while (!explore.isEmpty()) {
      // Pick next state to explore
      // (they are stored in order found so know index is src+1)
      state = explore.removeFirst();
      src++;
      // Go through asynchronous transitions of PTA 1
      for (String a : alpha1only) {
        for (Transition transition1 : pta1.getTransitionsByAction(state.i1, a)) {
          // Create new transition
          transition = par.addTransition(src, a);
          // Copy guard
          for (Constraint c : transition1.getGuardConstraints())
            transition.addGuardConstraint(c.deepCopy().renameClocks(pta1, par));
          // Combine edges
          for (Edge edge1 : transition1.getEdges()) {
            prob = edge1.getProbability();
            dest = addState(edge1.getDestination(), state.i2);
            edge = transition.addEdge(prob, dest);
            // Copy resets
            for (Map.Entry<Integer, Integer> e : edge1.getResets()) {
              edge.addReset(PTA.renameClock(pta1, par, e.getKey()), e.getValue());
            }
          }
        }
      }
      // Go through asynchronous transitions of PTA 2
      for (String a : alpha2only) {
        for (Transition transition2 : pta2.getTransitionsByAction(state.i2, a)) {
          // Create new transition
          transition = par.addTransition(src, a);
          // Copy guard
          for (Constraint c : transition2.getGuardConstraints())
            transition.addGuardConstraint(c.deepCopy().renameClocks(pta2, par));
          // Combine edges
          for (Edge edge2 : transition2.getEdges()) {
            prob = edge2.getProbability();
            dest = addState(state.i1, edge2.getDestination());
            edge = transition.addEdge(prob, dest);
            // Copy resets
            for (Map.Entry<Integer, Integer> e : edge2.getResets()) {
              edge.addReset(PTA.renameClock(pta2, par, e.getKey()), e.getValue());
            }
          }
        }
      }
      // Go through synchronous transitions
      for (String a : sync) {
        for (Transition transition1 : pta1.getTransitionsByAction(state.i1, a)) {
          for (Transition transition2 : pta2.getTransitionsByAction(state.i2, a)) {
            // Create new transition
            transition = par.addTransition(src, a);
            // Guard is conjunction of guards
            for (Constraint c : transition1.getGuardConstraints())
              transition.addGuardConstraint(c.deepCopy().renameClocks(pta1, par));
            for (Constraint c : transition2.getGuardConstraints())
              transition.addGuardConstraint(c.deepCopy().renameClocks(pta2, par));
            // Combine edges
            for (Edge edge1 : transition1.getEdges()) {
              for (Edge edge2 : transition2.getEdges()) {
                prob = edge1.getProbability() * edge2.getProbability();
                dest = addState(edge1.getDestination(), edge2.getDestination());
                edge = transition.addEdge(prob, dest);
                // Reset set is union of reset sets
                for (Map.Entry<Integer, Integer> e : edge1.getResets()) {
                  edge.addReset(PTA.renameClock(pta1, par, e.getKey()), e.getValue());
                }
                for (Map.Entry<Integer, Integer> e : edge2.getResets()) {
                  edge.addReset(PTA.renameClock(pta2, par, e.getKey()), e.getValue());
                }
              }
            }
          }
        }
      }
    }

    return par;
  }
Exemplo n.º 10
0
  /** Build a time bounded reachability query into a PTA; return the new target location set. */
  private BitSet buildTimeBoundIntoPta(
      PTA pta, BitSet targetLocs, int timeBound, boolean timeBoundStrict) {
    String timerClock = null;
    int timerClockIndex, numLocs, newTargetLoc;
    String newTargetLocString;
    List<Transition> trNewList;
    Transition trNew;
    BitSet targetLocsNew;
    boolean toTarget;
    int i;

    // Add a timer clock
    timerClock = "time";
    while (pta.getClockIndex(timerClock) != -1) timerClock += "_";
    timerClockIndex = pta.addClock(timerClock);
    // Add a new target location
    numLocs = pta.getNumLocations();
    newTargetLocString = "target";
    while (pta.getLocationIndex(newTargetLocString) != -1) newTargetLocString += "_";
    newTargetLoc = pta.addLocation(newTargetLocString);
    // Go through old (on-target) locations
    for (i = 0; i < numLocs; i++) {
      trNewList = new ArrayList<Transition>();
      for (Transition tr : pta.getTransitions(i)) {
        // See if the transition can go to a target location
        toTarget = false;
        for (Edge e : tr.getEdges()) {
          if (targetLocs.get(e.getDestination())) {
            toTarget = true;
            break;
          }
        }
        // Copy transition, modify edges going to target and add guard
        if (toTarget) {
          trNew = new Transition(tr);
          for (Edge e : trNew.getEdges()) {
            if (targetLocs.get(e.getDestination())) {
              e.setDestination(newTargetLoc);
            }
          }
          if (timeBoundStrict)
            trNew.addGuardConstraint(Constraint.buildLt(timerClockIndex, timeBound));
          else trNew.addGuardConstraint(Constraint.buildLeq(timerClockIndex, timeBound));
          trNewList.add(trNew);
          // Modify guard of copied transition
          if (timeBoundStrict)
            tr.addGuardConstraint(Constraint.buildGeq(timerClockIndex, timeBound));
          else tr.addGuardConstraint(Constraint.buildGt(timerClockIndex, timeBound));
        }
      }
      // Add new transitions to PTA
      for (Transition tr : trNewList) {
        pta.addTransition(tr);
      }
    }
    // Re-generate set of target locations
    targetLocsNew = new BitSet(pta.getNumLocations());
    targetLocsNew.set(newTargetLoc);

    return targetLocsNew;
  }