Ejemplo n.º 1
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);
      }
    }
  }
Ejemplo n.º 2
0
 /**
  * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>.
  *
  * @param parent
  */
 public void makeElement(Node parent) {
   Document doc;
   if (parent instanceof Document) {
     doc = (Document) parent;
   } else {
     doc = parent.getOwnerDocument();
   }
   Element element = doc.createElement("table");
   int size;
   if (this.id_ != null) {
     URelaxer.setAttributePropertyByString(element, "id", this.id_);
   }
   if (this.xmlLang_ != null) {
     URelaxer.setAttributePropertyByString(element, "xml:lang", this.xmlLang_);
   }
   if (this.caption_ != null) {
     this.caption_.makeElement(element);
   }
   size = this.tr_.size();
   for (int i = 0; i < size; i++) {
     FcTr value = (FcTr) this.tr_.get(i);
     value.makeElement(element);
   }
   parent.appendChild(element);
 }
Ejemplo n.º 3
0
  /**
   * Returns the result of an XSL Transformation as a JDOM document.
   *
   * <p>If the result of the transformation is a list of nodes, this method attempts to convert it
   * into a JDOM document. If successful, any subsequent call to {@link #getResult} will return an
   * empty list.
   *
   * <p><strong>Warning</strong>: The XSLT 1.0 specification states that the output of an XSL
   * transformation is not a well-formed XML document but a list of nodes. Applications should thus
   * use {@link #getResult} instead of this method or at least expect <code>null</code> documents to
   * be returned.
   *
   * @return the transformation result as a JDOM document or <code>null</code> if the result of the
   *     transformation can not be converted into a well-formed document.
   * @see #getResult
   */
  public Document getDocument() {
    Document doc = null;

    // Retrieve result from the document builder if not set.
    this.retrieveResult();

    if (result instanceof Document) {
      doc = (Document) result;
    } else {
      if ((result instanceof List) && (queried == false)) {
        // Try to create a document from the result nodes
        try {
          JDOMFactory f = this.getFactory();
          if (f == null) {
            f = new DefaultJDOMFactory();
          }

          doc = f.document(null);
          doc.setContent((List) result);

          result = doc;
        } catch (RuntimeException ex1) {
          // Some of the result nodes are not valid children of a
          // Document node. => return null.
        }
      }
    }
    queried = true;

    return (doc);
  }
  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);
  }
Ejemplo n.º 5
0
 /**
  * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>.
  *
  * @param parent
  */
 public void makeElement(Node parent) {
   Document doc;
   if (parent instanceof Document) {
     doc = (Document) parent;
   } else {
     doc = parent.getOwnerDocument();
   }
   Element element = doc.createElement("fixme");
   int size;
   if (this.author_ != null) {
     URelaxer.setAttributePropertyByString(element, "author", this.author_);
   }
   if (this.id_ != null) {
     URelaxer.setAttributePropertyByString(element, "id", this.id_);
   }
   if (this.xmlLang_ != null) {
     URelaxer.setAttributePropertyByString(element, "xml:lang", this.xmlLang_);
   }
   size = this.content_.size();
   for (int i = 0; i < size; i++) {
     IFdContentMixMixed value = (IFdContentMixMixed) this.content_.get(i);
     value.makeElement(element);
   }
   parent.appendChild(element);
 }
Ejemplo n.º 6
0
  /**
   * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web
   * service ** @return The virtual DBRecord (cannot be saved or reloaded)
   */
  @SuppressWarnings("unchecked")
  public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException {
    String CMD_dbget = DBFactory.CMD_dbget;
    String TAG_Response = servReq.getTagResponse();
    String TAG_Record = DBFactory.TAG_Record;
    String ATTR_command = servReq.getAttrCommand();
    String ATTR_result = servReq.getAttrResult();

    /* send request / get response */
    Document xmlDoc = null;
    try {
      xmlDoc =
          servReq.sendRequest(
              CMD_dbget,
              new ServiceRequest.RequestBody() {
                public StringBuffer appendRequestBody(StringBuffer sb, int indent) {
                  return DBRecordKey.this.toRequestXML(sb, indent);
                }
              });
    } catch (IOException ioe) {
      Print.logException("Error", ioe);
      throw new DBException("Request read error", ioe);
    }

    /* parse 'GTSResponse' */
    Element gtsResponse = xmlDoc.getDocumentElement();
    if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) {
      Print.logError("Request XML does not start with '%s'", TAG_Response);
      throw new DBException("Response XML does not begin eith '" + TAG_Response + "'");
    }

    /* request command/argument */
    String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command));
    String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result));
    if (StringTools.isBlank(result)) {
      result = StringTools.trim(gtsResponse.getAttribute("type"));
    }
    if (!result.equalsIgnoreCase("success")) {
      Print.logError("Response indicates failure");
      throw new DBException("Response does not indicate 'success'");
    }

    /* Record */
    NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record);
    if (rcdList.getLength() <= 0) {
      Print.logError("No 'Record' tags");
      throw new DBException("GTSResponse does not contain any 'Record' tags");
    }
    Element rcdElem = (Element) rcdList.item(0);

    /* return DBRecord */
    gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem);
    dbr.setVirtual(true);
    return dbr;
  }
Ejemplo n.º 7
0
 private void create() {
   try {
     tracks = new Vector();
     hash = new Hashtable();
     createDOM();
     doc = db.newDocument();
     docElt = doc.createElement(docElementName);
     doc.appendChild(docElt);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 8
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();
  }
Ejemplo n.º 9
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);
    }
  }
Ejemplo n.º 10
0
  @Override
  public VPackage parse() {

    logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath());

    long startParsing = System.currentTimeMillis();

    try {
      Document document = getDocument();
      Element root = document.getDocumentElement();

      _package = new VPackage(xmlFile);

      Node name = root.getElementsByTagName(EL_NAME).item(0);
      _package.setName(name.getTextContent());
      Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0);
      _package.setDescription(descr.getTextContent());

      NodeList list = root.getElementsByTagName(EL_CLASS);

      boolean initPainters = false;
      for (int i = 0; i < list.getLength(); i++) {
        PackageClass pc = parseClass((Element) list.item(i));
        if (pc.getPainterName() != null) {
          initPainters = true;
        }
      }

      if (initPainters) {
        _package.initPainters();
      }

      logger.info(
          "Parsing the package '{}' finished in {}ms.\n",
          _package.getName(),
          (System.currentTimeMillis() - startParsing));
    } catch (Exception e) {
      collector.collectDiagnostic(e.getMessage(), true);
      if (RuntimeProperties.isLogDebugEnabled()) {
        e.printStackTrace();
      }
    }

    try {
      checkProblems("Error parsing package file " + xmlFile.getName());
    } catch (Exception e) {
      return null;
    }

    return _package;
  }
Ejemplo n.º 11
0
  private void calculateEnabledState() {
    for (int i = 0, limit = Outliner.documents.openDocumentCount(); i < limit; i++) {
      Document doc = Outliner.documents.getDocument(i);

      if ((doc.isModified() || doc.getFileName().equals(""))
          && !PropertyContainerUtil.getPropertyAsBoolean(
              doc.getDocumentInfo(), DocumentInfo.KEY_IMPORTED)) {
        setEnabled(true);
        return;
      }
    }

    setEnabled(false);
  }
Ejemplo n.º 12
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);
    }
  }
 /**
  * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>.
  *
  * @param parent
  */
 public void makeElement(Node parent) {
   Document doc;
   if (parent instanceof Document) {
     doc = (Document) parent;
   } else {
     doc = parent.getOwnerDocument();
   }
   Element element =
       doc.createElementNS(
           "http://www.iso_relax.org/xmlns/miaou/binaryTreeAutomaton", "textTransition");
   rNSContext_.setupNamespace(element);
   int size;
   URelaxer.setAttributePropertyByInt(element, "target", this.target_);
   URelaxer.setAttributePropertyByInt(element, "right", this.right_);
   parent.appendChild(element);
 }
Ejemplo n.º 14
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");
    }
  }
Ejemplo n.º 15
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;
  }
Ejemplo n.º 16
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();
  }
Ejemplo n.º 17
0
 protected void setAttribute(String name, String attName, String attValue) {
   Element elt = getElement(name);
   if (elt == null) {
     elt = doc.createElement(name);
     docElt.appendChild(elt);
   }
   elt.setAttribute(attName, attValue);
 }
Ejemplo n.º 18
0
 /**
  * Pushes an element onto the tree under construction. Allows subclasses to put content under a
  * dummy root element which is useful for building content that would otherwise be a non-well
  * formed document.
  *
  * @param element root element under which content will be built
  */
 protected void pushElement(Element element) {
   if (atRoot) {
     document.setRootElement(element); // XXX should we use a factory call?
     atRoot = false;
   } else {
     factory.addContent(currentElement, element);
   }
   currentElement = element;
 }
  private QueryResult gatherResultInfoForSelectQuery(
      String queryString, int queryNr, boolean sorted, Document doc, String[] rows) {
    Element root = doc.getRootElement();

    // Get head information
    Element child =
        root.getChild("head", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));

    // Get result rows (<head>)
    List headChildren =
        child.getChildren(
            "variable", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));

    Iterator it = headChildren.iterator();
    ArrayList<String> headList = new ArrayList<String>();
    while (it.hasNext()) {
      headList.add(((Element) it.next()).getAttributeValue("name"));
    }

    List resultChildren =
        root.getChild("results", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"))
            .getChildren(
                "result", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
    int nrResults = resultChildren.size();

    QueryResult queryResult = new QueryResult(queryNr, queryString, nrResults, sorted, headList);

    it = resultChildren.iterator();
    while (it.hasNext()) {
      Element resultElement = (Element) it.next();
      String result = "";

      // get the row values and paste it together to one String
      for (int i = 0; i < rows.length; i++) {
        List bindings =
            resultElement.getChildren(
                "binding", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
        String rowName = rows[i];
        for (int j = 0; j < bindings.size(); j++) {
          Element binding = (Element) bindings.get(j);
          if (binding.getAttributeValue("name").equals(rowName))
            if (result.equals(""))
              result +=
                  rowName + ": " + ((Element) binding.getChildren().get(0)).getTextNormalize();
            else
              result +=
                  "\n"
                      + rowName
                      + ": "
                      + ((Element) binding.getChildren().get(0)).getTextNormalize();
        }
      }

      queryResult.addResult(result);
    }
    return queryResult;
  }
Ejemplo n.º 20
0
  private Element generateGraphicsNode(Document doc, ClassGraphics gr) {

    Element graphicsEl = doc.createElement(EL_GRAPHICS);

    Element bounds = doc.createElement(EL_BOUNDS);
    graphicsEl.appendChild(bounds);
    bounds.setAttribute(ATR_X, Integer.toString(gr.getBoundX()));
    bounds.setAttribute(ATR_Y, Integer.toString(gr.getBoundY()));
    bounds.setAttribute(ATR_WIDTH, Integer.toString(gr.getBoundWidth()));
    bounds.setAttribute(ATR_HEIGHT, Integer.toString(gr.getBoundHeight()));

    for (Shape shape : gr.getShapes()) {

      if (shape instanceof Rect) {
        Rect rect = (Rect) shape;
        Element rectEl = doc.createElement(EL_RECT);
        graphicsEl.appendChild(rectEl);
        rectEl.setAttribute(ATR_X, Integer.toString(rect.getX()));
        rectEl.setAttribute(ATR_Y, Integer.toString(rect.getY()));
        rectEl.setAttribute(ATR_WIDTH, Integer.toString(rect.getWidth()));
        rectEl.setAttribute(ATR_HEIGHT, Integer.toString(rect.getHeight()));
        rectEl.setAttribute(ATR_COLOUR, Integer.toString(rect.getColor().getRGB()));
        rectEl.setAttribute(ATR_FILLED, Boolean.toString(rect.isFilled()));
        rectEl.setAttribute(ATR_FIXED, Boolean.toString(rect.isFixed()));
        rectEl.setAttribute(ATR_STROKE, Float.toString(rect.getStroke().getLineWidth()));
        rectEl.setAttribute(ATR_LINETYPE, Float.toString(rect.getLineType()));
        rectEl.setAttribute(ATR_TRANSPARENCY, Integer.toString(rect.getTransparency()));
      } else if (shape instanceof Text) {
        Text text = (Text) shape;
        Element textEl = doc.createElement(EL_TEXT);
        textEl.setAttribute(ATR_STRING, text.getText());
        textEl.setAttribute(ATR_X, Integer.toString(text.getX()));
        textEl.setAttribute(ATR_Y, Integer.toString(text.getY()));
        textEl.setAttribute(ATR_FONTNAME, text.getFont().getName());
        textEl.setAttribute(ATR_FONTSIZE, Integer.toString(text.getFont().getSize()));
        textEl.setAttribute(ATR_FONTSTYLE, Integer.toString(text.getFont().getStyle()));
        textEl.setAttribute(ATR_TRANSPARENCY, Integer.toString(text.getTransparency()));
        textEl.setAttribute(ATR_COLOUR, Integer.toString(text.getColor().getRGB()));
        graphicsEl.appendChild(textEl);
      } // TODO handle the rest of shapes
    }

    return graphicsEl;
  }
Ejemplo n.º 21
0
  /**
   * Reads an XML document from an input source and copies its values into the specified object
   *
   * @param ob The object to receive the values
   * @param source The location of the XML document
   * @throws IOException If there is an error reading the document
   */
  public void readObject(Object ob, InputSource source) throws IOException {
    try {
      // Create a document builder to read the document
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Read the document
      Document doc = builder.parse(source);

      // Get the root element
      Element element = doc.getDocumentElement();

      // Copy the root element into the bean
      readObject(ob, element);
    } catch (SAXException exc) {
      throw new IOException("Error parsing XML document: " + exc.toString());
    } catch (ParserConfigurationException exc) {
      throw new IOException("Error parsing XML document: " + exc.toString());
    }
  }
Ejemplo n.º 22
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
  }
Ejemplo n.º 23
0
 public Track add(Track track) {
   synchronized (this) {
     Track copy;
     if ((copy = getTrack(track)) == null) {
       copy = new Track((Element) doc.importNode(track.getElement(), false));
       docElt.appendChild(copy.getElement());
       tracks.add(copy);
       hash.put(copy.getKey(), copy);
     }
     return copy;
   }
 }
Ejemplo n.º 24
0
 public String getProperty(String pPropertyName) {
   String propertyValue = null;
   NodeList nodeList = mConfigFileDocument.getElementsByTagName(pPropertyName);
   int nodeListLength = nodeList.getLength();
   if (nodeListLength > 0) {
     Node firstChildNode = nodeList.item(nodeListLength - 1).getFirstChild();
     if (null != firstChildNode) {
       propertyValue = firstChildNode.getNodeValue();
     }
   }
   return (propertyValue);
 }
Ejemplo n.º 25
0
  /**
   * This will output the <code>JDOM Document</code>, firing off the SAX events that have been
   * registered.
   *
   * @param document <code>JDOM Document</code> to output.
   * @throws JDOMException if any error occurred.
   */
  public void output(Document document) throws JDOMException {
    if (document == null) {
      return;
    }

    // contentHandler.setDocumentLocator()
    documentLocator(document);

    // contentHandler.startDocument()
    startDocument();

    // Fire DTD events
    if (this.reportDtdEvents) {
      dtdEvents(document);
    }

    // Handle root element, as well as any root level
    // processing instructions and comments
    Iterator i = document.getContent().iterator();
    while (i.hasNext()) {
      Object obj = i.next();

      // update locator
      locator.setNode(obj);

      if (obj instanceof Element) {
        // process root element and its content
        element(document.getRootElement(), new NamespaceStack());
      } else if (obj instanceof ProcessingInstruction) {
        // contentHandler.processingInstruction()
        processingInstruction((ProcessingInstruction) obj);
      } else if (obj instanceof Comment) {
        // lexicalHandler.comment()
        comment(((Comment) obj).getText());
      }
    }

    // contentHandler.endDocument()
    endDocument();
  }
Ejemplo n.º 26
0
  private Node generateFieldNode(Document doc, ClassField field) {
    Element fieldEl = doc.createElement(EL_FIELD);

    fieldEl.setAttribute(ATR_NAME, field.getName());
    fieldEl.setAttribute(ATR_TYPE, field.getType());

    if (field.isInput()) fieldEl.setAttribute(ATR_NATURE, "input");
    else if (field.isGoal()) fieldEl.setAttribute(ATR_NATURE, "goal");

    if (field.getValue() != null) fieldEl.setAttribute(ATR_VALUE, field.getValue());

    return fieldEl;
  }
  /**
   * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>.
   *
   * @param parent
   */
  public void makeElement(Node parent) {
    Document doc;

    if (parent instanceof Document) {
      doc = (Document) parent;
    } else {
      doc = parent.getOwnerDocument();
    }

    Element element =
        doc.createElementNS("http://www.asahi-net.or.jp/~cs8k-cyu/bulletml", "direction");
    rNSContext_.setupNamespace(element);
    URelaxer.setElementPropertyByString(element, this.content_);

    int size;

    if (this.type_ != null) {
      URelaxer.setAttributePropertyByString(element, "type", this.type_);
    }

    parent.appendChild(element);
  }
Ejemplo n.º 28
0
  private Element generatePortNode(Document doc, Port port) {
    Element portEl = doc.createElement(EL_PORT);

    portEl.setAttribute(ATR_NAME, port.getName());
    portEl.setAttribute(ATR_TYPE, port.getType());
    portEl.setAttribute(ATR_X, Integer.toString(port.getX()));
    portEl.setAttribute(ATR_Y, Integer.toString(port.getY()));
    portEl.setAttribute(ATR_PORT_CONNECTION, port.isArea() ? "area" : "");
    portEl.setAttribute(ATR_STRICT, Boolean.toString(port.isStrict()));
    portEl.setAttribute(ATR_MULTI, Boolean.toString(port.isMulti()));

    return portEl;
  }
Ejemplo n.º 29
0
 public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException {
   doc = db.parse(is);
   docElt = doc.getDocumentElement();
   if (docElt.getTagName().equals(docElementName)) {
     NodeList nl = docElt.getElementsByTagName(trackElementName);
     for (int i = 0; i < nl.getLength(); i++) {
       Element elt = (Element) nl.item(i);
       Track track = new Track(elt);
       tracks.add(track);
       hash.put(track.getKey(), track);
     }
   }
 }
Ejemplo n.º 30
0
 /**
  * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>.
  *
  * @param parent
  */
 public void makeElement(Node parent) {
   Document doc;
   if (parent instanceof Document) {
     doc = (Document) parent;
   } else {
     doc = parent.getOwnerDocument();
   }
   Element element = doc.createElement("header");
   int size;
   if (this.id_ != null) {
     URelaxer.setAttributePropertyByString(element, "id", this.id_);
   }
   if (this.xmlLang_ != null) {
     URelaxer.setAttributePropertyByString(element, "xml:lang", this.xmlLang_);
   }
   this.title_.makeElement(element);
   if (this.subtitle_ != null) {
     this.subtitle_.makeElement(element);
   }
   if (this.version_ != null) {
     this.version_.makeElement(element);
   }
   if (this.type_ != null) {
     this.type_.makeElement(element);
   }
   if (this.authors_ != null) {
     this.authors_.makeElement(element);
   }
   size = this.notice_.size();
   for (int i = 0; i < size; i++) {
     FtNotice value = (FtNotice) this.notice_.get(i);
     value.makeElement(element);
   }
   if (this.abstract_ != null) {
     this.abstract_.makeElement(element);
   }
   parent.appendChild(element);
 }