KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xmldb > xupdate > lexus > XUpdateQueryImpl


1 package org.xmldb.xupdate.lexus;
2
3 /*
4  * The XML:DB Initiative Software License, Version 1.0
5  *
6  *
7  * Copyright (c) 2000-2003 The XML:DB Initiative. All rights
8  * reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  * notice, this list of conditions and the following disclaimer.
16  *
17  * 2. Redistributions in binary form must reproduce the above copyright
18  * notice, this list of conditions and the following disclaimer in
19  * the documentation and/or other materials provided with the
20  * distribution.
21  *
22  * 3. The end-user documentation included with the redistribution,
23  * if any, must include the following acknowledgment:
24  * "This product includes software developed by the
25  * XML:DB Initiative (http://www.xmldb.org/)."
26  * Alternately, this acknowledgment may appear in the software itself,
27  * if and wherever such third-party acknowledgments normally appear.
28  *
29  * 4. The name "XML:DB Initiative" must not be used to endorse or
30  * promote products derived from this software without prior written
31  * permission. For written permission, please contact info@xmldb.org.
32  *
33  * 5. Products derived from this software may not be called "XML:DB",
34  * nor may "XML:DB" appear in their name, without prior written
35  * permission of the XML:DB Initiative.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals on behalf of the XML:DB Initiative. For more information
53  * on the XML:DB Initiative, please see <http://www.xmldb.org/>.
54  */

55
56 import org.w3c.dom.Node JavaDoc;
57 import org.w3c.dom.traversal.NodeFilter;
58 import org.xml.sax.InputSource JavaDoc;
59 import org.xml.sax.SAXException JavaDoc;
60 import org.xml.sax.helpers.ParserAdapter JavaDoc;
61 import org.xmldb.common.xml.queries.XUpdateQuery;
62 import org.xmldb.xupdate.lexus.commands.CommandConstants;
63 import org.xmldb.xupdate.lexus.commands.CommandObject;
64 import org.xmldb.xupdate.lexus.commands.DefaultCommand;
65
66 import javax.xml.parsers.DocumentBuilder JavaDoc;
67 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
68 import javax.xml.parsers.SAXParser JavaDoc;
69 import javax.xml.parsers.SAXParserFactory JavaDoc;
70 import java.io.BufferedReader JavaDoc;
71 import java.io.File JavaDoc;
72 import java.io.FileReader JavaDoc;
73 import java.io.StringReader JavaDoc;
74 import java.util.Enumeration JavaDoc;
75 import java.util.HashMap JavaDoc;
76 import java.util.Hashtable JavaDoc;
77 import java.util.Vector JavaDoc;
78
79 /**
80  * <b>Note:</b>
81  * If the DOM implementation you use does not support DOM-Level 2, some
82  * features will not work properly. XUpdate uses the method
83  * <code>getNamespaceURI</code> of the <code>org.w3c.dom.Node</code>
84  * interface. This method returns <code>null</code> if the current Node
85  * has no namespace. Your DOM implementation should implement this method
86  * and alway return null, then XUpdate should work better. Nevertheless
87  * you cannot use some features. Inserting elements and attributes just
88  * works, if you omit the optional attribute called namespace. For more
89  * detail about XUpdate look at the
90  * <a HREF="http://www.xmldb.org/xupdate/xupdate-wd.html">XUpdate Working Draft</a>.
91  * @version $Revision: 1.10 $ $Date: 2003/06/11 13:22:04 $
92  * @author <a HREF="http://www.smb-tec.com">SMB</a>
93  * @author <a HREF="mailto:tdean@gr.com">Timothy M. Dean</a>
94  */

95 public class XUpdateQueryImpl implements XUpdateQuery {
96   org.apache.log4j.Category log = org.apache.log4j.Category.getInstance(XUpdateQueryImpl.class);
97
98   /* The XUpdate namespace-uri. */
99   public static final String JavaDoc NAMESPACE_URI = "http://www.xmldb.org/xupdate";
100
101   /* Another representation of the query. It is faster than many String comparisons.*/
102   private Vector JavaDoc[] query = null;
103   /* Representation of commands and instructions as IDs. */
104   private CommandConstants commandConstants = null;
105   /* */
106   protected Node JavaDoc namespace = null;
107   /* */
108   protected HashMap JavaDoc namespaces = null;
109
110
111   /**
112    *
113    */

114   public XUpdateQueryImpl() {
115     commandConstants = new CommandConstants();
116   }
117
118
119   /**
120    *
121    */

122   public void setQString(String JavaDoc queryString) throws SAXException JavaDoc {
123     XUpdateQueryParser xuParser = new XUpdateQueryParser(commandConstants);
124
125     try {
126       SAXParser JavaDoc parser = SAXParserFactory.newInstance().newSAXParser();
127       ParserAdapter JavaDoc saxParser = new ParserAdapter JavaDoc(parser.getParser());
128       saxParser.setContentHandler(xuParser);
129       saxParser.parse(new InputSource JavaDoc(new StringReader JavaDoc(queryString)));
130     } catch (Exception JavaDoc e) {
131       throw new SAXException JavaDoc(e.getMessage());
132     }
133
134     namespaces = xuParser.getNamespaceMappings();
135     query = xuParser.getCachedQuery();
136     if (query[0].size() == 0) {
137       throw new SAXException JavaDoc("query contains no XUpdateOperation !");
138     }
139   }
140
141
142   /**
143    *
144    */

145   public void setNamespace(Node JavaDoc node) {
146     namespace = node;
147   }
148
149
150   /**
151    *
152    */

153   public void setNodeFilter(NodeFilter filter) {
154     filter = filter;
155   }
156
157
158   /**
159    *
160    */

161   public void execute(Node JavaDoc contextNode) throws Exception JavaDoc {
162     //log.error(".execute(): Starting XUpdate ...");
163
CommandObject currentCommand = new DefaultCommand(contextNode);
164     Enumeration JavaDoc commands = query[0].elements();
165     Enumeration JavaDoc attributes = query[1].elements();
166     Enumeration JavaDoc characters = query[2].elements();
167     while (commands.hasMoreElements()) {
168       //log.error(".execute(): Commands ...");
169
int id = ((Integer JavaDoc) commands.nextElement()).intValue();
170       if (id > 0) {
171         //log.error(".execute(): switch(id) ...");
172
switch (id) {
173           case CommandConstants.ATTRIBUTES:
174             currentCommand.submitAttributes((Hashtable JavaDoc) attributes.nextElement());
175             break;
176           case CommandConstants.CHARACTERS:
177             currentCommand.submitCharacters((String JavaDoc) characters.nextElement());
178             break;
179           default:
180             if (!currentCommand.submitInstruction(id)) {
181               commandConstants.setContextNode(contextNode);
182               currentCommand = commandConstants.commandForID(id);
183               if (currentCommand == null) {
184                 throw new Exception JavaDoc("operation can not have any XUpdate-instruction !");
185               }
186               currentCommand.reset();
187             }
188         }
189       } else {
190         //log.error(".execute(): else ...");
191
if (!currentCommand.executeInstruction()) {
192           contextNode = currentCommand.execute();
193           currentCommand = new DefaultCommand(contextNode);
194         }
195
196       }
197     }
198   //log.error(".execute(): Ending XUpdate ...");
199
}
200
201
202   /**
203    * Main-method. You can manually test your update operations.
204    */

205   public static void main(String JavaDoc args[]) throws Exception JavaDoc {
206     if (args.length == 0) {
207       System.err.println("usage: java org.xmldb.xupdate.lexus.XUpdateQueryImpl update document");
208       System.err.println(" update - filename of the file which contains XUpdate operations");
209       System.err.println(" document - filename of the file which contains the content to update");
210       System.exit(0);
211     }
212
213     // parse the update file
214
File JavaDoc file = new File JavaDoc(args[0]);
215     BufferedReader JavaDoc br = new BufferedReader JavaDoc(new FileReader JavaDoc(file));
216     char[] characters = new char[new Long JavaDoc(file.length()).intValue()];
217     br.read(characters, 0, new Long JavaDoc(file.length()).intValue());
218     String JavaDoc queryStr = new String JavaDoc(characters);
219
220     // parse the document file
221
Node JavaDoc myDocument = null;
222
223     DocumentBuilderFactory JavaDoc parserFactory = DocumentBuilderFactory.newInstance();
224
225     parserFactory.setValidating(false);
226     parserFactory.setNamespaceAware(true);
227     parserFactory.setIgnoringElementContentWhitespace(true);
228
229     DocumentBuilder JavaDoc builder = parserFactory.newDocumentBuilder();
230     myDocument = builder.parse(args[1]);
231
232     System.setProperty("org.xmldb.common.xml.queries.XPathQueryFactory",
233             "org.xmldb.common.xml.queries.xalan2.XPathQueryFactoryImpl");
234     // update the document and print time used for the updates
235
XUpdateQuery xq = new XUpdateQueryImpl();
236
237     System.err.println("Starting updates...");
238     long timeStart = System.currentTimeMillis();
239
240     xq.setQString(queryStr);
241     xq.execute(myDocument);
242
243     long timeEnd = System.currentTimeMillis();
244     System.err.println("Updates done in " + (timeEnd - timeStart) + " ms ...");
245
246
247
248
249     // <michi>
250
java.io.StringWriter JavaDoc writer = new java.io.StringWriter JavaDoc();
251     org.apache.xml.serialize.OutputFormat OutFormat = new org.apache.xml.serialize.OutputFormat("xml", "UTF-8", true);
252     org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer(writer, OutFormat);
253     serializer.asDOMSerializer().serialize((org.w3c.dom.Document JavaDoc) myDocument);
254     System.err.println("Result: \n"+writer.toString());
255     // </michi>
256
}
257
258 }
259
260
Popular Tags