/** * 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; }
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; }
/** * 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); }
// 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()); } }
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; }
/** * 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)); }
@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); } }
@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; }
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; }
@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); } }
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; }
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; }
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); } }
/** * 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) { } } } }
/** * 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); }
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; } }
/** 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)