protected Object addStatisticsAsText(String stats, Object result) throws UnsupportedEncodingException{ if (result != null) { if (stats == null) stats = context.statistics.printStatistics(); if (result instanceof Document) { Document document = (Document) result; Comment comment = document.createComment("\n" + stats); document.appendChild(comment); } else if (result instanceof byte[]) { String encodingCharSet = "UTF-8"; if (context.requestedObject != null) encodingCharSet = context.requestedObject.getEncodingCharSet(); String sResult = new String((byte[]) result, encodingCharSet); sResult += "<!--\n" + stats + "\n-->"; result = sResult.getBytes(encodingCharSet); } } return result; }
public static Element nextElement(Iterator iter) { while (iter.hasNext()) { Node n = (Node) iter.next(); if (n instanceof Text) { Text t = (Text) n; if (t.getData().trim().length() == 0) continue; fail("parsing.nonWhitespaceTextFound", t.getData().trim()); } if (n instanceof Comment) continue; if (!(n instanceof Element)) fail("parsing.elementExpected"); return (Element) n; } return null; }
/** * Extract the textual content from a Node. * This is rather like the XPath value of a Node. * @param node The node to extract the text from * @return The textual value of the node */ public static String getText(Node node) { StringBuffer reply = new StringBuffer(); NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ((child instanceof CharacterData && !(child instanceof Comment)) || child instanceof EntityReference) { reply.append(child.getNodeValue()); } else if (child.getNodeType() == Node.ELEMENT_NODE) { reply.append(getText(child)); } } return reply.toString(); }
/** * Serializes a Comment Node. * * @param node The Comment Node to serialize */ protected void serializeComment(Comment node) throws SAXException { // comments=true if ((fFeatures & COMMENTS) != 0) { String data = node.getData(); // well-formed=true if ((fFeatures & WELLFORMED) != 0) { isCommentWellFormed(data); } if (fLexicalHandler != null) { // apply the LSSerializer filter after the operations requested by the // DOMConfiguration parameters have been applied if (!applyFilter(node, NodeFilter.SHOW_COMMENT)) { return; } fLexicalHandler.comment(data.toCharArray(), 0, data.length()); } } }
protected int moveToChild(final int currentChild) { content = getCurrentElement().getChildNodes().item(currentChild); if (content instanceof Text) { return CHARACTERS; } else if (content instanceof Element) { return START_ELEMENT; } else if (content instanceof CDATASection) { return CDATA; } else if (content instanceof Comment) { return CHARACTERS; } else if (content instanceof EntityReference) { return ENTITY_REFERENCE; } throw new IllegalStateException(); }
private static void stripComments(NodeList children) { org.w3c.dom.Node child; List<Comment> remove; remove = new ArrayList<>(); for (int i = 0, max = children.getLength(); i < max; i++) { child = children.item(i); if (child instanceof Element) { stripComments(child.getChildNodes()); } else if (child instanceof Comment) { remove.add((Comment) child); } else { // nothing to do } } for (Comment c : remove) { c.getParentNode().removeChild(c); } }
protected static XNode parseNode(Node domNode) { if (domNode instanceof Element) { return XElement.parse((Element) domNode); } if (domNode instanceof Text) { return new XText(((Text) domNode).getTextContent()); } if (domNode instanceof Comment) { return new XComment(((Comment) domNode).getTextContent()); } if (domNode instanceof ProcessingInstruction) { return new XProcessingInstruction(((ProcessingInstruction) domNode).getTarget(), ((ProcessingInstruction) domNode).getData()); } if (domNode instanceof DocumentType) { return new XDocumentType(((DocumentType) domNode).getName(), ((DocumentType) domNode).getInternalSubset()); } throw new UnsupportedOperationException("implement " + domNode); }
protected void print(Node node, Map namespaces, boolean endWithComma) { switch (node.getNodeType()) { case Node.ELEMENT_NODE : printElement((Element) node, namespaces, endWithComma); break; case Node.PROCESSING_INSTRUCTION_NODE : printPI((ProcessingInstruction) node, endWithComma); break; case Node.TEXT_NODE : printText((Text) node, endWithComma); break; case Node.COMMENT_NODE : printComment((Comment) node, endWithComma); break; } }
static <R> R visitNode(Node node, NodeVisitor<R> visitor) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: return visitor.visitElement((Element) node); case Node.ATTRIBUTE_NODE: return visitor.visitAttr((Attr) node); case Node.TEXT_NODE: return visitor.visitText((Text) node); case Node.CDATA_SECTION_NODE: return visitor.visitCDATASection((CDATASection) node); case Node.ENTITY_REFERENCE_NODE: return visitor.visitEntityReference((EntityReference) node); case Node.ENTITY_NODE: return visitor.visitEntity((Entity) node); case Node.PROCESSING_INSTRUCTION_NODE: return visitor.visitProcessingInstruction((ProcessingInstruction) node); case Node.COMMENT_NODE: return visitor.visitComment((Comment) node); case Node.DOCUMENT_NODE: return visitor.visitDocument((Document) node); case Node.DOCUMENT_TYPE_NODE: return visitor.visitDocumentType((DocumentType) node); case Node.DOCUMENT_FRAGMENT_NODE: return visitor.visitDocumentFragment((DocumentFragment) node); case Node.NOTATION_NODE: return visitor.visitNotation((Notation) node); default: throw new RuntimeException(); } }
public Object put(Object key, Object value) { if (key.toString().equalsIgnoreCase("XmlRoot")) { return super.put(key, value); } else if (key.toString().equalsIgnoreCase("XmlComment")) { // Remove all comment nodes, and add 1 new one at the top remove(key); if (!((cfData) value).toString().trim().equals("")) { try { Comment c = ((Document) nodeData).createComment(((cfData) value).toString()); nodeData.insertBefore(c, nodeData.getFirstChild()); } catch (DOMException ex) { // Nothing else we can do here com.nary.Debug.printStackTrace(ex); } } nodeData.normalize(); return null; } else if (key.toString().equalsIgnoreCase("XMLDocType")) { // Do nothing return null; } else { return super.put(key, value); } }
public void testInvalidCharactersComment() throws Exception { ErrorRecorder errorRecorder = new ErrorRecorder(); domConfiguration.setParameter("error-handler", errorRecorder); domConfiguration.setParameter("namespaces", false); Element root = document.createElement("foo"); document.appendChild(root); Comment comment = document.createComment(""); root.appendChild(comment); for (int c = 0; c <= Character.MAX_VALUE; c++) { comment.setData(new String(new char[] { 'A', 'B', (char) c})); document.normalizeDocument(); if (isValid((char) c)) { assertEquals(Collections.<DOMError>emptyList(), errorRecorder.errors); } else { errorRecorder.assertAllErrors("For character " + c, DOMError.SEVERITY_ERROR, "wf-invalid-character"); } } }
public static Node duplicate(Node node, Document ownerDocument) { if (node instanceof Text) return ownerDocument.createTextNode(node.getNodeValue()); if (node instanceof Comment) return ownerDocument.createComment(node.getNodeValue()); Node newNode = ownerDocument.createElement(node.getNodeName()); NamedNodeMap attribs = node.getAttributes(); for (int i = 0; i < attribs.getLength(); i++) { Node attrib = attribs.item(i); addAttribute(newNode, attrib.getNodeName(), attrib.getNodeValue()); } for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) { Node newN = duplicate(n, ownerDocument); newNode.appendChild(newN); } return newNode; }
/** * Creates a new XmlComment as child of given parent. * @param parent The parent of the new XmlComment. * @param contents optional initial contents, ignored if empty * @return The created XmlElement. * @throws VilException if element could not be created. */ public static XmlComment create(XmlElement parent, @ParameterMeta(name = "contents") String contents) throws VilException { XmlComment newElement = null; if (null == parent) { throw new VilException("Can not append child from NULL element!", VilException.ID_IS_NULL); } try { Comment newNode = parent.getNode().getOwnerDocument().createComment(contents); parent.getNode().appendChild(newNode); // notifies change newElement = new XmlComment(parent, newNode); parent.addChild(newElement); // notifies change } catch (DOMException exc) { throw new VilException("Invalid character, name or ID!", VilException.ID_INVALID); } if (null != contents && contents.length() > 0) { newElement.setCdata(contents); } return newElement; }
public static Node duplicate(Node node, Document ownerDocument) { if (node instanceof Text) { return ownerDocument.createTextNode(node.getNodeValue()); } if (node instanceof Comment) { return ownerDocument.createComment(node.getNodeValue()); } Node newNode = ownerDocument.createElement(node.getNodeName()); NamedNodeMap attribs = node.getAttributes(); for (int i = 0; i < attribs.getLength(); i++) { Node attrib = attribs.item(i); addAttribute(newNode, attrib.getNodeName(), attrib.getNodeValue()); } for (Node n = node.getFirstChild(); n != null; n = n.getNextSibling()) { Node newN = duplicate(n, ownerDocument); newNode.appendChild(newN); } return newNode; }
@Test public void deeperStructure() { Element e = doc.createElement("foo"); doc.appendChild(e); Element e2 = doc.createElement("foo"); e.appendChild(e2); e2.appendChild(doc.createElement("foo")); Element e3 = doc.createElement("foo"); e2.appendChild(e3); e2.appendChild(doc.createComment("foo")); Comment c = doc.createComment("foo"); e2.appendChild(c); assertEquals("/foo[1]/foo[1]/foo[2]", builder.apply(e3).getXPath()); assertEquals("/foo[1]/foo[1]/comment()[2]", builder.apply(c).getXPath()); }
private void initXMLReport() { logger.debug(""); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); report = db.newDocument(); rootElement = report.createElement("root"); report.appendChild(rootElement); Comment comment = report.createComment("DDoc verification result"); report.insertBefore(comment, rootElement); } catch (ParserConfigurationException e) { logger.error(e.getMessage()); throw new DigiDoc4JException(e); } }
/** * Converts or extracts the SAAJ node from the given DOM Node (domNode) * * @param domNode * @return the SAAJ Node corresponding to the domNode */ static javax.xml.soap.Node toSAAJNode(org.w3c.dom.Node domNode, Node parentNode) { if (domNode == null) { return null; } Node saajNode = (Node)((NodeImpl)domNode).getUserData(SAAJ_NODE); if (saajNode == null) { // if SAAJ node has not been set in userData, try to construct it return toSAAJNode2(domNode, parentNode); } // update siblings for text nodes if (domNode instanceof org.w3c.dom.Text || domNode instanceof org.w3c.dom.Comment) { org.w3c.dom.Node prevSiblingDOMNode = domNode.getPreviousSibling(); org.w3c.dom.Node nextSiblingDOMNode = domNode.getNextSibling(); TextImplEx saajTextNode = (TextImplEx)saajNode; saajTextNode.setPreviousSibling(prevSiblingDOMNode); saajTextNode.setNextSibling(nextSiblingDOMNode); } return saajNode; }
private void processContents(Element element) throws Exception { Node node = element.getFirstChild(); while (node != null) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: processElement((Element) node); break; case Node.TEXT_NODE: processText(node); break; case Node.COMMENT_NODE: processComment((Comment) node); break; default: throw new Exception("unhandled node type "+Integer.toString(node.getNodeType())); } node = node.getNextSibling(); } }
/** * @param xmlNode XML node * @param xmlStreamWriter XML stream writer * @throws XMLStreamException the XML stream exception */ public static void writeNode(Node xmlNode, XMLStreamWriter xmlStreamWriter) throws XMLStreamException { if (xmlNode instanceof Element) { addElement((Element) xmlNode, xmlStreamWriter); } else if (xmlNode instanceof Text) { xmlStreamWriter.writeCharacters(xmlNode.getNodeValue()); } else if (xmlNode instanceof CDATASection) { xmlStreamWriter.writeCData(((CDATASection) xmlNode).getData()); } else if (xmlNode instanceof Comment) { xmlStreamWriter.writeComment(((Comment) xmlNode).getData()); } else if (xmlNode instanceof EntityReference) { xmlStreamWriter.writeEntityRef(xmlNode.getNodeValue()); } else if (xmlNode instanceof ProcessingInstruction) { ProcessingInstruction procInst = (ProcessingInstruction) xmlNode; xmlStreamWriter.writeProcessingInstruction(procInst.getTarget(), procInst.getData()); } else if (xmlNode instanceof Document) { writeToDocument((Document) xmlNode, xmlStreamWriter); } }
/** * * @param xmlNode * @param xmlStreamWriter * @throws XMLStreamException */ public static void writeNode(Node xmlNode, XMLStreamWriter xmlStreamWriter) throws XMLStreamException { if (xmlNode instanceof Element) { addElement((Element) xmlNode, xmlStreamWriter); } else if (xmlNode instanceof Text) { xmlStreamWriter.writeCharacters(((Text) xmlNode).getNodeValue()); } else if (xmlNode instanceof CDATASection) { xmlStreamWriter.writeCData(((CDATASection) xmlNode).getData()); } else if (xmlNode instanceof Comment) { xmlStreamWriter.writeComment(((Comment) xmlNode).getData()); } else if (xmlNode instanceof EntityReference) { xmlStreamWriter.writeEntityRef(((EntityReference) xmlNode) .getNodeValue()); } else if (xmlNode instanceof ProcessingInstruction) { ProcessingInstruction procInst = (ProcessingInstruction) xmlNode; xmlStreamWriter.writeProcessingInstruction(procInst.getTarget(), procInst.getData()); } else if (xmlNode instanceof Document) { writeToDocument((Document) xmlNode, xmlStreamWriter); } }
private Element createHeader() { Element p1 = tei.createElement("p"); Element header = tei.createElement("teiHeader"); Element fileDesc = tei.createElement("fileDesc"); Element publicationStmt = tei.createElement("publicationStmt"); publicationStmt.appendChild(p1); Element sourceDesc = tei.createElement("sourceDesc"); Element p = tei.createElement("p"); sourceDesc.appendChild(p); Element titleStmt = tei.createElement("titleStmt"); Element title = tei.createElement("title"); Comment ordering = tei.createComment(MessageFormat.format("ordering: {0} / {1} / {2}", project.getLevel1(), project.getLevel2(), project.getLevel3())); Text textNode = tei.createTextNode(project.getTitle()); title.appendChild(textNode); titleStmt.appendChild(title); fileDesc.appendChild(titleStmt); fileDesc.appendChild(publicationStmt); fileDesc.appendChild(sourceDesc); header.appendChild(fileDesc); header.appendChild(ordering); return header; }
private static Element getOrCreateRootElement(AuxiliaryConfiguration conf, boolean shared) { Element el = conf.getConfigurationFragment(ROOT, NAMESPACE, shared); if (el == null) { el = XMLUtil.createDocument(ROOT, NAMESPACE, null, null).getDocumentElement(); if (shared) { Comment comment = el.getOwnerDocument().createComment("\nProperties that influence various parts of the IDE, especially code formatting and the like. \n" + //NOI18N "You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.\n" + //NOI18N "That way multiple projects can share the same settings (useful for formatting rules for example).\n" + //NOI18N "Any value defined here will override the pom.xml file value but is only applicable to the current project.\n"); //NOI18N el.appendChild(comment); } } return el; }
private static void copyXMLTree(Document doc, Element from, Element to, String newNamespace) { NodeList nl = from.getChildNodes(); int length = nl.getLength(); for (int i = 0; i < length; i++) { org.w3c.dom.Node node = nl.item(i); org.w3c.dom.Node newNode; switch (node.getNodeType()) { case org.w3c.dom.Node.ELEMENT_NODE: Element oldElement = (Element) node; newNode = doc.createElementNS(newNamespace, oldElement.getTagName()); NamedNodeMap attrs = oldElement.getAttributes(); int alength = attrs.getLength(); for (int j = 0; j < alength; j++) { org.w3c.dom.Attr oldAttr = (org.w3c.dom.Attr) attrs.item(j); ((Element)newNode).setAttributeNS(oldAttr.getNamespaceURI(), oldAttr.getName(), oldAttr.getValue()); } copyXMLTree(doc, oldElement, (Element) newNode, newNamespace); break; case org.w3c.dom.Node.TEXT_NODE: newNode = doc.createTextNode(((Text) node).getData()); break; case org.w3c.dom.Node.COMMENT_NODE: newNode = doc.createComment(((Comment) node).getData()); break; default: // Other types (e.g. CDATA) not yet handled. throw new AssertionError(node); } to.appendChild(newNode); } }
private AntLocation handleInitials(Document doc, Lookup context) { ensurePropertiesCopied(doc.getDocumentElement()); Comment comm = doc.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_edit_target") + " "); doc.getDocumentElement().appendChild(comm); comm = doc.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_more_info_run.single") + " "); doc.getDocumentElement().appendChild(comm); return findPackageRoot(context); }
/** * Write. * * @param node * the node */ protected void write(Comment node) { printWriter.print("<!--"); //$NON-NLS-1$ String comment = node.getNodeValue(); if (comment != null && comment.length() > 0) { normalizeAndPrint(comment, false); } printWriter.print("-->"); //$NON-NLS-1$ printWriter.flush(); }
private void setModuleParams(Element parent, Module<T> module) throws PlanException, ParameterException, UnsupportedServiceException, ConverterException, SAXException, IOException, URISyntaxException { for (Node child : XMLUtils.childrenNodes(parent)) { if (child instanceof Comment) continue; if (checkEmptyText(child)) continue; if (child instanceof Element) { Element childElement = (Element) child; setParam(childElement, module); continue; } throw new PlanException("unexpected node: " + child); } }
public Object getValue() { if (node.getNodeType() == Node.COMMENT_NODE) { String text = ((Comment) node).getData(); return text == null ? "" : text.trim(); } return stringValue(node); }
public Object postGetDocument(Document document) throws Exception { Engine.logContext.debug("postGetDocument()"); String copyright = "\nGenerated by Convertigo Enterprise Mobility Server\n"; copyright += "Requester: " + getName() + "\n"; Comment comment = document.createComment(copyright); document.appendChild(comment); NodeList attachs = document.getDocumentElement().getElementsByTagName("attachment"); if ((attachs != null) && (attachs.getLength()>0)) { return document; } if (context.isXsltRequest) { if (context.absoluteSheetUrl == null) { String browser = findBrowserFromUserAgent(context.project, context.userAgent); Engine.logContext.debug("Browser for stylesheet: \"" + browser + "\""); findStyleSheet(browser); } setStyleSheet(document); Object result = performXSLT(document); return result; } else { return document; } }
protected void write(Comment node) { printWriter.print("<!--"); //$NON-NLS-1$ String comment = node.getNodeValue(); if (comment != null && comment.length() > 0) { printWriter.print(comment); } printWriter.print("-->"); //$NON-NLS-1$ printWriter.flush(); }
public static void createChildTextWithComment(Document paramDocument, Element paramElement, String paramString1, String paramString2, String paramString3) { Element localElement = paramDocument.createElement(paramString1); localElement.appendChild(paramDocument.createTextNode((paramString2 == null) ? "" : paramString2)); Comment localComment = paramDocument.createComment(paramString3); paramElement.appendChild(localComment); paramElement.appendChild(localElement); }