KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > xml > XPointerFactory


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17
18 /* $Id: XPointerFactory.java 42598 2004-03-01 16:18:28Z gregor $ */
19
20 package org.apache.lenya.xml;
21
22 import java.io.FileNotFoundException JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.util.Properties JavaDoc;
25 import java.util.Vector JavaDoc;
26
27 import org.apache.lenya.xml.xpointer.XPointer;
28 import org.apache.log4j.Category;
29 import org.w3c.dom.Document JavaDoc;
30 import org.w3c.dom.Element JavaDoc;
31 import org.w3c.dom.Node JavaDoc;
32 import org.w3c.dom.NodeList JavaDoc;
33
34 public class XPointerFactory {
35     static Category log = Category.getInstance(XPointerFactory.class);
36     XPointer xpointer = null;
37
38     /**
39      * Creates a new XPointerFactory object.
40      */

41     public XPointerFactory() {
42         Properties JavaDoc properties = new Properties JavaDoc();
43         String JavaDoc propertiesFileName = "conf.properties";
44
45         try {
46             properties.load(XPointerFactory.class.getResourceAsStream(propertiesFileName));
47         } catch (Exception JavaDoc e) {
48             log.fatal(": Failed to load properties from resource: " + propertiesFileName);
49         }
50
51         String JavaDoc xpointerName = properties.getProperty("XPointer");
52
53         if (xpointerName == null) {
54             log.fatal(": No XPointer specified in " + propertiesFileName);
55         }
56
57         try {
58             Class JavaDoc xpointerClass = Class.forName(xpointerName);
59             xpointer = (XPointer) xpointerClass.newInstance();
60         } catch (Exception JavaDoc e) {
61             log.fatal(": " + e);
62         }
63     }
64
65     /**
66      * DOCUMENT ME!
67      *
68      * @param args DOCUMENT ME!
69      */

70     public static void main(String JavaDoc[] args) {
71         XPointerFactory xpf = new XPointerFactory();
72         DOMParserFactory dpf = new DOMParserFactory();
73
74         if (args.length != 2) {
75             System.err.println("Usage: java " + xpf.getClass().getName() +
76                 " example.xml \"/Example/People/Person[1]/Name\"");
77
78             return;
79         }
80
81         Document JavaDoc document = null;
82
83         try {
84             document = dpf.getDocument(args[0]);
85         } catch (FileNotFoundException JavaDoc e) {
86             System.err.println("No such file or directory: " + e.getMessage());
87         } catch (Exception JavaDoc e) {
88             System.err.println(e.getMessage());
89         }
90
91         String JavaDoc xpath = args[1];
92
93         try {
94             Vector JavaDoc nodes = xpf.select(document.getDocumentElement(), "xpointer(" + xpath + ")");
95             String JavaDoc[] values = xpf.getNodeValues(nodes);
96
97             for (int i = 0; i < nodes.size(); i++) {
98                 System.out.println(((Node JavaDoc) nodes.elementAt(i)).getNodeName() + ": " + values[i]);
99             }
100         } catch (Exception JavaDoc e) {
101             System.err.println(xpf.getClass().getName() + ".main(): " + e);
102         }
103
104         Document JavaDoc doc = xpf.employees();
105
106         try {
107             Vector JavaDoc nodes = xpf.select(doc.getDocumentElement(), "xpointer(/Employees/Employee[2])");
108             String JavaDoc[] values = xpf.getNodeValues(nodes);
109
110             for (int i = 0; i < nodes.size(); i++) {
111                 System.out.println(((Node JavaDoc) nodes.elementAt(i)).getNodeName() + ": " + values[i]);
112             }
113
114             Element JavaDoc leviElement = (Element JavaDoc) nodes.elementAt(0);
115             leviElement.appendChild(dpf.newTextNode(doc, " Brucker"));
116         } catch (Exception JavaDoc e) {
117             System.err.println(xpf.getClass().getName() + ".main(): " + e);
118         }
119
120         new DOMWriter(new PrintWriter JavaDoc(System.out)).print(doc);
121         System.out.println("");
122     }
123
124     /**
125      * Parse reference for xpointer and namespaces
126      *
127      * @param reference xmlns(...)xpointer(...)xpointer(...)
128      *
129      * @exception MalformedXPointerException xpointer(xpath)
130      */

131     public void parse(String JavaDoc reference, Vector JavaDoc xpaths, Vector JavaDoc namespaces) throws MalformedXPointerException {
132         tokenize(reference, xpaths, namespaces);
133     }
134
135     /**
136      * Select nodes by xpointer
137      *
138      * @param node Document Node
139      * @param reference xmls(...)xpointer(...)
140      *
141      * @return nodes
142      *
143      * @exception Exception ...
144      */

145     public Vector JavaDoc select(Node JavaDoc node, String JavaDoc reference) throws Exception JavaDoc {
146         Vector JavaDoc xpaths = new Vector JavaDoc();
147         Vector JavaDoc namespaces = new Vector JavaDoc();
148         parse(reference, xpaths, namespaces);
149
150         Vector JavaDoc nodes = new Vector JavaDoc();
151
152         for (int i = 0; i < xpaths.size(); i++) {
153             Vector JavaDoc n = xpointer.select(node, (String JavaDoc) xpaths.elementAt(i), namespaces);
154
155             for (int j = 0; j < n.size(); j++) {
156                 nodes.addElement(n.elementAt(j));
157             }
158         }
159
160         return nodes;
161     }
162
163     /**
164      * Select nodes by xpointer and return node at specific position
165      *
166      * @param node Document Node
167      * @param reference xmls(...)xpointer(...)
168      *
169      * @return node
170      *
171      * @exception Exception ...
172      */

173     public Node JavaDoc selectAt(Node JavaDoc node, String JavaDoc reference, int i) throws Exception JavaDoc {
174         return (Node JavaDoc)select(node, reference).elementAt(i);
175     }
176
177     /**
178      * DOCUMENT ME!
179      *
180      * @param xpointer DOCUMENT ME!
181      * @param xpaths DOCUMENT ME!
182      *
183      * @exception MalformedXPointerException xpointer(xpath)xpointer(xpath)
184      */

185     public void tokenize(String JavaDoc xpointer, Vector JavaDoc xpaths, Vector JavaDoc namespaces) throws MalformedXPointerException {
186         if ((xpointer.indexOf("xpointer(") == 0) && (xpointer.charAt(xpointer.length() - 1) == ')')) {
187
188             String JavaDoc substring = xpointer.substring(9, xpointer.length());
189             int i = substring.indexOf(")");
190
191             if (i >= 0) {
192                 log.debug("XPath: " + substring.substring(0, i));
193                 xpaths.addElement(substring.substring(0, i));
194                 tokenize(substring.substring(i + 1, substring.length()), xpaths, namespaces);
195             } else {
196                 xpaths.addElement(substring.substring(0, substring.length() - 1));
197                 return;
198             }
199     } else if ((xpointer.indexOf("xmlns(") == 0) && (xpointer.charAt(xpointer.length() - 1) == ')')) {
200             String JavaDoc substring = xpointer.substring(6, xpointer.length());
201             int i = substring.indexOf(")");
202
203             if (i >= 0) {
204                 log.debug("Namespace: " + substring.substring(0, i));
205                 namespaces.addElement(substring.substring(0, i));
206                 tokenize(substring.substring(i + 1, substring.length()), xpaths, namespaces);
207             } else {
208                 xpaths.addElement(substring.substring(0, substring.length() - 1));
209                 return;
210             }
211     } else if (xpointer.equals("")) {
212                 return;
213         } else {
214             throw new MalformedXPointerException(xpointer);
215         }
216     }
217
218     /**
219      * DOCUMENT ME!
220      *
221      * @param nodes DOCUMENT ME!
222      *
223      * @return DOCUMENT ME!
224      *
225      * @throws Exception DOCUMENT ME!
226      */

227     public String JavaDoc[] getNodeValues(Vector JavaDoc nodes) throws Exception JavaDoc {
228         String JavaDoc[] values = new String JavaDoc[nodes.size()];
229
230         for (int i = 0; i < values.length; i++) {
231             Node JavaDoc node = (Node JavaDoc) nodes.elementAt(i);
232             short type = node.getNodeType();
233
234             switch (type) {
235             case Node.ELEMENT_NODE: {
236                 values[i] = getElementValue((Element JavaDoc) node);
237
238                 break;
239             }
240
241             case Node.ATTRIBUTE_NODE: {
242                 values[i] = node.getNodeValue();
243
244                 break;
245             }
246
247             default:
248                 values[i] = "";
249                 throw new Exception JavaDoc("Neither ELEMENT nor ATTRIBUTE: " + type);
250             }
251         }
252
253         return values;
254     }
255
256     /**
257      * DOCUMENT ME!
258      *
259      * @param element DOCUMENT ME!
260      *
261      * @return DOCUMENT ME!
262      */

263     public String JavaDoc getElementValue(Element JavaDoc element) {
264         String JavaDoc value = "";
265         NodeList JavaDoc nl = element.getChildNodes();
266
267         for (int k = 0; k < nl.getLength(); k++) {
268             short nodeType = nl.item(k).getNodeType();
269
270             if (nodeType == Node.TEXT_NODE) {
271                 value = value + nl.item(k).getNodeValue();
272             } else if (nodeType == Node.ELEMENT_NODE) {
273                 value = value + getElementValue((Element JavaDoc) nl.item(k));
274             } else {
275                 System.err.println("EXCEPTION: " + this.getClass().getName() +
276                     ".getElementValue(): No TEXT_NODE");
277             }
278         }
279
280         return value;
281     }
282
283     /**
284      * DOCUMENT ME!
285      *
286      * @param element DOCUMENT ME!
287      * @param text DOCUMENT ME!
288      */

289     public void getElementValue(Element JavaDoc element, Vector JavaDoc text) {
290         NodeList JavaDoc nl = element.getChildNodes();
291
292         for (int k = 0; k < nl.getLength(); k++) {
293             short nodeType = nl.item(k).getNodeType();
294
295             if (nodeType == Node.TEXT_NODE) {
296                 text.addElement(nl.item(k).getNodeValue());
297             } else if (nodeType == Node.ELEMENT_NODE) {
298                 getElementValue((Element JavaDoc) nl.item(k), text);
299             } else {
300                 System.err.println("EXCEPTION: " + this.getClass().getName() +
301                     ".getElementValue(): No TEXT_NODE");
302             }
303         }
304     }
305
306     /**
307      * DOCUMENT ME!
308      *
309      * @return DOCUMENT ME!
310      */

311     public Document JavaDoc employees() {
312         DOMParserFactory dpf = new DOMParserFactory();
313         Document JavaDoc doc = dpf.getDocument();
314         Element JavaDoc michi = dpf.newElementNode(doc, "Employee");
315         michi.setAttribute("Id", "0");
316         michi.appendChild(dpf.newTextNode(doc, "Michi"));
317
318         Element JavaDoc levi = dpf.newElementNode(doc, "Employee");
319         levi.setAttribute("Id", "1");
320         levi.appendChild(dpf.newTextNode(doc, "Levi"));
321
322         Element JavaDoc employees = dpf.newElementNode(doc, "Employees");
323         employees.appendChild(dpf.newTextNode(doc, "\n"));
324         employees.appendChild(michi);
325         employees.appendChild(dpf.newTextNode(doc, "\n"));
326         employees.appendChild(levi);
327         employees.appendChild(dpf.newTextNode(doc, "\n"));
328         doc.appendChild(employees);
329
330         return doc;
331     }
332 }
333
Popular Tags