aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/taskdefs/optional/junit/DOMUtil.java
blob: 325f44cfb523063682b5171fd491523d233dfd70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package org.apache.tools.ant.taskdefs.optional.junit;

import java.util.Vector;

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;

/**
 * Some utilities that might be useful when manipulating DOM trees.
 *
 */
public final class DOMUtil {

    /** unused constructor */
    private DOMUtil() {
    }

    /**
     * Filter interface to be applied when iterating over a DOM tree.
     * Just think of it like a <tt>FileFilter</tt> clone.
     */
    public interface NodeFilter {
        /**
         * @param       node    the node to check for acceptance.
         * @return      <tt>true</tt> if the node is accepted by this filter,
         *                      otherwise <tt>false</tt>
         */
        boolean accept(Node node);
    }

    /**
     * list a set of node that match a specific filter. The list can be made
     * recursively or not.
     * @param   parent  the parent node to search from
     * @param   filter  the filter that children should match.
     * @param   recurse <tt>true</tt> if you want the list to be made recursively
     *                  otherwise <tt>false</tt>.
     * @return the node list that matches the filter.
     */
    public static NodeList listChildNodes(Node parent, NodeFilter filter, boolean recurse) {
        NodeListImpl matches = new NodeListImpl();
        NodeList children = parent.getChildNodes();
        if (children != null) {
            final int len = children.getLength();
            for (int i = 0; i < len; i++) {
                Node child = children.item(i);
                if (filter.accept(child)) {
                    matches.addElement(child);
                }
                if (recurse) {
                    NodeList recmatches = listChildNodes(child, filter, recurse);
                    final int reclength = recmatches.getLength();
                    for (int j = 0; j < reclength; j++) {
                        matches.addElement(recmatches.item(i));
                    }
                }
            }
        }
        return matches;
    }

    /** custom implementation of a nodelist */
    public static class NodeListImpl extends Vector implements NodeList {
        private static final long serialVersionUID = 3175749150080946423L;

        /**
         * Get the number of nodes in the list.
         * @return the length of the list.
         */
        public int getLength() {
            return size();
        }
        /**
         * Get a particular node.
         * @param i the index of the node to get.
         * @return the node if the index is in bounds, null otherwise.
         */
        public Node item(int i) {
            try {
                return (Node) elementAt(i);
            } catch (ArrayIndexOutOfBoundsException e) {
                return null; // conforming to NodeList interface
            }
        }
    }

    /**
     * return the attribute value of an element.
     * @param node the node to get the attribute from.
     * @param name the name of the attribute we are looking for the value.
     * @return the value of the requested attribute or <tt>null</tt> if the
     *         attribute was not found or if <tt>node</tt> is not an <tt>Element</tt>.
     */
    public static String getNodeAttribute(Node node, String name) {
        if (node instanceof Element) {
            Element element = (Element) node;
            return element.getAttribute(name);
        }
        return null;
    }


    /**
     * Iterate over the children of a given node and return the first node
     * that has a specific name.
     * @param   parent  the node to search child from. Can be <tt>null</tt>.
     * @param   tagname the child name we are looking for. Cannot be <tt>null</tt>.
     * @return  the first child that matches the given name or <tt>null</tt> if
     *                  the parent is <tt>null</tt> or if a child does not match the
     *                  given name.
     */
    public static Element getChildByTagName (Node parent, String tagname) {
        if (parent == null) {
            return null;
        }
        NodeList childList = parent.getChildNodes();
        final int len = childList.getLength();
        for (int i = 0; i < len; i++) {
            Node child = childList.item(i);
            if (child != null && child.getNodeType() == Node.ELEMENT_NODE
                && child.getNodeName().equals(tagname)) {
                return (Element) child;
            }
        }
        return null;
    }

    /**
     * Simple tree walker that will clone recursively a node. This is to
     * avoid using parser-specific API such as Sun's <tt>changeNodeOwner</tt>
     * when we are dealing with DOM L1 implementations since <tt>cloneNode(boolean)</tt>
     * will not change the owner document.
     * <tt>changeNodeOwner</tt> is much faster and avoid the costly cloning process.
     * <tt>importNode</tt> is in the DOM L2 interface.
     * @param   parent  the node parent to which we should do the import to.
     * @param   child   the node to clone recursively. Its clone will be
     *              appended to <tt>parent</tt>.
     * @return  the cloned node that is appended to <tt>parent</tt>
     */
    public static Node importNode(Node parent, Node child) {
        Node copy = null;
        final Document doc = parent.getOwnerDocument();

        switch (child.getNodeType()) {
        case Node.CDATA_SECTION_NODE:
            copy = doc.createCDATASection(((CDATASection) child).getData());
            break;
        case Node.COMMENT_NODE:
            copy = doc.createComment(((Comment) child).getData());
            break;
        case Node.DOCUMENT_FRAGMENT_NODE:
            copy = doc.createDocumentFragment();
            break;
        case Node.ELEMENT_NODE:
            final Element elem = doc.createElement(((Element) child).getTagName());
            copy = elem;
            final NamedNodeMap attributes = child.getAttributes();
            if (attributes != null) {
                final int size = attributes.getLength();
                for (int i = 0; i < size; i++) {
                    final Attr attr = (Attr) attributes.item(i);
                    elem.setAttribute(attr.getName(), attr.getValue());
                }
            }
            break;
        case Node.ENTITY_REFERENCE_NODE:
            copy = doc.createEntityReference(child.getNodeName());
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
            final ProcessingInstruction pi = (ProcessingInstruction) child;
            copy = doc.createProcessingInstruction(pi.getTarget(), pi.getData());
            break;
        case Node.TEXT_NODE:
            copy = doc.createTextNode(((Text) child).getData());
            break;
        default:
            // this should never happen
            throw new IllegalStateException("Invalid node type: " + child.getNodeType());
        }

        // okay we have a copy of the child, now the child becomes the parent
        // and we are iterating recursively over its children.
        try {
            final NodeList children = child.getChildNodes();
            if (children != null) {
                final int size = children.getLength();
                for (int i = 0; i < size; i++) {
                    final Node newChild = children.item(i);
                    if (newChild != null) {
                        importNode(copy, newChild);
                    }
                }
            }
        } catch (DOMException ignored) {
            // Ignore
        }

        // bingo append it. (this should normally not be done here)
        parent.appendChild(copy);
        return copy;
    }
}