KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > PullExamples


1
2 import com.saxonica.validate.SchemaAwareConfiguration;
3 import net.sf.saxon.event.Sink;
4 import net.sf.saxon.Configuration;
5 import net.sf.saxon.TransformerFactoryImpl;
6 import net.sf.saxon.tree.TreeBuilder;
7 import net.sf.saxon.event.PipelineConfiguration;
8 import net.sf.saxon.event.Receiver;
9 import net.sf.saxon.event.ResultWrapper;
10 import net.sf.saxon.event.Sink;
11 import net.sf.saxon.om.NodeInfo;
12 import net.sf.saxon.om.Validation;
13 import net.sf.saxon.pull.*;
14 import net.sf.saxon.query.DynamicQueryContext;
15 import net.sf.saxon.query.StaticQueryContext;
16 import net.sf.saxon.query.XQueryExpression;
17 import net.sf.saxon.tinytree.TinyBuilder;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.value.Value;
20
21 import javax.xml.transform.*;
22 import javax.xml.transform.stream.StreamResult JavaDoc;
23 import javax.xml.transform.stream.StreamSource JavaDoc;
24 import java.io.*;
25 import java.util.Properties JavaDoc;
26
27 /**
28  * This class contains some examples of how to use the Pull interfaces
29  * in Saxon.
30  *
31  * These interfaces are currently experimental, and not fully integrated
32  * into the architecture of the product. They are expected to play a more
33  * significant role in future releases.
34  */

35
36 public class PullExamples {
37
38     private Configuration config;
39
40     /**
41      * Serialize a document that is supplied via the pull interface
42      */

43
44     public void serialize(PullProvider in, OutputStream out) throws XPathException, IOException {
45         Properties JavaDoc props = new Properties JavaDoc();
46         props.setProperty(OutputKeys.METHOD, "xml");
47         props.setProperty(OutputKeys.INDENT, "yes");
48         Receiver receiver = ResultWrapper.getReceiver(new StreamResult JavaDoc(out),
49                                                         in.getPipelineConfiguration(),
50                                                         props);
51         new PullPushCopier(in, receiver).copy();
52     }
53
54     /**
55      * Validate a document that is supplied via the pull interface
56      * (This requires the schema-aware version of Saxon)
57      */

58
59     public void validate(PullProvider in) throws XPathException, IOException {
60         SchemaAwareConfiguration config = new SchemaAwareConfiguration();
61         in.getPipelineConfiguration().setConfiguration(config);
62         Receiver sink = new Sink();
63         sink.setPipelineConfiguration(in.getPipelineConfiguration());
64         Receiver validator = config.getDocumentValidator(
65                 sink, in.getSourceLocator().getSystemId(), config.getNamePool(), Validation.STRICT, null);
66         validator.setPipelineConfiguration(in.getPipelineConfiguration());
67         //in = new PullTracer(in);
68
new PullPushCopier(in, validator).copy();
69     }
70
71     /**
72      * Transform a document supplied via the pull interface
73      */

74
75     public void transform(PullProvider in, File stylesheet, OutputStream out) throws TransformerException {
76         TransformerFactory factory = new TransformerFactoryImpl();
77         Templates templates = factory.newTemplates(new StreamSource JavaDoc(stylesheet));
78         Transformer transformer = templates.newTransformer();
79         transformer.transform(
80                 new PullSource(in),
81                 new StreamResult JavaDoc(out)
82         );
83     }
84
85     /**
86      * Run a query against input that is supplied using the pull interface
87      */

88
89     public void query(PullProvider in, String JavaDoc query, OutputStream out) throws XPathException {
90         final StaticQueryContext sqc = new StaticQueryContext(config);
91         final XQueryExpression exp = sqc.compileQuery(query);
92         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
93         dynamicContext.setContextNode(sqc.buildDocument(new PullSource(in)));
94         Properties JavaDoc props = new Properties JavaDoc();
95         props.setProperty(OutputKeys.INDENT, "yes");
96         exp.run(dynamicContext, new StreamResult JavaDoc(out), props);
97     }
98
99     /**
100      * Build a Saxon "tiny" tree from input supplied via the pull interface
101      */

102
103     public NodeInfo build(PullProvider in) throws XPathException {
104         TinyBuilder builder = new TinyBuilder();
105         builder.setPipelineConfiguration(in.getPipelineConfiguration());
106         new PullPushCopier(in, builder).copy();
107         return builder.getCurrentRoot();
108     }
109
110     /**
111      * Build a Saxon "standard" tree from input supplied via the pull interface
112      */

113
114     public NodeInfo buildStandardTree(PullProvider in) throws XPathException {
115         TreeBuilder builder = new TreeBuilder();
116         builder.setPipelineConfiguration(in.getPipelineConfiguration());
117         builder.open();
118         new PullPushCopier(in, builder).copy();
119         builder.close();
120         return builder.getCurrentRoot();
121     }
122
123     /**
124      * Get a PullProvider based on a StAX Parser for a given input file
125      */

126
127     public PullProvider getParser(File input) throws FileNotFoundException, XPathException {
128         StaxBridge parser = new StaxBridge();
129         parser.setInputStream(input.toURI().toString(), new FileInputStream(input));
130         parser.setPipelineConfiguration(config.makePipelineConfiguration());
131         return parser;
132     }
133
134     /**
135      * Get a PullProvider based on a document or element node in a Saxon tree
136      */

137
138     public PullProvider getTreeWalker(NodeInfo root) {
139         return TreeWalker.makeTreeWalker(root);
140     }
141
142     /**
143      * Run a query to produce a sequence of element nodes, and get a PullProvider over the results
144      * of the query
145      */

146
147     public PullProvider pullQueryResults(NodeInfo source, String JavaDoc query) throws XPathException {
148         final StaticQueryContext sqc = new StaticQueryContext(config);
149         final XQueryExpression exp = sqc.compileQuery(query);
150         final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
151         dynamicContext.setContextNode(source);
152         PullProvider pull = new PullFromIterator(exp.iterator(dynamicContext));
153         pull = new PullNamespaceReducer(pull);
154         pull.setPipelineConfiguration(config.makePipelineConfiguration());
155         return pull;
156     }
157
158     /**
159      * Create a copy of a document, filtered to remove all elements named "PRICE",
160      * together with their contents
161      */

162
163     public void removePriceElements(PullProvider in, OutputStream out) throws IOException, XPathException {
164         final int priceElement = config.getNamePool().allocate("", "", "PRICE");
165         PullFilter filter = new PullFilter(in) {
166             public int next() throws XPathException {
167                 currentEvent = super.next();
168                 if (currentEvent == START_ELEMENT && getFingerprint() == priceElement) {
169                     super.skipToMatchingEnd();
170                     currentEvent = next();
171                 }
172                 return currentEvent;
173             }
174         };
175         serialize(filter, out);
176     }
177
178     /**
179      * Get the average price of books, by scanning a document and taking the average of the
180      * values of the PRICE elements
181      */

182
183      public void displayAveragePrice(PullProvider in, OutputStream out) throws IOException, XPathException {
184         final int priceElement = config.getNamePool().allocate("", "", "PRICE");
185         double total = 0;
186         int count = 0;
187         while (true) {
188             int event = in.next();
189             if (event == PullProvider.END_OF_INPUT) {
190                 break;
191             }
192             if (event == PullProvider.START_ELEMENT && in.getFingerprint() == priceElement) {
193                 double value = Value.stringToNumber(in.getStringValue());
194                 total += value;
195                 count++;
196             }
197         }
198         double average = (count==0 ? Double.NaN : total/count);
199         String JavaDoc result = "<result>" + average + "</result>";
200         OutputStreamWriter writer = new OutputStreamWriter(out);
201         writer.write(result);
202         writer.flush();
203     }
204
205     /**
206      * Main program. Arguments:
207      * <ol>
208      * <li>Select examples. Each example is identified by a single letter. Use # to run all examples.
209      * <li>-s Source document</li>
210      * <li>-o Output file</li>
211      * <li>-xsl Stylesheet</li>
212      * <li>-q Query
213      * </ol>
214      */

215
216     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
217         String JavaDoc examples;
218         if (args.length < 1 || args[0].equals("#")) {
219             examples = "abcdefghijklmnopqrstuvwxyz";
220         } else {
221             examples = args[0];
222         }
223         File input = null;
224         OutputStream output = null;
225         String JavaDoc query = null;
226         File stylesheet = null;
227
228         for (int i=1; i<args.length; i++) {
229             if (args[i].equals("-s")) {
230                 input = new File(args[++i]);
231             } else if (args[i].equals("-o")) {
232                 output = new FileOutputStream(new File(args[++i]));
233             } else if (args[i].equals("-q")) {
234                 query = readFile(new File(args[++i]));
235             } else if (args[i].equals("-xsl")) {
236                 stylesheet = new File(args[++i]);
237             } else {
238                 System.err.println("Unknown argument " + args[i]);
239             }
240         }
241
242         if (input==null) {
243             input = new File("../data/books.xml");
244         }
245
246         if (output==null) {
247             output = System.out;
248         }
249
250         PullExamples o = new PullExamples();
251         Configuration config = new Configuration();
252         config.setLazyConstructionMode(true);
253         o.config = config;
254
255         PipelineConfiguration pipe = config.makePipelineConfiguration();
256         for (int i=0; i<examples.length(); i++) {
257             char ex = examples.charAt(i);
258             switch (ex) {
259                 case 'a': {
260                     System.out.println("\n\n=== Serialize the input to the output ===\n");
261
262                     PullProvider p = o.getParser(input);
263                     p.setPipelineConfiguration(pipe);
264                     o.serialize(p, output);
265                     break;
266                 }
267                 case 'b': {
268                     System.out.println("\n\n=== Validate the input ===\n");
269
270                     PullProvider p = o.getParser(input);
271                     p.setPipelineConfiguration(pipe);
272                     o.validate(p);
273                     break;
274                 }
275                 case 'c': {
276                     System.out.println("\n\n=== Transform the input to the output ===\n");
277
278                     if (stylesheet == null) {
279                         System.err.println("** No stylesheet supplied");
280                         break;
281                     }
282                     PullProvider p = o.getParser(input);
283                     p.setPipelineConfiguration(pipe);
284                     o.transform(p, stylesheet, output);
285                     break;
286                 }
287                 case 'd': {
288                     System.out.println("\n\n=== Run XQuery against the input ===\n");
289                     if (query == null) {
290                         query = "<result>{.}</result>";
291                     }
292                     PullProvider p = o.getParser(input);
293                     p.setPipelineConfiguration(pipe);
294                     o.query(p, query, output);
295                     break;
296                 }
297                 case 'e': {
298                     System.out.println("\n\n=== Remove PRICE elements from the input ===\n");
299
300                     PullProvider p = o.getParser(input);
301                     p.setPipelineConfiguration(pipe);
302                     o.removePriceElements(p, output);
303                     break;
304                 }
305                 case 'f': {
306                     System.out.println("\n\n=== Compute average of PRICE elements in the input ===\n");
307
308                     PullProvider p = o.getParser(input);
309                     p.setPipelineConfiguration(pipe);
310                     o.displayAveragePrice(p, output);
311                     break;
312                 }
313                 case 'g': {
314                     System.out.println("\n\n=== Obtain query results using a pull iterator ===\n");
315
316                     NodeInfo node = new StaticQueryContext(config)
317                             .buildDocument(new StreamSource JavaDoc(input));
318                     PullProvider p = o.pullQueryResults(node,
319
320                             "declare function local:f() {"+
321                               "for $var1 in (<abc/>, <def/>)"+
322                               "return <e xmlns:x='x1'><f xmlns:y='y1' xmlns:x='x2'>xyz</f></e>};"+
323                             "local:f()"
324
325                     );
326                     o.serialize(new PullTracer(p), output);
327                     break;
328                 }
329                 case 'h': {
330                     System.out.println("\n\n=== Obtain query results using a pull iterator on a 'standard' tree ===\n");
331
332                     PullProvider p1 = o.getParser(input);
333                     p1.setPipelineConfiguration(pipe);
334                     NodeInfo node = o.buildStandardTree(p1);
335                     PullProvider p2 = o.pullQueryResults(node,
336                            "//CATEGORIES"
337                     );
338                     o.serialize(p2, output);
339                 }
340             }
341         }
342     }
343
344     /**
345      * Read the contents of a file into a string
346      */

347
348     public static String JavaDoc readFile(File file) throws IOException {
349         Reader reader = new FileReader(file);
350         char[] buffer = new char[4096];
351         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(4096);
352         while (true) {
353             int n = reader.read(buffer);
354             if (n>0) {
355                 sb.append(buffer, 0, n);
356             } else {
357                 break;
358             }
359         }
360         return sb.toString();
361     }
362
363
364
365 }
366
367 //
368
// The contents of this file are subject to the Mozilla Public License Version 1.0 (the "License");
369
// you may not use this file except in compliance with the License. You may obtain a copy of the
370
// License at http://www.mozilla.org/MPL/
371
//
372
// Software distributed under the License is distributed on an "AS IS" basis,
373
// WITHOUT WARRANTY OF ANY KIND, either express or implied.
374
// See the License for the specific language governing rights and limitations under the License.
375
//
376
// The Original Code is: all this file.
377
//
378
// The Initial Developer of the Original Code is Michael H. Kay.
379
//
380
// Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved.
381
//
382
// Contributor(s): none.
383
//
384
Popular Tags