1 /***
2 *
3 * Copyright 2005 LogicBlaze, Inc. http://www.logicblaze.com
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 **/
18 package groovy.util;
19
20 import groovy.xml.QName;
21
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Iterator;
25
26 /***
27 * A List implementation which is returned by queries on a {@link Node} which provides some XPath like helper methods for GPath
28 *
29 * @version $Revision$
30 */
31 public class NodeList extends ArrayList {
32
33 public NodeList() {
34 }
35
36 public NodeList(Collection collection) {
37 super(collection);
38 }
39
40 public NodeList(int size) {
41 super(size);
42 }
43
44 /***
45 * Provides lookup of elements by non-namespaced name
46 */
47 public NodeList getAt(String name) {
48 NodeList answer = new NodeList();
49 for (Iterator iter = iterator(); iter.hasNext();) {
50 Object child = iter.next();
51 if (child instanceof Node) {
52 Node childNode = (Node) child;
53 Object temp = childNode.get(name);
54 if (temp instanceof Collection) {
55 answer.addAll((Collection) temp);
56 }
57 else {
58 answer.add(temp);
59 }
60 }
61 }
62 return answer;
63 }
64
65 /***
66 * Provides lookup of elements by QName
67 */
68 public NodeList getAt(QName name) {
69 NodeList answer = new NodeList();
70 for (Iterator iter = iterator(); iter.hasNext();) {
71 Object child = iter.next();
72 if (child instanceof Node) {
73 Node childNode = (Node) child;
74 NodeList temp = childNode.getAt(name);
75 answer.addAll(temp);
76 }
77 }
78 return answer;
79 }
80
81 /***
82 * Returns the text value of all of the elements in the collection
83 *
84 * @return the text value of all the elements in the collection or null
85 */
86 public String text() {
87 String previousText = null;
88 StringBuffer buffer = null;
89 for (Iterator iter = this.iterator(); iter.hasNext();) {
90 Object child = iter.next();
91 String text = null;
92 if (child instanceof String) {
93 text = (String) child;
94 }
95 else if (child instanceof Node) {
96 text = ((Node) child).text();
97 }
98 if (text != null) {
99 if (previousText == null) {
100 previousText = text;
101 }
102 else {
103 if (buffer == null) {
104 buffer = new StringBuffer();
105 buffer.append(previousText);
106 }
107 buffer.append(text);
108 }
109 }
110 }
111 if (buffer != null) {
112 return buffer.toString();
113 }
114 else {
115 if (previousText != null) {
116 return previousText;
117 }
118 }
119 return "";
120 }
121 }