List of usage examples for org.w3c.dom Node DOCUMENT_NODE
short DOCUMENT_NODE
To view the source code for org.w3c.dom Node DOCUMENT_NODE.
Click Source Link
Document
. From source file:org.apache.xml.security.utils.XMLUtils.java
/** * This method returns the first non-null owner document of the Nodes in this Set. * This method is necessary because it <I>always</I> returns a * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE> * if the {@link Node} is a {@link Document}. * * @param xpathNodeSet/*from w w w . ja v a 2 s . com*/ * @return the owner document */ public static Document getOwnerDocument(Set<Node> xpathNodeSet) { NullPointerException npe = null; for (Node node : xpathNodeSet) { int nodeType = node.getNodeType(); if (nodeType == Node.DOCUMENT_NODE) { return (Document) node; } try { if (nodeType == Node.ATTRIBUTE_NODE) { return ((Attr) node).getOwnerElement().getOwnerDocument(); } return node.getOwnerDocument(); } catch (NullPointerException e) { npe = e; } } throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + (npe == null ? "" : npe.getMessage()) + "\""); }
From source file:org.apache.xml.security.utils.XMLUtils.java
/** * This is the work horse for {@link #circumventBug2650}. * * @param node//w w w . ja v a 2 s . c o m * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650"> * Namespace axis resolution is not XPath compliant </A> */ private static void circumventBug2650internal(Node node) { Node parent = null; Node sibling = null; final String namespaceNs = Constants.NamespaceSpecNS; do { switch (node.getNodeType()) { case Node.ELEMENT_NODE: Element element = (Element) node; if (!element.hasChildNodes()) { break; } if (element.hasAttributes()) { NamedNodeMap attributes = element.getAttributes(); int attributesLength = attributes.getLength(); for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } Element childElement = (Element) child; for (int i = 0; i < attributesLength; i++) { Attr currentAttr = (Attr) attributes.item(i); if (!namespaceNs.equals(currentAttr.getNamespaceURI())) continue; if (childElement.hasAttributeNS(namespaceNs, currentAttr.getLocalName())) { continue; } childElement.setAttributeNS(namespaceNs, currentAttr.getName(), currentAttr.getNodeValue()); } } } case Node.ENTITY_REFERENCE_NODE: parent = node; sibling = node.getFirstChild(); break; case Node.DOCUMENT_NODE: parent = node; sibling = node.getFirstChild(); break; } while ((sibling == null) && (parent != null)) { sibling = parent.getNextSibling(); parent = parent.getParentNode(); } if (sibling == null) { return; } node = sibling; sibling = node.getNextSibling(); } while (true); }
From source file:org.apereo.portal.io.xml.PortalDataKey.java
public PortalDataKey(Node rootElement) { if (rootElement.getNodeType() == Node.DOCUMENT_NODE) { rootElement = ((Document) rootElement).getDocumentElement(); }/*w w w.j ava 2s .c o m*/ final String nodeName = rootElement.getNodeName(); final String namespaceURI = rootElement.getNamespaceURI(); if (namespaceURI != null) { this.name = new QName(namespaceURI, nodeName); } else { this.name = new QName(nodeName); } final NamedNodeMap attributes = rootElement.getAttributes(); if (attributes != null) { final Node scriptAttr = attributes.getNamedItem(SCRIPT_ATTRIBUTE_NAME.getLocalPart()); if (scriptAttr != null) { this.script = scriptAttr.getTextContent(); } else { this.script = null; } final Node versionAttr = attributes.getNamedItem(VERSION_ATTRIBUTE_NAME.getLocalPart()); if (versionAttr != null) { this.version = versionAttr.getTextContent(); } else { this.version = null; } } else { this.script = null; this.version = null; } }
From source file:org.chiba.xml.xforms.connector.SchemaValidator.java
/** * validate the instance according to the schema specified on the model * * @return false if the instance is not valid *//* w ww .j av a 2 s.com*/ public boolean validateSchema(Model model, Node instance) throws XFormsException { boolean valid = true; String message; if (LOGGER.isDebugEnabled()) LOGGER.debug("SchemaValidator.validateSchema: validating instance"); //needed if we want to load schemas from Model + set it as "schemaLocation" attribute String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema"); if (schemas != null && !schemas.equals("")) { // valid=false; //add schemas to element //shouldn't it be done on a copy of the doc ? Element el = null; if (instance.getNodeType() == Node.ELEMENT_NODE) el = (Element) instance; else if (instance.getNodeType() == Node.DOCUMENT_NODE) el = ((Document) instance).getDocumentElement(); else { if (LOGGER.isDebugEnabled()) LOGGER.debug("instance node type is: " + instance.getNodeType()); } String prefix = NamespaceResolver.getPrefix(el, XMLSCHEMA_INSTANCE_NS); //test if with targetNamespace or not //if more than one schema : namespaces are mandatory ! (optional only for 1) StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false); String schemaLocations = null; String noNamespaceSchemaLocation = null; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); //check that it is an URL URI uri = null; try { uri = new java.net.URI(token); } catch (java.net.URISyntaxException ex) { if (LOGGER.isDebugEnabled()) LOGGER.debug(token + " is not an URI"); } if (uri != null) { String ns; try { ns = this.getSchemaNamespace(uri); if (ns != null && !ns.equals("")) { if (schemaLocations == null) schemaLocations = ns + " " + token; else schemaLocations = schemaLocations + " " + ns + " " + token; ///add the namespace declaration if it is not on the instance? //TODO: how to know with which prefix ? String nsPrefix = NamespaceResolver.getPrefix(el, ns); if (nsPrefix == null) { //namespace not declared ! LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token + " is not declared in instance: declaring it as default..."); el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns); } } else if (noNamespaceSchemaLocation == null) noNamespaceSchemaLocation = token; else { //we have more than one schema without namespace LOGGER.warn("SchemaValidator: There is more than one schema without namespace !"); } } catch (Exception ex) { LOGGER.warn( "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(), ex); //in case there was an exception: do nothing, do not set the schema } } } //write schemaLocations found if (schemaLocations != null && !schemaLocations.equals("")) el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations); if (noNamespaceSchemaLocation != null) el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation", noNamespaceSchemaLocation); //save and parse the doc ValidationErrorHandler handler = null; File f; try { //save document f = File.createTempFile("instance", ".xml"); f.deleteOnExit(); TransformerFactory trFact = TransformerFactory.newInstance(); Transformer trans = trFact.newTransformer(); DOMSource source = new DOMSource(el); StreamResult result = new StreamResult(f); trans.transform(source, result); if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath()); //parse it with error handler to validate it handler = new ValidationErrorHandler(); SAXParserFactory parserFact = SAXParserFactory.newInstance(); parserFact.setValidating(true); parserFact.setNamespaceAware(true); SAXParser parser = parserFact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //validation activated reader.setFeature("http://xml.org/sax/features/validation", true); //schema validation activated reader.setFeature("http://apache.org/xml/features/validation/schema", true); //used only to validate the schema, not the instance //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true); //validate only if there is a grammar reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); parser.parse(f, handler); } catch (Exception ex) { LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex); //throw new XFormsException("XMLSchema validation failed. "+message); } //if no exception if (handler != null && handler.isValid()) valid = true; else { message = handler.getMessage(); //TODO: find a way to get the error message displayed throw new XFormsException("XMLSchema validation failed. " + message); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: result=" + valid); } return valid; }
From source file:org.chiba.xml.xforms.connector.serializer.FormDataSerializer.java
/** * Serialize instance into multipart/form-data stream as defined in * http://www.w3.org/TR/xforms/slice11.html#serialize-form-data * * @param submission/* w w w . j av a 2 s . c om*/ * @param instance * @param stream * @param defaultEncoding * @throws Exception on error */ public void serialize(Submission submission, Node instance, OutputStream stream, String defaultEncoding) throws Exception { // sanity checks if (instance == null) return; switch (instance.getNodeType()) { case Node.ELEMENT_NODE: break; case Node.DOCUMENT_NODE: instance = ((Document) instance).getDocumentElement(); break; default: return; } String encoding = defaultEncoding; if (submission.getEncoding() != null) { encoding = submission.getEncoding(); } // generate boundary Random rnd = new Random(System.currentTimeMillis()); String boundary = DigestUtils.md5Hex(getClass().getName() + rnd.nextLong()); // serialize the instance ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(bos, encoding))); serializeElement(writer, (Element) instance, boundary, encoding); writer.print("\r\n--" + boundary + "--"); writer.flush(); // write to the stream String header = "Content-Type: multipart/form-data;\r\n" + "\tcharset=\"" + encoding + "\";\r\n" + "\tboundary=\"" + boundary + "\";\r\n" + "Content-Length: " + bos.size() + "\r\n\r\n"; stream.write(header.getBytes(encoding)); bos.writeTo(stream); }
From source file:org.chiba.xml.xforms.constraints.RelevanceSelector.java
/** * Returns a document containing only the relevant model items of the * specified instance data./*from ww w .ja v a2 s . c o m*/ * * @param instance the instance. * @param path the path denoting an instance subtree. * @return a document containing only the relevant model items of the * specified instance data. */ public static Document selectRelevant(Instance instance, String path) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("select relevant: processing " + path); } Document relevantDocument = DOMUtil.newDocument(true, false); NodeImpl instanceRoot = (NodeImpl) instance.getInstanceDocument().getDocumentElement(); NodeImpl instanceNode = (NodeImpl) instance.getPointer(path).getNode(); if (instanceNode.getNodeType() == Node.DOCUMENT_NODE) { if (isEnabled(instanceRoot)) { // process document tree addElement(relevantDocument, instanceRoot); } } if (instanceNode.getNodeType() == Node.ELEMENT_NODE) { if (isEnabled(instanceNode)) { // process element subtree addElement(relevantDocument, instanceNode); // apply namespaces NamespaceResolver.applyNamespaces((Element) instanceNode, relevantDocument.getDocumentElement()); } } return relevantDocument; }
From source file:org.codelibs.robot.transformer.impl.XmlTransformer.java
protected NodeList getNodeList(final Document doc, final String xpath) throws TransformerException { final DefaultPrefixResolver prefixResolver = new DefaultPrefixResolver( doc.getNodeType() == Node.DOCUMENT_NODE ? doc.getDocumentElement() : doc); return getXPathAPI().eval(doc, xpath, prefixResolver).nodelist(); }
From source file:org.docx4j.XmlUtils.java
/** * Copy a node from one DOM document to another. Used * to avoid relying on an underlying implementation which might * not support importNode /*from w w w . j a v a2 s . co m*/ * (eg Xalan's org.apache.xml.dtm.ref.DTMNodeProxy). * * WARNING: doesn't fully support namespaces! * * @param sourceNode * @param destParent */ public static void treeCopy(Node sourceNode, Node destParent) { // http://osdir.com/ml/text.xml.xerces-j.devel/2004-04/msg00066.html // suggests the problem has been fixed? // source node maybe org.apache.xml.dtm.ref.DTMNodeProxy // (if its xslt output we are copying) // or com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl // (if its marshalled JAXB) log.debug("node type" + sourceNode.getNodeType()); switch (sourceNode.getNodeType()) { case Node.DOCUMENT_NODE: // type 9 case Node.DOCUMENT_FRAGMENT_NODE: // type 11 // log.debug("DOCUMENT:" + w3CDomNodeToString(sourceNode) ); // if (sourceNode.getChildNodes().getLength()==0) { // log.debug("..no children!"); // } // recurse on each child NodeList nodes = sourceNode.getChildNodes(); if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { log.debug("child " + i + "of DOCUMENT_NODE"); //treeCopy((DTMNodeProxy)nodes.item(i), destParent); treeCopy((Node) nodes.item(i), destParent); } } break; case Node.ELEMENT_NODE: // Copy of the node itself log.debug("copying: " + sourceNode.getNodeName()); Node newChild; if (destParent instanceof Document) { newChild = ((Document) destParent).createElementNS(sourceNode.getNamespaceURI(), sourceNode.getLocalName()); } else if (sourceNode.getNamespaceURI() != null) { newChild = destParent.getOwnerDocument().createElementNS(sourceNode.getNamespaceURI(), sourceNode.getLocalName()); } else { newChild = destParent.getOwnerDocument().createElement(sourceNode.getNodeName()); } destParent.appendChild(newChild); // .. its attributes NamedNodeMap atts = sourceNode.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { Attr attr = (Attr) atts.item(i); // log.debug("attr.getNodeName(): " + attr.getNodeName()); // log.debug("attr.getNamespaceURI(): " + attr.getNamespaceURI()); // log.debug("attr.getLocalName(): " + attr.getLocalName()); // log.debug("attr.getPrefix(): " + attr.getPrefix()); if (attr.getNodeName().startsWith("xmlns:")) { /* A document created from a dom4j document using dom4j 1.6.1's io.domWriter does this ?! attr.getNodeName(): xmlns:w attr.getNamespaceURI(): null attr.getLocalName(): null attr.getPrefix(): null unless i'm doing something wrong, this is another reason to remove use of dom4j from docx4j */ ; // this is a namespace declaration. not our problem } else if (attr.getNamespaceURI() == null) { //log.debug("attr.getLocalName(): " + attr.getLocalName() + "=" + attr.getValue()); ((org.w3c.dom.Element) newChild).setAttribute(attr.getName(), attr.getValue()); } else if (attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")) { ; // this is a namespace declaration. not our problem } else if (attr.getNodeName() != null) { // && attr.getNodeName().equals("xml:space")) { // restrict this fix to xml:space only, if necessary // Necessary when invoked from BindingTraverserXSLT, // com.sun.org.apache.xerces.internal.dom.AttrNSImpl // otherwise it was becoming w:space="preserve"! /* eg xml:space * attr.getNodeName(): xml:space attr.getNamespaceURI(): http://www.w3.org/XML/1998/namespace attr.getLocalName(): space attr.getPrefix(): xml */ ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(), attr.getValue()); } else { ((org.w3c.dom.Element) newChild).setAttributeNS(attr.getNamespaceURI(), attr.getLocalName(), attr.getValue()); } } // recurse on each child NodeList children = sourceNode.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { //treeCopy( (DTMNodeProxy)children.item(i), newChild); treeCopy((Node) children.item(i), newChild); } } break; case Node.TEXT_NODE: // Where destParent is com.sun.org.apache.xerces.internal.dom.DocumentImpl, // destParent.getOwnerDocument() returns null. // #document ; com.sun.org.apache.xerces.internal.dom.DocumentImpl // System.out.println(sourceNode.getNodeValue()); //System.out.println(destParent.getNodeName() + " ; " + destParent.getClass().getName() ); if (destParent.getOwnerDocument() == null && destParent.getNodeName().equals("#document")) { Node textNode = ((Document) destParent).createTextNode(sourceNode.getNodeValue()); destParent.appendChild(textNode); } else { Node textNode = destParent.getOwnerDocument().createTextNode(sourceNode.getNodeValue()); // Warning: If you attempt to write a single "&" character, it will be converted to & // even if it doesn't look like that with getNodeValue() or getTextContent()! // So avoid any tricks with entities! See notes in docx2xhtmlNG2.xslt Node appended = destParent.appendChild(textNode); } 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; } }
From source file:org.dspace.content.authority.DSpaceControlledVocabulary.java
private String buildString(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { return (""); } else {//from ww w .j av a 2 s . c o m String parentValue = buildString(node.getParentNode()); Node currentLabel = node.getAttributes().getNamedItem("label"); if (currentLabel != null) { String currentValue = currentLabel.getNodeValue(); if (parentValue.equals("")) { return currentValue; } else { return (parentValue + this.hierarchyDelimiter + currentValue); } } else { return (parentValue); } } }
From source file:org.eclipse.smila.connectivity.framework.crawler.web.parse.html.DOMBuilder.java
/** * Tell if the current node is outside the document element. * // www. j a v a2 s. c o m * @return true if the current node is outside the document element. */ private boolean isOutsideDocElem() { return (null == m_docFrag) && m_elemStack.size() == 0 && (null == m_currentNode || m_currentNode.getNodeType() == Node.DOCUMENT_NODE); }