// Gets the specified XML Schema doc if one is mentioned in the file
  public static File getSchemaFile(Document xmlDoc) {
    /** @todo Must be an easier way of doing this... */
    logger.logComment("Getting schema file for: " + xmlDoc.getDocumentURI());

    NodeList nl = xmlDoc.getChildNodes();
    for (int j = 0; j < nl.getLength(); j++) {
      Node node = nl.item(j);
      logger.logComment("Type: " + node.getNodeType() + "Name: " + node.getNodeName());
      if (node.getNodeName().equals(XML_STYLESHEET_NODE)) {
        String nodeVal = node.getNodeValue();

        logger.logComment("Looking at: " + nodeVal);
        String xslFileName =
            nodeVal.substring(nodeVal.indexOf("href=\"") + 6, nodeVal.length() - 1);
        File xslFile = new File(xslFileName);
        return xslFile;
      }

      if (node.getAttributes().getLength() > 0) {
        logger.logComment("Attributes: " + node.getAttributes());
        if (node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR) != null) {
          String locString = node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR).getNodeValue();
          logger.logComment("Loc string: " + locString);
          String file = locString.split("\\s")[1];
          return new File(file);
        }
      }
    }
    logger.logError("No node found with name: " + XML_STYLESHEET_NODE);
    return null;
  }
 /**
  * Marshall an array of Genes to an XML Element representation.
  *
  * @param a_geneValues the genes to represent as an XML element
  * @param a_xmlDocument a Document instance that will be used to create the Element instance. Note
  *     that the element will NOT be added to the document by this method
  * @return an Element object representing the given genes
  * @author Neil Rotstan
  * @author Klaus Meffert
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representGenesAsElement(
     final Gene[] a_geneValues, final Document a_xmlDocument) {
   // Create the parent genes element.
   // --------------------------------
   Element genesElement = a_xmlDocument.createElement(GENES_TAG);
   // Now add gene sub-elements for each gene in the given array.
   // -----------------------------------------------------------
   Element geneElement;
   for (int i = 0; i < a_geneValues.length; i++) {
     // Create the allele element for this gene.
     // ----------------------------------------
     geneElement = a_xmlDocument.createElement(GENE_TAG);
     // Add the class attribute and set its value to the class
     // name of the concrete class representing the current Gene.
     // ---------------------------------------------------------
     geneElement.setAttribute(CLASS_ATTRIBUTE, a_geneValues[i].getClass().getName());
     // Create a text node to contain the string representation of
     // the gene's value (allele).
     // ----------------------------------------------------------
     Element alleleRepresentation = representAlleleAsElement(a_geneValues[i], a_xmlDocument);
     // And now add the text node to the gene element, and then
     // add the gene element to the genes element.
     // -------------------------------------------------------
     geneElement.appendChild(alleleRepresentation);
     genesElement.appendChild(geneElement);
   }
   return genesElement;
 }
Beispiel #3
0
  private void loadFromXml(String fileName)
      throws ParserConfigurationException, SAXException, IOException, ParseException {
    System.out.println("NeuralNetwork : loading network topology from file " + fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.parse(fileName);

    Node nodeNeuralNetwork = doc.getDocumentElement();
    if (!nodeNeuralNetwork.getNodeName().equals("neuralNetwork"))
      throw new ParseException(
          "[Error] NN-Load: Parse error in XML file, neural network couldn't be loaded.", 0);
    // nodeNeuralNetwork ok
    // indexNeuralNetworkContent -> indexStructureContent -> indexLayerContent -> indexNeuronContent
    // -> indexNeuralInputContent
    NodeList nodeNeuralNetworkContent = nodeNeuralNetwork.getChildNodes();
    for (int innc = 0; innc < nodeNeuralNetworkContent.getLength(); innc++) {
      Node nodeStructure = nodeNeuralNetworkContent.item(innc);
      if (nodeStructure.getNodeName().equals("structure")) { // for structure element
        NodeList nodeStructureContent = nodeStructure.getChildNodes();
        for (int isc = 0; isc < nodeStructureContent.getLength(); isc++) {
          Node nodeLayer = nodeStructureContent.item(isc);
          if (nodeLayer.getNodeName().equals("layer")) { // for layer element
            NeuralLayer neuralLayer = new NeuralLayer(this);
            this.listLayers.add(neuralLayer);
            NodeList nodeLayerContent = nodeLayer.getChildNodes();
            for (int ilc = 0; ilc < nodeLayerContent.getLength(); ilc++) {
              Node nodeNeuron = nodeLayerContent.item(ilc);
              if (nodeNeuron.getNodeName().equals("neuron")) { // for neuron in layer
                Neuron neuron =
                    new Neuron(
                        Double.parseDouble(((Element) nodeNeuron).getAttribute("threshold")),
                        neuralLayer);
                neuralLayer.listNeurons.add(neuron);
                NodeList nodeNeuronContent = nodeNeuron.getChildNodes();
                for (int inc = 0; inc < nodeNeuronContent.getLength(); inc++) {
                  Node nodeNeuralInput = nodeNeuronContent.item(inc);
                  // if (nodeNeuralInput==null) System.out.print("-"); else System.out.print("*");

                  if (nodeNeuralInput.getNodeName().equals("input")) {
                    //                                        System.out.println("neuron at
                    // STR:"+innc+" LAY:"+isc+" NEU:"+ilc+" INP:"+inc);
                    NeuralInput neuralInput =
                        new NeuralInput(
                            Double.parseDouble(((Element) nodeNeuralInput).getAttribute("weight")),
                            neuron);
                    neuron.listInputs.add(neuralInput);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
Beispiel #4
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
 /**
  * Marshall a Chromosome instance to an XML Document representation, including its contained Gene
  * instances.
  *
  * @param a_subject the chromosome to represent as an XML document
  * @return a Document object representing the given Chromosome
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Document representChromosomeAsDocument(final IChromosome a_subject) {
   // DocumentBuilders do not have to be thread safe, so we have to
   // protect creation of the Document with a synchronized block.
   // -------------------------------------------------------------
   Document chromosomeDocument;
   synchronized (m_lock) {
     chromosomeDocument = m_documentCreator.newDocument();
   }
   Element chromosomeElement = representChromosomeAsElement(a_subject, chromosomeDocument);
   chromosomeDocument.appendChild(chromosomeElement);
   return chromosomeDocument;
 }
 /**
  * Marshall a Genotype to an XML Document representation, including its population of Chromosome
  * instances.
  *
  * @param a_subject the genotype to represent as an XML document
  * @return a Document object representing the given Genotype
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Document representGenotypeAsDocument(final Genotype a_subject) {
   // DocumentBuilders do not have to be thread safe, so we have to
   // protect creation of the Document with a synchronized block.
   // -------------------------------------------------------------
   Document genotypeDocument;
   synchronized (m_lock) {
     genotypeDocument = m_documentCreator.newDocument();
   }
   Element genotypeElement = representGenotypeAsElement(a_subject, genotypeDocument);
   genotypeDocument.appendChild(genotypeElement);
   return genotypeDocument;
 }
Beispiel #7
0
  /**
   * Advanced users only; use loadXML() in PApplet.
   *
   * <p>Added extra code to handle \u2028 (Unicode NLF), which is sometimes inserted by web browsers
   * (Safari?) and not distinguishable from a "real" LF (or CRLF) in some text editors (i.e.
   * TextEdit on OS X). Only doing this for XML (and not all Reader objects) because LFs are
   * essential. https://github.com/processing/processing/issues/2100
   *
   * @nowebref
   */
  public XML(final Reader reader, String options)
      throws IOException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Prevent 503 errors from www.w3.org
    try {
      factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (IllegalArgumentException e) {
      // ignore this; Android doesn't like it
    }

    // without a validating DTD, this doesn't do anything since it doesn't know what is ignorable
    //      factory.setIgnoringElementContentWhitespace(true);

    factory.setExpandEntityReferences(false);
    //      factory.setExpandEntityReferences(true);

    //      factory.setCoalescing(true);
    //      builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    //      builder.setEntityResolver()

    //      SAXParserFactory spf = SAXParserFactory.newInstance();
    //      spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    //      SAXParser p = spf.newSAXParser();

    //    builder = DocumentBuilderFactory.newDocumentBuilder();
    //    builder = new SAXBuilder();
    //    builder.setValidation(validating);

    Document document =
        builder.parse(
            new InputSource(
                new Reader() {
                  @Override
                  public int read(char[] cbuf, int off, int len) throws IOException {
                    int count = reader.read(cbuf, off, len);
                    for (int i = 0; i < count; i++) {
                      if (cbuf[off + i] == '\u2028') {
                        cbuf[off + i] = '\n';
                      }
                    }
                    return count;
                  }

                  @Override
                  public void close() throws IOException {
                    reader.close();
                  }
                }));
    node = document.getDocumentElement();
  }
Beispiel #8
0
  /** @param name creates a node with this name */
  public XML(String name) {
    try {
      // TODO is there a more efficient way of doing this? wow.
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.newDocument();
      node = document.createElement(name);
      this.parent = null;

    } catch (ParserConfigurationException pce) {
      throw new RuntimeException(pce);
    }
  }
Beispiel #9
0
    public Element reportDtElem() {
      StringBuffer sb = new StringBuffer(255);
      sb.append(shortTypeName);
      sb.append(" [ dataSourceName: ");
      sb.append(pds.getDataSourceName());
      sb.append("; identityToken: ");
      sb.append(pds.getIdentityToken());
      sb.append(" ]");

      Element dtElem = doc.createElement("dt");
      dtElem.appendChild(doc.createTextNode(sb.toString()));
      return dtElem;
    }
Beispiel #10
0
  public void read(Document doc) {
    try {
      Element root = doc.getDocumentElement();
      NodeList nList = doc.getElementsByTagName("user");
      for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
          Element element = (Element) node;
        }
      }
      //			Element e1 = (Element) nList.item(0);
    } catch (Exception e) {

    }
  }
Beispiel #11
0
  /**
   * Writes a table to a XML-file
   *
   * @param t - Output Model
   * @param destination - File Destination
   */
  public static void writeXML(Model t, String destination) {

    try {
      // Create the XML document builder, and document that will be used
      DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance();
      DocumentBuilder Builder = xmlBuilder.newDocumentBuilder();
      Document xmldoc = Builder.newDocument();

      // create Document node, and get it into the file
      Element Documentnode = xmldoc.createElement("SPREADSHEET");
      xmldoc.appendChild(Documentnode);

      // create element nodes, and their attributes (Cells, and row/column
      // data) and their content
      for (int row = 1; row < t.getRows(); row++) {
        for (int col = 1; col < t.getCols(col); col++) {
          Element cell = xmldoc.createElement("CELL");
          // set attributes
          cell.setAttribute("column", Integer.toString(col));
          cell.setAttribute("row", Integer.toString(col));
          // set content
          cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col)));
          // append node to document node
          Documentnode.appendChild(cell);
        }
      }
      // Creating a datastream for the DOM tree
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      // Indentation to make the XML file look better
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      // remove the java version
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMSource stream = new DOMSource(xmldoc);
      StreamResult target = new StreamResult(new File(destination));
      // write the file
      transformer.transform(stream, target);

    } catch (ParserConfigurationException e) {
      System.out.println("Can't create the XML document builder");
    } catch (TransformerConfigurationException e) {
      System.out.println("Can't create transformer");
    } catch (TransformerException e) {
      System.out.println("Can't write to file");
    }
  }
Beispiel #12
0
  /**
   * Method that reads a XML-file, and returns a Model that contains the information
   *
   * @param file
   * @return
   * @return
   */
  public static Model readXML(String file) {
    // initialize table to be filled with content of XML file
    Model t = new Model();
    try {
      // Create file to be parsed by document parser
      File xmlfile = new File(file);
      // create parser
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      // parse the file
      Document parsedfile = parser.parse(xmlfile);
      // normalize the parsed file (make it more user-friendly)
      parsedfile.getDocumentElement().normalize();

      NodeList cells = parsedfile.getElementsByTagName("CELL");
      for (int i = 0; i < cells.getLength(); i++) {
        // Get cell at list index i
        Node currentcell = cells.item(i);
        // read the elements "location" attributes row/column
        if (Node.ELEMENT_NODE == currentcell.getNodeType()) {
          Element cellinfo = (Element) currentcell;
          // get the row number from node attribute
          int row = Integer.parseInt(cellinfo.getAttribute("row")) - 1;
          // get the column number from the node attribute
          int col = Integer.parseInt(cellinfo.getAttribute("column")) - 1;
          // get content from node
          String content = cellinfo.getTextContent();
          if (content != null) {
            content = content.replace("\n", "");
          }
          // Make the content an Integer (if it is a number), easier
          // for
          // using it later on
          // put content in table, with row/column inserted as x/y
          t.setContent(row, col, (String) content);
        }
      }

    } catch (ParserConfigurationException e) {
      System.out.println("Fileparser could not be made");
    } catch (IOException f) {
      System.out.println("File could not be parsed, did you enter the correct file name?");
    } catch (SAXException g) {
      System.out.println("Something went wrong in parsing the file");
    }
    return t;
  }
Beispiel #13
0
  /**
   * Unlike the loadXML() method in PApplet, this version works with files that are not in UTF-8
   * format.
   *
   * @nowebref
   */
  public XML(InputStream input, String options)
      throws IOException, ParserConfigurationException, SAXException {
    // this(PApplet.createReader(input), options);  // won't handle non-UTF8
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      // Prevent 503 errors from www.w3.org
      factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (IllegalArgumentException e) {
      // ignore this; Android doesn't like it
    }

    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(input));
    node = document.getDocumentElement();
  }
Beispiel #14
0
  /**
   * Gets the string of an XML document containing multiple words for saving purposes.
   *
   * @param words The words to save.
   * @return String containing XML containing all words.
   */
  public static String getMultipleWordXML(Word[] words) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.newDocument();
      Element root = doc.createElement("Root");
      for (int i = 0; i < words.length; i++) {
        root.appendChild(words[i].getWordXMLNode(doc));
      }
      doc.appendChild(root);
      return getStringFromDocument(doc);

    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
Beispiel #15
0
  public void saveToXml(String fileName)
      throws ParserConfigurationException, FileNotFoundException, TransformerException,
          TransformerConfigurationException {
    System.out.println("Saving network topology to file " + fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.newDocument();

    Element root = doc.createElement("neuralNetwork");
    root.setAttribute("dateOfExport", new Date().toString());
    Element layers = doc.createElement("structure");
    layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers()));

    for (int il = 0; il < this.numberOfLayers(); il++) {
      Element layer = doc.createElement("layer");
      layer.setAttribute("index", Integer.toString(il));
      layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons()));

      for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) {
        Element neuron = doc.createElement("neuron");
        neuron.setAttribute("index", Integer.toString(in));
        neuron.setAttribute(
            "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs()));
        neuron.setAttribute(
            "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold));

        for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) {
          Element input = doc.createElement("input");
          input.setAttribute("index", Integer.toString(ii));
          input.setAttribute(
              "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight));

          neuron.appendChild(input);
        }

        layer.appendChild(neuron);
      }

      layers.appendChild(layer);
    }

    root.appendChild(layers);
    doc.appendChild(root);

    // save
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;

    fos = new FileOutputStream(xmlOutputFile);
    // Use a Transformer for output
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);
    // transform source into result will do save
    transformer.setOutputProperty("encoding", "iso-8859-2");
    transformer.setOutputProperty("indent", "yes");
    transformer.transform(source, result);
  }
Beispiel #16
0
 /**
  * Gets the definitions of a word, sets the main one if necessary, and returns it.
  *
  * @param overwrite if true, then function will attempt to retrieve from online even if the
  *     definition is already set.
  * @return String containing the main definition of the word.
  */
 public static Word[] getWordsFromFile(ByteArrayInputStream inputStream) {
   try {
     // now to parse the XML
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(inputStream);
     removeEmptyTextNodes(doc);
     NodeList wordList = doc.getElementsByTagName("WordDefinitions");
     int wordCount = wordList.getLength();
     Word[] returnWords = new Word[wordCount];
     for (int wordi = 0; wordi < wordCount; wordi++) {
       NodeList list = ((Element) wordList.item(wordi)).getElementsByTagName("Definition");
       Element wordElement = (Element) wordList.item(wordi);
       String word = wordElement.getAttribute("word");
       String mainDefinition = wordElement.getAttribute("mainDefinition");
       int numDefinitions = list.getLength();
       Definition[] wordOtherDefinitions = new Definition[numDefinitions];
       for (int i = 0; i < numDefinitions; i++) {
         Node node = list.item(i);
         NodeList children = node.getChildNodes(); // gets each child node of the definition
         // get all data
         String definition = children.item(XML_DEFINITION_LOC).getTextContent();
         String theWord = children.item(XML_WORD_LOC).getTextContent();
         NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes();
         String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent();
         String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent();
         // now we've got all the data lets add it to the array
         wordOtherDefinitions[i] =
             new Definition(dictionaryName, dictionaryId, definition, theWord);
       }
       if (wordOtherDefinitions.length == 0) {
         wordOtherDefinitions =
             new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)};
       }
       Word currentWord = new Word(word, mainDefinition);
       currentWord.setOtherDefinitions(wordOtherDefinitions);
       returnWords[wordi] = currentWord;
     }
     return returnWords;
   } catch (Exception ex) {
     ex.printStackTrace();
     return null;
   }
 }
Beispiel #17
0
  /** used for cut and paste. */
  public void addObjectFromClipboard(String a_value) throws CircularIncludeException {
    Reader reader = new StringReader(a_value);
    Document document = null;
    try {
      document = UJAXP.getDocument(reader);
    } catch (Exception e) {
      e.printStackTrace();
      return;
    } // try-catch

    Element root = document.getDocumentElement();
    if (!root.getNodeName().equals("clipboard")) {
      return;
    } // if

    Node child;
    for (child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (!(child instanceof Element)) {
        continue;
      } // if
      Element element = (Element) child;

      IGlyphFactory factory = GlyphFactory.getFactory();

      if (XModule.isMatch(element)) {
        EModuleInvoke module = (EModuleInvoke) factory.createXModule(element);
        addModule(module);
        continue;
      } // if

      if (XContour.isMatch(element)) {
        EContour contour = (EContour) factory.createXContour(element);
        addContour(contour);
        continue;
      } // if

      if (XInclude.isMatch(element)) {
        EIncludeInvoke include = (EIncludeInvoke) factory.createXInclude(element);
        addInclude(include);
        continue;
      } // if
    } // while
  }
Beispiel #18
0
  /**
   * Save the XML description of the circuit
   *
   * @param output an output stream to write in
   * @return true if the dump was successful, false either
   */
  public boolean dumpToXml(OutputStream output) {
    Document doc;
    Element root;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.newDocument();
    } catch (ParserConfigurationException pce) {
      System.err.println("dumpToXmlFile: unable to write XML save file.");
      return false;
    }

    root = doc.createElement("Circuit");
    root.setAttribute("name", this.getName());

    for (iterNodes = this.nodes.iterator(); iterNodes.hasNext(); )
      iterNodes.next().dumpToXml(doc, root);

    root.normalize();
    doc.appendChild(root);

    try {
      TransformerFactory tffactory = TransformerFactory.newInstance();
      Transformer transformer = tffactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(output);
      transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
      System.err.println("dumpToXmlFile:  Configuration Transformer exception.");
      return false;
    } catch (TransformerException te) {
      System.err.println("dumpToXmlFile: Transformer exception.");
      return false;
    }

    return true;
  }
Beispiel #19
0
 /**
  * Gets the definitions of a word, sets the main one if necessary, and returns it.
  *
  * @param overwrite if true, then function will attempt to retrieve from online even if the
  *     definition is already set.
  * @return String containing the main definition of the word.
  */
 public String getDefinitions(ByteArrayInputStream inputStream, boolean overwrite) {
   if (overwrite || (definition == null || definition.isEmpty())) {
     // get definition from online service
     // if not able to access internet, then do something
     try {
       // now to parse the XML
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       DocumentBuilder db = dbf.newDocumentBuilder();
       Document doc = db.parse(inputStream);
       removeEmptyTextNodes(doc);
       NodeList list = doc.getElementsByTagName("Definition");
       int numDefinitions = list.getLength();
       otherDefinitions = new Definition[numDefinitions];
       for (int i = 0; i < numDefinitions; i++) {
         Node node = list.item(i);
         NodeList children = node.getChildNodes(); // gets each child node of the definition
         // get all data
         String definition = children.item(XML_DEFINITION_LOC).getTextContent();
         String word = children.item(XML_WORD_LOC).getTextContent();
         NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes();
         String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent();
         String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent();
         // now we've got all the data lets add it to the array
         otherDefinitions[i] = new Definition(dictionaryName, dictionaryId, definition, word);
       }
       if (otherDefinitions.length == 0) {
         otherDefinitions =
             new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)};
       }
       this.setMainDefinition(otherDefinitions[0].getDefinition());
       return otherDefinitions[0].getDefinition();
     } catch (Exception ex) {
       ex.printStackTrace();
       return "ERROR! " + ex;
     }
   } else {
     return this.definition;
   }
 }
Beispiel #20
0
  private void call(String script)
      throws ParserConfigurationException, TransformerConfigurationException {
    File callerScript = this.currentScript;
    Document doc = null;
    try {
      this.currentScript = new File(script);
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      doc = db.parse(this.currentScript);
    } catch (Exception ex) {
      this.currentScript = callerScript;
      Utils.onError(new Error.FileParse(script));
      return;
    }

    NodeList operations = doc.getDocumentElement().getChildNodes();
    for (int i = 0; i < operations.getLength(); i++) {
      Node operation = operations.item(i);
      if (operation.getNodeType() != Node.ELEMENT_NODE) continue;
      call(operation);
    }
    this.currentScript = callerScript;
  }
 /**
  * Marshall a Chromosome instance to an XML Element representation, including its contained Genes
  * as sub-elements. This may be useful in scenarios where representation as an entire Document is
  * undesirable, such as when the representation of this Chromosome is to be combined with other
  * elements in a single Document.
  *
  * @param a_subject the chromosome to represent as an XML element
  * @param a_xmlDocument a Document instance that will be used to create the Element instance. Note
  *     that the element will NOT be added to the document by this method
  * @return an Element object representing the given Chromosome
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representChromosomeAsElement(
     final IChromosome a_subject, final Document a_xmlDocument) {
   // Start by creating an element for the chromosome and its size
   // attribute, which represents the number of genes in the chromosome.
   // ------------------------------------------------------------------
   Element chromosomeElement = a_xmlDocument.createElement(CHROMOSOME_TAG);
   chromosomeElement.setAttribute(SIZE_ATTRIBUTE, Integer.toString(a_subject.size()));
   // Next create the genes element with its nested gene elements,
   // which will contain string representations of the alleles.
   // --------------------------------------------------------------
   Element genesElement = representGenesAsElement(a_subject.getGenes(), a_xmlDocument);
   // Add the new genes element to the chromosome element and then
   // return the chromosome element.
   // -------------------------------------------------------------
   chromosomeElement.appendChild(genesElement);
   return chromosomeElement;
 }
 /**
  * Unmarshall a Chromosome instance from a given XML Document representation. Its genes will be
  * unmarshalled from the gene sub-elements.
  *
  * @param a_activeConfiguration the current active Configuration object that is to be used during
  *     construction of the Chromosome instances
  * @param a_xmlDocument the XML Document representation of the Chromosome
  * @return a new Chromosome instance setup with the data from the XML Document representation
  * @throws ImproperXMLException if the given Document is improperly structured or missing data
  * @throws InvalidConfigurationException if the given Configuration is in an inconsistent state
  * @throws UnsupportedRepresentationException if the actively configured Gene implementation does
  *     not support the string representation of the alleles used in the given XML document
  * @throws GeneCreationException if there is a problem creating or populating a Gene instance
  * @author Neil Rotstan
  * @since 1.0
  */
 public static Chromosome getChromosomeFromDocument(
     Configuration a_activeConfiguration, Document a_xmlDocument)
     throws ImproperXMLException, InvalidConfigurationException,
         UnsupportedRepresentationException, GeneCreationException {
   // Extract the root element, which should be a chromosome element.
   // After verifying that the root element is not null and that it
   // in fact is a chromosome element, then convert it into a Chromosome
   // instance.
   // ------------------------------------------------------------------
   Element rootElement = a_xmlDocument.getDocumentElement();
   if (rootElement == null || !(rootElement.getTagName().equals(CHROMOSOME_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Document: "
             + "'chromosome' element must be at root of Document.");
   }
   return getChromosomeFromElement(a_activeConfiguration, rootElement);
 }
 /**
  * Marshall a Genotype instance into an XML Element representation, including its population of
  * Chromosome instances as sub-elements. This may be useful in scenarios where representation as
  * an entire Document is undesirable, such as when the representation of this Genotype is to be
  * combined with other elements in a single Document.
  *
  * @param a_subject the genotype to represent as an XML element
  * @param a_xmlDocument a Document instance that will be used to create the Element instance. Note
  *     that the element will NOT be added to the document by this method
  * @return an Element object representing the given Genotype
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representGenotypeAsElement(
     final Genotype a_subject, final Document a_xmlDocument) {
   Population population = a_subject.getPopulation();
   // Start by creating the genotype element and its size attribute,
   // which represents the number of chromosomes present in the
   // genotype.
   // --------------------------------------------------------------
   Element genotypeTag = a_xmlDocument.createElement(GENOTYPE_TAG);
   genotypeTag.setAttribute(SIZE_ATTRIBUTE, Integer.toString(population.size()));
   // Next, add nested elements for each of the chromosomes in the
   // genotype.
   // ------------------------------------------------------------
   for (int i = 0; i < population.size(); i++) {
     Element chromosomeElement =
         representChromosomeAsElement(population.getChromosome(i), a_xmlDocument);
     genotypeTag.appendChild(chromosomeElement);
   }
   return genotypeTag;
 }
Beispiel #24
0
  /**
   * Gets XML string for this definition so that it may be printed.
   *
   * @return XML node that can be saved of this word.
   */
  public Element getWordXMLNode(Document doc) {
    try {
      Element rootWordElement = doc.createElement("WordDefinitions");
      rootWordElement.setAttribute("word", this.word);
      rootWordElement.setAttribute("mainDefinition", this.getMainDefinition());
      if (this.otherDefinitions == null) {
        this.getDefinitions();
      }
      for (int i = 0; i < this.otherDefinitions.length; i++) {
        // main definition node
        Element definition = doc.createElement("Definition");

        // word
        Element word = doc.createElement("Word");
        word.setTextContent(otherDefinitions[i].getWord());

        // dictionary
        Element dictionary = doc.createElement("Dictionary");
        Element id = doc.createElement("Id");
        id.setTextContent(otherDefinitions[i].getId());
        Element source = doc.createElement("Name");
        source.setTextContent(otherDefinitions[i].getSource());
        dictionary.appendChild(id);
        dictionary.appendChild(source);

        // definition
        Element wordDefinition = doc.createElement("WordDefinition");
        wordDefinition.setTextContent(otherDefinitions[i].getDefinition());

        // append all the children
        definition.appendChild(word);
        definition.appendChild(dictionary);
        definition.appendChild(wordDefinition);
        rootWordElement.appendChild(definition);
      }
      return rootWordElement;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
Beispiel #25
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);
  }
Beispiel #26
0
  /**
   * XML Circuit constructor
   *
   * @param file the file that contains the XML description of the circuit
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public CircuitUI(File file, Graphics g) throws CircuitLoadingException {
    this("");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    Element root;

    Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>();

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.parse(file);
    } catch (SAXException sxe) {
      throw new CircuitLoadingException("SAX exception raised, invalid XML file.");
    } catch (ParserConfigurationException pce) {
      throw new CircuitLoadingException(
          "Parser exception raised, parser configuration is invalid.");
    } catch (IOException ioe) {
      throw new CircuitLoadingException("I/O exception, file cannot be loaded.");
    }

    root = (Element) doc.getElementsByTagName("Circuit").item(0);
    this.setName(root.getAttribute("name"));

    NodeList nl = root.getElementsByTagName("Node");
    Element e;
    Node n;
    Class cl;

    for (int i = 0; i < nl.getLength(); ++i) {
      e = (Element) nl.item(i);

      try {
        cl = Class.forName(e.getAttribute("class"));
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      try {
        n = ((Node) cl.newInstance());
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      this.nodes.add(n);
      n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y")));

      if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name"));

      if (n instanceof giraffe.ui.CompositeNode) {
        try {
          ((CompositeNode) n)
              .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g);
        } catch (Exception exc) {
          /* try to load from the lib */
          ((CompositeNode) n)
              .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g);
        }
      }

      NodeList nlist = e.getElementsByTagName("Anchor");
      Element el;

      for (int j = 0; j < nlist.getLength(); ++j) {
        el = (Element) nlist.item(j);

        Anchor a = n.getAnchor(new Integer(el.getAttribute("id")));
        NodeList linklist = el.getElementsByTagName("Link");
        Element link;
        Link l;

        for (int k = 0; k < linklist.getLength(); ++k) {
          link = (Element) linklist.item(k);
          int id = new Integer(link.getAttribute("id"));
          int index = new Integer(link.getAttribute("index"));

          if (id >= this.linkID) linkID = id + 1;

          if (linkstable.containsKey(id)) {
            l = linkstable.get(id);
            l.addLinkedAnchorAt(a, index);
            a.addLink(l);
          } else {
            l = new Link(id);
            l.addLinkedAnchorAt(a, index);
            this.links.add(l);
            linkstable.put(id, l);
            a.addLink(l);
          }
        }
      }
    }
  }
Beispiel #27
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();
    }
  }
Beispiel #29
0
 public XML addChild(XML child) {
   Document document = node.getOwnerDocument();
   Node newChild = document.importNode((Node) child.getNative(), true);
   return appendChild(newChild);
 }
Beispiel #30
0
 /**
  * @webref xml:method
  * @brief Appends a new child to the element
  */
 public XML addChild(String tag) {
   Document document = node.getOwnerDocument();
   Node newChild = document.createElement(tag);
   return appendChild(newChild);
 }