/src/com/m039/mqst/ItemFactory.java

https://github.com/sanyaade/instant-sms-ussd · Java · 295 lines · 200 code · 64 blank · 31 comment · 21 complexity · 0520ee7c3ce3fe0e08d5c7edbb8544f4 MD5 · raw file

  1. package com.m039.mqst;
  2. import com.m039.mqst.items.InstantUssd;
  3. import com.m039.mqst.items.InstantSms;
  4. import com.m039.mqst.items.InstantItem;
  5. import org.xml.sax.helpers.DefaultHandler;
  6. import java.util.List;
  7. import java.util.ArrayList;
  8. import javax.xml.parsers.SAXParser;
  9. import javax.xml.parsers.SAXParserFactory;
  10. import java.io.InputStream;
  11. import android.util.Log;
  12. import org.xml.sax.Attributes;
  13. import android.content.Context;
  14. import android.content.res.AssetManager;
  15. import android.widget.Toast;
  16. import java.io.FileOutputStream;
  17. import java.io.DataInputStream;
  18. import android.content.res.AssetFileDescriptor;
  19. import javax.xml.parsers.DocumentBuilderFactory;
  20. import javax.xml.parsers.DocumentBuilder;
  21. import org.w3c.dom.Document;
  22. import org.w3c.dom.NodeList;
  23. import org.w3c.dom.Node;
  24. import org.w3c.dom.Element;
  25. import java.io.IOException;
  26. import java.io.OutputStream;
  27. /**
  28. * This is a singleton class.
  29. *
  30. * In this class static methods use IO (via DOM, writeonly)
  31. * operations.
  32. *
  33. * Not static methods use IO (via SAX, readonly).
  34. *
  35. * Created: Tue Aug 30 21:13:00 2011
  36. *
  37. * @author <a href="mailto:flam44@gmail.com">Mozgin Dmitry</a>
  38. * @version 1.0
  39. */
  40. public class ItemFactory {
  41. private final static String TAG = "ItemFactory";
  42. private final static String TEMPLATES_FILE = "ItemFactory";
  43. private static ItemFactory mFactory = null;
  44. /**
  45. * This class parse the xml file and fill the mItems appropriate.
  46. *
  47. */
  48. private class MyHandler extends DefaultHandler {
  49. @Override
  50. public void startElement(String uri,
  51. String name,
  52. String qName,
  53. Attributes atts) {
  54. InstantItem item = null;
  55. if (name.equals("item")) {
  56. try {
  57. String type = atts.getValue("type");
  58. if (type.equals("sms")) {
  59. item = new InstantSms(atts.getValue("help"),
  60. atts.getValue("address"),
  61. atts.getValue("text"),
  62. Boolean.valueOf(atts.getValue("warning")));
  63. mItems.add(item);
  64. }
  65. if (type.equals("ussd")) {
  66. item = new InstantUssd(atts.getValue("help"),
  67. atts.getValue("text"));
  68. mItems.add(item);
  69. }
  70. if (atts.getValue("selected").equals("true")) {
  71. mSelectedItem = item;
  72. }
  73. } catch (NullPointerException e) {
  74. // failed if getValue() doesn't find a attribute
  75. Log.e(TAG, "startElement");
  76. }
  77. }
  78. }
  79. }
  80. private final MyHandler mHandler = new MyHandler();
  81. private final List<InstantItem> mItems = new ArrayList<InstantItem>();
  82. private InstantItem mSelectedItem;
  83. public static ItemFactory getFactory() {
  84. return mFactory;
  85. }
  86. /**
  87. * Use this function to intialize and return mFactory reference
  88. */
  89. public static ItemFactory getFactory(Context context) {
  90. if (mFactory == null) {
  91. mFactory = ItemFactory.parse(context);
  92. }
  93. return mFactory;
  94. }
  95. public static void saveFactory(Context context) {
  96. try {
  97. DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
  98. DocumentBuilder dbuilder = dfactory.newDocumentBuilder();
  99. Document doc = dbuilder.newDocument();
  100. Element templates = doc.createElement("templates");
  101. for (InstantItem item: ItemFactory.getFactory().getItems()) {
  102. Element el = item.createElement(doc);
  103. templates.appendChild(el);
  104. }
  105. OutputStream os = context.openFileOutput(TEMPLATES_FILE, Context.MODE_PRIVATE);
  106. os.write(getStringFromNode(templates).getBytes());
  107. os.close();
  108. } catch (Exception e) {
  109. Log.e(TAG, "addItem");
  110. }
  111. }
  112. /**
  113. * Check if return value is null !
  114. */
  115. public static ItemFactory parse(Context context) {
  116. assetsToInternalStorage(context);
  117. ItemFactory ifactory = new ItemFactory();
  118. try {
  119. InputStream is = context.openFileInput(TEMPLATES_FILE);
  120. ifactory.parse(is);
  121. is.close();
  122. } catch (Exception e) {
  123. Log.e(TAG, "parse");
  124. }
  125. return ifactory;
  126. }
  127. private static void assetsToInternalStorage(Context context) {
  128. // check if the file already in the internal storage
  129. String[] files = context.fileList();
  130. for (String f: files) {
  131. if (f.equals(TEMPLATES_FILE)) {
  132. return;
  133. }
  134. }
  135. // read the file from assets
  136. AssetManager am = context.getAssets();
  137. try {
  138. InputStream is = am.open("sms_templates.xml");
  139. FileOutputStream fos = context.openFileOutput(TEMPLATES_FILE, Context.MODE_PRIVATE);
  140. byte[] bytes = new byte[1024];
  141. while (is.read(bytes) != -1) {
  142. fos.write(bytes);
  143. }
  144. is.close();
  145. fos.close();
  146. } catch (Exception e) {
  147. Log.e(TAG, "assetsToInternalStorage");
  148. }
  149. }
  150. public void parse(InputStream is) {
  151. SAXParserFactory factory = SAXParserFactory.newInstance();
  152. SAXParser parser;
  153. try {
  154. mItems.clear(); // reset items
  155. parser = factory.newSAXParser();
  156. parser.parse(is, mHandler);
  157. } catch (Exception e) {
  158. Log.e(TAG, "parse");
  159. }
  160. }
  161. public void addItem(InstantItem item) {
  162. mItems.add(item);
  163. }
  164. public void removeItem(int position) {
  165. mItems.remove(position);
  166. }
  167. public void setItem(int position, InstantItem item) {
  168. mItems.set(position, item);
  169. }
  170. public InstantItem getItem(int position) {
  171. return mItems.get(position);
  172. }
  173. // debugging purpose
  174. public static void addItem(Context context, InstantItem item) {
  175. try {
  176. DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
  177. DocumentBuilder dbuilder = dfactory.newDocumentBuilder();
  178. InputStream is = context.openFileInput(TEMPLATES_FILE);
  179. Document doc = dbuilder.parse(is);
  180. is.close();
  181. Node templates = doc.getElementsByTagName("templates").item(0);
  182. Element el = item.createElement(doc);
  183. templates.appendChild(el);
  184. OutputStream os = context.openFileOutput(TEMPLATES_FILE, Context.MODE_PRIVATE);
  185. os.write(getStringFromNode(templates).getBytes());
  186. os.close();
  187. } catch (Exception e) {
  188. Log.e(TAG, "addItem");
  189. }
  190. }
  191. // taken from SO
  192. private static String getStringFromNode(Node root) throws IOException {
  193. StringBuilder result = new StringBuilder();
  194. if (root.getNodeType() == 3)
  195. result.append(root.getNodeValue());
  196. else {
  197. if (root.getNodeType() != 9) {
  198. StringBuffer attrs = new StringBuffer();
  199. for (int k = 0; k < root.getAttributes().getLength(); ++k) {
  200. attrs.append(" ")
  201. .append(root.getAttributes().item(k).getNodeName())
  202. .append("=\"")
  203. .append(root.getAttributes().item(k).getNodeValue())
  204. .append("\" ");
  205. }
  206. result.append("<").append(root.getNodeName()).append(" ")
  207. .append(attrs).append(">");
  208. } else {
  209. result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  210. }
  211. NodeList nodes = root.getChildNodes();
  212. for (int i = 0, j = nodes.getLength(); i < j; i++) {
  213. Node node = nodes.item(i);
  214. result.append(getStringFromNode(node));
  215. }
  216. if (root.getNodeType() != 9) {
  217. result.append("</").append(root.getNodeName()).append(">");
  218. }
  219. }
  220. return result.toString();
  221. }
  222. /**
  223. * Check return for null
  224. */
  225. public InstantItem getSelectedItem() {
  226. return mSelectedItem;
  227. }
  228. public List<InstantItem> getItems() {
  229. return mItems;
  230. }
  231. }