// Implementation methods
 protected DOMDocumentType asDocumentType(org.w3c.dom.DocumentType docType) {
   if (docType instanceof DOMDocumentType) {
     return (DOMDocumentType) docType;
   } else {
     return new DOMDocumentType(docType.getName(), docType.getPublicId(), docType.getSystemId());
   }
 }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    NamedNodeMap notations;
    DocumentType docType;
    Node retval;
    Element elem;
    doc = (Document) load("hc_staff", true);
    docType = doc.getDoctype();

    if (!(("text/html".equals(getContentType())))) {
      assertNotNull("docTypeNotNull", docType);
      notations = docType.getNotations();
      assertNotNull("notationsNotNull", notations);
      elem = doc.createElementNS("http://www.w3.org/1999/xhtml", "br");

      try {
        retval = notations.setNamedItemNS(elem);
        fail("throw_HIER_OR_NO_MOD_ERR");

      } catch (DOMException ex) {
        switch (ex.code) {
          case 3:
            break;
          case 7:
            break;
          default:
            throw ex;
        }
      }
    }
  }
예제 #3
0
  /**
   * Tries to read from the given filename the outbound message
   *
   * @param file The file to read from
   * @return Outbound message read form the file
   * @throws IllegalArgumentExcpetion Is thrown if there's something wrong with the content of the
   *     file
   * @throws IOExcpetion Is throws if there's an I/O problem while reading the file
   */
  private OutboundMessage readDocument(File file) throws IllegalArgumentException {
    Document xmldoc = null;
    try {
      /* Check for valid XML file */
      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      dbfac.setValidating(true);
      DocumentBuilder db = dbfac.newDocumentBuilder();
      db.setErrorHandler(
          new ErrorHandler() {
            /*
             * (non-Javadoc)
             *
             * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
             */
            public void error(SAXParseException arg0) {
              throw new IllegalArgumentException(arg0);
            }

            /*
             * (non-Javadoc)
             *
             * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
             */
            public void fatalError(SAXParseException arg0) {
              throw new IllegalArgumentException(arg0);
            }

            /*
             * (non-Javadoc)
             *
             * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
             */
            public void warning(SAXParseException arg0) {
              throw new IllegalArgumentException(arg0);
            }
          });
      xmldoc = db.parse(file);
      DocumentType outDoctype = xmldoc.getDoctype();
      if (!"message".equals(outDoctype.getName())) {
        throw new IllegalArgumentException("Wrong DOCTYPE - Have to be message!");
      }
      if (!"smssvr_out.dtd".equals(outDoctype.getSystemId())) {
        throw new IllegalArgumentException(
            "Wrong SystemId in DOCTYPE - Have to be smssvr_out.dtd!");
      }
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
    /* Search "message" root element */
    NodeList rnl = xmldoc.getElementsByTagName("message");
    if (rnl == null || rnl.getLength() != 1) {
      throw new IllegalArgumentException("Wrong root element or root element count!");
    }
    /* Process all child elements aka "message" */
    return readNode(rnl.item(0));
  }
예제 #4
0
  protected static String getDocumentTypeData(DocumentType doctype) {
    String data = doctype.getName();
    if (doctype.getPublicId() != null) {
      data += " PUBLIC \"" + doctype.getPublicId() + "\"";
      String systemId = doctype.getSystemId();
      if (systemId == null) systemId = "";
      data += " \"" + systemId + "\"";
    } else data += " SYSTEM \"" + doctype.getSystemId() + "\"";

    return data;
  }
예제 #5
0
 /**
  * Runs the test case.
  *
  * @throws Throwable Any uncaught exception causes test to fail
  */
 public void runTest() throws Throwable {
   Document doc;
   DocumentType docType;
   NamedNodeMap entitiesMap;
   Entity entity;
   String encodingName;
   doc = (Document) load("external_barfoo", false);
   docType = doc.getDoctype();
   entitiesMap = docType.getEntities();
   entity = (Entity) entitiesMap.getNamedItem("ent5");
   encodingName = entity.getXmlEncoding();
   assertNull("entitygetxmlencoding02", encodingName);
 }
  /**
   * Convenience class to create a compiled stylesheet.
   *
   * @param node DOM source for the stylesheet.
   * @return a compiled stylesheet
   */
  public javax.xml.transform.Templates newTemplates(Node node)
      throws TransformerConfigurationException {
    Document doc = node.getOwnerDocument();
    if (node instanceof Document) doc = (Document) node;

    DocumentType dtd = doc.getDoctype();

    if (dtd != null && dtd.getSystemId() != null)
      return generate(node, getSearchPath().lookup(dtd.getSystemId()));
    else if (doc instanceof CauchoDocument) {
      String systemId = ((CauchoDocument) doc).getFilename();

      return generate(node, getSearchPath().lookup(systemId));
    } else return generate(node, null);
  }
  public static String[] getDoctypeInfo(Document document) {
    String[] result = null;
    DocumentType doctype = document.getDoctype();

    // defect 206833 ... here we test for DTDs that are declared inline
    // since we currently have no way of making use of inline DTDs we ignore them
    // so that the implict DTD (if any) can be used
    if (doctype != null && (doctype.getPublicId() != null || doctype.getSystemId() != null)) {
      result = new String[2];
      result[0] = doctype.getPublicId();
      result[1] = doctype.getSystemId();
    } else if (getImplictDoctype(document) != null) {
      result = getImplictDoctype(document);
    }
    return result;
  }
예제 #8
0
  @Override
  public DocumentTypeNode convert(DocumentType documentType) {

    DocumentTypeBuilder documentTypeBuilder = NodeBuilderFactory.newdoDocumentTypeBuilder();
    DocumentTypeNode documentTypeNode = null;

    documentTypeNode =
        documentTypeBuilder //
            .nodeName(documentType.getNodeName()) //
            .name(documentType.getName()) //
            .publicId(documentType.getPublicId()) //
            .systemId(documentType.getSystemId()) //
            .internalSubSet(documentType.getInternalSubset()) //
            .build();

    return documentTypeNode;
  }
예제 #9
0
  private boolean validSMSDtdDocType(Document doc) {
    boolean valid = false;
    DocumentType docType = doc.getDoctype();

    if (docType != null) {
      String dtdPath = docType.getSystemId();
      if (dtdPath != null) {
        int idx = dtdPath.lastIndexOf('/');
        if (idx != -1) {
          dtdPath = dtdPath.substring(idx + 1);
        }
        valid = dtdPath.equals("sms.dtd");
      }
    }

    return valid;
  }
예제 #10
0
  @Override
  public void receive(String title, String type, Document doc) {
    outputDir.mkdir();
    File outputFile = new File(outputDir, title + "." + type);

    DocumentType doctype = doc.getDoctype();

    try {
      Source source = new DOMSource(doc);
      Result result = new StreamResult(outputFile);
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());

      transformer.transform(source, result);
    } catch (TransformerException e) {
      throw new PrintingException("Failed during transform", e);
    }
  }
예제 #11
0
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    DocumentType docType;
    Entity entity;
    NamedNodeMap entitymap;
    String textContent;
    doc = (Document) load("hc_staff", true);
    docType = doc.getDoctype();
    entitymap = docType.getEntities();
    entity = (Entity) entitymap.getNamedItem("delta");

    {
      boolean success = false;
      try {
        entity.setTextContent("NA");
      } catch (DOMException ex) {
        success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR);
      }
      assertTrue("nodesettextcontent13", success);
    }
  }
예제 #12
0
  @Override
  public void save() throws ResourceStoreException {
    validateSave();

    try {
      if (this.document.getDocumentElement() != null) {
        final StringWriter sw = new StringWriter();

        sw.append(XML_DECLARATION);
        sw.append('\n');

        final DOMSource source = new DOMSource(this.document);
        final StreamResult result = new StreamResult(sw);

        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        final DocumentType doctype = this.document.getDoctype();
        if (doctype != null) {
          if (doctype.getPublicId() != null) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
          }
          if (doctype.getSystemId() != null) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
          }
        }

        transformer.transform(source, result);

        this.base.setContents(sw.toString().getBytes(UTF8));
      } else {
        this.base.setContents(new byte[0]);
      }

      this.base.save();
    } catch (Exception e) {
      throw new ResourceStoreException(e);
    }
  }
 /**
  * This method returns a list of CMDocumentReferences associated with a particular node or subtree
  */
 public List getCMDocumentReferences(Node node, boolean deep) {
   List result = new ArrayList();
   Document document =
       (node.getNodeType() == Node.DOCUMENT_NODE) ? (Document) node : node.getOwnerDocument();
   DocumentType doctype = document.getDoctype();
   // defect 206833 ... here we test for DTDs that are declared inline
   // since we currently have no way of making use of inline DTDs we ingore them
   // so that the implict DTD (if any) can be used
   if (doctype != null && (doctype.getPublicId() != null || doctype.getSystemId() != null)) {
     String uri = resolveGrammarURI(document, doctype.getPublicId(), doctype.getSystemId());
     result.add(new CMDocumentReferenceImpl(doctype.getPublicId(), uri));
   } else if (getImplictDoctype(document) != null) {
     String[] implicitDoctype = getImplictDoctype(document);
     String uri = resolveGrammarURI(document, implicitDoctype[0], implicitDoctype[1]);
     result.add(new CMDocumentReferenceImpl(implicitDoctype[0], uri));
   } else {
     NamespaceTable namespaceTable = new NamespaceTable(document);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       namespaceTable.addElement((Element) node);
     }
     if (deep) {
       addChildElementsToNamespaceTable(node, namespaceTable);
     }
     List list = namespaceTable.getNamespaceInfoList();
     for (Iterator i = list.iterator(); i.hasNext(); ) {
       NamespaceInfo info = (NamespaceInfo) i.next();
       String uri = resolveGrammarURI(document, info.uri, info.locationHint);
       result.add(new CMDocumentReferenceImpl(info.uri, uri));
     }
   }
   return result;
 }
 /**
  * Introduced in DOM Level 2.
  *
  * <p>Creates an XML Document object of the specified type with its document element.
  *
  * @param namespaceURI The namespace URI of the document element to create, or null.
  * @param qualifiedName The qualified name of the document element to create.
  * @param doctype The type of document to be created or null.
  *     <p>When doctype is not null, its Node.ownerDocument attribute is set to the document being
  *     created.
  * @return Document A new Document object.
  * @throws DOMException WRONG_DOCUMENT_ERR: Raised if doctype has already been used with a
  *     different document.
  * @since WD-DOM-Level-2-19990923
  */
 public Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype)
     throws DOMException {
   if (doctype != null && doctype.getOwnerDocument() != null) {
     throw new DOMException(
         DOMException.WRONG_DOCUMENT_ERR,
         DOMMessageFormatter.formatMessage(
             DOMMessageFormatter.XML_DOMAIN, "WRONG_DOCUMENT_ERR", null));
   }
   DocumentImpl doc = new PSVIDocumentImpl(doctype);
   Element e = doc.createElementNS(namespaceURI, qualifiedName);
   doc.appendChild(e);
   return doc;
 }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    DocumentType docType;
    NamedNodeMap entities;
    NamedNodeMap notations;
    Entity entity;
    Notation notation;
    Node newNode;
    String nullNS = null;

    doc = (Document) load("staffNS", true);
    docType = doc.getDoctype();
    entities = docType.getEntities();
    assertNotNull("entitiesNotNull", entities);
    notations = docType.getNotations();
    assertNotNull("notationsNotNull", notations);
    entity = (Entity) entities.getNamedItem("ent1");
    notation = (Notation) notations.getNamedItem("notation1");

    {
      boolean success = false;
      try {
        newNode = entities.setNamedItemNS(entity);
      } catch (DOMException ex) {
        success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR);
      }
      assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR_entities", success);
    }

    {
      boolean success = false;
      try {
        newNode = notations.setNamedItemNS(notation);
      } catch (DOMException ex) {
        success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR);
      }
      assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR_notations", success);
    }
  }
예제 #16
0
  public static String getDTDVersion(Document document) {
    String dtdVersion = null;
    DocumentType docType = document.getDoctype();

    if (docType != null) {
      String publicId = docType.getPublicId();
      String systemId = docType.getSystemId();

      if (publicId != null && systemId != null) {
        if (publicId.contains("6.0.0") || systemId.contains("6.0.0")) // $NON-NLS-1$ //$NON-NLS-2$
        {
          dtdVersion = "6.0.0"; // $NON-NLS-1$
        } else if (publicId.contains("6.1.0")
            || systemId.contains("6.1.0")) // $NON-NLS-1$ //$NON-NLS-2$
        {
          dtdVersion = "6.1.0"; // $NON-NLS-1$
        }
      }
    }

    return dtdVersion;
  }
예제 #17
0
 public boolean enter(DocumentType docType) {
   String name = docType.getName();
   String pubId = docType.getPublicId();
   String sysId = docType.getSystemId();
   String internalSubset = docType.getInternalSubset();
   if (docType.getPreviousSibling() != null) {
     buffer.append("\n");
   }
   buffer.append("<!DOCTYPE " + name + " ");
   if (pubId != null) {
     buffer.append("PUBLIC \"" + pubId + "\"");
     if (sysId != null) buffer.append(" \"" + sysId + "\"");
   } else if (sysId != null) {
     buffer.append("SYSTEM \"" + sysId + "\"");
   }
   if (internalSubset != null) {
     buffer.append(" [");
     buffer.append(internalSubset);
     buffer.append("]");
   }
   buffer.append(">\n");
   return true;
 }
  /**
   * generateDoctype method
   *
   * @return java.lang.String
   * @param docType org.w3c.dom.DocumentType
   */
  public String generateDoctype(DocumentType docType) {
    if (docType == null) return null;

    String name = docType.getName();
    int length = (name != null ? name.length() : 0);
    StringBuffer buffer = new StringBuffer(length + 16);
    buffer.append(DOCTYPE_OPEN);
    buffer.append(' ');
    if (name != null) buffer.append(name);
    DocumentTypeImpl dt = (DocumentTypeImpl) docType;
    String publicID = dt.getPublicId();
    String systemID = dt.getSystemId();
    if (publicID != null) {
      buffer.append(' ');
      buffer.append(PUBLIC_ID);
      buffer.append(' ');
      buffer.append('"');
      buffer.append(publicID);
      buffer.append('"');
      if (systemID != null) {
        buffer.append(' ');
        buffer.append('"');
        buffer.append(systemID);
        buffer.append('"');
      }
    } else {
      if (systemID != null) {
        buffer.append(' ');
        buffer.append(SYSTEM_ID);
        buffer.append(' ');
        buffer.append('"');
        buffer.append(systemID);
        buffer.append('"');
      }
    }
    buffer.append('>');
    return buffer.toString();
  }
  /**
   * Generates a compiled stylesheet from a parsed XSL document.
   *
   * @param xsl the parsed xsl document.
   * @param path the path to the document.
   */
  Templates generate(Node xsl, Path path) throws TransformerConfigurationException {
    log.fine("Generating XSL from " + path);

    // The code generation needs a static lock because the
    // application might have a separate factory object
    // for each thread.  The static lock protects the code generation
    // from overwriting its own code.
    synchronized (AbstractStylesheetFactory.class) {
      Generator gen = null;

      try {
        if (path == null && xsl != null) {
          Document doc = xsl.getOwnerDocument();
          if (doc == null && xsl instanceof Document) doc = (Document) xsl;

          DocumentType dtd = doc.getDoctype();
          String systemId = null;
          if (dtd != null) systemId = dtd.getSystemId();

          if (systemId != null) path = getStylePath().lookup(systemId);
        }

        if (path == null && xsl instanceof CauchoNode) {
          String filename = ((CauchoNode) xsl).getFilename();
          if (filename != null) path = getStylePath().lookup(filename);
        }

        if (path == null) path = getStylePath().lookup("anonymous.xsl");

        Path stylePath = path.getParent();

        Expr expr = XPath.parseExpr("//xtp:directive.page/@language");
        String language = expr.evalString(xsl);

        String userName = path.getUserPath();
        String mangledName = getMangledName(userName);

        String encoding = XPath.evalString("//xsl:output/@encoding", xsl);
        if (encoding != null && encoding.equals("")) encoding = null;

        if (language == null || language.equals("") || language.equals("java")) {
          language = "java";
          gen = new JavaGenerator(this, mangledName, encoding);
        } else throw new XslParseException(L.l("unsupported language `{0}'", language));

        gen.setPath(path);

        Iterator iter = XPath.select("//xtp:directive.page/@*", xsl);
        while (iter.hasNext()) {
          Attr attr = (Attr) iter.next();
          String name = attr.getNodeName();
          String value = attr.getNodeValue();

          if (name.equals("errorPage")) gen.setErrorPage(value);
          else if (name.equals("import")) gen.addImport(value);
          else if (name.equals("contentType")) gen.setContentType(value);
          else if (name.equals("language")) {
            if (!language.equalsIgnoreCase(value))
              throw new XslParseException(L.l("mismatched language `{0}'", value));
          } else if (name.equals("xml:space")) {
          } else throw new XslParseException(L.l("unknown directive `{0}'", name));
        }

        StylesheetImpl stylesheet = gen.generate(xsl);
        gen = null;
        stylesheet.init(path);
        // XXX: why was this here? stylesheet.init(getStylePath());
        stylesheet.setURIResolver(_uriResolver);

        return stylesheet;
      } catch (TransformerConfigurationException e) {
        throw e;
      } catch (Exception e) {
        throw new XslParseException(e);
      } finally {
        try {
          if (gen != null) gen.close();
        } catch (IOException e) {
        }
      }
    }
  }
예제 #20
0
  public void serializeNode(Node node, Writer writer, String indentLevel) throws IOException {
    // Determine action based on node type
    switch (node.getNodeType()) {
      case Node.DOCUMENT_NODE:
        writer.write("<?xml version = '1.0'?>"); // "<xml version=\"1.0\">");
        writer.write(lineSeparator);
        // recurse on each child
        NodeList nodes = node.getChildNodes();
        if (nodes != null) {
          for (int i = 0; i < nodes.getLength(); i++) {
            serializeNode(nodes.item(i), writer, "");
          }
        }

        /*
         *  Document doc = (Document)node;
         *  serializeNode(doc.getDocumentElement( ), writer, " ");
         */
        break;
      case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        writer.write(indentLevel + "<" + name);
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
          Node current = attributes.item(i);
          writer.write(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
        }
        writer.write(">");
        // recurse on each child
        NodeList children = node.getChildNodes();
        if (children != null) {
          if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE)) {
            writer.write(lineSeparator);
          }
          for (int i = 0; i < children.getLength(); i++) {
            serializeNode(children.item(i), writer, indentLevel + indent);
          }
          if ((children.item(0) != null)
              && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE)) {
            writer.write(indentLevel);
          }
        }
        writer.write("</" + name + ">");
        writer.write(lineSeparator);
        break;
      case Node.TEXT_NODE:
        writer.write(node.getNodeValue());
        break;
      case Node.CDATA_SECTION_NODE:
        writer.write("<![CDATA[" + node.getNodeValue() + "]]>");
        break;
      case Node.COMMENT_NODE:
        writer.write(indentLevel + "<!-- " + node.getNodeValue() + " -->");
        writer.write(lineSeparator);
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>");
        writer.write(lineSeparator);
        break;
      case Node.ENTITY_REFERENCE_NODE:
        writer.write("&" + node.getNodeName() + ";");
        break;
      case Node.DOCUMENT_TYPE_NODE:
        DocumentType docType = (DocumentType) node;
        writer.write("<!DOCTYPE " + docType.getName());
        if (docType.getPublicId() != null) {
          System.out.print(" PUBLIC \"" + docType.getPublicId() + "\" ");
        } else {
          writer.write(" SYSTEM ");
        }
        writer.write("\"" + docType.getSystemId() + "\">");
        writer.write(lineSeparator);
        break;
    }
  }
예제 #21
0
  public static String getMergedSource(GeneratedXmlFile generatedXmlFile, File existingFile)
      throws ShellException {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setExpandEntityReferences(false);
      DocumentBuilder builder = factory.newDocumentBuilder();
      builder.setEntityResolver(new NullEntityResolver());

      Document existingDocument = builder.parse(existingFile);
      StringReader sr = new StringReader(generatedXmlFile.getFormattedContent());
      Document newDocument = builder.parse(new InputSource(sr));

      DocumentType newDocType = newDocument.getDoctype();
      DocumentType existingDocType = existingDocument.getDoctype();

      if (!newDocType.getName().equals(existingDocType.getName())) {
        throw new ShellException(
            Messages.getString(
                "Warning.12", //$NON-NLS-1$
                existingFile.getName()));
      }

      Element existingRootElement = existingDocument.getDocumentElement();
      Element newRootElement = newDocument.getDocumentElement();

      // reconcile the root element attributes -
      // take all attributes from the new element and add to the existing element

      // remove all attributes from the existing root element
      NamedNodeMap attributes = existingRootElement.getAttributes();
      int attributeCount = attributes.getLength();
      for (int i = attributeCount - 1; i >= 0; i--) {
        Node node = attributes.item(i);
        existingRootElement.removeAttribute(node.getNodeName());
      }

      // add attributes from the new root node to the old root node
      attributes = newRootElement.getAttributes();
      attributeCount = attributes.getLength();
      for (int i = 0; i < attributeCount; i++) {
        Node node = attributes.item(i);
        existingRootElement.setAttribute(node.getNodeName(), node.getNodeValue());
      }

      // remove the old ibator generated elements and any
      // white space before the old ibator nodes
      List<Node> nodesToDelete = new ArrayList<Node>();
      NodeList children = existingRootElement.getChildNodes();
      int length = children.getLength();
      for (int i = 0; i < length; i++) {
        Node node = children.item(i);
        if (isAnIbatorNode(node)) {
          nodesToDelete.add(node);
        } else if (isWhiteSpace(node) && isAnIbatorNode(children.item(i + 1))) {
          nodesToDelete.add(node);
        }
      }

      for (Node node : nodesToDelete) {
        existingRootElement.removeChild(node);
      }

      // add the new ibator generated elements
      children = newRootElement.getChildNodes();
      length = children.getLength();
      Node firstChild = existingRootElement.getFirstChild();
      for (int i = 0; i < length; i++) {
        Node node = children.item(i);
        // don't add the last node if it is only white space
        if (i == length - 1) {
          if (isWhiteSpace(node)) {
            break;
          }
        }

        Node newNode = existingDocument.importNode(node, true);
        if (firstChild == null) {
          existingRootElement.appendChild(newNode);
        } else {
          existingRootElement.insertBefore(newNode, firstChild);
        }
      }

      // pretty print the result
      return prettyPrint(existingDocument);
    } catch (Exception e) {
      throw new ShellException(
          Messages.getString(
              "Warning.13", //$NON-NLS-1$
              existingFile.getName()),
          e);
    }
  }
예제 #22
0
 void serialize(Node node, ContentHandler ch, LexicalHandler lh) throws SAXException {
   attrs = node.getAttributes();
   Node children;
   Node next = node.getNextSibling();
   switch (node.getNodeType()) {
     case Node.ELEMENT_NODE:
       String uri = node.getNamespaceURI();
       String prefix = node.getPrefix();
       boolean defined = isDefined(prefix, uri);
       if (!defined) {
         define(prefix, uri);
         ch.startPrefixMapping(prefix, uri);
       }
       String localName = node.getLocalName();
       String qName = node.getNodeName();
       ch.startElement(uri, localName, qName, this);
       children = node.getFirstChild();
       if (children != null) {
         serialize(children, ch, lh);
       }
       ch.endElement(uri, localName, qName);
       if (!defined) {
         ch.endPrefixMapping(prefix);
         undefine(prefix, uri);
       }
       break;
     case Node.TEXT_NODE:
       char[] chars = node.getNodeValue().toCharArray();
       ch.characters(chars, 0, chars.length);
       break;
     case Node.CDATA_SECTION_NODE:
       char[] cdata = node.getNodeValue().toCharArray();
       if (lh != null) {
         lh.startCDATA();
         ch.characters(cdata, 0, cdata.length);
         lh.endCDATA();
       } else {
         ch.characters(cdata, 0, cdata.length);
       }
       break;
     case Node.COMMENT_NODE:
       if (lh != null) {
         char[] comment = node.getNodeValue().toCharArray();
         lh.comment(comment, 0, comment.length);
       }
       break;
     case Node.DOCUMENT_NODE:
     case Node.DOCUMENT_FRAGMENT_NODE:
       ch.startDocument();
       children = node.getFirstChild();
       if (children != null) {
         serialize(children, ch, lh);
       }
       ch.endDocument();
       break;
     case Node.DOCUMENT_TYPE_NODE:
       if (lh != null) {
         DocumentType doctype = (DocumentType) node;
         String publicId = doctype.getPublicId();
         String systemId = doctype.getSystemId();
         lh.startDTD(node.getNodeName(), publicId, systemId);
         NamedNodeMap entities = doctype.getEntities();
         int len = entities.getLength();
         for (int i = 0; i < len; i++) {
           Node entity = entities.item(i);
           String entityName = entity.getNodeName();
           lh.startEntity(entityName);
           lh.endEntity(entityName);
         }
         lh.endDTD();
       }
       break;
     case Node.PROCESSING_INSTRUCTION_NODE:
       ch.processingInstruction(node.getNodeName(), node.getNodeValue());
       break;
     case Node.ENTITY_REFERENCE_NODE:
       ch.skippedEntity(node.getNodeName());
       break;
   }
   attrs = null;
   if (next != null) {
     serialize(next, ch, lh);
   }
 }
예제 #23
0
  /**
   * Handle document type definition with validation of publicId and systemId.
   *
   * @param received
   * @param source
   * @param validationContext
   * @param namespaceContext
   */
  private void doDocumentTypeDefinition(
      Node received,
      Node source,
      XmlMessageValidationContext validationContext,
      NamespaceContext namespaceContext,
      TestContext context) {

    Assert.isTrue(
        source instanceof DocumentType,
        "Missing document type definition in expected xml fragment");

    DocumentType receivedDTD = (DocumentType) received;
    DocumentType sourceDTD = (DocumentType) source;

    if (log.isDebugEnabled()) {
      log.debug(
          "Validating document type definition: "
              + receivedDTD.getPublicId()
              + " ("
              + receivedDTD.getSystemId()
              + ")");
    }

    if (!StringUtils.hasText(sourceDTD.getPublicId())) {
      Assert.isNull(
          receivedDTD.getPublicId(),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Document type public id not equal",
              sourceDTD.getPublicId(),
              receivedDTD.getPublicId()));
    } else if (sourceDTD.getPublicId().trim().equals(CitrusConstants.IGNORE_PLACEHOLDER)) {
      if (log.isDebugEnabled()) {
        log.debug(
            "Document type public id: '"
                + receivedDTD.getPublicId()
                + "' is ignored by placeholder '"
                + CitrusConstants.IGNORE_PLACEHOLDER
                + "'");
      }
    } else {
      Assert.isTrue(
          StringUtils.hasText(receivedDTD.getPublicId())
              && receivedDTD.getPublicId().equals(sourceDTD.getPublicId()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Document type public id not equal",
              sourceDTD.getPublicId(),
              receivedDTD.getPublicId()));
    }

    if (!StringUtils.hasText(sourceDTD.getSystemId())) {
      Assert.isNull(
          receivedDTD.getSystemId(),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Document type system id not equal",
              sourceDTD.getSystemId(),
              receivedDTD.getSystemId()));
    } else if (sourceDTD.getSystemId().trim().equals(CitrusConstants.IGNORE_PLACEHOLDER)) {
      if (log.isDebugEnabled()) {
        log.debug(
            "Document type system id: '"
                + receivedDTD.getSystemId()
                + "' is ignored by placeholder '"
                + CitrusConstants.IGNORE_PLACEHOLDER
                + "'");
      }
    } else {
      Assert.isTrue(
          StringUtils.hasText(receivedDTD.getSystemId())
              && receivedDTD.getSystemId().equals(sourceDTD.getSystemId()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Document type system id not equal",
              sourceDTD.getSystemId(),
              receivedDTD.getSystemId()));
    }

    validateXmlTree(
        received.getNextSibling(),
        source.getNextSibling(),
        validationContext,
        namespaceContext,
        context);
  }
예제 #24
0
  /** Writes the specified node, recursively. */
  public void write(Node node) {

    // is there anything to do?
    if (node == null) {
      return;
    }

    short type = node.getNodeType();
    switch (type) {
      case Node.DOCUMENT_NODE:
        {
          Document document = (Document) node;
          if (!fCanonical) {
            fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            fOut.flush();
            write(document.getDoctype());
          }
          write(document.getDocumentElement());
          break;
        }

      case Node.DOCUMENT_TYPE_NODE:
        {
          DocumentType doctype = (DocumentType) node;
          fOut.print("<!DOCTYPE ");
          fOut.print(doctype.getName());
          String publicId = doctype.getPublicId();
          String systemId = doctype.getSystemId();
          if (publicId != null) {
            fOut.print(" PUBLIC '");
            fOut.print(publicId);
            fOut.print("' '");
            fOut.print(systemId);
            fOut.print('\'');
          } else {
            fOut.print(" SYSTEM '");
            fOut.print(systemId);
            fOut.print('\'');
          }
          String internalSubset = doctype.getInternalSubset();
          if (internalSubset != null) {
            fOut.println(" [");
            fOut.print(internalSubset);
            fOut.print(']');
          }
          fOut.println('>');
          break;
        }

      case Node.ELEMENT_NODE:
        {
          fOut.print('<');
          fOut.print(node.getNodeName());
          Attr attrs[] = sortAttributes(node.getAttributes());
          for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            fOut.print(' ');
            fOut.print(attr.getNodeName());
            fOut.print("=\"");
            normalizeAndPrint(attr.getNodeValue());
            fOut.print('"');
          }
          fOut.print('>');
          fOut.flush();

          Node child = node.getFirstChild();
          while (child != null) {
            write(child);
            child = child.getNextSibling();
          }
          break;
        }

      case Node.ATTRIBUTE_NODE:
        {
          Attr attr = (Attr) node;
          fOut.print(attr.getValue());
          fOut.flush();
          break;
        }

      case Node.ENTITY_REFERENCE_NODE:
        {
          if (fCanonical) {
            Node child = node.getFirstChild();
            while (child != null) {
              write(child);
              child = child.getNextSibling();
            }
          } else {
            fOut.print('&');
            fOut.print(node.getNodeName());
            fOut.print(';');
            fOut.flush();
          }
          break;
        }

      case Node.CDATA_SECTION_NODE:
        {
          if (fCanonical) {
            normalizeAndPrint(node.getNodeValue());
          } else {
            fOut.print("<![CDATA[");
            fOut.print(node.getNodeValue());
            fOut.print("]]>");
          }
          fOut.flush();
          break;
        }

      case Node.TEXT_NODE:
        {
          normalizeAndPrint(node.getNodeValue());
          fOut.flush();
          break;
        }

      case Node.PROCESSING_INSTRUCTION_NODE:
        {
          fOut.print("<?");
          fOut.print(node.getNodeName());
          String data = node.getNodeValue();
          if (data != null && data.length() > 0) {
            fOut.print(' ');
            fOut.print(data);
          }
          fOut.println("?>");
          fOut.flush();
          break;
        }
    }

    if (type == Node.ELEMENT_NODE) {
      fOut.print("</");
      fOut.print(node.getNodeName());
      fOut.print('>');
      fOut.flush();
    }
  } // write(Node)