KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > QueryAPIExamples


1
2 import net.sf.saxon.Configuration;
3 import net.sf.saxon.Controller;
4 import net.sf.saxon.instruct.UserFunction;
5 import net.sf.saxon.om.*;
6 import net.sf.saxon.query.DynamicQueryContext;
7 import net.sf.saxon.query.QueryResult;
8 import net.sf.saxon.query.StaticQueryContext;
9 import net.sf.saxon.query.XQueryExpression;
10 import net.sf.saxon.trans.XPathException;
11 import net.sf.saxon.value.IntegerValue;
12 import net.sf.saxon.value.Value;
13 import net.sf.saxon.xpath.XPathEvaluator;
14
15 import javax.xml.transform.*;
16 import javax.xml.transform.dom.DOMResult JavaDoc;
17 import javax.xml.transform.dom.DOMSource JavaDoc;
18 import javax.xml.transform.stream.StreamResult JavaDoc;
19 import javax.xml.transform.stream.StreamSource JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.FileReader JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.math.BigDecimal JavaDoc;
24 import java.util.Properties JavaDoc;
25
26
27 /**
28  * Some examples to show how the Saxon XQuery API should be used
29  */

30 public class QueryAPIExamples {
31
32     /**
33      * Class is not instantiated, so give it a private constructor
34      */

35     private QueryAPIExamples() {
36     }
37
38     /**
39      * Method main
40      */

41     public static void main(String JavaDoc argv[]) {
42
43         String JavaDoc test = "all";
44         if (argv.length > 0) {
45             test = argv[0];
46         }
47
48         if (test.equals("all") || test.equals("toStreamResult")) {
49             System.out.println("\n\n==== toStreamResult ====");
50
51             try {
52                 exampleToStreamResult();
53             } catch (XPathException ex) {
54                 handleException(ex);
55             }
56         }
57
58         if (test.equals("all") || test.equals("toSingleton")) {
59             System.out.println("\n\n==== toSingleton ====");
60
61             try {
62                 exampleToSingleton();
63             } catch (XPathException ex) {
64                 handleException(ex);
65             }
66         }
67
68         if (test.equals("all") || test.equals("toDOM")) {
69             System.out.println("\n\n==== toDOM ====");
70
71             try {
72                 exampleToDOM();
73             } catch (Exception JavaDoc ex) {
74                 handleException(ex);
75             }
76         }
77
78         if (test.equals("all") || test.equals("toSequence")) {
79             System.out.println("\n\n==== toSequence ====");
80
81             try {
82                 exampleToSequence();
83             } catch (XPathException ex) {
84                 handleException(ex);
85             }
86         }
87
88         if (test.equals("all") || test.equals("toSerializedSequence")) {
89             System.out.println("\n\n==== toSerializedSequence ====");
90
91             try {
92                 exampleToSerializedSequence();
93             } catch (XPathException ex) {
94                 handleException(ex);
95             }
96         }
97
98         if (test.equals("all") || test.equals("toWrappedSequence")) {
99             System.out.println("\n\n==== toWrappedSequence ====");
100
101             try {
102                 exampleToWrappedSequence();
103             } catch (XPathException ex) {
104                 handleException(ex);
105             }
106         }
107
108         if (test.equals("all") || test.equals("toHTMLFile")) {
109             System.out.println("\n\n==== toHTMLFile ====");
110
111             try {
112                 exampleToHTMLFile();
113             } catch (XPathException ex) {
114                 handleException(ex);
115             } catch (IOException JavaDoc ex) {
116                 System.err.println("Problem reading/writing files. Check that the current directory is the 'samples' directory");
117                 handleException(ex);
118             }
119         }
120
121         if (test.equals("all") || test.equals("withParam")) {
122             System.out.println("\n\n==== withParam ====");
123
124             try {
125                 exampleWithParam();
126             } catch (XPathException ex) {
127                 handleException(ex);
128             }
129         }
130
131         if (test.equals("all") || test.equals("pipeline")) {
132             System.out.println("\n\n==== pipeline ====");
133
134             try {
135                 examplePipeline();
136             } catch (XPathException ex) {
137                 handleException(ex);
138             }
139         }
140
141         if (test.equals("all") || test.equals("directFunction")) {
142             System.out.println("\n\n==== directFunction ====");
143
144             try {
145                 exampleDirectFunction();
146             } catch (XPathException ex) {
147                 handleException(ex);
148             }
149         }
150
151
152     }
153
154     /**
155      * Show a query producing a document as its result and serializing this
156      * directly to System.out
157      */

158
159     public static void exampleToStreamResult() throws XPathException {
160         final Configuration config = new Configuration();
161         final StaticQueryContext sqc = new StaticQueryContext(config);
162         final XQueryExpression exp = sqc.compileQuery("<a b='c'>{5+2}</a>");
163
164         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
165         final Properties JavaDoc props = new Properties JavaDoc();
166         props.setProperty(OutputKeys.METHOD, "xml");
167         props.setProperty(OutputKeys.INDENT, "yes");
168         exp.run(dynamicContext, new StreamResult JavaDoc(System.out), props);
169     }
170
171     /**
172      * Show a query producing a single atomic value as its result and returning the value
173      * to the Java application
174      */

175
176     public static void exampleToSingleton() throws XPathException {
177         final Configuration config = new Configuration();
178         final StaticQueryContext sqc = new StaticQueryContext(config);
179         final XQueryExpression exp = sqc.compileQuery("avg(for $i in 1 to 10 return $i*$i)");
180
181         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
182         final BigDecimal JavaDoc result = (BigDecimal JavaDoc)exp.evaluateSingle(dynamicContext);
183         System.out.println(result);
184
185     }
186
187     /**
188      * Show a query producing a DOM as its output. The DOM is then serialized using
189      * an identity transform
190      */

191
192     public static void exampleToDOM() throws TransformerException, TransformerConfigurationException {
193         final Configuration config = new Configuration();
194         final StaticQueryContext sqc = new StaticQueryContext(config);
195         final XQueryExpression exp = sqc.compileQuery("<a xmlns='http://a/uri' xmlns:a='another.uri'>text</a>");
196
197         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
198         DOMResult JavaDoc result = new DOMResult JavaDoc();
199         exp.run(dynamicContext, result, new Properties JavaDoc());
200
201         // now serialize the DOM
202

203         Transformer identity = TransformerFactory.newInstance().newTransformer();
204         identity.transform(new DOMSource JavaDoc(result.getNode()), new StreamResult JavaDoc(System.out));
205
206     }
207
208     /**
209      * Show a query producing a sequence as its result and returning the sequence
210      * to the Java application in the form of an iterator. For each item in the
211      * result, its string value is output.
212      */

213
214     public static void exampleToSequence() throws XPathException {
215         final Configuration config = new Configuration();
216         final StaticQueryContext sqc = new StaticQueryContext(config);
217         final XQueryExpression exp = sqc.compileQuery("for $i in 1 to 10 return ($i * $i)");
218
219         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
220         final SequenceIterator iter = exp.iterator(dynamicContext);
221         while (true) {
222             Item item = iter.next();
223             if (item == null) {
224                 break;
225             }
226             System.out.println(item.getStringValue());
227         }
228
229     }
230
231     /**
232      * Show a query producing a sequence as its result and returning the sequence
233      * to the Java application in the form of an iterator. The sequence is then
234      * output by serializing each item individually, with each item on a new line.
235      */

236
237     public static void exampleToSerializedSequence() throws XPathException {
238         final Configuration config = new Configuration();
239         final StaticQueryContext sqc = new StaticQueryContext(config);
240         final XQueryExpression exp = sqc.compileQuery("<doc><chap><a>3</a></chap></doc>//a, <b>4</b>, attribute c {5}, 19");
241         Properties JavaDoc props = new Properties JavaDoc();
242         props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
243
244         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
245         final SequenceIterator iter = exp.iterator(dynamicContext);
246         QueryResult.serializeSequence(iter, config, System.out, props);
247     }
248
249     /**
250      * Show a query producing a sequence as its result and returning the sequence
251      * to the Java application in the form of an iterator. The sequence is then
252      * output by wrapping the items in a document, with wrapping elements indicating
253      * the type of each item, and serializing the resulting document.
254      */

255
256     public static void exampleToWrappedSequence() throws XPathException {
257         final Configuration config = new Configuration();
258         final StaticQueryContext sqc = new StaticQueryContext(config);
259         final XQueryExpression exp = sqc.compileQuery("<doc><chap><a>3</a></chap></doc>//a, <b>4</b>, attribute c {5}, 19");
260         Properties JavaDoc props = new Properties JavaDoc();
261         props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
262         props.setProperty(OutputKeys.INDENT, "yes");
263
264         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
265         final SequenceIterator iter = exp.iterator(dynamicContext);
266         final DocumentInfo doc = QueryResult.wrap(iter, config);
267         QueryResult.serialize(doc, new StreamResult JavaDoc(System.out), props, config);
268     }
269
270
271     /**
272      * Show how to run a query that is read from a file and that serializes its output
273      * as HTML to another file. The input to the query (the initial value of the context
274      * node) is supplied as the content of another file.
275      */

276
277     public static void exampleToHTMLFile() throws XPathException, IOException JavaDoc {
278         final Configuration config = new Configuration();
279         final StaticQueryContext sqc = new StaticQueryContext(config);
280         final XQueryExpression exp = sqc.compileQuery(new FileReader JavaDoc("query/books-to-html.xq"));
281         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
282         dynamicContext.setContextNode(sqc.buildDocument(new StreamSource JavaDoc("data/books.xml")));
283         final Properties JavaDoc props = new Properties JavaDoc();
284         props.setProperty(OutputKeys.METHOD, "html");
285         props.setProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01 Transitional//EN");
286         exp.run(dynamicContext, new StreamResult JavaDoc(new File JavaDoc("booklist.html")), props);
287     }
288
289     /**
290      * Show a query that takes a parameter (external variable) as input.
291      * The query produces a single atomic value as its result and returns the value
292      * to the Java application. For the types of value that may be returned, and
293      * their mapping to XPath data types, see {@link XPathEvaluator#evaluate}
294      */

295
296     public static void exampleWithParam() throws XPathException {
297         final Configuration config = new Configuration();
298         final StaticQueryContext sqc = new StaticQueryContext(config);
299         final XQueryExpression exp = sqc.compileQuery("declare variable $in as xs:integer external;" +
300                 "$in * $in");
301
302         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
303         dynamicContext.setParameter("in", new Long JavaDoc(17));
304         final Long JavaDoc result = (Long JavaDoc)exp.evaluateSingle(dynamicContext);
305         System.out.println("17 * 17 = " + result);
306
307     }
308
309     /**
310      * Show how to run two queries in tandem. The second query is applied to the
311      * results of the first.
312      */

313
314     public static void examplePipeline() throws XPathException {
315         final Configuration config = new Configuration();
316
317         // Compile the first query
318
final StaticQueryContext sqc1 = new StaticQueryContext(config);
319         final XQueryExpression exp1 = sqc1.compileQuery("declare variable $in as xs:integer external;" +
320                 "document{ <a>{$in * $in}</a> }");
321
322         // Compile the second query (each query should have its own static context)
323
final StaticQueryContext sqc2 = new StaticQueryContext(config);
324         final XQueryExpression exp2 = sqc2.compileQuery("/a + 5");
325
326         // Run the first query
327
final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
328         dynamicContext.setParameter("in", new Long JavaDoc(3));
329         final NodeInfo doc = (NodeInfo)exp1.evaluateSingle(dynamicContext);
330
331         // Run the second query
332
dynamicContext.clearParameters();
333         dynamicContext.setContextNode(doc);
334         final Object JavaDoc result = exp2.evaluateSingle(dynamicContext);
335         System.out.println("3*3 + 5 = " + result);
336         // The result is actually a java.lang.Double
337
}
338
339     /**
340      * Show a direct call from the Java application to a function defined in the
341      * Query. This is a very efficient way of invoking a query, but it does minimal
342      * checking of the supplied arguments
343      */

344
345     public static void exampleDirectFunction() throws XPathException {
346         final StaticQueryContext sqc = new StaticQueryContext(new Configuration());
347         final XQueryExpression exp1 = sqc.compileQuery("declare namespace f='f.ns';" +
348                 "declare function f:t1($v1 as xs:integer, $v2 as xdt:untypedAtomic*) { " +
349                 " $v1 div $v2" +
350                 "};" +
351                 "10");
352
353         final UserFunction fn1 = exp1.getStaticContext().getUserDefinedFunction("f.ns", "t1", 2);
354         final Controller controller = exp1.getController();
355         final Value[] arglist = new Value[2];
356         arglist[0] = new IntegerValue(10);
357         for (int i = 3; i < 10; i++) {
358             arglist[1] = new IntegerValue(i);
359             final ValueRepresentation result = fn1.call(arglist, controller);
360             System.out.println(arglist[0] + " div " + arglist[1] + " = " + result);
361         }
362     }
363
364     /**
365      * Handle an exception thrown while running one of the examples
366      *
367      * @param ex the exception
368      */

369     private static void handleException(Exception JavaDoc ex) {
370         System.out.println("EXCEPTION: " + ex);
371         ex.printStackTrace();
372     }
373
374 }
375
376 //
377
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
378
// you may not use this file except in compliance with the License. You may obtain a copy of the
379
// License at http://www.mozilla.org/MPL/
380
//
381
// Software distributed under the License is distributed on an "AS IS" basis,
382
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
383
// See the License for the specific language governing rights and limitations under the License.
384
//
385
// The Original Code is: all this file.
386
//
387
// The Initial Developer of the Original Code is Michael H. Kay.
388
//
389
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
390
//
391
// Contributor(s): none.
392
//
393
Popular Tags