Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package applab.search.client;
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.List;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONException;
- import net.sf.json.JSONObject;
- import net.sf.json.JSONSerializer;
- import android.content.ContentValues;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.util.Log;
- import applab.client.ApplabActivity;
- import applab.client.PropertyStorage;
- import applab.client.search.R;
- /**
- * A custom XML parser that also sorts and adds content to search sequence
- * database.
- */
- public class KeywordParser {
- /** for debugging purposes in adb logcat */
- private static final String LOG_TAG = "KeywordParser";
- private static final String ALLOWED_MENU = "allowed";
- private static final String UPDATED_MENU_ITEMS = "updatedItems";
- private static final String DELETED_MENU_ITEMS = "deletedItems";
- private static final String UPDATED_IMAGES = "updatedImages";
- private static final String DELETED_IMAGES = "deletedImages";
- private static final String MENU_NAME = "menuName";
- private static final String MENU_ID = "menuId";
- private static final String ITEM_NAME = "itemName";
- private static final String ITEM_ID = "itemId";
- private static final String ITEM_PARENT_ID = "pId";
- private static final String ITEM_POSITION = "position";
- private static final String ITEM_CONTENT = "content";
- private static final String MENU_DATABASE_TABLE = null;
- private int progressLevel = 0;
- private Storage storage;
- /** handler to which progress updates are sent */
- private Handler progressHandler;
- private InputStream keywordStream;
- /** handler to which responses are sent */
- private Handler responseHandler;
- private Bundle bundle;
- private Integer nodeCount;
- private static String keywordVersion;
- private Integer addedNodes;
- private Integer deletedNodes;
- private String jsonKeywordString;
- private JSONObject jsonKeywordObject;
- private ArrayList<String> Ids = new ArrayList<String>();
- private ContentRow contentRow = new ContentRow();
- public KeywordParser(Handler progressHandler, Handler responseHandler,
- InputStream newKeywordStream) {
- this.keywordStream = newKeywordStream;
- this.responseHandler = responseHandler;
- this.progressHandler = progressHandler;
- }
- /**
- * Obsoleted: loading the xml file into DOM takes a lot of memory. Now using
- * walk() instead, which uses XMLPullParser
- */
- public void run() {
- try {
- addedNodes = 0;
- deletedNodes = 0;
- // This line was causing problems on android 2.2 (IDEOS)
- // this.xmlParser.reset();
- jsonKeywordParser();
- if (nodeCount == null || keywordVersion == null) {
- this.responseHandler
- .sendEmptyMessage(GlobalConstants.KEYWORD_PARSE_ERROR);
- } else if (keywordVersion != "") {
- KeywordParser.storeKeywordsVersion(keywordVersion);
- Log.d(LOG_TAG, "Stored version: " + keywordVersion);
- // let UI handler know
- Log.d(LOG_TAG, "Finished Parsing Keywords ... Added: "
- + addedNodes + ", Deleted: " + deletedNodes);
- this.responseHandler
- .sendEmptyMessage(GlobalConstants.KEYWORD_PARSE_SUCCESS);
- }
- } catch (IllegalStateException e) {
- this.responseHandler
- .sendEmptyMessage(GlobalConstants.KEYWORD_PARSE_ERROR);
- Log.d(LOG_TAG, "IllegalStateException: " + e);
- } finally {
- if (this.storage != null) {
- this.storage.close();
- }
- }
- }
- /**
- * @param rowId
- * @param order
- * @param category
- * @param attribution
- * @param updated
- * @param keyword
- * @param content
- * @param menu
- * @param menuId
- * @param position
- * @param pid
- */
- public void addMenuItemRecord(String rowId, Integer position,
- String content, String pid, String menuName, String menuId) {
- ContentValues addValues = new ContentValues();
- addValues.put(Storage.KEY_ROWID, rowId);
- addValues.put(Storage.KEY_PARENT_ID, pid);
- addValues.put(Storage.KEY_POSITION, position);
- addValues.put(Storage.KEY_MENU, menuName.replace("_", " "));
- addValues.put(Storage.KEY_CONTENT, content.replace("_", " "));
- addValues.put(Storage.KEY_MENU_ID, menuId);
- storage.insertContent(GlobalConstants.MENU_ITEMS_DATABASE_TABLE,
- addValues);
- addedNodes++;
- // Use this to increment progress
- incrementProgressLevel();
- }
- public void addMenuRecord(String rowId, String menuName) {
- ContentValues addValues = new ContentValues();
- addValues.put(Storage.KEY_ROWID, rowId);
- addValues.put(Storage.KEY_MENU, menuName.replace("_", " "));
- storage.insertContent(GlobalConstants.MENU_DATABASE_TABLE, addValues);
- addedNodes++;
- // Use this to increment progress
- incrementProgressLevel();
- }
- /**
- * Call this each time to increment the progress bar by one level
- */
- private void incrementProgressLevel() {
- Message message = progressHandler.obtainMessage();
- bundle.putInt("node", ++progressLevel);
- Log.d(LOG_TAG, "Processed : " + progressLevel + " of " + nodeCount);
- message.setData(bundle);
- progressHandler.sendMessage(message);
- }
- /**
- * Record last update version in preferences
- *
- * @param document
- */
- public void storeKeywordsVersion() {
- String version = getKeywordsVersion();
- storeKeywordsVersion(version);
- }
- static void storeKeywordsVersion(String version) {
- PropertyStorage.getLocal().setValue(
- GlobalConstants.KEYWORDS_VERSION_KEY, version);
- }
- public String getKeywordsVersion() {
- // TODO: Get keywords version from json string
- // keywordVersion =
- // this.jsonKeywordObject.getString(VERSION_ATTRIBUTE_NAME);
- // for now keywordversion is set to current date
- Calendar currentDate = Calendar.getInstance();
- SimpleDateFormat formatter = new SimpleDateFormat(
- "yyyy/MMM/dd HH:mm:ss");
- String version = formatter.format(currentDate.getTime());
- if (version.length() > 0) {
- return version;
- }
- return "";
- }
- private void jsonKeywordParser() {
- this.jsonKeywordConvertor();
- try {
- // Getting Arrays
- JSONArray menusArray = this.jsonKeywordObject
- .getJSONArray(ALLOWED_MENU);
- nodeCount += menusArray.size();
- JSONArray updatedMenuItemsArray = this.jsonKeywordObject
- .getJSONArray(UPDATED_MENU_ITEMS);
- nodeCount += updatedMenuItemsArray.size();
- JSONArray deletedMenuItemsArray = this.jsonKeywordObject
- .getJSONArray(DELETED_MENU_ITEMS);
- nodeCount += deletedMenuItemsArray.size();
- JSONArray updatedImageArray = this.jsonKeywordObject
- .getJSONArray(UPDATED_IMAGES);
- nodeCount += updatedImageArray.size();
- JSONArray deletedImageArray = this.jsonKeywordObject
- .getJSONArray(DELETED_IMAGES);
- nodeCount += deletedImageArray.size();
- if (keywordVersion != "" && nodeCount > 0) {
- nodeCount += 1; // Add one for the start document node
- Log.d(LOG_TAG, "Total nodes: " + nodeCount);
- Log.d(LOG_TAG, "Keyword version: " + keywordVersion);
- bundle = new Bundle();
- // Show parse dialog (send signal with total node count)
- Message message = responseHandler.obtainMessage();
- bundle.putInt("nodeCount", nodeCount);
- message.what = GlobalConstants.KEYWORD_PARSE_GOT_NODE_TOTAL;
- message.setData(bundle);
- responseHandler.sendMessage(message);
- // If this is the first node, we open the storage
- if (storage == null) {
- storage = new Storage(ApplabActivity.getGlobalContext());
- storage.open();
- }
- }
- // pass arrays to due methods for processing
- updateMenuTable(menusArray);
- updateMenuItemsTable(updatedMenuItemsArray);
- deleteMenuItems(deletedMenuItemsArray);
- updateImages(updatedImageArray, deletedImageArray);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- storeKeywordsVersion();
- }
- /**
- * Loops through all Deleted MenuItems
- *
- * @param deletedMenuItemsArray
- */
- private void deleteMenuItems(JSONArray deletedMenuItemsArray) {
- for (int i = 0; i < deletedMenuItemsArray.size(); i++) {
- JSONObject menuItems = deletedMenuItemsArray.getJSONObject(i);
- // Pick the item id whose row to delete
- String rowId = menuItems.getString(ITEM_ID);
- if (storage != null) {
- boolean isDeleted = storage.deleteMenuItemEntry(
- GlobalConstants.MENU_ITEMS_DATABASE_TABLE, rowId);
- if (isDeleted == true) {
- deletedNodes++;
- // Use this to increment progress
- incrementProgressLevel();
- }
- }
- }
- }
- /**
- * Loops through all Updated MenuItems and upserts
- *
- * @param updatedMenuItemsArray
- */
- private void updateMenuItemsTable(JSONArray updatedMenuItemsArray) {
- for (int i = 0; i < updatedMenuItemsArray.size(); i++) {
- JSONObject menuItems = updatedMenuItemsArray.getJSONObject(i);
- // Updating database with new info
- contentRow.setRowId(menuItems.getString(MENU_ID));
- contentRow.setMenuId(menuItems.getString(ITEM_ID));
- contentRow.setName(menuItems.getString(ITEM_NAME));
- contentRow.setParentId(menuItems.getString(ITEM_PARENT_ID));
- contentRow.setPosition(menuItems.getInt(ITEM_POSITION));
- contentRow.setContent(menuItems.getString(ITEM_CONTENT));
- contentRow.itemSave();
- contentRow = null;
- }
- }
- /**
- * Loops through all Menus: If a menu exists thats not in the updated list
- * then delete it together with all its children; otherwise upsert
- *
- * @param menusArray
- *
- */
- private void updateMenuTable(JSONArray menusArray) {
- Ids = storage.getLocalMenuIds(MENU_DATABASE_TABLE);
- ArrayList<String> newIds = new ArrayList<String>();
- JSONObject menu = new JSONObject();
- for (int i = 0; i < menusArray.size(); i++) {
- menu = menusArray.getJSONObject(i);
- newIds.add(menu.getString(MENU_ID));
- }
- // Check if local menu ids match the new ones; if local id doesn't exist
- // among new ids delete it and all its children
- if (!Ids.isEmpty()) {
- for (int i = 0; i < menusArray.size(); i++) {
- if (!newIds.contains(Ids.get(i))) {
- storage.deleteMenuEntry(
- GlobalConstants.MENU_DATABASE_TABLE, Ids.get(i));
- storage.deleteMenuItemEntry(
- GlobalConstants.MENU_ITEMS_DATABASE_TABLE,
- Ids.get(i));
- }
- }
- }
- for (int i = 0; i < menusArray.size(); i++) {
- contentRow.setMenuId(newIds.get(i));
- contentRow.setName(menu.getString(MENU_NAME));
- contentRow.save();
- contentRow = null;
- }
- }
- /**
- * @param updatedImageArray
- * @param deletedImageArray
- */
- private void updateImages(JSONArray updatedImageArray,
- JSONArray deletedImageArray) {
- List<String> updatedImages = new ArrayList<String>();
- List<String> deletedImages = new ArrayList<String>();
- // Looping through all updated Images to load them into a list
- for (int i = 0; i < updatedImageArray.size(); i++) {
- JSONObject menuItems = deletedImageArray.getJSONObject(i);
- // Pick the item id whose row to delete
- updatedImages.add(menuItems.getString(ITEM_ID));
- }
- for (int i = 0; i < deletedImageArray.size(); i++) {
- JSONObject menuItems = deletedImageArray.getJSONObject(i);
- // Pick the item id whose row to delete
- deletedImages.add(menuItems.getString(ITEM_ID));
- }
- ImageManager.updatePhoneImages(updatedImages, deletedImages);
- }
- public JSONObject jsonKeywordConvertor() {
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- this.keywordStream, "iso-8859-1"), 8);
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line + "\n");
- }
- this.keywordStream.close();
- this.jsonKeywordString = sb.toString();
- } catch (Exception e) {
- Log.e("Buffer Error", "Error converting result " + e.toString());
- }
- // Parse the JSON string to a JSON object
- try {
- this.jsonKeywordObject = (JSONObject) JSONSerializer
- .toJSON(this.jsonKeywordString);
- } catch (JSONException e) {
- Log.e("JSON Parser", "Error parsing data " + e.toString());
- }
- // return JSON Object
- return jsonKeywordObject;
- }
- private class ContentRow {
- // Row Fields
- String rowId = null;
- Integer position = null;
- String menuId = null;
- String content = "";
- String itemId = null;
- String menuName = null;
- String parentId = null;
- public void itemSave() {
- addMenuItemRecord(rowId, position, content, parentId, itemId,
- menuId);
- }
- public void save() {
- addMenuRecord(menuId, menuName);
- }
- public void setParentId(String pId) {
- this.parentId = pId;
- }
- public void setPosition(int posn) {
- this.position = posn;
- }
- public void setMenuId(String menuId) {
- this.menuId = menuId;
- }
- public void setName(String menuName) {
- this.menuName = menuName;
- }
- public void setContent(String content) {
- this.content += content;
- }
- public void setRowId(String id) {
- this.rowId = id;
- }
- }
- }
Add Comment
Please, Sign In to add comment