KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > kawa > xml > Document


1 // Copyright (c) 2001, 2002, 2003, 2006 Per M.A. Bothner and Brainfood Inc.
2
// This is free software; for terms and warranty disclaimer see ./COPYING.
3

4 package gnu.kawa.xml;
5 import gnu.mapping.*;
6 import gnu.lists.*;
7 import gnu.xml.*;
8 import java.net.URL JavaDoc;
9 import gnu.text.*;
10
11 /** Implement the XQuery function 'document'. */
12
13 public class Document
14 {
15   public static final Document document = new Document();
16
17   public static void parse (Object JavaDoc name, Consumer out) throws Throwable JavaDoc
18   {
19     SourceMessages messages = new SourceMessages();
20     XMLParser parser = new XMLParser(name, messages, out);
21     if (out instanceof XConsumer)
22       ((XConsumer) out).beginEntity(name);
23     out.beginDocument();
24     if (out instanceof TreeList)
25       ((TreeList) out).writeDocumentUri(name);
26     parser.parse();
27     if (messages.seenErrors())
28       throw new SyntaxException("document function read invalid XML",
29                 messages);
30     out.endDocument();
31     if (out instanceof XConsumer)
32       ((XConsumer) out).endEntity();
33   }
34
35   public static KDocument parse (Object JavaDoc uri) throws Throwable JavaDoc
36   {
37     NodeTree doc = new NodeTree();
38     parse(uri, doc);
39     return new KDocument(doc, 0);
40   }
41
42   /** Internal namespace used to mange cached documents. */
43   static String JavaDoc docNamespace = "http://gnu.org/kawa/cached-documents";
44
45   public static Object JavaDoc parseCached (Object JavaDoc uri)
46     throws Throwable JavaDoc
47   {
48     Symbol sym = Symbol.make(docNamespace, uri.toString());
49     Environment env = Environment.getCurrent();
50     synchronized (sym)
51       {
52         NamedLocation loc = env.getLocation(sym, null, true);
53         Object JavaDoc val = loc.get(null);
54         if (val != null)
55           return val;
56
57         NodeTree tree = new NodeTree();
58         SourceMessages messages = new SourceMessages();
59         XMLParser parser = new XMLParser(uri, messages, tree);
60         tree.beginEntity(uri);
61         tree.beginDocument();
62         tree.writeDocumentUri(uri);
63         parser.parse();
64         parser.close();
65         if (messages.seenErrors())
66           throw new SyntaxException("document function read invalid XML",
67                                     messages);
68         tree.endDocument();
69         tree.endEntity();
70         val = new KDocument(tree, TreeList.BEGIN_ENTITY_SIZE << 1);
71         loc.set(val);
72         return val;
73       }
74   }
75 }
76
Popular Tags