Example #1
0
  /**
   * Performs an XPATH lookup in an xml document whose filename is specified by the first parameter
   * (assumed to be in the auxiliary subdirectory) The XPATH expression is supplied as the second
   * string parameter The return value is of type string e.g. this is currently used primarily for
   * looking up the Company Prefix Index for encoding a GS1 Company Prefix into a 64-bit EPC tag
   */
  private String xpathlookup(String xml, String expression) {

    try {

      // Parse the XML as a W3C document.
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document =
          builder.parse(new File(xmldir + File.separator + "auxiliary" + File.separator + xml));

      XPath xpath = XPathFactory.newInstance().newXPath();

      String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING);

      return rv;

    } catch (ParserConfigurationException e) {
      System.err.println("ParserConfigurationException caught...");
      e.printStackTrace();
      return null;
    } catch (XPathExpressionException e) {
      System.err.println("XPathExpressionException caught...");
      e.printStackTrace();
      return null;
    } catch (SAXException e) {
      System.err.println("SAXException caught...");
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      System.err.println("IOException caught...");
      e.printStackTrace();
      return null;
    }
  }
 Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }
Example #3
0
 private void indexFiles(String dir, String index, int featureIndex, boolean createNewIndex)
     throws IOException {
   ArrayList<String> images = FileUtils.getAllImages(new File(dir), true);
   IndexWriter iw =
       LuceneUtils.createIndexWriter(
           index, createNewIndex, LuceneUtils.AnalyzerType.WhitespaceAnalyzer);
   // select one feature for the large index:
   int count = 0;
   long ms = System.currentTimeMillis();
   DocumentBuilder builder = new ChainedDocumentBuilder();
   ((ChainedDocumentBuilder) builder).addBuilder(builders[featureIndex]);
   //        ((ChainedDocumentBuilder) builder).addBuilder(builders[0]);
   for (Iterator<String> iterator = images.iterator(); iterator.hasNext(); ) {
     count++;
     if (count > 100 && count % 5000 == 0) {
       System.out.println(
           count
               + " files indexed. "
               + (System.currentTimeMillis() - ms) / (count)
               + " ms per file");
     }
     String file = iterator.next();
     try {
       iw.addDocument(builder.createDocument(new FileInputStream(file), file));
     } catch (Exception e) {
       System.err.println("Error: " + e.getMessage());
     }
   }
   iw.close();
 }
  // Lee la configuracion que se encuentra en conf/RegistryConf
  private void readConfXml() {
    try {
      File inputFile = new File("src/java/Conf/RegistryConf.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(inputFile);
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("RegistryConf");
      for (int i = 0; i < nList.getLength(); i++) {
        Node nNode = nList.item(i);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) nNode;
          RegistryConf reg = new RegistryConf();
          String aux;
          int idSensor;
          int value;
          aux = eElement.getElementsByTagName("idSensor").item(0).getTextContent();
          idSensor = Integer.parseInt(aux);
          reg.setIdSensor(idSensor);

          aux = eElement.getElementsByTagName("saveType").item(0).getTextContent();
          reg.setSaveTypeString(aux);

          aux = eElement.getElementsByTagName("value").item(0).getTextContent();
          value = Integer.parseInt(aux);
          reg.setValue(value);

          registryConf.add(reg);
          lastRead.put(idSensor, 0);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #5
0
  private void guardaRes(String resu, CliGol cliGol)
      throws ParserConfigurationException, SAXException, IOException {

    String[] nodos = {"NoHit", "Hit", "Buro"};

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(resu));
    Document xml = db.parse(is);

    Element raiz = xml.getDocumentElement();

    String nombre = obtenerNombre(raiz);

    for (String s : nodos) {

      Node nodo =
          raiz.getElementsByTagName(s) == null ? null : raiz.getElementsByTagName(s).item(0);

      if (nodo != null) {
        String informacion = sustraerInformacionNodo(cliGol, nodo);

        guardarEnListas(nodo.getNodeName(), nombre + "," + informacion);
      }
    }
  }
Example #6
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);
  }
Example #7
0
  /**
   * Create from factory a DocumentBuilder and let it create a org.w3c.dom.Document. This method
   * takes InputSource. After successful finish the document tree is returned.
   *
   * @param input a parser input (for URL users use: <code>new InputSource(url.toExternalForm())
   *     </code>
   * @param validate if true validating parser is used
   * @param namespaceAware if true DOM is created by namespace aware parser
   * @param errorHandler a error handler to notify about exception or <code>null</code>
   * @param entityResolver SAX entity resolver or <code>null</code>; see class Javadoc for hints
   * @throws IOException if an I/O problem during parsing occurs
   * @throws SAXException is thrown if a parser error occurs
   * @throws FactoryConfigurationError Application developers should never need to directly catch
   *     errors of this type.
   * @return document representing given input, or null if a parsing error occurs
   */
  public static Document parse(
      InputSource input,
      boolean validate,
      boolean namespaceAware,
      ErrorHandler errorHandler,
      EntityResolver entityResolver)
      throws IOException, SAXException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validate);
    factory.setNamespaceAware(namespaceAware);

    DocumentBuilder builder = null;
    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
      throw new SAXException(
          "Cannot create parser satisfying configuration parameters", ex); // NOI18N
    }

    if (errorHandler != null) {
      builder.setErrorHandler(errorHandler);
    }

    if (entityResolver != null) {
      builder.setEntityResolver(entityResolver);
    }

    return builder.parse(input);
  }
  public ArrayList<String> parseXML() throws Exception {
    ArrayList<String> ret = new ArrayList<String>();

    handshake();

    URL url =
        new URL(
            "http://mangaonweb.com/page.do?cdn="
                + cdn
                + "&cpn=book.xml&crcod="
                + crcod
                + "&rid="
                + (int) (Math.random() * 10000));
    String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(page));
    Document d = builder.parse(is);
    Element doc = d.getDocumentElement();

    NodeList pages = doc.getElementsByTagName("page");
    total = pages.getLength();
    for (int i = 0; i < pages.getLength(); i++) {
      Element e = (Element) pages.item(i);
      ret.add(e.getAttribute("path"));
    }

    return (ret);
  }
  /**
   * Constructor
   *
   * @param filename the XML config file
   */
  public LdapConfig(String filename) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(filename);

    // -- root element
    Node node = document.getFirstChild();
    while (node != null && node.getNodeType() != Node.ELEMENT_NODE) node = node.getNextSibling();

    if (node == null || !node.getNodeName().equals("ldap"))
      throw new Exception("root element is different from 'ldap'");

    this.ldapUrl = node.getAttributes().getNamedItem("url").getNodeValue();

    node = node.getFirstChild();
    while (node != null) {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if (node.getNodeName().equals("authentication")) handleAuthentication(node);
        else if (node.getNodeName().equals("plugins")) handlePlugins(node);
        else if (node.getNodeName().equals("services")) handleServices(node);
        else if (node.getNodeName().equals("users")) handleUsers(node);
        else if (node.getNodeName().equals("groups")) handleGroups(node);
        else Logging.getLogger().warning("unexepected node : " + node.getNodeName());
      }
      node = node.getNextSibling();
    }
  }
  @Test
  public void testExceptions() {
    SolrCore core = h.getCore();

    // make sure a null value is not indexed
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "123", 1.0f);
    doc.addField("unknown", "something", 1.0f);
    try {
      DocumentBuilder.toDocument(doc, core.getLatestSchema());
      fail("added an unknown field");
    } catch (Exception ex) {
      assertTrue("should have document ID", ex.getMessage().indexOf("doc=123") > 0);
    }
    doc.remove("unknown");

    doc.addField("weight", "not a number", 1.0f);
    try {
      DocumentBuilder.toDocument(doc, core.getLatestSchema());
      fail("invalid 'float' field value");
    } catch (Exception ex) {
      assertTrue("should have document ID", ex.getMessage().indexOf("doc=123") > 0);
      assertTrue("cause is number format", ex.getCause() instanceof NumberFormatException);
    }

    // now make sure it is OK
    doc.setField("weight", "1.34", 1.0f);
    DocumentBuilder.toDocument(doc, core.getLatestSchema());
  }
 public static void main(String args[]) throws Exception {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   DocumentBuilder parser = dbf.newDocumentBuilder();
   Document xmldoc = parser.parse("addr.xml");
   Element root = xmldoc.getDocumentElement();
   System.out.println(root);
 }
Example #12
0
  private void indexFiles(ArrayList<String> images, DocumentBuilder builder, String indexPath)
      throws IOException {
    // eventually check if the directory is there or not ...
    IndexWriter iw = LuceneUtils.createIndexWriter(testIndex, false);
    int count = 0;
    long time = System.currentTimeMillis();
    for (String identifier : images) {
      // TODO: cut toes from the image ... -> doesn't work out very well. Stable at first,
      // decreasing then.
      // TODO: Joint Histogram ...
      // TODO: LSA / PCA on the vectors ...-> this looks like a job for me :-D
      // TODO: local features ...
      Document doc = null;
      if (cutImages) {
        BufferedImage bimg =
            ImageUtils.cropImage(ImageIO.read(new FileInputStream(identifier)), 0, 0, 200, 69);
        doc = builder.createDocument(bimg, identifier);
      } else doc = builder.createDocument(new FileInputStream(identifier), identifier);
      iw.addDocument(doc);
      count++;
      if (count % 100 == 0) {
        int percent = (int) Math.floor(((double) count * 100.0) / (double) images.size());
        double timeTemp = (double) (System.currentTimeMillis() - time) / 1000d;
        int secsLeft =
            (int) Math.round(((timeTemp / (double) count) * (double) images.size()) - timeTemp);
        System.out.println(percent + "% finished (" + count + " files), " + secsLeft + " s left");
      }
    }
    long timeTaken = (System.currentTimeMillis() - time);
    float sec = ((float) timeTaken) / 1000f;

    System.out.println(sec + " seconds taken, " + (timeTaken / count) + " ms per image.");
    iw.commit();
    iw.close();
  }
  /**
   * WhiteboardObjectTextJabberImpl constructor.
   *
   * @param xml the XML string object to parse.
   */
  public WhiteboardObjectTextJabberImpl(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      InputStream in = new ByteArrayInputStream(xml.getBytes());
      Document doc = builder.parse(in);

      Element e = doc.getDocumentElement();
      String elementName = e.getNodeName();
      if (elementName.equals("text")) {
        // we have a text
        String id = e.getAttribute("id");
        double x = Double.parseDouble(e.getAttribute("x"));
        double y = Double.parseDouble(e.getAttribute("y"));
        String fill = e.getAttribute("fill");
        String fontFamily = e.getAttribute("font-family");
        int fontSize = Integer.parseInt(e.getAttribute("font-size"));
        String text = e.getTextContent();

        this.setID(id);
        this.setWhiteboardPoint(new WhiteboardPoint(x, y));
        this.setFontName(fontFamily);
        this.setFontSize(fontSize);
        this.setText(text);
        this.setColor(Color.decode(fill).getRGB());
      }
    } catch (ParserConfigurationException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (Exception ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    }
  }
Example #14
0
  @Override
  public Parse parse(ContentEntity entity, Task newLink) throws DroidsException, IOException {

    Document document = null;
    InputStream stream = entity.obtainContent();
    try {
      for (DocumentBuilder builder : documentBuilders) {
        if (document != null) {
          // Reconvert the existing document back to a stream
          try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Source xmlSource = new DOMSource(document);
            Result outputTarget = new StreamResult(outputStream);
            TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
            stream.close();
            stream = new ByteArrayInputStream(outputStream.toByteArray());
          }
        }

        document = builder.build(stream);
      }
    } catch (TransformerException ex) {
      logger.log(Level.WARNING, "Unable to process URI " + newLink.getURI().toASCIIString(), ex);
    } finally {
      stream.close();
    }

    return new ParseImpl(newLink.getId(), document, null);
  }
Example #15
0
  public List parsePage(String pageCode) {
    List sections = new ArrayList();
    List folders = new ArrayList();
    List files = new ArrayList();
    int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\"");
    int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\"");
    String usefulSection = "";
    if (start != -1 && end != -1) {
      usefulSection = pageCode.substring(start, end);
    } else {
      debug("Could not parse page");
    }
    try {
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(usefulSection));
      Document doc = db.parse(is);

      NodeList divs = doc.getElementsByTagName("div");
      for (int i = 0; i < divs.getLength(); i++) {
        Element div = (Element) divs.item(i);
        boolean isFolder = false;
        if (div.getAttribute("class").equals("filename")) {
          NodeList imgs = div.getElementsByTagName("img");
          for (int j = 0; j < imgs.getLength(); j++) {
            Element img = (Element) imgs.item(j);
            if (img.getAttribute("class").indexOf("folder") > 0) {
              isFolder = true;
            } else {
              isFolder = false; // it's a file
            }
          }

          NodeList anchors = div.getElementsByTagName("a");
          Element anchor = (Element) anchors.item(0);
          String attr = anchor.getAttribute("href");
          String fileName = anchor.getAttribute("title");
          String fileURL;
          if (isFolder && !attr.equals("#")) {
            folders.add(attr);
            folders.add(fileName);
          } else if (!isFolder && !attr.equals("#")) {
            // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be
            // sneaky here.
            fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1";
            files.add(fileURL);
            files.add(fileName);
          }
        }
      }
    } catch (Exception e) {
      debug(e.toString());
    }

    sections.add(files);
    sections.add(folders);

    return sections;
  }
Example #16
0
 /**
  * Creates an AppConfig using class <code>pAppClass</code> to search for the config file resource.
  * That class must have a resource file <code>AppConfig.xml</code>.
  */
 private AppConfig(InputSource pInputSource) throws InvalidInputException, DataNotFoundException {
   try {
     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     Document document = builder.parse(pInputSource);
     mConfigFileDocument = document;
   } catch (Exception e) {
     e.printStackTrace(System.err);
     throw new InvalidInputException("unable to load XML configuration file", e);
   }
 }
 public static Document newXMLDocument() {
   DocumentBuilder dbuilder = null;
   try {
     dbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   } catch (ParserConfigurationException e) {
     e.printStackTrace();
     return null;
   }
   return dbuilder.newDocument();
 }
Example #18
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);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  public static void main(String[] args) throws Exception {
    // The path to the documents directory.
    String dataDir = Utils.getDataDir(InsertNestedFields.class);

    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    // Insert few page breaks (just for testing)
    for (int i = 0; i < 5; i++) builder.insertBreak(BreakType.PAGE_BREAK);

    // Move DocumentBuilder cursor into the primary footer.
    builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);

    // We want to insert a field like this:
    // { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
    Field field = builder.insertField("IF ");
    builder.moveTo(field.getSeparator());
    builder.insertField("PAGE");
    builder.write(" <> ");
    builder.insertField("NUMPAGES");
    builder.write(" \"See Next Page\" \"Last Page\" ");

    // Finally update the outer field to recalcaluate the final value. Doing this will automatically
    // update
    // the inner fields at the same time.
    field.update();

    doc.save(dataDir + "InsertNestedFields Out.docx");

    System.out.println("Nested fields inserted into the document successfully.");
  }
Example #20
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);
    }
  }
Example #21
0
 /** Возвращает объект Document, который является объектным представлением XML документа. */
 private static Document getDocument() throws Exception {
   try {
     DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
     f.setValidating(false);
     DocumentBuilder builder = f.newDocumentBuilder();
     return builder.parse(new File("app.xml"));
   } catch (Exception exception) {
     String message = "XML parsing error!";
     throw new Exception(message);
   }
 }
 public WikipediaMinerAnnotator(String configFile)
     throws ParserConfigurationException, FileNotFoundException, SAXException, IOException,
         XPathExpressionException {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document doc = builder.parse(new FileInputStream(configFile));
   url = getConfigValue("access", "url", doc);
   if (url.equals(""))
     throw new AnnotationException(
         "Configuration file " + configFile + " has missing value 'url'.");
 }
Example #23
0
 public static Document getDocumentE(String filename) throws Exception {
   File f = new File(filename);
   if (!f.exists()) {
     throw new FileNotFoundException(filename);
   }
   Document doc = null;
   DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
   DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
   doc = docBuilder.parse(filename);
   return doc;
 }
Example #24
0
 public static Document getDocument() {
   Document doc = null;
   try {
     DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
     doc = docBuilder.newDocument();
   } catch (Exception exc) {
     log.error("XmlWorks::getDocument()", exc);
   }
   return doc;
 }
Example #25
0
 public XMLHelper(String root) {
   this();
   try {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     DocumentBuilder builder = factory.newDocumentBuilder();
     Document document = builder.newDocument();
     setElement((Element) document.appendChild(document.createElement(root)));
   } catch (ParserConfigurationException e) {
     // Not quite sure when this would happen
     severe("Could not extantiate XML builder: " + e.getMessage());
   }
 }
Example #26
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();
  }
Example #27
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);
    }
  }
Example #28
0
  public apiParser(String sdkfile) {
    System.out.println(sdkfile);
    File file = new File(sdkfile);
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(file);
      NodeList apiList = doc.getElementsByTagName("n1:api");
      NodeList inputList = doc.getElementsByTagName("n1:input");
      NodeList typeList = doc.getElementsByTagName("n1:type");

      for (int i = 0; i < apiList.getLength(); i++) {
        Node api_node = apiList.item(i);
        String api_id = api_node.getAttributes().getNamedItem("id").getNodeValue();
        String api_name = api_node.getAttributes().getNamedItem("name").getNodeValue();
        String input_type_id =
            inputList.item(i).getAttributes().getNamedItem("type_ref").getNodeValue();

        // System.out.println(api_id + " : " + api_name + " : " + input_type_id);
        ArrayList<String> api_params = new ArrayList<String>();

        for (int j = 0; j < typeList.getLength(); j++) {

          if (input_type_id.equalsIgnoreCase(
              typeList.item(j).getAttributes().getNamedItem("id").getNodeValue())) {
            Element e1 = (Element) typeList.item(j);

            NodeList param_l = e1.getElementsByTagName("n1:param");

            for (int k = 0; k < param_l.getLength(); k++) {

              String param_name =
                  param_l.item(k).getAttributes().getNamedItem("name").getNodeValue();
              // String param_desc =
              // param_l.item(k).getAttributes().getNamedItem("desc").getNodeValue();
              api_params.add(param_name);
              // System.out.println(param_name +":"+param_desc);
            }

            break;
          }
        }
        apiRoom s_room = new apiRoom(api_id, api_name, api_params);
        apiRooms.add(s_room);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #29
0
 public static final Skeleton loadSkeleton(File file) {
   try {
     FileInputStream input_stream = new FileInputStream(file);
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     factory.setValidating(true);
     DocumentBuilder builder = factory.newDocumentBuilder();
     builder.setErrorHandler(new GeometryErrorHandler());
     Document document = builder.parse(input_stream);
     Element root = document.getDocumentElement();
     return parseSkeleton(root);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #30
0
 public static void main(String args[]) {
   try {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     factory.setNamespaceAware(true);
     factory.setValidating(true);
     DocumentBuilder builder = factory.newDocumentBuilder();
     Document doc = builder.parse(args[0]);
   } catch (SAXException e) {
     // e.printStackTrace();
     System.out.println(e.getMessage());
   } catch (Exception e) {
     // e.printStackTrace();
   }
 }