1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.talika.tarsis.command.factory.xml;
24
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.Map;
28
29 import javax.xml.parsers.ParserConfigurationException;
30 import javax.xml.parsers.SAXParserFactory;
31
32 import org.talika.tarsis.context.Context;
33 import org.talika.tarsis.log.Logger;
34 import org.xml.sax.InputSource;
35 import org.xml.sax.SAXException;
36 import org.xml.sax.XMLReader;
37
38 /**
39 * Utility class that permits load command definitions of a package definition file.
40 *
41 * @author Jose M. Palomar
42 * @version $Revision: 269 $
43 */
44 public final class XmlCommandPackageLoader {
45
46
47 /**
48 * Tarsis context.
49 */
50 private Context context;
51
52 /**
53 * Tarsis logger.
54 */
55 private Logger logger;
56
57
58 /**
59 * Creatres a new <code>XmlCommandPackageLoader</code> for a given Tarsis
60 * context.
61 *
62 * @param context Context Tarsis context.
63 */
64 public XmlCommandPackageLoader(Context context) {
65 this.context = context;
66 this.logger = context.getLogger();
67 }
68
69
70 /**
71 * Loads command definitions of a package from a given file.
72 *
73 * @param packageName String package name.
74 * @param fileName String command definitions file which contains package
75 * definition.
76 * @return Map map of commands.
77 * @throws SAXException Any SAX exception, possibly wrapping another exception.
78 * @throws IOException If there is an error setting up the input source.
79 * @throws ParserConfigurationException if a parser cannot be created which
80 * satisfies the requested configuration.
81 */
82 public Map load(String packageName, String fileName)
83 throws SAXException, IOException, ParserConfigurationException {
84
85 if (logger.isInfoEnabled()) {
86 logger.logInfo("Loading package " + packageName + " from file " + fileName);
87 }
88
89 InputStream file = context.getResourceAsStream(fileName);
90 if (file != null) {
91
92 InputSource input = new InputSource(file);
93 SAXParserFactory spf = SAXParserFactory.newInstance();
94 spf.setValidating(true);
95 spf.setNamespaceAware(false);
96
97 XMLReader parser = null;
98 parser = spf.newSAXParser().getXMLReader();
99 XmlCommandPackageHandler handler = new XmlCommandPackageHandler();
100 parser.setContentHandler(handler);
101 parser.setErrorHandler(handler);
102 parser.setEntityResolver(handler);
103 parser.parse(input);
104
105 if (handler.getPackage().equals(packageName)) {
106 return handler.getCommands();
107 }
108 else {
109 throw new SAXException("File package name mismatch " +
110 handler.getPackage() +
111 " != " + packageName);
112 }
113
114 }
115 else {
116 throw new SAXException("File not found " + fileName);
117 }
118
119 }
120
121 }