diff --git a/astrid/.classpath b/astrid/.classpath index 2f3055c87..ef4e117f9 100644 --- a/astrid/.classpath +++ b/astrid/.classpath @@ -2,10 +2,10 @@ - + diff --git a/astrid/.project b/astrid/.project index a8cc9332f..a7616e562 100644 --- a/astrid/.project +++ b/astrid/.project @@ -36,4 +36,11 @@ org.eclipse.jdt.core.javanature org.eclipse.wst.common.project.facet.core.nature + + + astridApi + 2 + _android_astridApi/src + + diff --git a/astrid/api-src/com/todoroo/astrid/api/Addon.java b/astrid/api-src/com/todoroo/astrid/api/Addon.java deleted file mode 100644 index 98c98e7e5..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/Addon.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents an add-onn for Astrid. Users can enable or disable add-ons, - * which affect all other extension points that share the same identifier. - * - * @author Tim Su - * - */ -public class Addon implements Parcelable { - - /** - * Add-on Identifier - */ - public String addon = null; - - /** - * Plug-in Title - */ - public String title = null; - - /** - * Plug-in Author - */ - public String author = null; - - /** - * Plug-in Description - */ - public String description = null; - - /** - * Convenience constructor to generate a plug-in object - * - * @param addon - * @param title - * @param author - * @param description - */ - public Addon(String addon, String title, String author, String description) { - this.addon = addon; - this.title = title; - this.author = author; - this.description = description; - } - - // --- parcelable helpers - - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(addon); - dest.writeString(title); - dest.writeString(author); - dest.writeString(description); - } - - /** - * Parcelable creator - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - public Addon createFromParcel(Parcel source) { - return new Addon(source.readString(), source.readString(), - source.readString(), source.readString()); - } - - /** - * {@inheritDoc} - */ - public Addon[] newArray(int size) { - return new Addon[size]; - }; - }; - -} diff --git a/astrid/api-src/com/todoroo/astrid/api/AstridApiConstants.java b/astrid/api-src/com/todoroo/astrid/api/AstridApiConstants.java deleted file mode 100644 index c4a81e15e..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/AstridApiConstants.java +++ /dev/null @@ -1,242 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.widget.RemoteViews; - -/** - * Constants for interfacing with Astrid. - * - * @author Tim Su - */ -@SuppressWarnings("nls") -public class AstridApiConstants { - - // --- General Constants - - /** - * Astrid broadcast base package name - */ - public static final String PACKAGE = "com.todoroo.astrid"; - - /** - * Permission for reading tasks and receiving to GET_FILTERS intent - */ - public static final String PERMISSION_READ = PACKAGE + ".READ"; - - /** - * Permission for writing and creating tasks - */ - public static final String PERMISSION_WRITE = PACKAGE + ".WRITE"; - - // --- Content Provider - - /** - * URI to append to base content URI for making group-by queries - */ - public static final String GROUP_BY_URI = "/groupby/"; - - // --- Broadcast Extras - - /** - * Extras name for task id - */ - public static final String EXTRAS_TASK_ID = "task"; - - /** - * Extras name for a response item broadcast to astrid - */ - public static final String EXTRAS_RESPONSE = "response"; - - /** - * Extras name for plug-in identifier - */ - public static final String EXTRAS_ADDON = "addon"; - - /** - * Extras name for whether task detail request is extended - */ - public static final String EXTRAS_EXTENDED = "extended"; - - /** - * Extras name for old task due date - */ - public static final String EXTRAS_OLD_DUE_DATE= "oldDueDate"; - - /** - * Extras name for new task due date - */ - public static final String EXTRAS_NEW_DUE_DATE = "newDueDate"; - - /** - * Extras name for sync provider name - */ - public static final String EXTRAS_NAME = "name"; - - // --- Add-ons API - - /** - * Action name for broadcast intent requesting add-ons - */ - public static final String BROADCAST_REQUEST_ADDONS = PACKAGE + ".REQUEST_ADDONS"; - - /** - * Action name for broadcast intent sending add-ons back to Astrid - * @extra EXTRAS_RESPONSE an {@link Addon} object - */ - public static final String BROADCAST_SEND_ADDONS = PACKAGE + ".SEND_ADDONS"; - - // --- Filters API - - /** - * Action name for broadcast intent requesting filters - */ - public static final String BROADCAST_REQUEST_FILTERS = PACKAGE + ".REQUEST_FILTERS"; - - /** - * Action name for broadcast intent sending filters back to Astrid - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_RESPONSE an array of {@link FilterListItem}s - */ - public static final String BROADCAST_SEND_FILTERS = PACKAGE + ".SEND_FILTERS"; - - // --- Edit Controls API - - /** - * Action name for broadcast intent requesting task edit controls - * @extra EXTRAS_TASK_ID id of the task user is editing - */ - public static final String BROADCAST_REQUEST_EDIT_CONTROLS = PACKAGE + ".REQUEST_EDIT_CONTROLS"; - - /** - * Action name for broadcast intent sending task edit controls back to Astrid - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_RESPONSE a {@link RemoteViews} with your edit controls - */ - public static final String BROADCAST_SEND_EDIT_CONTROLS = PACKAGE + ".SEND_EDIT_CONTROLS"; - - // --- Task Details API - - /** - * Action name for broadcast intent requesting details for a task. - * Extended details are displayed when a user presses on a task. - * - * @extra EXTRAS_TASK_ID id of the task - * @extra EXTRAS_EXTENDED whether request is for standard or extended details - */ - public static final String BROADCAST_REQUEST_DETAILS = PACKAGE + ".REQUEST_DETAILS"; - - /** - * Action name for broadcast intent sending details back to Astrid - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_TASK_ID id of the task - * @extra EXTRAS_EXTENDED whether request is for standard or extended details - * @extra EXTRAS_RESPONSE a String - */ - public static final String BROADCAST_SEND_DETAILS = PACKAGE + ".SEND_DETAILS"; - - // --- Sync Action API - - /** - * Action name for broadcast intent requesting a listing of active - * sync actions users can activate from the menu - */ - public static final String BROADCAST_REQUEST_SYNC_ACTIONS = PACKAGE + ".REQUEST_SYNC_ACTIONS"; - - /** - * Action name for broadcast intent sending sync provider information back to Astrid - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_RESPONSE a {@link SyncAction} to invoke synchronization - */ - public static final String BROADCAST_SEND_SYNC_ACTIONS = PACKAGE + ".SEND_SYNC_ACTIONS"; - - // --- Task Actions API - - /** - * Action name for broadcast intent requesting actions for a task - * @extra EXTRAS_TASK_ID id of the task - */ - public static final String BROADCAST_REQUEST_ACTIONS = PACKAGE + ".REQUEST_ACTIONS"; - - /** - * Action name for broadcast intent sending actions back to Astrid - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_TASK_ID id of the task - * @extra EXTRAS_RESPONSE a String - */ - public static final String BROADCAST_SEND_ACTIONS = PACKAGE + ".SEND_ACTIONS"; - - // --- Task Decorations API - - /** - * Action name for broadcast intent requesting task list decorations for a task - * @extra EXTRAS_TASK_ID id of the task - */ - public static final String BROADCAST_REQUEST_DECORATIONS = PACKAGE + ".REQUEST_DECORATIONS"; - - /** - * Action name for broadcast intent sending decorations back to Astrid - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_TASK_ID id of the task - * @extra EXTRAS_RESPONSE a {@link TaskDecoration} - */ - public static final String BROADCAST_SEND_DECORATIONS = PACKAGE + ".SEND_DECORATIONS"; - - // --- Actions API - - /** - * Action name for intents to be displayed on task context menu - * @extra EXTRAS_TASK_ID id of the task - */ - public static final String ACTION_TASK_CONTEXT_MENU = PACKAGE + ".CONTEXT_MENU"; - - /** - * Action name for intents to be displayed on Astrid's task list menu - * @extra EXTRAS_ADDON your add-on identifier - * @extra EXTRAS_RESPONSE an array of {@link Intent}s - */ - public static final String ACTION_TASK_LIST_MENU = PACKAGE + ".TASK_LIST_MENU"; - - /** - * Action name for intents to be displayed in Astrid's settings. By default, - * your application will be put into the category named by your application, - * but you can add a string meta-data with name "category" to override this. - */ - public static final String ACTION_SETTINGS = PACKAGE + ".SETTINGS"; - - // --- Events API - - /** - * Action name for broadcast intent notifying add-ons that Astrid started up - */ - public static final String BROADCAST_EVENT_STARTUP = PACKAGE + ".STARTUP"; - - /** - * Action name for broadcast intent notifying Astrid task list to refresh - */ - public static final String BROADCAST_EVENT_REFRESH = PACKAGE + ".REFRESH"; - - /** - * Action name for broadcast intent notifying Astrid to clear detail cache - * because an event occurred that potentially affects all tasks (e.g. - * logging out of a sync provider). Use this call carefully, as loading - * details can degrade the performance of Astrid. - */ - public static final String BROADCAST_EVENT_FLUSH_DETAILS = PACKAGE + ".FLUSH_DETAILS"; - - /** - * Action name for broadcast intent notifying that task was completed - * @extra EXTRAS_TASK_ID id of the task - */ - public static final String BROADCAST_EVENT_TASK_COMPLETED = PACKAGE + ".TASK_COMPLETED"; - - /** - * Action name for broadcast intent notifying that task was created from repeating template - * @extra EXTRAS_TASK_ID id of the task - * @extra EXTRAS_OLD_DUE_DATE task old due date (could be 0) - * @extra EXTRAS_NEW_DUE_DATE task new due date (will not be 0) - */ - public static final String BROADCAST_EVENT_TASK_REPEATED = PACKAGE + ".TASK_REPEATED"; - -} diff --git a/astrid/api-src/com/todoroo/astrid/api/CustomFilterCriterion.java b/astrid/api-src/com/todoroo/astrid/api/CustomFilterCriterion.java deleted file mode 100644 index b37f94609..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/CustomFilterCriterion.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.content.ContentValues; -import android.graphics.Bitmap; -import android.os.Parcel; -import android.os.Parcelable; -import edu.umd.cs.findbugs.annotations.CheckForNull; - -/** - * CustomFilterCriteria allow users to build a custom filter by chaining - * together criteria - * - * @author Tim Su - * - */ -public final class CustomFilterCriterion implements Parcelable { - - /** - * Criteria Identifier. This identifier allows saved filters to be reloaded. - *

- * e.g "duedate" - */ - @CheckForNull - public String identifier; - - /** - * Criteria Title. If the title contains ?, this is replaced by the entry - * label string selected. - *

- * e.g "Due: ?" - */ - @CheckForNull - public String text; - - /** - * Criterion SQL. This query should return task id's. If this contains - * ?, it will be replaced by the entry value - *

- * Examples: - *

    - *
  • SELECT _id FROM tasks WHERE dueDate <= ? - *
  • SELECT task FROM metadata WHERE value = '?' - *
- */ - @CheckForNull - public String sql; - - /** - * Values to apply to a task when quick-adding a task from a filter - * created from this criterion. ? will be replaced with the entry value. - * For example, when a user views tasks tagged 'ABC', the - * tasks they create should also be tagged 'ABC'. If set to null, no - * additional values will be stored for a task. - */ - @CheckForNull - public ContentValues valuesForNewTasks = null; - - /** - * Array of entries for user to select from - */ - @CheckForNull - public String[] entryTitles; - - /** - * Array of entry values corresponding to entries - */ - @CheckForNull - public String[] entryValues; - - /** - * Icon for this criteria. Can be null for no bitmap - */ - @CheckForNull - public Bitmap icon; - - /** - * Criteria name. This is displayed when users are selecting a criteria - */ - @CheckForNull - public String name; - - /** - * Create a new CustomFilterCriteria object - * - * @param title - * @param sql - * @param valuesForNewTasks - * @param entryTitles - * @param entryValues - * @param icon - * @param name - */ - public CustomFilterCriterion(String identifier, String title, String sql, - ContentValues valuesForNewTasks, String[] entryTitles, - String[] entryValues, Bitmap icon, String name) { - this.identifier = identifier; - this.text = title; - this.sql = sql; - this.valuesForNewTasks = valuesForNewTasks; - this.entryTitles = entryTitles; - this.entryValues = entryValues; - this.icon = icon; - this.name = name; - } - - // --- parcelable - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(identifier); - dest.writeString(text); - dest.writeString(sql); - dest.writeParcelable(valuesForNewTasks, 0); - dest.writeStringArray(entryTitles); - dest.writeStringArray(entryValues); - dest.writeParcelable(icon, 0); - dest.writeString(name); - } - - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - public CustomFilterCriterion createFromParcel(Parcel source) { - CustomFilterCriterion item = new CustomFilterCriterion( - source.readString(), source.readString(), source.readString(), - (ContentValues)source.readParcelable(ContentValues.class.getClassLoader()), - source.createStringArray(), source.createStringArray(), - (Bitmap)source.readParcelable(Bitmap.class.getClassLoader()), - source.readString()); - return item; - } - - /** - * {@inheritDoc} - */ - public CustomFilterCriterion[] newArray(int size) { - return new CustomFilterCriterion[size]; - } - - }; - -} diff --git a/astrid/api-src/com/todoroo/astrid/api/Filter.java b/astrid/api-src/com/todoroo/astrid/api/Filter.java deleted file mode 100644 index af7eb8e97..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/Filter.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.content.ContentValues; -import android.os.Parcel; -import android.os.Parcelable; - -import com.todoroo.andlib.sql.QueryTemplate; - -import edu.umd.cs.findbugs.annotations.CheckForNull; - -/** - * A FilterListFilter allows users to display tasks that have - * something in common. - *

- * A plug-in can expose new FilterListFilters to the system by - * responding to the com.todoroo.astrid.GET_FILTERS broadcast - * intent. - * - * @author Tim Su - * - */ -public final class Filter extends FilterListItem { - - // --- constants - - /** Constant for valuesForNewTasks to indicate the value should be replaced - * with the current time as long */ - public static final long VALUE_NOW = Long.MIN_VALUE + 1; - - // --- instance variables - - /** - * Expanded title of this filter. This is displayed at the top - * of the screen when user is viewing this filter. - *

- * e.g "Tasks With Notes" - */ - @CheckForNull - public String title; - - /** - * {@link PermaSql} query for this filter. The query will be appended to the select - * statement after "SELECT fields FROM table %s". It is - * recommended that you use a {@link QueryTemplate} to construct your - * query. - *

- * Examples: - *

    - *
  • "WHERE completionDate = 0" - *
  • "INNER JOIN " + - * Constants.TABLE_METADATA + " ON metadata.task = tasks.id WHERE - * metadata.namespace = " + NAMESPACE + " AND metadata.key = 'a' AND - * metadata.value = 'b' GROUP BY tasks.id ORDER BY tasks.title" - *
- */ - @CheckForNull - public String sqlQuery; - - /** - * Values to apply to a task when quick-adding a task from this filter. - * For example, when a user views tasks tagged 'ABC', the - * tasks they create should also be tagged 'ABC'. If set to null, no - * additional values will be stored for a task. Can use {@link PermaSql} - */ - @CheckForNull - public ContentValues valuesForNewTasks = null; - - /** - * Utility constructor for creating a Filter object - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param title - * Expanded title of this filter when user is viewing this - * filter, e.g. Inbox (20 tasks) - * @param sqlQuery - * SQL query for this list (see {@link sqlQuery} for examples). - * @param valuesForNewTasks - * see {@link sqlForNewTasks} - */ - public Filter(String listingTitle, String title, - QueryTemplate sqlQuery, ContentValues valuesForNewTasks) { - this(listingTitle, title, sqlQuery == null ? null : sqlQuery.toString(), - valuesForNewTasks); - } - - /** - * Utility constructor for creating a Filter object - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param title - * Expanded title of this filter when user is viewing this - * filter, e.g. Inbox (20 tasks) - * @param sqlQuery - * SQL query for this list (see {@link sqlQuery} for examples). - * @param valuesForNewTasks - * see {@link sqlForNewTasks} - */ - public Filter(String listingTitle, String title, - String sqlQuery, ContentValues valuesForNewTasks) { - this.listingTitle = listingTitle; - this.title = title; - this.sqlQuery = sqlQuery; - this.valuesForNewTasks = valuesForNewTasks; - } - - /** - * Utility constructor - * - * @param plugin - * {@link Addon} identifier that encompasses object - */ - protected Filter() { - // do nothing - } - - // --- parcelable - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(title); - dest.writeString(sqlQuery); - dest.writeParcelable(valuesForNewTasks, 0); - } - - /** - * Parcelable Creator Object - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - public Filter createFromParcel(Parcel source) { - Filter item = new Filter(); - item.readFromParcel(source); - item.title = source.readString(); - item.sqlQuery = source.readString(); - item.valuesForNewTasks = source.readParcelable(ContentValues.class.getClassLoader()); - return item; - } - - /** - * {@inheritDoc} - */ - public Filter[] newArray(int size) { - return new Filter[size]; - } - - }; -} diff --git a/astrid/api-src/com/todoroo/astrid/api/FilterCategory.java b/astrid/api-src/com/todoroo/astrid/api/FilterCategory.java deleted file mode 100644 index 4b00695ad..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/FilterCategory.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.os.Parcel; -import android.os.Parcelable; -import edu.umd.cs.findbugs.annotations.CheckForNull; - -/** - * A FilterCategory groups common {@link Filter}s and allows - * a user to show/hide all of its children. - * - * @author Tim Su - * - */ -public class FilterCategory extends FilterListItem { - - /** - * {@link Filter}s contained by this category - */ - @CheckForNull - public Filter[] children; - - /** - * Constructor for creating a new FilterCategory - * @param listingTitle - * Title of this item as displayed on the lists page, e.g. Inbox - * @param children - * filters belonging to this category - */ - public FilterCategory(String listingTitle, Filter[] children) { - this.listingTitle = listingTitle; - this.children = children; - } - - /** - * Constructor for creating a new FilterCategory - * - * @param plugin - * {@link Addon} identifier that encompasses object - */ - protected FilterCategory() { - // - } - - // --- parcelable - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeParcelableArray(children, 0); - } - - /** - * Parcelable creator - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - /** - * {@inheritDoc} - */ - public FilterCategory createFromParcel(Parcel source) { - FilterCategory item = new FilterCategory(); - item.readFromParcel(source); - - Parcelable[] parcelableChildren = source.readParcelableArray( - FilterCategory.class.getClassLoader()); - item.children = new Filter[parcelableChildren.length]; - for(int i = 0; i < item.children.length; i++) { - if(parcelableChildren[i] instanceof FilterListItem) - item.children[i] = (Filter) parcelableChildren[i]; - else - item.children[i] = null; - } - - return item; - } - - /** - * {@inheritDoc} - */ - public FilterCategory[] newArray(int size) { - return new FilterCategory[size]; - } - - }; -} diff --git a/astrid/api-src/com/todoroo/astrid/api/FilterListHeader.java b/astrid/api-src/com/todoroo/astrid/api/FilterListHeader.java deleted file mode 100644 index 47b8d751f..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/FilterListHeader.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Section Header for Filter List - * - * @author Tim Su - * - */ -public class FilterListHeader extends FilterListItem { - - /** - * Constructor for creating a new FilterListHeader - * @param listingTitle - * @param listingIconResource - * @param priority - */ - public FilterListHeader(String listingTitle) { - this.listingTitle = listingTitle; - } - - /** - * Constructor for creating a new FilterListHeader - * - * @param plugin - * {@link Addon} identifier that encompasses object - */ - protected FilterListHeader() { - // - } - - // --- parcelable - - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - - public FilterListHeader createFromParcel(Parcel source) { - FilterListHeader item = new FilterListHeader(); - item.readFromParcel(source); - return item; - } - - public FilterListHeader[] newArray(int size) { - return new FilterListHeader[size]; - } - - }; -} diff --git a/astrid/api-src/com/todoroo/astrid/api/FilterListItem.java b/astrid/api-src/com/todoroo/astrid/api/FilterListItem.java deleted file mode 100644 index fe64b3227..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/FilterListItem.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.content.Intent; -import android.graphics.Bitmap; -import android.os.Parcel; -import android.os.Parcelable; -import edu.umd.cs.findbugs.annotations.CheckForNull; - -/** - * Represents an item displayed by Astrid's FilterListActivity - * - * @author Tim Su - * - */ -abstract public class FilterListItem implements Parcelable { - - /** - * Title of this item displayed on the Filters page - */ - @CheckForNull - public String listingTitle = null; - - /** - * Bitmap for icon used on listing page. null => no icon - */ - @CheckForNull - public Bitmap listingIcon = null; - - /** - * Text Color. 0 => default color - */ - public int color = 0; - - /** - * Context Menu labels. The context menu will be displayed when users - * long-press on this filter list item. - */ - @CheckForNull - public String contextMenuLabels[] = new String[0]; - - /** - * Context menu intents. This intent will be started when the corresponding - * content menu label is invoked. This array must be the same size as - * the contextMenuLabels array. - */ - @CheckForNull - public Intent contextMenuIntents[] = new Intent[0]; - - // --- parcelable helpers - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(listingTitle); - dest.writeParcelable(listingIcon, 0); - dest.writeInt(color); - - // write array lengths before arrays - dest.writeStringArray(contextMenuLabels); - dest.writeTypedArray(contextMenuIntents, 0); - } - - /** - * Utility method to read FilterListItem properties from a parcel. - * - * @param source - */ - public void readFromParcel(Parcel source) { - listingTitle = source.readString(); - listingIcon = source.readParcelable(Bitmap.class.getClassLoader()); - color = source.readInt(); - - contextMenuLabels = source.createStringArray(); - contextMenuIntents = source.createTypedArray(Intent.CREATOR); - } -} diff --git a/astrid/api-src/com/todoroo/astrid/api/PermaSql.java b/astrid/api-src/com/todoroo/astrid/api/PermaSql.java deleted file mode 100644 index e6723ed8b..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/PermaSql.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import java.util.Date; - -import com.todoroo.andlib.utility.DateUtilities; - -/** - * PermaSql allows for creating SQL statements that can be saved and used - * later without dates getting stale. It also allows these values to be - * used in - * - * @author Tim Su - * - */ -public final class PermaSql { - - // --- placeholder strings - - /** value to be replaced with the current time as long */ - public static final String VALUE_NOW = "NOW()"; //$NON-NLS-1$ - - /** value to be replaced by end of day as long */ - public static final String VALUE_EOD = "EOD()"; //$NON-NLS-1$ - - /** value to be replaced by end of day yesterday as long */ - public static final String VALUE_EOD_YESTERDAY = "EODY()"; //$NON-NLS-1$ - - /** value to be replaced by end of day tomorrow as long */ - public static final String VALUE_EOD_TOMORROW = "EODT()"; //$NON-NLS-1$ - - /** value to be replaced by end of day day after tomorrow as long */ - public static final String VALUE_EOD_DAY_AFTER = "EODTT()"; //$NON-NLS-1$ - - /** value to be replaced by end of day next week as long */ - public static final String VALUE_EOD_NEXT_WEEK = "EODW()"; //$NON-NLS-1$ - - /** Replace placeholder strings with actual */ - public static String replacePlaceholders(String value) { - if(value.contains(VALUE_NOW)) - value = value.replace(VALUE_NOW, Long.toString(DateUtilities.now())); - if(value.contains(VALUE_EOD) || value.contains(VALUE_EOD_DAY_AFTER) || - value.contains(VALUE_EOD_NEXT_WEEK) || value.contains(VALUE_EOD_TOMORROW) || - value.contains(VALUE_EOD_YESTERDAY)) { - Date date = new Date(); - date.setHours(23); - date.setMinutes(59); - date.setSeconds(59); - long time = date.getTime(); - value = value.replace(VALUE_EOD_YESTERDAY, Long.toString(time - DateUtilities.ONE_DAY)); - value = value.replace(VALUE_EOD, Long.toString(time)); - value = value.replace(VALUE_EOD_TOMORROW, Long.toString(time + DateUtilities.ONE_DAY)); - value = value.replace(VALUE_EOD_DAY_AFTER, Long.toString(time + 2 * DateUtilities.ONE_DAY)); - value = value.replace(VALUE_EOD_NEXT_WEEK, Long.toString(time + 7 * DateUtilities.ONE_DAY)); - } - return value; - } - -} diff --git a/astrid/api-src/com/todoroo/astrid/api/SyncAction.java b/astrid/api-src/com/todoroo/astrid/api/SyncAction.java deleted file mode 100644 index 207bfc3fe..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/SyncAction.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.app.PendingIntent; -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents an intent that can be called to perform synchronization - * - * @author Tim Su - * - */ -public class SyncAction implements Parcelable { - - /** - * Label - */ - public String label = null; - - /** - * Intent to call when invoking this operation - */ - public PendingIntent intent = null; - - /** - * Create an EditOperation object - * - * @param label - * label to display - * @param intent - * intent to invoke. {@link EXTRAS_TASK_ID} will be passed - */ - public SyncAction(String label, PendingIntent intent) { - super(); - this.label = label; - this.intent = intent; - } - - /** - * Returns the label of this action - */ - @Override - public String toString() { - return label; - } - - // --- parcelable helpers - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(label); - dest.writeParcelable(intent, 0); - } - - /** - * Parcelable creator - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - public SyncAction createFromParcel(Parcel source) { - return new SyncAction(source.readString(), (PendingIntent)source.readParcelable( - PendingIntent.class.getClassLoader())); - } - - /** - * {@inheritDoc} - */ - public SyncAction[] newArray(int size) { - return new SyncAction[size]; - }; - }; - -} diff --git a/astrid/api-src/com/todoroo/astrid/api/TaskAction.java b/astrid/api-src/com/todoroo/astrid/api/TaskAction.java deleted file mode 100644 index 75aed3b1a..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/TaskAction.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.app.PendingIntent; -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Represents an intent that can be called on a task - * - * @author Tim Su - * - */ -public class TaskAction implements Parcelable { - - /** - * Label - */ - public String text = null; - - /** - * Intent to call when invoking this operation - */ - public PendingIntent intent = null; - - /** - * Create an EditOperation object - * - * @param text - * label to display - * @param intent - * intent to invoke. {@link EXTRAS_TASK_ID} will be passed - */ - public TaskAction(String text, PendingIntent intent) { - super(); - this.text = text; - this.intent = intent; - } - - // --- parcelable helpers - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(text); - dest.writeParcelable(intent, 0); - } - - /** - * Parcelable creator - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - public TaskAction createFromParcel(Parcel source) { - return new TaskAction(source.readString(), (PendingIntent)source.readParcelable( - PendingIntent.class.getClassLoader())); - } - - /** - * {@inheritDoc} - */ - public TaskAction[] newArray(int size) { - return new TaskAction[size]; - }; - }; - -} diff --git a/astrid/api-src/com/todoroo/astrid/api/TaskDecoration.java b/astrid/api-src/com/todoroo/astrid/api/TaskDecoration.java deleted file mode 100644 index 3d12aab10..000000000 --- a/astrid/api-src/com/todoroo/astrid/api/TaskDecoration.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.api; - -import android.os.Parcel; -import android.os.Parcelable; -import android.widget.RemoteViews; -import android.widget.RemoteViews.RemoteView; -import edu.umd.cs.findbugs.annotations.CheckForNull; - -/** - * Represents a line of text displayed in the Task List - * - * @author Tim Su - * - */ -public final class TaskDecoration implements Parcelable { - - /** - * Place decoration between completion box and task title - */ - public static final int POSITION_LEFT = 0; - - /** - * Place decoration between task title and importance bar - */ - public static final int POSITION_RIGHT = 1; - - /** - * {@link RemoteView} decoration - */ - @CheckForNull - public RemoteViews decoration = null; - - /** - * Decoration position - */ - public int position = POSITION_LEFT; - - /** - * Decorated task background color. 0 is default - */ - public int color = 0; - - /** - * Creates a TaskDetail object - * @param text - * text to display - * @param color - * color to use for text. Use 0 for default color - */ - public TaskDecoration(RemoteViews decoration, int position, int color) { - this.decoration = decoration; - this.position = position; - this.color = color; - } - - // --- parcelable helpers - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeParcelable(decoration, 0); - dest.writeInt(position); - dest.writeInt(color); - } - - /** - * Parcelable creator - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - /** - * {@inheritDoc} - */ - public TaskDecoration createFromParcel(Parcel source) { - return new TaskDecoration((RemoteViews)source.readParcelable( - RemoteViews.class.getClassLoader()), - source.readInt(), source.readInt()); - } - - /** - * {@inheritDoc} - */ - public TaskDecoration[] newArray(int size) { - return new TaskDecoration[size]; - }; - }; - -} diff --git a/astrid/astrid.launch b/astrid/astrid.launch index 89ae0a49d..8df8ec564 100644 --- a/astrid/astrid.launch +++ b/astrid/astrid.launch @@ -16,11 +16,9 @@ - - diff --git a/astrid/common-src/com/todoroo/andlib/data/AbstractDatabase.java b/astrid/common-src/com/todoroo/andlib/data/AbstractDatabase.java deleted file mode 100644 index e3525a0ca..000000000 --- a/astrid/common-src/com/todoroo/andlib/data/AbstractDatabase.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright (c) 2009, Todoroo Inc - * All Rights Reserved - * http://www.todoroo.com - */ -package com.todoroo.andlib.data; - -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteDatabase.CursorFactory; -import android.database.sqlite.SQLiteOpenHelper; -import android.util.Log; - -import com.todoroo.andlib.data.Property.PropertyVisitor; -import com.todoroo.andlib.service.ContextManager; -import com.todoroo.andlib.utility.AndroidUtilities; - -/** - * AbstractDatabase is a database abstraction which wraps a SQLite database. - *

- * Users of this class are in charge of the database's lifecycle - ensuring that - * the database is open when needed and closed when usage is finished. Within an - * activity, this is typically accomplished through the onResume and onPause - * methods, though if the database is not needed for the activity's entire - * lifecycle, it can be closed earlier. - *

- * Direct querying is not recommended for type safety reasons. Instead, use one - * of the service classes to issue the request and return a {@link TodorooCursor}. - * - * @author Tim Su - * - */ -@SuppressWarnings("nls") -abstract public class AbstractDatabase { - - // --- abstract methods - - /** - * @return database name - */ - protected abstract String getName(); - - /** - * @return all tables in this database - */ - protected abstract Table[] getTables(); - - /** - * @return database version - */ - protected abstract int getVersion(); - - /** - * Called after database and tables are created. Use this method to - * create indices and perform other database maintenance - */ - protected abstract void onCreateTables(); - - /** - * Upgrades an open database from one version to the next - * @param oldVersion - * @param newVersion - * @return true if upgrade was handled, false otherwise - */ - protected abstract boolean onUpgrade(int oldVersion, int newVersion); - - // --- protected variables - - /** - * SQLiteOpenHelper that takes care of database operations - */ - protected SQLiteOpenHelper helper = null; - - /** - * Internal pointer to open database. Hides the fact that there is a - * database and a wrapper by making a single monolithic interface - */ - protected SQLiteDatabase database = null; - - // --- internal implementation - - /** - * Return the name of the table containing these models - * @param modelType - * @return - */ - public final Table getTable(Class modelType) { - for(Table table : getTables()) { - if(table.modelClass.equals(modelType)) - return table; - } - throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$ - } - - protected synchronized final void initializeHelper() { - if(helper == null) { - if(ContextManager.getContext() == null) - throw new NullPointerException("Null context creating database helper"); - helper = new DatabaseHelper(ContextManager.getContext(), - getName(), null, getVersion()); - } - } - - /** - * Open the database for writing. Must be closed afterwards. If user is - * out of disk space, database may be opened for reading instead - */ - public synchronized final void openForWriting() { - initializeHelper(); - - if(database != null && !database.isReadOnly() && database.isOpen()) - return; - - try { - database = helper.getWritableDatabase(); - } catch (NullPointerException e) { - // don't know why this happens - throw new IllegalStateException(e); - } catch (final RuntimeException original) { - Log.e("database-" + getName(), "Error opening db", - original); - try { - // provide read-only database - openForReading(); - } catch (Exception readException) { - // throw original write exception - throw original; - } - } - } - - /** - * Open the database for reading. Must be closed afterwards - */ - public synchronized final void openForReading() { - initializeHelper(); - if(database != null && database.isOpen()) - return; - database = helper.getReadableDatabase(); - } - - /** - * Close the database if it has been opened previously - */ - public synchronized final void close() { - if(database != null) { - database.close(); - } - database = null; - } - - /** - * Clear all data in database. Warning: this does what it says. Any open - * database resources will be abruptly closed. - */ - public synchronized final void clear() { - close(); - ContextManager.getContext().deleteDatabase(getName()); - } - - /** - * @return sql database. opens database if not yet open - */ - public synchronized final SQLiteDatabase getDatabase() { - if(database == null) { - AndroidUtilities.sleepDeep(300L); - openForWriting(); - } - return database; - } - - /** - * @return human-readable database name for debugging - */ - @Override - public String toString() { - return "DB:" + getName(); - } - - // --- database wrapper - - /* - * @see android.database.sqlite.SQLiteDatabase#rawQuery(String sql, String[] selectionArgs) - */ - public synchronized Cursor rawQuery(String sql, String[] selectionArgs) { - return getDatabase().rawQuery(sql, selectionArgs); - } - - /* - * @see android.database.sqlite.SQLiteDatabase#insert(String table, String nullColumnHack, ContentValues values) - */ - public synchronized long insert(String table, String nullColumnHack, ContentValues values) { - return getDatabase().insert(table, nullColumnHack, values); - } - - /* - * @see android.database.sqlite.SQLiteDatabase#delete(String table, String whereClause, String[] whereArgs) - */ - public synchronized int delete(String table, String whereClause, String[] whereArgs) { - return getDatabase().delete(table, whereClause, whereArgs); - } - - /* - * @see android.database.sqlite.SQLiteDatabase#update(String table, ContentValues values, String whereClause, String[] whereArgs) - */ - public synchronized int update(String table, ContentValues values, String whereClause, String[] whereArgs) { - return getDatabase().update(table, values, whereClause, whereArgs); - } - - // --- helper classes - - /** - * Default implementation of Astrid database helper - */ - private class DatabaseHelper extends SQLiteOpenHelper { - - public DatabaseHelper(Context context, String name, - CursorFactory factory, int version) { - super(context, name, factory, version); - } - - /** - * Called to create the database tables - */ - @Override - public synchronized void onCreate(SQLiteDatabase db) { - StringBuilder sql = new StringBuilder(); - SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor(); - - // create tables - for(Table table : getTables()) { - sql.append("CREATE TABLE IF NOT EXISTS ").append(table.name).append('('). - append(AbstractModel.ID_PROPERTY).append(" INTEGER PRIMARY KEY AUTOINCREMENT"); - for(Property property : table.getProperties()) { - if(AbstractModel.ID_PROPERTY.name.equals(property.name)) - continue; - sql.append(',').append(property.accept(sqlVisitor, null)); - } - sql.append(')'); - db.execSQL(sql.toString()); - sql.setLength(0); - } - - // post-table-creation - database = db; - onCreateTables(); - } - - /** - * Called to upgrade the database to a new version - */ - @Override - public synchronized void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - Log.w("database-" + getName(), String.format("Upgrading database from version %d to %d.", - oldVersion, newVersion)); - - database = db; - if(!AbstractDatabase.this.onUpgrade(oldVersion, newVersion)) { - // We don't know how to handle this case because someone forgot to - // implement the upgrade. We can't drop tables, we can only - // throw a nasty exception at this time - - throw new IllegalStateException("Missing database migration " + - "from " + oldVersion + " to " + newVersion); - } - } - } - - /** - * Visitor that returns SQL constructor for this property - * - * @author Tim Su - * - */ - public static class SqlConstructorVisitor implements PropertyVisitor { - - public String visitDouble(Property property, Void data) { - return String.format("%s REAL", property.name); - } - - public String visitInteger(Property property, Void data) { - return String.format("%s INTEGER", property.name); - } - - public String visitLong(Property property, Void data) { - return String.format("%s INTEGER", property.name); - } - - public String visitString(Property property, Void data) { - return String.format("%s TEXT", property.name); - } - } -} - diff --git a/astrid/common-src/com/todoroo/andlib/data/AbstractModel.java b/astrid/common-src/com/todoroo/andlib/data/AbstractModel.java deleted file mode 100644 index a17aa8b23..000000000 --- a/astrid/common-src/com/todoroo/andlib/data/AbstractModel.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright (c) 2009, Todoroo Inc - * All Rights Reserved - * http://www.todoroo.com - */ -package com.todoroo.andlib.data; - -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; - -import android.content.ContentValues; -import android.os.Parcel; -import android.os.Parcelable; - -import com.todoroo.andlib.data.Property.DoubleProperty; -import com.todoroo.andlib.data.Property.IntegerProperty; -import com.todoroo.andlib.data.Property.LongProperty; -import com.todoroo.andlib.data.Property.PropertyVisitor; - -/** - * AbstractModel represents a row in a database. - *

- * A single database can be represented by multiple AbstractModels - * corresponding to different queries that return a different set of columns. - * Each model exposes a set of properties that it contains. - * - * @author Tim Su - * - */ -public abstract class AbstractModel implements Parcelable { - - // --- static variables - - private static final ContentValuesSavingVisitor saver = new ContentValuesSavingVisitor(); - - // --- constants - - /** id property common to all models */ - protected static final String ID_PROPERTY_NAME = "_id"; //$NON-NLS-1$ - - /** id field common to all models */ - public static final IntegerProperty ID_PROPERTY = new IntegerProperty(null, ID_PROPERTY_NAME); - - /** sentinel for objects without an id */ - public static final long NO_ID = 0; - - // --- abstract methods - - /** Get the default values for this object */ - abstract public ContentValues getDefaultValues(); - - // --- data store variables and management - - /* Data Source Ordering: - * - * In order to return the best data, we want to check first what the user - * has explicitly set (setValues), then the values we have read out of - * the database (values), then defaults (getDefaultValues) - */ - - /** User set values */ - protected ContentValues setValues = null; - - /** Values from database */ - protected ContentValues values = null; - - /** Get database-read values for this object */ - public ContentValues getDatabaseValues() { - return values; - } - - /** Get the user-set values for this object */ - public ContentValues getSetValues() { - return setValues; - } - - /** Get a list of all field/value pairs merged across data sources */ - public ContentValues getMergedValues() { - ContentValues mergedValues = new ContentValues(); - - ContentValues defaultValues = getDefaultValues(); - if(defaultValues != null) - mergedValues.putAll(defaultValues); - if(values != null) - mergedValues.putAll(values); - if(setValues != null) - mergedValues.putAll(setValues); - - return mergedValues; - } - - /** - * Clear all data on this model - */ - public void clear() { - values = null; - setValues = null; - } - - /** - * Transfers all set values into values. This occurs when a task is - * saved - future saves will not need to write all the data as before. - */ - public void markSaved() { - if(values == null) - values = setValues; - else if(setValues != null) - values.putAll(setValues); - setValues = null; - } - - /** - * Use merged values to compare two models to each other. Must be of - * exactly the same class. - */ - @Override - public boolean equals(Object other) { - if(other == null || other.getClass() != getClass()) - return false; - - return getMergedValues().equals(((AbstractModel)other).getMergedValues()); - } - - @Override - public int hashCode() { - return getMergedValues().hashCode() ^ getClass().hashCode(); - } - - // --- data retrieval - - /** - * Reads all properties from the supplied cursor and store - */ - protected synchronized void readPropertiesFromCursor(TodorooCursor cursor) { - if (values == null) - values = new ContentValues(); - - // clears user-set values - setValues = null; - - for (Property property : cursor.getProperties()) { - saver.save(property, values, cursor.get(property)); - } - } - - /** - * Reads the given property. Make sure this model has this property! - */ - public synchronized TYPE getValue(Property property) { - Object value; - if(setValues != null && setValues.containsKey(property.name)) - value = setValues.get(property.name); - - else if(values != null && values.containsKey(property.name)) - value = values.get(property.name); - - else if(getDefaultValues().containsKey(property.name)) - value = getDefaultValues().get(property.name); - - else - throw new UnsupportedOperationException( - "Model Error: Did not read property " + property.name); //$NON-NLS-1$ - - // resolve properties that were retrieved with a different type than accessed - if(value instanceof String && property instanceof LongProperty) - return (TYPE) Long.valueOf((String)value); - else if(value instanceof String && property instanceof IntegerProperty) - return (TYPE) Integer.valueOf((String)value); - else if(value instanceof String && property instanceof DoubleProperty) - return (TYPE) Double.valueOf((String)value); - else if(value instanceof Integer && property instanceof LongProperty) - return (TYPE) Long.valueOf(((Number)value).longValue()); - return (TYPE) value; - } - - /** - * Utility method to get the identifier of the model, if it exists. - * - * @return {@value #NO_ID} if this model was not added to the database - */ - abstract public long getId(); - - protected long getIdHelper(LongProperty id) { - if(setValues != null && setValues.containsKey(id.name)) - return setValues.getAsLong(id.name); - else if(values != null && values.containsKey(id.name)) - return values.getAsLong(id.name); - else - return NO_ID; - } - - public void setId(long id) { - if (setValues == null) - setValues = new ContentValues(); - - if(id == NO_ID) - setValues.remove(ID_PROPERTY_NAME); - else - setValues.put(ID_PROPERTY_NAME, id); - } - - /** - * @return true if this model has found Jesus (i.e. the database) - */ - public boolean isSaved() { - return getId() != NO_ID; - } - - /** - * @param property - * @return true if setValues or values contains this property - */ - public boolean containsValue(Property property) { - if(setValues != null && setValues.containsKey(property.name)) - return true; - if(values != null && values.containsKey(property.name)) - return true; - return false; - } - - /** - * @param property - * @return true if setValues or values contains this property, and the value - * stored is not null - */ - public boolean containsNonNullValue(Property property) { - if(setValues != null && setValues.containsKey(property.name)) - return setValues.get(property.name) != null; - if(values != null && values.containsKey(property.name)) - return values.get(property.name) != null; - return false; - } - - // --- data storage - - /** - * Check whether the user has changed this property value and it should be - * stored for saving in the database - */ - protected synchronized boolean shouldSaveValue( - Property property, TYPE newValue) { - - // we've already decided to save it, so overwrite old value - if (setValues.containsKey(property.name)) - return true; - - // values contains this key, we should check it out - if(values != null && values.containsKey(property.name)) { - TYPE value = getValue(property); - if (value == null) { - if (newValue == null) - return false; - } else if (value.equals(newValue)) - return false; - } - - // otherwise, good to save - return true; - } - - /** - * Sets the given property. Make sure this model has this property! - */ - public synchronized void setValue(Property property, - TYPE value) { - if (setValues == null) - setValues = new ContentValues(); - if (!shouldSaveValue(property, value)) - return; - - saver.save(property, setValues, value); - } - - /** - * Merges content values with those coming from another source - */ - public synchronized void mergeWith(ContentValues other) { - if (setValues == null) - setValues = new ContentValues(); - setValues.putAll(other); - } - - /** - * Clear the key for the given property - * @param property - */ - public synchronized void clearValue(Property property) { - if(setValues != null && setValues.containsKey(property.name)) - setValues.remove(property.name); - else if(values != null && values.containsKey(property.name)) - values.remove(property.name); - else if(getDefaultValues().containsKey(property.name)) - throw new IllegalArgumentException("Property has a default value"); //$NON-NLS-1$ - } - - // --- property management - - /** - * Looks inside the given class and finds all declared properties - */ - protected static Property[] generateProperties(Class cls) { - ArrayList> properties = new ArrayList>(); - if(cls.getSuperclass() != AbstractModel.class) - properties.addAll(Arrays.asList(generateProperties( - (Class) cls.getSuperclass()))); - - // a property is public, static & extends Property - for(Field field : cls.getFields()) { - if((field.getModifiers() & Modifier.STATIC) == 0) - continue; - if(!Property.class.isAssignableFrom(field.getType())) - continue; - try { - properties.add((Property) field.get(null)); - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - return properties.toArray(new Property[properties.size()]); - } - - /** - * Visitor that saves a value into a content values store - * - * @author Tim Su - * - */ - public static class ContentValuesSavingVisitor implements PropertyVisitor { - - private ContentValues store; - - public synchronized void save(Property property, ContentValues newStore, Object value) { - this.store = newStore; - - // we don't allow null values, as they indicate unset properties - // when the database was written - - if(value != null) - property.accept(this, value); - } - - public Void visitDouble(Property property, Object value) { - store.put(property.name, (Double) value); - return null; - } - - public Void visitInteger(Property property, Object value) { - store.put(property.name, (Integer) value); - return null; - } - - public Void visitLong(Property property, Object value) { - store.put(property.name, (Long) value); - return null; - } - - public Void visitString(Property property, Object value) { - store.put(property.name, (String) value); - return null; - } - } - - // --- parcelable helpers - - /** - * {@inheritDoc} - */ - public int describeContents() { - return 0; - } - - /** - * {@inheritDoc} - */ - public void writeToParcel(Parcel dest, int flags) { - dest.writeParcelable(setValues, 0); - dest.writeParcelable(values, 0); - } - - /** - * In addition to overriding this class, model classes should create - * a static final variable named "CREATOR" in order to satisfy the - * requirements of the Parcelable interface. - */ - abstract protected Parcelable.Creator getCreator(); - - /** - * Parcelable creator helper - */ - protected static final class ModelCreator - implements Parcelable.Creator { - - private final Class cls; - - public ModelCreator(Class cls) { - super(); - this.cls = cls; - } - - /** - * {@inheritDoc} - */ - public TYPE createFromParcel(Parcel source) { - TYPE model; - try { - model = cls.newInstance(); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } - model.setValues = source.readParcelable(ContentValues.class.getClassLoader()); - model.values = source.readParcelable(ContentValues.class.getClassLoader()); - return model; - } - - /** - * {@inheritDoc} - */ - public TYPE[] newArray(int size) { - return (TYPE[]) Array.newInstance(cls, size); - }; - }; - -} diff --git a/astrid/common-src/com/todoroo/andlib/data/GenericDao.java b/astrid/common-src/com/todoroo/andlib/data/GenericDao.java deleted file mode 100644 index c8308df0e..000000000 --- a/astrid/common-src/com/todoroo/andlib/data/GenericDao.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2009, Todoroo Inc - * All Rights Reserved - * http://www.todoroo.com - */ -package com.todoroo.andlib.data; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import android.content.ContentValues; -import android.database.Cursor; -import android.util.Log; - -import com.todoroo.andlib.sql.Criterion; -import com.todoroo.andlib.sql.Query; -import com.todoroo.astrid.utility.Constants; - - - -/** - * Abstract data access object - * - * @author Tim Su - * - */ -public class GenericDao { - - private final Class modelClass; - - private Table table; - - private AbstractDatabase database; - - public GenericDao(Class modelClass) { - this.modelClass = modelClass; - } - - public GenericDao(Class modelClass, AbstractDatabase database) { - this.modelClass = modelClass; - setDatabase(database); - } - - /** Gets table associated with this DAO */ - public Table getTable() { - return table; - } - - /** - * Sets database accessed by this DAO. Used for dependency-injected - * initialization by child classes and unit tests - * - * @param database - */ - public void setDatabase(AbstractDatabase database) { - if(database == this.database) - return; - this.database = database; - table = database.getTable(modelClass); - } - - // --- dao methods - - /** - * Construct a query with SQL DSL objects - * - * @param query - * @return - */ - public TodorooCursor query(Query query) { - query.from(table); - if(Constants.DEBUG) - Log.i("SQL-" + modelClass.getSimpleName(), query.toString()); //$NON-NLS-1$ - Cursor cursor = database.rawQuery(query.toString(), null); - return new TodorooCursor(cursor, query.getFields()); - } - - /** - * Construct a query with raw SQL - * - * @param properties - * @param selection - * @param selectionArgs - * @return - */ - public TodorooCursor rawQuery(String selection, String[] selectionArgs, Property... properties) { - String[] fields = new String[properties.length]; - for(int i = 0; i < properties.length; i++) - fields[i] = properties[i].name; - return new TodorooCursor(database.getDatabase().query(table.name, - fields, selection, selectionArgs, null, null, null), - properties); - } - - /** - * Returns object corresponding to the given identifier - * - * @param database - * @param table - * name of table - * @param properties - * properties to read - * @param id - * id of item - * @return null if no item found - */ - public TYPE fetch(long id, Property... properties) { - TodorooCursor cursor = fetchItem(id, properties); - try { - if (cursor.getCount() == 0) - return null; - Constructor constructor = modelClass.getConstructor(TodorooCursor.class); - return constructor.newInstance(cursor); - } catch (SecurityException e) { - throw new RuntimeException(e); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } finally { - cursor.close(); - } - } - - /** - * Delete the given id - * - * @param database - * @param id - * @return true if delete was successful - */ - public boolean delete(long id) { - return database.delete(table.name, - AbstractModel.ID_PROPERTY.eq(id).toString(), null) > 0; - } - - /** - * Delete all matching a clause - * @param database - * @param where - * @return # of deleted items - */ - public int deleteWhere(Criterion where) { - return database.delete(table.name, - where.toString(), null); - } - - /** - * Save the given object to the database. Creates a new object if - * model id property has not been set - * - * @return true on success. - */ - public boolean persist(TYPE item) { - if (item.getId() == AbstractModel.NO_ID) { - return createNew(item); - } else { - ContentValues values = item.getSetValues(); - - if (values.size() == 0) // nothing changed - return true; - - return saveExisting(item); - } - } - - /** - * Creates the given item. - * - * @param database - * @param table - * table name - * @param item - * item model - * @return returns true on success. - */ - public boolean createNew(TYPE item) { - long newRow = database.insert(table.name, - AbstractModel.ID_PROPERTY.name, item.getMergedValues()); - boolean result = newRow >= 0; - if(result) { - item.markSaved(); - item.setId(newRow); - } - return result; - } - - /** - * Saves the given item. Will not create a new item! - * - * @param database - * @param table - * table name - * @param item - * item model - * @return returns true on success. - */ - public boolean saveExisting(TYPE item) { - ContentValues values = item.getSetValues(); - if(values == null || values.size() == 0) // nothing changed - return true; - boolean result = database.update(table.name, values, - AbstractModel.ID_PROPERTY.eq(item.getId()).toString(), null) > 0; - if(result) - item.markSaved(); - return result; - } - - /** - * Updates multiple rows of the database based on model set values - * - * @param item - * item model - * @param criterion - * @return returns true on success. - */ - public int updateMultiple(ContentValues values, Criterion criterion) { - if(values.size() == 0) // nothing changed - return 0; - return database.update(table.name, values, criterion.toString(), null); - } - - // --- helper methods - - - /** - * Returns cursor to object corresponding to the given identifier - * - * @param database - * @param table - * name of table - * @param properties - * properties to read - * @param id - * id of item - * @return - */ - protected TodorooCursor fetchItem(long id, Property... properties) { - TodorooCursor cursor = query( - Query.select(properties).where(AbstractModel.ID_PROPERTY.eq(id))); - cursor.moveToFirst(); - return new TodorooCursor(cursor, properties); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/data/Property.java b/astrid/common-src/com/todoroo/andlib/data/Property.java deleted file mode 100644 index 9a4665bf2..000000000 --- a/astrid/common-src/com/todoroo/andlib/data/Property.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2009, Todoroo Inc - * All Rights Reserved - * http://www.todoroo.com - */ -package com.todoroo.andlib.data; - -import com.todoroo.andlib.sql.Field; - -/** - * Property represents a typed column in a database. - * - * Within a given database row, the parameter may not exist, in which case the - * value is null, it may be of an incorrect type, in which case an exception is - * thrown, or the correct type, in which case the value is returned. - * - * @author Tim Su - * - * @param - * a database supported type, such as String or Integer - */ -@SuppressWarnings("nls") -public abstract class Property extends Field implements Cloneable { - - // --- implementation - - /** The database table name this property */ - public final Table table; - - /** The database column name for this property */ - public final String name; - - /** - * Create a property by table and column name. Uses the default property - * expression which is derived from default table name - */ - protected Property(Table table, String columnName) { - this(table, columnName, (table == null) ? (columnName) : (table.name + "." + columnName)); - } - - /** - * Create a property by table and column name, manually specifying an - * expression to use in SQL - */ - protected Property(Table table, String columnName, String expression) { - super(expression); - this.table = table; - this.name = columnName; - } - - /** - * Accept a visitor - */ - abstract public RETURN accept( - PropertyVisitor visitor, PARAMETER data); - - /** - * Return a clone of this property - */ - @Override - public Property clone() { - try { - return (Property) super.clone(); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } - - // --- helper classes and interfaces - - /** - * Visitor interface for property classes - * - * @author Tim Su - * - */ - public interface PropertyVisitor { - public RETURN visitInteger(Property property, PARAMETER data); - - public RETURN visitLong(Property property, PARAMETER data); - - public RETURN visitDouble(Property property, PARAMETER data); - - public RETURN visitString(Property property, PARAMETER data); - } - - // --- children - - /** - * Integer property type. See {@link Property} - * - * @author Tim Su - * - */ - public static class IntegerProperty extends Property { - - public IntegerProperty(Table table, String name) { - super(table, name); - } - - protected IntegerProperty(Table table, String name, String expression) { - super(table, name, expression); - } - - @Override - public RETURN accept( - PropertyVisitor visitor, PARAMETER data) { - return visitor.visitInteger(this, data); - } - } - - /** - * String property type. See {@link Property} - * - * @author Tim Su - * - */ - public static class StringProperty extends Property { - - public StringProperty(Table table, String name) { - super(table, name); - } - - protected StringProperty(Table table, String name, String expression) { - super(table, name, expression); - } - - @Override - public RETURN accept( - PropertyVisitor visitor, PARAMETER data) { - return visitor.visitString(this, data); - } - } - - /** - * Double property type. See {@link Property} - * - * @author Tim Su - * - */ - public static class DoubleProperty extends Property { - - public DoubleProperty(Table table, String name) { - super(table, name); - } - - protected DoubleProperty(Table table, String name, String expression) { - super(table, name, expression); - } - - - @Override - public RETURN accept( - PropertyVisitor visitor, PARAMETER data) { - return visitor.visitDouble(this, data); - } - } - - /** - * Long property type. See {@link Property} - * - * @author Tim Su - * - */ - public static class LongProperty extends Property { - - public LongProperty(Table table, String name) { - super(table, name); - } - - protected LongProperty(Table table, String name, String expression) { - super(table, name, expression); - } - - @Override - public RETURN accept( - PropertyVisitor visitor, PARAMETER data) { - return visitor.visitLong(this, data); - } - } - - // --- pseudo-properties - - /** Runs a SQL function and returns the result as a string */ - public static class StringFunctionProperty extends StringProperty { - public StringFunctionProperty(String function, String columnName) { - super(null, columnName, function); - alias = columnName; - } - } - - /** Runs a SQL function and returns the result as a string */ - public static class IntegerFunctionProperty extends IntegerProperty { - public IntegerFunctionProperty(String function, String columnName) { - super(null, columnName, function); - alias = columnName; - } - } - - /** Counting in aggregated tables. Returns the result of COUNT(1) */ - public static final class CountProperty extends IntegerFunctionProperty { - public CountProperty() { - super("COUNT(1)", "count"); - } - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/data/Table.java b/astrid/common-src/com/todoroo/andlib/data/Table.java deleted file mode 100644 index 3d2cb8880..000000000 --- a/astrid/common-src/com/todoroo/andlib/data/Table.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.todoroo.andlib.data; - -import com.todoroo.andlib.sql.Field; -import com.todoroo.andlib.sql.SqlTable; - -/** - * Table class. Most fields are final, so methods such as as will - * clone the table when it returns. - * - * @author Tim Su - * - */ -public final class Table extends SqlTable { - public final String name; - public final Class modelClass; - - public Table(String name, Class modelClass) { - this(name, modelClass, null); - } - - public Table(String name, Class modelClass, String alias) { - super(name); - this.name = name; - this.alias = alias; - this.modelClass = modelClass; - } - - /** - * Reads a list of properties from model class by reflection - * @return property array - */ - @SuppressWarnings("nls") - public Property[] getProperties() { - try { - return (Property[])modelClass.getField("PROPERTIES").get(null); - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (SecurityException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (NoSuchFieldException e) { - throw new RuntimeException(e); - } - } - - // --- for sql-dsl - - /** - * Create a new join table based on this table, but with an alias - */ - @Override - public Table as(String newAlias) { - return new Table(name, modelClass, newAlias); - } - - /** - * Create a field object based on the given property - * @param property - * @return - */ - @SuppressWarnings("nls") - public Field field(Property property) { - if(alias != null) - return Field.field(alias + "." + property.name); - return Field.field(name + "." + property.name); - } -} \ No newline at end of file diff --git a/astrid/common-src/com/todoroo/andlib/data/TodorooCursor.java b/astrid/common-src/com/todoroo/andlib/data/TodorooCursor.java deleted file mode 100644 index 4ef2c8ccc..000000000 --- a/astrid/common-src/com/todoroo/andlib/data/TodorooCursor.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.data; - -import java.util.WeakHashMap; - -import android.database.Cursor; -import android.database.CursorWrapper; - -import com.todoroo.andlib.data.Property.PropertyVisitor; - -/** - * AstridCursor wraps a cursor and allows users to query for individual - * {@link Property} types or read an entire {@link AbstractModel} from - * a database row. - * - * @author Tim Su - * - * @param a model type that is returned by this cursor - */ -public class TodorooCursor extends CursorWrapper { - - /** Properties read by this cursor */ - private final Property[] properties; - - /** Weakly cache field name to column id references for this cursor. - * Because it's a weak hash map, entire keys can be discarded by GC */ - private final WeakHashMap columnIndexCache; - - /** Property reading visitor */ - private static final CursorReadingVisitor reader = new CursorReadingVisitor(); - - /** - * Create an AstridCursor from the supplied {@link Cursor} - * object. - * - * @param cursor - * @param properties properties read from this cursor - */ - public TodorooCursor(Cursor cursor, Property[] properties) { - super(cursor); - - this.properties = properties; - columnIndexCache = new WeakHashMap(); - } - - /** - * Get the value for the given property on the underlying {@link Cursor} - * - * @param type to return - * @param property to retrieve - * @return - */ - public PROPERTY_TYPE get(Property property) { - return (PROPERTY_TYPE)property.accept(reader, this); - } - - /** - * Gets entire property list - * @return - */ - public Property[] getProperties() { - return properties; - } - - /** - * Use cache to get the column index for the given field name - */ - public synchronized int getColumnIndexFromCache(String field) { - Integer index = columnIndexCache.get(field); - if(index == null) { - index = getColumnIndexOrThrow(field); - columnIndexCache.put(field, index); - } - - return index; - } - - /** - * Visitor that reads the given property from a cursor - * - * @author Tim Su - * - */ - public static class CursorReadingVisitor implements PropertyVisitor> { - - public Object visitDouble(Property property, - TodorooCursor cursor) { - return cursor.getDouble(cursor.getColumnIndexFromCache(property.name)); - } - - public Object visitInteger(Property property, - TodorooCursor cursor) { - return cursor.getInt(cursor.getColumnIndexFromCache(property.name)); - } - - public Object visitLong(Property property, TodorooCursor cursor) { - return cursor.getLong(cursor.getColumnIndexFromCache(property.name)); - } - - public Object visitString(Property property, - TodorooCursor cursor) { - return cursor.getString(cursor.getColumnIndexFromCache(property.name)); - } - - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/AbstractDependencyInjector.java b/astrid/common-src/com/todoroo/andlib/service/AbstractDependencyInjector.java deleted file mode 100644 index fbf4fdfb8..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/AbstractDependencyInjector.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.todoroo.andlib.service; - -import java.lang.reflect.Field; - -/** - * A Dependency Injector knows how to inject certain dependencies based - * on the field that is passed in. - * - * @author Tim Su - * - */ -public interface AbstractDependencyInjector { - - /** - * Gets the injected object for this field. If implementing class does not - * know how to handle this dependency, it should return null - * - * @param object - * object to perform dependency injection on - * @param field - * field tagged with {link Autowired} annotation - * @return object to assign to this field, or null - */ - abstract Object getInjection(Object object, Field field); - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/Autowired.java b/astrid/common-src/com/todoroo/andlib/service/Autowired.java deleted file mode 100644 index 3b0b1c765..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/Autowired.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.todoroo.andlib.service; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Autowired is an annotation that tells the dependency injector to - * set up the class as appropriate. - * - * @author Tim Su - * - */ -@Target({ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Autowired { - // -} diff --git a/astrid/common-src/com/todoroo/andlib/service/ContextManager.java b/astrid/common-src/com/todoroo/andlib/service/ContextManager.java deleted file mode 100644 index fb8c0b6c9..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/ContextManager.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.service; - -import android.content.Context; -import android.content.res.Resources; - -/** - * Singleton class to manage current application context - * b - * @author Tim Su - * - */ -public final class ContextManager { - - /** - * Global application context - */ - private static Context context = null; - - /** - * Sets the global context - * @param context - */ - public static void setContext(Context context) { - ContextManager.context = context; - } - - /** - * Gets the global context - */ - public static Context getContext() { - return context; - } - - /** - * Convenience method to read a string from the resources - * - * @param resid - * @param parameters - * @return - */ - public static String getString(int resId, Object... formatArgs) { - return context.getString(resId, formatArgs); - } - - /** - * Convenience method to read resources - * - * @return - */ - public static Resources getResources() { - return context.getResources(); - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/DependencyInjectionService.java b/astrid/common-src/com/todoroo/andlib/service/DependencyInjectionService.java deleted file mode 100644 index 361d16a1e..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/DependencyInjectionService.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.todoroo.andlib.service; - -import java.lang.reflect.Field; -import java.util.Arrays; - -import android.util.Log; - -import com.todoroo.astrid.utility.Constants; - - - -/** - * Simple Dependency Injection Service for Android. - *

- * Add dependency injectors to the injector chain, then invoke this method - * against classes you wish to perform dependency injection for. - *

- * All errors encountered are handled as warnings, so if dependency injection - * seems to be failing, check the logs for more information. - * - * @author Tim Su - * - */ -public class DependencyInjectionService { - - private static final String QUALIFIED_PACKAGE = "com.t"; //$NON-NLS-1$ - - /** - * Dependency injectors. Use getters and setters to modify this list - */ - private AbstractDependencyInjector[] injectors = {}; - - /** - * Perform dependency injection in the caller object - * - * @param caller - * object to perform DI on - */ - @SuppressWarnings("nls") - public void inject(Object caller) { - - // Traverse through class and all parent classes, looking for - // fields declared with the @Autowired annotation and using - // dependency injection to set them as appropriate - - Class cls = caller.getClass(); - while(cls != null) { - String packageName = cls.getPackage().getName(); - if(!packageName.startsWith(QUALIFIED_PACKAGE)) - break; - - for(Field field : cls.getDeclaredFields()) { - if(field.getAnnotation(Autowired.class) != null) { - field.setAccessible(true); - try { - handleField(caller, field); - } catch (IllegalStateException e) { - throw new RuntimeException(String.format("Unable to set field '%s' of type '%s'", - field.getName(), field.getType()), e); - } catch (IllegalArgumentException e) { - throw new RuntimeException(String.format("Unable to set field '%s' of type '%s'", - field.getName(), field.getType()), e); - } catch (IllegalAccessException e) { - throw new RuntimeException(String.format("Unable to set field '%s' of type '%s'", - field.getName(), field.getType()), e); - } - } - } - - cls = cls.getSuperclass(); - } - } - - /** - * This method returns the appropriate dependency object based on the type - * that this autowired field accepts - * - * @param caller - * calling object - * @param field - * field to inject - */ - @SuppressWarnings("nls") - private synchronized void handleField(Object caller, Field field) - throws IllegalStateException, IllegalArgumentException, - IllegalAccessException { - - if(field.getType().isPrimitive()) - throw new IllegalStateException(String.format( - "Tried to dependency-inject primative field '%s' of type '%s'", - field.getName(), field.getType())); - - // field has already been processed, ignore - if (field.get(caller) != null) { - return; - } - - for (AbstractDependencyInjector injector : injectors) { - Object injection = injector.getInjection(caller, field); - if (injection != null) { - if(Constants.DEBUG) - Log.d("INJECTOR", injector + ":" + caller + "." + field.getName() + " => " + injection); - field.set(caller, injection); - return; - } - } - - throw new IllegalStateException( - String.format("No dependency injector found for autowired " + - "field '%s' in class '%s'. Injectors: %s", - field.getName(), caller.getClass().getName(), - Arrays.asList(getInjectors()))); - } - - // --- static methods - - private static DependencyInjectionService instance = null; - - DependencyInjectionService() { - // prevent instantiation - } - - /** - * Gets the singleton instance of the dependency injection service. - * @return - */ - public synchronized static DependencyInjectionService getInstance() { - if(instance == null) - instance = new DependencyInjectionService(); - return instance; - } - - /** - * Gets the array of installed injectors - * @return - */ - public synchronized AbstractDependencyInjector[] getInjectors() { - return injectors; - } - - /** - * Sets the array of installed injectors - * @param injectors - */ - public synchronized void setInjectors(AbstractDependencyInjector[] injectors) { - this.injectors = injectors; - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/ExceptionService.java b/astrid/common-src/com/todoroo/andlib/service/ExceptionService.java deleted file mode 100644 index 471af5b5a..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/ExceptionService.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.todoroo.andlib.service; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.net.SocketTimeoutException; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.Context; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.util.Log; - -/** - * Exception handling utility class - reports and logs errors - * - * @author Tim Su - * - */ -public class ExceptionService { - - @Autowired - public ErrorReporter[] errorReporters; - - @Autowired - public Integer errorDialogTitleResource; - - @Autowired - public Integer errorDialogBodyGeneric; - - @Autowired - public Integer errorDialogBodyNullError; - - @Autowired - public Integer errorDialogBodySocketTimeout; - - public ExceptionService() { - DependencyInjectionService.getInstance().inject(this); - } - - /** - * Report the error via registered error handlers - * - * @param name Internal error name. Not displayed to user - * @param error Exception encountered. Message will be displayed to user - */ - public void reportError(String name, Throwable error) { - if(errorReporters == null) - return; - - for(ErrorReporter reporter : errorReporters) - reporter.handleError(name, error); - } - - /** - * Display error dialog if context is activity and report error - * - * @param context Application Context - * @param name Internal error name. Not displayed to user - * @param error Exception encountered. Message will be displayed to user - */ - public void displayAndReportError(final Context context, String name, Throwable error) { - if(context instanceof Activity) { - final String messageToDisplay; - - // pretty up the message when displaying to user - if(error == null) - messageToDisplay = context.getString(errorDialogBodyNullError); - else if(error instanceof SocketTimeoutException) - messageToDisplay = context.getString(errorDialogBodySocketTimeout); - else - messageToDisplay = context.getString(errorDialogBodyGeneric, error); - - ((Activity)context).runOnUiThread(new Runnable() { - public void run() { - try { - new AlertDialog.Builder(context) - .setTitle(errorDialogTitleResource) - .setMessage(messageToDisplay) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, null) - .show(); - } catch (Exception e) { - // suppress errors during dialog creation - } - } - }); - } - - reportError(name, error); - } - - /** - * Error reporter interface - * - * @author Tim Su - * - */ - public interface ErrorReporter { - public void handleError(String name, Throwable error); - } - - /** - * AndroidLogReporter reports errors to LogCat - * - * @author Tim Su - * - */ - public static class AndroidLogReporter implements ErrorReporter { - - /** - * Report the error to the logs - * - * @param name - * @param error - */ - public void handleError(String name, Throwable error) { - String tag = null; - if(ContextManager.getContext() != null) { - PackageManager pm = ContextManager.getContext().getPackageManager(); - try { - String appName = pm.getApplicationInfo(ContextManager.getContext(). - getPackageName(), 0).name; - tag = appName + "-" + name; //$NON-NLS-1$ - } catch (NameNotFoundException e) { - // give up - } - } - - if(tag == null) - tag = "unknown-" + name; //$NON-NLS-1$ - - if(error == null) - Log.e(tag, "Exception: " + name); //$NON-NLS-1$ - else - Log.e(tag, error.toString(), error); - } - } - - /** - * Uncaught exception handler uses the exception utilities class to - * report errors - * - * @author Tim Su - * - */ - public static class TodorooUncaughtExceptionHandler implements UncaughtExceptionHandler { - private final UncaughtExceptionHandler defaultUEH; - - @Autowired - protected ExceptionService exceptionService; - - public TodorooUncaughtExceptionHandler() { - defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); - DependencyInjectionService.getInstance().inject(this); - } - - public void uncaughtException(Thread thread, Throwable ex) { - if(exceptionService != null) - exceptionService.reportError("uncaught", ex); //$NON-NLS-1$ - defaultUEH.uncaughtException(thread, ex); - } - } - -} - diff --git a/astrid/common-src/com/todoroo/andlib/service/HttpErrorException.java b/astrid/common-src/com/todoroo/andlib/service/HttpErrorException.java deleted file mode 100644 index c2c46fc03..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/HttpErrorException.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.todoroo.andlib.service; - -import java.io.IOException; - -public class HttpErrorException extends IOException { - - private static final long serialVersionUID = 5373340422464657279L; - - public HttpErrorException(int code, String message) { - super(String.format("%d %s", code, message)); //$NON-NLS-1$ - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/HttpRestClient.java b/astrid/common-src/com/todoroo/andlib/service/HttpRestClient.java deleted file mode 100644 index 7c7493b4d..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/HttpRestClient.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.todoroo.andlib.service; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.ref.WeakReference; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; - -import android.util.Log; - -/** - * RestClient allows Android to consume web requests. - *

- * Portions by Praeda: - * http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple - * -restful-client-at-android/ - * - * @author Tim Su - * - */ -public class HttpRestClient implements RestClient { - - private static final int HTTP_UNAVAILABLE_END = 599; - private static final int HTTP_UNAVAILABLE_START = 500; - private static final int HTTP_OK = 200; - - private static final int TIMEOUT_MILLIS = 30000; - - private static WeakReference httpClient = null; - - @Autowired - private Boolean debug; - - public HttpRestClient() { - DependencyInjectionService.getInstance().inject(this); - } - - private static String convertStreamToString(InputStream is) { - /* - * To convert the InputStream to String we use the - * BufferedReader.readLine() method. We iterate until the BufferedReader - * return null which means there's no more data to read. Each line will - * appended to a StringBuilder and returned as String. - */ - BufferedReader reader = new BufferedReader(new InputStreamReader(is), 16384); - StringBuilder sb = new StringBuilder(); - - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb.append(line + "\n"); //$NON-NLS-1$ - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - return sb.toString(); - } - - private synchronized static HttpClient getClient() { - if (httpClient == null || httpClient.get() == null) { - HttpParams params = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MILLIS); - HttpConnectionParams.setSoTimeout(params, TIMEOUT_MILLIS); - HttpClient client = new DefaultHttpClient(params); - httpClient = new WeakReference(client); - return client; - } else { - return httpClient.get(); - } - } - - private String processHttpResponse(HttpResponse response) throws IOException { - int statusCode = response.getStatusLine().getStatusCode(); - if(statusCode >= HTTP_UNAVAILABLE_START && statusCode <= HTTP_UNAVAILABLE_END) { - throw new HttpUnavailableException(); - } else if(statusCode != HTTP_OK) { - throw new HttpErrorException(response.getStatusLine().getStatusCode(), - response.getStatusLine().getReasonPhrase()); - } - - HttpEntity entity = response.getEntity(); - - if (entity != null) { - InputStream contentStream = entity.getContent(); - try { - return convertStreamToString(contentStream); - } finally { - contentStream.close(); - } - } - - return null; - } - - /** - * Issue an HTTP GET for the given URL, return the response - * - * @param url url with url-encoded params - * @return response, or null if there was no response - * @throws IOException - */ - public synchronized String get(String url) throws IOException { - if(debug) - Log.d("http-rest-client-get", url); //$NON-NLS-1$ - - try { - HttpGet httpGet = new HttpGet(url); - HttpResponse response = getClient().execute(httpGet); - - return processHttpResponse(response); - } catch (IOException e) { - throw e; - } catch (Exception e) { - IOException ioException = new IOException(e.getMessage()); - ioException.initCause(e); - throw ioException; - } - } - - /** - * Issue an HTTP POST for the given URL, return the response - * - * @param url - * @param data - * url-encoded data - * @throws IOException - */ - public synchronized String post(String url, String data) throws IOException { - if(debug) - Log.d("http-rest-client-post", url + " | " + data); //$NON-NLS-1$ //$NON-NLS-2$ - - try { - HttpPost httpPost = new HttpPost(url); - httpPost.setEntity(new StringEntity(data)); - HttpResponse response = getClient().execute(httpPost); - - return processHttpResponse(response); - } catch (IOException e) { - throw e; - } catch (Exception e) { - IOException ioException = new IOException(e.getMessage()); - ioException.initCause(e); - throw ioException; - } - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/HttpUnavailableException.java b/astrid/common-src/com/todoroo/andlib/service/HttpUnavailableException.java deleted file mode 100644 index ac6e8c860..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/HttpUnavailableException.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.todoroo.andlib.service; - -import java.io.IOException; - -/** - * Exception displayed when a 500 error is received on an HTTP invocation - * - * @author Tim Su - * - */ -public class HttpUnavailableException extends IOException { - - private static final long serialVersionUID = 5373340422464657279L; - - public HttpUnavailableException() { - super(); - DependencyInjectionService.getInstance().inject(this); - } - - @Override - public String getMessage() { - return "Sorry, our servers are experiencing some issues. Please try again later!"; //$NON-NLS-1$ // FIXME - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/service/NotificationManager.java b/astrid/common-src/com/todoroo/andlib/service/NotificationManager.java deleted file mode 100644 index 56e229eb7..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/NotificationManager.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.andlib.service; - -import android.app.Notification; -import android.content.Context; - -/** - * Notification Manager stub - * - * @author timsu - * - */ -public interface NotificationManager { - - public void cancel(int id); - - public void cancelAll(); - - public void notify(int id, Notification notification); - - /** - * Instantiation of notification manager that passes through to - * Android's notification manager - * - * @author timsu - * - */ - public static class AndroidNotificationManager implements NotificationManager { - private final android.app.NotificationManager nm; - public AndroidNotificationManager(Context context) { - nm = (android.app.NotificationManager) - context.getSystemService(Context.NOTIFICATION_SERVICE); - } - - public void cancel(int id) { - nm.cancel(id); - } - - public void cancelAll() { - nm.cancelAll(); - } - - public void notify(int id, Notification notification) { - nm.notify(id, notification); - } - } -} diff --git a/astrid/common-src/com/todoroo/andlib/service/RestClient.java b/astrid/common-src/com/todoroo/andlib/service/RestClient.java deleted file mode 100644 index 0bf35e461..000000000 --- a/astrid/common-src/com/todoroo/andlib/service/RestClient.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.todoroo.andlib.service; - -import java.io.IOException; - -/** - * RestClient stub invokes the HTML requests as desired - * - * @author Tim Su - * - */ -public interface RestClient { - public String get(String url) throws IOException; - public String post(String url, String data) throws IOException; -} \ No newline at end of file diff --git a/astrid/common-src/com/todoroo/andlib/sql/Criterion.java b/astrid/common-src/com/todoroo/andlib/sql/Criterion.java deleted file mode 100644 index 5acdc6535..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Criterion.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.AND; -import static com.todoroo.andlib.sql.SqlConstants.EXISTS; -import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.NOT; -import static com.todoroo.andlib.sql.SqlConstants.OR; -import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -public abstract class Criterion { - protected final Operator operator; - - Criterion(Operator operator) { - this.operator = operator; - } - - public static Criterion all = new Criterion(Operator.exists) { - @Override - protected void populate(StringBuilder sb) { - sb.append(1); - } - }; - - public static Criterion none = new Criterion(Operator.exists) { - @Override - protected void populate(StringBuilder sb) { - sb.append(0); - } - }; - - public static Criterion and(final Criterion criterion, final Criterion... criterions) { - return new Criterion(Operator.and) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(criterion); - for (Criterion c : criterions) { - sb.append(SPACE).append(AND).append(SPACE).append(c); - } - } - }; - } - - public static Criterion or(final Criterion criterion, final Criterion... criterions) { - return new Criterion(Operator.or) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(criterion); - for (Criterion c : criterions) { - sb.append(SPACE).append(OR).append(SPACE).append(c.toString()); - } - } - }; - } - - public static Criterion exists(final Query query) { - return new Criterion(Operator.exists) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(EXISTS).append(SPACE).append(LEFT_PARENTHESIS).append(query).append(RIGHT_PARENTHESIS); - } - }; - } - - public static Criterion not(final Criterion criterion) { - return new Criterion(Operator.not) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(NOT).append(SPACE); - criterion.populate(sb); - } - }; - } - - protected abstract void populate(StringBuilder sb); - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(LEFT_PARENTHESIS); - populate(builder); - builder.append(RIGHT_PARENTHESIS); - return builder.toString(); - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/DBObject.java b/astrid/common-src/com/todoroo/andlib/sql/DBObject.java deleted file mode 100644 index b29c6550b..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/DBObject.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.AS; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -public abstract class DBObject> implements Cloneable { - protected String alias; - protected final String expression; - - protected DBObject(String expression){ - this.expression = expression; - } - - public T as(String newAlias) { - try { - T clone = (T) clone(); - clone.alias = newAlias; - return clone; - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } - - public boolean hasAlias() { - return alias != null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - DBObject dbObject = (DBObject) o; - - if (alias != null ? !alias.equals(dbObject.alias) : dbObject.alias != null) return false; - if (expression != null ? !expression.equals(dbObject.expression) : dbObject.expression != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = alias != null ? alias.hashCode() : 0; - result = 31 * result + (expression != null ? expression.hashCode() : 0); - return result; - } - - @Override - public final String toString() { - if (hasAlias()) { - return alias; - } - return expression; - } - - public final String toStringInSelect() { - StringBuilder sb = new StringBuilder(expression); - if (hasAlias()) { - sb.append(SPACE).append(AS).append(SPACE).append(alias); - } else { - int pos = expression.indexOf('.'); - if(pos > 0) - sb.append(SPACE).append(AS).append(SPACE).append(expression.substring(pos + 1)); - } - return sb.toString(); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/EqCriterion.java b/astrid/common-src/com/todoroo/andlib/sql/EqCriterion.java deleted file mode 100644 index 8873069cb..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/EqCriterion.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.todoroo.andlib.sql; - -public class EqCriterion extends UnaryCriterion { - EqCriterion(Field field, Object value) { - super(field, Operator.eq, value); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/Field.java b/astrid/common-src/com/todoroo/andlib/sql/Field.java deleted file mode 100644 index 822118d54..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Field.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.AND; -import static com.todoroo.andlib.sql.SqlConstants.BETWEEN; -import static com.todoroo.andlib.sql.SqlConstants.COMMA; -import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -public class Field extends DBObject { - - protected Field(String expression) { - super(expression); - } - - public static Field field(String expression) { - return new Field(expression); - } - - public Criterion eq(Object value) { - if(value == null) - return UnaryCriterion.isNull(this); - return UnaryCriterion.eq(this, value); - } - - public Criterion neq(Object value) { - if(value == null) - return UnaryCriterion.isNotNull(this); - return UnaryCriterion.neq(this, value); - } - - public Criterion gt(Object value) { - return UnaryCriterion.gt(this, value); - } - - public Criterion lt(final Object value) { - return UnaryCriterion.lt(this, value); - } - - public Criterion lte(final Object value) { - return UnaryCriterion.lte(this, value); - } - - public Criterion isNull() { - return UnaryCriterion.isNull(this); - } - - public Criterion isNotNull() { - return UnaryCriterion.isNotNull(this); - } - - public Criterion between(final Object lower, final Object upper) { - final Field field = this; - return new Criterion(null) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(field).append(SPACE).append(BETWEEN).append(SPACE).append(lower).append(SPACE).append(AND) - .append(SPACE).append(upper); - } - }; - } - - public Criterion like(final String value) { - return UnaryCriterion.like(this, value); - } - - public Criterion like(String value, String escape) { - return UnaryCriterion.like(this, value, escape); - } - - - public Criterion in(final T... value) { - final Field field = this; - return new Criterion(Operator.in) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(field).append(SPACE).append(Operator.in).append(SPACE).append(LEFT_PARENTHESIS).append(SPACE); - for (T t : value) { - sb.append(t.toString()).append(COMMA); - } - sb.deleteCharAt(sb.length() - 1).append(RIGHT_PARENTHESIS); - } - }; - } - - public Criterion in(final Query query) { - final Field field = this; - return new Criterion(Operator.in) { - - @Override - protected void populate(StringBuilder sb) { - sb.append(field).append(SPACE).append(Operator.in).append(SPACE).append(LEFT_PARENTHESIS).append(query) - .append(RIGHT_PARENTHESIS); - } - }; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/Functions.java b/astrid/common-src/com/todoroo/andlib/sql/Functions.java deleted file mode 100644 index fb4f964ee..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Functions.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.todoroo.andlib.sql; - - -@SuppressWarnings("nls") -public final class Functions { - - public static String caseStatement(Criterion when, Object ifTrue, Object ifFalse) { - return new StringBuilder("(CASE WHEN "). - append(when.toString()).append(" THEN ").append(value(ifTrue)). - append(" ELSE ").append(value(ifFalse)).append(" END)").toString(); - } - - private static String value(Object value) { - return value.toString(); - } - - public static Field upper(Field title) { - return new Field("UPPER(" + title.toString() + ")"); - } - - /** - * @return SQL now (in milliseconds) - */ - public static Field now() { - return new Field("(strftime('%s','now')*1000)"); - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/GroupBy.java b/astrid/common-src/com/todoroo/andlib/sql/GroupBy.java deleted file mode 100644 index df8c19df9..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/GroupBy.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.todoroo.andlib.sql; - -import java.util.ArrayList; -import java.util.List; - -public class GroupBy { - private List fields = new ArrayList(); - - public static GroupBy groupBy(Field field) { - GroupBy groupBy = new GroupBy(); - groupBy.fields.add(field); - return groupBy; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/Join.java b/astrid/common-src/com/todoroo/andlib/sql/Join.java deleted file mode 100644 index ac8a479f2..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Join.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.JOIN; -import static com.todoroo.andlib.sql.SqlConstants.ON; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -public class Join { - private final SqlTable joinTable; - private final JoinType joinType; - private final Criterion[] criterions; - - private Join(SqlTable table, JoinType joinType, Criterion... criterions) { - joinTable = table; - this.joinType = joinType; - this.criterions = criterions; - } - - public static Join inner(SqlTable expression, Criterion... criterions) { - return new Join(expression, JoinType.INNER, criterions); - } - - public static Join left(SqlTable table, Criterion... criterions) { - return new Join(table, JoinType.LEFT, criterions); - } - - public static Join right(SqlTable table, Criterion... criterions) { - return new Join(table, JoinType.RIGHT, criterions); - } - - public static Join out(SqlTable table, Criterion... criterions) { - return new Join(table, JoinType.OUT, criterions); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(joinType).append(SPACE).append(JOIN).append(SPACE).append(joinTable).append(SPACE).append(ON); - for (Criterion criterion : criterions) { - sb.append(SPACE).append(criterion); - } - return sb.toString(); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/JoinType.java b/astrid/common-src/com/todoroo/andlib/sql/JoinType.java deleted file mode 100644 index 84e632b53..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/JoinType.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.todoroo.andlib.sql; - -public enum JoinType { - INNER, LEFT, RIGHT, OUT -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/Operator.java b/astrid/common-src/com/todoroo/andlib/sql/Operator.java deleted file mode 100644 index 5581987d4..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Operator.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -import java.util.HashMap; -import java.util.Map; - -@SuppressWarnings("nls") -public final class Operator { - - private final String operator; - public static final Operator eq = new Operator("="); - public static final Operator neq = new Operator("<>"); - public static final Operator isNull = new Operator("IS NULL"); - public static final Operator isNotNull = new Operator("IS NOT NULL"); - public static final Operator gt = new Operator(">"); - public static final Operator lt = new Operator("<"); - public static final Operator gte = new Operator(">="); - public static final Operator lte = new Operator("<="); - public static final Operator and = new Operator("AND"); - public static final Operator or = new Operator("OR"); - public static final Operator not = new Operator("NOT"); - public static final Operator exists = new Operator("EXISTS"); - public static final Operator like = new Operator("LIKE"); - public static final Operator in = new Operator("IN"); - - private static final Map contraryRegistry = new HashMap(); - - static { - contraryRegistry.put(eq, neq); - contraryRegistry.put(neq, eq); - contraryRegistry.put(isNull, isNotNull); - contraryRegistry.put(isNotNull, isNull); - contraryRegistry.put(gt, lte); - contraryRegistry.put(lte, gt); - contraryRegistry.put(lt, gte); - contraryRegistry.put(gte, lt); - } - - private Operator(String operator) { - this.operator = operator; - } - - public Operator getContrary() { - if(!contraryRegistry.containsKey(this)){ - Operator opposite = new Operator(not.toString() + SPACE + this.toString()); - contraryRegistry.put(this, opposite); - contraryRegistry.put(opposite, this); - } - return contraryRegistry.get(this); - } - - @Override - public String toString() { - return this.operator.toString(); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/Order.java b/astrid/common-src/com/todoroo/andlib/sql/Order.java deleted file mode 100644 index 0cb91a670..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Order.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -public class Order { - private final Object expression; - private final OrderType orderType; - - private Order(Object expression) { - this(expression, OrderType.ASC); - } - - private Order(Object expression, OrderType orderType) { - this.expression = expression; - this.orderType = orderType; - } - - public static Order asc(Object expression) { - return new Order(expression); - } - - public static Order desc(Object expression) { - return new Order(expression, OrderType.DESC); - } - - @Override - public String toString() { - return expression + SPACE + orderType; - } - - public Order reverse() { - if(orderType == OrderType.ASC) - return new Order(expression, OrderType.DESC); - else - return new Order(expression, OrderType.ASC); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/OrderType.java b/astrid/common-src/com/todoroo/andlib/sql/OrderType.java deleted file mode 100644 index d84742e28..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/OrderType.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.todoroo.andlib.sql; - -public enum OrderType { - DESC, ASC -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/Query.java b/astrid/common-src/com/todoroo/andlib/sql/Query.java deleted file mode 100644 index b0a612def..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/Query.java +++ /dev/null @@ -1,205 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.ALL; -import static com.todoroo.andlib.sql.SqlConstants.COMMA; -import static com.todoroo.andlib.sql.SqlConstants.FROM; -import static com.todoroo.andlib.sql.SqlConstants.GROUP_BY; -import static com.todoroo.andlib.sql.SqlConstants.LEFT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.LIMIT; -import static com.todoroo.andlib.sql.SqlConstants.ORDER_BY; -import static com.todoroo.andlib.sql.SqlConstants.RIGHT_PARENTHESIS; -import static com.todoroo.andlib.sql.SqlConstants.SELECT; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; -import static com.todoroo.andlib.sql.SqlConstants.WHERE; -import static com.todoroo.andlib.sql.SqlTable.table; -import static java.util.Arrays.asList; - -import java.util.ArrayList; - -import com.todoroo.andlib.data.Property; - -public final class Query { - - private SqlTable table; - private String queryTemplate = null; - private final ArrayList criterions = new ArrayList(); - private final ArrayList fields = new ArrayList(); - private final ArrayList joins = new ArrayList(); - private final ArrayList groupBies = new ArrayList(); - private final ArrayList orders = new ArrayList(); - private final ArrayList havings = new ArrayList(); - private int limits = -1; - - private Query(Field... fields) { - this.fields.addAll(asList(fields)); - } - - public static Query select(Field... fields) { - return new Query(fields); - } - - public Query from(SqlTable fromTable) { - this.table = fromTable; - return this; - } - - public Query join(Join... join) { - joins.addAll(asList(join)); - return this; - } - - public Query where(Criterion criterion) { - criterions.add(criterion); - return this; - } - - public Query groupBy(Field... groupBy) { - groupBies.addAll(asList(groupBy)); - return this; - } - - public Query orderBy(Order... order) { - orders.addAll(asList(order)); - return this; - } - - public Query limit(int limit) { - limits = limit; - return this; - } - - public Query appendSelectFields(Property... selectFields) { - this.fields.addAll(asList(selectFields)); - return this; - } - - @Override - public boolean equals(Object o) { - return this == o || !(o == null || getClass() != o.getClass()) && this.toString().equals(o.toString()); - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - - @Override - public String toString() { - StringBuilder sql = new StringBuilder(); - visitSelectClause(sql); - visitFromClause(sql); - - visitJoinClause(sql); - if(queryTemplate == null) { - visitWhereClause(sql); - visitGroupByClause(sql); - visitOrderByClause(sql); - visitLimitClause(sql); - } else { - if(groupBies.size() > 0 || orders.size() > 0 || - havings.size() > 0) - throw new IllegalStateException("Can't have extras AND query template"); //$NON-NLS-1$ - sql.append(queryTemplate); - } - - return sql.toString(); - } - - private void visitOrderByClause(StringBuilder sql) { - if (orders.isEmpty()) { - return; - } - sql.append(ORDER_BY); - for (Order order : orders) { - sql.append(SPACE).append(order).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - } - - @SuppressWarnings("nls") - private void visitGroupByClause(StringBuilder sql) { - if (groupBies.isEmpty()) { - return; - } - sql.append(GROUP_BY); - for (Field groupBy : groupBies) { - sql.append(SPACE).append(groupBy).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - if (havings.isEmpty()) { - return; - } - sql.append("HAVING"); - for (Criterion havingCriterion : havings) { - sql.append(SPACE).append(havingCriterion).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - } - - private void visitWhereClause(StringBuilder sql) { - if (criterions.isEmpty()) { - return; - } - sql.append(WHERE); - for (Criterion criterion : criterions) { - sql.append(SPACE).append(criterion).append(SPACE); - } - } - - private void visitJoinClause(StringBuilder sql) { - for (Join join : joins) { - sql.append(join).append(SPACE); - } - } - - private void visitFromClause(StringBuilder sql) { - if (table == null) { - return; - } - sql.append(FROM).append(SPACE).append(table).append(SPACE); - } - - private void visitSelectClause(StringBuilder sql) { - sql.append(SELECT).append(SPACE); - if (fields.isEmpty()) { - sql.append(ALL).append(SPACE); - return; - } - for (Field field : fields) { - sql.append(field.toStringInSelect()).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - } - - private void visitLimitClause(StringBuilder sql) { - if(limits > -1) - sql.append(LIMIT).append(SPACE).append(limits).append(SPACE); - } - - public SqlTable as(String alias) { - return table(LEFT_PARENTHESIS + this.toString() + RIGHT_PARENTHESIS).as(alias); - } - - public Query having(Criterion criterion) { - this.havings.add(criterion); - return this; - } - - /** - * Gets a list of fields returned by this query - * @return - */ - public Property[] getFields() { - return fields.toArray(new Property[fields.size()]); - } - - /** - * Add the SQL query template (comes after the "from") - * @param sqlQuery - * @return - */ - public Query withQueryTemplate(String template) { - queryTemplate = template; - return this; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/QueryTemplate.java b/astrid/common-src/com/todoroo/andlib/sql/QueryTemplate.java deleted file mode 100644 index abd506f18..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/QueryTemplate.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.COMMA; -import static com.todoroo.andlib.sql.SqlConstants.GROUP_BY; -import static com.todoroo.andlib.sql.SqlConstants.LIMIT; -import static com.todoroo.andlib.sql.SqlConstants.ORDER_BY; -import static com.todoroo.andlib.sql.SqlConstants.SPACE; -import static com.todoroo.andlib.sql.SqlConstants.WHERE; -import static java.util.Arrays.asList; - -import java.util.ArrayList; - -/** - * Query Template returns a bunch of criteria that allows a query to be - * constructed - * - * @author Tim Su - * - */ -public final class QueryTemplate { - - private final ArrayList criterions = new ArrayList(); - private final ArrayList joins = new ArrayList(); - private final ArrayList groupBies = new ArrayList(); - private final ArrayList orders = new ArrayList(); - private final ArrayList havings = new ArrayList(); - private Integer limit = null; - - public QueryTemplate join(Join... join) { - joins.addAll(asList(join)); - return this; - } - - public QueryTemplate where(Criterion criterion) { - criterions.add(criterion); - return this; - } - - public QueryTemplate groupBy(Field... groupBy) { - groupBies.addAll(asList(groupBy)); - return this; - } - - public QueryTemplate orderBy(Order... order) { - orders.addAll(asList(order)); - return this; - } - - @Override - public String toString() { - StringBuilder sql = new StringBuilder(); - visitJoinClause(sql); - visitWhereClause(sql); - visitGroupByClause(sql); - visitOrderByClause(sql); - if(limit != null) - sql.append(LIMIT).append(SPACE).append(limit); - return sql.toString(); - } - - private void visitOrderByClause(StringBuilder sql) { - if (orders.isEmpty()) { - return; - } - sql.append(ORDER_BY); - for (Order order : orders) { - sql.append(SPACE).append(order).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - } - - @SuppressWarnings("nls") - private void visitGroupByClause(StringBuilder sql) { - if (groupBies.isEmpty()) { - return; - } - sql.append(GROUP_BY); - for (Field groupBy : groupBies) { - sql.append(SPACE).append(groupBy).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - if (havings.isEmpty()) { - return; - } - sql.append("HAVING"); - for (Criterion havingCriterion : havings) { - sql.append(SPACE).append(havingCriterion).append(COMMA); - } - sql.deleteCharAt(sql.length() - 1).append(SPACE); - } - - private void visitWhereClause(StringBuilder sql) { - if (criterions.isEmpty()) { - return; - } - sql.append(WHERE); - for (Criterion criterion : criterions) { - sql.append(SPACE).append(criterion).append(SPACE); - } - } - - private void visitJoinClause(StringBuilder sql) { - for (Join join : joins) { - sql.append(join).append(SPACE); - } - } - - public QueryTemplate having(Criterion criterion) { - this.havings.add(criterion); - return this; - } - - public QueryTemplate limit(int limitValue) { - this.limit = limitValue; - return this; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/SqlConstants.java b/astrid/common-src/com/todoroo/andlib/sql/SqlConstants.java deleted file mode 100644 index bb61d9580..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/SqlConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.todoroo.andlib.sql; - -@SuppressWarnings("nls") -public final class SqlConstants { - static final String SELECT = "SELECT"; - static final String SPACE = " "; - static final String AS = "AS"; - static final String COMMA = ","; - static final String FROM = "FROM"; - static final String ON = "ON"; - static final String JOIN = "JOIN"; - static final String ALL = "*"; - static final String LEFT_PARENTHESIS = "("; - static final String RIGHT_PARENTHESIS = ")"; - static final String AND = "AND"; - static final String BETWEEN = "BETWEEN"; - static final String LIKE = "LIKE"; - static final String OR = "OR"; - static final String ORDER_BY = "ORDER BY"; - static final String GROUP_BY = "GROUP BY"; - static final String WHERE = "WHERE"; - public static final String EXISTS = "EXISTS"; - public static final String NOT = "NOT"; - public static final String LIMIT = "LIMIT"; -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/SqlTable.java b/astrid/common-src/com/todoroo/andlib/sql/SqlTable.java deleted file mode 100644 index 4205ce617..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/SqlTable.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.todoroo.andlib.sql; - -public class SqlTable extends DBObject { - - protected SqlTable(String expression) { - super(expression); - } - - public static SqlTable table(String table) { - return new SqlTable(table); - } - - @SuppressWarnings("nls") - protected String fieldExpression(String fieldName) { - if (hasAlias()) { - return alias + "." + fieldName; - } - return expression+"."+fieldName; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/sql/UnaryCriterion.java b/astrid/common-src/com/todoroo/andlib/sql/UnaryCriterion.java deleted file mode 100644 index 0dcff2bd5..000000000 --- a/astrid/common-src/com/todoroo/andlib/sql/UnaryCriterion.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.todoroo.andlib.sql; - -import static com.todoroo.andlib.sql.SqlConstants.SPACE; - -public class UnaryCriterion extends Criterion { - protected final Field expression; - protected final Object value; - - UnaryCriterion(Field expression, Operator operator, Object value) { - super(operator); - this.expression = expression; - this.value = value; - } - - @Override - protected void populate(StringBuilder sb) { - beforePopulateOperator(sb); - populateOperator(sb); - afterPopulateOperator(sb); - } - - public static Criterion eq(Field expression, Object value) { - return new UnaryCriterion(expression, Operator.eq, value); - } - - protected void beforePopulateOperator(StringBuilder sb) { - sb.append(expression); - } - - protected void populateOperator(StringBuilder sb) { - sb.append(operator); - } - - @SuppressWarnings("nls") - protected void afterPopulateOperator(StringBuilder sb) { - if(value == null) - return; - else if(value instanceof String) - sb.append("'").append(sanitize((String) value)).append("'"); - else - sb.append(value); - } - - /** - * Sanitize the given input for SQL - * @param input - * @return - */ - @SuppressWarnings("nls") - public static String sanitize(String input) { - return input.replace("'", "''"); - } - - public static Criterion neq(Field field, Object value) { - return new UnaryCriterion(field, Operator.neq, value); - } - - public static Criterion gt(Field field, Object value) { - return new UnaryCriterion(field, Operator.gt, value); - } - - public static Criterion lt(Field field, Object value) { - return new UnaryCriterion(field, Operator.lt, value); - } - - public static Criterion lte(Field field, Object value) { - return new UnaryCriterion(field, Operator.lte, value); - } - - public static Criterion isNull(Field field) { - return new UnaryCriterion(field, Operator.isNull, null) { - @Override - protected void populateOperator(StringBuilder sb) { - sb.append(SPACE).append(operator); - } - }; - } - - public static Criterion isNotNull(Field field) { - return new UnaryCriterion(field, Operator.isNotNull, null) { - @Override - protected void populateOperator(StringBuilder sb) { - sb.append(SPACE).append(operator); - } - }; - } - - public static Criterion like(Field field, String value) { - return new UnaryCriterion(field, Operator.like, value) { - @Override - protected void populateOperator(StringBuilder sb) { - sb.append(SPACE).append(operator).append(SPACE); - } - }; - } - - public static Criterion like(Field field, String value, final String escape) { - return new UnaryCriterion(field, Operator.like, value) { - @Override - protected void populateOperator(StringBuilder sb) { - sb.append(SPACE).append(operator).append(SPACE); - } - @SuppressWarnings("nls") - @Override - protected void afterPopulateOperator(StringBuilder sb) { - super.afterPopulateOperator(sb); - sb.append(SPACE).append("ESCAPE").append(" '").append(sanitize(escape)).append("'"); - } - }; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/utility/AndroidUtilities.java b/astrid/common-src/com/todoroo/andlib/utility/AndroidUtilities.java deleted file mode 100644 index 8ab1674a0..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/AndroidUtilities.java +++ /dev/null @@ -1,385 +0,0 @@ -package com.todoroo.andlib.utility; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Map.Entry; - -import android.app.Activity; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.NetworkInfo.State; -import android.text.InputType; -import android.util.Log; -import android.view.MotionEvent; -import android.view.View; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.todoroo.andlib.service.Autowired; -import com.todoroo.andlib.service.DependencyInjectionService; -import com.todoroo.andlib.service.ExceptionService; - -/** - * Android Utility Classes - * - * @author Tim Su - * - */ -public class AndroidUtilities { - - public static final String SEPARATOR_ESCAPE = "!PIPE!"; //$NON-NLS-1$ - public static final String SERIALIZATION_SEPARATOR = "|"; //$NON-NLS-1$ - - // --- utility methods - - private static class ExceptionHelper { - @Autowired - public ExceptionService exceptionService; - - public ExceptionHelper() { - DependencyInjectionService.getInstance().inject(this); - } - } - - /** Suppress virtual keyboard until user's first tap */ - public static void suppressVirtualKeyboard(final TextView editor) { - final int inputType = editor.getInputType(); - editor.setInputType(InputType.TYPE_NULL); - editor.setOnTouchListener(new OnTouchListener() { - public boolean onTouch(View v, MotionEvent event) { - editor.setInputType(inputType); - editor.setOnTouchListener(null); - return false; - } - }); - } - - /** - * @return true if we're connected to the internet - */ - public static boolean isConnected(Context context) { - ConnectivityManager manager = (ConnectivityManager) - context.getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo info = manager.getActiveNetworkInfo(); - if (info == null) - return false; - if (info.getState() != State.CONNECTED) - return false; - return true; - } - - /** Fetch the image specified by the given url */ - public static Bitmap fetchImage(URL url) throws IOException { - InputStream is = null; - try { - URLConnection conn = url.openConnection(); - conn.connect(); - is = conn.getInputStream(); - BufferedInputStream bis = new BufferedInputStream(is, 16384); - try { - Bitmap bitmap = BitmapFactory.decodeStream(bis); - return bitmap; - } finally { - bis.close(); - } - } finally { - if(is != null) - is.close(); - } - } - - /** - * Start the given intent, handling security exceptions if they arise - * - * @param context - * @param intent - * @param request request code. if negative, no request. - */ - public static void startExternalIntent(Context context, Intent intent, int request) { - try { - if(request > -1 && context instanceof Activity) - ((Activity)context).startActivityForResult(intent, request); - else - context.startActivity(intent); - } catch (Exception e) { - ExceptionHelper helper = new ExceptionHelper(); - helper.exceptionService.displayAndReportError(context, - "start-external-intent-" + intent.toString(), //$NON-NLS-1$ - e); - } - } - - /** - * Start the given intent, handling security exceptions if they arise - * - * @param activity - * @param intent - * @param requestCode - */ - public static void startExternalIntentForResult( - Activity activity, Intent intent, int requestCode) { - try { - activity.startActivityForResult(intent, requestCode); - } catch (SecurityException e) { - ExceptionHelper helper = new ExceptionHelper(); - helper.exceptionService.displayAndReportError(activity, - "start-external-intent-" + intent.toString(), //$NON-NLS-1$ - e); - } - } - - /** - * Put an arbitrary object into a {@link ContentValues} - * @param target - * @param key - * @param value - */ - public static void putInto(ContentValues target, String key, Object value) { - if(value instanceof String) - target.put(key, (String) value); - else if(value instanceof Long) - target.put(key, (Long) value); - else if(value instanceof Integer) - target.put(key, (Integer) value); - else if(value instanceof Double) - target.put(key, (Double) value); - else - throw new UnsupportedOperationException("Could not handle type " + //$NON-NLS-1$ - value.getClass()); - } - - /** - * Rips apart a content value into two string arrays, keys and value - */ - public static String[][] contentValuesToStringArrays(ContentValues source) { - String[][] result = new String[2][source.size()]; - int i = 0; - for(Entry entry : source.valueSet()) { - result[0][i] = entry.getKey(); - result[1][i++] = entry.getValue().toString(); - } - return result; - } - - /** - * Return index of value in array - * @param array array to search - * @param value value to look for - * @return - */ - public static int indexOf(TYPE[] array, TYPE value) { - for(int i = 0; i < array.length; i++) - if(array[i].equals(value)) - return i; - return -1; - } - - /** - * Serializes a content value into a string - */ - public static String contentValuesToSerializedString(ContentValues source) { - StringBuilder result = new StringBuilder(); - for(Entry entry : source.valueSet()) { - result.append(entry.getKey().replace(SERIALIZATION_SEPARATOR, SEPARATOR_ESCAPE)).append( - SERIALIZATION_SEPARATOR); - Object value = entry.getValue(); - if(value instanceof Integer) - result.append('i').append(value); - else if(value instanceof Double) - result.append('d').append(value); - else if(value instanceof Long) - result.append('l').append(value); - else if(value instanceof String) - result.append('s').append(value.toString()); - else - throw new UnsupportedOperationException(value.getClass().toString()); - result.append(SERIALIZATION_SEPARATOR); - } - return result.toString(); - } - - /** - * Turn ContentValues into a string - * @param string - * @return - */ - public static ContentValues contentValuesFromSerializedString(String string) { - if(string == null) - return new ContentValues(); - - String[] pairs = string.split("\\" + SERIALIZATION_SEPARATOR); //$NON-NLS-1$ - ContentValues result = new ContentValues(); - for(int i = 0; i < pairs.length; i += 2) { - String key = pairs[i].replaceAll(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR); - String value = pairs[i+1].substring(1); - switch(pairs[i+1].charAt(0)) { - case 'i': - result.put(key, Integer.parseInt(value)); - break; - case 'd': - result.put(key, Double.parseDouble(value)); - break; - case 'l': - result.put(key, Long.parseLong(value)); - break; - case 's': - result.put(key, value.replace(SEPARATOR_ESCAPE, SERIALIZATION_SEPARATOR)); - break; - } - } - return result; - } - - /** - * Turn ContentValues into a string - * @param string - * @return - */ - @SuppressWarnings("nls") - public static ContentValues contentValuesFromString(String string) { - if(string == null) - return null; - - String[] pairs = string.split("="); - ContentValues result = new ContentValues(); - String key = null; - for(int i = 0; i < pairs.length; i++) { - String newKey = null; - int lastSpace = pairs[i].lastIndexOf(' '); - if(lastSpace != -1) { - newKey = pairs[i].substring(lastSpace + 1); - pairs[i] = pairs[i].substring(0, lastSpace); - } else { - newKey = pairs[i]; - } - if(key != null) - result.put(key.trim(), pairs[i].trim()); - key = newKey; - } - return result; - } - - /** - * Returns true if a and b or null or a.equals(b) - * @param a - * @param b - * @return - */ - public static boolean equals(Object a, Object b) { - if(a == null && b == null) - return true; - if(a == null) - return false; - return a.equals(b); - } - - /** - * Copy a file from one place to another - * - * @param in - * @param out - * @throws Exception - */ - public static void copyFile(File in, File out) throws Exception { - FileInputStream fis = new FileInputStream(in); - FileOutputStream fos = new FileOutputStream(out); - try { - byte[] buf = new byte[1024]; - int i = 0; - while ((i = fis.read(buf)) != -1) { - fos.write(buf, 0, i); - } - } catch (Exception e) { - throw e; - } finally { - fis.close(); - fos.close(); - } - } - - /** - * Find a child view of a certain type - * @param view - * @param type - * @return first view (by DFS) if found, or null if none - */ - public static TYPE findViewByType(View view, Class type) { - if(view == null) - return null; - if(type.isInstance(view)) - return (TYPE) view; - if(view instanceof ViewGroup) { - ViewGroup group = (ViewGroup) view; - for(int i = 0; i < group.getChildCount(); i++) { - TYPE v = findViewByType(group.getChildAt(i), type); - if(v != null) - return v; - } - } - return null; - } - - /** - * @return Android SDK version as an integer. Works on all versions - */ - public static int getSdkVersion() { - return Integer.parseInt(android.os.Build.VERSION.SDK); - } - - /** - * Copy databases to a given folder. Useful for debugging - * @param folder - */ - public static void copyDatabases(Context context, String folder) { - File folderFile = new File(folder); - if(!folderFile.exists()) - folderFile.mkdir(); - for(String db : context.databaseList()) { - File dbFile = context.getDatabasePath(db); - try { - copyFile(dbFile, new File(folderFile.getAbsolutePath() + - File.separator + db)); - } catch (Exception e) { - Log.e("ERROR", "ERROR COPYING DB " + db, e); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - - /** - * Sort files by date so the newest file is on top - * @param files - */ - public static void sortFilesByDateDesc(File[] files) { - Arrays.sort(files, new Comparator() { - public int compare(File o1, File o2) { - return Long.valueOf(o2.lastModified()).compareTo(Long.valueOf(o1.lastModified())); - } - }); - } - - /** - * Sleep, ignoring interruption - * @param l - */ - public static void sleepDeep(long l) { - try { - Thread.sleep(l); - } catch (InterruptedException e) { - // ignore - } - } -} diff --git a/astrid/common-src/com/todoroo/andlib/utility/Base64.java b/astrid/common-src/com/todoroo/andlib/utility/Base64.java deleted file mode 100644 index 497b1f2c1..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/Base64.java +++ /dev/null @@ -1,2052 +0,0 @@ -package com.todoroo.andlib.utility; - -/** - *

Encodes and decodes to and from Base64 notation.

- *

Homepage: http://iharder.net/base64.

- * - *

Example:

- * - * String encoded = Base64.encode( myByteArray ); - *
- * byte[] myByteArray = Base64.decode( encoded ); - * - *

The options parameter, which appears in a few places, is used to pass - * several pieces of information to the encoder. In the "higher level" methods such as - * encodeBytes( bytes, options ) the options parameter can be used to indicate such - * things as first gzipping the bytes before encoding them, not inserting linefeeds, - * and encoding using the URL-safe and Ordered dialects.

- * - *

Note, according to RFC3548, - * Section 2.1, implementations should not add line feeds unless explicitly told - * to do so. I've got Base64 set to this behavior now, although earlier versions - * broke lines by default.

- * - *

The constants defined in Base64 can be OR-ed together to combine options, so you - * might make a call like this:

- * - * String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES ); - *

to compress the data before encoding it and then making the output have newline characters.

- *

Also...

- * String encoded = Base64.encodeBytes( crazyString.getBytes() ); - * - * - * - *

- * Change Log: - *

- *
    - *
  • v2.3.4 - Fixed bug when working with gzipped streams whereby flushing - * the Base64.OutputStream closed the Base64 encoding (by padding with equals - * signs) too soon. Also added an option to suppress the automatic decoding - * of gzipped streams. Also added experimental support for specifying a - * class loader when using the - * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} - * method.
  • - *
  • v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java - * footprint with its CharEncoders and so forth. Fixed some javadocs that were - * inconsistent. Removed imports and specified things like java.io.IOException - * explicitly inline.
  • - *
  • v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the - * final encoded data will be so that the code doesn't have to create two output - * arrays: an oversized initial one and then a final, exact-sized one. Big win - * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not - * using the gzip options which uses a different mechanism with streams and stuff).
  • - *
  • v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some - * similar helper methods to be more efficient with memory by not returning a - * String but just a byte array.
  • - *
  • v2.3 - This is not a drop-in replacement! This is two years of comments - * and bug fixes queued up and finally executed. Thanks to everyone who sent - * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. - * Much bad coding was cleaned up including throwing exceptions where necessary - * instead of returning null values or something similar. Here are some changes - * that may affect you: - *
      - *
    • Does not break lines, by default. This is to keep in compliance with - * RFC3548.
    • - *
    • Throws exceptions instead of returning null values. Because some operations - * (especially those that may permit the GZIP option) use IO streams, there - * is a possiblity of an java.io.IOException being thrown. After some discussion and - * thought, I've changed the behavior of the methods to throw java.io.IOExceptions - * rather than return null if ever there's an error. I think this is more - * appropriate, though it will require some changes to your code. Sorry, - * it should have been done this way to begin with.
    • - *
    • Removed all references to System.out, System.err, and the like. - * Shame on me. All I can say is sorry they were ever there.
    • - *
    • Throws NullPointerExceptions and IllegalArgumentExceptions as needed - * such as when passed arrays are null or offsets are invalid.
    • - *
    • Cleaned up as much javadoc as I could to avoid any javadoc warnings. - * This was especially annoying before for people who were thorough in their - * own projects and then had gobs of javadoc warnings on this file.
    • - *
    - *
  • v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug - * when using very small files (~< 40 bytes).
  • - *
  • v2.2 - Added some helper methods for encoding/decoding directly from - * one file to the next. Also added a main() method to support command line - * encoding/decoding from one file to the next. Also added these Base64 dialects: - *
      - *
    1. The default is RFC3548 format.
    2. - *
    3. Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates - * URL and file name friendly format as described in Section 4 of RFC3548. - * http://www.faqs.org/rfcs/rfc3548.html
    4. - *
    5. Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates - * URL and file name friendly format that preserves lexical ordering as described - * in http://www.faqs.org/qa/rfcc-1940.html
    6. - *
    - * Special thanks to Jim Kellerman at http://www.powerset.com/ - * for contributing the new Base64 dialects. - *
  • - * - *
  • v2.1 - Cleaned up javadoc comments and unused variables and methods. Added - * some convenience methods for reading and writing to and from files.
  • - *
  • v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems - * with other encodings (like EBCDIC).
  • - *
  • v2.0.1 - Fixed an error when decoding a single byte, that is, when the - * encoded data was a single byte.
  • - *
  • v2.0 - I got rid of methods that used booleans to set options. - * Now everything is more consolidated and cleaner. The code now detects - * when data that's being decoded is gzip-compressed and will decompress it - * automatically. Generally things are cleaner. You'll probably have to - * change some method calls that you were making to support the new - * options format (ints that you "OR" together).
  • - *
  • v1.5.1 - Fixed bug when decompressing and decoding to a - * byte[] using decode( String s, boolean gzipCompressed ). - * Added the ability to "suspend" encoding in the Output Stream so - * you can turn on and off the encoding if you need to embed base64 - * data in an otherwise "normal" stream (like an XML file).
  • - *
  • v1.5 - Output stream pases on flush() command but doesn't do anything itself. - * This helps when using GZIP streams. - * Added the ability to GZip-compress objects before encoding them.
  • - *
  • v1.4 - Added helper methods to read/write files.
  • - *
  • v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.
  • - *
  • v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream - * where last buffer being read, if not completely full, was not returned.
  • - *
  • v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.
  • - *
  • v1.3.3 - Fixed I/O streams which were totally messed up.
  • - *
- * - *

- * I am placing this code in the Public Domain. Do with it as you will. - * This software comes with no guarantees or warranties but with - * plenty of well-wishing instead! - * Please visit http://iharder.net/base64 - * periodically to check for updates or to contribute improvements. - *

- * - * @author Robert Harder - * @author rob@iharder.net - * @version 2.3.3 - */ -@SuppressWarnings({"nls", "null"}) -public class Base64 -{ - -/* ******** P U B L I C F I E L D S ******** */ - - - /** No options specified. Value is zero. */ - public final static int NO_OPTIONS = 0; - - /** Specify encoding in first bit. Value is one. */ - public final static int ENCODE = 1; - - - /** Specify decoding in first bit. Value is zero. */ - public final static int DECODE = 0; - - - /** Specify that data should be gzip-compressed in second bit. Value is two. */ - public final static int GZIP = 2; - - /** Specify that gzipped data should not be automatically gunzipped. */ - public final static int DONT_GUNZIP = 4; - - - /** Do break lines when encoding. Value is 8. */ - public final static int DO_BREAK_LINES = 8; - - /** - * Encode using Base64-like encoding that is URL- and Filename-safe as described - * in Section 4 of RFC3548: - * http://www.faqs.org/rfcs/rfc3548.html. - * It is important to note that data encoded this way is not officially valid Base64, - * or at the very least should not be called Base64 without also specifying that is - * was encoded using the URL- and Filename-safe dialect. - */ - public final static int URL_SAFE = 16; - - - /** - * Encode using the special "ordered" dialect of Base64 described here: - * http://www.faqs.org/qa/rfcc-1940.html. - */ - public final static int ORDERED = 32; - - -/* ******** P R I V A T E F I E L D S ******** */ - - - /** Maximum line length (76) of Base64 output. */ - private final static int MAX_LINE_LENGTH = 76; - - - /** The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte)'='; - - - /** The new line character (\n) as a byte. */ - private final static byte NEW_LINE = (byte)'\n'; - - - /** Preferred encoding. */ - private final static String PREFERRED_ENCODING = "US-ASCII"; - - - private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding - private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding - - -/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ - - /** The 64 valid Base64 values. */ - /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ - private final static byte[] _STANDARD_ALPHABET = { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' - }; - - - /** - * Translates a Base64 value to either its 6-bit reconstruction value - * or a negative number indicating some other meaning. - **/ - private final static byte[] _STANDARD_DECODABET = { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9,-9,-9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; - - -/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ - - /** - * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: - * http://www.faqs.org/rfcs/rfc3548.html. - * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." - */ - private final static byte[] _URL_SAFE_ALPHABET = { - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', - (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' - }; - - /** - * Used in decoding URL- and Filename-safe dialects of Base64. - */ - private final static byte[] _URL_SAFE_DECODABET = { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 62, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' - 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' - -9,-9,-9,-9, // Decimal 91 - 94 - 63, // Underscore at decimal 95 - -9, // Decimal 96 - 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' - 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; - - - -/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ - - /** - * I don't get the point of this technique, but someone requested it, - * and it is described here: - * http://www.faqs.org/qa/rfcc-1940.html. - */ - private final static byte[] _ORDERED_ALPHABET = { - (byte)'-', - (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', - (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', - (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', - (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', - (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', - (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', - (byte)'_', - (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', - (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', - (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', - (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' - }; - - /** - * Used in decoding the "ordered" dialect of Base64. - */ - private final static byte[] _ORDERED_DECODABET = { - -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 - -5,-5, // Whitespace: Tab and Linefeed - -9,-9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 - -9,-9,-9,-9,-9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 0, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine - -9,-9,-9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9,-9,-9, // Decimal 62 - 64 - 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' - 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' - -9,-9,-9,-9, // Decimal 91 - 94 - 37, // Underscore at decimal 95 - -9, // Decimal 96 - 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' - 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' - -9,-9,-9,-9 // Decimal 123 - 126 - /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 - -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ - }; - - -/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ - - - /** - * Returns one of the _SOMETHING_ALPHABET byte arrays depending on - * the options specified. - * It's possible, though silly, to specify ORDERED and URLSAFE - * in which case one of them will be picked, though there is - * no guarantee as to which one will be picked. - */ - final static byte[] getAlphabet( int options ) { - if ((options & URL_SAFE) == URL_SAFE) { - return _URL_SAFE_ALPHABET; - } else if ((options & ORDERED) == ORDERED) { - return _ORDERED_ALPHABET; - } else { - return _STANDARD_ALPHABET; - } - } // end getAlphabet - - - /** - * Returns one of the _SOMETHING_DECODABET byte arrays depending on - * the options specified. - * It's possible, though silly, to specify ORDERED and URL_SAFE - * in which case one of them will be picked, though there is - * no guarantee as to which one will be picked. - */ - final static byte[] getDecodabet( int options ) { - if( (options & URL_SAFE) == URL_SAFE) { - return _URL_SAFE_DECODABET; - } else if ((options & ORDERED) == ORDERED) { - return _ORDERED_DECODABET; - } else { - return _STANDARD_DECODABET; - } - } // end getAlphabet - - - - /** Defeats instantiation. */ - private Base64(){/**/} - - - - -/* ******** E N C O D I N G M E T H O D S ******** */ - - - /** - * Encodes up to the first three bytes of array threeBytes - * and returns a four-byte array in Base64 notation. - * The actual number of significant bytes in your array is - * given by numSigBytes. - * The array threeBytes needs only be as big as - * numSigBytes. - * Code can reuse a byte array by passing a four-byte array as b4. - * - * @param b4 A reusable byte array to reduce array instantiation - * @param threeBytes the array to convert - * @param numSigBytes the number of significant bytes in your array - * @return four byte array in Base64 notation. - * @since 1.5.1 - */ - static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { - encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); - return b4; - } // end encode3to4 - - - /** - *

Encodes up to three bytes of the array source - * and writes the resulting four Base64 bytes to destination. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * srcOffset and destOffset. - * This method does not check to make sure your arrays - * are large enough to accomodate srcOffset + 3 for - * the source array or destOffset + 4 for - * the destination array. - * The actual number of significant bytes in your array is - * given by numSigBytes.

- *

This is the lowest level of the encoding methods with - * all possible parameters.

- * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param numSigBytes the number of significant bytes in your array - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @return the destination array - * @since 1.3 - */ - static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset, int options ) { - - byte[] ALPHABET = getAlphabet( options ); - - // 1 2 3 - // 01234567890123456789012345678901 Bit position - // --------000000001111111122222222 Array position from threeBytes - // --------| || || || | Six bit groups to index ALPHABET - // >>18 >>12 >> 6 >> 0 Right shift necessary - // 0x3f 0x3f 0x3f Additional AND - - // Create buffer with zero-padding if there are only one or two - // significant bytes passed in the array. - // We have to shift left 24 in order to flush out the 1's that appear - // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) - | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) - | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); - - switch( numSigBytes ) - { - case 3: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; - return destination; - - case 2: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; - destination[ destOffset + 3 ] = EQUALS_SIGN; - return destination; - - case 1: - destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; - destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; - destination[ destOffset + 2 ] = EQUALS_SIGN; - destination[ destOffset + 3 ] = EQUALS_SIGN; - return destination; - - default: - return destination; - } // end switch - } // end encode3to4 - - - - /** - * Performs Base64 encoding on the raw ByteBuffer, - * writing it to the encoded ByteBuffer. - * This is an experimental feature. Currently it does not - * pass along any options (such as {@link #DO_BREAK_LINES} - * or {@link #GZIP}. - * - * @param raw input buffer - * @param encoded output buffer - * @since 2.3 - */ - public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ - byte[] raw3 = new byte[3]; - byte[] enc4 = new byte[4]; - - while( raw.hasRemaining() ){ - int rem = Math.min(3,raw.remaining()); - raw.get(raw3,0,rem); - Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); - encoded.put(enc4); - } // end input remaining - } - - - /** - * Performs Base64 encoding on the raw ByteBuffer, - * writing it to the encoded CharBuffer. - * This is an experimental feature. Currently it does not - * pass along any options (such as {@link #DO_BREAK_LINES} - * or {@link #GZIP}. - * - * @param raw input buffer - * @param encoded output buffer - * @since 2.3 - */ - public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ - byte[] raw3 = new byte[3]; - byte[] enc4 = new byte[4]; - - while( raw.hasRemaining() ){ - int rem = Math.min(3,raw.remaining()); - raw.get(raw3,0,rem); - Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); - for( int i = 0; i < 4; i++ ){ - encoded.put( (char)(enc4[i] & 0xFF) ); - } - } // end input remaining - } - - - - - /** - * Serializes an object and returns the Base64-encoded - * version of that serialized object. - * - *

As of v 2.3, if the object - * cannot be serialized or there is another error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned a null value, but - * in retrospect that's a pretty poor way to handle it.

- * - * The object is not GZip-compressed before being encoded. - * - * @param serializableObject The object to encode - * @return The Base64-encoded object - * @throws java.io.IOException if there is an error - * @throws NullPointerException if serializedObject is null - * @since 1.4 - */ - public static String encodeObject( java.io.Serializable serializableObject ) - throws java.io.IOException { - return encodeObject( serializableObject, NO_OPTIONS ); - } // end encodeObject - - - - /** - * Serializes an object and returns the Base64-encoded - * version of that serialized object. - * - *

As of v 2.3, if the object - * cannot be serialized or there is another error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned a null value, but - * in retrospect that's a pretty poor way to handle it.

- * - * The object is not GZip-compressed before being encoded. - *

- * Example options:

-     *   GZIP: gzip-compresses object before encoding it.
-     *   DO_BREAK_LINES: break lines at 76 characters
-     * 
- *

- * Example: encodeObject( myObj, Base64.GZIP ) or - *

- * Example: encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * @param serializableObject The object to encode - * @param options Specified options - * @return The Base64-encoded object - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @since 2.0 - */ - public static String encodeObject( java.io.Serializable serializableObject, int options ) - throws java.io.IOException { - - if( serializableObject == null ){ - throw new NullPointerException( "Cannot serialize a null object." ); - } // end if: null - - // Streams - java.io.ByteArrayOutputStream baos = null; - java.io.OutputStream b64os = null; - java.util.zip.GZIPOutputStream gzos = null; - java.io.ObjectOutputStream oos = null; - - - try { - // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream( baos, ENCODE | options ); - if( (options & GZIP) != 0 ){ - // Gzip - gzos = new java.util.zip.GZIPOutputStream(b64os); - oos = new java.io.ObjectOutputStream( gzos ); - } else { - // Not gzipped - oos = new java.io.ObjectOutputStream( b64os ); - } - oos.writeObject( serializableObject ); - } // end try - catch( java.io.IOException e ) { - // Catch it and then throw it immediately so that - // the finally{/**/} block is called for cleanup. - throw e; - } // end catch - finally { - try{ oos.close(); } catch( Exception e ){/**/} - try{ gzos.close(); } catch( Exception e ){/**/} - try{ b64os.close(); } catch( Exception e ){/**/} - try{ baos.close(); } catch( Exception e ){/**/} - } // end finally - - // Return value according to relevant encoding. - try { - return new String( baos.toByteArray(), PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue){ - // Fall back to some Java default - return new String( baos.toByteArray() ); - } // end catch - - } // end encode - - - - /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * - * @param source The data to convert - * @return The data in Base64-encoded form - * @throws NullPointerException if source array is null - * @since 1.4 - */ - public static String encodeBytes( byte[] source ) { - // Since we're not going to have the GZIP encoding turned on, - // we're not going to have an java.io.IOException thrown, so - // we should not force the user to have to catch it. - String encoded = null; - try { - encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); - } catch (java.io.IOException ex) { - assert false : ex.getMessage(); - } // end catch - assert encoded != null; - return encoded; - } // end encodeBytes - - - - /** - * Encodes a byte array into Base64 notation. - *

- * Example options:

-     *   GZIP: gzip-compresses object before encoding it.
-     *   DO_BREAK_LINES: break lines at 76 characters
-     *     Note: Technically, this makes your encoding non-compliant.
-     * 
- *

- * Example: encodeBytes( myData, Base64.GZIP ) or - *

- * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * - *

As of v 2.3, if there is an error with the GZIP stream, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned a null value, but - * in retrospect that's a pretty poor way to handle it.

- * - * - * @param source The data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws NullPointerException if source array is null - * @since 2.0 - */ - public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { - return encodeBytes( source, 0, source.length, options ); - } // end encodeBytes - - - /** - * Encodes a byte array into Base64 notation. - * Does not GZip-compress data. - * - *

As of v 2.3, if there is an error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned a null value, but - * in retrospect that's a pretty poor way to handle it.

- * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @return The Base64-encoded data as a String - * @throws NullPointerException if source array is null - * @throws IllegalArgumentException if source array, offset, or length are invalid - * @since 1.4 - */ - public static String encodeBytes( byte[] source, int off, int len ) { - // Since we're not going to have the GZIP encoding turned on, - // we're not going to have an java.io.IOException thrown, so - // we should not force the user to have to catch it. - String encoded = null; - try { - encoded = encodeBytes( source, off, len, NO_OPTIONS ); - } catch (java.io.IOException ex) { - assert false : ex.getMessage(); - } // end catch - assert encoded != null; - return encoded; - } // end encodeBytes - - - - /** - * Encodes a byte array into Base64 notation. - *

- * Example options:

-     *   GZIP: gzip-compresses object before encoding it.
-     *   DO_BREAK_LINES: break lines at 76 characters
-     *     Note: Technically, this makes your encoding non-compliant.
-     * 
- *

- * Example: encodeBytes( myData, Base64.GZIP ) or - *

- * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * - *

As of v 2.3, if there is an error with the GZIP stream, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned a null value, but - * in retrospect that's a pretty poor way to handle it.

- * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws NullPointerException if source array is null - * @throws IllegalArgumentException if source array, offset, or length are invalid - * @since 2.0 - */ - public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { - byte[] encoded = encodeBytesToBytes( source, off, len, options ); - - // Return value according to relevant encoding. - try { - return new String( encoded, PREFERRED_ENCODING ); - } // end try - catch (java.io.UnsupportedEncodingException uue) { - return new String( encoded ); - } // end catch - - } // end encodeBytes - - - - - /** - * Similar to {@link #encodeBytes(byte[])} but returns - * a byte array instead of instantiating a String. This is more efficient - * if you're working with I/O streams and have large data sets to encode. - * - * - * @param source The data to convert - * @return The Base64-encoded data as a byte[] (of ASCII characters) - * @throws NullPointerException if source array is null - * @since 2.3.1 - */ - public static byte[] encodeBytesToBytes( byte[] source ) { - byte[] encoded = null; - try { - encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); - } catch( java.io.IOException ex ) { - assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); - } - return encoded; - } - - - /** - * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns - * a byte array instead of instantiating a String. This is more efficient - * if you're working with I/O streams and have large data sets to encode. - * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws NullPointerException if source array is null - * @throws IllegalArgumentException if source array, offset, or length are invalid - * @since 2.3.1 - */ - public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { - - if( source == null ){ - throw new NullPointerException( "Cannot serialize a null array." ); - } // end if: null - - if( off < 0 ){ - throw new IllegalArgumentException( "Cannot have negative offset: " + off ); - } // end if: off < 0 - - if( len < 0 ){ - throw new IllegalArgumentException( "Cannot have length offset: " + len ); - } // end if: len < 0 - - if( off + len > source.length ){ - throw new IllegalArgumentException( - String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); - } // end if: off < 0 - - - - // Compress? - if( (options & GZIP) != 0 ) { - java.io.ByteArrayOutputStream baos = null; - java.util.zip.GZIPOutputStream gzos = null; - Base64.OutputStream b64os = null; - - try { - // GZip -> Base64 -> ByteArray - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream( baos, ENCODE | options ); - gzos = new java.util.zip.GZIPOutputStream( b64os ); - - gzos.write( source, off, len ); - gzos.close(); - } // end try - catch( java.io.IOException e ) { - // Catch it and then throw it immediately so that - // the finally{/**/} block is called for cleanup. - throw e; - } // end catch - finally { - try{ gzos.close(); } catch( Exception e ){/**/} - try{ b64os.close(); } catch( Exception e ){/**/} - try{ baos.close(); } catch( Exception e ){/**/} - } // end finally - - return baos.toByteArray(); - } // end if: compress - - // Else, don't compress. Better not to use streams at all then. - else { - boolean breakLines = (options & DO_BREAK_LINES) > 0; - - //int len43 = len * 4 / 3; - //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 - // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding - // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines - // Try to determine more precisely how big the array needs to be. - // If we get it right, we don't have to do an array copy, and - // we save a bunch of memory. - int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding - if( breakLines ){ - encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters - } - byte[] outBuff = new byte[ encLen ]; - - - int d = 0; - int e = 0; - int len2 = len - 2; - int lineLength = 0; - for( ; d < len2; d+=3, e+=4 ) { - encode3to4( source, d+off, 3, outBuff, e, options ); - - lineLength += 4; - if( breakLines && lineLength >= MAX_LINE_LENGTH ) - { - outBuff[e+4] = NEW_LINE; - e++; - lineLength = 0; - } // end if: end of line - } // en dfor: each piece of array - - if( d < len ) { - encode3to4( source, d+off, len - d, outBuff, e, options ); - e += 4; - } // end if: some padding needed - - - // Only resize array if we didn't guess it right. - if( e < outBuff.length - 1 ){ - byte[] finalOut = new byte[e]; - System.arraycopy(outBuff,0, finalOut,0,e); - //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); - return finalOut; - } else { - //System.err.println("No need to resize array."); - return outBuff; - } - - } // end else: don't compress - - } // end encodeBytesToBytes - - - - - -/* ******** D E C O D I N G M E T H O D S ******** */ - - - /** - * Decodes four bytes from array source - * and writes the resulting bytes (up to three of them) - * to destination. - * The source and destination arrays can be manipulated - * anywhere along their length by specifying - * srcOffset and destOffset. - * This method does not check to make sure your arrays - * are large enough to accomodate srcOffset + 4 for - * the source array or destOffset + 3 for - * the destination array. - * This method returns the actual number of bytes that - * were converted from the Base64 encoding. - *

This is the lowest level of the decoding methods with - * all possible parameters.

- * - * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @param options alphabet type is pulled from this (standard, url-safe, ordered) - * @return the number of decoded bytes converted - * @throws NullPointerException if source or destination arrays are null - * @throws IllegalArgumentException if srcOffset or destOffset are invalid - * or there is not enough room in the array. - * @since 1.3 - */ - static int decode4to3( - byte[] source, int srcOffset, - byte[] destination, int destOffset, int options ) { - - // Lots of error checking and exception throwing - if( source == null ){ - throw new NullPointerException( "Source array was null." ); - } // end if - if( destination == null ){ - throw new NullPointerException( "Destination array was null." ); - } // end if - if( srcOffset < 0 || srcOffset + 3 >= source.length ){ - throw new IllegalArgumentException( String.format( - "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); - } // end if - if( destOffset < 0 || destOffset +2 >= destination.length ){ - throw new IllegalArgumentException( String.format( - "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); - } // end if - - - byte[] DECODABET = getDecodabet( options ); - - // Example: Dk== - if( source[ srcOffset + 2] == EQUALS_SIGN ) { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - return 1; - } - - // Example: DkL= - else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); - - destination[ destOffset ] = (byte)( outBuff >>> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); - return 2; - } - - // Example: DkLE - else { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) - // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); - int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) - | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) - | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) - | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); - - - destination[ destOffset ] = (byte)( outBuff >> 16 ); - destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); - destination[ destOffset + 2 ] = (byte)( outBuff ); - - return 3; - } - } // end decodeToBytes - - - - - - /** - * Low-level access to decoding ASCII characters in - * the form of a byte array. Ignores GUNZIP option, if - * it's set. This is not generally a recommended method, - * although it is used internally as part of the decoding process. - * Special case: if len = 0, an empty array is returned. Still, - * if you need more speed and reduced memory footprint (and aren't - * gzipping), consider this method. - * - * @param source The Base64 encoded data - * @return decoded data - * @since 2.3.1 - */ - public static byte[] decode( byte[] source ){ - byte[] decoded = null; - try { - decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); - } catch( java.io.IOException ex ) { - assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); - } - return decoded; - } - - - - /** - * Low-level access to decoding ASCII characters in - * the form of a byte array. Ignores GUNZIP option, if - * it's set. This is not generally a recommended method, - * although it is used internally as part of the decoding process. - * Special case: if len = 0, an empty array is returned. Still, - * if you need more speed and reduced memory footprint (and aren't - * gzipping), consider this method. - * - * @param source The Base64 encoded data - * @param off The offset of where to begin decoding - * @param len The length of characters to decode - * @param options Can specify options such as alphabet type to use - * @return decoded data - * @throws java.io.IOException If bogus characters exist in source data - * @since 1.3 - */ - public static byte[] decode( byte[] source, int off, int len, int options ) - throws java.io.IOException { - - // Lots of error checking and exception throwing - if( source == null ){ - throw new NullPointerException( "Cannot decode null source array." ); - } // end if - if( off < 0 || off + len > source.length ){ - throw new IllegalArgumentException( String.format( - "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); - } // end if - - if( len == 0 ){ - return new byte[0]; - }else if( len < 4 ){ - throw new IllegalArgumentException( - "Base64-encoded string must have at least four characters, but length specified was " + len ); - } // end if - - byte[] DECODABET = getDecodabet( options ); - - int len34 = len * 3 / 4; // Estimate on array size - byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output - int outBuffPosn = 0; // Keep track of where we're writing - - byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space - int b4Posn = 0; // Keep track of four byte input buffer - int i = 0; // Source array counter - byte sbiCrop = 0; // Low seven bits (ASCII) of input - byte sbiDecode = 0; // Special value from DECODABET - - for( i = off; i < off+len; i++ ) { // Loop through source - - sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits - sbiDecode = DECODABET[ sbiCrop ]; // Special value - - // White space, Equals sign, or legit Base64 character - // Note the values such as -5 and -9 in the - // DECODABETs at the top of the file. - if( sbiDecode >= WHITE_SPACE_ENC ) { - if( sbiDecode >= EQUALS_SIGN_ENC ) { - b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace - if( b4Posn > 3 ) { // Time to decode? - outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); - b4Posn = 0; - - // If that was the equals sign, break out of 'for' loop - if( sbiCrop == EQUALS_SIGN ) { - break; - } // end if: equals sign - } // end if: quartet built - } // end if: equals sign or better - } // end if: white space, equals sign or better - else { - // There's a bad input character in the Base64 stream. - throw new java.io.IOException( String.format( - "Bad Base64 input character '%c' in array position %d", source[i], i ) ); - } // end else: - } // each input character - - byte[] out = new byte[ outBuffPosn ]; - System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); - return out; - } // end decode - - - - - /** - * Decodes data from Base64 notation, automatically - * detecting gzip-compressed data and decompressing it. - * - * @param s the string to decode - * @return the decoded data - * @throws java.io.IOException If there is a problem - * @since 1.4 - */ - public static byte[] decode( String s ) throws java.io.IOException { - return decode( s, NO_OPTIONS ); - } - - - - /** - * Decodes data from Base64 notation, automatically - * detecting gzip-compressed data and decompressing it. - * - * @param s the string to decode - * @param options encode options such as URL_SAFE - * @return the decoded data - * @throws java.io.IOException if there is an error - * @throws NullPointerException if s is null - * @since 1.4 - */ - public static byte[] decode( String s, int options ) throws java.io.IOException { - - if( s == null ){ - throw new NullPointerException( "Input string was null." ); - } // end if - - byte[] bytes; - try { - bytes = s.getBytes( PREFERRED_ENCODING ); - } // end try - catch( java.io.UnsupportedEncodingException uee ) { - bytes = s.getBytes(); - } // end catch - // - - // Decode - bytes = decode( bytes, 0, bytes.length, options ); - - // Check to see if it's gzip-compressed - // GZIP Magic Two-Byte Number: 0x8b1f (35615) - boolean dontGunzip = (options & DONT_GUNZIP) != 0; - if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { - - int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); - if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { - java.io.ByteArrayInputStream bais = null; - java.util.zip.GZIPInputStream gzis = null; - java.io.ByteArrayOutputStream baos = null; - byte[] buffer = new byte[2048]; - int length = 0; - - try { - baos = new java.io.ByteArrayOutputStream(); - bais = new java.io.ByteArrayInputStream( bytes ); - gzis = new java.util.zip.GZIPInputStream( bais ); - - while( ( length = gzis.read( buffer ) ) >= 0 ) { - baos.write(buffer,0,length); - } // end while: reading input - - // No error? Get new bytes. - bytes = baos.toByteArray(); - - } // end try - catch( java.io.IOException e ) { - e.printStackTrace(); - // Just return originally-decoded bytes - } // end catch - finally { - try{ baos.close(); } catch( Exception e ){/**/} - try{ gzis.close(); } catch( Exception e ){/**/} - try{ bais.close(); } catch( Exception e ){/**/} - } // end finally - - } // end if: gzipped - } // end if: bytes.length >= 2 - - return bytes; - } // end decode - - - - /** - * Attempts to decode Base64 data and deserialize a Java - * Object within. Returns null if there was an error. - * - * @param encodedObject The Base64 data to decode - * @return The decoded and deserialized object - * @throws NullPointerException if encodedObject is null - * @throws java.io.IOException if there is a general error - * @throws ClassNotFoundException if the decoded object is of a - * class that cannot be found by the JVM - * @since 1.5 - */ - public static Object decodeToObject( String encodedObject ) - throws java.io.IOException, java.lang.ClassNotFoundException { - return decodeToObject(encodedObject,NO_OPTIONS,null); - } - - - /** - * Attempts to decode Base64 data and deserialize a Java - * Object within. Returns null if there was an error. - * If loader is not null, it will be the class loader - * used when deserializing. - * - * @param encodedObject The Base64 data to decode - * @param options Various parameters related to decoding - * @param loader Optional class loader to use in deserializing classes. - * @return The decoded and deserialized object - * @throws NullPointerException if encodedObject is null - * @throws java.io.IOException if there is a general error - * @throws ClassNotFoundException if the decoded object is of a - * class that cannot be found by the JVM - * @since 2.3.4 - */ - public static Object decodeToObject( - String encodedObject, int options, final ClassLoader loader ) - throws java.io.IOException, java.lang.ClassNotFoundException { - - // Decode and gunzip if necessary - byte[] objBytes = decode( encodedObject, options ); - - java.io.ByteArrayInputStream bais = null; - java.io.ObjectInputStream ois = null; - Object obj = null; - - try { - bais = new java.io.ByteArrayInputStream( objBytes ); - - // If no custom class loader is provided, use Java's builtin OIS. - if( loader == null ){ - ois = new java.io.ObjectInputStream( bais ); - } // end if: no loader provided - - // Else make a customized object input stream that uses - // the provided class loader. - else { - ois = new java.io.ObjectInputStream(bais){ - @Override - public Class resolveClass(java.io.ObjectStreamClass streamClass) - throws java.io.IOException, ClassNotFoundException { - Class c = Class.forName(streamClass.getName(), false, loader); - if( c == null ){ - return super.resolveClass(streamClass); - } else { - return c; // Class loader knows of this class. - } // end else: not null - } // end resolveClass - }; // end ois - } // end else: no custom class loader - - obj = ois.readObject(); - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and throw in order to execute finally{/**/} - } // end catch - catch( java.lang.ClassNotFoundException e ) { - throw e; // Catch and throw in order to execute finally{/**/} - } // end catch - finally { - try{ bais.close(); } catch( Exception e ){/**/} - try{ ois.close(); } catch( Exception e ){/**/} - } // end finally - - return obj; - } // end decodeObject - - - - /** - * Convenience method for encoding data to a file. - * - *

As of v 2.3, if there is a error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned false, but - * in retrospect that's a pretty poor way to handle it.

- * - * @param dataToEncode byte array of data to encode in base64 form - * @param filename Filename for saving encoded data - * @throws java.io.IOException if there is an error - * @throws NullPointerException if dataToEncode is null - * @since 2.1 - */ - public static void encodeToFile( byte[] dataToEncode, String filename ) - throws java.io.IOException { - - if( dataToEncode == null ){ - throw new NullPointerException( "Data to encode was null." ); - } // end iff - - Base64.OutputStream bos = null; - try { - bos = new Base64.OutputStream( - new java.io.FileOutputStream( filename ), Base64.ENCODE ); - bos.write( dataToEncode ); - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and throw to execute finally{/**/} block - } // end catch: java.io.IOException - finally { - try{ bos.close(); } catch( Exception e ){/**/} - } // end finally - - } // end encodeToFile - - - /** - * Convenience method for decoding data to a file. - * - *

As of v 2.3, if there is a error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned false, but - * in retrospect that's a pretty poor way to handle it.

- * - * @param dataToDecode Base64-encoded data as a string - * @param filename Filename for saving decoded data - * @throws java.io.IOException if there is an error - * @since 2.1 - */ - public static void decodeToFile( String dataToDecode, String filename ) - throws java.io.IOException { - - Base64.OutputStream bos = null; - try{ - bos = new Base64.OutputStream( - new java.io.FileOutputStream( filename ), Base64.DECODE ); - bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and throw to execute finally{/**/} block - } // end catch: java.io.IOException - finally { - try{ bos.close(); } catch( Exception e ){/**/} - } // end finally - - } // end decodeToFile - - - - - /** - * Convenience method for reading a base64-encoded - * file and decoding it. - * - *

As of v 2.3, if there is a error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned false, but - * in retrospect that's a pretty poor way to handle it.

- * - * @param filename Filename for reading encoded data - * @return decoded byte array - * @throws java.io.IOException if there is an error - * @since 2.1 - */ - public static byte[] decodeFromFile( String filename ) - throws java.io.IOException { - - byte[] decodedData = null; - Base64.InputStream bis = null; - try - { - // Set up some useful variables - java.io.File file = new java.io.File( filename ); - byte[] buffer = null; - int length = 0; - int numBytes = 0; - - // Check for size of file - if( file.length() > Integer.MAX_VALUE ) - { - throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); - } // end if: file too big for int index - buffer = new byte[ (int)file.length() ]; - - // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( file ) ), Base64.DECODE ); - - // Read until done - while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { - length += numBytes; - } // end while - - // Save in a variable to return - decodedData = new byte[ length ]; - System.arraycopy( buffer, 0, decodedData, 0, length ); - - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and release to execute finally{/**/} - } // end catch: java.io.IOException - finally { - try{ bis.close(); } catch( Exception e) {/**/} - } // end finally - - return decodedData; - } // end decodeFromFile - - - - /** - * Convenience method for reading a binary file - * and base64-encoding it. - * - *

As of v 2.3, if there is a error, - * the method will throw an java.io.IOException. This is new to v2.3! - * In earlier versions, it just returned false, but - * in retrospect that's a pretty poor way to handle it.

- * - * @param filename Filename for reading binary data - * @return base64-encoded string - * @throws java.io.IOException if there is an error - * @since 2.1 - */ - public static String encodeFromFile( String filename ) - throws java.io.IOException { - - String encodedData = null; - Base64.InputStream bis = null; - try - { - // Set up some useful variables - java.io.File file = new java.io.File( filename ); - byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1) - int length = 0; - int numBytes = 0; - - // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream( file ) ), Base64.ENCODE ); - - // Read until done - while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { - length += numBytes; - } // end while - - // Save in a variable to return - encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); - - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and release to execute finally{/**/} - } // end catch: java.io.IOException - finally { - try{ bis.close(); } catch( Exception e) {/**/} - } // end finally - - return encodedData; - } // end encodeFromFile - - /** - * Reads infile and encodes it to outfile. - * - * @param infile Input file - * @param outfile Output file - * @throws java.io.IOException if there is an error - * @since 2.2 - */ - public static void encodeFileToFile( String infile, String outfile ) - throws java.io.IOException { - - String encoded = Base64.encodeFromFile( infile ); - java.io.OutputStream out = null; - try{ - out = new java.io.BufferedOutputStream( - new java.io.FileOutputStream( outfile ) ); - out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and release to execute finally{/**/} - } // end catch - finally { - try { out.close(); } - catch( Exception ex ){/**/} - } // end finally - } // end encodeFileToFile - - - /** - * Reads infile and decodes it to outfile. - * - * @param infile Input file - * @param outfile Output file - * @throws java.io.IOException if there is an error - * @since 2.2 - */ - public static void decodeFileToFile( String infile, String outfile ) - throws java.io.IOException { - - byte[] decoded = Base64.decodeFromFile( infile ); - java.io.OutputStream out = null; - try{ - out = new java.io.BufferedOutputStream( - new java.io.FileOutputStream( outfile ) ); - out.write( decoded ); - } // end try - catch( java.io.IOException e ) { - throw e; // Catch and release to execute finally{/**/} - } // end catch - finally { - try { out.close(); } - catch( Exception ex ){/**/} - } // end finally - } // end decodeFileToFile - - - /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ - - - - /** - * A {@link Base64.InputStream} will read data from another - * java.io.InputStream, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. - * - * @see Base64 - * @since 1.3 - */ - public static class InputStream extends java.io.FilterInputStream { - - private final boolean encode; // Encoding or decoding - private int position; // Current position in the buffer - private final byte[] buffer; // Small buffer holding converted data - private final int bufferLength; // Length of buffer (3 or 4) - private int numSigBytes; // Number of meaningful bytes in the buffer - private int lineLength; - private final boolean breakLines; // Break lines at less than 80 characters - private final int options; // Record options used to create the stream. - private final byte[] decodabet; // Local copies to avoid extra method calls - - - /** - * Constructs a {@link Base64.InputStream} in DECODE mode. - * - * @param in the java.io.InputStream from which to read data. - * @since 1.3 - */ - public InputStream( java.io.InputStream in ) { - this( in, DECODE ); - } // end constructor - - - /** - * Constructs a {@link Base64.InputStream} in - * either ENCODE or DECODE mode. - *

- * Valid options:

-         *   ENCODE or DECODE: Encode or Decode as data is read.
-         *   DO_BREAK_LINES: break lines at 76 characters
-         *     (only meaningful when encoding)
-         * 
- *

- * Example: new Base64.InputStream( in, Base64.DECODE ) - * - * - * @param in the java.io.InputStream from which to read data. - * @param options Specified options - * @see Base64#ENCODE - * @see Base64#DECODE - * @see Base64#DO_BREAK_LINES - * @since 2.0 - */ - public InputStream( java.io.InputStream in, int options ) { - - super( in ); - this.options = options; // Record for later - this.breakLines = (options & DO_BREAK_LINES) > 0; - this.encode = (options & ENCODE) > 0; - this.bufferLength = encode ? 4 : 3; - this.buffer = new byte[ bufferLength ]; - this.position = -1; - this.lineLength = 0; - this.decodabet = getDecodabet(options); - } // end constructor - - /** - * Reads enough of the input stream to convert - * to/from Base64 and returns the next byte. - * - * @return next byte - * @since 1.3 - */ - @Override - public int read() throws java.io.IOException { - - // Do we need to get data? - if( position < 0 ) { - if( encode ) { - byte[] b3 = new byte[3]; - int numBinaryBytes = 0; - for( int i = 0; i < 3; i++ ) { - int b = in.read(); - - // If end of stream, b is -1. - if( b >= 0 ) { - b3[i] = (byte)b; - numBinaryBytes++; - } else { - break; // out of for loop - } // end else: end of stream - - } // end for: each needed input byte - - if( numBinaryBytes > 0 ) { - encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); - position = 0; - numSigBytes = 4; - } // end if: got data - else { - return -1; // Must be end of stream - } // end else - } // end if: encoding - - // Else decoding - else { - byte[] b4 = new byte[4]; - int i = 0; - for( i = 0; i < 4; i++ ) { - // Read four "meaningful" bytes: - int b = 0; - do{ b = in.read(); } - while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); - - if( b < 0 ) { - break; // Reads a -1 if end of stream - } // end if: end of stream - - b4[i] = (byte)b; - } // end for: each needed input byte - - if( i == 4 ) { - numSigBytes = decode4to3( b4, 0, buffer, 0, options ); - position = 0; - } // end if: got four characters - else if( i == 0 ){ - return -1; - } // end else if: also padded correctly - else { - // Must have broken out from above. - throw new java.io.IOException( "Improperly padded Base64 input." ); - } // end - - } // end else: decode - } // end else: get data - - // Got data? - if( position >= 0 ) { - // End of relevant data? - if( /*!encode &&*/ position >= numSigBytes ){ - return -1; - } // end if: got data - - if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { - lineLength = 0; - return '\n'; - } // end if - else { - lineLength++; // This isn't important when decoding - // but throwing an extra "if" seems - // just as wasteful. - - int b = buffer[ position++ ]; - - if( position >= bufferLength ) { - position = -1; - } // end if: end - - return b & 0xFF; // This is how you "cast" a byte that's - // intended to be unsigned. - } // end else - } // end if: position >= 0 - - // Else error - else { - throw new java.io.IOException( "Error in Base64 code reading stream." ); - } // end else - } // end read - - - /** - * Calls {@link #read()} repeatedly until the end of stream - * is reached or len bytes are read. - * Returns number of bytes read into array or -1 if - * end of stream is encountered. - * - * @param dest array to hold values - * @param off offset for array - * @param len max number of bytes to read into array - * @return bytes read into array or -1 if end of stream is encountered. - * @since 1.3 - */ - @Override - public int read( byte[] dest, int off, int len ) - throws java.io.IOException { - int i; - int b; - for( i = 0; i < len; i++ ) { - b = read(); - - if( b >= 0 ) { - dest[off + i] = (byte) b; - } - else if( i == 0 ) { - return -1; - } - else { - break; // Out of 'for' loop - } // Out of 'for' loop - } // end for: each byte read - return i; - } // end read - - } // end inner class InputStream - - - - - - - /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ - - - - /** - * A {@link Base64.OutputStream} will write data to another - * java.io.OutputStream, given in the constructor, - * and encode/decode to/from Base64 notation on the fly. - * - * @see Base64 - * @since 1.3 - */ - public static class OutputStream extends java.io.FilterOutputStream { - - private final boolean encode; - private int position; - private byte[] buffer; - private final int bufferLength; - private int lineLength; - private final boolean breakLines; - private final byte[] b4; // Scratch used in a few places - private boolean suspendEncoding; - private final int options; // Record for later - private final byte[] decodabet; // Local copies to avoid extra method calls - - /** - * Constructs a {@link Base64.OutputStream} in ENCODE mode. - * - * @param out the java.io.OutputStream to which data will be written. - * @since 1.3 - */ - public OutputStream( java.io.OutputStream out ) { - this( out, ENCODE ); - } // end constructor - - - /** - * Constructs a {@link Base64.OutputStream} in - * either ENCODE or DECODE mode. - *

- * Valid options:

-         *   ENCODE or DECODE: Encode or Decode as data is read.
-         *   DO_BREAK_LINES: don't break lines at 76 characters
-         *     (only meaningful when encoding)
-         * 
- *

- * Example: new Base64.OutputStream( out, Base64.ENCODE ) - * - * @param out the java.io.OutputStream to which data will be written. - * @param options Specified options. - * @see Base64#ENCODE - * @see Base64#DECODE - * @see Base64#DO_BREAK_LINES - * @since 1.3 - */ - public OutputStream( java.io.OutputStream out, int options ) { - super( out ); - this.breakLines = (options & DO_BREAK_LINES) != 0; - this.encode = (options & ENCODE) != 0; - this.bufferLength = encode ? 3 : 4; - this.buffer = new byte[ bufferLength ]; - this.position = 0; - this.lineLength = 0; - this.suspendEncoding = false; - this.b4 = new byte[4]; - this.options = options; - this.decodabet = getDecodabet(options); - } // end constructor - - - /** - * Writes the byte to the output stream after - * converting to/from Base64 notation. - * When encoding, bytes are buffered three - * at a time before the output stream actually - * gets a write() call. - * When decoding, bytes are buffered four - * at a time. - * - * @param theByte the byte to write - * @since 1.3 - */ - @Override - public void write(int theByte) - throws java.io.IOException { - // Encoding suspended? - if( suspendEncoding ) { - this.out.write( theByte ); - return; - } // end if: supsended - - // Encode? - if( encode ) { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) { // Enough to encode. - - this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); - - lineLength += 4; - if( breakLines && lineLength >= MAX_LINE_LENGTH ) { - this.out.write( NEW_LINE ); - lineLength = 0; - } // end if: end of line - - position = 0; - } // end if: enough to output - } // end if: encoding - - // Else, Decoding - else { - // Meaningful Base64 character? - if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { - buffer[ position++ ] = (byte)theByte; - if( position >= bufferLength ) { // Enough to output. - - int len = Base64.decode4to3( buffer, 0, b4, 0, options ); - out.write( b4, 0, len ); - position = 0; - } // end if: enough to output - } // end if: meaningful base64 character - else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { - throw new java.io.IOException( "Invalid character in Base64 data." ); - } // end else: not white space either - } // end else: decoding - } // end write - - - - /** - * Calls {@link #write(int)} repeatedly until len - * bytes are written. - * - * @param theBytes array from which to read bytes - * @param off offset for array - * @param len max number of bytes to read into array - * @since 1.3 - */ - @Override - public void write( byte[] theBytes, int off, int len ) - throws java.io.IOException { - // Encoding suspended? - if( suspendEncoding ) { - this.out.write( theBytes, off, len ); - return; - } // end if: supsended - - for( int i = 0; i < len; i++ ) { - write( theBytes[ off + i ] ); - } // end for: each byte written - - } // end write - - - - /** - * Method added by PHIL. [Thanks, PHIL. -Rob] - * This pads the buffer without closing the stream. - * @throws java.io.IOException if there's an error. - */ - public void flushBase64() throws java.io.IOException { - if( position > 0 ) { - if( encode ) { - out.write( encode3to4( b4, buffer, position, options ) ); - position = 0; - } // end if: encoding - else { - throw new java.io.IOException( "Base64 input not properly padded." ); - } // end else: decoding - } // end if: buffer partially full - - } // end flush - - - /** - * Flushes and closes (I think, in the superclass) the stream. - * - * @since 1.3 - */ - @Override - public void close() throws java.io.IOException { - // 1. Ensure that pending characters are written - flushBase64(); - - // 2. Actually close the stream - // Base class both flushes and closes. - super.close(); - - buffer = null; - out = null; - } // end close - - - - /** - * Suspends encoding of the stream. - * May be helpful if you need to embed a piece of - * base64-encoded data in a stream. - * - * @throws java.io.IOException if there's an error flushing - * @since 1.5.1 - */ - public void suspendEncoding() throws java.io.IOException { - flushBase64(); - this.suspendEncoding = true; - } // end suspendEncoding - - - /** - * Resumes encoding of the stream. - * May be helpful if you need to embed a piece of - * base64-encoded data in a stream. - * - * @since 1.5.1 - */ - public void resumeEncoding() { - this.suspendEncoding = false; - } // end resumeEncoding - - - - } // end inner class OutputStream - - -} // end class Base64 diff --git a/astrid/common-src/com/todoroo/andlib/utility/DateUtilities.java b/astrid/common-src/com/todoroo/andlib/utility/DateUtilities.java deleted file mode 100644 index b1c64eeb4..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/DateUtilities.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright (c) 2009, Todoroo Inc - * All Rights Reserved - * http://www.todoroo.com - */ -package com.todoroo.andlib.utility; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import android.content.Context; -import android.content.res.Resources; -import android.text.format.DateUtils; - -import com.todoroo.andlib.service.Autowired; -import com.todoroo.andlib.service.ContextManager; -import com.todoroo.andlib.service.DependencyInjectionService; - - -public class DateUtilities { - - @Autowired - public Integer yearsResource; - - @Autowired - public Integer monthsResource; - - @Autowired - public Integer weeksResource; - - @Autowired - public Integer daysResource; - - @Autowired - public Integer hoursResource; - - @Autowired - public Integer minutesResource; - - @Autowired - public Integer secondsResource; - - @Autowired - public Integer daysAbbrevResource; - - @Autowired - public Integer hoursAbbrevResource; - - @Autowired - public Integer minutesAbbrevResource; - - @Autowired - public Integer secondsAbbrevResource; - - public DateUtilities() { - DependencyInjectionService.getInstance().inject(this); - } - - /* ====================================================================== - * ============================================================ long time - * ====================================================================== */ - - /** Convert unixtime into date */ - public static final Date unixtimeToDate(long millis) { - if(millis == 0) - return null; - return new Date(millis); - } - - /** Convert date into unixtime */ - public static final long dateToUnixtime(Date date) { - if(date == null) - return 0; - return date.getTime(); - } - - /** Returns unixtime for current time */ - public static final long now() { - return System.currentTimeMillis(); - } - - /** Returns unixtime one month from now */ - public static final long oneMonthFromNow() { - Date date = new Date(); - date.setMonth(date.getMonth() + 1); - return date.getTime(); - } - - /** Represents a single hour */ - public static long ONE_HOUR = 3600000L; - - /** Represents a single day */ - public static long ONE_DAY = 24 * ONE_HOUR; - - /** Represents a single week */ - public static long ONE_WEEK = 7 * ONE_DAY; - - /* ====================================================================== - * =========================================================== formatters - * ====================================================================== */ - - @SuppressWarnings("nls") - public static boolean is24HourFormat(Context context) { - String value = android.provider.Settings.System.getString(context.getContentResolver(), - android.provider.Settings.System.TIME_12_24); - boolean b24 = !(value == null || value.equals("12")); - return b24; - } - - /** - * @param context android context - * @param date time to format - * @return time, with hours and minutes - */ - @SuppressWarnings("nls") - public static String getTimeString(Context context, Date date) { - String value; - if (is24HourFormat(context)) { - value = "H:mm"; - } else { - value = "h:mm a"; - } - return new SimpleDateFormat(value).format(date); - } - - /** - * @param context android context - * @param date date to format - * @return date, with month, day, and year - */ - @SuppressWarnings("nls") - public static String getDateString(Context context, Date date) { - String month = "'" + DateUtils.getMonthString(date.getMonth() + - Calendar.JANUARY, DateUtils.LENGTH_MEDIUM) + "'"; - String value; - // united states, you are special - if (Locale.US.equals(Locale.getDefault()) - || Locale.CANADA.equals(Locale.getDefault())) - value = month + " d yyyy"; - else - value = "d " + month + " yyyy"; - return new SimpleDateFormat(value).format(date); - } - - /** - * @return date format as getDateFormat with weekday - */ - @SuppressWarnings("nls") - public static String getDateStringWithWeekday(Context context, Date date) { - String weekday = DateUtils.getDayOfWeekString(date.getDay() + Calendar.SUNDAY, - DateUtils.LENGTH_LONG); - return weekday + ", " + getDateString(context, date); - } - - /** - * @return date format as getDateFormat with weekday - */ - @SuppressWarnings("nls") - public static String getDateStringWithTimeAndWeekday(Context context, Date date) { - return getDateStringWithWeekday(context, date) + " " + getTimeString(context, date); - } - - /** - * @return date with time at the end - */ - @SuppressWarnings("nls") - public static String getDateStringWithTime(Context context, Date date) { - return getDateString(context, date) + " " + getTimeString(context, date); - } - - /* ====================================================================== - * ============================================================= duration - * ====================================================================== */ - - /** - * Convenience method for dropping the preposition argument. - * @param duration in millis - * @param unitsToShow number of units to show (i.e. if 2, then 5 hours - * 3 minutes 2 seconds is truncated to 5 hours 3 minutes) - */ - public String getDurationString(long duration, int unitsToShow) { - return getDurationString(duration, unitsToShow, false); - } - - /** - * Format a time into the format: 5 days, 3 hours, 2 minutes - * - * @param duration in millis - * @param unitsToShow number of units to show (i.e. if 2, then 5 hours - * 3 minutes 2 seconds is truncated to 5 hours 3 minutes) - * @param withPreposition whether there is a preceding preposition - * @return - */ - public String getDurationString(long duration, int unitsToShow, boolean withPreposition) { - Resources r = ContextManager.getContext().getResources(); - short unitsDisplayed = 0; - duration = Math.abs(duration); - - if(duration == 0) - return r.getQuantityString(secondsResource, 0, 0); - - Date now = new Date(80, 1, 1); - Date then = new Date(now.getTime() + duration); - - int[] values = new int[] { - then.getYear() - now.getYear(), - then.getMonth() - now.getMonth(), - (then.getDate() - now.getDate())/7, - (then.getDate() - now.getDate()) - (then.getDate() - now.getDate())/7*7, - then.getHours() - now.getHours(), - then.getMinutes() - now.getMinutes(), - then.getSeconds() - now.getSeconds(), - }; - int[] maxValues = new int[] { - Integer.MAX_VALUE, - 12, - 5, - 7, - 24, - 60, - 60 - }; - - // perform rounding (this is definitely magic... trust the unit tests) - int cursor = 0; - while(values[cursor] == 0 && ++cursor < values.length) - ; - int postCursor = cursor + unitsToShow; - for(int i = values.length - 1; i >= postCursor; i--) { - if(values[i] >= maxValues[i]/2) { - values[i-1]++; - } - } - for(int i = Math.min(values.length, postCursor) - 1; i >= 1; i--) { - if(values[i] == maxValues[i]) { - values[i-1]++; - for(int j = i; j < values.length; j++) - values[j] = 0; - } - } - - - StringBuilder result = new StringBuilder(); - unitsDisplayed = displayUnits(r, yearsResource, unitsToShow, values[0], - unitsDisplayed, result); - unitsDisplayed = displayUnits(r, monthsResource, unitsToShow, values[1], - unitsDisplayed, result); - unitsDisplayed = displayUnits(r, weeksResource, unitsToShow, values[2], - unitsDisplayed, result); - unitsDisplayed = displayUnits(r, daysResource, unitsToShow, values[3], - unitsDisplayed, result); - unitsDisplayed = displayUnits(r, hoursResource, unitsToShow, values[4], - unitsDisplayed, result); - unitsDisplayed = displayUnits(r, minutesResource, unitsToShow, values[5], - unitsDisplayed, result); - unitsDisplayed = displayUnits(r, secondsResource, unitsToShow, values[6], - unitsDisplayed, result); - - return result.toString().trim(); - } - - /** Display units, rounding up if necessary. Returns units to show */ - private short displayUnits(Resources r, int resource, int unitsToShow, int value, - short unitsDisplayed, StringBuilder result) { - if(unitsDisplayed < unitsToShow && value > 0) { - result.append(r.getQuantityString(resource, value, value)). - append(' '); - unitsDisplayed++; - } - return unitsDisplayed; - } - - /** - * Format a time into the format: 5 days, 3 hrs, 2 min - * - * @param r Resources to get strings from - * @param timeInSeconds - * @param unitsToShow number of units to show (i.e. if 2, then 5 hours - * 3 minutes 2 seconds is truncated to 5 hours 3 minutes) - * @return - */ - public String getAbbreviatedDurationString(Resources r, int timeInSeconds, - int unitsToShow) { - short days, hours, minutes, seconds; - short unitsDisplayed = 0; - timeInSeconds = Math.abs(timeInSeconds); - - if(timeInSeconds == 0) - return r.getQuantityString(secondsAbbrevResource, 0, 0); - - days = (short)(timeInSeconds / 24 / 3600); - timeInSeconds -= days*24*3600; - hours = (short)(timeInSeconds / 3600); - timeInSeconds -= hours * 3600; - minutes = (short)(timeInSeconds / 60); - timeInSeconds -= minutes * 60; - seconds = (short)timeInSeconds; - - StringBuilder result = new StringBuilder(); - if(days > 0) { - // round up if needed - if(unitsDisplayed == unitsToShow && hours >= 12) - days++; - result.append(r.getQuantityString(daysAbbrevResource, days, days)). - append(' '); - unitsDisplayed++; - } - if(unitsDisplayed < unitsToShow && hours > 0) { - // round up if needed - if(unitsDisplayed == unitsToShow && minutes >= 30) - days++; - result.append(r.getQuantityString(hoursAbbrevResource, hours, - hours)). - append(' '); - unitsDisplayed++; - } - if(unitsDisplayed < unitsToShow && minutes > 0) { - // round up if needed - if(unitsDisplayed == unitsToShow && seconds >= 30) - days++; - result.append(r.getQuantityString(minutesAbbrevResource, minutes, - minutes)).append(' '); - unitsDisplayed++; - } - if(unitsDisplayed < unitsToShow && seconds > 0) { - result.append(r.getQuantityString(secondsAbbrevResource, seconds, - seconds)).append(' '); - } - - return result.toString().trim(); - } - -} diff --git a/astrid/common-src/com/todoroo/andlib/utility/DialogUtilities.java b/astrid/common-src/com/todoroo/andlib/utility/DialogUtilities.java deleted file mode 100644 index 3ccb6d7ea..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/DialogUtilities.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.todoroo.andlib.utility; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.view.View; - -import com.todoroo.andlib.service.Autowired; -import com.todoroo.andlib.service.DependencyInjectionService; - -public class DialogUtilities { - - @Autowired - public Integer informationDialogTitleResource; - - @Autowired - public Integer confirmDialogTitleResource; - - public DialogUtilities() { - DependencyInjectionService.getInstance().inject(this); - } - - /** - * Displays a dialog box with a EditText and an ok / cancel - * - * @param activity - * @param text - * @param okListener - */ - public void viewDialog(final Activity activity, final String text, - final View view, final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { - if(activity.isFinishing()) - return; - - activity.runOnUiThread(new Runnable() { - public void run() { - new AlertDialog.Builder(activity) - .setTitle(confirmDialogTitleResource) - .setMessage(text) - .setView(view) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, okListener) - .setNegativeButton(android.R.string.cancel, cancelListener) - .show().setOwnerActivity(activity); - } - }); - } - - /** - * Displays a dialog box with an OK button - * - * @param activity - * @param text - * @param okListener - */ - public void okDialog(final Activity activity, final String text, - final DialogInterface.OnClickListener okListener) { - if(activity.isFinishing()) - return; - - activity.runOnUiThread(new Runnable() { - public void run() { - new AlertDialog.Builder(activity) - .setTitle(informationDialogTitleResource) - .setMessage(text) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, okListener) - .show().setOwnerActivity(activity); - } - }); - } - - /** - * Displays a dialog box with an OK button - * - * @param activity - * @param text - * @param okListener - */ - public void okDialog(final Activity activity, final int icon, final CharSequence text, - final DialogInterface.OnClickListener okListener) { - if(activity.isFinishing()) - return; - - activity.runOnUiThread(new Runnable() { - public void run() { - new AlertDialog.Builder(activity) - .setTitle(informationDialogTitleResource) - .setMessage(text) - .setIcon(icon) - .setPositiveButton(android.R.string.ok, okListener) - .show().setOwnerActivity(activity); - } - }); - } - - /** - * Displays a dialog box with OK and Cancel buttons and custom title - * - * @param activity - * @param title - * @param text - * @param okListener - * @param cancelListener - */ - public void okCancelDialog(final Activity activity, final String title, - final String text, final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { - if(activity.isFinishing()) - return; - - activity.runOnUiThread(new Runnable() { - public void run() { - new AlertDialog.Builder(activity) - .setTitle(title) - .setMessage(text) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, okListener) - .setNegativeButton(android.R.string.cancel, cancelListener) - .show().setOwnerActivity(activity); - } - }); - } - - /** - * Displays a dialog box with OK and Cancel buttons - * - * @param activity - * @param text - * @param okListener - * @param cancelListener - */ - public void okCancelDialog(final Activity activity, final String text, - final DialogInterface.OnClickListener okListener, - final DialogInterface.OnClickListener cancelListener) { - if(activity.isFinishing()) - return; - - activity.runOnUiThread(new Runnable() { - public void run() { - new AlertDialog.Builder(activity) - .setTitle(confirmDialogTitleResource) - .setMessage(text) - .setIcon(android.R.drawable.ic_dialog_alert) - .setPositiveButton(android.R.string.ok, okListener) - .setNegativeButton(android.R.string.cancel, cancelListener) - .show().setOwnerActivity(activity); - } - }); - } - - /** - * Displays a progress dialog. Must be run on the UI thread - * @param context - * @param text - * @return - */ - public ProgressDialog progressDialog(Context context, String text) { - ProgressDialog dialog = new ProgressDialog(context); - dialog.setIndeterminate(true); - dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); - dialog.setMessage(text); - dialog.show(); - dialog.setOwnerActivity((Activity)context); - return dialog; - } - - /** - * Dismiss a dialog off the UI thread - * - * @param activity - * @param dialog - */ - public void dismissDialog(Activity activity, final ProgressDialog dialog) { - activity.runOnUiThread(new Runnable() { - public void run() { - try { - dialog.dismiss(); - } catch (Exception e) { - // could have killed activity - } - } - }); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/utility/EmailValidator.java b/astrid/common-src/com/todoroo/andlib/utility/EmailValidator.java deleted file mode 100644 index 2029596d6..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/EmailValidator.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.todoroo.andlib.utility; - -import java.util.regex.Pattern; - -/** - * E-mail Validator Copyright 2008 Les Hazlewood - * Licensed under the Apache License, Version 2.0 (the "License"); - */ -@SuppressWarnings("nls") -public final class EmailValidator { - - // RFC 2822 2.2.2 Structured Header Field Bodies - private static final String wsp = "[ \\t]"; // space or tab - private static final String fwsp = wsp + "*"; - - // RFC 2822 3.2.1 Primitive tokens - private static final String dquote = "\\\""; - // ASCII Control characters excluding white space: - private static final String noWsCtl = "\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F"; - // all ASCII characters except CR and LF: - private static final String asciiText = "[\\x01-\\x09\\x0B\\x0C\\x0E-\\x7F]"; - - // RFC 2822 3.2.2 Quoted characters: - // single backslash followed by a text char - private static final String quotedPair = "(\\\\" + asciiText + ")"; - - // RFC 2822 3.2.4 Atom: - private static final String atext = "[a-zA-Z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; - private static final String dotAtomText = atext + "+" + "(" + "\\." + atext - + "+)*"; - private static final String dotAtom = fwsp + "(" + dotAtomText + ")" + fwsp; - - // RFC 2822 3.2.5 Quoted strings: - // noWsCtl and the rest of ASCII except the doublequote and backslash - // characters: - private static final String qtext = "[" + noWsCtl - + "\\x21\\x23-\\x5B\\x5D-\\x7E]"; - private static final String qcontent = "(" + qtext + "|" + quotedPair + ")"; - private static final String quotedString = dquote + "(" + fwsp + qcontent - + ")*" + fwsp + dquote; - - // RFC 1035 tokens for domain names: - private static final String letter = "[a-zA-Z]"; - private static final String letDig = "[a-zA-Z0-9]"; - private static final String letDigHyp = "[a-zA-Z0-9-]"; - private static final String rfcLabel = letDig + "(" + letDigHyp + "{0,61}" - + letDig + ")?"; - private static final String rfc1035DomainName = rfcLabel + "(\\." - + rfcLabel + ")*\\." + letter + "{2,6}"; - - private static final String domain = rfc1035DomainName; - - private static final String localPart = "((" + dotAtom + ")|(" - + quotedString + "))"; - private static final String addrSpec = localPart + "@" + domain; - - // now compile a pattern for efficient re-use: - // if we're allowing quoted identifiers or not: - private static final String patternString = addrSpec; - public static final Pattern VALID_PATTERN = Pattern.compile(patternString); - - - public static boolean validateEmail(String value) { - return VALID_PATTERN.matcher(value).matches(); - } -} \ No newline at end of file diff --git a/astrid/common-src/com/todoroo/andlib/utility/Pair.java b/astrid/common-src/com/todoroo/andlib/utility/Pair.java deleted file mode 100644 index d3001a568..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/Pair.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.todoroo.andlib.utility; - -/** - * Pair utility class - * - * @author Tim Su - * - * @param - * @param - */ -public class Pair { - - private final L left; - private final R right; - - public R getRight() { - return right; - } - - public L getLeft() { - return left; - } - - public Pair(final L left, final R right) { - this.left = left; - this.right = right; - } - - public static Pair create(A left, B right) { - return new Pair(left, right); - } - - @Override - public final boolean equals(Object o) { - if (!(o instanceof Pair)) - return false; - - final Pair other = (Pair) o; - return equal(getLeft(), other.getLeft()) && equal(getRight(), other.getRight()); - } - - public static final boolean equal(Object o1, Object o2) { - if (o1 == null) { - return o2 == null; - } - return o1.equals(o2); - } - - @Override - public int hashCode() { - int hLeft = getLeft() == null ? 0 : getLeft().hashCode(); - int hRight = getRight() == null ? 0 : getRight().hashCode(); - - return hLeft + (57 * hRight); - } -} diff --git a/astrid/common-src/com/todoroo/andlib/utility/SoftHashMap.java b/astrid/common-src/com/todoroo/andlib/utility/SoftHashMap.java deleted file mode 100644 index a0726ec94..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/SoftHashMap.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.todoroo.andlib.utility; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -/** - * SoftHashMap from javaspecialists.eu Issue 98 - * - * - * @param - * @param - */ -public class SoftHashMap extends AbstractMap { - private static final long serialVersionUID = -3796460667941300642L; - - /** The internal HashMap that will hold the SoftReference. */ - private final Map> hash = new HashMap>(); - - private final Map, K> reverseLookup = new HashMap, K>(); - - /** Reference queue for cleared SoftReference objects. */ - protected final ReferenceQueue queue = new ReferenceQueue(); - - @Override - public V get(Object key) { - expungeStaleEntries(); - V result = null; - // We get the SoftReference represented by that key - SoftReference soft_ref = hash.get(key); - if (soft_ref != null) { - // From the SoftReference we get the value, which can be - // null if it has been garbage collected - result = soft_ref.get(); - if (result == null) { - // If the value has been garbage collected, remove the - // entry from the HashMap. - hash.remove(key); - reverseLookup.remove(soft_ref); - } - } - return result; - } - - private void expungeStaleEntries() { - Reference sv; - while ((sv = queue.poll()) != null) { - hash.remove(reverseLookup.remove(sv)); - } - } - - @Override - public V put(K key, V value) { - expungeStaleEntries(); - SoftReference soft_ref = new SoftReference(value, queue); - reverseLookup.put(soft_ref, key); - SoftReference result = hash.put(key, soft_ref); - if (result == null) - return null; - reverseLookup.remove(result); - return result.get(); - } - - @Override - public V remove(Object key) { - expungeStaleEntries(); - SoftReference result = hash.remove(key); - if (result == null) - return null; - return result.get(); - } - - @Override - public void clear() { - hash.clear(); - reverseLookup.clear(); - } - - @Override - public int size() { - expungeStaleEntries(); - return hash.size(); - } - - /** - * Returns a copy of the key/values in the map at the point of calling. - * However, setValue still sets the value in the actual SoftHashMap. - */ - @Override - public Set> entrySet() { - expungeStaleEntries(); - Set> result = new LinkedHashSet>(); - for (final Entry> entry : hash.entrySet()) { - final V value = entry.getValue().get(); - if (value != null) { - result.add(new Entry() { - public K getKey() { - return entry.getKey(); - } - - public V getValue() { - return value; - } - - public V setValue(V v) { - entry.setValue(new SoftReference(v, queue)); - return value; - } - }); - } - } - return result; - } -} diff --git a/astrid/common-src/com/todoroo/andlib/utility/UserTask.java b/astrid/common-src/com/todoroo/andlib/utility/UserTask.java deleted file mode 100644 index 61ad05a88..000000000 --- a/astrid/common-src/com/todoroo/andlib/utility/UserTask.java +++ /dev/null @@ -1,450 +0,0 @@ -package com.todoroo.andlib.utility; - -/* - * Copyright (C) 2008 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; - -import android.os.Handler; -import android.os.Message; -import android.os.Process; - -/** - *

UserTask enables proper and easy use of the UI thread. This class allows to - * perform background operations and publish results on the UI thread without - * having to manipulate threads and/or handlers.

- * - *

A user task is defined by a computation that runs on a background thread and - * whose result is published on the UI thread. A user task is defined by 3 generic - * types, called Params, Progress and Result, - * and 4 steps, called begin, doInBackground, - * processProgress and end.

- * - *

Usage

- *

UserTask must be subclassed to be used. The subclass will override at least - * one method ({@link #doInBackground(Object[])}), and most often will override a - * second one ({@link #end(Object)}.)

- * - *

Here is an example of subclassing:

- *
- * private class DownloadFilesTask extends UserTask<URL, Integer, Long> {
- *     public File doInBackground(URL... urls) {
- *         int count = urls.length;
- *         long totalSize = 0;
- *         for (int i = 0; i < count; i++) {
- *             totalSize += Downloader.downloadFile(urls[i]);
- *             publishProgress((int) ((i / (float) count) * 100));
- *         }
- *     }
- *
- *     public void processProgress(Integer... progress) {
- *         setProgressPercent(progress[0]);
- *     }
- *
- *     public void end(Long result) {
- *         showDialog("Downloaded " + result + " bytes");
- *     }
- * }
- * 
- * - *

Once created, a task is executed very simply:

- *
- * new DownloadFilesTask().execute(new URL[] { ... });
- * 
- * - *

User task's generic types

- *

The three types used by a user task are the following:

- *
    - *
  1. Params, the type of the parameters sent to the task upon - * execution.
  2. - *
  3. Progress, the type of the progress units published during - * the background computation.
  4. - *
  5. Result, the type of the result of the background - * computation.
  6. - *
- *

Not all types are always used by a user task. To mark a type as unused, - * simply use the type {@link Void}:

- *
- * private class MyTask extends UserTask
- *
- * 

The 4 steps

- *

When a user task is executed, the task goes through 4 steps:

- *
    - *
  1. {@link #begin()}, invoked on the UI thread immediately after the task - * is executed. This step is normally used to setup the task, for instance by - * showing a progress bar in the user interface.
  2. - *
  3. {@link #doInBackground(Object[])}, invoked on the background thread - * immediately after {@link #begin()} finishes executing. This step is used - * to perform background computation that can take a long time. The parameters - * of the user task are passed to this step. The result of the computation must - * be returned by this step and will be passed back to the last step. This step - * can also use {@link #publishProgress(Object[])} to publish one or more units - * of progress. These values are published on the UI thread, in the - * {@link #processProgress(Object[])} step.
  4. - *
  5. {@link #processProgress(Object[])}, invoked on the UI thread after a - * call to {@link #publishProgress(Object[])}. The timing of the execution is - * undefined. This method is used to display any form of progress in the user - * interface while the background computation is still executing. For instance, - * it can be used to animate a progress bar or show logs in a text field.
  6. - *
  7. {@link #end(Object)}, invoked on the UI thread after the background - * computation finishes. The result of the background computation is passed to - * this step as a parameter.
  8. - *
- * - *

Threading rules

- *

There are a few threading rules that must be followed for this class to - * work properly:

- *
    - *
  • The task instance must be created on the UI thread.
  • - *
  • {@link #execute(Object[])} must be invoked on the UI thread.
  • - *
  • Do not call {@link #begin()}, {@link #end(Object)}, - * {@link #doInBackground(Object[])}, {@link #processProgress(Object[])} - * manually.
  • - *
  • The task can be executed only once (an exception will be thrown if - * a second execution is attempted.)
  • - *
- */ -@SuppressWarnings("nls") -public abstract class UserTask { - private static final String LOG_TAG = "UserTask"; - - private static final int CORE_POOL_SIZE = 4; - private static final int MAXIMUM_POOL_SIZE = 10; - private static final int KEEP_ALIVE = 10; - - private static final BlockingQueue sWorkQueue = - new LinkedBlockingQueue(MAXIMUM_POOL_SIZE); - - private static final ThreadFactory sThreadFactory = new ThreadFactory() { - private final AtomicInteger mCount = new AtomicInteger(1); - - public Thread newThread(Runnable r) { - final Thread thread = new Thread(r, "UserTask #" + mCount.getAndIncrement()); - Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - return thread; - } - }; - - private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, - MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); - - private static final int MESSAGE_POST_RESULT = 0x1; - private static final int MESSAGE_POST_PROGRESS = 0x2; - - protected static InternalHandler sHandler; - - private final WorkerRunnable mWorker; - private final FutureTask mFuture; - - private volatile Status mStatus = Status.PENDING; - - /** - * Indicates the current status of the task. Each status will be set only once - * during the lifetime of a task. - */ - public enum Status { - /** - * Indicates that the task has not been executed yet. - */ - PENDING, - /** - * Indicates that the task is running. - */ - RUNNING, - /** - * Indicates that {@link UserTask#end(Object)} has finished. - */ - FINISHED, - } - - /** - * Creates a new user task. This constructor must be invoked on the UI thread. - */ - public UserTask() { - synchronized(UserTask.class) { - if (sHandler == null) { - sHandler = new InternalHandler(); - } - } - - mWorker = new WorkerRunnable() { - public Result call() throws Exception { - return doInBackground(mParams); - } - }; - - mFuture = new FutureTask(mWorker) { - @Override - protected void done() { - Result result = null; - try { - result = mFuture.get(); - } catch (InterruptedException e) { - android.util.Log.w(LOG_TAG, e); - } catch (ExecutionException e) { - throw new RuntimeException("An error occured while executing doInBackground()", - e.getCause()); - } catch (CancellationException e) { - return; - } catch (Throwable t) { - throw new RuntimeException("An error occured while executing " - + "doInBackground()", t); - } - - final Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, - new UserTaskResult(UserTask.this, result)); - message.sendToTarget(); - } - }; - } - - /** - * Returns the current status of this task. - * - * @return The current status. - */ - public final Status getStatus() { - return mStatus; - } - - /** - * Override this method to perform a computation on a background thread. The - * specified parameters are the parameters passed to {@link #execute(Object[])} - * by the caller of this task. - * - * This method can call {@link #publishProgress(Object[])} to publish updates - * on the UI thread. - * - * @params params The parameters of the task. - * - * @return A result, defined by the subclass of this task. - * - * @see #begin() - * @see #end(Object) - * @see #publishProgress(Object[]) - */ - public Result doInBackground(@SuppressWarnings("unused") Params... params) { - return null; - } - - /** - * Runs on the UI thread before {@link #doInBackground(Object[])}. - * - * @see #end(Object) - * @see #doInBackground(Object[]) - */ - public void begin() { - // ... - } - - /** - * Runs on the UI thread after {@link #doInBackground(Object[])}. The - * specified result is the value returned by {@link #doInBackground(Object[])} - * or null if the task was cancelled or an exception occured. - * - * @see #begin() - * @see #doInBackground(Object[]) - */ - public void end(@SuppressWarnings("unused") Result result) { - // ... - } - - /** - * Runs on the UI thread after {@link #publishProgress(Object[])} is invoked. - * The specified values are the values passed to {@link #publishProgress(Object[])}. - * - * @see #publishProgress(Object[]) - * @see #doInBackground(Object[]) - */ - public void processProgress(@SuppressWarnings("unused") Progress... values) { - // ... - } - - /** - * Returns true if this task was cancelled before it completed - * normally. - * - * @return true if task was cancelled before it completed - * - * @see #cancel(boolean) - */ - public final boolean isCancelled() { - return mFuture.isCancelled(); - } - - /** - * Attempts to cancel execution of this task. This attempt will - * fail if the task has already completed, already been cancelled, - * or could not be cancelled for some other reason. If successful, - * and this task has not started when cancel is called, - * this task should never run. If the task has already started, - * then the mayInterruptIfRunning parameter determines - * whether the thread executing this task should be interrupted in - * an attempt to stop the task. - * - * @param mayInterruptIfRunning true if the thread executing this - * task should be interrupted; otherwise, in-progress tasks are allowed - * to complete. - * - * @return false if the task could not be cancelled, - * typically because it has already completed normally; - * true otherwise - * - * @see #isCancelled() - */ - public final boolean cancel(boolean mayInterruptIfRunning) { - return mFuture.cancel(mayInterruptIfRunning); - } - - /** - * Waits if necessary for the computation to complete, and then - * retrieves its result. - * - * @return The computed result. - * - * @throws CancellationException If the computation was cancelled. - * @throws ExecutionException If the computation threw an exception. - * @throws InterruptedException If the current thread was interrupted - * while waiting. - */ - public final Result get() throws InterruptedException, ExecutionException { - return mFuture.get(); - } - - /** - * Waits if necessary for at most the given time for the computation - * to complete, and then retrieves its result. - * - * @return The computed result. - * - * @throws CancellationException If the computation was cancelled. - * @throws ExecutionException If the computation threw an exception. - * @throws InterruptedException If the current thread was interrupted - * while waiting. - * @throws TimeoutException If the wait timed out. - */ - public final Result get(long timeout, TimeUnit unit) throws InterruptedException, - ExecutionException, TimeoutException { - return mFuture.get(timeout, unit); - } - - /** - * Executes the task with the specified parameters. The task returns - * itself (this) so that the caller can keep a reference to it. - * - * This method must be invoked on the UI thread. - * - * @params params The parameters of the task. - * - * @return This instance of UserTask. - * - * @throws IllegalStateException If {@link #getStatus()} returns either - * {@link com.google.android.photostream.UserTask.Status#RUNNING} or - * {@link com.google.android.photostream.UserTask.Status#FINISHED}. - */ - public final UserTask execute(Params... params) { - if (mStatus != Status.PENDING) { - switch (mStatus) { - case RUNNING: - throw new IllegalStateException("Cannot execute task:" - + " the task is already running."); - case FINISHED: - throw new IllegalStateException("Cannot execute task:" - + " the task has already been executed " - + "(a task can be executed only once)"); - } - } - - mStatus = Status.RUNNING; - - begin(); - - mWorker.mParams = params; - - try { - sExecutor.execute(mFuture); - } catch (RejectedExecutionException e) { - // cannot schedule because of some other error. just die quietly - } - - return this; - } - - /** - * This method can be invoked from {@link #doInBackground(Object[])} to - * publish updates on the UI thread while the background computation is - * still running. Each call to this method will trigger the execution of - * {@link #processProgress(Object[])} on the UI thread. - * - * @params values The progress values to update the UI with. - * - * @see #processProgress(Object[]) - * @see #doInBackground(Object[]) - */ - protected final void publishProgress(Progress... values) { - sHandler.obtainMessage(MESSAGE_POST_PROGRESS, - new UserTaskResult(this, values)).sendToTarget(); - } - - protected void finish(Result result) { - end(result); - mStatus = Status.FINISHED; - } - - protected static class InternalHandler extends Handler { - @SuppressWarnings("unchecked") - @Override - public void handleMessage(Message msg) { - @SuppressWarnings("rawtypes") - UserTaskResult result = (UserTaskResult) msg.obj; - switch (msg.what) { - case MESSAGE_POST_RESULT: - // There is only one result - result.mTask.finish(result.mData[0]); - break; - case MESSAGE_POST_PROGRESS: - result.mTask.processProgress(result.mData); - break; - } - } - } - - protected static abstract class WorkerRunnable implements Callable { - Params[] mParams; - } - - protected static class UserTaskResult { - final UserTask mTask; - final Data[] mData; - - UserTaskResult(UserTask task, Data... data) { - mTask = task; - mData = data; - } - } -} diff --git a/astrid/default.properties b/astrid/default.properties index c5d5335ee..d47181a7f 100644 --- a/astrid/default.properties +++ b/astrid/default.properties @@ -9,6 +9,7 @@ # Indicates whether an apk should be generated for each density. split.density=false +android.library.reference.1=../../astridApi/ # Project target. target=android-8 apk-configurations= diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/Alarm.java b/astrid/plugin-src/com/todoroo/astrid/alarms/Alarm.java index 29e0e7d0a..61bbacf81 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/Alarm.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/Alarm.java @@ -2,7 +2,7 @@ package com.todoroo.astrid.alarms; import com.todoroo.andlib.data.Property.IntegerProperty; import com.todoroo.andlib.data.Property.LongProperty; -import com.todoroo.astrid.model.Metadata; +import com.todoroo.astrid.data.Metadata; /** * Metadata entry for a task alarm diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java index f03ed0aac..1f6263145 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmControlSet.java @@ -15,8 +15,8 @@ import com.timsu.astrid.R; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.widget.DateControlSet; import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; /** * Control set to manage adding and removing tags diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java index 4a25599e1..f411e5b7c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmDetailExposer.java @@ -12,7 +12,7 @@ import com.timsu.astrid.R; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; -import com.todoroo.astrid.model.Metadata; +import com.todoroo.astrid.data.Metadata; /** * Exposes Task Detail for tags, i.e. "Tags: frogs, animals" diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java index 4cdef4b35..09aac7fe3 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmService.java @@ -19,8 +19,8 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.reminders.Notifications; import com.todoroo.astrid.reminders.ReminderService; import com.todoroo.astrid.service.MetadataService; diff --git a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java index 6b4696de0..676b29b08 100644 --- a/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/alarms/AlarmTaskRepeatListener.java @@ -9,7 +9,7 @@ import android.content.Intent; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; -import com.todoroo.astrid.model.Metadata; +import com.todoroo.astrid.data.Metadata; public class AlarmTaskRepeatListener extends BroadcastReceiver { diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java b/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java index edde100e4..4f144cfa3 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/BackupPreferences.java @@ -11,7 +11,6 @@ import android.view.View; import android.view.ViewGroup.OnHierarchyChangeListener; import com.timsu.astrid.R; -import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.widget.TodorooPreferences; @@ -32,9 +31,6 @@ public class BackupPreferences extends TodorooPreferences { static final String PREF_BACKUP_LAST_ERROR = "backupError"; //$NON-NLS-1$ - @Autowired - private DialogUtilities dialogUtilities; - private int statusColor = Color.BLACK; @Override @@ -66,7 +62,7 @@ public class BackupPreferences extends TodorooPreferences { restorePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { - dialogUtilities.okCancelDialog(BackupPreferences.this, + DialogUtilities.okCancelDialog(BackupPreferences.this, getString(R.string.DLG_information_title), getString(R.string.backup_BPr_how_to_restore_dialog), AddOnActivity.createAddOnClicker(BackupPreferences.this, false), null); @@ -115,7 +111,7 @@ public class BackupPreferences extends TodorooPreferences { statusColor = Color.rgb(100, 0, 0); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { - dialogUtilities.okDialog(BackupPreferences.this, error, null); + DialogUtilities.okDialog(BackupPreferences.this, error, null); return true; } }); diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java index e9722312e..489f654f6 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlExporter.java @@ -25,8 +25,8 @@ import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.core.PluginServices; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Preferences; diff --git a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java index 93e963be0..30c31cf16 100644 --- a/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java +++ b/astrid/plugin-src/com/todoroo/astrid/backup/TasksXmlImporter.java @@ -32,12 +32,12 @@ import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.core.PluginServices; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.legacy.LegacyImportance; import com.todoroo.astrid.legacy.LegacyRepeatInfo; import com.todoroo.astrid.legacy.LegacyRepeatInfo.LegacyRepeatInterval; import com.todoroo.astrid.legacy.LegacyTaskModel; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; import com.todoroo.astrid.service.MetadataService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.tags.TagService; diff --git a/astrid/plugin-src/com/todoroo/astrid/common/SyncProvider.java b/astrid/plugin-src/com/todoroo/astrid/common/SyncProvider.java deleted file mode 100644 index 5b27684b7..000000000 --- a/astrid/plugin-src/com/todoroo/astrid/common/SyncProvider.java +++ /dev/null @@ -1,331 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.common; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; - -import android.app.Activity; -import android.app.Notification; -import android.app.Service; -import android.content.Context; -import android.widget.Toast; - -import com.timsu.astrid.R; -import com.todoroo.andlib.data.Property.LongProperty; -import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.service.NotificationManager; -import com.todoroo.astrid.model.Task; -import com.todoroo.astrid.utility.Constants; - -/** - * A helper class for writing synchronization services for Astrid. This class - * contains logic for merging incoming changes and writing outgoing changes. - *

- * Use {@link initiate} as the entry point for your synchronization service, - * which should handle authentication and then call {@link synchronizeTasks} to - * initiate synchronization. - * - * @author timsu - * - */ -public abstract class SyncProvider { - - // --- abstract methods - your services should implement these - - /** - * Perform log in (launching activity if necessary) and sync. This is - * invoked when users manually request synchronization - * - * @param activity - * context - */ - abstract protected void initiateManual(Activity activity); - - /** - * Perform synchronize. Since this can be called from background services, - * you should not open up new activities. Instead, if the user is not signed - * in, your service should do nothing. - * - * @param service - * context - */ - abstract protected void initiateBackground(Service service); - - /** - * Updates the text of a notification and the intent to open when tapped - * @param context - * @param notification - */ - abstract protected void updateNotification(Context context, Notification n); - - /** - * Deal with an exception that occurs during synchronization - * - * @param tag - * short string description of where error occurred - * @param e - * exception - * @param displayError - * whether to display error to the user - */ - abstract protected void handleException(String tag, Exception e, boolean displayError); - - /** - * Create a task on the remote server. - * - * @param task - * task to create - * @return task created on remote server - */ - abstract protected TYPE create(TYPE task) throws IOException; - - /** - * Push variables from given task to the remote server. - * - * @param task - * task proxy to push - * @param remoteTask - * remote task that we merged with. may be null - */ - abstract protected void push(TYPE task, TYPE remote) throws IOException; - - /** - * Fetch remote task. Used to re-read merged tasks - * - * @param task - * task with id's to re-read - * @return new Task - */ - abstract protected TYPE pull(TYPE task) throws IOException; - - /** - * Reads a task container from a task in the database - * - * @param task - */ - abstract protected TYPE read(TodorooCursor task) throws IOException; - - /** - * Save task. Used to save local tasks that have been updated and remote - * tasks that need to be created locally - * - * @param task - */ - abstract protected void write(TYPE task) throws IOException; - - /** - * Finds a task in the list with the same remote identifier(s) as - * the task passed in - * - * @return task from list if matches, null otherwise - */ - abstract protected int matchTask(ArrayList tasks, TYPE target); - - /** - * Transfer remote identifier(s) from one task to another - */ - abstract protected void transferIdentifiers(TYPE source, - TYPE destination); - - // --- implementation - - private final Notification notification; - - public SyncProvider() { - // initialize notification - int icon = android.R.drawable.stat_notify_sync; - long when = System.currentTimeMillis(); - notification = new Notification(icon, null, when); - notification.flags |= Notification.FLAG_ONGOING_EVENT; - } - - public void synchronize(final Context context) { - // display toast - if(context instanceof Activity) { - ((Activity) context).runOnUiThread(new Runnable() { - @Override - public void run() { - Toast.makeText(context, R.string.SyP_progress_toast, - Toast.LENGTH_LONG).show(); - } - }); - initiateManual((Activity)context); - } else if(context instanceof Service) { - // display notification - updateNotification(context, notification); - final NotificationManager nm = new NotificationManager.AndroidNotificationManager(context); - nm.notify(Constants.NOTIFICATION_SYNC, notification); - - // start next step in background thread - new Thread(new Runnable() { - public void run() { - try { - initiateBackground((Service)context); - } finally { - nm.cancel(Constants.NOTIFICATION_SYNC); - } - } - }).start(); - } - } - - // --- synchronization logic - - /** - * Helper to synchronize remote tasks with our local database. - * - * This initiates the following process: 1. local changes are read 2. remote - * changes are read 3. local tasks are merged with remote changes and pushed - * across 4. remote changes are then read in - * - * @param data synchronization data structure - */ - protected void synchronizeTasks(SyncData data) throws IOException { - int length; - - // create internal data structures - HashMap remoteNewTaskNameMap = new HashMap(); - length = data.remoteUpdated.size(); - for(int i = 0; i < length; i++) { - TYPE remote = data.remoteUpdated.get(i); - if(remote.task.getId() != Task.NO_ID) - continue; - remoteNewTaskNameMap.put(remote.task.getValue(Task.TITLE), i); - } - - // 1. CREATE: grab newly created tasks and create them remotely - length = data.localCreated.getCount(); - for(int i = 0; i < length; i++) { - data.localCreated.moveToNext(); - TYPE local = read(data.localCreated); - try { - - String taskTitle = local.task.getValue(Task.TITLE); - - /* If there exists an incoming remote task with the same name and no - * mapping, we don't want to create this on the remote server, - * because user could have synchronized like this before. Instead, - * we create a mapping and do an update. - */ - if (remoteNewTaskNameMap.containsKey(taskTitle)) { - int remoteIndex = remoteNewTaskNameMap.remove(taskTitle); - TYPE remote = data.remoteUpdated.get(remoteIndex); - - transferIdentifiers(remote, local); - push(local, remote); - - // re-read remote task after merge, update remote task list - remote = pull(remote); - remote.task.setId(local.task.getId()); - data.remoteUpdated.set(remoteIndex, remote); - - } else { - create(local); - } - } catch (Exception e) { - handleException("sync-local-created", e, false); //$NON-NLS-1$ - } - write(local); - } - - // 2. UPDATE: for each updated local task - length = data.localUpdated.getCount(); - for(int i = 0; i < length; i++) { - data.localUpdated.moveToNext(); - TYPE local = read(data.localUpdated); - try { - if(local.task == null) - continue; - - // if there is a conflict, merge - int remoteIndex = matchTask((ArrayList)data.remoteUpdated, local); - if(remoteIndex != -1) { - TYPE remote = data.remoteUpdated.get(remoteIndex); - push(local, remote); - - // re-read remote task after merge - remote = pull(remote); - remote.task.setId(local.task.getId()); - data.remoteUpdated.set(remoteIndex, remote); - } else { - push(local, null); - } - } catch (Exception e) { - handleException("sync-local-updated", e, false); //$NON-NLS-1$ - } - write(local); - } - - // 3. REMOTE: load remote information - - // Rearrange remoteTasks so completed tasks get synchronized first. - // This prevents bugs where a repeated task has two copies come down - // the wire, the new version and the completed old version. The new - // version would get merged, then completed, if done in the wrong order. - - Collections.sort(data.remoteUpdated, new Comparator() { - private static final int SENTINEL = -2; - private final int check(TYPE o1, TYPE o2, LongProperty property) { - long o1Property = o1.task.getValue(property); - long o2Property = o2.task.getValue(property); - if(o1Property != 0 && o2Property != 0) - return 0; - else if(o1Property != 0) - return -1; - else if(o2Property != 0) - return 1; - return SENTINEL; - } - public int compare(TYPE o1, TYPE o2) { - int comparison = check(o1, o2, Task.DELETION_DATE); - if(comparison != SENTINEL) - return comparison; - comparison = check(o1, o2, Task.COMPLETION_DATE); - if(comparison != SENTINEL) - return comparison; - return 0; - } - }); - - length = data.remoteUpdated.size(); - for(int i = 0; i < length; i++) { - TYPE remote = data.remoteUpdated.get(i); - - // don't synchronize new & deleted / completed tasks - if(!remote.task.isSaved() && (remote.task.isDeleted() || - remote.task.isCompleted())) - continue; - - try { - write(remote); - } catch (Exception e) { - handleException("sync-remote-updated", e, false); //$NON-NLS-1$ - } - } - } - - // --- helper classes - - /** data structure builder */ - protected static class SyncData { - public final ArrayList remoteUpdated; - - public final TodorooCursor localCreated; - public final TodorooCursor localUpdated; - - public SyncData(ArrayList remoteUpdated, - TodorooCursor localCreated, - TodorooCursor localUpdated) { - super(); - this.remoteUpdated = remoteUpdated; - this.localCreated = localCreated; - this.localUpdated = localUpdated; - } - - } -} diff --git a/astrid/plugin-src/com/todoroo/astrid/common/SyncProviderPreferences.java b/astrid/plugin-src/com/todoroo/astrid/common/SyncProviderPreferences.java deleted file mode 100644 index 0c90c8499..000000000 --- a/astrid/plugin-src/com/todoroo/astrid/common/SyncProviderPreferences.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.todoroo.astrid.common; - -import java.util.Date; - -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.content.res.Resources; -import android.graphics.Color; -import android.os.Bundle; -import android.preference.Preference; -import android.preference.Preference.OnPreferenceClickListener; -import android.view.View; -import android.view.ViewGroup.OnHierarchyChangeListener; - -import com.timsu.astrid.R; -import com.todoroo.andlib.service.Autowired; -import com.todoroo.andlib.utility.AndroidUtilities; -import com.todoroo.andlib.utility.DateUtilities; -import com.todoroo.andlib.utility.DialogUtilities; -import com.todoroo.andlib.widget.TodorooPreferences; - -/** - * Utility class for common synchronization action: displaying synchronization - * preferences and an action panel so users can initiate actions from the menu. - * - * @author Tim Su sync - if(!loggedIn) { - status = r.getString(R.string.sync_status_loggedout); - statusColor = Color.RED; - preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference p) { - startSync(); - finish(); - return true; - } - }); - } - // sync is occurring - else if(getUtilities().isOngoing()) { - status = r.getString(R.string.sync_status_ongoing); - statusColor = Color.rgb(0, 0, 100); - } - // last sync was error - else if(getUtilities().getLastAttemptedSyncDate() != 0) { - status = r.getString(R.string.sync_status_failed, - DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, - new Date(getUtilities().getLastAttemptedSyncDate()))); - if(getUtilities().getLastSyncDate() > 0) { - subtitle = r.getString(R.string.sync_status_failed_subtitle, - DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, - new Date(getUtilities().getLastSyncDate()))); - } - statusColor = Color.rgb(100, 0, 0); - preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference p) { - String error = getUtilities().getLastError(); - if(error != null) - dialogUtilities.okDialog(SyncProviderPreferences.this, error, null); - return true; - } - }); - } else if(getUtilities().getLastSyncDate() > 0) { - status = r.getString(R.string.sync_status_success, - DateUtilities.getDateStringWithTime(SyncProviderPreferences.this, - new Date(getUtilities().getLastSyncDate()))); - statusColor = Color.rgb(0, 100, 0); - } else { - status = r.getString(R.string.sync_status_never); - statusColor = Color.rgb(0, 0, 100); - preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference p) { - startSync(); - finish(); - return true; - } - }); - } - preference.setTitle(status); - preference.setSummary(subtitle); - - View view = findViewById(R.id.status); - if(view != null) - view.setBackgroundColor(statusColor); - } - - // sync button - else if (r.getString(R.string.sync_SPr_sync_key).equals(preference.getKey())) { - boolean loggedIn = getUtilities().isLoggedIn(); - preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference p) { - startSync(); - finish(); - return true; - } - }); - if(!loggedIn) - preference.setTitle(R.string.sync_SPr_sync_log_in); - } - - // log out button - else if (r.getString(R.string.sync_SPr_forget_key).equals(preference.getKey())) { - boolean loggedIn = getUtilities().isLoggedIn(); - preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference p) { - dialogUtilities.okCancelDialog(SyncProviderPreferences.this, - r.getString(R.string.sync_forget_confirm), new OnClickListener() { - @Override - public void onClick(DialogInterface dialog, - int which) { - logOut(); - initializePreference(getPreferenceScreen()); - } - }, null); - return true; - } - }); - if(!loggedIn) - preference.setEnabled(false); - } - } - -} \ No newline at end of file diff --git a/astrid/plugin-src/com/todoroo/astrid/common/SyncProviderUtilities.java b/astrid/plugin-src/com/todoroo/astrid/common/SyncProviderUtilities.java deleted file mode 100644 index ced9daf15..000000000 --- a/astrid/plugin-src/com/todoroo/astrid/common/SyncProviderUtilities.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.todoroo.astrid.common; - -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import android.preference.PreferenceManager; - -import com.todoroo.andlib.service.ContextManager; -import com.todoroo.andlib.utility.DateUtilities; - -/** - * Sync Provider Utility class for accessing preferences - */ -abstract public class SyncProviderUtilities { - - /** - * @return your plugin identifier - */ - abstract public String getIdentifier(); - - /** - * @return key for sync interval - */ - abstract public int getSyncIntervalKey(); - - // --- implementation - - private static final String PREF_TOKEN = "_token"; //$NON-NLS-1$ - - private static final String PREF_LAST_SYNC = "_last_sync"; //$NON-NLS-1$ - - private static final String PREF_LAST_ATTEMPTED_SYNC = "_last_attempted"; //$NON-NLS-1$ - - private static final String PREF_LAST_ERROR = "_last_error"; //$NON-NLS-1$ - - private static final String PREF_ONGOING = "_ongoing"; //$NON-NLS-1$ - - /** Get preferences object from the context */ - protected static SharedPreferences getPrefs() { - return PreferenceManager.getDefaultSharedPreferences(ContextManager.getContext()); - } - - /** - * @return true if we have a token for this user, false otherwise - */ - public boolean isLoggedIn() { - return getPrefs().getString(getIdentifier() + PREF_TOKEN, null) != null; - } - - /** authentication token, or null if doesn't exist */ - public String getToken() { - return getPrefs().getString(getIdentifier() + PREF_TOKEN, null); - } - - /** Sets the authentication token. Set to null to clear. */ - public void setToken(String setting) { - Editor editor = getPrefs().edit(); - editor.putString(getIdentifier() + PREF_TOKEN, setting); - editor.commit(); - } - - /** @return Last Successful Sync Date, or 0 */ - public long getLastSyncDate() { - return getPrefs().getLong(getIdentifier() + PREF_LAST_SYNC, 0); - } - - /** @return Last Attempted Sync Date, or 0 if it was successful */ - public long getLastAttemptedSyncDate() { - return getPrefs().getLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); - } - - /** @return Last Error, or null if no last error */ - public String getLastError() { - return getPrefs().getString(PREF_LAST_ERROR, null); - } - - /** @return Last Error, or null if no last error */ - public boolean isOngoing() { - return getPrefs().getBoolean(getIdentifier() + PREF_ONGOING, false); - } - - /** Deletes Last Successful Sync Date */ - public void clearLastSyncDate() { - Editor editor = getPrefs().edit(); - editor.remove(getIdentifier() + PREF_LAST_SYNC); - editor.commit(); - } - - /** Set Last Successful Sync Date */ - public void setLastError(String error) { - Editor editor = getPrefs().edit(); - editor.putString(getIdentifier() + PREF_LAST_ERROR, error); - editor.commit(); - } - - /** Set Ongoing */ - public void stopOngoing() { - Editor editor = getPrefs().edit(); - editor.putBoolean(getIdentifier() + PREF_ONGOING, false); - editor.commit(); - } - - /** Set Last Successful Sync Date */ - public void recordSuccessfulSync() { - Editor editor = getPrefs().edit(); - editor.putLong(getIdentifier() + PREF_LAST_SYNC, DateUtilities.now()); - editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, 0); - editor.commit(); - } - - /** Set Last Attempted Sync Date */ - public void recordSyncStart() { - Editor editor = getPrefs().edit(); - editor.putLong(getIdentifier() + PREF_LAST_ATTEMPTED_SYNC, - DateUtilities.now()); - editor.putString(getIdentifier() + PREF_LAST_ERROR, null); - editor.putBoolean(getIdentifier() + PREF_ONGOING, true); - editor.commit(); - } - - /** - * Reads the frequency, in seconds, auto-sync should occur. - * - * @return seconds duration, or 0 if not desired - */ - public int getSyncAutoSyncFrequency() { - String value = getPrefs().getString( - ContextManager.getContext().getString( - getSyncIntervalKey()), null); - if (value == null) - return 0; - try { - return Integer.parseInt(value); - } catch (Exception e) { - return 0; - } - } -} diff --git a/astrid/plugin-src/com/todoroo/astrid/common/TaskContainer.java b/astrid/plugin-src/com/todoroo/astrid/common/TaskContainer.java deleted file mode 100644 index a4ff29e64..000000000 --- a/astrid/plugin-src/com/todoroo/astrid/common/TaskContainer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.todoroo.astrid.common; - -import java.util.ArrayList; - -import com.todoroo.andlib.utility.AndroidUtilities; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; - -/** - * Container class for transmitting tasks and including local and remote - * metadata. Synchronization Providers can subclass this class if desired. - * - * @see {@link SyncProvider} - * @author Tim Su - * - */ -public class TaskContainer { - public Task task; - public ArrayList metadata; - - /** - * Check if the metadata contains anything with the given key - * @param key - * @return first match. or null - */ - public Metadata findMetadata(String key) { - for(Metadata item : metadata) { - if(AndroidUtilities.equals(key, item.getValue(Metadata.KEY))) - return item; - } - return null; - } - -} \ No newline at end of file diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java index bda90c3db..9653e8a90 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CoreFilterExposer.java @@ -20,8 +20,8 @@ import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.tags.TagService; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java index f4e7ad211..52f787cfb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterActivity.java @@ -38,8 +38,8 @@ import com.todoroo.astrid.api.PermaSql; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.tags.TagService.Tag; diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java index f603b5a62..d52df7554 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterAdapter.java @@ -18,7 +18,7 @@ import android.widget.TextView; import com.timsu.astrid.R; import com.todoroo.astrid.core.CustomFilterActivity.CriterionInstance; -import com.todoroo.astrid.model.AddOn; +import com.todoroo.astrid.data.AddOn; /** * Adapter for {@link AddOn}s diff --git a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java index 0fceca416..79605b126 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/CustomFilterExposer.java @@ -15,7 +15,6 @@ import android.os.Bundle; import com.timsu.astrid.R; import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.sql.Order; import com.todoroo.andlib.sql.Query; @@ -26,7 +25,7 @@ import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.api.FilterCategory; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.dao.StoreObjectDao; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.StoreObject; /** * Exposes Astrid's built in filters to the {@link FilterListActivity} @@ -101,9 +100,6 @@ public final class CustomFilterExposer extends BroadcastReceiver { */ public static class DeleteActivity extends Activity { - @Autowired - DialogUtilities dialogUtilities; - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -117,7 +113,7 @@ public final class CustomFilterExposer extends BroadcastReceiver { final String name = getIntent().getStringExtra(TOKEN_FILTER_NAME); DependencyInjectionService.getInstance().inject(this); - dialogUtilities.okCancelDialog(this, + DialogUtilities.okCancelDialog(this, getString(R.string.DLG_delete_this_item_question, name), new DialogInterface.OnClickListener() { diff --git a/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java b/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java index c1c67eaca..5e60bd77d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/PluginServices.java @@ -33,7 +33,7 @@ public final class PluginServices { MetadataService metadataService; @Autowired - DialogUtilities dialogUtilities; + DialogUtilities DialogUtilities; @Autowired DateUtilities dateUtilities; @@ -79,7 +79,7 @@ public final class PluginServices { } public static DialogUtilities getDialogUtilities() { - return getInstance().dialogUtilities; + return getInstance().DialogUtilities; } public static DateUtilities getDateUtilities() { diff --git a/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java b/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java index a355e8667..b3a78e749 100644 --- a/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java +++ b/astrid/plugin-src/com/todoroo/astrid/core/SavedFilter.java @@ -10,7 +10,7 @@ import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.core.CustomFilterActivity.CriterionInstance; import com.todoroo.astrid.dao.StoreObjectDao; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.StoreObject; /** * {@link StoreObject} entries for a saved custom filter diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java index 70f4380bb..a50b74407 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalControlSet.java @@ -27,8 +27,8 @@ import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.gcal.Calendars.CalendarResult; -import com.todoroo.astrid.model.Task; /** * Control Set for managing repeats diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java index d7e6843f3..0599b4b78 100644 --- a/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/gcal/GCalTaskCompleteListener.java @@ -12,7 +12,7 @@ import android.util.Log; import com.timsu.astrid.R; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; public class GCalTaskCompleteListener extends BroadcastReceiver { diff --git a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java index b60afb28b..4c30a3157 100644 --- a/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java +++ b/astrid/plugin-src/com/todoroo/astrid/locale/LocaleReceiver.java @@ -16,7 +16,7 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.activity.ShortcutActivity; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.reminders.Notifications; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Preferences; diff --git a/astrid/plugin-src/com/todoroo/astrid/notes/NoteDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/notes/NoteDetailExposer.java index 3f487750d..1b989e76a 100644 --- a/astrid/plugin-src/com/todoroo/astrid/notes/NoteDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/notes/NoteDetailExposer.java @@ -11,7 +11,7 @@ import android.content.Intent; import com.timsu.astrid.R; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.utility.Preferences; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevControlSet.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevControlSet.java index 53f2aa993..1306f82ba 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevControlSet.java @@ -25,9 +25,9 @@ import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.producteev.sync.ProducteevDashboard; import com.todoroo.astrid.producteev.sync.ProducteevDataService; import com.todoroo.astrid.producteev.sync.ProducteevSyncProvider; @@ -46,7 +46,6 @@ public class ProducteevControlSet implements TaskEditControlSet { // --- instance variables private final Activity activity; - private final DialogUtilities dialogUtilites; private final View view; private Task myTask; @@ -65,7 +64,6 @@ public class ProducteevControlSet implements TaskEditControlSet { DependencyInjectionService.getInstance().inject(this); this.activity = activity; - this.dialogUtilites = new DialogUtilities(); view = LayoutInflater.from(activity).inflate(R.layout.producteev_control, parent, true); @@ -94,7 +92,7 @@ public class ProducteevControlSet implements TaskEditControlSet { dialog.cancel(); } else { // create the real dashboard, select it in the spinner and refresh responsiblespinner - ProgressDialog progressDialog = dialogUtilites.progressDialog(context, + ProgressDialog progressDialog = com.todoroo.andlib.utility.DialogUtilities.progressDialog(context, context.getString(R.string.DLG_wait)); try { progressDialog.show(); @@ -107,11 +105,11 @@ public class ProducteevControlSet implements TaskEditControlSet { adapter.insert(newDashboard, adapter.getCount()-1); dashSelector.setSelection(adapter.getCount()-2); refreshResponsibleSpinner(newDashboard.getUsers()); - dialogUtilites.dismissDialog(context, progressDialog); + DialogUtilities.dismissDialog(context, progressDialog); } } catch (Exception e) { - dialogUtilites.dismissDialog(context, progressDialog); - dialogUtilites.okDialog(context, + DialogUtilities.dismissDialog(context, progressDialog); + DialogUtilities.okDialog(context, context.getString(R.string.DLG_error, e.getMessage()), new OnClickListener() { @Override @@ -133,7 +131,7 @@ public class ProducteevControlSet implements TaskEditControlSet { dashboardSelector.setSelection(lastDashboardSelection); } }; - dialogUtilites.viewDialog(ProducteevControlSet.this.activity, + DialogUtilities.viewDialog(ProducteevControlSet.this.activity, ProducteevControlSet.this.activity.getString(R.string.producteev_create_dashboard_name), editor, okListener, diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java index 69f14ccfd..c02153b2b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevDetailExposer.java @@ -11,8 +11,8 @@ import com.timsu.astrid.R; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.astrid.adapter.TaskAdapter; import com.todoroo.astrid.api.AstridApiConstants; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; import com.todoroo.astrid.producteev.sync.ProducteevDashboard; import com.todoroo.astrid.producteev.sync.ProducteevDataService; import com.todoroo.astrid.producteev.sync.ProducteevNote; diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevFilterExposer.java index 384547c5c..7d88030ad 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevFilterExposer.java @@ -22,8 +22,8 @@ import com.todoroo.astrid.api.FilterListHeader; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; import com.todoroo.astrid.producteev.sync.ProducteevDashboard; import com.todoroo.astrid.producteev.sync.ProducteevDataService; import com.todoroo.astrid.producteev.sync.ProducteevTask; diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevLoginActivity.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevLoginActivity.java index 5fb911b59..1c27050ff 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevLoginActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevLoginActivity.java @@ -32,7 +32,6 @@ import android.widget.EditText; import android.widget.TextView; import com.timsu.astrid.R; -import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.utility.DialogUtilities; @@ -49,9 +48,6 @@ import com.todoroo.astrid.utility.Preferences; */ public class ProducteevLoginActivity extends Activity { - @Autowired - DialogUtilities dialogUtilities; - // --- ui initialization public ProducteevLoginActivity() { @@ -130,7 +126,7 @@ public class ProducteevLoginActivity extends Activity { private void performLogin(final String email, final String password) { - final ProgressDialog dialog = dialogUtilities.progressDialog(this, + final ProgressDialog dialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_wait)); final TextView errors = (TextView) findViewById(R.id.error); dialog.show(); @@ -168,7 +164,7 @@ public class ProducteevLoginActivity extends Activity { private void performSignup(final String email, final String password, final String firstName, final String lastName) { - final ProgressDialog dialog = dialogUtilities.progressDialog(this, + final ProgressDialog dialog = DialogUtilities.progressDialog(this, getString(R.string.DLG_wait)); final TextView errors = (TextView) findViewById(R.id.error); dialog.show(); diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevPreferences.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevPreferences.java index de93da04f..3d51b53ae 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevPreferences.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevPreferences.java @@ -7,12 +7,12 @@ import android.preference.Preference; import com.timsu.astrid.R; import com.todoroo.andlib.utility.AndroidUtilities; -import com.todoroo.astrid.common.SyncProviderPreferences; -import com.todoroo.astrid.common.SyncProviderUtilities; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.StoreObject; import com.todoroo.astrid.producteev.sync.ProducteevDashboard; import com.todoroo.astrid.producteev.sync.ProducteevDataService; import com.todoroo.astrid.producteev.sync.ProducteevSyncProvider; +import com.todoroo.astrid.sync.SyncProviderPreferences; +import com.todoroo.astrid.sync.SyncProviderUtilities; /** * Displays synchronization preferences and an action panel so users can diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevUtilities.java b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevUtilities.java index 6d3e0e669..bbf7f12fa 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevUtilities.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/ProducteevUtilities.java @@ -1,7 +1,7 @@ package com.todoroo.astrid.producteev; import com.timsu.astrid.R; -import com.todoroo.astrid.common.SyncProviderUtilities; +import com.todoroo.astrid.sync.SyncProviderUtilities; import com.todoroo.astrid.utility.Preferences; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDashboard.java b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDashboard.java index 5c763d3c3..ce5d93bf7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDashboard.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDashboard.java @@ -5,7 +5,7 @@ import java.util.StringTokenizer; import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.Property.StringProperty; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.StoreObject; /** * {@link StoreObject} entries for a Producteev Dashboard diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDataService.java b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDataService.java index 742a123d3..cc2573362 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDataService.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevDataService.java @@ -26,9 +26,9 @@ import com.todoroo.astrid.dao.TaskDao; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.StoreObjectDao.StoreObjectCriteria; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.producteev.ProducteevUtilities; import com.todoroo.astrid.producteev.api.ApiUtilities; import com.todoroo.astrid.service.MetadataService; diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevNote.java b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevNote.java index f93f06cb6..c277529aa 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevNote.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevNote.java @@ -4,7 +4,7 @@ import org.json.JSONObject; import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.Property.StringProperty; -import com.todoroo.astrid.model.Metadata; +import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.producteev.api.ApiUtilities; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java index 7d2b1d4e8..fdc25f0f9 100644 --- a/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java +++ b/astrid/plugin-src/com/todoroo/astrid/producteev/sync/ProducteevSyncProvider.java @@ -35,11 +35,9 @@ import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.activity.ShortcutActivity; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.Filter; -import com.todoroo.astrid.common.SyncProvider; -import com.todoroo.astrid.common.TaskContainer; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.producteev.ProducteevBackgroundService; import com.todoroo.astrid.producteev.ProducteevFilterExposer; import com.todoroo.astrid.producteev.ProducteevLoginActivity; @@ -50,6 +48,8 @@ import com.todoroo.astrid.producteev.api.ApiServiceException; import com.todoroo.astrid.producteev.api.ApiUtilities; import com.todoroo.astrid.producteev.api.ProducteevInvoker; import com.todoroo.astrid.service.AstridDependencyInjector; +import com.todoroo.astrid.sync.SyncContainer; +import com.todoroo.astrid.sync.SyncProvider; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Preferences; @@ -72,9 +72,6 @@ public class ProducteevSyncProvider extends SyncProvider property, TaskContainer remoteTask) { + private boolean shouldTransmit(SyncContainer task, Property property, SyncContainer remoteTask) { if(!task.task.containsValue(property)) return false; @@ -711,7 +708,7 @@ public class ProducteevSyncProvider extends SyncProvider * */ -public class ProducteevTaskContainer extends TaskContainer { +public class ProducteevTaskContainer extends SyncContainer { public Metadata pdvTask; diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java b/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java index 53c20484d..de4ea8c0f 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/Notifications.java @@ -23,7 +23,7 @@ import com.todoroo.andlib.service.NotificationManager; import com.todoroo.andlib.service.NotificationManager.AndroidNotificationManager; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Preferences; diff --git a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java index dc199f3af..535807ddb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java +++ b/astrid/plugin-src/com/todoroo/astrid/reminders/ReminderService.java @@ -23,7 +23,7 @@ import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.utility.Preferences; diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java index cf4bddc5c..d5e7b13fb 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatControlSet.java @@ -29,7 +29,7 @@ import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.ui.NumberPicker; import com.todoroo.astrid.ui.NumberPickerDialog; import com.todoroo.astrid.ui.NumberPickerDialog.OnNumberPickedListener; diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java index 9ae22f082..67998dde8 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatDetailExposer.java @@ -18,7 +18,7 @@ import com.google.ical.values.WeekdayNum; import com.timsu.astrid.R; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; /** * Exposes Task Detail for repeats, i.e. "Repeats every 2 days" diff --git a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java index 3d9248a57..ed0a86fc7 100644 --- a/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/repeats/RepeatTaskCompleteListener.java @@ -19,7 +19,7 @@ import com.google.ical.values.RRule; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; public class RepeatTaskCompleteListener extends BroadcastReceiver { diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java index 110a7a1fc..1b053dc03 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java @@ -24,7 +24,7 @@ import com.todoroo.astrid.api.FilterCategory; import com.todoroo.astrid.api.FilterListHeader; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; +import com.todoroo.astrid.data.Metadata; import com.todoroo.astrid.tags.TagService.Tag; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java index 62509f576..12a476d3d 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagService.java @@ -15,8 +15,8 @@ import com.todoroo.andlib.sql.QueryTemplate; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; /** * Provides operations for working with tags diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java index b24c0960a..680b9598e 100644 --- a/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagsControlSet.java @@ -27,8 +27,8 @@ import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.tags.TagService.Tag; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionExposer.java index b530b6a3b..ddc41fa11 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerActionExposer.java @@ -13,7 +13,7 @@ import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.TaskAction; import com.todoroo.astrid.api.TaskDecoration; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; /** * Exposes {@link TaskDecoration} for timers diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java index 866fee76d..c0776e6ec 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerControlSet.java @@ -8,7 +8,7 @@ import com.timsu.astrid.R; import com.todoroo.andlib.data.Property.IntegerProperty; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.astrid.activity.TaskEditActivity.TaskEditControlSet; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.ui.TimeDurationControlSet; /** diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java index 45b5159ac..105b6119b 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerDecorationExposer.java @@ -19,7 +19,7 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.TaskDecoration; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; /** * Exposes {@link TaskDecoration} for timers diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java index 224dd34fc..a8d274587 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerFilterExposer.java @@ -18,7 +18,7 @@ import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; /** * Exposes "working on" filter to the {@link FilterListActivity} diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java index ab1439959..69d632dff 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerPlugin.java @@ -17,7 +17,7 @@ import com.todoroo.astrid.api.Addon; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.utility.Constants; public class TimerPlugin extends BroadcastReceiver { diff --git a/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java b/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java index 8da52acaf..6dcee1def 100644 --- a/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java +++ b/astrid/plugin-src/com/todoroo/astrid/timers/TimerTaskCompleteListener.java @@ -6,7 +6,7 @@ import android.content.Intent; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.core.PluginServices; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; public class TimerTaskCompleteListener extends BroadcastReceiver { diff --git a/astrid/res/layout/status_preference.xml b/astrid/res/layout/status_preference.xml deleted file mode 100644 index 65bf255aa..000000000 --- a/astrid/res/layout/status_preference.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/astrid/res/values/colors.xml b/astrid/res/values/colors.xml index e201ecdd0..bc8dbafcc 100644 --- a/astrid/res/values/colors.xml +++ b/astrid/res/values/colors.xml @@ -19,12 +19,6 @@ #ff44bb66 #ffbbbbbb #ffff0000 - - #ffff5555 - #fffea400 - #ff33a5e8 - #ff808080 - #ff505050 - #ff202020 + diff --git a/astrid/res/values/strings-core.xml b/astrid/res/values/strings-core.xml index 31ce8d9f5..c1430bbab 100644 --- a/astrid/res/values/strings-core.xml +++ b/astrid/res/values/strings-core.xml @@ -21,66 +21,6 @@ - - - 1 Year - - %d Years - - - - 1 Month - - %d Months - - - - 1 Week - - %d Weeks - - - - 1 Day - - %d Days - - - - 1 Hour - - %d Hours - - - - 1 Minute - - %d Minutes - - - - 1 Second - - %d Seconds - - - - 1 Hr - - %d Hrs - - - - 1 Min - - %d Min - - - - 1 Sec - - %d Sec - 1 task @@ -89,43 +29,13 @@ - - - Confirm? - - - Question: - - - Information - - - Yes - - - No - - - Close - - - Oops, looks like some trouble occurred! Here\'s what happened:\n\n%s - + Delete this task? Delete this item: %s? - - - Done - - - Cancel - - - Please wait... - + Upgrading your tasks... diff --git a/astrid/res/values/strings-sync.xml b/astrid/res/values/strings-sync.xml deleted file mode 100644 index 586ddf1ae..000000000 --- a/astrid/res/values/strings-sync.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - Synchronizing your tasks... - - - Synchronizing... - - - Synchronization - - - - - Status - - - Not Logged In! - - Sync Ongoing... - - Last Sync: %s - - Failed On: %s - - Last Successful Sync: %s - - Never Synchronized! - - - Options - - - Background Sync - - Background synchronization is disabled - - Currently set to: %s - - - Wifi Only Setting - - Background synchronization only happens when on Wifi - - Background synchronization will always occur - - - Actions - - - Synchronize Now! - - Log In & Synchronize! - - - Log Out - - Clears all synchronization data - - - Log out / clear synchronization data? - - - - disable - every fifteen minutes - every thirty minutes - every hour - every three hours - every six hours - every twelve hours - every day - every three days - every week - - - - diff --git a/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java b/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java index 73e3d219a..024b81b83 100644 --- a/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/AddOnActivity.java @@ -18,7 +18,7 @@ import com.timsu.astrid.R; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.astrid.adapter.AddOnAdapter; -import com.todoroo.astrid.model.AddOn; +import com.todoroo.astrid.data.AddOn; import com.todoroo.astrid.service.AddOnService; import com.todoroo.astrid.service.AstridDependencyInjector; diff --git a/astrid/src/com/todoroo/astrid/activity/EditPreferences.java b/astrid/src/com/todoroo/astrid/activity/EditPreferences.java index 6afd38e77..25eb03bd6 100644 --- a/astrid/src/com/todoroo/astrid/activity/EditPreferences.java +++ b/astrid/src/com/todoroo/astrid/activity/EditPreferences.java @@ -28,7 +28,7 @@ import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.widget.TodorooPreferences; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.dao.Database; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.StartupService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Constants; @@ -53,9 +53,6 @@ public class EditPreferences extends TodorooPreferences { @Autowired private Database database; - @Autowired - private DialogUtilities dialogUtilities; - public EditPreferences() { DependencyInjectionService.getInstance().inject(this); } @@ -161,7 +158,7 @@ public class EditPreferences extends TodorooPreferences { task.setValue(Task.TITLE, Integer.toString(i)); taskService.save(task); } - dialogUtilities.okDialog(EditPreferences.this, "done", null); + DialogUtilities.okDialog(EditPreferences.this, "done", null); return false; } }); @@ -173,7 +170,7 @@ public class EditPreferences extends TodorooPreferences { public boolean onPreferenceClick(Preference p) { database.openForWriting(); taskService.deleteWhere(Criterion.all); - dialogUtilities.okDialog(EditPreferences.this, "done", null); + DialogUtilities.okDialog(EditPreferences.this, "done", null); return false; } }); diff --git a/astrid/src/com/todoroo/astrid/activity/FilterListActivity.java b/astrid/src/com/todoroo/astrid/activity/FilterListActivity.java index 9aa23b516..cd05deffe 100644 --- a/astrid/src/com/todoroo/astrid/activity/FilterListActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/FilterListActivity.java @@ -47,7 +47,7 @@ import com.todoroo.astrid.api.FilterCategory; import com.todoroo.astrid.api.FilterListItem; import com.todoroo.astrid.core.IntentFilter; import com.todoroo.astrid.core.SearchFilter; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.StartupService; import com.todoroo.astrid.utility.Constants; @@ -76,7 +76,7 @@ public class FilterListActivity extends ExpandableListActivity { protected ExceptionService exceptionService; @Autowired - protected DialogUtilities dialogUtilities; + protected DialogUtilities DialogUtilities; FilterAdapter adapter = null; diff --git a/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java b/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java index 976e21393..456000fc8 100644 --- a/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/ShortcutActivity.java @@ -31,7 +31,7 @@ import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.sql.QueryTemplate; import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.astrid.api.Filter; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; /** * This activity is launched when a user opens up a notification from the diff --git a/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java b/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java index d469e99f2..dde851c63 100644 --- a/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/SortSelectionActivity.java @@ -14,7 +14,7 @@ import com.todoroo.andlib.sql.Functions; import com.todoroo.andlib.sql.Order; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.TaskService; /** diff --git a/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java b/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java index 36748afd1..95d742038 100644 --- a/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskEditActivity.java @@ -74,8 +74,8 @@ import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.alarms.AlarmControlSet; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.dao.Database; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.gcal.GCalControlSet; -import com.todoroo.astrid.model.Task; import com.todoroo.astrid.producteev.ProducteevControlSet; import com.todoroo.astrid.producteev.ProducteevUtilities; import com.todoroo.astrid.reminders.Notifications; @@ -148,9 +148,6 @@ public final class TaskEditActivity extends TabActivity { @Autowired private MetadataService metadataService; - @Autowired - private DateUtilities dateUtilities; - @Autowired private AddOnService addOnService; @@ -461,7 +458,9 @@ public final class TaskEditActivity extends TabActivity { } else { stringResource = R.string.TEA_onTaskSave_due; } - String formattedDate = dateUtilities.getDurationString(dueFromNow, 1); + CharSequence formattedDate = + DateUtils.getRelativeTimeSpanString(dueFromNow, DateUtilities.now(), + DateUtils.MINUTE_IN_MILLIS, 0); Toast.makeText(this, getResources().getString(stringResource, formattedDate), Toast.LENGTH_SHORT).show(); @@ -795,7 +794,7 @@ public final class TaskEditActivity extends TabActivity { Task.URGENCY_TOMORROW); String dayAfterTomorrow = DateUtils.getDayOfWeekString( new Date(DateUtilities.now() + 2 * DateUtilities.ONE_DAY).getDay() + - Calendar.SUNDAY, DateUtils.FORMAT_ABBREV_ALL); + Calendar.SUNDAY, DateUtils.LENGTH_LONG); urgencyValues[3] = new UrgencyValue(dayAfterTomorrow, Task.URGENCY_DAY_AFTER); urgencyValues[4] = new UrgencyValue(labels[4], diff --git a/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java b/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java index 5f80c5887..1fd140993 100644 --- a/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java +++ b/astrid/src/com/todoroo/astrid/activity/TaskListActivity.java @@ -75,8 +75,8 @@ import com.todoroo.astrid.backup.BackupActivity; import com.todoroo.astrid.core.CoreFilterExposer; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.reminders.Notifications; import com.todoroo.astrid.reminders.ReminderService; import com.todoroo.astrid.reminders.ReminderService.AlarmScheduler; @@ -142,7 +142,7 @@ public class TaskListActivity extends ListActivity implements OnScrollListener, protected MetadataService metadataService; @Autowired - protected DialogUtilities dialogUtilities; + protected DialogUtilities DialogUtilities; @Autowired protected Database database; diff --git a/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java b/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java index 933c82d49..63bb7a335 100644 --- a/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/AddOnAdapter.java @@ -21,7 +21,7 @@ import android.widget.ImageView; import android.widget.TextView; import com.timsu.astrid.R; -import com.todoroo.astrid.model.AddOn; +import com.todoroo.astrid.data.AddOn; /** * Adapter for {@link AddOn}s diff --git a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java index d99c1caed..837f5ad78 100644 --- a/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java +++ b/astrid/src/com/todoroo/astrid/adapter/TaskAdapter.java @@ -47,7 +47,7 @@ import com.todoroo.astrid.activity.TaskListActivity; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.api.TaskAction; import com.todoroo.astrid.api.TaskDecoration; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.AddOnService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Constants; diff --git a/astrid/src/com/todoroo/astrid/dao/Database.java b/astrid/src/com/todoroo/astrid/dao/Database.java index 949845695..d03d534cf 100644 --- a/astrid/src/com/todoroo/astrid/dao/Database.java +++ b/astrid/src/com/todoroo/astrid/dao/Database.java @@ -9,9 +9,9 @@ import com.todoroo.andlib.data.AbstractDatabase; import com.todoroo.andlib.data.AbstractModel; import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.Table; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; +import com.todoroo.astrid.data.Task; /** * Database wrapper diff --git a/astrid/src/com/todoroo/astrid/dao/MetadataDao.java b/astrid/src/com/todoroo/astrid/dao/MetadataDao.java index 5b269fe29..fd11b52d2 100644 --- a/astrid/src/com/todoroo/astrid/dao/MetadataDao.java +++ b/astrid/src/com/todoroo/astrid/dao/MetadataDao.java @@ -7,7 +7,7 @@ package com.todoroo.astrid.dao; import android.database.Cursor; -import com.todoroo.andlib.data.GenericDao; +import com.todoroo.andlib.data.DatabaseDao; import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.service.Autowired; @@ -15,8 +15,8 @@ import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Join; import com.todoroo.andlib.sql.Query; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.provider.Astrid2TaskProvider; /** @@ -25,7 +25,7 @@ import com.todoroo.astrid.provider.Astrid2TaskProvider; * @author Tim Su * */ -public class MetadataDao extends GenericDao { +public class MetadataDao extends DatabaseDao { @Autowired private Database database; diff --git a/astrid/src/com/todoroo/astrid/dao/StoreObjectDao.java b/astrid/src/com/todoroo/astrid/dao/StoreObjectDao.java index cffb6c76a..5b27305c4 100644 --- a/astrid/src/com/todoroo/astrid/dao/StoreObjectDao.java +++ b/astrid/src/com/todoroo/astrid/dao/StoreObjectDao.java @@ -5,11 +5,11 @@ */ package com.todoroo.astrid.dao; -import com.todoroo.andlib.data.GenericDao; +import com.todoroo.andlib.data.DatabaseDao; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.sql.Criterion; -import com.todoroo.astrid.model.StoreObject; +import com.todoroo.astrid.data.StoreObject; /** * Data Access layer for {@link StoreObject}-related operations. @@ -17,7 +17,7 @@ import com.todoroo.astrid.model.StoreObject; * @author Tim Su * */ -public class StoreObjectDao extends GenericDao { +public class StoreObjectDao extends DatabaseDao { @Autowired private Database database; diff --git a/astrid/src/com/todoroo/astrid/dao/TaskDao.java b/astrid/src/com/todoroo/astrid/dao/TaskDao.java index c5f7d2841..c1dbdd5c6 100644 --- a/astrid/src/com/todoroo/astrid/dao/TaskDao.java +++ b/astrid/src/com/todoroo/astrid/dao/TaskDao.java @@ -10,7 +10,7 @@ import android.content.Context; import android.content.Intent; import com.timsu.astrid.R; -import com.todoroo.andlib.data.GenericDao; +import com.todoroo.andlib.data.DatabaseDao; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; @@ -19,7 +19,7 @@ import com.todoroo.andlib.sql.Functions; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.provider.Astrid2TaskProvider; import com.todoroo.astrid.reminders.Notifications; import com.todoroo.astrid.reminders.ReminderService; @@ -32,7 +32,7 @@ import com.todoroo.astrid.widget.TasksWidget; * @author Tim Su * */ -public class TaskDao extends GenericDao { +public class TaskDao extends DatabaseDao { @Autowired private MetadataDao metadataDao; diff --git a/astrid/src/com/todoroo/astrid/model/AddOn.java b/astrid/src/com/todoroo/astrid/data/AddOn.java similarity index 98% rename from astrid/src/com/todoroo/astrid/model/AddOn.java rename to astrid/src/com/todoroo/astrid/data/AddOn.java index c23961a52..edb5ea584 100644 --- a/astrid/src/com/todoroo/astrid/model/AddOn.java +++ b/astrid/src/com/todoroo/astrid/data/AddOn.java @@ -1,4 +1,4 @@ -package com.todoroo.astrid.model; +package com.todoroo.astrid.data; import android.graphics.Bitmap; diff --git a/astrid/src/com/todoroo/astrid/legacy/AlarmDatabase.java b/astrid/src/com/todoroo/astrid/legacy/AlarmDatabase.java index e3fc1c698..6545096fb 100644 --- a/astrid/src/com/todoroo/astrid/legacy/AlarmDatabase.java +++ b/astrid/src/com/todoroo/astrid/legacy/AlarmDatabase.java @@ -6,7 +6,7 @@ package com.todoroo.astrid.legacy; import com.todoroo.andlib.data.AbstractDatabase; -import com.todoroo.andlib.data.GenericDao; +import com.todoroo.andlib.data.DatabaseDao; import com.todoroo.andlib.data.Table; /** @@ -41,7 +41,7 @@ public class AlarmDatabase extends AbstractDatabase { // --- implementation - private final GenericDao dao = new GenericDao(TransitionalAlarm.class, this); + private final DatabaseDao dao = new DatabaseDao(TransitionalAlarm.class, this); @Override protected String getName() { @@ -58,7 +58,7 @@ public class AlarmDatabase extends AbstractDatabase { return TABLES; } - public GenericDao getDao() { + public DatabaseDao getDao() { return dao; } diff --git a/astrid/src/com/todoroo/astrid/legacy/TransitionalAlarm.java b/astrid/src/com/todoroo/astrid/legacy/TransitionalAlarm.java index 1a62f7723..4efe16bc2 100644 --- a/astrid/src/com/todoroo/astrid/legacy/TransitionalAlarm.java +++ b/astrid/src/com/todoroo/astrid/legacy/TransitionalAlarm.java @@ -11,7 +11,7 @@ import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.Property.LongProperty; import com.todoroo.andlib.data.Table; import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; /** * Data Model which represents an alarm. This is a transitional class - diff --git a/astrid/src/com/todoroo/astrid/model/Metadata.java b/astrid/src/com/todoroo/astrid/model/Metadata.java deleted file mode 100644 index 9fcb3a665..000000000 --- a/astrid/src/com/todoroo/astrid/model/Metadata.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.model; - - -import android.content.ContentValues; -import android.net.Uri; - -import com.todoroo.andlib.data.AbstractModel; -import com.todoroo.andlib.data.Property; -import com.todoroo.andlib.data.Table; -import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.data.Property.LongProperty; -import com.todoroo.andlib.data.Property.StringProperty; -import com.todoroo.astrid.api.AstridApiConstants; - -/** - * Data Model which represents a piece of metadata associated with a task - * - * @author Tim Su - * - */ -@SuppressWarnings("nls") -public class Metadata extends AbstractModel { - - // --- table - - /** table for this model */ - public static final Table TABLE = new Table("metadata", Metadata.class); - - /** content uri for this model */ - public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.PACKAGE + "/" + - TABLE.name); - - // --- properties - - /** ID */ - public static final LongProperty ID = new LongProperty( - TABLE, ID_PROPERTY_NAME); - - /** Associated Task */ - public static final LongProperty TASK = new LongProperty( - TABLE, "task"); - - /** Metadata Key */ - public static final StringProperty KEY = new StringProperty( - TABLE, "key"); - - /** Metadata Text Value Column 1 */ - public static final StringProperty VALUE1 = new StringProperty( - TABLE, "value"); - - /** Metadata Text Value Column 2 */ - public static final StringProperty VALUE2 = new StringProperty( - TABLE, "value2"); - - /** Metadata Text Value Column 3 */ - public static final StringProperty VALUE3 = new StringProperty( - TABLE, "value3"); - - /** Metadata Text Value Column 4 */ - public static final StringProperty VALUE4 = new StringProperty( - TABLE, "value4"); - - /** Metadata Text Value Column 5 */ - public static final StringProperty VALUE5 = new StringProperty( - TABLE, "value5"); - - /** List of all properties for this model */ - public static final Property[] PROPERTIES = generateProperties(Metadata.class); - - // --- defaults - - /** Default values container */ - private static final ContentValues defaultValues = new ContentValues(); - - @Override - public ContentValues getDefaultValues() { - return defaultValues; - } - - // --- data access boilerplate - - public Metadata() { - super(); - } - - public Metadata(TodorooCursor cursor) { - this(); - readPropertiesFromCursor(cursor); - } - - public void readFromCursor(TodorooCursor cursor) { - super.readPropertiesFromCursor(cursor); - } - - @Override - public long getId() { - return getIdHelper(ID); - }; - - // --- parcelable helpers - - private static final Creator CREATOR = new ModelCreator(Metadata.class); - - @Override - protected Creator getCreator() { - return CREATOR; - } - -} diff --git a/astrid/src/com/todoroo/astrid/model/StoreObject.java b/astrid/src/com/todoroo/astrid/model/StoreObject.java deleted file mode 100644 index ae183a0fa..000000000 --- a/astrid/src/com/todoroo/astrid/model/StoreObject.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * See the file "LICENSE" for the full license governing this code. - */ -package com.todoroo.astrid.model; - - -import android.content.ContentValues; -import android.net.Uri; - -import com.todoroo.andlib.data.AbstractModel; -import com.todoroo.andlib.data.Property; -import com.todoroo.andlib.data.Table; -import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.data.Property.LongProperty; -import com.todoroo.andlib.data.Property.StringProperty; -import com.todoroo.astrid.api.AstridApiConstants; - -/** - * Data Model which represents a piece of data unrelated to a task - * - * @author Tim Su - * - */ -@SuppressWarnings("nls") -public class StoreObject extends AbstractModel { - - // --- table - - /** table for this model */ - public static final Table TABLE = new Table("store", StoreObject.class); - - /** content uri for this model */ - public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.PACKAGE + "/" + - TABLE.name); - - // --- properties - - /** ID */ - public static final LongProperty ID = new LongProperty( - TABLE, ID_PROPERTY_NAME); - - /** Store Type Key */ - public static final StringProperty TYPE = new StringProperty( - TABLE, "type"); - - /** Store Item Key */ - public static final StringProperty ITEM= new StringProperty( - TABLE, "item"); - - /** Store Value Column 1 */ - public static final StringProperty VALUE1 = new StringProperty( - TABLE, "value"); - - /** Store Value Column 2 */ - public static final StringProperty VALUE2 = new StringProperty( - TABLE, "value2"); - - /** Store Value Column 3 */ - public static final StringProperty VALUE3 = new StringProperty( - TABLE, "value3"); - - /** Store Value Column 4 */ - public static final StringProperty VALUE4 = new StringProperty( - TABLE, "value4"); - - /** Store Value Column 5 */ - public static final StringProperty VALUE5 = new StringProperty( - TABLE, "value5"); - - /** List of all properties for this model */ - public static final Property[] PROPERTIES = generateProperties(StoreObject.class); - - // --- defaults - - /** Default values container */ - private static final ContentValues defaultValues = new ContentValues(); - - @Override - public ContentValues getDefaultValues() { - return defaultValues; - } - - // --- data access boilerplate - - public StoreObject() { - super(); - } - - public StoreObject(TodorooCursor cursor) { - this(); - readPropertiesFromCursor(cursor); - } - - public void readFromCursor(TodorooCursor cursor) { - super.readPropertiesFromCursor(cursor); - } - - @Override - public long getId() { - return getIdHelper(ID); - }; - - // --- parcelable helpers - - private static final Creator CREATOR = new ModelCreator(StoreObject.class); - - @Override - protected Creator getCreator() { - return CREATOR; - } - -} diff --git a/astrid/src/com/todoroo/astrid/model/Task.java b/astrid/src/com/todoroo/astrid/model/Task.java deleted file mode 100644 index a8a7bc1ae..000000000 --- a/astrid/src/com/todoroo/astrid/model/Task.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Copyright (c) 2009, Todoroo Inc - * All Rights Reserved - * http://www.todoroo.com - */ -package com.todoroo.astrid.model; - - -import java.util.Date; - -import android.content.ContentValues; -import android.content.res.Resources; -import android.net.Uri; - -import com.timsu.astrid.R; -import com.todoroo.andlib.data.AbstractModel; -import com.todoroo.andlib.data.Property; -import com.todoroo.andlib.data.Table; -import com.todoroo.andlib.data.TodorooCursor; -import com.todoroo.andlib.data.Property.IntegerProperty; -import com.todoroo.andlib.data.Property.LongProperty; -import com.todoroo.andlib.data.Property.StringProperty; -import com.todoroo.andlib.utility.DateUtilities; -import com.todoroo.astrid.api.AstridApiConstants; - -/** - * Data Model which represents a task users need to accomplish. - * - * @author Tim Su - * - */ -@SuppressWarnings("nls") -public final class Task extends AbstractModel { - - // --- table and uri - - /** table for this model */ - public static final Table TABLE = new Table("tasks", Task.class); - - /** content uri for this model */ - public static final Uri CONTENT_URI = Uri.parse("content://" + AstridApiConstants.PACKAGE + "/" + - TABLE.name); - - // --- properties - - /** ID */ - public static final LongProperty ID = new LongProperty( - TABLE, ID_PROPERTY_NAME); - - /** Name of Task */ - public static final StringProperty TITLE = new StringProperty( - TABLE, "title"); - - /** Importance of Task (see importance flags) */ - public static final IntegerProperty IMPORTANCE = new IntegerProperty( - TABLE, "importance"); - - /** Unixtime Task is due, 0 if not set */ - public static final LongProperty DUE_DATE = new LongProperty( - TABLE, "dueDate"); - - /** Unixtime Task should be hidden until, 0 if not set */ - public static final LongProperty HIDE_UNTIL = new LongProperty( - TABLE, "hideUntil"); - - /** Unixtime Task was created */ - public static final LongProperty CREATION_DATE = new LongProperty( - TABLE, "created"); - - /** Unixtime Task was last touched */ - public static final LongProperty MODIFICATION_DATE = new LongProperty( - TABLE, "modified"); - - /** Unixtime Task was completed. 0 means active */ - public static final LongProperty COMPLETION_DATE = new LongProperty( - TABLE, "completed"); - - /** Unixtime Task was deleted. 0 means not deleted */ - public static final LongProperty DELETION_DATE = new LongProperty( - TABLE, "deleted"); - - /** Cached Details Column - built from add-on detail exposers. A null - * value means there is no value in the cache and it needs to be - * refreshed */ - public static final StringProperty DETAILS = new StringProperty( - TABLE, "details"); - - // --- for migration purposes from astrid 2 (eventually we may want to - // move these into the metadata table and treat them as plug-ins - - public static final StringProperty NOTES = new StringProperty( - TABLE, "notes"); - - public static final IntegerProperty ESTIMATED_SECONDS = new IntegerProperty( - TABLE, "estimatedSeconds"); - - public static final IntegerProperty ELAPSED_SECONDS = new IntegerProperty( - TABLE, "elapsedSeconds"); - - public static final LongProperty TIMER_START = new LongProperty( - TABLE, "timerStart"); - - public static final IntegerProperty POSTPONE_COUNT = new IntegerProperty( - TABLE, "postponeCount"); - - /** Flags for when to send reminders */ - public static final IntegerProperty REMINDER_FLAGS = new IntegerProperty( - TABLE, "notificationFlags"); - - /** Reminder period, in milliseconds. 0 means disabled */ - public static final LongProperty REMINDER_PERIOD = new LongProperty( - TABLE, "notifications"); - - /** Unixtime the last reminder was triggered */ - public static final LongProperty REMINDER_LAST = new LongProperty( - TABLE, "lastNotified"); - - public static final StringProperty RECURRENCE = new StringProperty( - TABLE, "recurrence"); - - public static final IntegerProperty FLAGS = new IntegerProperty( - TABLE, "flags"); - - public static final StringProperty CALENDAR_URI = new StringProperty( - TABLE, "calendarUri"); - - /** List of all properties for this model */ - public static final Property[] PROPERTIES = generateProperties(Task.class); - - // --- flags - - /** whether repeat occurs relative to completion date instead of due date */ - public static final int FLAG_REPEAT_AFTER_COMPLETION = 1 << 1; - - // --- notification flags - - /** whether to send a reminder at deadline */ - public static final int NOTIFY_AT_DEADLINE = 1 << 1; - - /** whether to send reminders while task is overdue */ - public static final int NOTIFY_AFTER_DEADLINE = 1 << 2; - - /** reminder mode non-stop */ - public static final int NOTIFY_NONSTOP = 1 << 3; - - // --- importance settings - - public static final int IMPORTANCE_DO_OR_DIE = 0; - public static final int IMPORTANCE_MUST_DO = 1; - public static final int IMPORTANCE_SHOULD_DO = 2; - public static final int IMPORTANCE_NONE = 3; - - /** - * @return colors that correspond to importance values - */ - public static int[] getImportanceColors(Resources r) { - return new int[] { - r.getColor(R.color.importance_1), - r.getColor(R.color.importance_2), - r.getColor(R.color.importance_3), - r.getColor(R.color.importance_4), - - // for external services with importances > 4 - r.getColor(R.color.importance_5), - r.getColor(R.color.importance_6), - }; - } - - public static final int IMPORTANCE_MOST = IMPORTANCE_DO_OR_DIE; - public static final int IMPORTANCE_LEAST = IMPORTANCE_NONE; - - // --- defaults - - /** Default values container */ - private static final ContentValues defaultValues = new ContentValues(); - - static { - defaultValues.put(TITLE.name, ""); - defaultValues.put(DUE_DATE.name, 0); - defaultValues.put(HIDE_UNTIL.name, 0); - defaultValues.put(COMPLETION_DATE.name, 0); - defaultValues.put(DELETION_DATE.name, 0); - defaultValues.put(IMPORTANCE.name, IMPORTANCE_NONE); - - defaultValues.put(CALENDAR_URI.name, ""); - defaultValues.put(RECURRENCE.name, ""); - defaultValues.put(REMINDER_PERIOD.name, 0); - defaultValues.put(REMINDER_FLAGS.name, 0); - defaultValues.put(ESTIMATED_SECONDS.name, 0); - defaultValues.put(ELAPSED_SECONDS.name, 0); - defaultValues.put(POSTPONE_COUNT.name, 0); - defaultValues.put(NOTES.name, ""); - defaultValues.put(FLAGS.name, 0); - defaultValues.put(TIMER_START.name, 0); - defaultValues.put(DETAILS.name, (String)null); - } - - @Override - public ContentValues getDefaultValues() { - return defaultValues; - } - - // --- data access boilerplate - - public Task() { - super(); - } - - public Task(TodorooCursor cursor) { - this(); - readPropertiesFromCursor(cursor); - } - - public void readFromCursor(TodorooCursor cursor) { - super.readPropertiesFromCursor(cursor); - } - - @Override - public long getId() { - return getIdHelper(ID); - } - - // --- parcelable helpers - - public static final Creator CREATOR = new ModelCreator(Task.class); - - @Override - protected Creator getCreator() { - return CREATOR; - } - - // --- data access methods - - /** Checks whether task is done. Requires COMPLETION_DATE */ - public boolean isCompleted() { - return getValue(COMPLETION_DATE) > 0; - } - - /** Checks whether task is deleted. Will return false if DELETION_DATE not read */ - public boolean isDeleted() { - // assume false if we didn't load deletion date - if(!containsValue(DELETION_DATE)) - return false; - else - return getValue(DELETION_DATE) > 0; - } - - /** Checks whether task is hidden. Requires HIDDEN_UNTIL */ - public boolean isHidden() { - return getValue(HIDE_UNTIL) > DateUtilities.now(); - } - - /** Checks whether task is done. Requires DUE_DATE */ - public boolean hasDueDate() { - return getValue(DUE_DATE) > 0; - } - - /** - * Returns the set state of the given flag on the given property - * @param property - * @param flag - * @return - */ - public boolean getFlag(IntegerProperty property, int flag) { - return (getValue(property) & flag) > 0; - } - - /** - * Sets the state of the given flag on the given property - * @param property - * @param flag - * @param value - */ - public void setFlag(IntegerProperty property, int flag, boolean value) { - if(value) - setValue(property, getValue(property) | flag); - else - setValue(property, getValue(property) & ~flag); - } - - // --- due and hide until date management - - /** urgency array index -> significance */ - public static final int URGENCY_NONE = 0; - public static final int URGENCY_TODAY = 1; - public static final int URGENCY_TOMORROW = 2; - public static final int URGENCY_DAY_AFTER = 3; - public static final int URGENCY_NEXT_WEEK = 4; - public static final int URGENCY_NEXT_MONTH = 5; - public static final int URGENCY_SPECIFIC_DAY = 6; - public static final int URGENCY_SPECIFIC_DAY_TIME = 7; - - /** hide until array index -> significance */ - public static final int HIDE_UNTIL_NONE = 0; - public static final int HIDE_UNTIL_DUE = 1; - public static final int HIDE_UNTIL_DAY_BEFORE = 2; - public static final int HIDE_UNTIL_WEEK_BEFORE = 3; - public static final int HIDE_UNTIL_SPECIFIC_DAY = 4; - - /** - * Creates due date for this task. If this due date has no time associated, - * we move it to the last millisecond of the day. - * - * @param setting - * one of the URGENCY_* constants - * @param customDate - * if specific day or day & time is set, this value - */ - public long createDueDate(int setting, long customDate) { - long date; - - switch(setting) { - case URGENCY_NONE: - date = 0; - break; - case URGENCY_TODAY: - date = DateUtilities.now(); - break; - case URGENCY_TOMORROW: - date = DateUtilities.now() + DateUtilities.ONE_DAY; - break; - case URGENCY_DAY_AFTER: - date = DateUtilities.now() + 2 * DateUtilities.ONE_DAY; - break; - case URGENCY_NEXT_WEEK: - date = DateUtilities.now() + DateUtilities.ONE_WEEK; - break; - case URGENCY_NEXT_MONTH: - date = DateUtilities.oneMonthFromNow(); - break; - case URGENCY_SPECIFIC_DAY: - case URGENCY_SPECIFIC_DAY_TIME: - date = customDate; - break; - default: - throw new IllegalArgumentException("Unknown setting " + setting); - } - - if(date <= 0) - return date; - - Date dueDate = new Date(date / 1000L * 1000L); // get rid of millis - if(setting != URGENCY_SPECIFIC_DAY_TIME) { - dueDate.setHours(23); - dueDate.setMinutes(59); - dueDate.setSeconds(59); - } else if(isEndOfDay(dueDate)) { - dueDate.setSeconds(58); - } - return dueDate.getTime(); - } - - /** - * Create hide until for this task. - * - * @param setting - * one of the HIDE_UNTIL_* constants - * @param customDate - * if specific day is set, this value - * @return - */ - public long createHideUntil(int setting, long customDate) { - long date; - - switch(setting) { - case HIDE_UNTIL_NONE: - return 0; - case HIDE_UNTIL_DUE: - date = getValue(DUE_DATE); - break; - case HIDE_UNTIL_DAY_BEFORE: - date = getValue(DUE_DATE) - DateUtilities.ONE_DAY; - break; - case HIDE_UNTIL_WEEK_BEFORE: - date = getValue(DUE_DATE) - DateUtilities.ONE_WEEK; - break; - case HIDE_UNTIL_SPECIFIC_DAY: - date = customDate; - break; - default: - throw new IllegalArgumentException("Unknown setting " + setting); - } - - if(date <= 0) - return date; - - Date hideUntil = new Date(date / 1000L * 1000L); // get rid of millis - hideUntil.setHours(0); - hideUntil.setMinutes(0); - hideUntil.setSeconds(0); - return hideUntil.getTime(); - } - - /** - * @return true if hours, minutes, and seconds indicate end of day - */ - private static boolean isEndOfDay(Date date) { - int hours = date.getHours(); - int minutes = date.getMinutes(); - int seconds = date.getSeconds(); - return hours == 23 && minutes == 59 && seconds == 59; - } - - /** - * Checks whether this due date has a due time or only a date - */ - public boolean hasDueTime() { - if(!hasDueDate()) - return false; - return hasDueTime(getValue(Task.DUE_DATE)); - } - - /** - * Checks whether provided due date has a due time or only a date - */ - public static boolean hasDueTime(long dueDate) { - return !isEndOfDay(new Date(dueDate)); - } - -} diff --git a/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java b/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java index 1a0d9301c..0b0907d11 100644 --- a/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java +++ b/astrid/src/com/todoroo/astrid/provider/Astrid2TaskProvider.java @@ -21,8 +21,8 @@ import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.tags.TagService; diff --git a/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java b/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java index 709026ffa..b525e5699 100644 --- a/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java +++ b/astrid/src/com/todoroo/astrid/provider/Astrid3ContentProvider.java @@ -15,7 +15,7 @@ import android.text.TextUtils; import com.todoroo.andlib.data.AbstractDatabase; import com.todoroo.andlib.data.AbstractModel; -import com.todoroo.andlib.data.GenericDao; +import com.todoroo.andlib.data.DatabaseDao; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.service.ExceptionService; @@ -24,9 +24,9 @@ import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.StoreObjectDao; import com.todoroo.astrid.dao.TaskDao; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.AstridDependencyInjector; /** @@ -147,7 +147,7 @@ public class Astrid3ContentProvider extends ContentProvider { public TYPE model; /** dao */ - public GenericDao dao; + public DatabaseDao dao; /** creates from given model */ public boolean create() { diff --git a/astrid/src/com/todoroo/astrid/service/AddOnService.java b/astrid/src/com/todoroo/astrid/service/AddOnService.java index 90515f6c1..83013d9f5 100644 --- a/astrid/src/com/todoroo/astrid/service/AddOnService.java +++ b/astrid/src/com/todoroo/astrid/service/AddOnService.java @@ -20,7 +20,7 @@ import android.widget.Button; import com.timsu.astrid.R; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.utility.DateUtilities; -import com.todoroo.astrid.model.AddOn; +import com.todoroo.astrid.data.AddOn; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Preferences; diff --git a/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java b/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java index 0a764f70c..695755656 100644 --- a/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java +++ b/astrid/src/com/todoroo/astrid/service/Astrid2To3UpgradeHelper.java @@ -19,7 +19,7 @@ import com.google.ical.values.RRule; import com.timsu.astrid.R; import com.timsu.astrid.utilities.LegacyTasksXmlExporter; import com.todoroo.andlib.data.AbstractModel; -import com.todoroo.andlib.data.GenericDao; +import com.todoroo.andlib.data.DatabaseDao; import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.Property.PropertyVisitor; import com.todoroo.andlib.data.TodorooCursor; @@ -34,13 +34,13 @@ import com.todoroo.astrid.backup.TasksXmlImporter; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.TaskDao; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.legacy.AlarmDatabase; import com.todoroo.astrid.legacy.LegacyAlertModel; import com.todoroo.astrid.legacy.LegacyRepeatInfo; import com.todoroo.astrid.legacy.LegacyTaskModel; import com.todoroo.astrid.legacy.TransitionalAlarm; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.utility.Preferences; @@ -324,7 +324,7 @@ public class Astrid2To3UpgradeHelper { @SuppressWarnings("nls") private static final void upgradeTable(Context context, String legacyTable, HashMap> propertyMap, TYPE model, - GenericDao dao) { + DatabaseDao dao) { if(!checkIfDatabaseExists(context, legacyTable)) return; @@ -482,7 +482,7 @@ public class Astrid2To3UpgradeHelper { return; AlarmDatabase alarmsDatabase = new AlarmDatabase(); - GenericDao dao = new GenericDao( + DatabaseDao dao = new DatabaseDao( TransitionalAlarm.class, alarmsDatabase); TodorooCursor cursor = dao.query(Query.select(TransitionalAlarm.PROPERTIES)); diff --git a/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java b/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java index 4d14d2dc0..efecc4d0f 100644 --- a/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java +++ b/astrid/src/com/todoroo/astrid/service/AstridDependencyInjector.java @@ -3,22 +3,16 @@ */ package com.todoroo.astrid.service; -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.util.HashMap; - import com.timsu.astrid.R; import com.todoroo.andlib.service.AbstractDependencyInjector; import com.todoroo.andlib.service.DependencyInjectionService; -import com.todoroo.andlib.service.ExceptionService; import com.todoroo.andlib.service.ExceptionService.AndroidLogReporter; import com.todoroo.andlib.service.ExceptionService.ErrorReporter; -import com.todoroo.andlib.utility.DateUtilities; -import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.StoreObjectDao; import com.todoroo.astrid.dao.TaskDao; +import com.todoroo.astrid.utility.Constants; /** * Astrid application dependency injector loads classes in Astrid with the @@ -29,61 +23,25 @@ import com.todoroo.astrid.dao.TaskDao; * @author Tim Su * */ -public class AstridDependencyInjector implements AbstractDependencyInjector { - - private static final boolean DEBUG = false; +public class AstridDependencyInjector extends AbstractDependencyInjector { /** * Boolean bit to prevent multiple copies of this injector to be loaded */ private static AstridDependencyInjector instance = null; - /** - * Dependencies this class knows how to handle - */ - private static final HashMap injectables = new HashMap(); - - /** - * Cache of classes that were instantiated by the injector - */ - private final HashMap, WeakReference> createdObjects = - new HashMap, WeakReference>(); - /** * Initialize list of injectables. Special care must used when * instantiating classes that themselves depend on dependency injection * (i.e. {@link ErrorReporter}. */ + @Override @SuppressWarnings("nls") - private static void addInjectables() { - injectables.put("debug", DEBUG); + protected void addInjectables() { + injectables.put("debug", Constants.DEBUG); // com.todoroo.android.service injectables.put("applicationName", "astrid"); - injectables.put("exceptionService", ExceptionService.class); - injectables.put("errorDialogTitleResource", R.string.DLG_error); - - // TODO - injectables.put("errorDialogBodyGeneric", R.string.DLG_error); - injectables.put("errorDialogBodyNullError", R.string.DLG_error); - injectables.put("errorDialogBodySocketTimeout", R.string.DLG_error); - - // com.todoroo.android.utility - injectables.put("dialogUtilities", DialogUtilities.class); - injectables.put("informationDialogTitleResource", R.string.DLG_information_title); - injectables.put("confirmDialogTitleResource", R.string.DLG_confirm_title); - injectables.put("dateUtilities", DateUtilities.class); - injectables.put("yearsResource", R.plurals.DUt_years); - injectables.put("monthsResource", R.plurals.DUt_months); - injectables.put("weeksResource", R.plurals.DUt_weeks); - injectables.put("daysResource", R.plurals.DUt_days); - injectables.put("hoursResource", R.plurals.DUt_hours); - injectables.put("minutesResource", R.plurals.DUt_minutes); - injectables.put("secondsResource", R.plurals.DUt_seconds); - injectables.put("daysAbbrevResource", R.plurals.DUt_days); - injectables.put("hoursAbbrevResource", R.plurals.DUt_hoursShort); - injectables.put("minutesAbbrevResource", R.plurals.DUt_minutesShort); - injectables.put("secondsAbbrevResource", R.plurals.DUt_secondsShort); // com.todoroo.android.utility injectables.put("nNumberPickerLayout", R.layout.n_number_picker_dialog); @@ -120,66 +78,30 @@ public class AstridDependencyInjector implements AbstractDependencyInjector { }); } - /** - * {@inheritDoc} - */ - public Object getInjection(Object object, Field field) { - if(injectables.containsKey(field.getName())) { - Object injection = injectables.get(field.getName()); - - // if it's a class, instantiate the class - if(injection instanceof Class) { - if(createdObjects.containsKey(injection) && - createdObjects.get(injection).get() != null) { - injection = createdObjects.get(injection).get(); - } else { - Class cls = (Class)injection; - try { - injection = cls.newInstance(); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } - - createdObjects.put(cls, - new WeakReference(injection)); - } - } - - return injection; - } - - return null; - } - /** * Install this service as the default Dependency Injector */ - public synchronized static void initialize() { + public static void initialize() { if(instance != null) return; - instance = new AstridDependencyInjector(); - DependencyInjectionService.getInstance().setInjectors(new AbstractDependencyInjector[] { - instance - }); - - addInjectables(); + synchronized(AstridDependencyInjector.class) { + if(instance == null) + instance = new AstridDependencyInjector(); + DependencyInjectionService.getInstance().setInjectors(new AbstractDependencyInjector[] { + instance + }); + } } AstridDependencyInjector() { // prevent instantiation - } - - @Override - public String toString() { - return getClass().getSimpleName(); + super(); } /** * Flush dependency injection cache. Useful for unit tests. */ - public static void flush() { - instance.createdObjects.clear(); + public synchronized static void flush() { + instance.flushCreated(); } } diff --git a/astrid/src/com/todoroo/astrid/service/MetadataService.java b/astrid/src/com/todoroo/astrid/service/MetadataService.java index 40fc63b99..721dd40ef 100644 --- a/astrid/src/com/todoroo/astrid/service/MetadataService.java +++ b/astrid/src/com/todoroo/astrid/service/MetadataService.java @@ -12,7 +12,7 @@ import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.sql.Query; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; -import com.todoroo.astrid.model.Metadata; +import com.todoroo.astrid.data.Metadata; /** * Service layer for {@link Metadata}-centered activities. diff --git a/astrid/src/com/todoroo/astrid/service/TaskService.java b/astrid/src/com/todoroo/astrid/service/TaskService.java index ae0f28f8d..7c2c5b531 100644 --- a/astrid/src/com/todoroo/astrid/service/TaskService.java +++ b/astrid/src/com/todoroo/astrid/service/TaskService.java @@ -17,8 +17,8 @@ import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; /** * Service layer for {@link Task}-centered activities. diff --git a/astrid/src/com/todoroo/astrid/service/UpgradeService.java b/astrid/src/com/todoroo/astrid/service/UpgradeService.java index 3f5512bed..45b883047 100644 --- a/astrid/src/com/todoroo/astrid/service/UpgradeService.java +++ b/astrid/src/com/todoroo/astrid/service/UpgradeService.java @@ -26,9 +26,6 @@ public final class UpgradeService { private static final int V3_0_0 = 136; private static final int V2_14_4 = 135; - @Autowired - private DialogUtilities dialogUtilities; - @Autowired private Database database; @@ -51,7 +48,7 @@ public final class UpgradeService { // pop up a progress dialog final ProgressDialog dialog; if(context instanceof Activity) - dialog = dialogUtilities.progressDialog(context, + dialog = DialogUtilities.progressDialog(context, context.getString(R.string.DLG_upgrading)); else dialog = null; diff --git a/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java b/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java index 49bffa78e..208bb3cd1 100644 --- a/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java +++ b/astrid/src/com/todoroo/astrid/ui/TimeDurationControlSet.java @@ -21,6 +21,7 @@ package com.todoroo.astrid.ui; import android.app.Activity; import android.content.res.Resources; +import android.text.format.DateUtils; import android.view.View; import android.widget.Button; @@ -103,8 +104,7 @@ public class TimeDurationControlSet implements OnNNumberPickedListener, prefix = r.getString(prefixResource); timeButton.setText(prefix + " " - + dateUtilities.getDurationString( - timeDurationInSeconds * 1000L, 2)); + + DateUtils.getRelativeTimeSpanString(activity, timeDurationInSeconds * 1000L)); int hours = timeDuration / 3600; int minutes = timeDuration / 60 - 60 * hours; dialog.setInitialValues(new int[] { hours, minutes }); diff --git a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java index 42112c562..c1206e6b5 100644 --- a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java +++ b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java @@ -26,7 +26,7 @@ import com.todoroo.astrid.activity.TaskListActivity; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.core.CoreFilterExposer; import com.todoroo.astrid.dao.Database; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.utility.Preferences; diff --git a/tests/src/com/todoroo/andlib/service/TestDependencyInjector.java b/tests/src/com/todoroo/andlib/service/TestDependencyInjector.java index 94e7edc3e..9c0d0b54f 100644 --- a/tests/src/com/todoroo/andlib/service/TestDependencyInjector.java +++ b/tests/src/com/todoroo/andlib/service/TestDependencyInjector.java @@ -1,17 +1,10 @@ package com.todoroo.andlib.service; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.Iterator; -public class TestDependencyInjector implements AbstractDependencyInjector { - - /** - * Dependencies this class knows how to handle - */ - private final HashMap injectables = new HashMap(); +public class TestDependencyInjector extends AbstractDependencyInjector { private String name; @@ -23,12 +16,9 @@ public class TestDependencyInjector implements AbstractDependencyInjector { injectables.put(field, injection); } - public Object getInjection(Object object, Field field) { - if(injectables.containsKey(field.getName())) { - return injectables.get(field.getName()); - } - - return null; + @Override + protected void addInjectables() { + // do nothing, we populate injectables via the addInjectable method } @Override diff --git a/tests/src/com/todoroo/astrid/dao/MetadataDaoTests.java b/tests/src/com/todoroo/astrid/dao/MetadataDaoTests.java index da93bcf7c..ecccdbd3b 100644 --- a/tests/src/com/todoroo/astrid/dao/MetadataDaoTests.java +++ b/tests/src/com/todoroo/astrid/dao/MetadataDaoTests.java @@ -5,8 +5,8 @@ import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.sql.Query; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.test.DatabaseTestCase; public class MetadataDaoTests extends DatabaseTestCase { diff --git a/tests/src/com/todoroo/astrid/dao/TaskDaoTests.java b/tests/src/com/todoroo/astrid/dao/TaskDaoTests.java index 6478fb845..0236de3db 100644 --- a/tests/src/com/todoroo/astrid/dao/TaskDaoTests.java +++ b/tests/src/com/todoroo/astrid/dao/TaskDaoTests.java @@ -7,7 +7,7 @@ import com.todoroo.andlib.sql.Order; import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.test.DatabaseTestCase; public class TaskDaoTests extends DatabaseTestCase { diff --git a/tests/src/com/todoroo/astrid/model/TaskTests.java b/tests/src/com/todoroo/astrid/model/TaskTests.java index ee2498e99..b4ee677dc 100644 --- a/tests/src/com/todoroo/astrid/model/TaskTests.java +++ b/tests/src/com/todoroo/astrid/model/TaskTests.java @@ -7,6 +7,7 @@ import android.content.ContentValues; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.utility.DateUtilities; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.test.DatabaseTestCase; import com.todoroo.astrid.utility.Preferences; diff --git a/tests/src/com/todoroo/astrid/provider/Astrid3ProviderTests.java b/tests/src/com/todoroo/astrid/provider/Astrid3ProviderTests.java index b4e489bdd..611abdcd9 100644 --- a/tests/src/com/todoroo/astrid/provider/Astrid3ProviderTests.java +++ b/tests/src/com/todoroo/astrid/provider/Astrid3ProviderTests.java @@ -8,9 +8,9 @@ import android.net.Uri; import com.todoroo.andlib.data.Property.IntegerProperty; import com.todoroo.andlib.data.Property.StringProperty; import com.todoroo.astrid.api.AstridApiConstants; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.StoreObject; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.StoreObject; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.test.DatabaseTestCase; public class Astrid3ProviderTests extends DatabaseTestCase { diff --git a/tests/src/com/todoroo/astrid/reminders/NotificationTests.java b/tests/src/com/todoroo/astrid/reminders/NotificationTests.java index 4ba0b8c8a..7dec8c27d 100644 --- a/tests/src/com/todoroo/astrid/reminders/NotificationTests.java +++ b/tests/src/com/todoroo/astrid/reminders/NotificationTests.java @@ -10,7 +10,7 @@ import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.NotificationManager; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.test.DatabaseTestCase; import com.todoroo.astrid.utility.Preferences; diff --git a/tests/src/com/todoroo/astrid/reminders/ReminderServiceTests.java b/tests/src/com/todoroo/astrid/reminders/ReminderServiceTests.java index 9ddb7d6ae..74b69fa0c 100644 --- a/tests/src/com/todoroo/astrid/reminders/ReminderServiceTests.java +++ b/tests/src/com/todoroo/astrid/reminders/ReminderServiceTests.java @@ -3,7 +3,7 @@ package com.todoroo.astrid.reminders; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.TaskDao; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.reminders.ReminderService.AlarmScheduler; import com.todoroo.astrid.test.DatabaseTestCase; import com.todoroo.astrid.utility.Preferences; diff --git a/tests/src/com/todoroo/astrid/repeats/AdvancedRepeatTests.java b/tests/src/com/todoroo/astrid/repeats/AdvancedRepeatTests.java index ede9fafa0..8a5343b73 100644 --- a/tests/src/com/todoroo/astrid/repeats/AdvancedRepeatTests.java +++ b/tests/src/com/todoroo/astrid/repeats/AdvancedRepeatTests.java @@ -11,7 +11,7 @@ import com.google.ical.values.Weekday; import com.google.ical.values.WeekdayNum; import com.todoroo.andlib.test.TodorooTestCase; import com.todoroo.andlib.utility.DateUtilities; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Task; public class AdvancedRepeatTests extends TodorooTestCase { diff --git a/tests/src/com/todoroo/astrid/repeats/RepeatTests.java b/tests/src/com/todoroo/astrid/repeats/RepeatTests.java index 7b485e0f3..629994d12 100644 --- a/tests/src/com/todoroo/astrid/repeats/RepeatTests.java +++ b/tests/src/com/todoroo/astrid/repeats/RepeatTests.java @@ -11,8 +11,8 @@ import com.todoroo.andlib.sql.Query; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.TaskDao; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.test.DatabaseTestCase; import com.todoroo.astrid.utility.Preferences; diff --git a/tests/src/com/todoroo/astrid/upgrade/Astrid2To3UpgradeTests.java b/tests/src/com/todoroo/astrid/upgrade/Astrid2To3UpgradeTests.java index 7a39853ec..6d6573309 100644 --- a/tests/src/com/todoroo/astrid/upgrade/Astrid2To3UpgradeTests.java +++ b/tests/src/com/todoroo/astrid/upgrade/Astrid2To3UpgradeTests.java @@ -14,6 +14,8 @@ import com.todoroo.astrid.dao.MetadataDao; import com.todoroo.astrid.dao.MetadataDao.MetadataCriteria; import com.todoroo.astrid.dao.TaskDao; import com.todoroo.astrid.dao.TaskDao.TaskCriteria; +import com.todoroo.astrid.data.Metadata; +import com.todoroo.astrid.data.Task; import com.todoroo.astrid.legacy.AlarmDatabase; import com.todoroo.astrid.legacy.TransitionalAlarm; import com.todoroo.astrid.legacy.data.alerts.AlertController; @@ -28,8 +30,6 @@ import com.todoroo.astrid.legacy.data.task.TaskController; import com.todoroo.astrid.legacy.data.task.TaskIdentifier; import com.todoroo.astrid.legacy.data.task.TaskModelForEdit; import com.todoroo.astrid.legacy.data.task.TaskModelForSync; -import com.todoroo.astrid.model.Metadata; -import com.todoroo.astrid.model.Task; import com.todoroo.astrid.service.Astrid2To3UpgradeHelper; import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.tags.TagService.Tag;