/** * 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; }
private boolean dump(Node node, boolean silent, int depth) { boolean ok = true; if (!silent) { for (int i = 0; i < depth; i++) { System.out.print(" "); } System.out.println(node); } if (node.getNodeType() == Node.TEXT_NODE) { String text = ((Text) node).getData(); ok = ok && text.trim().length() > 0; } if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) { Node child = node.getFirstChild(); while (child != null) { ok = ok && dump(child, silent, depth + 1); child = child.getNextSibling(); } } return ok; }
/** * Base64 encodes and sets the bytes as the content of the SignatureValue * Node. * * @param bytes bytes to be used by SignatureValue before Base64 encoding */ private void setSignatureValueElement(byte[] bytes) { while (signatureValueElement.hasChildNodes()) { signatureValueElement.removeChild(signatureValueElement.getFirstChild()); } String base64codedValue = Base64.encode(bytes); if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) { base64codedValue = "\n" + base64codedValue + "\n"; } Text t = this.doc.createTextNode(base64codedValue); signatureValueElement.appendChild(t); }
/** * Method getStrFromNode * * @param xpathnode * @return the string for the node. */ public static String getStrFromNode(Node xpathnode) { if (xpathnode.getNodeType() == Node.TEXT_NODE) { // we iterate over all siblings of the context node because eventually, // the text is "polluted" with pi's or comments StringBuilder sb = new StringBuilder(); for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); currentSibling != null; currentSibling = currentSibling.getNextSibling()) { if (currentSibling.getNodeType() == Node.TEXT_NODE) { sb.append(((Text) currentSibling).getData()); } } return sb.toString(); } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { return ((Attr) xpathnode).getNodeValue(); } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { return ((ProcessingInstruction) xpathnode).getNodeValue(); } return null; }
@Test public void testSplitText() throws Exception { Document document = createDOMWithNS("Text01.xml"); NodeList nodeList = document.getElementsByTagName("p"); Node node = nodeList.item(0); Text textNode = document.createTextNode("This is a text node"); node.appendChild(textNode); int rawChildNum = node.getChildNodes().getLength(); textNode.splitText(0); int increased = node.getChildNodes().getLength() - rawChildNum; assertEquals(increased, 1); }
/** * Checks if an Text node is well-formed, by checking if it contains invalid * XML characters. * * @param data The contents of the comment node */ protected void isTextWellFormed(Text node) { // Does the data valid XML character data Character invalidChar = isWFXMLChar(node.getData()); if (invalidChar != null) { String msg = Utils.messages.createMessage( MsgKey.ER_WF_INVALID_CHARACTER_IN_TEXT, new Object[] { Integer.toHexString(Character.getNumericValue(invalidChar.charValue())) }); if (fErrorHandler != null) { fErrorHandler.handleError( new DOMErrorImpl( DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_WF_INVALID_CHARACTER, null, null, null)); } } }
/** * Find all direct child elements of an element. * 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 * * @since 8.4 */ public static List<Element> findSubElements(Element parent) throws IllegalArgumentException { NodeList l = parent.getChildNodes(); List<Element> elements = new ArrayList<Element>(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; }
/** * Obtains the text stored in the first child of a given node. * @param node the node that stores the text * @return the text string, <code>null</code> if no text was found */ private static String getFirstChildText(Node node) { if (node == null) { return null; } NodeList nodes = node.getChildNodes(); if (nodes == null || nodes.getLength() == 0) { return null; } Node child = nodes.item(0); if (child.getNodeType() == Node.TEXT_NODE) { return ((Text)child).getNodeValue(); } return null; }
/** * Method decode * * Takes the <CODE>Text</CODE> children of the Element and interprets * them as input for the <CODE>Base64.decode()</CODE> function. * * @param element * @return the byte obtained of the decoding the element * $todo$ not tested yet * @throws Base64DecodingException */ public static final byte[] decode(Element element) throws Base64DecodingException { Node sibling = element.getFirstChild(); StringBuilder sb = new StringBuilder(); while (sibling != null) { if (sibling.getNodeType() == Node.TEXT_NODE) { Text t = (Text) sibling; sb.append(t.getData()); } sibling = sibling.getNextSibling(); } return decode(sb.toString()); }
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; }
public String getTextContent() throws DocumentedException { NodeList childNodes = element.getChildNodes(); if (childNodes.getLength() == 0) { return DEFAULT_NAMESPACE_PREFIX; } for(int i = 0; i < childNodes.getLength(); i++) { Node textChild = childNodes.item(i); if (textChild instanceof Text) { String content = textChild.getTextContent(); return content.trim(); } } throw new DocumentedException(getName() + " should contain text.", DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.INVALID_VALUE, DocumentedException.ErrorSeverity.ERROR ); }
/** * Method engineGetContextFromElement * * @param element */ protected void engineGetContextFromElement(Element element) { super.engineGetContextFromElement(element); if (element == null) { throw new IllegalArgumentException("element null"); } Text hmaclength = XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); if (hmaclength != null) { this.HMACOutputLength = Integer.parseInt(hmaclength.getData()); this.HMACOutputLengthSet = true; } }
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { Element rootElement = document.getDocumentElement(); Element objectElement; Text objectText; objectElement = document.createElement("threads"); rootElement.appendChild(objectElement); objectText = document.createTextNode("" + com.twinsoft.convertigo.beans.core.RequestableObject.nbCurrentWorkerThreads); objectElement.appendChild(objectText); objectElement = document.createElement("contexts"); rootElement.appendChild(objectElement); try { objectText = document.createTextNode(Engine.isStarted ? "" + Engine.theApp.contextManager.getNumberOfContexts() : "0"); } catch (Exception e) { objectText = document.createTextNode("0"); } objectElement.appendChild(objectText); objectElement = document.createElement("requests"); rootElement.appendChild(objectElement); long i = EngineStatistics.getAverage(EngineStatistics.REQUEST); if (i == -1) i = 0; objectText = document.createTextNode("" + i); objectElement.appendChild(objectText); }
/** * Method engineAddContextToElement * * @param element */ public void engineAddContextToElement(Element element) { if (element == null) { throw new IllegalArgumentException("null element"); } if (this.HMACOutputLengthSet) { Document doc = element.getOwnerDocument(); Element HMElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); Text HMText = doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); HMElem.appendChild(HMText); XMLUtils.addReturnToElement(element); element.appendChild(HMElem); XMLUtils.addReturnToElement(element); } }
/** * Update the param-value node of the context-param entry. Don't add it if it already exists. * * @param doc * @param children * @param childNode */ @Override protected void updateParamValue(Document doc, Node contextParamElement) { NodeList valueChildren = contextParamElement.getChildNodes(); boolean foundEntry = false; for (int i = 0; i < valueChildren.getLength() && !foundEntry; i++) { Node valueChild = valueChildren.item(i); if (valueChild instanceof Text) { String value = valueChild.getNodeValue(); int index = value.indexOf(applicationContextPath); if (index >= 0) { System.out.println("Application context entry " + getApplicationContextPathWithClasspath() + " already in document."); foundEntry = true; } } } if (!foundEntry) { System.out.println("Adding " + getApplicationContextPathWithClasspath() + " to context"); contextParamElement.appendChild(doc.createTextNode(" " + getApplicationContextPathWithClasspath() + "\n")); } }
/** * Gets the value of the child element by tag name under the given parent * element. If there is more than one child element, return the value of the * first one. * * @param parent the parent element * @param tagName the tag name of the child element * @return value of the first child element, NULL if tag not exists */ public static String getElementValue(Element parent, String tagName) { Element element = getChildElement(parent, tagName); if (element != null) { NodeList nodes = element.getChildNodes(); if (nodes != null && nodes.getLength() > 0) { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node instanceof Text) { return ((Text) node).getData(); } } } } return null; }
/** * Receive notification of character data. * * <p>The Parser will call this method to report each chunk of * character data. SAX parsers may return all contiguous character * data in a single chunk, or they may split it into several * chunks; however, all of the characters in any single event * must come from the same external entity, so that the Locator * provides useful information.</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Note that some parsers will report whitespace using the * ignorableWhitespace() method rather than this one (validating * parsers must do so).</p> * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @see #ignorableWhitespace * @see org.xml.sax.Locator */ public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException { if(isOutsideDocElem() && com.sun.org.apache.xml.internal.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length)) return; // avoid DOM006 Hierarchy request error if (m_inCData) { cdata(ch, start, length); return; } String s = new String(ch, start, length); Node childNode; childNode = m_currentNode != null ? m_currentNode.getLastChild(): null; if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){ ((Text)childNode).appendData(s); } else{ Text text = m_doc.createTextNode(s); append(text); } }
public int next() throws XMLStreamException { while(true) { int r = _next(); switch (r) { case CHARACTERS: // if we are currently at text node, make sure that this is a meaningful text node. Node prev = _current.getPreviousSibling(); if(prev!=null && prev.getNodeType()==Node.TEXT_NODE) continue; // nope. this is just a continuation of previous text that should be invisible Text t = (Text)_current; wholeText = t.getWholeText(); if(wholeText.length()==0) continue; // nope. this is empty text. return CHARACTERS; case START_ELEMENT: splitAttributes(); return START_ELEMENT; default: return r; } } }
public static String getTextForNode(Node node) { StringBuilder sb = new StringBuilder(); NodeList children = node.getChildNodes(); if (children.getLength() == 0) return null; for (int i = 0; i < children.getLength(); ++i) { Node n = children.item(i); if (n instanceof Text) sb.append(n.getNodeValue()); else if (n instanceof EntityReference) { String s = getTextForNode(n); if (s == null) return null; else sb.append(s); } else return null; } return sb.toString(); }
/** * Appends the formatted text of the value as a text node to it's parent; */ public Node format(Object value, Node parent) { String txt = this.componentAdapter.formatObject(value); if (txt != null && !txt.isEmpty()) { Document document = parent.getOwnerDocument(); Text text = document.createTextNode(txt); parent.appendChild(text); return text; } else return null; }
/** * Optimized dispatch of characters. */ private final void dispatachChars(Node node) throws org.xml.sax.SAXException { if(m_contentHandler instanceof CharacterNodeHandler) { ((CharacterNodeHandler)m_contentHandler).characters(node); } else { String data = ((Text) node).getData(); this.m_contentHandler.characters(data.toCharArray(), 0, data.length()); } }
/** * Method setDigestValueElement * * @param digestValue */ private void setDigestValueElement(byte[] digestValue) { Node n = digestValueElement.getFirstChild(); while (n != null) { digestValueElement.removeChild(n); n = n.getNextSibling(); } String base64codedValue = Base64.encode(digestValue); Text t = this.doc.createTextNode(base64codedValue); digestValueElement.appendChild(t); }
/** * Equivalence class partitioning with state and input values orientation * for public void setParameter(String name, Object value) throws * DOMException, <br> * <b>pre-conditions</b>: the root element has one CDATASection followed by * one Text node, <br> * <b>name</b>: cdata-sections <br> * <b>value</b>: true. <br> * <b>Expected results</b>: the CDATASection is left intact */ @Test public void testCdataSections001() { DOMImplementation domImpl = null; try { domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation(); } catch (ParserConfigurationException pce) { Assert.fail(pce.toString()); } catch (FactoryConfigurationError fce) { Assert.fail(fce.toString()); } Document doc = domImpl.createDocument("namespaceURI", "ns:root", null); String cdataText = "CDATA CDATA CDATA"; String textText = "text text text"; CDATASection cdata = doc.createCDATASection(cdataText); Text text = doc.createTextNode(textText); DOMConfiguration config = doc.getDomConfig(); config.setParameter("cdata-sections", Boolean.TRUE); Element root = doc.getDocumentElement(); root.appendChild(cdata); root.appendChild(text); setHandler(doc); doc.normalizeDocument(); Node returned = root.getFirstChild(); if (returned.getNodeType() != Node.CDATA_SECTION_NODE) { Assert.fail("reurned: " + returned + ", expected: CDATASection"); } return; // Status.passed("OK"); }
/** * Extract nested text from a node. * Currently does not handle coalescing text nodes, CDATA sections, etc. * @param parent a parent element * @return the nested text, or null if none was found * * @since 8.4 */ public static String findText(Node parent) { NodeList l = parent.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { if (l.item(i).getNodeType() == Node.TEXT_NODE) { Text text = (Text) l.item(i); return text.getNodeValue(); } } return null; }
/** * Returns the combined text of previous nodes of the given element */ private static String getPreviousText(Node node) { StringBuilder builder = new StringBuilder(); while (node != null) { node = node.getPreviousSibling(); if (node instanceof Text) { Text textNode = (Text) node; builder.append(textNode.getWholeText()); } else { break; } } return builder.toString(); }
/** * Adds the given text to the given node */ public static Text addText(Element element, String text) { Document doc = element.getOwnerDocument(); Text textNode = doc.createTextNode(text + " "); element.appendChild(textNode); return textNode; }
private static boolean isWhiteSpace(Node node) { boolean rc = false; if (node != null && node.getNodeType() == Node.TEXT_NODE) { Text tn = (Text) node; if (tn.getData().trim().length() == 0) { rc = true; } } return rc; }
private void appendOrCreateTextData(String textData) { Node lastChild = _currentNode.getLastChild(); if (lastChild instanceof Text) { ((Text) lastChild).appendData(textData); } else { _currentNode.appendChild( _document.createTextNode(textData)); } }
/** * Get the text content of the element, i.e. the bit between the tags * * @return The text content of the node */ public String getContent() { String content = ""; NodeList list = dom.getChildNodes(); for (int i=0;i<list.getLength();i++) { if (list.item(i) instanceof Text) { content += (list.item(i).getNodeValue()); } } return content; }
@Override public void readFields(DataInput in) throws IOException { clear(); int size = WritableUtils.readVInt(in); for(int i=0; i < size; ++i) { String key = org.apache.hadoop.io.Text.readString(in); String value = org.apache.hadoop.io.Text.readString(in); set(key, value); String sources[] = WritableUtils.readCompressedStringArray(in); if(sources != null) { updatingResource.put(key, sources); } } }
@Override public void write(DataOutput out) throws IOException { Properties props = getProps(); WritableUtils.writeVInt(out, props.size()); for(Map.Entry<Object, Object> item: props.entrySet()) { org.apache.hadoop.io.Text.writeString(out, (String) item.getKey()); org.apache.hadoop.io.Text.writeString(out, (String) item.getValue()); WritableUtils.writeCompressedStringArray(out, updatingResource.get(item.getKey())); } }
/** * @param sibling * @param nodeName * @param number * @return nodes with the constrain */ public static Text selectDsNodeText(Node sibling, String nodeName, int number) { Node n = selectDsNode(sibling,nodeName,number); if (n == null) { return null; } n = n.getFirstChild(); while (n != null && n.getNodeType() != Node.TEXT_NODE) { n = n.getNextSibling(); } return (Text)n; }
@Test public void singleNodeWhenSingleNodeFound() throws XPathExpressionException { givenResultNodeSetContains("string1"); Text result = (Text) this.fromNode.selectNode("aQuery").get(); assertThat(result.getData(), is("string1")); }
private void givenResultNodeSetContains(String... values) { when(this.nodeList.getLength()).thenReturn(values.length); for (int i = 0; i < values.length; ++i) { Text textNode = mock(Text.class); when(textNode.getData()).thenReturn(values[i]); when(this.nodeList.item(i)).thenReturn(textNode); } }