Example #1
0
  // ## operation checkChemkinMessage()
  public void checkChemkinMessage() {
    // #[ operation checkChemkinMessage()
    try {
      String dir = System.getProperty("RMG.workingDirectory");
      String filename = "chemkin/chem.message";
      FileReader fr = new FileReader(filename);
      BufferedReader br = new BufferedReader(fr);

      String line = br.readLine().trim();
      if (line.startsWith("NO ERRORS FOUND ON INPUT")) {
        return;
      } else if (line.startsWith("WARNING...THERE IS AN ERROR IN THE LINKING FILE")) {
        System.out.println("Error in chemkin linking to reactor!");
        System.exit(0);
      } else {
        System.out.println("Unknown message in chem.message!");
        System.exit(0);
      }
    } catch (Exception e) {
      System.out.println("Can't read chem.message!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
Example #2
0
  // ## operation runReactor()
  public void runReactor() {
    // #[ operation runReactor()
    // run reactor
    String dir = System.getProperty("RMG.workingDirectory");

    try {
      // system call for reactor
      String[] command = {dir + "/software/reactorModel/reactor.exe"};
      File runningDir = new File("chemkin");
      Process reactor = Runtime.getRuntime().exec(command, null, runningDir);
      InputStream ips = reactor.getInputStream();
      InputStreamReader is = new InputStreamReader(ips);
      BufferedReader br = new BufferedReader(is);
      String line = null;
      while ((line = br.readLine()) != null) {
        // System.out.println(line);
      }
      int exitValue = reactor.waitFor();
    } catch (Exception e) {
      System.out.println("Error in running reactor!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
Example #3
0
  public static void writeChemkinInputFile(ReactionSystem rs) {
    // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot)

    StringBuilder result = new StringBuilder();
    result.append(writeChemkinHeader());
    result.append(writeChemkinElement());
    double start = System.currentTimeMillis();
    result.append(writeChemkinSpecies(rs.reactionModel, rs.initialStatus));
    result.append(writeChemkinThermo(rs.reactionModel));
    Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60;
    start = System.currentTimeMillis();
    result.append(writeChemkinPdepReactions(rs));
    Global.chemkinReaction =
        Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60;

    String dir = System.getProperty("RMG.workingDirectory");
    if (!dir.endsWith("/")) dir += "/";
    dir += "software/reactorModel/";
    String file = "chemkin/chem.inp";

    try {
      FileWriter fw = new FileWriter(file);
      fw.write(result.toString());
      fw.close();
    } catch (Exception e) {
      System.out.println("Error in writing chemkin input file chem.inp!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
Example #4
0
  // ## operation writeChemkinInputFile(ReactionModel,SystemSnapshot)
  public static void writeChemkinInputFile(
      final ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) {
    // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot)

    StringBuilder result = new StringBuilder();
    result.append(writeChemkinHeader());
    result.append(writeChemkinElement());
    double start = System.currentTimeMillis();
    result.append(writeChemkinSpecies(p_reactionModel, p_beginStatus));
    result.append(writeChemkinThermo(p_reactionModel));
    Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60;
    start = System.currentTimeMillis();
    result.append(
        writeChemkinPdepReactions(
            p_reactionModel, p_beginStatus)); // 10/26/07 gmagoon: changed to pass p_beginStatus
    // result.append(writeChemkinPdepReactions(p_reactionModel));
    Global.chemkinReaction =
        Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60;

    String dir = System.getProperty("RMG.workingDirectory");
    if (!dir.endsWith("/")) dir += "/";
    dir += "software/reactorModel/";
    String file = "chemkin/chem.inp";

    try {
      FileWriter fw = new FileWriter(file);
      fw.write(result.toString());
      fw.close();
    } catch (Exception e) {
      System.out.println("Error in writing chemkin input file chem.inp!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    if (PDepRateConstant.getMode() == Mode.CHEBYSHEV
        || PDepRateConstant.getMode() == Mode.PDEPARRHENIUS
        || PDepRateConstant.getMode() == Mode.RATE) {
      StringBuilder gridOfRateCoeffs = new StringBuilder();
      gridOfRateCoeffs.append(writeGridOfRateCoeffs(p_reactionModel));
      String newFile = "chemkin/tableOfRateCoeffs.txt";
      try {
        FileWriter fw = new FileWriter(newFile);
        fw.write(gridOfRateCoeffs.toString());
        fw.close();
      } catch (Exception e) {
        System.out.println("Error in writing tableOfRateCoeffs.txt");
        System.out.println(e.getMessage());
        System.exit(0);
      }
    }

    // #]
  }
Example #5
0
  public void saveGlyphFile(OutputStream a_output) {
    try {
      Transformer transformer = getTransformer();
      Document document = m_glyph.makeDocument();
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(a_output);
      transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException e) {
      e.printStackTrace();
    }

    m_savedTime = System.currentTimeMillis();
    m_modifiedTime = m_savedTime;
  }
Example #6
0
  // ## operation Chemkin(double,double,String)
  public Chemkin(double p_rtol, double p_atol, String p_reactorType) {
    // #[ operation Chemkin(double,double,String)
    if (p_rtol < 0 || p_atol < 0)
      throw new InvalidChemkinParameterException("Negative rtol or atol!");
    if (p_reactorType == null) throw new NullPointerException();

    String dir = System.getProperty("RMG.workingDirectory");

    // create the documentTypesDefinitions
    File docFile = new File("chemkin/documentTypeDefinitions");
    docFile.mkdir();
    copyFiles(
        dir + "/software/reactorModel/documentTypeDefinitions/reactorInput.dtd",
        "chemkin/documentTypeDefinitions/reactorInput.dtd");
    copyFiles(
        dir + "/software/reactorModel/documentTypeDefinitions/reactorOutput.dtd",
        "chemkin/documentTypeDefinitions/reactorOutput.dtd");

    rtol = p_rtol;
    atol = p_atol;
    reactorType = p_reactorType;
  }
Example #7
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);
  }
  public StartProcess() {
    super();

    Hashtable jndiProps = new Hashtable();
    jndiProps.put(Context.PROVIDER_URL, "t3://soaps3.alfa.local:8001/soa-infra");
    jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    jndiProps.put(Context.SECURITY_PRINCIPAL, "weblogic");
    jndiProps.put(Context.SECURITY_CREDENTIALS, "weblogic1");
    jndiProps.put("dedicated.connection", "true");

    String inputPayload =
        "<process xmlns=\"http://xmlns.oracle.com/HelloWorld/Helloworld/BPELProcess1\">"
            + "   <input>hello</input>"
            + "</process>";

    Locator locator = null;
    try {
      // connect to the soa server
      locator = LocatorFactory.createLocator(jndiProps);
      String compositeDN = "default/Helloworld!1.0";

      // find composite
      Composite composite = locator.lookupComposite("default/Helloworld!1.0");

      System.out.println("Got Composite : " + composite.toString());

      // find exposed service of the composite
      Service service = composite.getService("ADFBindingService");
      System.out.println("Got serviceName : " + service.toString());

      // make the input request and add this to a operation of the service
      NormalizedMessage input = new NormalizedMessageImpl();
      String uuid = "uuid:" + UUID.randomUUID();
      input.addProperty(NormalizedMessage.PROPERTY_CONVERSATION_ID, uuid);

      // payload is the partname of the process operation
      input.getPayload().put("payload", inputPayload);

      // process is the operation of the employee service
      NormalizedMessage res = null;
      try {
        res = service.request("process", input);
      } catch (Exception e) {
        e.printStackTrace();
      }

      Map payload = res.getPayload();
      Element element = (Element) payload.get("payload");

      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty("indent", "yes");
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);

      DOMSource source = new DOMSource(element);

      transformer.transform(source, result);
      System.out.println("Result\n" + sw.toString());

      System.out.println("instances");

      CompositeInstanceFilter filter = new CompositeInstanceFilter();
      filter.setMinCreationDate(new java.util.Date((System.currentTimeMillis() - 2000000)));
      // get composite instances by filter ..
      List<CompositeInstance> obInstances = composite.getInstances(filter);
      // for each of the returned composite instances..
      for (CompositeInstance instance : obInstances) {
        System.out.println(
            " DN: "
                + instance.getCompositeDN()
                + " Instance: "
                + instance.getId()
                + " creation-date: "
                + instance.getCreationDate()
                + " state ("
                + instance.getState()
                + "): "
                + getStateAsString(instance.getState()));

        // setup a component filter
        ComponentInstanceFilter cInstanceFilter = new ComponentInstanceFilter();
        // get child component instances ..
        List<ComponentInstance> childComponentInstances =
            instance.getChildComponentInstances(cInstanceFilter);

        // for each child component instance (e.g. a bpel process)
        for (ComponentInstance cInstance : childComponentInstances) {
          System.out.println(
              "  -> componentinstance: "
                  + cInstance.getComponentName()
                  + " type: "
                  + cInstance.getServiceEngine().getEngineType()
                  + " state: "
                  + getStateAsString(cInstance.getState()));
          System.out.println("State: " + cInstance.getNormalizedStateAsString());
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #9
0
  // ## operation writeReactorInputFile(ReactionModel,ReactionTime,ReactionTime,SystemSnapshot)
  public boolean writeReactorInputFile(
      ReactionModel p_reactionModel,
      ReactionTime p_beginTime,
      ReactionTime p_endTime,
      SystemSnapshot p_beginStatus) {
    // #[ operation writeReactorInputFile(ReactionModel,ReactionTime,ReactionTime,SystemSnapshot)
    // construct "input" string
    String input = "<?xml version=\"1.0\" standalone=\"no\"?>" + "\n";

    String dir = System.getProperty("RMG.workingDirectory");
    if (!dir.endsWith("/")) dir += "/";
    String dtd = dir + "software/reactorModel/documentTypeDefinitions/reactorInput.dtd";
    input += "<!DOCTYPE reactorinput SYSTEM \"" + dtd + "\">" + "\n";

    input += "<reactorinput>" + "\n";
    input += "<header>" + "\n";
    input += "<title>Reactor Input File</title>" + "\n";
    input +=
        "<description>RMG-generated file used to call an external reactor model</description>"
            + "\n";
    input += "</header>" + "\n";
    input += "<inputvalues>" + "\n";
    input += "<integrationparameters>" + "\n";
    input += "<reactortype>" + reactorType + "</reactortype>" + "\n";
    input +=
        "<starttime units=\""
            + p_beginTime.getUnit()
            + "\">"
            + MathTool.formatDouble(p_beginTime.getTime(), 15, 6)
            + "</starttime>"
            + "\n";
    input +=
        "<endtime units=\""
            + p_endTime.getUnit()
            + "\">"
            + MathTool.formatDouble(p_endTime.getTime(), 15, 6)
            + "</endtime>"
            + "\n";
    //      input += "<starttime units=\"" + p_beginTime.unit + "\">" +
    // MathTool.formatDouble(p_beginTime.time,15,6) +  "</starttime>" + "\n";
    //      input += "<endtime units=\"" + p_endTime.unit + "\">" +
    // MathTool.formatDouble(p_endTime.time,15,6) +  "</endtime>" + "\n";
    input += "<rtol>" + rtol + "</rtol>" + "\n";
    input += "<atol>" + atol + "</atol>" + "\n";
    input += "</integrationparameters>" + "\n";
    input += "<chemistry>" + "\n";
    input += "</chemistry>" + "\n";
    input += "<systemstate>" + "\n";
    input +=
        "<temperature units=\"K\">"
            + MathTool.formatDouble(p_beginStatus.getTemperature().getK(), 15, 6)
            + "</temperature>"
            + "\n";
    input +=
        "<pressure units=\"Pa\">"
            + MathTool.formatDouble(p_beginStatus.getPressure().getPa(), 15, 6)
            + "</pressure>"
            + "\n";
    for (Iterator iter = p_beginStatus.getSpeciesStatus(); iter.hasNext(); ) {
      SpeciesStatus spcStatus = (SpeciesStatus) iter.next();
      Species thisSpecies = spcStatus.getSpecies();
      CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionModel;
      if (cerm.containsAsReactedSpecies(thisSpecies)) {
        String spcChemkinName = thisSpecies.getChemkinName();
        double concentration = spcStatus.getConcentration();
        input +=
            "<amount units=\"molPerCm3\" speciesid=\""
                + spcChemkinName
                + "\">"
                + concentration
                + "</amount>"
                + "\n";
      }
    }
    for (Iterator iter = p_beginStatus.getInertGas(); iter.hasNext(); ) {
      String name = (String) iter.next();
      double conc = p_beginStatus.getInertGas(name);
      if (conc != 0.0)
        input +=
            "<amount units=\"molPerCm3\" speciesid=\"" + name + "\">" + conc + "</amount>" + "\n";
    }
    input += "</systemstate>" + "\n";
    input += "</inputvalues>" + "\n";
    input += "</reactorinput>" + "\n";

    // write "input" string to file
    try {
      String file = "chemkin/reactorInput.xml";
      FileWriter fw = new FileWriter(file);
      fw.write(input);
      fw.close();
      return true;
    } catch (Exception e) {
      System.out.println("Error in writing reactorInput.xml!");
      System.out.println(e.getMessage());
      return false;
    }

    // #]
  }
Example #10
0
  // ## operation readReactorOutputFile(ReactionModel)
  public SystemSnapshot readReactorOutputFile(ReactionModel p_reactionModel) {
    // #[ operation readReactorOutputFile(ReactionModel)
    try {
      // open output file and build the DOM tree
      String dir = System.getProperty("RMG.workingDirectory");
      String filename = "chemkin/reactorOutput.xml";
      File inputFile = new File(filename);

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(true); // validate the document with the DTD
      factory.setIgnoringElementContentWhitespace(true); // ignore whitespace
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(inputFile);

      // get root element and its children
      Element root = doc.getDocumentElement();
      NodeList rootchildren = root.getChildNodes();

      // header is rootchildren.item(0)

      // get return message and check for successful run
      Element returnmessageElement = (Element) rootchildren.item(1);
      Text returnmessageText = (Text) returnmessageElement.getFirstChild();
      String returnmessage = returnmessageText.toString();
      returnmessage = returnmessage.trim();
      if (!returnmessage.contains("SUCCESSFULLY COMPLETED RUN.")) {
        System.out.println("External reactor model failed!");
        System.out.println("Reactor model error message: " + returnmessage);
        System.exit(0);
      }

      // get outputvalues element and its children
      Element outputvaluesElement = (Element) rootchildren.item(2);
      NodeList children = outputvaluesElement.getChildNodes();

      // get time
      Element timeElement = (Element) children.item(0);
      Text timeText = (Text) timeElement.getFirstChild();
      double time = Double.parseDouble(timeText.getData());
      String timeUnits = timeElement.getAttribute("units");

      // get systemstate element and its children
      Element systemstateElement = (Element) children.item(1);
      NodeList states = systemstateElement.getChildNodes();

      // get temperature and its units
      Element temperatureElement = (Element) states.item(0);
      String tempUnits = temperatureElement.getAttribute("units");
      Text temperatureText = (Text) temperatureElement.getFirstChild();
      double temp = Double.parseDouble(temperatureText.getData());
      Temperature T = new Temperature(temp, tempUnits);

      // get pressure and its units
      Element pressureElement = (Element) states.item(1);
      String presUnits = pressureElement.getAttribute("units");
      Text pressureText = (Text) pressureElement.getFirstChild();
      double pres = Double.parseDouble(pressureText.getData());
      Pressure P = new Pressure(pres, presUnits);

      // get species amounts (e.g. concentrations)
      ArrayList speciesIDs = new ArrayList();
      ArrayList amounts = new ArrayList();
      ArrayList fluxes = new ArrayList();
      String amountUnits = null;
      String fluxUnits = null;

      // loop thru all the species
      // begin at i=2, since T and P take already the first two position of states
      int nSpe = (states.getLength() - 2) / 2;
      int index = 0;
      LinkedHashMap inertGas = new LinkedHashMap();
      for (int i = 2; i < nSpe + 2; i++) {
        // get amount element and the units
        Element amountElement = (Element) states.item(i);
        amountUnits = amountElement.getAttribute("units");

        Element fluxElement = (Element) states.item(i + nSpe);
        fluxUnits = fluxElement.getAttribute("units");

        // get speciesid and store in an array list
        String thisSpeciesID = amountElement.getAttribute("speciesid");

        // get amount (e.g. concentraion) and store in an array list
        Text amountText = (Text) amountElement.getFirstChild();
        double thisAmount = Double.parseDouble(amountText.getData());
        if (thisAmount < 0) {
          double aTol = ReactionModelGenerator.getAtol();
          // if (Math.abs(thisAmount) < aTol) thisAmount = 0;
          // else throw new NegativeConcentrationException("Negative concentration in
          // reactorOutput.xml: " + thisSpeciesID);
          if (thisAmount < -100.0 * aTol)
            throw new NegativeConcentrationException(
                "Species "
                    + thisSpeciesID
                    + " has negative concentration: "
                    + String.valueOf(thisAmount));
        }

        // get amount (e.g. concentraion) and store in an array list
        Text fluxText = (Text) fluxElement.getFirstChild();
        double thisFlux = Double.parseDouble(fluxText.getData());

        if (thisSpeciesID.compareToIgnoreCase("N2") == 0
            || thisSpeciesID.compareToIgnoreCase("Ne") == 0
            || thisSpeciesID.compareToIgnoreCase("Ar") == 0) {
          inertGas.put(thisSpeciesID, new Double(thisAmount));
        } else {
          speciesIDs.add(index, thisSpeciesID);
          amounts.add(index, new Double(thisAmount));
          fluxes.add(index, new Double(thisFlux));
          index++;
        }
      }

      // print results for debugging purposes
      /**
       * System.out.println(returnmessage); System.out.println("Temp = " + temp + " " + tempUnits);
       * System.out.println("Pres = " + pres + " " + presUnits); for (int i = 0; i < amounts.size();
       * i++) { System.out.println(speciesIDs.get(i) + " " + amounts.get(i) + " " + amountUnits); }
       */
      ReactionTime rt = new ReactionTime(time, timeUnits);
      LinkedHashMap speStatus = generateSpeciesStatus(p_reactionModel, speciesIDs, amounts, fluxes);
      SystemSnapshot ss = new SystemSnapshot(rt, speStatus, T, P);
      ss.inertGas = inertGas;
      return ss;
    } catch (Exception e) {
      System.out.println("Error reading reactor model output: " + e.getMessage());
      System.exit(0);
      return null;
    }

    // #]
  }
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
Example #12
0
  /**
   * Format this XML data as a String.
   *
   * @webref xml:method
   * @brief Formats XML data as a String
   * @param indent -1 for a single line (and no declaration), >= 0 for indents and newlines
   * @return the content
   * @see XML#toString()
   */
  public String format(int indent) {
    try {
      // entities = doctype.getEntities()
      boolean useIndentAmount = false;
      TransformerFactory factory = TransformerFactory.newInstance();
      if (indent != -1) {
        try {
          factory.setAttribute("indent-number", indent);
        } catch (IllegalArgumentException e) {
          useIndentAmount = true;
        }
      }
      Transformer transformer = factory.newTransformer();

      // Add the XML declaration at the top if this node is the root and we're
      // not writing to a single line (indent = -1 means single line).
      if (indent == -1 || parent == null) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      } else {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      }

      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "sample.dtd");

      transformer.setOutputProperty(OutputKeys.METHOD, "xml");

      //      transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");  // huh?

      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      //          "-//W3C//DTD XHTML 1.0 Transitional//EN");
      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
      //          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");

      // For Android, because (at least 2.3.3) doesn't like indent-number
      if (useIndentAmount) {
        transformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
      }

      //      transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
      //      transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      //      transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS

      // Always indent, otherwise the XML declaration will just be jammed
      // onto the first line with the XML code as well.
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      //      Properties p = transformer.getOutputProperties();
      //      for (Object key : p.keySet()) {
      //        System.out.println(key + " -> " + p.get(key));
      //      }

      // If you smell something, that's because this code stinks. No matter
      // the settings of the Transformer object, if the XML document already
      // has whitespace elements, it won't bother re-indenting/re-formatting.
      // So instead, transform the data once into a single line string.
      // If indent is -1, then we're done. Otherwise re-run and the settings
      // of the factory will kick in. If you know a better way to do this,
      // please contribute. I've wasted too much of my Sunday on it. But at
      // least the Giants are getting blown out by the Falcons.

      final String decl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
      final String sep = System.getProperty("line.separator");

      StringWriter tempWriter = new StringWriter();
      StreamResult tempResult = new StreamResult(tempWriter);
      transformer.transform(new DOMSource(node), tempResult);
      String[] tempLines = PApplet.split(tempWriter.toString(), sep);
      //      PApplet.println(tempLines);
      if (tempLines[0].startsWith("<?xml")) {
        // Remove XML declaration from the top before slamming into one line
        int declEnd = tempLines[0].indexOf("?>") + 2;
        // if (tempLines[0].length() == decl.length()) {
        if (tempLines[0].length() == declEnd) {
          // If it's all the XML declaration, remove it
          //          PApplet.println("removing first line");
          tempLines = PApplet.subset(tempLines, 1);
        } else {
          //          PApplet.println("removing part of first line");
          // If the first node has been moved to this line, be more careful
          // tempLines[0] = tempLines[0].substring(decl.length());
          tempLines[0] = tempLines[0].substring(declEnd);
        }
      }
      String singleLine = PApplet.join(PApplet.trim(tempLines), "");
      if (indent == -1) {
        return singleLine;
      }

      // Might just be whitespace, which won't be valid XML for parsing below.
      // https://github.com/processing/processing/issues/1796
      // Since indent is not -1, that means they want valid XML,
      // so we'll give them the single line plus the decl... Lame? sure.
      if (singleLine.trim().length() == 0) {
        // You want whitespace? I've got your whitespace right here.
        return decl + sep + singleLine;
      }

      // Since the indent is not -1, bring back the XML declaration
      // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

      StringWriter stringWriter = new StringWriter();
      StreamResult xmlOutput = new StreamResult(stringWriter);
      //      DOMSource source = new DOMSource(node);
      Source source = new StreamSource(new StringReader(singleLine));
      transformer.transform(source, xmlOutput);
      String outgoing = stringWriter.toString();

      // Add the XML declaration to the top if it's not there already
      if (outgoing.startsWith(decl)) {
        int declen = decl.length();
        int seplen = sep.length();
        if (outgoing.length() > declen + seplen
            && !outgoing.substring(declen, declen + seplen).equals(sep)) {
          // make sure there's a line break between the XML decl and the code
          return outgoing.substring(0, decl.length()) + sep + outgoing.substring(decl.length());
        }
        return outgoing;
      } else {
        return decl + sep + outgoing;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Example #13
0
 public Memento createMemento(String a_description) {
   m_modifiedTime = System.currentTimeMillis();
   byte[] bytes = m_glyph.makeTextDocument().getBytes();
   return new Memento(a_description, bytes);
 }
 public static void main(String args[]) {
   try {
     SeleniumHtmlClient client = new SeleniumHtmlClient();
     String testFile = null;
     String testSuite = null;
     String resultsFilename = null;
     for (int i = 0; i < args.length; i++) {
       if (args[i].equals("--host")) {
         i++;
         if (i < args.length) {
           client.setHost(args[i]);
         } else {
           throw new BadUsageException("--host must be followed by a hostname");
         }
       } else if (args[i].equals("--port")) {
         i++;
         if (i < args.length) {
           client.setPort(Integer.parseInt(args[i]));
         } else {
           throw new BadUsageException("--port must be followed by a port number");
         }
       } else if (args[i].equals("--browser")) {
         i++;
         if (i < args.length) {
           client.setBrowser(args[i]);
         } else {
           throw new BadUsageException("--browser must be followed by a browser spec");
         }
       } else if (args[i].equals("--out")) {
         i++;
         if (i < args.length) {
           resultsFilename = args[i];
         } else {
           throw new BadUsageException("--out must be followed by a filename");
         }
         /*
         } else if (args[i].equals("--outdir")) {
         	i++;
         	if (i < args.length) {
         		client.setResultsDir(new File(args[i]));
         	} else {
         		throw new BadUsageException("--outdir must be followed by a path");
         	}
         	*/
       } else if (args[i].equals("--baseurl")) {
         i++;
         if (i < args.length) {
           client.setBaseUrl(args[i]);
         } else {
           throw new BadUsageException("--baseurl must be followed by a URL");
         }
       } else if (args[i].equals("--test")) {
         i++;
         if (i < args.length) {
           if (testFile == null) {
             testFile = args[i];
           } else {
             throw new BadUsageException("only one test file permitted");
           }
         } else {
           throw new BadUsageException("--test must be followed by a test filepath");
         }
       } else if (args[i].equals("--testsuite")) {
         i++;
         if (i < args.length) {
           testSuite = args[i];
         } else {
           throw new BadUsageException("--testsuite must be followed by a testsuite filepath");
         }
       } else if (args[i].equals("--verbose") || args[i].equals("-v")) {
         client.setVerbose(true);
       } else if (args[i].equals("--help") || args[i].equals("-h")) {
         printUsage();
         System.exit(0);
       } else {
         throw new BadUsageException("Unknown parameter " + args[i]);
       }
     }
     if (testFile == null && testSuite == null) {
       throw new BadUsageException("No test or testsuite file specified");
     } else if (testFile != null && testSuite != null) {
       throw new BadUsageException("A test and testsuite file cannot both be specified");
     }
     Writer resultsWriter = null;
     if (resultsFilename != null) {
       resultsWriter = new FileWriter(resultsFilename);
     } else /* if (client.resultsDir == null) */ {
       resultsWriter = new OutputStreamWriter(System.out);
     }
     client.setResultsWriter(resultsWriter);
     if (testFile != null) {
       client.runTest(testFile);
     } else {
       client.runSuite(testSuite);
     }
     if (resultsWriter != null) resultsWriter.close();
   } catch (BadUsageException e) {
     System.err.println("Error: " + e.getMessage());
     System.err.println();
     printUsage();
     System.exit(1);
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
  public boolean runSuite(String filename) throws Exception {
    if (this.verbose) {
      System.out.println(
          "Running test suite "
              + filename
              + " against "
              + this.host
              + ":"
              + this.port
              + " with "
              + this.browser);
    }
    TestSuite suite = new TestSuite();
    long start = System.currentTimeMillis();
    suite.numTestPasses = 0;
    suite.file = new File(filename);
    File suiteDirectory = suite.file.getParentFile();
    this.document = parseDocument(filename);
    Element table = (Element) this.document.getElementsByTagName("table").item(0);
    NodeList tableRows = table.getElementsByTagName("tr");
    Element tableNameRow = (Element) tableRows.item(0);
    suite.name = tableNameRow.getTextContent();
    suite.result = true;
    suite.tests = new Test[tableRows.getLength() - 1];
    for (int i = 1; i < tableRows.getLength(); i++) {
      Element tableRow = (Element) tableRows.item(i);
      Element cell = (Element) tableRow.getElementsByTagName("td").item(0);
      Element link = (Element) cell.getElementsByTagName("a").item(0);
      Test test = new Test();
      test.label = link.getTextContent();
      test.file = new File(suiteDirectory, link.getAttribute("href"));

      SeleniumHtmlClient subclient = new SeleniumHtmlClient();
      subclient.setHost(this.host);
      subclient.setPort(this.port);
      subclient.setBrowser(this.browser);
      // subclient.setResultsWriter(this.resultsWriter);
      subclient.setBaseUrl(this.baseUrl);
      subclient.setVerbose(this.verbose);
      subclient.runTest(test);
      if (test.result) {
        suite.numTestPasses++;
      }
      suite.result &= test.result;
      suite.tests[i - 1] = test;
    }
    long end = System.currentTimeMillis();

    suite.totalTime = (end - start) / 1000;

    if (this.resultsWriter != null) {
      this.resultsWriter.write("<html><head>\n");
      this.resultsWriter.write("<style type='text/css'>\n");
      this.resultsWriter.write(
          "body, table {font-family: Verdana, Arial, sans-serif;font-size: 12;}\n");
      this.resultsWriter.write("table {border-collapse: collapse;border: 1px solid #ccc;}\n");
      this.resultsWriter.write("th, td {padding-left: 0.3em;padding-right: 0.3em;}\n");
      this.resultsWriter.write("a {text-decoration: none;}\n");
      this.resultsWriter.write(".title {font-style: italic;}");
      this.resultsWriter.write(".selected {background-color: #ffffcc;}\n");
      this.resultsWriter.write(".status_done {background-color: #eeffee;}\n");
      this.resultsWriter.write(".status_passed {background-color: #ccffcc;}\n");
      this.resultsWriter.write(".status_failed {background-color: #ffcccc;}\n");
      this.resultsWriter.write(
          ".breakpoint {background-color: #cccccc;border: 1px solid black;}\n");
      this.resultsWriter.write("</style>\n");
      this.resultsWriter.write("<title>" + suite.name + "</title>\n");
      this.resultsWriter.write("</head><body>\n");
      this.resultsWriter.write("<h1>Test suite results </h1>\n\n");
      this.resultsWriter.write("<table>\n");
      this.resultsWriter.write(
          "<tr>\n<td>result:</td>\n<td>" + (suite.result ? "passed" : "failed") + "</td>\n</tr>\n");
      this.resultsWriter.write(
          "<tr>\n<td>totalTime:</td>\n<td>" + suite.totalTime + "</td>\n</tr>\n");
      this.resultsWriter.write(
          "<tr>\n<td>numTestTotal:</td>\n<td>" + suite.tests.length + "</td>\n</tr>\n");
      this.resultsWriter.write(
          "<tr>\n<td>numTestPasses:</td>\n<td>" + suite.numTestPasses + "</td>\n</tr>\n");
      int numTestFailures = suite.tests.length - suite.numTestPasses;
      this.resultsWriter.write(
          "<tr>\n<td>numTestFailures:</td>\n<td>" + numTestFailures + "</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>numCommandPasses:</td>\n<td>0</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>numCommandFailures:</td>\n<td>0</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>numCommandErrors:</td>\n<td>0</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>Selenium Version:</td>\n<td>2.24</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>Selenium Revision:</td>\n<td>.1</td>\n</tr>\n");

      // test suite
      this.resultsWriter.write("<tr>\n<td>\n");
      this.resultsWriter.write(
          "<table id=\"suiteTable\" class=\"selenium\" border=\"1\" cellpadding=\"1\" cellspacing=\"1\"><tbody>\n");
      this.resultsWriter.write(
          "<tr class=\"title "
              + (suite.result ? "status_passed" : "status_failed")
              + "\"><td><b>Test Suite</b></td></tr>\n");

      int i = 0;
      for (Test test : suite.tests) {
        this.resultsWriter.write(
            "<tr class=\""
                + (test.result ? "status_passed" : "status_failed")
                + "\"><td><a href=\"#testresult"
                + i
                + "\">"
                + test.name
                + "</a></td></tr>");
        i++;
      }
      this.resultsWriter.write(
          "</tbody></table>\n</td>\n<td>&nbsp;</td>\n</tr>\n</table>\n<table>");
      int j = 0;
      for (Test test : suite.tests) {
        this.resultsWriter.write(
            "<tr><td><a name=\"testresult" + j + "\">" + test.file + "</a><br/><div>\n");
        this.resultsWriter.write("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\">\n");
        this.resultsWriter.write(
            "<thead>\n<tr class=\"title "
                + (test.result ? "status_passed" : "status_failed")
                + "\"><td rowspan=\"1\" colspan=\"3\">"
                + test.name
                + "</td></tr>");
        this.resultsWriter.write("</thead><tbody>\n");
        for (Command command : test.commands) {
          boolean result = command.result.startsWith("OK");
          boolean isAssert = command.cmd.startsWith("assert") || command.cmd.startsWith("verify");
          ;
          if (!isAssert) {
            this.resultsWriter.write(
                "<tr class=\"" + (result ? "status_done" : "") + "\">\n<td>\n");
          } else {
            this.resultsWriter.write(
                "<tr class=\"" + (result ? "status_passed" : "status_failed") + "\">\n<td>\n");
          }
          this.resultsWriter.write(command.cmd);
          this.resultsWriter.write("</td>\n");
          if (command.args != null) {
            for (String arg : Arrays.asList(command.args)) {
              this.resultsWriter.write("<td>" + arg + "</td>\n");
            }
          }
        }
        this.resultsWriter.write("</tr>\n");
        this.resultsWriter.write("</tbody></table>\n");
        this.resultsWriter.write("</div></td>\n<td>&nbsp;</td>\n</tr>");

        j++;
      }

      int k = 0;
      for (Test test : suite.tests) {

        k++;
      }

      this.resultsWriter.write("</tbody></table>\n</td><td>&nbsp;</td>\n</tr>\n</table>\n");
      this.resultsWriter.write("</body></html>");
    }
    return suite.result;
  }