Xml2Js.java 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.UnsupportedEncodingException;
  10. import java.net.URLEncoder;
  11. import java.util.Arrays;
  12. import java.util.HashSet;
  13. import java.util.Iterator;
  14. import java.util.LinkedList;
  15. import java.util.List;
  16. import java.util.Set;
  17. import java.util.zip.Deflater;
  18. public class Xml2Js
  19. {
  20. /**
  21. *
  22. */
  23. protected static final int IO_BUFFER_SIZE = 4 * 1024;
  24. /**
  25. *
  26. */
  27. public static String CHARSET_FOR_URL_ENCODING = "ISO-8859-1";
  28. /**
  29. *
  30. * @param path
  31. * @return
  32. */
  33. public List<String> walk(File base, File root) throws IOException
  34. {
  35. if (root == null)
  36. {
  37. root = base;
  38. }
  39. List<String> result = new LinkedList<String>();
  40. String basePath = base.getCanonicalPath();
  41. File[] list = root.listFiles();
  42. if (list != null)
  43. {
  44. for (File f : list)
  45. {
  46. if (f.isDirectory())
  47. {
  48. result.addAll(walk(base, f));
  49. }
  50. else if (f.getCanonicalPath().toLowerCase().endsWith(".xml"))
  51. {
  52. String name = f.getCanonicalPath()
  53. .substring(basePath.length() + 1);
  54. result.add(
  55. "f['" + name + "'] = '" + processFile(f) + "';\n");
  56. }
  57. }
  58. }
  59. return result;
  60. }
  61. /**
  62. *
  63. * @param file
  64. * @return
  65. * @throws IOException
  66. */
  67. public static String processFile(File file) throws IOException
  68. {
  69. System.out.println("Processing " + file.getCanonicalPath() + "...");
  70. Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
  71. byte[] inBytes = encodeURIComponent(
  72. readInputStream(new FileInputStream(file)),
  73. CHARSET_FOR_URL_ENCODING).getBytes("UTF-8");
  74. deflater.setInput(inBytes);
  75. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
  76. inBytes.length);
  77. deflater.finish();
  78. byte[] buffer = new byte[IO_BUFFER_SIZE];
  79. while (!deflater.finished())
  80. {
  81. int count = deflater.deflate(buffer); // returns the generated code... index
  82. outputStream.write(buffer, 0, count);
  83. }
  84. outputStream.close();
  85. return encodeToString(outputStream.toByteArray(), false);
  86. }
  87. /**
  88. *
  89. * @param stream
  90. * @return
  91. * @throws IOException
  92. */
  93. public static String readInputStream(InputStream stream) throws IOException
  94. {
  95. BufferedReader reader = new BufferedReader(
  96. new InputStreamReader(stream));
  97. StringBuffer result = new StringBuffer();
  98. String tmp = reader.readLine();
  99. while (tmp != null)
  100. {
  101. result.append(tmp + "\n");
  102. tmp = reader.readLine();
  103. }
  104. reader.close();
  105. return result.toString();
  106. }
  107. public static String encodeURIComponent(String s, String charset)
  108. {
  109. if (s == null)
  110. {
  111. return null;
  112. }
  113. else
  114. {
  115. String result;
  116. try
  117. {
  118. result = URLEncoder.encode(s, charset).replaceAll("\\+", "%20")
  119. .replaceAll("\\%21", "!").replaceAll("\\%27", "'")
  120. .replaceAll("\\%28", "(").replaceAll("\\%29", ")")
  121. .replaceAll("\\%7E", "~");
  122. }
  123. catch (UnsupportedEncodingException e)
  124. {
  125. // This exception should never occur
  126. result = s;
  127. }
  128. return result;
  129. }
  130. }
  131. private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  132. .toCharArray();
  133. private static final int[] IA = new int[256];
  134. static
  135. {
  136. Arrays.fill(IA, -1);
  137. for (int i = 0, iS = CA.length; i < iS; i++)
  138. IA[CA[i]] = i;
  139. IA['='] = 0;
  140. }
  141. // ****************************************************************************************
  142. // * char[] version
  143. // ****************************************************************************************
  144. /** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
  145. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  146. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  147. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  148. * little faster.
  149. * @return A BASE64 encoded array. Never <code>null</code>.
  150. */
  151. public final static char[] encodeToChar(byte[] sArr, boolean lineSep)
  152. {
  153. // Check special case
  154. int sLen = sArr != null ? sArr.length : 0;
  155. if (sLen == 0)
  156. return new char[0];
  157. int eLen = (sLen / 3) * 3; // Length of even 24-bits.
  158. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
  159. int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
  160. char[] dArr = new char[dLen];
  161. // Encode even 24-bits
  162. for (int s = 0, d = 0, cc = 0; s < eLen;)
  163. {
  164. // Copy next three bytes into lower 24 bits of int, paying attension to sign.
  165. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8
  166. | (sArr[s++] & 0xff);
  167. // Encode the int into four chars
  168. dArr[d++] = CA[(i >>> 18) & 0x3f];
  169. dArr[d++] = CA[(i >>> 12) & 0x3f];
  170. dArr[d++] = CA[(i >>> 6) & 0x3f];
  171. dArr[d++] = CA[i & 0x3f];
  172. // Add optional line separator
  173. if (lineSep && ++cc == 19 && d < dLen - 2)
  174. {
  175. dArr[d++] = '\r';
  176. dArr[d++] = '\n';
  177. cc = 0;
  178. }
  179. }
  180. // Pad and encode last bits if source isn't even 24 bits.
  181. int left = sLen - eLen; // 0 - 2.
  182. if (left > 0)
  183. {
  184. // Prepare the int
  185. int i = ((sArr[eLen] & 0xff) << 10)
  186. | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
  187. // Set last four chars
  188. dArr[dLen - 4] = CA[i >> 12];
  189. dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
  190. dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
  191. dArr[dLen - 1] = '=';
  192. }
  193. return dArr;
  194. }
  195. // ****************************************************************************************
  196. // * String version
  197. // ****************************************************************************************
  198. /** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
  199. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
  200. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
  201. * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
  202. * little faster.
  203. * @return A BASE64 encoded array. Never <code>null</code>.
  204. */
  205. public final static String encodeToString(byte[] sArr, boolean lineSep)
  206. {
  207. // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
  208. return new String(encodeToChar(sArr, lineSep));
  209. }
  210. /**
  211. * Main
  212. */
  213. public static void main(String[] args)
  214. {
  215. if (args.length < 2)
  216. {
  217. System.out.println("Usage: xml2js path file");
  218. }
  219. else
  220. {
  221. try
  222. {
  223. Xml2Js fw = new Xml2Js();
  224. // Generates result
  225. StringBuffer result = new StringBuffer();
  226. result.append("(function() {\nvar f = {};\n");
  227. List<String> files = fw
  228. .walk(new File(new File(".").getCanonicalPath()
  229. + File.separator + args[0]), null);
  230. Iterator<String> it = files.iterator();
  231. while (it.hasNext())
  232. {
  233. result.append(it.next());
  234. }
  235. result.append("\n");
  236. result.append("var l = mxStencilRegistry.loadStencil;\n\n");
  237. result.append(
  238. "mxStencilRegistry.loadStencil = function(filename, fn)\n{\n");
  239. result.append(" var t = f[filename.substring(STENCIL_PATH.length + 1)];\n");
  240. result.append(" var s = null;\n");
  241. result.append(" if (t != null) {\n");
  242. result.append(" t = pako.inflateRaw(atob(t));\n");
  243. result.append(" s = new Array(t.length);\n");
  244. result.append(" for (var i = 0; i < t.length; i++) {\n");
  245. result.append(" s[i] = String.fromCharCode(t[i]);\n");
  246. result.append(" };\n");
  247. result.append(" s = decodeURIComponent(s.join(''));\n");
  248. result.append(" }\n");
  249. result.append(" if (fn != null && s != null) {\n");
  250. result.append(
  251. " window.setTimeout(function(){fn(mxUtils.parseXml(s))}, 0);\n");
  252. result.append(" } else {\n");
  253. result.append(
  254. " return (s != null) ? mxUtils.parseXml(s) : l.apply(this, arguments)\n");
  255. result.append(" }\n");
  256. result.append("};\n");
  257. result.append("})();\n");
  258. FileWriter writer = new FileWriter(
  259. new File(new File(".").getCanonicalPath()
  260. + File.separator + args[1]));
  261. writer.write(result.toString());
  262. writer.flush();
  263. writer.close();
  264. }
  265. catch (IOException ex)
  266. {
  267. ex.printStackTrace();
  268. }
  269. }
  270. }
  271. }