Java Code Examples for org.w3c.dom.Node#TEXT_NODE
The following examples show how to use
org.w3c.dom.Node#TEXT_NODE .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RangeImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** This function is called from DOM. * The text has already beeen inserted. * Fix-up any offsets. */ void receiveDeletedText(Node node, int offset, int count) { if (node == null) return; if (fDeleteNode == node) return; if (node == fStartContainer && fStartContainer.getNodeType() == Node.TEXT_NODE) { if (fStartOffset > offset+count) { fStartOffset = offset+(fStartOffset-(offset+count)); } else if (fStartOffset > offset) { fStartOffset = offset; } } if (node == fEndContainer && fEndContainer.getNodeType() == Node.TEXT_NODE) { if (fEndOffset > offset+count) { fEndOffset = offset+(fEndOffset-(offset+count)); } else if (fEndOffset > offset) { fEndOffset = offset; } } }
Example 2
Source File: XMLUtil.java From netbeans with Apache License 2.0 | 6 votes |
/** * Find all direct child elements of an element. * More useful than {@link Element#getElementsByTagNameNS} because it does * not recurse into recursive child elements. * Children which are all-whitespace text nodes or comments are ignored; others cause * an exception to be thrown. * @param parent a parent element in a DOM tree * @return a list of direct child elements (may be empty) * @throws IllegalArgumentException if there are non-element children besides whitespace */ static List<Element> findSubElements(Element parent) throws IllegalArgumentException { NodeList l = parent.getChildNodes(); List<Element> elements = new ArrayList<>(l.getLength()); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { elements.add((Element)n); } else if (n.getNodeType() == Node.TEXT_NODE) { String text = ((Text)n).getNodeValue(); if (text.trim().length() > 0) { throw new IllegalArgumentException("non-ws text encountered in " + parent + ": " + text); // NOI18N } } else if (n.getNodeType() == Node.COMMENT_NODE) { // OK, ignore } else { throw new IllegalArgumentException("unexpected non-element child of " + parent + ": " + n); // NOI18N } } return elements; }
Example 3
Source File: RangeImpl.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** Fix up this Range if another Range has split a Text Node * into 2 Nodes. */ void receiveSplitData(Node node, Node newNode, int offset) { if (node == null || newNode == null) return; if (fSplitNode == node) return; if (node == fStartContainer && fStartContainer.getNodeType() == Node.TEXT_NODE) { if (fStartOffset > offset) { fStartOffset = fStartOffset - offset; fStartContainer = newNode; } } if (node == fEndContainer && fEndContainer.getNodeType() == Node.TEXT_NODE) { if (fEndOffset > offset) { fEndOffset = fEndOffset-offset; fEndContainer = newNode; } } }
Example 4
Source File: DeferredDocumentImpl.java From JDKSourceCode1.8 with MIT License | 5 votes |
/** Creates a clone of the specified node. */ public int cloneNode(int nodeIndex, boolean deep) { // clone immediate node int nchunk = nodeIndex >> CHUNK_SHIFT; int nindex = nodeIndex & CHUNK_MASK; int nodeType = fNodeType[nchunk][nindex]; int cloneIndex = createNode((short)nodeType); int cchunk = cloneIndex >> CHUNK_SHIFT; int cindex = cloneIndex & CHUNK_MASK; setChunkValue(fNodeName, fNodeName[nchunk][nindex], cchunk, cindex); setChunkValue(fNodeValue, fNodeValue[nchunk][nindex], cchunk, cindex); setChunkValue(fNodeURI, fNodeURI[nchunk][nindex], cchunk, cindex); int extraIndex = fNodeExtra[nchunk][nindex]; if (extraIndex != -1) { if (nodeType != Node.ATTRIBUTE_NODE && nodeType != Node.TEXT_NODE) { extraIndex = cloneNode(extraIndex, false); } setChunkIndex(fNodeExtra, extraIndex, cchunk, cindex); } // clone and attach children if (deep) { int prevIndex = -1; int childIndex = getLastChild(nodeIndex, false); while (childIndex != -1) { int clonedChildIndex = cloneNode(childIndex, deep); insertBefore(cloneIndex, clonedChildIndex, prevIndex); prevIndex = clonedChildIndex; childIndex = getRealPrevSibling(childIndex, false); } } // return cloned node index return cloneIndex; }
Example 5
Source File: CajaTreeBuilder.java From caja with Apache License 2.0 | 5 votes |
@Override protected Node shallowClone(Node node) { Node clone = node.cloneNode(false); if (needsDebugData) { Nodes.setFilePositionFor(clone, Nodes.getFilePositionFor(node)); } switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: if (needsDebugData) { Nodes.setFilePositionForValue( (Attr) clone, Nodes.getFilePositionForValue((Attr) node)); } break; case Node.ELEMENT_NODE: Element el = (Element) node; Element cloneEl = (Element) clone; NamedNodeMap attrs = el.getAttributes(); for (int i = 0, n = attrs.getLength(); i < n; ++i) { Attr a = (Attr) attrs.item(i); Attr cloneA = cloneEl.getAttributeNodeNS( a.getNamespaceURI(), a.getLocalName()); if (needsDebugData) { Nodes.setFilePositionFor(cloneA, Nodes.getFilePositionFor(a)); Nodes.setFilePositionForValue( cloneA, Nodes.getFilePositionForValue(a)); } } break; case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: if (needsDebugData) { Text t = (Text) node; Nodes.setRawText(t, Nodes.getRawText(t)); } break; } return clone; }
Example 6
Source File: DOMUtils.java From pdfxtk with Apache License 2.0 | 5 votes |
/** Get the value of the first text child of an element. @param element Element whose text element we want @return String value or null. */ public static String getTextValue(Element element) { NodeList childs = element.getChildNodes(); for (int i = 0; i < childs.getLength(); i++) { Node node = childs.item(i); if (Node.TEXT_NODE == node.getNodeType()) { return node.getNodeValue(); } } return null; }
Example 7
Source File: DocumentImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * NON-DOM INTERNAL: Pre-mutation context check, in * preparation for later generating DOMAttrModified events. * Determines whether this node is within an Attr * @param node node to get enclosing attribute for * @return either a description of that Attr, or null if none such. */ protected void saveEnclosingAttr(NodeImpl node) { savedEnclosingAttr = null; // MUTATION PREPROCESSING AND PRE-EVENTS: // If we're within the scope of an Attr and DOMAttrModified // was requested, we need to preserve its previous value for // that event. LCount lc = LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED); if (lc.total > 0) { NodeImpl eventAncestor = node; while (true) { if (eventAncestor == null) return; int type = eventAncestor.getNodeType(); if (type == Node.ATTRIBUTE_NODE) { EnclosingAttr retval = new EnclosingAttr(); retval.node = (AttrImpl) eventAncestor; retval.oldvalue = retval.node.getNodeValue(); savedEnclosingAttr = retval; return; } else if (type == Node.ENTITY_REFERENCE_NODE) eventAncestor = eventAncestor.parentNode(); else if (type == Node.TEXT_NODE) eventAncestor = eventAncestor.parentNode(); else return; // Any other parent means we're not in an Attr } } }
Example 8
Source File: XPath2FilterContainer.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Returns the first Text node which contains information from the XPath 2 * Filter String. We must use this stupid hook to enable the here() function * to work. * * $todo$ I dunno whether this crashes: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath> * @return the first Text node which contains information from the XPath 2 Filter String */ public Node getXPathFilterTextNode() { NodeList children = this.constructionElement.getChildNodes(); int length = children.getLength(); for (int i = 0; i < length; i++) { if (children.item(i).getNodeType() == Node.TEXT_NODE) { return children.item(i); } } return null; }
Example 9
Source File: TextImpl.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public TextImpl(StringBuffer str, SchemaDOM sDOM, int row, int col) { fData = str.toString(); fSchemaDOM = sDOM; fRow = row; fCol = col; rawname = prefix = localpart = uri = null; nodeType = Node.TEXT_NODE; }
Example 10
Source File: XMLDocument.java From mts with GNU General Public License v3.0 | 5 votes |
/** * Recursively remove text nodes containing white spaces */ private void removeWhistespacesTextNodes(Node node) { if(null == node) { return; } NodeList list = node.getChildNodes(); for(int i=0; i<list.getLength(); i++) { Node child = list.item(i); if(Node.TEXT_NODE == child.getNodeType()) { Text text = (Text) child; // if(text.isElementContentWhitespace()) { node.removeChild(child); i--; } } else if(Node.ELEMENT_NODE == child.getNodeType()) { removeWhistespacesTextNodes(child); } } }
Example 11
Source File: RangeImpl.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
void checkIndex(Node refNode, int offset) throws DOMException { if (offset < 0) { throw new DOMException( DOMException.INDEX_SIZE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null)); } int type = refNode.getNodeType(); // If the node contains text, ensure that the // offset of the range is <= to the length of the text if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE || type == Node.COMMENT_NODE || type == Node.PROCESSING_INSTRUCTION_NODE) { if (offset > refNode.getNodeValue().length()) { throw new DOMException(DOMException.INDEX_SIZE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null)); } } else { // Since the node is not text, ensure that the offset // is valid with respect to the number of child nodes if (offset > refNode.getChildNodes().getLength()) { throw new DOMException(DOMException.INDEX_SIZE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null)); } } }
Example 12
Source File: XhtmlGenerator.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
private void writeNode(Writer out, Node node, XhtmlGeneratorAdornerState state, int level) throws Exception { if (node.getNodeType() == Node.ELEMENT_NODE) writeElement(out, (Element) node, state, level); else if (node.getNodeType() == Node.TEXT_NODE) writeText(out, (Text) node, level); else if (node.getNodeType() == Node.COMMENT_NODE) writeComment(out, (Comment) node, level); else if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) writeProcessingInstruction(out, (ProcessingInstruction) node); else if (node.getNodeType() != Node.ATTRIBUTE_NODE) throw new FHIRException("Unhandled node type"); }
Example 13
Source File: FuncHere.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
/** * The here function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node * that directly bears the XPath expression. This expression results * in an error if the containing XPath expression does not appear in the * same XML document against which the XPath expression is being evaluated. * * @param xctxt * @return the xobject * @throws javax.xml.transform.TransformerException */ @Override public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); if (xpathOwnerNode == null) { return null; } int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); int currentNode = xctxt.getCurrentNode(); DTM dtm = xctxt.getDTM(currentNode); int docContext = dtm.getDocument(); if (DTM.NULL == docContext) { error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); } { // check whether currentNode and the node containing the XPath expression // are in the same document Document currentDoc = XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); if (currentDoc != xpathOwnerDoc) { throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); } } XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); NodeSetDTM nodeSet = nodes.mutableNodeset(); { int hereNode = DTM.NULL; switch (dtm.getNodeType(xpathOwnerNodeDTM)) { case Node.ATTRIBUTE_NODE : case Node.PROCESSING_INSTRUCTION_NODE : { // returns a node-set containing the attribute / processing instruction node hereNode = xpathOwnerNodeDTM; nodeSet.addNode(hereNode); break; } case Node.TEXT_NODE : { // returns a node-set containing the parent element of the // text node that directly bears the XPath expression hereNode = dtm.getParent(xpathOwnerNodeDTM); nodeSet.addNode(hereNode); break; } default : break; } } /** $todo$ Do I have to do this detach() call? */ nodeSet.detach(); return nodes; }
Example 14
Source File: FuncHere.java From hottub with GNU General Public License v2.0 | 4 votes |
/** * The here function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node * that directly bears the XPath expression. This expression results * in an error if the containing XPath expression does not appear in the * same XML document against which the XPath expression is being evaluated. * * @param xctxt * @return the xobject * @throws javax.xml.transform.TransformerException */ @Override public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); if (xpathOwnerNode == null) { return null; } int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); int currentNode = xctxt.getCurrentNode(); DTM dtm = xctxt.getDTM(currentNode); int docContext = dtm.getDocument(); if (DTM.NULL == docContext) { error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); } { // check whether currentNode and the node containing the XPath expression // are in the same document Document currentDoc = XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); if (currentDoc != xpathOwnerDoc) { throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); } } XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); NodeSetDTM nodeSet = nodes.mutableNodeset(); { int hereNode = DTM.NULL; switch (dtm.getNodeType(xpathOwnerNodeDTM)) { case Node.ATTRIBUTE_NODE : case Node.PROCESSING_INSTRUCTION_NODE : { // returns a node-set containing the attribute / processing instruction node hereNode = xpathOwnerNodeDTM; nodeSet.addNode(hereNode); break; } case Node.TEXT_NODE : { // returns a node-set containing the parent element of the // text node that directly bears the XPath expression hereNode = dtm.getParent(xpathOwnerNodeDTM); nodeSet.addNode(hereNode); break; } default : break; } } /** $todo$ Do I have to do this detach() call? */ nodeSet.detach(); return nodes; }
Example 15
Source File: DOMSubTreeData.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
/** * Recursively traverses the subtree, and returns an XPath-equivalent * node-set of all nodes traversed, excluding any comment nodes, * if specified. * * @param node the node to traverse * @param nodeSet the set of nodes traversed so far * @param the previous sibling node */ @SuppressWarnings("fallthrough") private void nodeSetMinusCommentNodes(Node node, List<Node> nodeSet, Node prevSibling) { switch (node.getNodeType()) { case Node.ELEMENT_NODE : NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { for (int i = 0, len = attrs.getLength(); i < len; i++) { nodeSet.add(attrs.item(i)); } } nodeSet.add(node); Node pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { nodeSetMinusCommentNodes(child, nodeSet, pSibling); pSibling = child; } break; case Node.DOCUMENT_NODE : pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { nodeSetMinusCommentNodes(child, nodeSet, pSibling); pSibling = child; } break; case Node.TEXT_NODE : case Node.CDATA_SECTION_NODE: // emulate XPath which only returns the first node in // contiguous text/cdata nodes if (prevSibling != null && (prevSibling.getNodeType() == Node.TEXT_NODE || prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { return; } nodeSet.add(node); break; case Node.PROCESSING_INSTRUCTION_NODE : nodeSet.add(node); break; case Node.COMMENT_NODE: if (withComments) { nodeSet.add(node); } } }
Example 16
Source File: FuncHere.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
/** * The here function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node * that directly bears the XPath expression. This expression results * in an error if the containing XPath expression does not appear in the * same XML document against which the XPath expression is being evaluated. * * @param xctxt * @return the xobject * @throws javax.xml.transform.TransformerException */ @Override public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); if (xpathOwnerNode == null) { return null; } int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); int currentNode = xctxt.getCurrentNode(); DTM dtm = xctxt.getDTM(currentNode); int docContext = dtm.getDocument(); if (DTM.NULL == docContext) { error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); } { // check whether currentNode and the node containing the XPath expression // are in the same document Document currentDoc = XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); if (currentDoc != xpathOwnerDoc) { throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); } } XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); NodeSetDTM nodeSet = nodes.mutableNodeset(); { int hereNode = DTM.NULL; switch (dtm.getNodeType(xpathOwnerNodeDTM)) { case Node.ATTRIBUTE_NODE : case Node.PROCESSING_INSTRUCTION_NODE : { // returns a node-set containing the attribute / processing instruction node hereNode = xpathOwnerNodeDTM; nodeSet.addNode(hereNode); break; } case Node.TEXT_NODE : { // returns a node-set containing the parent element of the // text node that directly bears the XPath expression hereNode = dtm.getParent(xpathOwnerNodeDTM); nodeSet.addNode(hereNode); break; } default : break; } } /** $todo$ Do I have to do this detach() call? */ nodeSet.detach(); return nodes; }
Example 17
Source File: XmlUtil.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Get a textual representation of a Node. * @param node The Node * @return the document in a text string */ public static String getDOMString(Node node) { //String domString = ""; StringBuilder domStringbuf = new StringBuilder(); int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { domStringbuf.append("<?xml version=\"1.0\" ?>\n"); domStringbuf.append(getDOMString(((Document)node).getDocumentElement())); break; } // print element with attributes case Node.ELEMENT_NODE: { domStringbuf.append("<"); domStringbuf.append(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); //domString += (" " + attr.getNodeName().trim() + // "=\"" + attr.getNodeValue().trim() + // "\""); domStringbuf.append((" " + attr.getNodeName().trim() + "=\"" + attr.getNodeValue().trim() + "\"")); } //domString = domStringbuf.toString(); domStringbuf.append(">"); NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) domStringbuf.append(getDOMString(children.item(i))); } domStringbuf.append("</"); domStringbuf.append(node.getNodeName()); domStringbuf.append(">\n"); break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { domStringbuf.append("&"); domStringbuf.append(node.getNodeName().trim()); domStringbuf.append(";"); break; } // print cdata sections case Node.CDATA_SECTION_NODE: { domStringbuf.append(""); break; } // print text case Node.TEXT_NODE: { String val = node.getNodeValue(); if (val==null) val = ""; domStringbuf.append(val);//rshastri .trim() removed SAK-1671 break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { domStringbuf.append(""); break; } } if (type == Node.ELEMENT_NODE) { domStringbuf.append("\n"); } String domString = domStringbuf.toString(); return domString; }
Example 18
Source File: PUCompletionManager.java From netbeans with Apache License 2.0 | 4 votes |
public int completeValues(CompletionContext context, List<JPACompletionItem> valueItems) { int anchorOffset = -1; DocumentContext docContext = context.getDocumentContext(); SyntaxElement curElem = docContext.getCurrentElement(); SyntaxElement prevElem = docContext.getCurrentElement().getPrevious(); TagElement propTag; String tagName; if (curElem.getType() == Node.ELEMENT_NODE && ((TagElement)curElem).isStart()) { tagName = curElem.getNode().getNodeName(); } else if (prevElem.getType() == Node.ELEMENT_NODE && ((TagElement)prevElem).isStart()) { tagName = prevElem.getNode().getNodeName(); } else { tagName = null; } PUCompletor completor = locateCompletor(tagName, null); if (completor != null) { valueItems.addAll(completor.doCompletion(context)); if (completor.getAnchorOffset() != -1) { anchorOffset = completor.getAnchorOffset(); } } else { // If current element is a start tag and its tag is <property> // or the current element is text and its prev is a start <property> tag, // then do the code completion if (curElem.getType() == Node.ELEMENT_NODE && ((TagElement)curElem).isStart() && PersistenceCfgXmlConstants.PROPERTY_TAG.equalsIgnoreCase(curElem.getNode().getNodeName())) { propTag = (TagElement)curElem; } else if (curElem.getType() == Node.TEXT_NODE && (prevElem.getType() == Node.ELEMENT_NODE && ((TagElement)prevElem).isStart()) && PersistenceCfgXmlConstants.PROPERTY_TAG.equalsIgnoreCase(prevElem.getNode().getNodeName())) { propTag = (TagElement)prevElem; } else { return anchorOffset; } String propName = JPAEditorUtil.getPersistencePropertyName(propTag.getNode()); int caretOffset = context.getCaretOffset(); String typedChars = context.getTypedPrefix(); Object possibleValue = PersistenceCfgProperties.getPossiblePropertyValue(null, propName); if (possibleValue instanceof String[]) { // Add the values in the String[] as completion items String[] values = (String[])possibleValue; for (int i = 0; i < values.length; i++) { if (values[i].startsWith(typedChars.trim()) || values[i].startsWith( "org.hibernate.dialect." + typedChars.trim()) ) { // NOI18N JPACompletionItem item = JPACompletionItem.createHbPropertyValueItem(caretOffset-typedChars.length(), values[i]); valueItems.add(item); } } try { anchorOffset = context.getDocumentContext(). runWithSequence((TokenSequence s) -> { if (!s.movePrevious()) { return -1; } return s.offset(); }); } catch (BadLocationException ex) { anchorOffset = -1; } } } return anchorOffset; }
Example 19
Source File: XrdsParserImpl.java From openid4java with Apache License 2.0 | 4 votes |
public List parseXrds(String input, Set targetTypes) throws DiscoveryException { if (DEBUG) _log.debug("Parsing XRDS input for service types: " + targetTypes.toString()); Document document = parseXmlInput(input); NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD); Node lastXRD; if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null) throw new DiscoveryException("No XRD elements found."); // get the canonical ID, if any (needed for XRIs) String canonicalId = null; Node canonicalIdNode; NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID); for (int i = 0; i < canonicalIDs.getLength(); i++) { canonicalIdNode = canonicalIDs.item(i); if (canonicalIdNode.getParentNode() != lastXRD) continue; if (canonicalId != null) throw new DiscoveryException("More than one Canonical ID found."); canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? canonicalIdNode.getFirstChild().getNodeValue() : null; } // extract the services that match the specified target types NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE); Map serviceTypes = new HashMap(); Set selectedServices = new HashSet(); Node typeNode, serviceNode; for (int i = 0; i < types.getLength(); i++) { typeNode = types.item(i); String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? typeNode.getFirstChild().getNodeValue() : null; if (type == null) continue; serviceNode = typeNode.getParentNode(); if (serviceNode.getParentNode() != lastXRD) continue; if (targetTypes.contains(type)) selectedServices.add(serviceNode); addServiceType(serviceTypes, serviceNode, type); } if (DEBUG) _log.debug("Found " + serviceTypes.size() + " services for the requested types."); // extract local IDs Map serviceLocalIDs = extractElementsByParent(XRD_NS, XRD_ELEM_LOCALID, selectedServices, document); Map serviceDelegates = extractElementsByParent(OPENID_NS, OPENID_ELEM_DELEGATE, selectedServices, document); // build XrdsServiceEndpoints for all URIs in the found services List result = new ArrayList(); NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI); Node uriNode; for (int i = 0; i < uris.getLength(); i++) { uriNode = uris.item(i); if (uriNode == null || !selectedServices.contains(uriNode.getParentNode())) continue; String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? uriNode.getFirstChild().getNodeValue() : null; serviceNode = uriNode.getParentNode(); Set typeSet = (Set) serviceTypes.get(serviceNode); String localId = (String) serviceLocalIDs.get(serviceNode); String delegate = (String) serviceDelegates.get(serviceNode); XrdsServiceEndpoint endpoint = new XrdsServiceEndpoint(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, delegate, canonicalId); if (DEBUG) _log.debug("Discovered endpoint: \n" + endpoint); result.add(endpoint); } Collections.sort(result); return result; }
Example 20
Source File: OutputFormat.java From jdk8u60 with GNU General Public License v2.0 | 4 votes |
/** * Determine the output method for the specified document. * If the document is an instance of {@link org.w3c.dom.html.HTMLDocument} * then the method is said to be <tt>html</tt>. If the root * element is 'html' and all text nodes preceding the root * element are all whitespace, then the method is said to be * <tt>html</tt>. Otherwise the method is <tt>xml</tt>. * * @param doc The document to check * @return The suitable method */ public static String whichMethod( Document doc ) { Node node; String value; int i; // If document is derived from HTMLDocument then the default // method is html. if ( doc instanceof HTMLDocument ) return Method.HTML; // Lookup the root element and the text nodes preceding it. // If root element is html and all text nodes contain whitespace // only, the method is html. // FIXME (SM) should we care about namespaces here? node = doc.getFirstChild(); while (node != null) { // If the root element is html, the method is html. if ( node.getNodeType() == Node.ELEMENT_NODE ) { if ( node.getNodeName().equalsIgnoreCase( "html" ) ) { return Method.HTML; } else if ( node.getNodeName().equalsIgnoreCase( "root" ) ) { return Method.FOP; } else { return Method.XML; } } else if ( node.getNodeType() == Node.TEXT_NODE ) { // If a text node preceding the root element contains // only whitespace, this might be html, otherwise it's // definitely xml. value = node.getNodeValue(); for ( i = 0 ; i < value.length() ; ++i ) if ( value.charAt( i ) != 0x20 && value.charAt( i ) != 0x0A && value.charAt( i ) != 0x09 && value.charAt( i ) != 0x0D ) return Method.XML; } node = node.getNextSibling(); } // Anything else, the method is xml. return Method.XML; }