Beispiel #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;
    }
  }
Beispiel #2
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);
      }
    }
  }
Beispiel #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();
    }
  }
Beispiel #5
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);
  }
 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;
 }
Beispiel #7
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();
  }
Beispiel #8
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);
  }
  /**
   * 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);
    }
  }
  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);
  }
Beispiel #11
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;
  }
 public static Document newXMLDocument() {
   DocumentBuilder dbuilder = null;
   try {
     dbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   } catch (ParserConfigurationException e) {
     e.printStackTrace();
     return null;
   }
   return dbuilder.newDocument();
 }
Beispiel #13
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);
   }
 }
Beispiel #14
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 #15
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;
 }
Beispiel #16
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;
 }
Beispiel #17
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);
    }
  }
Beispiel #18
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);
   }
 }
Beispiel #19
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 #20
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 #21
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();
   }
 }
 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);
   }
 }
Beispiel #23
0
  static {
    try {
      URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC);

      InputStream stream = url.openStream();

      if (stream == null) throw new IOException();

      // strict parsing options
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      factory.setValidating(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);

      // parses configuration xml
      /*-
       * Warning: Felix is unable to import the com.sun.rowset.internal
       * package, meaning this can't use the XmlErrorHandler. This causes
       * a warning and a default handler to be attached. Otherwise this
       * should have: builder.setErrorHandler(new XmlErrorHandler());
       */
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(stream);

      // iterates over nodes, parsing contents
      Node root = doc.getChildNodes().item(1);

      NodeList categories = root.getChildNodes();

      for (int i = 0; i < categories.getLength(); ++i) {
        Node node = categories.item(i);
        if (node.getNodeName().equals(NODE_DEFAULTS)) {
          parseDefaults(node.getChildNodes());
        } else if (node.getNodeName().equals(NODE_LOCALES)) {
          parseLocales(node.getChildNodes());
        } else {
          logger.warn("Unrecognized category: " + node.getNodeName());
        }
      }
    } catch (IOException exc) {
      logger.error("Unable to load spell checker parameters", exc);
    } catch (SAXException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    } catch (ParserConfigurationException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    }
  }
Beispiel #24
0
  public static void testEnum() throws Exception {
    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setProperty("Export-Package", "test.metatype");
    b.setProperty("-metatype", "*");
    b.build();
    assertEquals(0, b.getErrors().size());
    assertEquals(0, b.getWarnings().size());

    Resource r = b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$Enums.xml");
    IO.copy(r.openInputStream(), System.err);

    Document d = db.parse(r.openInputStream());
    assertEquals(
        "http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement().getNamespaceURI());

    Properties p = new Properties();
    p.setProperty("r", "requireConfiguration");
    p.setProperty("i", "ignoreConfiguration");
    p.setProperty("o", "optionalConfiguration");
    Enums enums = Configurable.createConfigurable(Enums.class, (Map<Object, Object>) p);
    assertEquals(Enums.X.requireConfiguration, enums.r());
    assertEquals(Enums.X.ignoreConfiguration, enums.i());
    assertEquals(Enums.X.optionalConfiguration, enums.o());
  }
 /**
  * Given a DICOM object encoded as a list of attributes, get an XML document as a DOM tree.
  *
  * @param list the list of DICOM attributes
  */
 public Document getDocument(AttributeList list) {
   Document document = db.newDocument();
   org.w3c.dom.Node element = document.createElement("DicomObject");
   document.appendChild(element);
   addAttributesFromListToNode(list, document, element);
   return document;
 }
Beispiel #26
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 #27
0
  public static void main(String[] args) {
    try {
      // open existing file
      File xmlFile = new File(userFile);
      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder dbuild = dbfac.newDocumentBuilder();
      Document doc = dbuild.parse(xmlFile);

      //			DocumentBuilderFactory dbfac2 = DocumentBuilderFactory.newInstance();
      //			DocumentBuilder docBuilder = dbfac2.newDocumentBuilder();
      //			Document doc2 = docBuilder.parse(xmlFile);
      //			doc.getDocumentElement().normalize();

    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
  }
 private void createDOM() throws ParserConfigurationException {
   if (dbf == null) {
     dbf = DocumentBuilderFactory.newInstance();
     db = dbf.newDocumentBuilder();
     dil = (DOMImplementationLS) db.getDOMImplementation();
     dw = dil.createDOMWriter();
   }
 }
Beispiel #29
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 #30
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();
  }