Esempio n. 1
0
 private Node getTextNode() {
   NodeList list = element.getChildNodes();
   int length = list.getLength();
   for (int i = 0; i < length; i++) {
     Node node = list.item(i);
     if (node.getNodeType() == Node.TEXT_NODE) {
       return node;
     }
   }
   return element.appendChild(element.getOwnerDocument().createTextNode(""));
 }
Esempio n. 2
0
  public static List<Tombstone> loadTombstone(String chestsPath, DeathChests plugin) {
    LinkedList<Tombstone> deathChests = new LinkedList<>();
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Start the parser
      Document doc = builder.parse(new File(chestsPath));

      Element rootElement = doc.getDocumentElement();

      String version = rootElement.getAttribute("version");
      if (!Settings.getVersion().equals(version)) {
        System.out.println(
            "The version of the Deathchests-File changed. There are possible errors at loading them. (Probably not if your updated it)");
      }

      long timestamp = System.currentTimeMillis();

      NodeList list = rootElement.getChildNodes();
      int length = list.getLength();
      for (int i = 0; i < length; i++) {
        try {
          Node node = list.item(i);
          String name = node.getNodeName();
          if (name.equalsIgnoreCase(Utils.DEATHCHEST_XML_TAG)) {
            deathChests.add(new Tombstone((Element) node, timestamp, plugin));
          }
        } catch (XMLParseException ex) {
          System.err.println("Corrupted deathchest! Skipping this one!");
          ex.printStackTrace();
        }
      }
    } catch (IOException | ParserConfigurationException | SAXException ex) {
      System.err.println("Error while loading deathchest data:");
      ex.printStackTrace();
    }
    return deathChests;
  }
Esempio n. 3
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;
    }

    // #]
  }
Esempio n. 4
0
  void xml() {
    try {
      File file = new File("c:\\users\\jason\\desktop\\proxies.xml");

      // Create instance of DocumentBuilderFactory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      // Get the DocumentBuilder
      DocumentBuilder docBuilder = factory.newDocumentBuilder();

      // Using existing XML Document
      Document doc = docBuilder.parse(file);

      // normalize the text
      doc.getDocumentElement().normalize();

      // gets just the name of the root
      String simple_root = doc.getDocumentElement().getNodeName();

      Element root = doc.getDocumentElement();

      // gets the ip elements
      NodeList proxy = doc.getElementsByTagName("proxy");

      // checks the make sure i got the ip elements by printing out the number of occurances
      int total = proxy.getLength();

      NodeList list = doc.getElementsByTagName("*");
      System.out.println("\nElements in the proxy file:");
      int proxy_num = 1;
      for (int i = 0; i < list.getLength(); i++) {
        Node num2 = proxy.item(i);
        Element second = (Element) num2;
        Element element2 = (Element) list.item(i);
        NodeList text2 = element2.getChildNodes();
        if (element2.getNodeName() != "proxies" && element2.getNodeName() != "proxy") {
          if (element2.getNodeName() == "ip") {
            System.out.println("");
            System.out.println("Proxy #: " + proxy_num);
            proxy_num++;
            System.out.println(
                element2.getNodeName() + ": " + ((Node) text2.item(0)).getNodeValue().trim());

          } else
            System.out.println(
                element2.getNodeName() + ": " + ((Node) text2.item(0)).getNodeValue().trim());
          if (element2.getNodeName() == "source-ip") {
            ip = ((Node) text2.item(0)).getNodeValue().trim();
            myArr.add(ip);
            jComboBox.addItem(ip);
          }
        }
      }

      // set up a transformer
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();

      // create string from xml tree
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      DOMSource source = new DOMSource(doc);
      trans.transform(source, result);
      String xmlString = sw.toString();

      OutputStream f0;
      byte buf[] = xmlString.getBytes();
      f0 = new FileOutputStream("c:\\users\\jason\\desktop\\connections.xml");
      for (int i = 0; i < buf.length; i++) {
        f0.write(buf[i]);
      }
      f0.close();
      buf = null;
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }
 /**
  * Unmarshall a Chromosome instance from a given XML Element representation.
  *
  * @param a_activeConfiguration current Configuration object
  * @param a_xmlElement the XML Element representation of the Chromosome
  * @return a new Chromosome instance setup with the data from the XML Element representation
  * @throws ImproperXMLException if the given Element is improperly structured or missing data
  * @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 Gene[] getGenesFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException {
   // Do some sanity checking. Make sure the XML Element isn't null and
   // that it in fact represents a set of genes.
   // -----------------------------------------------------------------
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "given Element is not a 'genes' element.");
   }
   List genes = Collections.synchronizedList(new ArrayList());
   // Extract the nested gene elements.
   // ---------------------------------
   NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG);
   if (geneElements == null) {
     throw new ImproperXMLException(
         "Unable to build Gene instances from XML Element: "
             + "'"
             + GENE_TAG
             + "'"
             + " sub-elements not found.");
   }
   // For each gene, get the class attribute so we know what class
   // to instantiate to represent the gene instance, and then find
   // the child text node, which is where the string representation
   // of the allele is located, and extract the representation.
   // -------------------------------------------------------------
   int numberOfGeneNodes = geneElements.getLength();
   for (int i = 0; i < numberOfGeneNodes; i++) {
     Element thisGeneElement = (Element) geneElements.item(i);
     thisGeneElement.normalize();
     // Fetch the class attribute and create an instance of that
     // class to represent the current gene.
     // --------------------------------------------------------
     String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE);
     Gene thisGeneObject;
     Class geneClass = null;
     try {
       geneClass = Class.forName(geneClassName);
       try {
         Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration});
       } catch (NoSuchMethodException nsme) {
         // Try it by calling method newGeneInternal.
         // -----------------------------------------
         Constructor constr = geneClass.getConstructor(new Class[] {});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {});
         thisGeneObject =
             (Gene)
                 PrivateAccessor.invoke(
                     thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {});
       }
     } catch (Throwable e) {
       throw new GeneCreationException(geneClass, e);
     }
     // Find the text node and fetch the string representation of
     // the allele.
     // ---------------------------------------------------------
     NodeList children = thisGeneElement.getChildNodes();
     int childrenSize = children.getLength();
     String alleleRepresentation = null;
     for (int j = 0; j < childrenSize; j++) {
       Element alleleElem = (Element) children.item(j);
       if (alleleElem.getTagName().equals(ALLELE_TAG)) {
         alleleRepresentation = alleleElem.getAttribute("value");
       }
       if (children.item(j).getNodeType() == Node.TEXT_NODE) {
         // We found the text node. Extract the representation.
         // ---------------------------------------------------
         alleleRepresentation = children.item(j).getNodeValue();
         break;
       }
     }
     // Sanity check: Make sure the representation isn't null.
     // ------------------------------------------------------
     if (alleleRepresentation == null) {
       throw new ImproperXMLException(
           "Unable to build Gene instance from XML Element: "
               + "value (allele) is missing representation.");
     }
     // Now set the value of the gene to that reflect the
     // string representation.
     // -------------------------------------------------
     try {
       thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation);
     } catch (UnsupportedOperationException e) {
       throw new GeneCreationException(
           "Unable to build Gene because it does not support the "
               + "setValueFromPersistentRepresentation() method.");
     }
     // Finally, add the current gene object to the list of genes.
     // ----------------------------------------------------------
     genes.add(thisGeneObject);
   }
   return (Gene[]) genes.toArray(new Gene[genes.size()]);
 }