XmlPullParserFactory.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/
  2. // for license please see accompanying XmlPull license file (available also at http://www.xmlpull.org/)
  3. package org.xmlpull.v1;
  4. import java.io.InputStream;
  5. import java.util.Enumeration;
  6. import java.util.Hashtable;
  7. import java.util.Vector;
  8. /**
  9. * This class is used to create implementations of XML Pull Parser defined in XMPULL V1 API.
  10. * The name of actual factory class will be determined based on several parameters.
  11. * It works similar to JAXP but tailored to work in J2ME environments
  12. * (no access to system properties or file system) so name of parser class factory to use
  13. * and its class used for loading (no class loader - on J2ME no access to context class loaders)
  14. * must be passed explicitly. If no name of parser factory was passed (or is null)
  15. * it will try to find name by searching in CLASSPATH for
  16. * META-INF/services/org.xmlpull.v1.XmlPullParserFactory resource that should contain
  17. * a comma separated list of class names of factories or parsers to try (in order from
  18. * left to the right). If none found, it will throw an exception.
  19. *
  20. * <br /><strong>NOTE:</strong>In J2SE or J2EE environments, you may want to use
  21. * <code>newInstance(property, classLoaderCtx)</code>
  22. * where first argument is
  23. * <code>System.getProperty(XmlPullParserFactory.PROPERTY_NAME)</code>
  24. * and second is <code>Thread.getContextClassLoader().getClass()</code> .
  25. *
  26. * @see IXmlPullParser
  27. *
  28. * @author <a href="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a>
  29. * @author Stefan Haustein
  30. */
  31. public class XmlPullParserFactory {
  32. /** used as default class to server as context class in newInstance() */
  33. final static Class referenceContextClass;
  34. static {
  35. XmlPullParserFactory f = new XmlPullParserFactory();
  36. referenceContextClass = f.getClass();
  37. }
  38. /** Name of the system or midlet property that should be used for
  39. a system property containing a comma separated list of factory
  40. or parser class names (value:
  41. org.xmlpull.v1.XmlPullParserFactory). */
  42. public static final String PROPERTY_NAME =
  43. "org.xmlpull.v1.XmlPullParserFactory";
  44. private static final String RESOURCE_NAME =
  45. "/META-INF/services/" + PROPERTY_NAME;
  46. // public static final String DEFAULT_PROPERTY =
  47. // "org.xmlpull.xpp3.XmlPullParser,org.kxml2.io.KXmlParser";
  48. protected Vector parserClasses;
  49. protected String classNamesLocation;
  50. protected Vector serializerClasses;
  51. // features are kept there
  52. protected Hashtable features = new Hashtable();
  53. /**
  54. * Protected constructor to be called by factory implementations.
  55. */
  56. protected XmlPullParserFactory() {
  57. }
  58. /**
  59. * Set the features to be set when XML Pull Parser is created by this factory.
  60. * <p><b>NOTE:</b> factory features are not used for XML ISerializer.
  61. *
  62. * @param name string with URI identifying feature
  63. * @param state if true feature will be set; if false will be ignored
  64. */
  65. public void setFeature(String name,
  66. boolean state) throws XmlPullParserException {
  67. features.put(name, new Boolean(state));
  68. }
  69. /**
  70. * Return the current value of the feature with given name.
  71. * <p><b>NOTE:</b> factory features are not used for XML ISerializer.
  72. *
  73. * @param name The name of feature to be retrieved.
  74. * @return The value of named feature.
  75. * Unknown features are <string>always</strong> returned as false
  76. */
  77. public boolean getFeature (String name) {
  78. Boolean value = (Boolean) features.get(name);
  79. return value != null ? value.booleanValue() : false;
  80. }
  81. /**
  82. * Specifies that the parser produced by this factory will provide
  83. * support for XML namespaces.
  84. * By default the value of this is set to false.
  85. *
  86. * @param awareness true if the parser produced by this code
  87. * will provide support for XML namespaces; false otherwise.
  88. */
  89. public void setNamespaceAware(boolean awareness) {
  90. features.put (IXmlPullParser.FEATURE_PROCESS_NAMESPACES, new Boolean (awareness));
  91. }
  92. /**
  93. * Indicates whether or not the factory is configured to produce
  94. * parsers which are namespace aware
  95. * (it simply set feature IXmlPullParser.FEATURE_PROCESS_NAMESPACES to true or false).
  96. *
  97. * @return true if the factory is configured to produce parsers
  98. * which are namespace aware; false otherwise.
  99. */
  100. public boolean isNamespaceAware() {
  101. return getFeature (IXmlPullParser.FEATURE_PROCESS_NAMESPACES);
  102. }
  103. /**
  104. * Specifies that the parser produced by this factory will be validating
  105. * (it simply set feature IXmlPullParser.FEATURE_VALIDATION to true or false).
  106. *
  107. * By default the value of this is set to false.
  108. *
  109. * @param validating - if true the parsers created by this factory must be validating.
  110. */
  111. public void setValidating(boolean validating) {
  112. features.put (IXmlPullParser.FEATURE_VALIDATION, new Boolean (validating));
  113. }
  114. /**
  115. * Indicates whether or not the factory is configured to produce parsers
  116. * which validate the XML content during parse.
  117. *
  118. * @return true if the factory is configured to produce parsers
  119. * which validate the XML content during parse; false otherwise.
  120. */
  121. public boolean isValidating() {
  122. return getFeature (IXmlPullParser.FEATURE_VALIDATION);
  123. }
  124. /**
  125. * Creates a new instance of a XML Pull Parser
  126. * using the currently configured factory features.
  127. *
  128. * @return A new instance of a XML Pull Parser.
  129. * @throws XmlPullParserException if a parser cannot be created which satisfies the
  130. * requested configuration.
  131. */
  132. public IXmlPullParser newPullParser() throws XmlPullParserException {
  133. if (parserClasses == null) throw new XmlPullParserException
  134. ("Factory initialization was incomplete - has not tried "+classNamesLocation);
  135. if (parserClasses.size() == 0) throw new XmlPullParserException
  136. ("No valid parser classes found in "+classNamesLocation);
  137. final StringBuffer issues = new StringBuffer ();
  138. for (int i = 0; i < parserClasses.size (); i++) {
  139. final Class ppClass = (Class) parserClasses.elementAt (i);
  140. try {
  141. final IXmlPullParser pp = (IXmlPullParser) ppClass.newInstance();
  142. // if( ! features.isEmpty() ) {
  143. //Enumeration keys = features.keys();
  144. // while(keys.hasMoreElements()) {
  145. for (Enumeration e = features.keys (); e.hasMoreElements ();) {
  146. final String key = (String) e.nextElement();
  147. final Boolean value = (Boolean) features.get(key);
  148. if(value != null && value.booleanValue()) {
  149. pp.setFeature(key, true);
  150. }
  151. }
  152. return pp;
  153. } catch(Exception ex) {
  154. issues.append (ppClass.getName () + ": "+ ex.toString ()+"; ");
  155. }
  156. }
  157. throw new XmlPullParserException ("could not create parser: "+issues);
  158. }
  159. /**
  160. * Creates a new instance of a XML ISerializer.
  161. *
  162. * <p><b>NOTE:</b> factory features are not used for XML ISerializer.
  163. *
  164. * @return A new instance of a XML ISerializer.
  165. * @throws XmlPullParserException if a parser cannot be created which satisfies the
  166. * requested configuration.
  167. */
  168. public IXmlSerializer newSerializer() throws XmlPullParserException {
  169. if (serializerClasses == null) {
  170. throw new XmlPullParserException
  171. ("Factory initialization incomplete - has not tried "+classNamesLocation);
  172. }
  173. if(serializerClasses.size() == 0) {
  174. throw new XmlPullParserException
  175. ("No valid serializer classes found in "+classNamesLocation);
  176. }
  177. final StringBuffer issues = new StringBuffer ();
  178. for (int i = 0; i < serializerClasses.size (); i++) {
  179. final Class ppClass = (Class) serializerClasses.elementAt (i);
  180. try {
  181. final IXmlSerializer ser = (IXmlSerializer) ppClass.newInstance();
  182. // for (Enumeration e = features.keys (); e.hasMoreElements ();) {
  183. // String key = (String) e.nextElement();
  184. // Boolean value = (Boolean) features.get(key);
  185. // if(value != null && value.booleanValue()) {
  186. // ser.setFeature(key, true);
  187. // }
  188. // }
  189. return ser;
  190. } catch(Exception ex) {
  191. issues.append (ppClass.getName () + ": "+ ex.toString ()+"; ");
  192. }
  193. }
  194. throw new XmlPullParserException ("could not create serializer: "+issues);
  195. }
  196. /**
  197. * Create a new instance of a PullParserFactory that can be used
  198. * to create XML pull parsers (see class description for more
  199. * details).
  200. *
  201. * @return a new instance of a PullParserFactory, as returned by newInstance (null, null);
  202. */
  203. public static XmlPullParserFactory newInstance () throws XmlPullParserException {
  204. return newInstance(null, null);
  205. }
  206. public static XmlPullParserFactory newInstance (String classNames, Class context)
  207. throws XmlPullParserException {
  208. if (context == null) {
  209. //NOTE: make sure context uses the same class loader as API classes
  210. // this is the best we can do without having access to context classloader in J2ME
  211. // if API is in the same classloader as implementation then this will work
  212. context = referenceContextClass;
  213. }
  214. String classNamesLocation = null;
  215. if (classNames == null || classNames.length() == 0 || "DEFAULT".equals(classNames)) {
  216. try {
  217. InputStream is = context.getResourceAsStream (RESOURCE_NAME);
  218. if (is == null) throw new XmlPullParserException
  219. ("resource not found: "+RESOURCE_NAME
  220. +" make sure that parser implementing XmlPull API is available");
  221. final StringBuffer sb = new StringBuffer();
  222. while (true) {
  223. final int ch = is.read();
  224. if (ch < 0) break;
  225. else if (ch > ' ')
  226. sb.append((char) ch);
  227. }
  228. is.close ();
  229. classNames = sb.toString ();
  230. }
  231. catch (Exception e) {
  232. throw new XmlPullParserException (null, null, e);
  233. }
  234. classNamesLocation = "resource "+RESOURCE_NAME+" that contained '"+classNames+"'";
  235. } else {
  236. classNamesLocation =
  237. "parameter classNames to newInstance() that contained '"+classNames+"'";
  238. }
  239. XmlPullParserFactory factory = null;
  240. final Vector parserClasses = new Vector ();
  241. final Vector serializerClasses = new Vector ();
  242. int pos = 0;
  243. while (pos < classNames.length ()) {
  244. int cut = classNames.indexOf (',', pos);
  245. if (cut == -1) cut = classNames.length ();
  246. final String name = classNames.substring (pos, cut);
  247. Class candidate = null;
  248. Object instance = null;
  249. try {
  250. candidate = Class.forName (name);
  251. // necessary because of J2ME .class issue
  252. instance = candidate.newInstance ();
  253. }
  254. catch (Exception e) {}
  255. if (candidate != null) {
  256. boolean recognized = false;
  257. if (instance instanceof IXmlPullParser) {
  258. parserClasses.addElement (candidate);
  259. recognized = true;
  260. }
  261. if (instance instanceof IXmlSerializer) {
  262. serializerClasses.addElement (candidate);
  263. recognized = true;
  264. }
  265. if (instance instanceof XmlPullParserFactory) {
  266. if (factory == null) {
  267. factory = (XmlPullParserFactory) instance;
  268. }
  269. recognized = true;
  270. }
  271. if (!recognized) {
  272. throw new XmlPullParserException ("incompatible class: "+name);
  273. }
  274. }
  275. pos = cut + 1;
  276. }
  277. if (factory == null) {
  278. factory = new XmlPullParserFactory ();
  279. }
  280. factory.parserClasses = parserClasses;
  281. factory.serializerClasses = serializerClasses;
  282. factory.classNamesLocation = classNamesLocation;
  283. return factory;
  284. }
  285. }