DocumentParser.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.engines;
  16. import java.io.File;
  17. import java.util.logging.Logger;
  18. import javax.xml.parsers.DocumentBuilder;
  19. import javax.xml.parsers.DocumentBuilderFactory;
  20. import org.w3c.dom.Document;
  21. import org.w3c.dom.NamedNodeMap;
  22. import org.w3c.dom.Node;
  23. import org.xml.sax.ErrorHandler;
  24. import org.xml.sax.SAXParseException;
  25. import com.l2jserver.Config;
  26. import com.l2jserver.util.file.filter.XMLFilter;
  27. /**
  28. * Abstract class for XML parsers.<br>
  29. * It's in <i>beta</i> state, so it's expected to change over time.
  30. * @author Zoey76
  31. */
  32. public abstract class DocumentParser
  33. {
  34. protected final Logger _log = Logger.getLogger(getClass().getName());
  35. private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
  36. private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
  37. private static final XMLFilter xmlFilter = new XMLFilter();
  38. private File _currentFile;
  39. private Document _currentDocument;
  40. /**
  41. * This method can be used to load/reload the data.<br>
  42. * It's highly recommended to clear the data storage, either the list or map.
  43. */
  44. public abstract void load();
  45. /**
  46. * Wrapper for {@link #parseFile(File)} method.
  47. * @param path the relative path to the datapack root of the XML file to parse.
  48. */
  49. protected void parseDatapackFile(String path)
  50. {
  51. parseFile(new File(Config.DATAPACK_ROOT, path));
  52. }
  53. /**
  54. * Parses a single XML file.<br>
  55. * If the file was successfully parsed, call {@link #parseDocument(Document)} for the parsed document.<br>
  56. * <b>Validation is enforced.</b>
  57. * @param f the XML file to parse.
  58. */
  59. protected void parseFile(File f)
  60. {
  61. if (!xmlFilter.accept(f))
  62. {
  63. _log.warning(getClass().getSimpleName() + ": Could not parse " + f.getName() + " is not a file or it doesn't exist!");
  64. return;
  65. }
  66. final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  67. dbf.setNamespaceAware(true);
  68. dbf.setValidating(true);
  69. dbf.setIgnoringComments(true);
  70. _currentDocument = null;
  71. _currentFile = f;
  72. try
  73. {
  74. dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
  75. final DocumentBuilder db = dbf.newDocumentBuilder();
  76. db.setErrorHandler(new XMLErrorHandler());
  77. _currentDocument = db.parse(f);
  78. }
  79. catch (Exception e)
  80. {
  81. _log.warning(getClass().getSimpleName() + ": Could not parse " + f.getName() + " file: " + e.getMessage());
  82. return;
  83. }
  84. parseDocument();
  85. }
  86. /**
  87. * Gets the current file.
  88. * @return the current file
  89. */
  90. public File getCurrentFile()
  91. {
  92. return _currentFile;
  93. }
  94. /**
  95. * Gets the current document.
  96. * @return the current document
  97. */
  98. protected Document getCurrentDocument()
  99. {
  100. return _currentDocument;
  101. }
  102. /**
  103. * Wrapper for {@link #parseDirectory(File, boolean)}.
  104. * @param file the path to the directory where the XML files are.
  105. * @return {@code false} if it fails to find the directory, {@code true} otherwise.
  106. */
  107. protected boolean parseDirectory(File file)
  108. {
  109. return parseDirectory(file, false);
  110. }
  111. /**
  112. * Wrapper for {@link #parseDirectory(File, boolean)}.
  113. * @param path the path to the directory where the XML files are.
  114. * @return {@code false} if it fails to find the directory, {@code true} otherwise.
  115. */
  116. protected boolean parseDirectory(String path)
  117. {
  118. return parseDirectory(new File(path), false);
  119. }
  120. /**
  121. * Wrapper for {@link #parseDirectory(File, boolean)}.
  122. * @param path the path to the directory where the XML files are.
  123. * @param recursive parses all sub folders if there is.
  124. * @return {@code false} if it fails to find the directory, {@code true} otherwise.
  125. */
  126. protected boolean parseDirectory(String path, boolean recursive)
  127. {
  128. return parseDirectory(new File(path), recursive);
  129. }
  130. /**
  131. * Loads all XML files from {@code path} and calls {@link #parseFile(File)} for each one of them.
  132. * @param dir the directory object to scan.
  133. * @param recursive parses all sub folders if there is.
  134. * @return {@code false} if it fails to find the directory, {@code true} otherwise.
  135. */
  136. protected boolean parseDirectory(File dir, boolean recursive)
  137. {
  138. if (!dir.exists())
  139. {
  140. _log.warning(getClass().getSimpleName() + ": Folder " + dir.getAbsolutePath() + " doesn't exist!");
  141. return false;
  142. }
  143. final File[] listOfFiles = dir.listFiles();
  144. for (File f : listOfFiles)
  145. {
  146. if (recursive && f.isDirectory())
  147. {
  148. parseDirectory(f, recursive);
  149. }
  150. else if (xmlFilter.accept(f))
  151. {
  152. parseFile(f);
  153. }
  154. }
  155. return true;
  156. }
  157. /**
  158. * Overridable method that could parse a custom document.<br>
  159. * @param doc the document to parse.
  160. */
  161. protected void parseDocument(Document doc)
  162. {
  163. // Do nothing, to be overridden in sub-classes.
  164. }
  165. /**
  166. * Abstract method that when implemented will parse the current document.<br>
  167. * Is expected to be call from {@link #parseFile(File)}.
  168. */
  169. protected abstract void parseDocument();
  170. /**
  171. * Parses the int.
  172. * @param n the named node map.
  173. * @param name the attribute name.
  174. * @return a parsed integer.
  175. */
  176. protected static int parseInt(NamedNodeMap n, String name)
  177. {
  178. return Integer.parseInt(n.getNamedItem(name).getNodeValue());
  179. }
  180. /**
  181. * Parses the integer.
  182. * @param n the named node map.
  183. * @param name the attribute name.
  184. * @return a parsed integer object.
  185. */
  186. protected static Integer parseInteger(NamedNodeMap n, String name)
  187. {
  188. return Integer.valueOf(n.getNamedItem(name).getNodeValue());
  189. }
  190. /**
  191. * Parses the int.
  192. * @param n the node to parse.
  193. * @return the parsed integer.
  194. */
  195. protected static int parseInt(Node n)
  196. {
  197. return Integer.parseInt(n.getNodeValue());
  198. }
  199. /**
  200. * Parses the integer.
  201. * @param n the node to parse.
  202. * @return the parsed integer object.
  203. */
  204. protected static Integer parseInteger(Node n)
  205. {
  206. return Integer.valueOf(n.getNodeValue());
  207. }
  208. /**
  209. * Parses the long.
  210. * @param n the named node map.
  211. * @param name the attribute name.
  212. * @return a parsed integer.
  213. */
  214. protected static Long parseLong(NamedNodeMap n, String name)
  215. {
  216. return Long.valueOf(n.getNamedItem(name).getNodeValue());
  217. }
  218. /**
  219. * Parses the double.
  220. * @param n the named node map.
  221. * @param name the attribute name.
  222. * @return a parsed double.
  223. */
  224. protected static Double parseDouble(NamedNodeMap n, String name)
  225. {
  226. return Double.valueOf(n.getNamedItem(name).getNodeValue());
  227. }
  228. /**
  229. * Parses the boolean.
  230. * @param n the named node map.
  231. * @param name the attribute name.
  232. * @return {@code true} if the attribute exists and it's value is {@code true}, {@code false} otherwise.
  233. */
  234. protected static boolean parseBoolean(NamedNodeMap n, String name)
  235. {
  236. final Node b = n.getNamedItem(name);
  237. return (b != null) && Boolean.parseBoolean(b.getNodeValue());
  238. }
  239. /**
  240. * @param n the named node map
  241. * @param name the attribute name
  242. * @return the node string value for the given node name and named node map if exist, otherwise an empty string
  243. */
  244. protected static String parseString(NamedNodeMap n, String name)
  245. {
  246. final Node b = n.getNamedItem(name);
  247. return (b == null) ? "" : b.getNodeValue();
  248. }
  249. /**
  250. * Simple XML error handler.
  251. * @author Zoey76
  252. */
  253. protected class XMLErrorHandler implements ErrorHandler
  254. {
  255. @Override
  256. public void warning(SAXParseException e) throws SAXParseException
  257. {
  258. throw e;
  259. }
  260. @Override
  261. public void error(SAXParseException e) throws SAXParseException
  262. {
  263. throw e;
  264. }
  265. @Override
  266. public void fatalError(SAXParseException e) throws SAXParseException
  267. {
  268. throw e;
  269. }
  270. }
  271. }