1 package org.xml.sax.demo;
2 // SAX demonstration for custom entity resolution.
3 // No warranty; no copyright -- use this as you will.
4 // $Id: EntityDemo.java,v 1.2 1998/05/01 20:52:16 david Exp $
6 import org.xml.sax.InputSource;
7 import org.xml.sax.Parser;
8 import org.xml.sax.SAXException;
10 import org.xml.sax.helpers.ParserFactory;
12 import java.io.StringReader;
17 * Demonstrate custom entity resolution.
19 * <p>Usage: java -Dorg.xml.sax.parser=<var>classname</var> EntityDemo
20 * <var>systemId</var></p>
22 * <p>If you create an XML document which references an
23 * external text entity with the public identifier
24 * "-//megginson//TEXT Sample Entity//EN", this application will
25 * substitute the string "Entity resolution works!" for the
26 * entity's contents:</p>
31 * PUBLIC "-//megginson//TEXT Sample Entity//EN" "ent.xml">
34 * <para>&ent;</para>
38 * <p>The SAX parser will open a connection to the URI itself.</p>
42 public class EntityDemo extends DemoHandler {
44 // This is the Reader that will be
45 // substituted for the entity contents.
47 new StringReader("Entity resolution works!");
52 public static void main (String args[])
58 // Check the command-line usage.
59 if (args.length != 1) {
60 System.err.println("Usage: java -Dorg.xml.sax.parser=<classname> " +
61 "EntityDemo <document>");
65 // Make the parser, using the value
66 // provided in the org.xml.sax.parser property.
67 parser = ParserFactory.makeParser();
69 // Create an event handler, and register
70 // it with the SAX parser.
71 handler = new EntityDemo();
72 parser.setEntityResolver(handler);
73 parser.setDTDHandler(handler);
74 parser.setDocumentHandler(handler);
75 parser.setErrorHandler(handler);
77 // Parse the document.
78 parser.parse(makeAbsoluteURL(args[0]));
83 * Override resolveEntity().
85 * <p>If the public identifier is "-//megginson//TEXT Sample
86 * //Entity//EN", instruct the parser to read the entity's
87 * contents from the StringReader rather than from the
88 * system identifier.</p>
90 * <p>The public identifier is safer than the system identifier,
91 * since the parser may have resolved the system identifier to
92 * an absolute URL.</p>
94 * @see org.xml.sax.EntityResolver#resolveEntity
97 public InputSource resolveEntity (String publicId, String systemId)
99 if (publicId != null &&
100 publicId.equals("-//megginson//TEXT Sample Entity//EN")) {
101 return new InputSource(reader);
109 * If a URL is relative, make it absolute against the current directory.
111 private static String makeAbsoluteURL (String url)
112 throws java.net.MalformedURLException
116 String currentDirectory = System.getProperty("user.dir");
117 String fileSep = System.getProperty("file.separator");
118 String file = currentDirectory.replace(fileSep.charAt(0), '/') + '/';
120 if (file.charAt(0) != '/') {
123 baseURL = new URL("file", null, file);
125 return new URL(baseURL, url).toString();