code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
package org.dodgybits.shuffle.android.persistence.migrations;
import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class V1Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
createProjectTable(db);
createTaskTable(db);
}
private void createProjectTable(SQLiteDatabase db) {
Log.w(AbstractCollectionProvider.cTag, "Destroying all old data");
db.execSQL("DROP TABLE IF EXISTS " + ProjectProvider.PROJECT_TABLE_NAME);
db.execSQL("CREATE TABLE "
+ ProjectProvider.PROJECT_TABLE_NAME
+ " ("
+ "_id INTEGER PRIMARY KEY,"
+ "name TEXT,"
+ "archived INTEGER,"
+ "defaultContextId INTEGER"
+ ");");
}
private void createTaskTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TaskProvider.TASK_TABLE_NAME);
db.execSQL("CREATE TABLE "
+ TaskProvider.TASK_TABLE_NAME
+ " ("
+ "_id INTEGER PRIMARY KEY,"
+ "description TEXT,"
+ "details TEXT,"
+ "contextId INTEGER,"
+ "projectId INTEGER,"
+ "created INTEGER,"
+ "modified INTEGER,"
+ "due INTEGER,"
+ "displayOrder INTEGER,"
+ "complete INTEGER"
+ ");");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V1Migration.java | Java | asf20 | 1,495 |
package org.dodgybits.shuffle.android.persistence.migrations;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import android.database.sqlite.SQLiteDatabase;
public class V10Migration implements Migration {
@Override
public void migrate(SQLiteDatabase db) {
// Shuffle v1.1 (1st release)
createTaskProjectIdIndex(db);
createTaskContextIdIndex(db);
// no break since we want it to fall through
}
private void createTaskProjectIdIndex(SQLiteDatabase db) {
db.execSQL("DROP INDEX IF EXISTS taskProjectIdIndex");
db.execSQL("CREATE INDEX taskProjectIdIndex ON " + TaskProvider.TASK_TABLE_NAME
+ " (" + TaskProvider.Tasks.PROJECT_ID + ");");
}
private void createTaskContextIdIndex(SQLiteDatabase db) {
db.execSQL("DROP INDEX IF EXISTS taskContextIdIndex");
db.execSQL("CREATE INDEX taskContextIdIndex ON " + TaskProvider.TASK_TABLE_NAME
+ " (" + TaskProvider.Tasks.CONTEXT_ID + ");");
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/migrations/V10Migration.java | Java | asf20 | 983 |
package org.dodgybits.shuffle.android.persistence.provider;
import android.net.Uri;
public class ReminderProvider extends AbstractCollectionProvider {
private static final String AUTHORITY = Shuffle.PACKAGE+".reminderprovider";
public static final String cUpdateIntent = "org.dodgybits.shuffle.android.REMINDER_UPDATE";
/**
* Reminders table
*/
public static final class Reminders implements ShuffleTable {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://"
+ AUTHORITY + "/reminders");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "minutes DESC";
/**
* The task the reminder belongs to
* <P>
* Type: INTEGER (foreign key to the task table)
* </P>
*/
public static final String TASK_ID = "taskId";
/**
* The minutes prior to the event that the alarm should ring. -1
* specifies that we should use the default value for the system.
* <P>
* Type: INTEGER
* </P>
*/
public static final String MINUTES = "minutes";
public static final int MINUTES_DEFAULT = -1;
/**
* The alarm method.
*/
public static final String METHOD = "method";
public static final int METHOD_DEFAULT = 0;
public static final int METHOD_ALERT = 1;
/**
* Projection for all the columns of a context.
*/
public static final String[] cFullProjection = new String[] { _ID,
MINUTES, METHOD, };
public static final int MINUTES_INDEX = 1;
public static final int METHOD_INDEX = 2;
}
public static final String cReminderTableName = "Reminder";
public ReminderProvider() {
super(
AUTHORITY,
"reminders",
cReminderTableName,
cUpdateIntent,
Reminders.METHOD,
Reminders._ID,
Reminders.CONTENT_URI,
Reminders._ID,Reminders.TASK_ID,Reminders.MINUTES, Reminders.METHOD );
setDefaultSortOrder(Reminders.DEFAULT_SORT_ORDER);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/ReminderProvider.java | Java | asf20 | 2,087 |
package org.dodgybits.shuffle.android.persistence.provider;
import android.net.Uri;
import android.provider.BaseColumns;
public class ContextProvider extends AbstractCollectionProvider {
public static final String CONTEXT_TABLE_NAME = "context";
public static final String UPDATE_INTENT = "org.dodgybits.shuffle.android.CONTEXT_UPDATE";
private static final String AUTHORITY = Shuffle.PACKAGE + ".contextprovider";
static final int CONTEXT_TASKS = 103;
private static final String URL_COLLECTION_NAME = "contexts";
public ContextProvider() {
super(
AUTHORITY, // authority
URL_COLLECTION_NAME, // collectionNamePlural
CONTEXT_TABLE_NAME, // tableName
UPDATE_INTENT, // update intent action
Contexts.NAME, // primary key
BaseColumns._ID, // id field
Contexts.CONTENT_URI,// content URI
BaseColumns._ID, // fields...
Contexts.NAME,
Contexts.COLOUR,
Contexts.ICON,
ShuffleTable.TRACKS_ID,
ShuffleTable.MODIFIED_DATE,
ShuffleTable.DELETED,
ShuffleTable.ACTIVE
);
uriMatcher.addURI(AUTHORITY, "contextTasks", CONTEXT_TASKS);
restrictionBuilders.put(CONTEXT_TASKS,
new CustomElementFilterRestrictionBuilder(
"context, task", "task.contextId = context._id", "context._id"));
groupByBuilders.put(CONTEXT_TASKS,
new StandardGroupByBuilder("context._id"));
elementInserters.put(COLLECTION_MATCH_ID, new ContextInserter());
setDefaultSortOrder(Contexts.DEFAULT_SORT_ORDER);
}
/**
* Contexts table
*/
public static final class Contexts implements ShuffleTable {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/contexts");
public static final Uri CONTEXT_TASKS_CONTENT_URI = Uri
.parse("content://" + AUTHORITY + "/contextTasks");
public static final Uri ACTIVE_CONTEXTS = Uri
.parse("content://" + AUTHORITY + "/activeContexts");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "name DESC";
public static final String NAME = "name";
public static final String COLOUR = "colour";
public static final String ICON = "iconName";
/**
* Projection for all the columns of a context.
*/
public static final String[] FULL_PROJECTION = new String[] {
_ID,
NAME,
COLOUR,
ICON,
TRACKS_ID,
MODIFIED_DATE,
DELETED,
ACTIVE
};
public static final String TASK_COUNT = "count";
/**
* Projection for fetching the task count for each context.
*/
public static final String[] FULL_TASK_PROJECTION = new String[] { _ID,
TASK_COUNT, };
}
private class ContextInserter extends ElementInserterImpl {
public ContextInserter() {
super(Contexts.NAME);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/ContextProvider.java | Java | asf20 | 3,084 |
package org.dodgybits.shuffle.android.persistence.provider;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
public class TaskProvider extends AbstractCollectionProvider {
public static final String TASK_TABLE_NAME = "task";
public static final String UPDATE_INTENT = "org.dodgybits.shuffle.android.TASK_UPDATE";
private static final String URL_COLLECTION_NAME = "tasks";
public TaskProvider() {
super(
AUTHORITY, // authority
URL_COLLECTION_NAME, // collectionNamePlural
TASK_TABLE_NAME, // tableName
UPDATE_INTENT, // update intent action
Tasks.DESCRIPTION, // primary key
BaseColumns._ID, // id field
Tasks.CONTENT_URI, // content URI
BaseColumns._ID, // fields...
Tasks.DESCRIPTION,
Tasks.DETAILS,
Tasks.CONTEXT_ID,
Tasks.PROJECT_ID,
Tasks.CREATED_DATE,
Tasks.START_DATE,
Tasks.DUE_DATE,
Tasks.TIMEZONE,
Tasks.CAL_EVENT_ID,
Tasks.DISPLAY_ORDER,
Tasks.COMPLETE,
Tasks.ALL_DAY,
Tasks.HAS_ALARM,
ShuffleTable.TRACKS_ID,
ShuffleTable.MODIFIED_DATE,
ShuffleTable.DELETED,
ShuffleTable.ACTIVE
);
makeSearchable(Tasks._ID,
Tasks.DESCRIPTION, Tasks.DETAILS,
Tasks.DESCRIPTION, Tasks.DETAILS);
elementInserters.put(COLLECTION_MATCH_ID, new TaskInserter());
setDefaultSortOrder(Tasks.DEFAULT_SORT_ORDER);
}
public static final String AUTHORITY = Shuffle.PACKAGE + ".taskprovider";
/**
* Tasks table
*/
public static final class Tasks implements ShuffleTable {
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY+"/tasks");
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "due ASC, created ASC";
public static final String DESCRIPTION = "description";
public static final String DETAILS = "details";
public static final String CONTEXT_ID = "contextId";
public static final String PROJECT_ID = "projectId";
public static final String CREATED_DATE = "created";
public static final String START_DATE = "start";
public static final String DUE_DATE = "due";
public static final String TIMEZONE = "timezone";
public static final String CAL_EVENT_ID = "calEventId";
public static final String DISPLAY_ORDER = "displayOrder";
public static final String COMPLETE = "complete";
public static final String ALL_DAY = "allDay";
public static final String HAS_ALARM = "hasAlarm";
/**
* Projection for all the columns of a task.
*/
public static final String[] FULL_PROJECTION = new String[] { _ID,
DESCRIPTION, DETAILS, PROJECT_ID, CONTEXT_ID, CREATED_DATE,
MODIFIED_DATE, START_DATE, DUE_DATE, TIMEZONE, CAL_EVENT_ID,
DISPLAY_ORDER, COMPLETE, ALL_DAY, HAS_ALARM, TRACKS_ID, DELETED, ACTIVE };
}
private class TaskInserter extends ElementInserterImpl {
public TaskInserter() {
super(Tasks.DESCRIPTION);
}
@Override
protected void addDefaultValues(ContentValues values) {
super.addDefaultValues(values);
// Make sure that the fields are all set
Long now = System.currentTimeMillis();
if (!values.containsKey(Tasks.CREATED_DATE)) {
values.put(Tasks.CREATED_DATE, now);
}
if (!values.containsKey(Tasks.DETAILS)) {
values.put(Tasks.DETAILS, "");
}
if (!values.containsKey(Tasks.DISPLAY_ORDER)) {
values.put(Tasks.DISPLAY_ORDER, 0);
}
if (!values.containsKey(Tasks.COMPLETE)) {
values.put(Tasks.COMPLETE, 0);
}
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/TaskProvider.java | Java | asf20 | 4,062 |
/**
*
*/
package org.dodgybits.shuffle.android.persistence.provider;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.dodgybits.shuffle.android.persistence.migrations.*;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class DatabaseHelper extends SQLiteOpenHelper {
private static final SortedMap<Integer, Migration> ALL_MIGRATIONS = new TreeMap<Integer, Migration>();
static {
ALL_MIGRATIONS.put(1, new V1Migration());
ALL_MIGRATIONS.put(9, new V9Migration());
ALL_MIGRATIONS.put(10, new V10Migration());
ALL_MIGRATIONS.put(11, new V11Migration());
ALL_MIGRATIONS.put(12, new V12Migration());
ALL_MIGRATIONS.put(13, new V13Migration());
ALL_MIGRATIONS.put(14, new V14Migration());
ALL_MIGRATIONS.put(15, new V15Migration());
ALL_MIGRATIONS.put(16, new V16Migration());
}
DatabaseHelper(Context context) {
super(context, AbstractCollectionProvider.cDatabaseName, null, AbstractCollectionProvider.cDatabaseVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(AbstractCollectionProvider.cTag, "Creating shuffle DB");
executeMigrations(db, ALL_MIGRATIONS.keySet());
}
private void executeMigrations(SQLiteDatabase db,
Set<Integer> migrationVersions) {
for (Integer version : migrationVersions) {
Log.i(AbstractCollectionProvider.cTag, "Migrating to version " + version);
ALL_MIGRATIONS.get(version).migrate(db);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(AbstractCollectionProvider.cTag,
"Upgrading database from version " + oldVersion + " to " + newVersion);
SortedMap<Integer, Migration> migrations = ALL_MIGRATIONS.subMap(oldVersion, newVersion);
executeMigrations(db, migrations.keySet());
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/DatabaseHelper.java | Java | asf20 | 1,945 |
package org.dodgybits.shuffle.android.persistence.provider;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
public abstract class AbstractCollectionProvider extends ContentProvider {
public static final String cDatabaseName = "shuffle.db";
static final int cDatabaseVersion = 17;
public static final String cTag = "ShuffleProvider";
public static interface ShuffleTable extends BaseColumns {
static final String CONTENT_TYPE_PATH = "vnd.dodgybits";
static final String CONTENT_TYPE_PRE_PREFIX = "vnd.android.cursor.dir/";
static final String CONTENT_ITEM_TYPE_PRE_PREFIX = "vnd.android.cursor.item/";
static final String CONTENT_TYPE_PREFIX = CONTENT_TYPE_PRE_PREFIX+CONTENT_TYPE_PATH;
static final String CONTENT_ITEM_TYPE_PREFIX = CONTENT_ITEM_TYPE_PRE_PREFIX+CONTENT_TYPE_PATH;
public static final String MODIFIED_DATE = "modified";
public static final String TRACKS_ID = "tracks_id";
public static final String DELETED = "deleted";
public static final String ACTIVE = "active";
}
protected static final int SEARCH = 3;
protected static final int COLLECTION_MATCH_ID = 1;
protected static final int ELEMENT_MATCH_ID = 2;
protected static Map<String, String> createSuggestionsMap(String idField,
String column1Field, String column2Field) {
HashMap<String, String> sSuggestionProjectionMap = new HashMap<String, String>();
sSuggestionProjectionMap.put(SearchManager.SUGGEST_COLUMN_TEXT_1,
column1Field + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_1);
sSuggestionProjectionMap.put(SearchManager.SUGGEST_COLUMN_TEXT_2,
column2Field + " AS " + SearchManager.SUGGEST_COLUMN_TEXT_2);
sSuggestionProjectionMap.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID,
idField + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
sSuggestionProjectionMap.put(idField, idField);
return sSuggestionProjectionMap;
}
protected static Map<String, String> createTableMap(String tableName,
String... fieldNames) {
HashMap<String, String> fieldNameMap = new HashMap<String, String>();
for (String fieldName : fieldNames) {
fieldNameMap.put(fieldName, tableName + "."+fieldName);
}
return fieldNameMap;
}
private final String authority;
protected DatabaseHelper mOpenHelper;
protected Map<String, String> suggestionProjectionMap;
protected final Map<Integer, RestrictionBuilder> restrictionBuilders;
protected final Map<Integer, GroupByBuilder> groupByBuilders;
protected final Map<Integer, CollectionUpdater> collectionUpdaters;
protected final Map<Integer, ElementInserter> elementInserters;
protected final Map<Integer, ElementDeleter> elementDeleters;
private final String tableName;
private final String updateIntentAction;
private final Map<String, String> elementsMap;
protected final Map<Integer,String> mimeTypes;
protected final Uri contentUri;
private String defaultSortOrder = null;
protected void setDefaultSortOrder(String defaultSortOrder) {
this.defaultSortOrder = defaultSortOrder;
}
protected String getTableName() {
return tableName;
}
protected Map<String,String> getElementsMap() {
return elementsMap;
}
private void notifyOnChange(Uri uri) {
getContext().getContentResolver().notifyChange(uri, null);
getContext().sendBroadcast(new Intent(updateIntentAction));
}
public static interface RestrictionBuilder {
void addRestrictions(Uri uri, SQLiteQueryBuilder qb);
}
private class EntireCollectionRestrictionBuilder implements RestrictionBuilder {
@Override
public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) {
qb.setTables(getTableName());
qb.setProjectionMap(getElementsMap());
}
}
private class ElementByIdRestrictionBuilder implements RestrictionBuilder {
@Override
public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) {
qb.setTables(getTableName());
qb.appendWhere("_id=" + uri.getPathSegments().get(1));
}
}
private class SearchRestrictionBuilder implements RestrictionBuilder {
private final String[] searchFields;
public SearchRestrictionBuilder(String[] searchFields) {
super();
this.searchFields = searchFields;
}
@Override
public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) {
qb.setTables(getTableName());
String query = uri.getLastPathSegment();
if (!TextUtils.isEmpty(query)) {
for (int i = 0; i < searchFields.length; i++) {
String field = searchFields[i];
qb.appendWhere(field + " LIKE ");
qb.appendWhereEscapeString('%' + query + '%');
if (i < searchFields.length - 1)
qb.appendWhere(" OR ");
}
}
qb.setProjectionMap(suggestionProjectionMap);
}
}
protected class CustomElementFilterRestrictionBuilder implements RestrictionBuilder {
private final String tables;
private final String restrictions;
private final String idField;
public CustomElementFilterRestrictionBuilder(String tables,
String restrictions, String idField) {
super();
this.tables = tables;
this.restrictions = restrictions;
this.idField = idField;
}
@Override
public void addRestrictions(Uri uri, SQLiteQueryBuilder qb) {
Map<String, String> projectionMap = new HashMap<String, String>();
projectionMap.put("_id", idField);
projectionMap.put("count", "count(*)");
qb.setProjectionMap(projectionMap);
qb.setTables(tables);
qb.appendWhere(restrictions);
}
}
public static interface GroupByBuilder {
String getGroupBy(Uri uri);
}
protected class StandardGroupByBuilder implements GroupByBuilder
{
private String mGroupBy;
public StandardGroupByBuilder(String groupBy) {
mGroupBy = groupBy;
}
@Override
public String getGroupBy(Uri uri) {
return mGroupBy;
}
}
protected final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
public AbstractCollectionProvider(String authority, String collectionNamePlural,
String tableName,
String updateIntentAction,
String primaryKey, String idField,Uri contentUri,
String... fields) {
this.authority = authority;
this.contentUri = contentUri;
registerCollectionUrls(collectionNamePlural);
this.restrictionBuilders = new HashMap<Integer, RestrictionBuilder>();
this.restrictionBuilders.put(COLLECTION_MATCH_ID, new EntireCollectionRestrictionBuilder());
this.restrictionBuilders.put(ELEMENT_MATCH_ID, new ElementByIdRestrictionBuilder());
this.tableName = tableName;
this.updateIntentAction = updateIntentAction;
this.elementsMap = createTableMap(tableName, fields);
this.mimeTypes = new HashMap<Integer, String>();
this.mimeTypes.put(COLLECTION_MATCH_ID, getContentType());
this.mimeTypes.put(ELEMENT_MATCH_ID, getContentItemType());
this.collectionUpdaters = new HashMap<Integer, CollectionUpdater>();
this.collectionUpdaters.put(COLLECTION_MATCH_ID, new EntireCollectionUpdater());
this.collectionUpdaters.put(ELEMENT_MATCH_ID, new SingleElementUpdater());
this.elementInserters = new HashMap<Integer, ElementInserter>();
this.elementInserters.put(COLLECTION_MATCH_ID, new ElementInserterImpl(primaryKey));
this.elementDeleters = new HashMap<Integer, ElementDeleter>();
this.elementDeleters.put(COLLECTION_MATCH_ID, new EntireCollectionDeleter());
this.elementDeleters.put(ELEMENT_MATCH_ID, new ElementDeleterImpl(idField));
this.groupByBuilders = new HashMap<Integer, GroupByBuilder>();
}
@Override
public String getType(Uri uri) {
String mimeType = mimeTypes.get(match(uri));
if (mimeType == null) throw new IllegalArgumentException("Unknown Uri " + uri);
return mimeType;
}
SQLiteQueryBuilder createQueryBuilder() {
return new SQLiteQueryBuilder();
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = getWriteableDatabase();
int count = doDelete(uri, where, whereArgs, db);
notifyOnChange(uri);
return count;
}
SQLiteDatabase getReadableDatabase() {
return mOpenHelper.getReadableDatabase();
}
protected String getSortOrder(Uri uri, String sort) {
if (defaultSortOrder != null && TextUtils.isEmpty(sort)) {
return defaultSortOrder;
}
return sort;
}
protected SQLiteDatabase getWriteableDatabase() {
return mOpenHelper.getWritableDatabase();
}
@Override
public Uri insert(Uri url, ContentValues initialValues) {
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
SQLiteDatabase db = getWriteableDatabase();
return doInsert(url, values, db);
}
protected void makeSearchable(String idField, String descriptionField,
String detailsField, String...searchFields) {
uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH);
uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH);
suggestionProjectionMap = createSuggestionsMap(idField,descriptionField,detailsField);
restrictionBuilders.put(SEARCH, new SearchRestrictionBuilder(searchFields));
}
public int match(Uri uri) {
return uriMatcher.match(uri);
}
@Override
public boolean onCreate() {
Log.i(cTag, "+onCreate");
mOpenHelper = new DatabaseHelper(getContext());
return true;
}
protected int doUpdate(Uri uri, ContentValues values, String where,
String[] whereArgs, SQLiteDatabase db) {
CollectionUpdater updater = collectionUpdaters.get(match(uri));
if (updater == null) throw new IllegalArgumentException("Unknown URL " + uri);
return updater.update(uri, values, where, whereArgs, db);
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = createQueryBuilder();
SQLiteDatabase db = getReadableDatabase();
addRestrictions(uri, qb);
String orderBy = getSortOrder(uri, sort);
String groupBy = getGroupBy(uri);
if (Log.isLoggable(cTag, Log.DEBUG)) {
Log.d(cTag, "Executing " + selection + " with args "
+ Arrays.toString(selectionArgs) + " ORDER BY " + orderBy);
}
Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy,
null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
protected String getGroupBy(Uri uri) {
String groupBy = null;
GroupByBuilder builder = groupByBuilders.get(match(uri));
if (builder != null) {
groupBy = builder.getGroupBy(uri);
}
return groupBy;
}
protected void registerCollectionUrls(String collectionName) {
uriMatcher.addURI(authority, collectionName, COLLECTION_MATCH_ID);
uriMatcher.addURI(authority, collectionName+"/#", ELEMENT_MATCH_ID);
}
protected String getContentType() {
return ShuffleTable.CONTENT_TYPE_PREFIX+"."+getTableName();
}
public String getContentItemType() {
return ShuffleTable.CONTENT_ITEM_TYPE_PREFIX+"."+getTableName();
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
int count = 0;
SQLiteDatabase db = getWriteableDatabase();
count = doUpdate(uri, values, where, whereArgs, db);
notifyOnChange(uri);
return count;
}
protected void addRestrictions(Uri uri, SQLiteQueryBuilder qb) {
RestrictionBuilder restrictionBuilder = restrictionBuilders.get(match(uri));
if (restrictionBuilder == null) throw new IllegalArgumentException("Unknown URL " + uri);
restrictionBuilder.addRestrictions(uri, qb);
}
public interface CollectionUpdater {
int update(Uri uri, ContentValues values, String where,
String[] whereArgs, SQLiteDatabase db);
}
private class EntireCollectionUpdater implements CollectionUpdater {
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs, SQLiteDatabase db) {
return db.update(getTableName(), values, where, whereArgs);
}
}
private class SingleElementUpdater implements CollectionUpdater {
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs, SQLiteDatabase db) {
String segment = uri.getPathSegments().get(1);
return db.update(getTableName(), values,
"_id="
+ segment
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ')' : ""), whereArgs);
}
}
public interface ElementInserter {
Uri insert(Uri url, ContentValues values, SQLiteDatabase db);
}
protected class ElementInserterImpl implements ElementInserter {
private final String primaryKey;
public ElementInserterImpl(String primaryKey) {
super();
this.primaryKey = primaryKey;
}
@Override
public Uri insert(Uri url, ContentValues values, SQLiteDatabase db) {
addDefaultValues(values);
long rowID = db.insert(getTableName(), getElementsMap()
.get(primaryKey), values);
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(contentUri,
rowID);
notifyOnChange(uri);
return uri;
}
throw new SQLException("Failed to insert row into " + url);
}
protected void addDefaultValues(ContentValues values) {
Long now = System.currentTimeMillis();
if (!values.containsKey(ShuffleTable.MODIFIED_DATE)) {
values.put(ShuffleTable.MODIFIED_DATE, now);
}
if (!values.containsKey(ShuffleTable.DELETED)) {
values.put(ShuffleTable.DELETED, 0);
}
if (!values.containsKey(ShuffleTable.ACTIVE)) {
values.put(ShuffleTable.ACTIVE, 1);
}
if (!values.containsKey(primaryKey)) {
values.put(primaryKey, "");
}
}
}
protected Uri doInsert(Uri url, ContentValues values, SQLiteDatabase db) {
ElementInserter elementInserter = elementInserters.get(match(url));
if (elementInserter == null) throw new IllegalArgumentException("Unknown URL " + url);
return elementInserter.insert(url, values, db);
}
public static interface ElementDeleter {
int delete(Uri uri, String where, String[] whereArgs,
SQLiteDatabase db);
}
private class ElementDeleterImpl implements ElementDeleter {
private final String idField;
public ElementDeleterImpl(String idField) {
super();
this.idField = idField;
}
@Override
public int delete(Uri uri, String where, String[] whereArgs,
SQLiteDatabase db) {
String id = uri.getPathSegments().get(1);
int rowsUpdated = db.delete(getTableName(),
idField + "=" + id +
(!TextUtils.isEmpty(where) ? " AND (" + where +
')' : ""), whereArgs);
notifyOnChange(uri);
return rowsUpdated;
}
}
private class EntireCollectionDeleter implements ElementDeleter {
@Override
public int delete(Uri uri, String where, String[] whereArgs,
SQLiteDatabase db) {
int rowsUpdated = db.delete(getTableName(), where, whereArgs);
notifyOnChange(uri);
return rowsUpdated;
}
}
protected int doDelete(Uri uri, String where, String[] whereArgs,
SQLiteDatabase db) {
ElementDeleter elementDeleter = elementDeleters.get(match(uri));
if (elementDeleter == null) throw new IllegalArgumentException("Unknown uri " + uri);
return elementDeleter.delete(uri, where, whereArgs, db);
}
} | 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/AbstractCollectionProvider.java | Java | asf20 | 16,337 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* 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.
*/
package org.dodgybits.shuffle.android.persistence.provider;
public class Shuffle {
public static final String PACKAGE = "org.dodgybits.android.shuffle.provider";
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/Shuffle.java | Java | asf20 | 804 |
package org.dodgybits.shuffle.android.persistence.provider;
import android.net.Uri;
import android.provider.BaseColumns;
public class ProjectProvider extends AbstractCollectionProvider {
public static final String PROJECT_TABLE_NAME = "project";
public static final String UPDATE_INTENT = "org.dodgybits.shuffle.android.PROJECT_UPDATE";
private static final String AUTHORITY = Shuffle.PACKAGE+".projectprovider";
static final int PROJECT_TASKS = 203;
private static final String URL_COLLECTION_NAME = "projects";
public ProjectProvider() {
super(
AUTHORITY, // authority
URL_COLLECTION_NAME, // collectionNamePlural
PROJECT_TABLE_NAME, // tableName
UPDATE_INTENT, // update intent action
Projects.NAME, // primary key
BaseColumns._ID, // id field
Projects.CONTENT_URI,// content URI
BaseColumns._ID, // fields...
Projects.NAME,
Projects.DEFAULT_CONTEXT_ID,
Projects.PARALLEL,
Projects.ARCHIVED,
ShuffleTable.TRACKS_ID,
ShuffleTable.MODIFIED_DATE,
ShuffleTable.DELETED,
ShuffleTable.ACTIVE
);
makeSearchable(Projects._ID, Projects.NAME, Projects.NAME, Projects.NAME);
uriMatcher.addURI(AUTHORITY, "projectTasks", PROJECT_TASKS);
String idField = "project._id";
String tables = "project, task";
String restrictions = "task.projectId = project._id";
restrictionBuilders.put(PROJECT_TASKS,
new CustomElementFilterRestrictionBuilder(
tables, restrictions, idField));
groupByBuilders.put(PROJECT_TASKS,
new StandardGroupByBuilder("project._id"));
elementInserters.put(COLLECTION_MATCH_ID, new ProjectInserter());
setDefaultSortOrder(Projects.DEFAULT_SORT_ORDER);
}
/**
* Projects table
*/
public static final class Projects implements ShuffleTable {
public static final String ARCHIVED = "archived";
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + URL_COLLECTION_NAME);
public static final Uri PROJECT_TASKS_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/projectTasks");
public static final String DEFAULT_CONTEXT_ID = "defaultContextId";
/**
* The default sort order for this table
*/
public static final String DEFAULT_SORT_ORDER = "name DESC";
public static final String NAME = "name";
public static final String PARALLEL = "parallel";
public static final String TASK_COUNT = "count";
/**
* Projection for all the columns of a project.
*/
public static final String[] FULL_PROJECTION = new String[] {
_ID,
NAME,
DEFAULT_CONTEXT_ID,
TRACKS_ID,
MODIFIED_DATE,
PARALLEL,
ARCHIVED,
DELETED,
ACTIVE
};
/**
* Projection for fetching the task count for each project.
*/
public static final String[] FULL_TASK_PROJECTION = new String[] {
_ID,
TASK_COUNT,
};
}
private class ProjectInserter extends ElementInserterImpl {
public ProjectInserter() {
super(Projects.NAME);
}
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/provider/ProjectProvider.java | Java | asf20 | 3,739 |
/*
* Copyright (C) 2009 Android Shuffle Open Source Project
*
* 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.
*/
package org.dodgybits.shuffle.android.persistence;
import java.util.Arrays;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.widget.SimpleCursorAdapter;
/**
* A database cursor adaptor that can be used for an AutoCompleteTextField.
*
*/
public class AutoCompleteCursorAdapter extends SimpleCursorAdapter {
private static final String cTag = "AutoCompleteCursorAdapter";
private Context mContext;
private String[] mProjection;
private Uri mContentUri;
public AutoCompleteCursorAdapter(Context context, Cursor c, String[] from, Uri contentUri) {
super(context, android.R.layout.simple_list_item_1, c, from, new int[] { android.R.id.text1 });
mContext = context;
mProjection = from;
mContentUri = contentUri;
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (constraint == null || constraint.length() == 0) {
return super.runQueryOnBackgroundThread(constraint);
}
StringBuilder buffer = null;
String[] args = null;
if (constraint != null) {
buffer = new StringBuilder();
buffer.append(mProjection[0]);
buffer.append(" LIKE ?");
args = new String[] { '%' + constraint.toString() + '%'};
}
String query = buffer.toString();
Log.d(cTag, "Query '" + query + "' with params: " + Arrays.asList(args));
return mContext.getContentResolver().query(mContentUri, mProjection,
query, args, null);
}
@Override
public CharSequence convertToString(Cursor cursor) {
// assuming name is first entry in cursor....
return cursor.getString(0);
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/persistence/AutoCompleteCursorAdapter.java | Java | asf20 | 2,366 |
package org.dodgybits.shuffle.android.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class RoboAppWidgetProvider extends RoboBroadcastReceiver {
@Override
protected void handleReceive(Context context, Intent intent) {
// Protect against rogue update broadcasts (not really a security issue,
// just filter bad broadcasts out so subclasses are less likely to crash).
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
Bundle extras = intent.getExtras();
if (extras != null) {
int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (appWidgetIds != null && appWidgetIds.length > 0) {
this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds);
}
}
}
else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
this.onDeleted(context, new int[] { appWidgetId });
}
}
else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) {
this.onEnabled(context);
}
else if (AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(action)) {
this.onDisabled(context);
}
}
/**
* Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_UPDATE} broadcast when
* this AppWidget provider is being asked to provide {@link android.widget.RemoteViews RemoteViews}
* for a set of AppWidgets. Override this method to implement your own AppWidget functionality.
*
* {@more}
*
* @param context The {@link android.content.Context Context} in which this receiver is
* running.
* @param appWidgetManager A {@link AppWidgetManager} object you can call {@link
* AppWidgetManager#updateAppWidget} on.
* @param appWidgetIds The appWidgetIds for which an update is needed. Note that this
* may be all of the AppWidget instances for this provider, or just
* a subset of them.
*
* @see AppWidgetManager#ACTION_APPWIDGET_UPDATE
*/
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
}
/**
* Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_DELETED} broadcast when
* one or more AppWidget instances have been deleted. Override this method to implement
* your own AppWidget functionality.
*
* {@more}
*
* @param context The {@link android.content.Context Context} in which this receiver is
* running.
* @param appWidgetIds The appWidgetIds that have been deleted from their host.
*
* @see AppWidgetManager#ACTION_APPWIDGET_DELETED
*/
public void onDeleted(Context context, int[] appWidgetIds) {
}
/**
* Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_ENABLED} broadcast when
* the a AppWidget for this provider is instantiated. Override this method to implement your
* own AppWidget functionality.
*
* {@more}
* When the last AppWidget for this provider is deleted,
* {@link AppWidgetManager#ACTION_APPWIDGET_DISABLED} is sent by the AppWidget manager, and
* {@link #onDisabled} is called. If after that, an AppWidget for this provider is created
* again, onEnabled() will be called again.
*
* @param context The {@link android.content.Context Context} in which this receiver is
* running.
*
* @see AppWidgetManager#ACTION_APPWIDGET_ENABLED
*/
public void onEnabled(Context context) {
}
/**
* Called in response to the {@link AppWidgetManager#ACTION_APPWIDGET_DISABLED} broadcast, which
* is sent when the last AppWidget instance for this provider is deleted. Override this method
* to implement your own AppWidget functionality.
*
* {@more}
*
* @param context The {@link android.content.Context Context} in which this receiver is
* running.
*
* @see AppWidgetManager#ACTION_APPWIDGET_DISABLED
*/
public void onDisabled(Context context) {
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/widget/RoboAppWidgetProvider.java | Java | asf20 | 4,646 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.
*/
package org.dodgybits.shuffle.android.widget;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.view.ContextIcon;
import roboguice.inject.ContextSingleton;
import android.view.View;
import android.widget.RemoteViews;
@ContextSingleton
/**
* A widget provider. We have a string that we pull from a preference in order to show
* the configuration settings and the current time when the widget was updated. We also
* register a BroadcastReceiver for time-changed and timezone-changed broadcasts, and
* update then too.
*/
public class LightWidgetProvider extends AbstractWidgetProvider {
@Override
protected int getWidgetLayoutId() {
return R.layout.widget;
}
@Override
protected int getTotalEntries() {
return 4;
}
@Override
protected int updateContext(android.content.Context androidContext, RemoteViews views, Context context, int taskCount) {
int contextIconId = getIdIdentifier(androidContext, "context_icon_" + taskCount);
String iconName = context != null ? context.getIconName() : null;
ContextIcon icon = ContextIcon.createIcon(iconName, androidContext.getResources());
if (icon != ContextIcon.NONE) {
views.setImageViewResource(contextIconId, icon.smallIconId);
views.setViewVisibility(contextIconId, View.VISIBLE);
} else {
views.setViewVisibility(contextIconId, View.INVISIBLE);
}
return contextIconId;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/widget/LightWidgetProvider.java | Java | asf20 | 2,190 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.
*/
package org.dodgybits.shuffle.android.widget;
import java.util.HashMap;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.util.TextColours;
import org.dodgybits.shuffle.android.core.view.DrawableUtils;
import org.dodgybits.shuffle.android.list.config.StandardTaskQueries;
import roboguice.inject.ContextSingleton;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
@ContextSingleton
/**
* A widget provider. We have a string that we pull from a preference in order to show
* the configuration settings and the current time when the widget was updated. We also
* register a BroadcastReceiver for time-changed and timezone-changed broadcasts, and
* update then too.
*/
public class DarkWidgetProvider extends AbstractWidgetProvider {
private static final Bitmap sEmptyBitmap = Bitmap.createBitmap(8, 40, Bitmap.Config.ARGB_8888);
private HashMap<Integer, Bitmap> mGradientCache;
private TextColours mColours;
@Override
protected int getWidgetLayoutId() {
return R.layout.widget_dark;
}
@Override
protected int getTotalEntries() {
return 7;
}
@Override
public void handleReceive(android.content.Context context, Intent intent) {
mColours = TextColours.getInstance(context);
mGradientCache = new HashMap<Integer, Bitmap>(mColours.getNumColours());
super.handleReceive(context, intent);
}
@Override
protected void setupFrameClickIntents(android.content.Context androidContext, RemoteViews views, String queryName){
super.setupFrameClickIntents(androidContext, views, queryName);
Intent intent = StandardTaskQueries.getActivityIntent(androidContext, queryName);
PendingIntent pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0);
views.setOnClickPendingIntent(R.id.all_tasks, pendingIntent);
}
@Override
protected int updateContext(android.content.Context androidContext, RemoteViews views, Context context, int taskCount) {
Bitmap gradientBitmap = null;
if (context != null) {
int colourIndex = context.getColourIndex();
gradientBitmap = mGradientCache.get(colourIndex);
if (gradientBitmap == null) {
int colour = mColours.getBackgroundColour(colourIndex);
GradientDrawable drawable = DrawableUtils.createGradient(colour, Orientation.TOP_BOTTOM);
drawable.setCornerRadius(6.0f);
Bitmap bitmap = Bitmap.createBitmap(16, 80, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
RelativeLayout l = new RelativeLayout(androidContext);
l.setBackgroundDrawable(drawable);
l.layout(0, 0, 16, 80);
l.draw(canvas);
gradientBitmap = Bitmap.createBitmap(bitmap, 6, 0, 10, 80);
mGradientCache.put(colourIndex, gradientBitmap);
}
}
views.setImageViewBitmap(getIdIdentifier(androidContext, "contextColour_" + taskCount), gradientBitmap == null ? sEmptyBitmap : gradientBitmap);
return 0;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/widget/DarkWidgetProvider.java | Java | asf20 | 4,110 |
package org.dodgybits.shuffle.android.widget;
import java.util.ArrayList;
import java.util.List;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.view.IconArrayAdapter;
import org.dodgybits.shuffle.android.list.config.StandardTaskQueries;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.activity.RoboListActivity;
import roboguice.util.Ln;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* The configuration screen for the DarkWidgetProvider widget.
*/
public class WidgetConfigure extends RoboListActivity {
private static final int NEXT_TASKS = 0;
private static final int DUE_TODAY = 1;
private static final int DUE_NEXT_WEEK = 2;
private static final int DUE_NEXT_MONTH = 3;
private static final int INBOX = 4;
private static final int TICKLER = 5;
private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
private List<String> mLabels;
public WidgetConfigure() {
super();
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
setContentView(R.layout.launcher_shortcut);
setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
// Find the widget id from the intent.
final Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
mLabels = new ArrayList<String>();
// TODO figure out a non-retarded way of added padding between text and icon
mLabels.add(" " + getString(R.string.title_next_tasks));
mLabels.add(" " + getString(R.string.title_due_today));
mLabels.add(" " + getString(R.string.title_due_next_week));
mLabels.add(" " + getString(R.string.title_due_next_month));
mLabels.add(" " + getString(R.string.title_inbox));
mLabels.add(" " + getString(R.string.title_tickler));
setTitle(R.string.title_widget_picker);
Integer[] iconIds = new Integer[6];
iconIds[NEXT_TASKS] = R.drawable.next_actions;
iconIds[DUE_TODAY] = R.drawable.due_actions;
iconIds[DUE_NEXT_WEEK] = R.drawable.due_actions;
iconIds[DUE_NEXT_MONTH] = R.drawable.due_actions;
iconIds[INBOX] = R.drawable.inbox;
iconIds[TICKLER] = R.drawable.ic_media_pause;
ArrayAdapter<CharSequence> adapter = new IconArrayAdapter(
this, R.layout.text_item_view, R.id.name, mLabels.toArray(new String[0]), iconIds);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String key = Preferences.getWidgetQueryKey(mAppWidgetId);
String queryName = queryValue(position);
Preferences.getEditor(this).putString(key, queryName).commit();
Ln.d("Saving query %s under key %s", queryName, key);
// let widget update itself (suggested approach of calling updateAppWidget did nothing)
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {mAppWidgetId});
intent.setPackage(getPackageName());
sendBroadcast(intent);
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
private String queryValue(int position) {
String result = null;
switch (position) {
case INBOX:
result = StandardTaskQueries.cInbox;
break;
case NEXT_TASKS:
result = StandardTaskQueries.cNextTasks;
break;
case DUE_TODAY:
result = StandardTaskQueries.cDueToday;
break;
case DUE_NEXT_WEEK:
result = StandardTaskQueries.cDueNextWeek;
break;
case DUE_NEXT_MONTH:
result = StandardTaskQueries.cDueNextMonth;
break;
case TICKLER:
result = StandardTaskQueries.cTickler;
break;
}
return result;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/widget/WidgetConfigure.java | Java | asf20 | 5,000 |
package org.dodgybits.shuffle.android.widget;
import static org.dodgybits.shuffle.android.core.util.Constants.cIdType;
import static org.dodgybits.shuffle.android.core.util.Constants.cPackage;
import static org.dodgybits.shuffle.android.core.util.Constants.cStringType;
import java.util.Arrays;
import java.util.HashMap;
import org.dodgybits.android.shuffle.R;
import org.dodgybits.shuffle.android.core.model.Context;
import org.dodgybits.shuffle.android.core.model.Project;
import org.dodgybits.shuffle.android.core.model.Task;
import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister;
import org.dodgybits.shuffle.android.core.model.persistence.EntityCache;
import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister;
import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister;
import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector;
import org.dodgybits.shuffle.android.list.config.StandardTaskQueries;
import org.dodgybits.shuffle.android.persistence.provider.ContextProvider;
import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider;
import org.dodgybits.shuffle.android.persistence.provider.TaskProvider;
import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings;
import org.dodgybits.shuffle.android.preference.model.Preferences;
import roboguice.util.Ln;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.view.View;
import android.widget.RemoteViews;
import com.google.inject.Inject;
public abstract class AbstractWidgetProvider extends RoboAppWidgetProvider {
private static final HashMap<String,Integer> sIdCache = new HashMap<String,Integer>();
@Inject TaskPersister mTaskPersister;
@Inject ProjectPersister mProjectPersister;
@Inject EntityCache<Project> mProjectCache;
@Inject ContextPersister mContextPersister;
@Inject EntityCache<Context> mContextCache;
@Override
public void handleReceive(android.content.Context context, Intent intent) {
super.handleReceive(context, intent);
String action = intent.getAction();
if (TaskProvider.UPDATE_INTENT.equals(action) ||
ProjectProvider.UPDATE_INTENT.equals(action) ||
ContextProvider.UPDATE_INTENT.equals(action) ||
Preferences.CLEAN_INBOX_INTENT.equals(action) ||
ListPreferenceSettings.LIST_PREFERENCES_UPDATED.equals(action)) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
// Retrieve the identifiers for each instance of your chosen widget.
ComponentName thisWidget = new ComponentName(context, getClass());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
if (appWidgetIds != null && appWidgetIds.length > 0) {
this.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
}
@Override
public void onUpdate(android.content.Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Ln.d("onUpdate");
ComponentName thisWidget = new ComponentName(context, getClass());
int[] localAppWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
Arrays.sort(localAppWidgetIds);
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
if (Arrays.binarySearch(localAppWidgetIds, appWidgetId) >= 0) {
String prefKey = Preferences.getWidgetQueryKey(appWidgetId);
String queryName = Preferences.getWidgetQuery(context, prefKey);
Ln.d("App widget %s found query %s for key %s", appWidgetId, queryName, prefKey);
updateAppWidget(context, appWidgetManager, appWidgetId, queryName);
} else {
Ln.d("App widget %s not handled by this provider %s", appWidgetId, getClass());
}
}
}
@Override
public void onDeleted(android.content.Context context, int[] appWidgetIds) {
Ln.d("onDeleted");
// When the user deletes the widget, delete the preference associated with it.
final int N = appWidgetIds.length;
SharedPreferences.Editor editor = Preferences.getEditor(context);
for (int i=0; i<N; i++) {
String prefKey = Preferences.getWidgetQueryKey(appWidgetIds[i]);
editor.remove(prefKey);
}
editor.commit();
}
@Override
public void onEnabled(android.content.Context context) {
}
@Override
public void onDisabled(android.content.Context context) {
}
private void updateAppWidget(final android.content.Context androidContext, AppWidgetManager appWidgetManager,
int appWidgetId, String queryName) {
Ln.d("updateAppWidget appWidgetId=%s queryName=%s provider=%s", appWidgetId, queryName, getClass());
RemoteViews views = new RemoteViews(androidContext.getPackageName(), getWidgetLayoutId());
Cursor taskCursor = createCursor(androidContext, queryName);
if (taskCursor == null) return;
int titleId = getIdentifier(androidContext, "title_" + queryName, cStringType);
views.setTextViewText(R.id.title, androidContext.getString(titleId) + " (" + taskCursor.getCount() + ")");
setupFrameClickIntents(androidContext, views, queryName);
int totalEntries = getTotalEntries();
for (int taskCount = 1; taskCount <= totalEntries; taskCount++) {
Task task = null;
Project project = null;
Context context = null;
if (taskCursor.moveToNext()) {
task = mTaskPersister.read(taskCursor);
project = mProjectCache.findById(task.getProjectId());
context = mContextCache.findById(task.getContextId());
}
int descriptionViewId = updateDescription(androidContext, views, task, taskCount);
int projectViewId = updateProject(androidContext, views, project, taskCount);
int contextIconId = updateContext(androidContext, views, context, taskCount);
if (task != null) {
Uri.Builder builder = TaskProvider.Tasks.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, task.getLocalId().getId());
Uri taskUri = builder.build();
Intent intent = new Intent(Intent.ACTION_VIEW, taskUri);
Ln.d("Adding pending event for viewing uri %s", taskUri);
int entryId = getIdIdentifier(androidContext, "entry_" + taskCount);
PendingIntent pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0);
views.setOnClickPendingIntent(entryId, pendingIntent);
views.setOnClickPendingIntent(descriptionViewId, pendingIntent);
views.setOnClickPendingIntent(projectViewId, pendingIntent);
if (contextIconId != 0) {
views.setOnClickPendingIntent(contextIconId, pendingIntent);
}
}
}
taskCursor.close();
appWidgetManager.updateAppWidget(appWidgetId, views);
}
protected Cursor createCursor(android.content.Context androidContext, String queryName) {
TaskSelector query = StandardTaskQueries.getQuery(queryName);
if (query == null) return null;
String key = StandardTaskQueries.getFilterPrefsKey(queryName);
ListPreferenceSettings settings = new ListPreferenceSettings(key);
query = query.builderFrom().applyListPreferences(androidContext, settings).build();
return androidContext.getContentResolver().query(
TaskProvider.Tasks.CONTENT_URI,
TaskProvider.Tasks.FULL_PROJECTION,
query.getSelection(androidContext),
query.getSelectionArgs(),
query.getSortOrder());
}
abstract int getWidgetLayoutId();
abstract int getTotalEntries();
protected void setupFrameClickIntents(android.content.Context androidContext, RemoteViews views, String queryName){
Intent intent = StandardTaskQueries.getActivityIntent(androidContext, queryName);
PendingIntent pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0);
views.setOnClickPendingIntent(R.id.title, pendingIntent);
intent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI);
pendingIntent = PendingIntent.getActivity(androidContext, 0, intent, 0);
views.setOnClickPendingIntent(R.id.add_task, pendingIntent);
}
protected int updateDescription(android.content.Context androidContext, RemoteViews views, Task task, int taskCount) {
int descriptionViewId = getIdIdentifier(androidContext, "description_" + taskCount);
if (descriptionViewId != 0) {
views.setTextViewText(descriptionViewId, task != null ? task.getDescription() : "");
}
return descriptionViewId;
}
protected int updateProject(android.content.Context androidContext, RemoteViews views, Project project, int taskCount) {
int projectViewId = getIdIdentifier(androidContext, "project_" + taskCount);
views.setViewVisibility(projectViewId, project == null ? View.INVISIBLE : View.VISIBLE);
views.setTextViewText(projectViewId, project != null ? project.getName() : "");
return projectViewId;
}
abstract protected int updateContext(android.content.Context androidContext, RemoteViews views, Context context, int taskCount);
static int getIdIdentifier(android.content.Context context, String name) {
Integer id = sIdCache.get(name);
if (id == null) {
id = getIdentifier(context, name, cIdType);
if (id == 0) return id;
sIdCache.put(name, id);
}
Ln.d("Got id " + id + " for resource " + name);
return id;
}
static int getIdentifier(android.content.Context context, String name, String type) {
int id = context.getResources().getIdentifier(
name, type, cPackage);
Ln.d("Got id " + id + " for resource " + name);
return id;
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/widget/AbstractWidgetProvider.java | Java | asf20 | 10,506 |
package org.dodgybits.shuffle.android.widget;
import roboguice.RoboGuice;
import roboguice.inject.RoboInjector;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* To ensure proper ContextScope usage, override the handleReceive method
*
* Replace with robojuice version when following issue is fixed...
* http://code.google.com/p/roboguice/issues/detail?id=150
*/
public abstract class RoboBroadcastReceiver extends BroadcastReceiver {
/** Handles the receive event. This method should not be overridden, instead override
* the handleReceive method to ensure that the proper ContextScope is maintained.
* @param context
* @param intent
*/
@Override
public final void onReceive(Context context, Intent intent) {
final RoboInjector injector = RoboGuice.getInjector(context);
injector.injectMembers(this);
handleReceive(context, intent);
}
/**
* Template method that should be overridden to handle the broadcast event
* Using this method ensures that the proper ContextScope is maintained before and after
* the execution of the receiver.
* @param context
* @param intent
*/
@SuppressWarnings("UnusedParameters")
protected void handleReceive(Context context, Intent intent) {
// proper template method to handle the receive
}
}
| 1012607376-daihanlong | shuffle-android/src/org/dodgybits/shuffle/android/widget/RoboBroadcastReceiver.java | Java | asf20 | 1,411 |
{\rtf1\ansi\ansicpg1252\cocoartf1138\cocoasubrtf230
{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset0 Consolas;}
{\colortbl;\red255\green255\blue255;}
{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid1}
{\list\listtemplateid2\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid101\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid2}
{\list\listtemplateid3\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid201\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid3}}
{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}{\listoverride\listid3\listoverridecount0\ls3}}
\paperw11900\paperh16840\margl1440\margr1440\vieww24460\viewh18600\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\b\fs48 \cf0 Shuffle Developer Setup Guide\
\b0\fs24 \
\fs36 Introduction
\fs24 \
\
Shuffle uses Maven for building and dependency management.\
\
\fs36 Prerequisites
\fs24 \
\
\pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\pardirnatural
\ls1\ilvl0\cf0 {\listtext 1. }Maven 3.0.x - http://maven.apache.org/download.html\
{\listtext 2. }Google Protocol Buffer compiler - http://code.google.com/p/protobuf/downloads/list\
{\listtext 3. }Android SDK - http://developer.android.com/sdk/index.html\
{\listtext 4. }Set environment variable ANDROID_HOME to the path of your installed Android SDK and add $ANDROID_HOME/tools as well as $ANDROID_HOME/platform-tools to your $PATH. (or on Windows %ANDROID_HOME%\\tools and %ANDROID_HOME%\\platform-tools).\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\cf0 \
\b Installing missing artifacts\
\b0 \
I couldn't find c2dm or flurry sdk in any publicly available maven repository, so you'll need to install them manually.\
\
From lib directory run...\
\f1 mvn install:install-file -Dfile=c2dm-server.jar -Dsources=c2dm-server-src.jar -DgroupId=com.google.android.c2dm -DartifactId=c2dm-server -Dversion=1.5.5 -Dpackaging=jar\
mvn install:install-file -Dfile=c2dm.jar -Dsources=c2dm-sources.jar -DgroupId=com.google.android.c2dm -DartifactId=c2dm -Dversion=1.5.5 -Dpackaging=jar\
mvn install:install-file -Dfile=FlurryAgent.jar -DgroupId=com.flurry -DartifactId=flurry-sdk -Dversion=2.2.1 -Dpackaging=jar\
\f0 \
Clone git repo from here https://github.com/mosabua/maven-android-sdk-deployer\
Then from a shell in your local clone...\
\f1 mvn clean install -N\
cd extras\
mvn clean install\
#To compile from the command line, you'll also need to generate v3 since the maven android\
#plugin is ignoring the exclude\
mvn clean install -DPkg.Revision=3\
\f0 \
\fs36 Eclipse integration\
\fs24 \
Download the Google Eclipse plugin and the GWT and Google App Engine SDK versions corresponding to those currently used by Shuffle.\
\
\b Android\
\b0 \
\pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\pardirnatural
\ls2\ilvl0\cf0 {\listtext 1. }Install m2e-android connector from http://rgladwell.github.com/m2e-android/updates/master/\
{\listtext 2. }Follow instructions here: http://rgladwell.github.com/m2e-android/\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\cf0 \
\b Google App Engine and GWT\
\b0 \
\pard\tx220\tx720\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\li720\fi-720\pardirnatural
\ls3\ilvl0\cf0 {\listtext 1. }Install m2eclipse-wtp http://download.jboss.org/jbosstools/updates/m2eclipse-wtp\
{\listtext 2. }Install m2e connector for build-helper-maven-plugin This should happen automatically when you import a project that requires it. If not, you'll see an error in the POM. To install it, go to Window > Preferences > Discovery > Open Catalog and install the buildhelper connector, then re-import the project from scratch.\
{\listtext 3. }Import your maven project into eclipse using m2eclipse import wizard.\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\cf0 \
\b Troubleshooting
\b0 \
\
If you get the following error in Eclipse, in Project preferences > Google switch to using the GWT and GAE versions from Google rather than the ones in your local repository.\
\
\f1 The type javax.validation.ConstraintViolation cannot be resolved. It is indirectly referenced from required .class files\
\f0 \
\fs36 IntelliJ integration\
\fs24 \
For OS X, you'll probably need to set ANDROID_HOME in ~/.MacOSX/environment.plist, logout then in again. See http://developer.apple.com/library/mac/#qa/qa2001/qa1067.html\
\
New project > Import project from external model > Maven\
Remove GWT facet from all but the shuffle-app-engine module\
\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\b \cf0 Troubleshooting
\b0 \
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\cf0 \
If the android-shuffle module is setup with the Java 1.6 SDK, you need to replace it with the Android SDK.\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\cf0 Right click shuffle-android and select Project Structure\
Click on SDKs and add Android 2.2 Platform\
Click on Modules > shuffle-android > Dependencies and select Android 2.2 SDK\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\cf0 \
\
} | 1012607376-daihanlong | INSTALL.rtf | Rich Text Format | asf20 | 6,113 |
#!/bin/bash
if [ $# != 1 ]
then
echo "Usage: $0 emailAddress"
exit 1
fi
read -s -p "Password: " mypassword
echo ""
curl https://www.google.com/accounts/ClientLogin -d Email=$1 -d "Passwd=$mypassword" -d accountType=GOOGLE -d source=Google-cURL-Example -d service=ac2dm
| 1012607376-daihanlong | shuffle-app-engine/auth.sh | Shell | asf20 | 282 |
<!doctype html>
<!-- The DOCTYPE declaration above will set the -->
<!-- browser's rendering engine into -->
<!-- "Standards Mode". Replacing this declaration -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout. -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- -->
<!-- Consider inlining CSS to reduce the number of requested files -->
<!-- -->
<link type="text/css" rel="stylesheet" href="Shuffle.css">
<!-- -->
<!-- Any title is fine -->
<!-- -->
<title>Shuffle</title>
<!-- -->
<!-- This script loads your compiled module. -->
<!-- If you add any GWT meta tags, they must -->
<!-- be added before this line. -->
<!-- -->
<script type="text/javascript" language="javascript" src="shuffle/shuffle.nocache.js"></script>
</head>
<!-- -->
<!-- The body can have arbitrary html, or -->
<!-- you can leave the body empty if you want -->
<!-- to create a completely dynamic UI. -->
<!-- -->
<body>
<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>
</body>
</html>
| 1012607376-daihanlong | shuffle-app-engine/src/main/webapp/Shuffle.html | HTML | asf20 | 2,165 |
/** Add css rules here for your application. */
html,body {
padding: 0px;
margin: 0px;
width: 100%;
height: 100%;
position: absolute;
}
body {
font-family: Arial, helvetica, verdana, sans-serif;
background: #efefef;
overflow-x: hidden;
}
#header {
width: 100%;
text-align: center;
background: #666;
padding: 15px 0px 50px 0px;
-webkit-box-shadow: inset 0px -5px 5px 0px #444;
-moz-box-shadow: inset 0px -5px 5px 0px #444;
box-shadow: inset 0px -5px 5px 0px #444;
}
#header p {
color: #efefef;
}
#footer {
width: 100%;
text-align: center;
clear: both;
padding-top: 40px;
}
#footer p {
color: #ccc;
}
.status {
font-size: 13px;
margin: 15px;
font-weight: bold;
display: inline;
padding: 3px 7px;
}
.success {
background: #FFF1A8;
}
.error {
background: #990000;
color: #fff;
}
.none {
background: #666;
}
#message {
width: 600px;
margin: 40px auto -25px;
height: 100%;
}
p {
font-size: 13px;
color: #898989;
}
.roundRect {
margin-top: 12px;
background: #fff;
-moz-box-shadow: 0 0 10px #ddd;
-webkit-box-shadow: 0 0 10px #ddd;
box-shadow: 0 0 10px #ddd;
border-radius: 5px;
}
input.field {
font-family: Arial, helvetica, verdana, sans-serif;
padding: 10px 12px 12px 12px;
font-size: 18px;
text-shadow: 0px 1px 0px #fff;
border: none;
border-bottom: 1px solid #E9E9E9;
outline:none;
width: 560px;
margin:3px 0px;
}
textarea {
padding: 5px 12px;
font-size: 18px;
text-shadow: 0px 1px 0px #fff;
border: none;
outline:none;
resize: none;
font-family: Arial, helvetica, verdana, sans-serif;
margin:3px 0px;
width: 552px;
}
button.send {
margin-top:10px;
float: right;
padding: 10px 14px;
font-size:12px;
font-weight: bold;
text-transform:uppercase;
color:#fff;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#5D9AFE), to(#4785E8));
background: -moz-linear-gradient(top, #5D9AFE, #4785E8);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
border: none;
}
button.send:active {
margin-top:10px;
float: right;
padding: 10px 14px;
font-size:12px;
font-weight: bold;
text-transform:uppercase;
color:#fff;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#4785E8), to(#5D9AFE));
background: -moz-linear-gradient(top, #4785E8, #5D9AFE);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
border: none;
}
button.centerbtn {
float: none;
display: inline;
margin: 0 auto;
}
button.centerbtn:active {
float: none;
display: inline;
margin: 0 auto;
} | 1012607376-daihanlong | shuffle-app-engine/src/main/webapp/Shuffle.css | CSS | asf20 | 2,800 |
.edit-form {
text-align: left;
}
.edit-form span {
font-weight: bold;
text-align: right;
width: 6em;
float: left;
padding-right: 1em;
padding-top: 3px;
}
.button-bar {
float: right;
}
.details {
padding: 4px;
border: 1px solid #ccc;
border-top: 1px solid #666;
font-size: 100%;
-moz-box-shadow: 1px 1px 2px hsla(0, 0%, 0%, .3);
-webkit-box-shadow: 1px 1px 2px hsla(0, 0%, 0%, .3);
box-shadow: 1px 1px 2px hsla(0, 0%, 0%, .3); /* Opera, IE 9 */
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/resources/org/dodgybits/shuffle/gwt/core/editAction.css | CSS | asf20 | 509 |
body {
font-family: "Segoe UI", Segoe, Calibri, Arial, sans-serif;
color: #000;
background: #fff;
}
a:link, a:visited, a:hover, a:active {
color: #000;
}
/* Action tables */
.action-title {
white-space: nowrap;
}
.action-details {
white-space: nowrap;
color: gray;
}
.action-due-in-future {
}
.action-due-in-pass {
color: red;
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/resources/org/dodgybits/shuffle/gwt/global.css | CSS | asf20 | 377 |
package org.dodgybits.shuffle.gwt.gin;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.google.inject.Provider;
import com.gwtplatform.dispatch.client.gin.DispatchAsyncModule;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import org.dodgybits.shuffle.client.ShuffleRequestFactory;
import org.dodgybits.shuffle.gwt.core.ErrorPresenter;
import org.dodgybits.shuffle.gwt.core.HelpPresenter;
import org.dodgybits.shuffle.gwt.core.InboxPresenter;
import org.dodgybits.shuffle.gwt.core.LoginPresenter;
import org.dodgybits.shuffle.gwt.core.MainPresenter;
import org.dodgybits.shuffle.gwt.core.NavigationPresenter;
import org.dodgybits.shuffle.gwt.core.EditActionPresenter;
import org.dodgybits.shuffle.gwt.core.WelcomePresenter;
import org.dodgybits.shuffle.gwt.gin.ClientModule;
@GinModules({ DispatchAsyncModule.class, ClientModule.class })
public interface ClientGinjector extends Ginjector {
EventBus getEventBus();
PlaceManager getPlaceManager();
Provider<WelcomePresenter> getWelcomePresenter();
AsyncProvider<ErrorPresenter> getErrorPresenter();
Provider<MainPresenter> getMainPresenter();
AsyncProvider<LoginPresenter> getLoginPresenter();
AsyncProvider<HelpPresenter> getHelpPresenter();
AsyncProvider<InboxPresenter> getInboxPresenter();
AsyncProvider<EditActionPresenter> getNewActionPresenter();
Provider<NavigationPresenter> getNavigationPresenter();
ShuffleRequestFactory getRequestFactory();
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/gin/ClientGinjector.java | Java | asf20 | 1,592 |
package org.dodgybits.shuffle.gwt.gin;
import org.dodgybits.shuffle.client.ShuffleRequestFactory;
import org.dodgybits.shuffle.gwt.core.ErrorPresenter;
import org.dodgybits.shuffle.gwt.core.ErrorView;
import org.dodgybits.shuffle.gwt.core.HelpPresenter;
import org.dodgybits.shuffle.gwt.core.HelpView;
import org.dodgybits.shuffle.gwt.core.InboxPresenter;
import org.dodgybits.shuffle.gwt.core.InboxView;
import org.dodgybits.shuffle.gwt.core.LoginPresenter;
import org.dodgybits.shuffle.gwt.core.LoginView;
import org.dodgybits.shuffle.gwt.core.MainPresenter;
import org.dodgybits.shuffle.gwt.core.MainView;
import org.dodgybits.shuffle.gwt.core.NavigationPresenter;
import org.dodgybits.shuffle.gwt.core.NavigationView;
import org.dodgybits.shuffle.gwt.core.EditActionPresenter;
import org.dodgybits.shuffle.gwt.core.EditActionView;
import org.dodgybits.shuffle.gwt.core.WelcomePresenter;
import org.dodgybits.shuffle.gwt.core.WelcomeView;
import org.dodgybits.shuffle.gwt.place.ClientPlaceManager;
import org.dodgybits.shuffle.gwt.place.DefaultPlace;
import org.dodgybits.shuffle.gwt.place.ErrorPlace;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import org.dodgybits.shuffle.shared.TaskService;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.gwtplatform.mvp.client.gin.AbstractPresenterModule;
import com.gwtplatform.mvp.client.gin.DefaultModule;
public class ClientModule extends AbstractPresenterModule {
@Override
protected void configure() {
install(new DefaultModule(ClientPlaceManager.class));
bindPresenter(WelcomePresenter.class, WelcomePresenter.MyView.class,
WelcomeView.class, WelcomePresenter.MyProxy.class);
bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.welcome);
bindPresenter(ErrorPresenter.class, ErrorPresenter.MyView.class,
ErrorView.class, ErrorPresenter.MyProxy.class);
bindConstant().annotatedWith(ErrorPlace.class).to(NameTokens.error);
bindPresenter(MainPresenter.class, MainPresenter.MyView.class,
MainView.class, MainPresenter.MyProxy.class);
bindPresenter(LoginPresenter.class, LoginPresenter.MyView.class,
LoginView.class, LoginPresenter.MyProxy.class);
bindPresenter(HelpPresenter.class, HelpPresenter.MyView.class,
HelpView.class, HelpPresenter.MyProxy.class);
bindPresenter(InboxPresenter.class, InboxPresenter.MyView.class,
InboxView.class, InboxPresenter.MyProxy.class);
bindPresenter(EditActionPresenter.class,
EditActionPresenter.MyView.class, EditActionView.class,
EditActionPresenter.MyProxy.class);
bindPresenterWidget(NavigationPresenter.class,
NavigationPresenter.MyView.class, NavigationView.class);
bind(ShuffleRequestFactory.class).in(Singleton.class);
}
@Provides
TaskService provideTaskService(ShuffleRequestFactory requestFactory) {
return requestFactory.taskService();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/gin/ClientModule.java | Java | asf20 | 2,866 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.gwt;
import java.util.Date;
import java.util.List;
import org.dodgybits.shuffle.client.ShuffleRequestFactory;
import org.dodgybits.shuffle.client.ShuffleRequestFactory.HelloWorldRequest;
import org.dodgybits.shuffle.client.ShuffleRequestFactory.MessageRequest;
import org.dodgybits.shuffle.gwt.formatter.ActionDateFormatter;
import org.dodgybits.shuffle.shared.MessageProxy;
import org.dodgybits.shuffle.shared.TaskProxy;
import org.dodgybits.shuffle.shared.TaskService;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.TextAreaElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
public class ShuffleWidget extends Composite {
private static final int STATUS_DELAY = 4000;
private static final String STATUS_ERROR = "status error";
private static final String STATUS_NONE = "status none";
private static final String STATUS_SUCCESS = "status success";
interface ShuffleUiBinder extends UiBinder<Widget, ShuffleWidget> {
}
private static ShuffleUiBinder uiBinder = GWT.create(ShuffleUiBinder.class);
private ActionDateFormatter mFormatter;
@UiField
TextAreaElement messageArea;
@UiField
InputElement recipientArea;
@UiField
DivElement status;
@UiField
Button sayHelloButton;
@UiField
Button sendMessageButton;
@UiField
Button fetchTasksButton;
@UiField
FlexTable table;
/**
* Timer to clear the UI.
*/
Timer timer = new Timer() {
@Override
public void run() {
status.setInnerText("");
status.setClassName(STATUS_NONE);
recipientArea.setValue("");
messageArea.setValue("");
}
};
private void setStatus(String message, boolean error) {
status.setInnerText(message);
if (error) {
status.setClassName(STATUS_ERROR);
} else {
if (message.length() == 0) {
status.setClassName(STATUS_NONE);
} else {
status.setClassName(STATUS_SUCCESS);
}
}
timer.schedule(STATUS_DELAY);
}
public ShuffleWidget() {
initWidget(uiBinder.createAndBindUi(this));
sayHelloButton.getElement().setClassName("send centerbtn");
sendMessageButton.getElement().setClassName("send");
mFormatter = new ActionDateFormatter();
final EventBus eventBus = new SimpleEventBus();
final ShuffleRequestFactory requestFactory = GWT.create(ShuffleRequestFactory.class);
requestFactory.initialize(eventBus);
sendMessageButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String recipient = recipientArea.getValue();
String message = messageArea.getValue();
setStatus("Connecting...", false);
sendMessageButton.setEnabled(false);
// Send a message using RequestFactory
MessageRequest request = requestFactory.messageRequest();
MessageProxy messageProxy = request.create(MessageProxy.class);
messageProxy.setRecipient(recipient);
messageProxy.setMessage(message);
Request<String> sendRequest = request.send().using(messageProxy);
sendRequest.fire(new Receiver<String>() {
@Override
public void onFailure(ServerFailure error) {
sendMessageButton.setEnabled(true);
setStatus(error.getMessage(), true);
}
@Override
public void onSuccess(String response) {
sendMessageButton.setEnabled(true);
setStatus(response, response.startsWith("Failure:"));
}
});
}
});
fetchTasksButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
setStatus("Connecting...", false);
fetchTasksButton.setEnabled(false);
// Send a message using RequestFactory
TaskService service = requestFactory.taskService();
Request<List<TaskProxy>> taskListRequest = service.listAll();
taskListRequest.fire(new Receiver<List<TaskProxy>>() {
@Override
public void onFailure(ServerFailure error) {
fetchTasksButton.setEnabled(true);
setStatus(error.getMessage(), true);
}
@Override
public void onSuccess(List<TaskProxy> tasks) {
fetchTasksButton.setEnabled(true);
setStatus("Success - got " + tasks.size(), false);
displayActions(tasks);
}
});
}
});
sayHelloButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
sayHelloButton.setEnabled(false);
HelloWorldRequest helloWorldRequest = requestFactory.helloWorldRequest();
helloWorldRequest.getMessage().fire(new Receiver<String>() {
@Override
public void onFailure(ServerFailure error) {
sayHelloButton.setEnabled(true);
setStatus(error.getMessage(), true);
}
@Override
public void onSuccess(String response) {
sayHelloButton.setEnabled(true);
setStatus(response, response.startsWith("Failure:"));
}
});
}
});
}
private void displayActions(List<TaskProxy> tasks) {
int numActions = tasks.size();
for (int i = 0; i < numActions; i++) {
TaskProxy taskValue = tasks.get(i);
displayAction(taskValue, i);
}
}
private void displayAction(TaskProxy taskValue, int row) {
String description = "<div class='actionTitle'>"
+ escapeHtml(taskValue.getDescription())
+ "<span class='actionDetails'> - "
+ escapeHtml(taskValue.getDetails()) + "</span></div>";
table.setHTML(row, 0, description);
table.setText(row, 1, mFormatter.getShortDate(taskValue.getModifiedDate()));
table.getCellFormatter().setStyleName(
row,
1,
isInPast(taskValue.getModifiedDate()) ? "actionDueInPass"
: "actionDueInFuture");
}
private static String escapeHtml(String maybeHtml) {
final Element div = DOM.createDiv();
DOM.setInnerText(div, maybeHtml);
return DOM.getInnerHTML(div);
}
private static boolean isInPast(Date date) {
return date != null && date.getTime() < System.currentTimeMillis();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/ShuffleWidget.java | Java | asf20 | 7,773 |
package org.dodgybits.shuffle.gwt.place;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface DefaultPlace {
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/place/DefaultPlace.java | Java | asf20 | 516 |
package org.dodgybits.shuffle.gwt.place;
import com.gwtplatform.mvp.client.proxy.PlaceManagerImpl;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.google.inject.Inject;
import com.google.gwt.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.TokenFormatter;
public class ClientPlaceManager extends PlaceManagerImpl {
private final PlaceRequest defaultPlaceRequest;
private final PlaceRequest errorPlaceRequest;
@Inject
public ClientPlaceManager(final EventBus eventBus,
final TokenFormatter tokenFormatter,
@DefaultPlace final String defaultPlaceNameToken,
@ErrorPlace final String errorPlaceNameToken) {
super(eventBus, tokenFormatter);
this.defaultPlaceRequest = new PlaceRequest(defaultPlaceNameToken);
this.errorPlaceRequest = new PlaceRequest(errorPlaceNameToken);
}
@Override
public void revealDefaultPlace() {
revealPlace(defaultPlaceRequest, false);
}
@Override
public void revealErrorPlace(String invalidHistoryToken) {
revealPlace(errorPlaceRequest, false);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/place/ClientPlaceManager.java | Java | asf20 | 1,071 |
package org.dodgybits.shuffle.gwt.place;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
public @interface ErrorPlace {
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/place/ErrorPlace.java | Java | asf20 | 514 |
package org.dodgybits.shuffle.gwt.place;
public class NameTokens {
public static final String welcome = "!welcome";
public static final String error = "!error";
public static final String login = "!login";
public static final String help = "!help";
public static final String inbox = "!inbox";
public static final String dueActions = "!dueActions";
public static final String nextActions = "!nextActions";
public static final String projects = "!projects";
public static final String tickler = "!tickler";
public static final String editAction = "!editAction";
public static String getWelcome() {
return welcome;
}
public static String getError() {
return error;
}
public static String getLogin() {
return login;
}
public static String getHelp() {
return help;
}
public static String getInbox() {
return inbox;
}
public static String getDueActions() {
return dueActions;
}
public static String getNextActions() {
return nextActions;
}
public static String getProjects() {
return projects;
}
public static String getTickler() {
return tickler;
}
public static String getEditAction() {
return editAction;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/place/NameTokens.java | Java | asf20 | 1,228 |
package org.dodgybits.shuffle.gwt.formatter;
import java.util.Date;
import com.google.gwt.i18n.client.DateTimeFormat;
public class ActionDateFormatter {
private DateTimeFormat dateFormat;
public ActionDateFormatter() {
dateFormat = DateTimeFormat.getFormat("d MMM");
}
public String getShortDate(Date date) {
String result = "";
if (date != null) {
if (isSameDay(date, new Date())) {
// only show time if date is today
result = DateTimeFormat.getShortTimeFormat().format(date);
} else {
result = dateFormat.format(date);
}
}
return result;
}
@SuppressWarnings("deprecation")
private static boolean isSameDay(Date date1, Date date2) {
return date1.getYear() == date2.getYear() &&
date1.getMonth() == date2.getMonth() &&
date1.getDate() == date2.getDate();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/formatter/ActionDateFormatter.java | Java | asf20 | 814 |
package org.dodgybits.shuffle.gwt;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class SingleUploadSample implements EntryPoint {
public void onModuleLoad() {
// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
form.setAction("/restoreBackup");
// Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
// Create a TextBox, giving it a name so that it will be submitted.
final TextBox tb = new TextBox();
tb.setName("textBoxFormElement");
panel.add(tb);
// Create a ListBox, giving it a name and some values to be associated
// with
// its options.
ListBox lb = new ListBox();
lb.setName("listBoxFormElement");
lb.addItem("foo", "fooValue");
lb.addItem("barry", "barValue");
lb.addItem("baz", "bazValue");
panel.add(lb);
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);
// Add a 'submit' button.
panel.add(new Button("Submit", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
form.submit();
}
}));
form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this
// event is
// fired. Assuming the service returned a response of type
// text/html,
// we can get the result text here (see the FormPanel
// documentation for
// further explanation).
Window.alert(event.getResults());
}
});
form.addSubmitHandler(new SubmitHandler() {
@Override
public void onSubmit(SubmitEvent event) {
// This event is fired just before the form is submitted. We can
// take
// this opportunity to perform validation.
if (tb.getText().length() == 0) {
Window.alert("The text box must not be empty");
event.cancel();
}
}
});
RootPanel.get().add(form);
RootPanel.get().add(new Button("Submit", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
form.submit();
}
}));
}
} | 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/SingleUploadSample.java | Java | asf20 | 3,726 |
package org.dodgybits.shuffle.gwt.core;
import java.util.List;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import org.dodgybits.shuffle.shared.TaskProxy;
import org.dodgybits.shuffle.shared.TaskService;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
public class InboxPresenter extends
Presenter<InboxPresenter.MyView, InboxPresenter.MyProxy> {
public interface MyView extends View {
void displayTasks(List<TaskProxy> tasks);
}
@ProxyCodeSplit
@NameToken(NameTokens.inbox)
public interface MyProxy extends ProxyPlace<InboxPresenter> {
}
private final Provider<TaskService> taskServiceProvider;
@Inject
public InboxPresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy, final Provider<TaskService> taskServiceProvider) {
super(eventBus, view, proxy);
this.taskServiceProvider = taskServiceProvider;
}
@Override
protected void revealInParent() {
RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this);
}
@Override
protected void onReset() {
super.onReset();
// Send a message using RequestFactory
Request<List<TaskProxy>> taskListRequest = taskServiceProvider.get().listAll();
taskListRequest.fire(new Receiver<List<TaskProxy>>() {
@Override
public void onFailure(ServerFailure error) {
GWT.log(error.getMessage());
}
@Override
public void onSuccess(List<TaskProxy> tasks) {
GWT.log("Success - got " + tasks.size() + " tasks");
getView().displayTasks(tasks);
}
});
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/InboxPresenter.java | Java | asf20 | 2,289 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.ViewImpl;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class MainView extends ViewImpl implements MainPresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, MainView> {
}
@UiField HTMLPanel mainPanel;
@UiField HTMLPanel navigation;
@Inject
public MainView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void setInSlot(Object slot, Widget widget) {
if (slot == MainPresenter.MAIN_SLOT) {
mainPanel.clear();
mainPanel.add(widget);
} else if (slot == MainPresenter.NAVIGATION_SLOT) {
navigation.clear();
navigation.add(widget);
}
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/MainView.java | Java | asf20 | 1,005 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.NameToken;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.google.inject.Inject;
import com.google.gwt.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import org.dodgybits.shuffle.gwt.core.MainPresenter;
public class HelpPresenter extends
Presenter<HelpPresenter.MyView, HelpPresenter.MyProxy> {
public interface MyView extends View {
// TODO Put your view methods here
}
@ProxyCodeSplit
@NameToken(NameTokens.help)
public interface MyProxy extends ProxyPlace<HelpPresenter> {
}
@Inject
public HelpPresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy) {
super(eventBus, view, proxy);
}
@Override
protected void revealInParent() {
RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/HelpPresenter.java | Java | asf20 | 1,116 |
package org.dodgybits.shuffle.gwt.core;
import java.util.Date;
import java.util.List;
import org.dodgybits.shuffle.gwt.formatter.ActionDateFormatter;
import org.dodgybits.shuffle.shared.TaskProxy;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionModel;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewImpl;
public class InboxView extends ViewImpl implements InboxPresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, InboxView> {
}
private static final ProvidesKey<TaskProxy> KEY_PROVIDER =
new ProvidesKey<TaskProxy>() {
@Override
public Object getKey(TaskProxy item) {
return item.getId();
}
};
private ActionDateFormatter mFormatter;
@UiField(provided=true)
CellTable<TaskProxy> table;
/**
* The provider that holds the list of contacts in the database.
*/
private ListDataProvider<TaskProxy> dataProvider = new ListDataProvider<TaskProxy>();
@Inject
public InboxView(final Binder binder) {
mFormatter = new ActionDateFormatter();
// Create a table.
// Set a key provider that provides a unique key for each contact. If key is
// used to identify contacts when fields (such as the name and address)
// change.
table = new CellTable<TaskProxy>(KEY_PROVIDER);
table.setWidth("100%", true);
// Add a selection model so we can select cells.
final SelectionModel<TaskProxy> selectionModel = new MultiSelectionModel<TaskProxy>(KEY_PROVIDER);
table.setSelectionModel(selectionModel,
DefaultSelectionEventManager.<TaskProxy> createCheckboxManager());
// Initialize the columns.
initTableColumns(selectionModel);
widget = binder.createAndBindUi(this);
}
/**
* Add the columns to the table.
*/
private void initTableColumns(
final SelectionModel<TaskProxy> selectionModel) {
// Checkbox column. This table will uses a checkbox column for selection.
// Alternatively, you can call table.setSelectionEnabled(true) to enable
// mouse selection.
Column<TaskProxy, Boolean> checkColumn = new Column<TaskProxy, Boolean>(
new CheckboxCell(true, false)) {
@Override
public Boolean getValue(TaskProxy object) {
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
table.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
table.setColumnWidth(checkColumn, 40, Unit.PX);
// Details.
Column<TaskProxy, String> detailsColumn = new Column<TaskProxy, String>(
new EditTextCell(new SafeHtmlRenderer<String>() {
public SafeHtml render(String object) {
return (object == null) ? SafeHtmlUtils.EMPTY_SAFE_HTML : SafeHtmlUtils.fromTrustedString(object);
}
public void render(String object, SafeHtmlBuilder appendable) {
appendable.append(SafeHtmlUtils.fromTrustedString(object));
}
})) {
@Override
public String getValue(TaskProxy taskValue) {
String description = "<div class='action-title'>"
+ SafeHtmlUtils.htmlEscape(taskValue.getDescription())
+ "<span class='action-details'> - "
+ SafeHtmlUtils.htmlEscape(taskValue.getDetails()) + "</span></div>";
return description;
}
};
table.addColumn(detailsColumn, "Details");
table.setColumnWidth(detailsColumn, 80, Unit.PCT);
// Date.
Column<TaskProxy, String> dueDateColumn = new Column<TaskProxy, String>(
new TextCell()) {
@Override
public String getValue(TaskProxy taskValue) {
return mFormatter.getShortDate(taskValue.getModifiedDate());
}
};
dueDateColumn.setSortable(true);
table.addColumn(dueDateColumn, "Due");
table.setColumnWidth(dueDateColumn, 60, Unit.PCT);
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void displayTasks(List<TaskProxy> tasks) {
dataProvider.setList(tasks);
dataProvider.addDataDisplay(table);
}
// private void displayAction(TaskProxy taskValue, int row) {
// String description = "<div class='actionTitle'>"
// + escapeHtml(taskValue.getDescription())
// + "<span class='actionDetails'> - "
// + escapeHtml(taskValue.getDetails()) + "</span></div>";
// table.setHTML(row, 0, description);
//
// table.setText(row, 1,
// mFormatter.getShortDate(taskValue.getModifiedDate()));
// table.getCellFormatter().setStyleName(
// row,
// 1,
// isInPast(taskValue.getModifiedDate()) ? "actionDueInPass"
// : "actionDueInFuture");
// }
//
// private static String escapeHtml(String maybeHtml) {
// final Element div = DOM.createDiv();
// DOM.setInnerText(div, maybeHtml);
// return DOM.getInnerHTML(div);
// }
private static boolean isInPast(Date date) {
return date != null && date.getTime() < System.currentTimeMillis();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/InboxView.java | Java | asf20 | 6,026 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.UiHandlers;
public interface NavigationUiHandlers extends UiHandlers {
void onNewAction();
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/NavigationUiHandlers.java | Java | asf20 | 172 |
package org.dodgybits.shuffle.gwt.core;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
public class NavigationView extends ViewWithUiHandlers<NavigationUiHandlers> implements NavigationPresenter.MyView, IsWidget {
private final Widget widget;
public interface Binder extends UiBinder<Widget, NavigationView> {
}
@UiField Button newAction;
@Inject
public NavigationView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
@UiHandler("newAction")
void onNewActionButtonClicked(ClickEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onNewAction();
}
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/NavigationView.java | Java | asf20 | 1,081 |
package org.dodgybits.shuffle.gwt.core;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewImpl;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
import org.dodgybits.shuffle.shared.TaskProxy;
public class EditActionView extends ViewWithUiHandlers<EditEntityUiHandlers> implements EditActionPresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, EditActionView> {
}
@UiField Button save;
@UiField Button cancel;
@UiField
TextBox description;
@UiField
TextBox context;
@UiField
TextBox project;
@UiField
TextArea details;
@UiField
DateBox from;
@UiField
DateBox due;
@Inject
public EditActionView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void displayTask(TaskProxy task) {
description.setText(task.getDescription());
details.setText(task.getDetails());
due.setValue(task.getModifiedDate());
}
@UiHandler("save")
void onSaveButtonClicked(ClickEvent event) {
GWT.log("Saving task");
if (getUiHandlers() != null) {
getUiHandlers().save(description.getText(), details.getText());
}
}
@UiHandler("cancel")
void onCancelButtonClicked(ClickEvent event) {
GWT.log("Canceling task edit");
if (getUiHandlers() != null) {
getUiHandlers().cancel();
}
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/EditActionView.java | Java | asf20 | 2,031 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.ViewImpl;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class LoginView extends ViewImpl implements LoginPresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, LoginView> {
}
@Inject
public LoginView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/LoginView.java | Java | asf20 | 566 |
package org.dodgybits.shuffle.gwt.core;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
public class NavigationPresenter extends
PresenterWidget<NavigationPresenter.MyView> implements NavigationUiHandlers {
public interface MyView extends View, HasUiHandlers<NavigationUiHandlers> {
// TODO Put your view methods here
}
private PlaceManager placeManager;
@Inject
public NavigationPresenter(final EventBus eventBus, final MyView view, PlaceManager placeManager) {
super(eventBus, view);
this.placeManager = placeManager;
getView().setUiHandlers(this);
}
public void onNewAction() {
PlaceRequest myRequest = new PlaceRequest(NameTokens.editAction);
placeManager.revealPlace( myRequest );
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/NavigationPresenter.java | Java | asf20 | 1,093 |
package org.dodgybits.shuffle.gwt.core;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent;
public class MainPresenter extends
Presenter<MainPresenter.MyView, MainPresenter.MyProxy> {
public interface MyView extends View {
// TODO Put your view methods here
}
@ProxyStandard
public interface MyProxy extends Proxy<MainPresenter> {
}
@ContentSlot
public static final Type<RevealContentHandler<?>> MAIN_SLOT = new Type<RevealContentHandler<?>>();
@ContentSlot
public static final Type<RevealContentHandler<?>> NAVIGATION_SLOT = new Type<RevealContentHandler<?>>();
private final NavigationPresenter navigationPresenter;
@Inject
public MainPresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy, final NavigationPresenter navigationPresenter) {
super(eventBus, view, proxy);
this.navigationPresenter = navigationPresenter;
}
@Override
protected void revealInParent() {
RevealRootLayoutContentEvent.fire(this, this);
}
@Override
protected void onReveal()
{
setInSlot(NAVIGATION_SLOT, navigationPresenter);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/MainPresenter.java | Java | asf20 | 1,608 |
package org.dodgybits.shuffle.gwt.core;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent;
public class WelcomePresenter extends
Presenter<WelcomePresenter.MyView, WelcomePresenter.MyProxy> {
public interface MyView extends View {
public void setFormattedDate(String formattedDate);
public void setBackgroundColor(String color);
}
@ProxyStandard
@NameToken(NameTokens.welcome)
public interface MyProxy extends ProxyPlace<WelcomePresenter> {
}
private final DispatchAsync dispatcher;
@Inject
public WelcomePresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy, final DispatchAsync dispatcher) {
super(eventBus, view, proxy);
this.dispatcher = dispatcher;
}
@Override
protected void revealInParent() {
RevealRootLayoutContentEvent.fire(this, this);
}
@Override
protected void onReset() {
getView().setFormattedDate("Loading...");
// dispatcher.execute(new GetServerDate(), new AsyncCallback<GetServerDateResult>() {
// @Override
// public void onFailure(Throwable caught) {
// getView().setFormattedDate("An error occurred!");
// }
// @Override
// public void onSuccess(GetServerDateResult result) {
// getView().setFormattedDate(result.getFormattedDate());
// }
// });
super.onReset();
}
@Override
public void prepareFromRequest(PlaceRequest request) {
// Gets the preferred color from a URL parameter, defaults to lightBlue
String color = request.getParameter("col", "lightBlue");
getView().setBackgroundColor(color);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/WelcomePresenter.java | Java | asf20 | 2,100 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.ViewImpl;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class HelpView extends ViewImpl implements HelpPresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, HelpView> {
}
@Inject
public HelpView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/HelpView.java | Java | asf20 | 562 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.NameToken;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import org.dodgybits.shuffle.shared.TaskProxy;
import org.dodgybits.shuffle.shared.TaskService;
public class EditActionPresenter extends
Presenter<EditActionPresenter.MyView, EditActionPresenter.MyProxy>
implements EditEntityUiHandlers {
private enum Action {
NEW, EDIT
}
public interface MyView extends View, HasUiHandlers<EditEntityUiHandlers> {
void displayTask(TaskProxy task);
}
@ProxyCodeSplit
@NameToken(NameTokens.editAction)
public interface MyProxy extends ProxyPlace<EditActionPresenter> {
}
private final TaskService mTaskService;
private PlaceManager placeManager;
private Action mAction;
private TaskProxy mTask = null;
@Inject
public EditActionPresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy, final PlaceManager placeManager, final Provider<TaskService> taskServiceProvider) {
super(eventBus, view, proxy);
this.placeManager = placeManager;
this.mTaskService = taskServiceProvider.get();
getView().setUiHandlers(this);
}
@Override
public void prepareFromRequest(PlaceRequest placeRequest) {
super.prepareFromRequest(placeRequest);
// In the next call, "view" is the default value,
// returned if "action" is not found on the URL.
String actionString = placeRequest.getParameter("action", "new");
mAction = Action.NEW;
if ("edit".equals(actionString)) {
Long taskId = null;
mAction = Action.EDIT;
try {
taskId = Long.valueOf(placeRequest.getParameter("taskId", null));
} catch (NumberFormatException e) {
}
if (taskId == null) {
placeManager.revealErrorPlace(placeRequest.getNameToken());
return;
}
load(taskId);
}
}
@Override
protected void revealInParent() {
RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this);
}
private void load(Long taskId) {
// Send a message using RequestFactory
Request<TaskProxy> taskListRequest = mTaskService.findById(taskId);
taskListRequest.fire(new Receiver<TaskProxy>() {
@Override
public void onFailure(ServerFailure error) {
GWT.log(error.getMessage());
}
@Override
public void onSuccess(TaskProxy task) {
mTask = task;
GWT.log("Success - got " + task);
getView().displayTask(task);
}
});
}
@Override
public void save(String description, String details) {
if (mAction == Action.NEW)
{
mTask = mTaskService.create(TaskProxy.class);
}
mTask.setDescription(description);
mTask.setDetails(details);
Request<Void> saveRequest = mTaskService.save(mTask);
saveRequest.fire(new Receiver<Void>() {
@Override
public void onFailure(ServerFailure error) {
GWT.log(error.getMessage());
}
@Override
public void onSuccess(Void response) {
GWT.log("Success");
goBack();
}
});
}
@Override
public void cancel() {
goBack();
}
private void goBack() {
// TODO - go back to previous page
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/EditActionPresenter.java | Java | asf20 | 4,530 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.ViewImpl;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class ErrorView extends ViewImpl implements ErrorPresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, ErrorView> {
}
@Inject
public ErrorView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/ErrorView.java | Java | asf20 | 566 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.UiHandlers;
import org.dodgybits.shuffle.shared.TaskProxy;
public interface EditEntityUiHandlers extends UiHandlers {
void save(String description, String details);
void cancel();
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/EditEntityUiHandlers.java | Java | asf20 | 266 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.NameToken;
import org.dodgybits.shuffle.gwt.place.NameTokens;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.google.inject.Inject;
import com.google.gwt.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import org.dodgybits.shuffle.gwt.core.MainPresenter;
public class LoginPresenter extends
Presenter<LoginPresenter.MyView, LoginPresenter.MyProxy> {
public interface MyView extends View {
// TODO Put your view methods here
}
@ProxyCodeSplit
@NameToken(NameTokens.login)
public interface MyProxy extends ProxyPlace<LoginPresenter> {
}
@Inject
public LoginPresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy) {
super(eventBus, view, proxy);
}
@Override
protected void revealInParent() {
RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/LoginPresenter.java | Java | asf20 | 1,122 |
package org.dodgybits.shuffle.gwt.core;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent;
import org.dodgybits.shuffle.gwt.place.NameTokens;
public class ErrorPresenter extends
Presenter<ErrorPresenter.MyView, ErrorPresenter.MyProxy> {
public interface MyView extends View {
// TODO Put your view methods here
}
@ProxyCodeSplit
@NameToken(NameTokens.error)
public interface MyProxy extends ProxyPlace<ErrorPresenter> {
}
@Inject
public ErrorPresenter(final EventBus eventBus, final MyView view,
final MyProxy proxy) {
super(eventBus, view, proxy);
}
@Override
protected void revealInParent() {
RevealRootLayoutContentEvent.fire(this, this);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/ErrorPresenter.java | Java | asf20 | 1,063 |
package org.dodgybits.shuffle.gwt.core;
import com.gwtplatform.mvp.client.ViewImpl;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class WelcomeView extends ViewImpl implements WelcomePresenter.MyView {
private final Widget widget;
public interface Binder extends UiBinder<Widget, WelcomeView> {
}
@UiField HTMLPanel mainPanel;
@UiField HTML dateField;
@Inject
public WelcomeView(final Binder binder) {
widget = binder.createAndBindUi(this);
}
@Override
public Widget asWidget() {
return widget;
}
@Override
public void setFormattedDate(String formattedDate) {
dateField.setText(formattedDate);
}
@Override
public void setBackgroundColor(String color) {
mainPanel.getElement().getStyle().setBackgroundColor(color);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/core/WelcomeView.java | Java | asf20 | 1,019 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.gwt;
import org.dodgybits.shuffle.gwt.gin.ClientGinjector;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.CssResource.NotStrict;
import com.gwtplatform.mvp.client.DelayedBindRegistry;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Shuffle implements EntryPoint {
interface GlobalResources extends ClientBundle {
@NotStrict
@Source("../../../../../resources/org/dodgybits/shuffle/gwt/global.css")
CssResource css();
}
private final ClientGinjector ginjector = GWT.create(ClientGinjector.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// Wire the request factory and the event bus
ginjector.getRequestFactory().initialize(ginjector.getEventBus());
// Inject global styles.
GWT.<GlobalResources> create(GlobalResources.class).css()
.ensureInjected();
// This is required for Gwt-Platform proxy's generator
DelayedBindRegistry.bind(ginjector);
ginjector.getPlaceManager().revealCurrentPlace();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/gwt/Shuffle.java | Java | asf20 | 1,807 |
package org.dodgybits.shuffle.server.service;
import org.dodgybits.shuffle.server.model.AppUser;
public class AppUserDao extends ObjectifyDao<AppUser>
{
// Inherit all methods from generic Dao
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/service/AppUserDao.java | Java | asf20 | 198 |
package org.dodgybits.shuffle.server.service;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.Embedded;
import javax.persistence.Transient;
import org.dodgybits.shuffle.server.model.Task;
import org.dodgybits.shuffle.server.model.AppUser;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.web.bindery.requestfactory.server.RequestFactoryServlet;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.googlecode.objectify.util.DAOBase;
/**
* Generic DAO for use with Objectify
*/
public class ObjectifyDao<T> extends DAOBase
{
static final int BAD_MODIFIERS = Modifier.FINAL | Modifier.STATIC
| Modifier.TRANSIENT;
static
{
ObjectifyService.register(Task.class);
ObjectifyService.register(AppUser.class);
}
protected Class<T> clazz;
@SuppressWarnings("unchecked")
public ObjectifyDao()
{
clazz = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public Key<T> put(T entity)
{
return ofy().put(entity);
}
public Map<Key<T>, T> putAll(Iterable<T> entities)
{
return ofy().put(entities);
}
public void delete(T entity)
{
ofy().delete(entity);
}
public void deleteKey(Key<T> entityKey)
{
ofy().delete(entityKey);
}
public void deleteAll(Iterable<T> entities)
{
ofy().delete(entities);
}
public void deleteKeys(Iterable<Key<T>> keys)
{
ofy().delete(keys);
}
public T get(Long id) throws EntityNotFoundException
{
return ofy().get(this.clazz, id);
}
public T get(Key<T> key) throws EntityNotFoundException
{
return ofy().get(key);
}
public Map<Key<T>, T> get(Iterable<Key<T>> keys)
{
return ofy().get(keys);
}
public List<T> listAll()
{
Query<T> q = ofy().query(clazz);
return q.list();
}
/**
* Convenience method to get all objects matching a single property
*
* @param propName
* @param propValue
* @return T matching Object
* @throws TooManyResultsException
*/
public T getByProperty(String propName, Object propValue)
{
Query<T> q = ofy().query(clazz);
q.filter(propName, propValue);
Iterator<T> fetch = q.limit(2).list().iterator();
if (!fetch.hasNext())
{
return null;
}
T obj = fetch.next();
if (fetch.hasNext())
{
throw new RuntimeException(q.toString()
+ " returned too many results");
}
return obj;
}
public List<T> listByProperty(String propName, Object propValue)
{
Query<T> q = ofy().query(clazz);
q.filter(propName, propValue);
return q.list();
}
public List<Key<T>> listKeysByProperty(String propName, Object propValue)
{
Query<T> q = ofy().query(clazz);
q.filter(propName, propValue);
return q.listKeys();
}
public T getByExample(T exampleObj)
{
Query<T> q = buildQueryByExample(exampleObj);
Iterator<T> fetch = q.limit(2).list().iterator();
if (!fetch.hasNext())
{
return null;
}
T obj = fetch.next();
if (fetch.hasNext())
{
throw new RuntimeException(q.toString()
+ " returned too many results");
}
return obj;
}
public List<T> listByExample(T exampleObj)
{
Query<T> queryByExample = buildQueryByExample(exampleObj);
return queryByExample.list();
}
public Key<T> getKey(Long id)
{
return new Key<T>(this.clazz, id);
}
public Key<T> key(T obj)
{
return ObjectifyService.factory().getKey(obj);
}
public List<T> listChildren(Object parent)
{
return ofy().query(clazz).ancestor(parent).list();
}
public List<Key<T>> listChildKeys(Object parent)
{
return ofy().query(clazz).ancestor(parent).listKeys();
}
protected Query<T> buildQueryByExample(T exampleObj)
{
Query<T> q = ofy().query(clazz);
// Add all non-null properties to query filter
for (Field field : clazz.getDeclaredFields())
{
// Ignore transient, embedded, array, and collection properties
if (field.isAnnotationPresent(Transient.class)
|| (field.isAnnotationPresent(Embedded.class))
|| (field.getType().isArray())
|| (field.getType().isArray())
|| (Collection.class.isAssignableFrom(field.getType()))
|| ((field.getModifiers() & BAD_MODIFIERS) != 0))
continue;
field.setAccessible(true);
Object value;
try
{
value = field.get(exampleObj);
} catch (IllegalArgumentException e)
{
throw new RuntimeException(e);
} catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
if (value != null)
{
q.filter(field.getName(), value);
}
}
return q;
}
/*
* Application-specific methods to retrieve items owned by a specific user
*/
public List<T> listAllForUser()
{
Key<AppUser> userKey = new Key<AppUser>(AppUser.class, getCurrentUser()
.getId());
return listByProperty("owner", userKey);
}
private AppUser getCurrentUser()
{
return (AppUser) RequestFactoryServlet.getThreadLocalRequest()
.getAttribute(LoginService.AUTH_USER);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/service/ObjectifyDao.java | Java | asf20 | 5,373 |
package org.dodgybits.shuffle.server.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dodgybits.shuffle.server.model.AppUser;
import org.dodgybits.shuffle.server.servlet.AuthFilter;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
/**
* Server-side class that provides all login-related
* operations. Called only from server code.
*/
public class LoginService
{
public static final String AUTH_USER = "loggedInUser";
public static AppUser login(HttpServletRequest req, HttpServletResponse res)
{
UserService userService = UserServiceFactory.getUserService();
// User is logged into GAE
// Find or add user in our app Datastore
String userEmail = userService.getCurrentUser().getEmail();
AppUser loggedInUser = findUser(userEmail);
if (loggedInUser == null)
{
// Auto-add user
loggedInUser = addUser(userEmail);
}
req.setAttribute(AUTH_USER, loggedInUser);
return loggedInUser;
}
public static AppUser getLoggedInUser()
{
HttpServletRequest req = AuthFilter.getThreadLocalRequest();
return (AppUser)req.getAttribute(AUTH_USER);
}
private static AppUser findUser(String userEmail)
{
AppUserDao userDao = new AppUserDao();
// Query for user by email
return userDao.getByProperty("email", userEmail);
}
private static AppUser addUser(String email)
{
AppUserDao userDao = new AppUserDao();
AppUser newUser = new AppUser(email);
userDao.put(newUser);
return newUser;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/service/LoginService.java | Java | asf20 | 1,563 |
package org.dodgybits.shuffle.server.service;
import java.util.List;
import com.google.appengine.api.datastore.EntityNotFoundException;
import org.dodgybits.shuffle.server.model.AppUser;
import org.dodgybits.shuffle.server.model.Task;
public class TaskDao extends ObjectifyDao<Task> {
@Override
public List<Task> listAll()
{
List<Task> tasks = listAllForUser();
return tasks;
}
/**
* Wraps put() so as not to return a Key, which RequestFactory can't handle
*/
public void save(Task task)
{
AppUser loggedInUser = LoginService.getLoggedInUser();
task.setOwner(loggedInUser);
this.put(task);
}
public Task saveAndReturn(Task task)
{
AppUser loggedInUser = LoginService.getLoggedInUser();
task.setOwner(loggedInUser);
this.put(task);
return task;
}
public void deleteTask(Task task)
{
this.delete(task);
}
public Task findById(Long id)
{
Task task = null;
try {
task = super.get(id);
AppUser loggedInUser = LoginService.getLoggedInUser();
if (!task.getOwner().equals(loggedInUser)) {
// wrong user - bail
task = null;
}
} catch (EntityNotFoundException e) {
// couldn't find task
}
return task;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/service/TaskDao.java | Java | asf20 | 1,403 |
/*
* Copyright 2010 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.
*/
package org.dodgybits.shuffle.server.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dodgybits.shuffle.server.service.LoginService;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
/**
* A servlet filter that handles basic GAE user authentication.
* Based on http://code.google.com/p/google-web-toolkit/source/browse/trunk/samples/expenses/src/main/java/com/google/gwt/sample/gaerequest/server/GaeAuthFilter.java
*/
public class AuthFilter implements Filter
{
private static final ThreadLocal<HttpServletRequest> perThreadRequest =
new ThreadLocal<HttpServletRequest>();
/**
* Returns the thread-local {@link HttpServletRequest}.
*
* @return an {@link HttpServletRequest} instance
*/
public static HttpServletRequest getThreadLocalRequest() {
return perThreadRequest.get();
}
@Override
public void init(FilterConfig config)
{
}
@Override
public void destroy()
{
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException
{
UserService userService = UserServiceFactory.getUserService();
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
perThreadRequest.set(request);
try
{
if (!userService.isUserLoggedIn())
{
// User is not logged in to App Engine so redirect to login page
response.setHeader("login",
userService.createLoginURL(request.getRequestURI()));
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
LoginService.login(request, response);
filterChain.doFilter(request, response);
}
finally {
perThreadRequest.set(null);
}
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/servlet/AuthFilter.java | Java | asf20 | 2,832 |
package org.dodgybits.shuffle.server.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.dodgybits.shuffle.dto.ShuffleProtos;
import org.dodgybits.shuffle.dto.ShuffleProtos.Catalogue;
import org.dodgybits.shuffle.server.model.Task;
import org.dodgybits.shuffle.server.service.TaskDao;
@SuppressWarnings("serial")
public class RestoreBackupServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger(RestoreBackupServlet.class.getName());
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
logger.log(Level.FINE, "Request multipart " + isMultipart);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
try
{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
Catalogue catalogue = Catalogue.parseFrom(stream);
int tasksSaved = saveAll(catalogue);
response.getWriter().println("Saved " + tasksSaved + " actions.");
response.flushBuffer();
}
}
} catch (FileUploadException e) {
throw new ServletException(e);
}
}
private int saveAll(Catalogue catalogue) {
List<ShuffleProtos.Task> protoTasks = catalogue.getTaskList();
List<Task> tasks = new ArrayList<Task>(protoTasks.size());
TaskDao dao = new TaskDao();
for (ShuffleProtos.Task protoTask : protoTasks) {
logger.info("Saving task: " + protoTask.toString());
Task task = toModelTask(protoTask);
dao.save(task);
tasks.add(task);
}
return tasks.size();
}
private Task toModelTask(ShuffleProtos.Task protoTask) {
Task task = new Task();
task.setDescription(protoTask.getDescription());
task.setDetails(protoTask.getDetails());
task.setActive(protoTask.getActive());
task.setComplete(protoTask.getComplete());
task.setCreatedDate(new Date(protoTask.getCreated().getMillis()));
task.setDeleted(protoTask.getDeleted());
task.setModifiedDate(new Date(protoTask.getModified().getMillis()));
task.setOrder(protoTask.getOrder());
return task;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/servlet/RestoreBackupServlet.java | Java | asf20 | 3,762 |
/*
* Copyright 2010 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.
*/
package org.dodgybits.shuffle.server;
import com.google.android.c2dm.server.PMF;
import com.google.appengine.api.datastore.Key;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
/**
* Registration info.
*
* An account may be associated with multiple phones,
* and a phone may be associated with multiple accounts.
*
* registrations lists different phones registered to that account.
*/
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class DeviceInfo {
private static final Logger log =
Logger.getLogger(DeviceInfo.class.getName());
/**
* User-email # device-id
*
* Device-id can be specified by device, default is hash of abs(registration
* id).
*
* user@example.com#1234
*/
@PrimaryKey
@Persistent
private Key key;
/**
* The ID used for sending messages to.
*/
@Persistent
private String deviceRegistrationID;
/**
* Current supported types:
* (default) - ac2dm, regular froyo+ devices using C2DM protocol
*
* New types may be defined - for example for sending to chrome.
*/
@Persistent
private String type;
/**
* For statistics - and to provide hints to the user.
*/
@Persistent
private Date registrationTimestamp;
@Persistent
private Boolean debug;
public DeviceInfo(Key key, String deviceRegistrationID) {
log.info("new DeviceInfo: key=" + key + ", deviceRegistrationId=" + deviceRegistrationID);
this.key = key;
this.deviceRegistrationID = deviceRegistrationID;
this.setRegistrationTimestamp(new Date()); // now
}
public DeviceInfo(Key key) {
log.info("new DeviceInfo: key=" + key);
this.key = key;
}
public Key getKey() {
log.info("DeviceInfo: return key=" + key);
return key;
}
public void setKey(Key key) {
log.info("DeviceInfo: set key=" + key);
this.key = key;
}
// Accessor methods for properties added later (hence can be null)
public String getDeviceRegistrationID() {
log.info("DeviceInfo: return deviceRegistrationID=" + deviceRegistrationID);
return deviceRegistrationID;
}
public void setDeviceRegistrationID(String deviceRegistrationID) {
log.info("DeviceInfo: set deviceRegistrationID=" + deviceRegistrationID);
this.deviceRegistrationID = deviceRegistrationID;
}
public boolean getDebug() {
return (debug != null ? debug.booleanValue() : false);
}
public void setDebug(boolean debug) {
this.debug = new Boolean(debug);
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type != null ? type : "";
}
public void setRegistrationTimestamp(Date registrationTimestamp) {
this.registrationTimestamp = registrationTimestamp;
}
public Date getRegistrationTimestamp() {
return registrationTimestamp;
}
/**
* Helper function - will query all registrations for a user.
*/
@SuppressWarnings("unchecked")
public static List<DeviceInfo> getDeviceInfoForUser(String user) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
// Canonicalize user name
user = user.toLowerCase(Locale.ENGLISH);
Query query = pm.newQuery(DeviceInfo.class);
query.setFilter("key >= '" +
user + "' && key < '" + user + "$'");
List<DeviceInfo> qresult = (List<DeviceInfo>) query.execute();
// Copy to array - we need to close the query
List<DeviceInfo> result = new ArrayList<DeviceInfo>();
for (DeviceInfo di : qresult) {
result.add(di);
}
query.closeAll();
log.info("Return " + result.size() + " devices for user " + user);
return result;
} finally {
pm.close();
}
}
@Override
public String toString() {
return "DeviceInfo[key=" + key + ", deviceRegistrationID="
+ deviceRegistrationID + ", type=" + type
+ ", registrationTimestamp=" + registrationTimestamp + ", debug="
+ debug + "]";
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/DeviceInfo.java | Java | asf20 | 5,164 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.server;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.util.Date;
import java.util.logging.Logger;
public class HelloWorldService {
private static final Logger log = Logger.getLogger(HelloWorldService.class.getName());
public HelloWorldService() {
}
public static String getMessage() {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String message;
if (user == null) {
message = "No one is logged in!\nSent from App Engine at " + new Date();
} else {
message = "Hello, " + user.getEmail() + "!\nSent from App Engine at " + new Date();
}
log.info("Returning message \"" + message + "\"");
return message;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/HelloWorldService.java | Java | asf20 | 1,468 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.server;
import com.google.android.c2dm.server.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
public class RegistrationInfo {
private static final Logger log = Logger.getLogger(RegistrationInfo.class.getName());
private static final int MAX_DEVICES = 5;
String deviceId;
String deviceRegistrationId;
public RegistrationInfo() {
}
public String getAccountName() {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
return user.getEmail();
}
public String getDeviceId() {
return deviceId;
}
public String getDeviceRegistrationId() {
return deviceRegistrationId;
}
public void register() {
log.info("register " + this);
try {
doRegister(getDeviceRegistrationId(), "ac2dm", getDeviceId(), getAccountName());
} catch (Exception e) {
log.info("Got exception in registration: " + e + " - " + e.getMessage());
for (StackTraceElement ste : e.getStackTrace()) {
log.info(ste.toString());
}
}
log.info("Successfully registered");
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public void setDeviceRegistrationId(String deviceRegistrationId) {
this.deviceRegistrationId = deviceRegistrationId;
}
@Override
public String toString() {
return "RegistrationInfo [deviceId=" + deviceId
+ ", deviceRegistrationId=" + deviceRegistrationId + "]";
}
public void unregister() {
log.info("unregister " + this);
try {
doUnregister(getDeviceRegistrationId(), getAccountName());
} catch (Exception e) {
log.info("Got exception in unregistration: " + e + " - " + e.getMessage());
for (StackTraceElement ste : e.getStackTrace()) {
log.info(ste.toString());
}
}
log.info("Successfully unregistered");
}
private void doRegister(String deviceRegistrationId, String deviceType, String deviceId,
String accountName) throws Exception {
log.info("in register: accountName = " + accountName);
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
List<DeviceInfo> registrations = DeviceInfo.getDeviceInfoForUser(accountName);
log.info("got registrations");
if (registrations.size() > MAX_DEVICES) {
log.info("got registrations > MAX_DEVICES");
// we could return an error - but user can't handle it yet.
// we can't let it grow out of bounds.
// TODO: we should also define a 'ping' message and expire/remove
// unused registrations
DeviceInfo oldest = registrations.get(0);
if (oldest.getRegistrationTimestamp() == null) {
pm.deletePersistent(oldest);
} else {
long oldestTime = oldest.getRegistrationTimestamp().getTime();
for (int i = 1; i < registrations.size(); i++) {
if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) {
oldest = registrations.get(i);
oldestTime = oldest.getRegistrationTimestamp().getTime();
}
}
pm.deletePersistent(oldest);
}
}
// Get device if it already exists, else create
String suffix =
(deviceId != null ? "#" + Long.toHexString(Math.abs(deviceId.hashCode())) : "");
log.info("suffix = " + suffix);
Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), accountName + suffix);
log.info("key = " + key);
DeviceInfo device = null;
try {
device = pm.getObjectById(DeviceInfo.class, key);
} catch (JDOObjectNotFoundException e) {
log.info("Caught JDOObjectNotFoundException");
}
if (device == null) {
device = new DeviceInfo(key, deviceRegistrationId);
device.setType(deviceType);
} else {
// update registration id
device.setDeviceRegistrationID(deviceRegistrationId);
device.setRegistrationTimestamp(new Date());
}
pm.makePersistent(device);
return;
} catch (Exception e) {
log.info("Caught exception: " + e);
throw e;
} finally {
pm.close();
}
}
private void doUnregister(String deviceRegistrationID, String accountName) {
log.info("in unregister: accountName = " + accountName);
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
List<DeviceInfo> registrations = DeviceInfo.getDeviceInfoForUser(accountName);
for (int i = 0; i < registrations.size(); i++) {
DeviceInfo deviceInfo = registrations.get(i);
if (deviceInfo.getDeviceRegistrationID().equals(deviceRegistrationID)) {
pm.deletePersistent(deviceInfo);
// Keep looping in case of duplicates
}
}
} catch (JDOObjectNotFoundException e) {
log.warning("User " + accountName + " unknown");
} catch (Exception e) {
log.warning("Error unregistering device: " + e.getMessage());
} finally {
pm.close();
}
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/RegistrationInfo.java | Java | asf20 | 6,023 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.server;
import com.google.web.bindery.requestfactory.server.RequestFactoryServlet;
import com.google.web.bindery.requestfactory.shared.Locator;
public class MessageLocator extends Locator<Message, Void> {
@Override
public Message create(Class<? extends Message> clazz) {
return new Message(RequestFactoryServlet.getThreadLocalRequest().getSession().getServletContext());
}
@Override
public Message find(Class<? extends Message> clazz, Void id) {
throw new UnsupportedOperationException();
}
@Override
public Class<Message> getDomainType() {
throw new UnsupportedOperationException();
}
@Override
public Void getId(Message domainObject) {
throw new UnsupportedOperationException();
}
@Override
public Class<Void> getIdType() {
throw new UnsupportedOperationException();
}
@Override
public Object getVersion(Message domainObject) {
throw new UnsupportedOperationException();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/MessageLocator.java | Java | asf20 | 1,571 |
package org.dodgybits.shuffle.server.locator;
public class TaskLocator extends ObjectifyLocator {
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/locator/TaskLocator.java | Java | asf20 | 107 |
package org.dodgybits.shuffle.server.locator;
import com.google.web.bindery.requestfactory.shared.Locator;
import com.googlecode.objectify.util.DAOBase;
import org.dodgybits.shuffle.server.model.DatastoreObject;
/**
* Generic @Locator for objects that extend DatastoreObject
*/
public class ObjectifyLocator extends Locator<DatastoreObject, Long> {
@Override
public DatastoreObject create(Class<? extends DatastoreObject> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public DatastoreObject find(Class<? extends DatastoreObject> clazz, Long id) {
DAOBase daoBase = new DAOBase();
return daoBase.ofy().find(clazz, id);
}
@Override
public Class<DatastoreObject> getDomainType() {
// Never called
return null;
}
@Override
public Long getId(DatastoreObject domainObject) {
return domainObject.getId();
}
@Override
public Class<Long> getIdType() {
return Long.class;
}
@Override
public Object getVersion(DatastoreObject domainObject) {
return domainObject.getVersion();
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/locator/ObjectifyLocator.java | Java | asf20 | 1,223 |
package org.dodgybits.shuffle.server.locator;
import com.google.web.bindery.requestfactory.shared.ServiceLocator;
/**
* Generic locator service that can be referenced in the @Service annotation
* for any RequestFactory service stub
*/
public class DaoServiceLocator implements ServiceLocator {
@Override
public Object getInstance(Class<?> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/locator/DaoServiceLocator.java | Java | asf20 | 552 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.server;
import com.google.android.c2dm.server.C2DMessaging;
import com.google.android.c2dm.server.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.util.List;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletContext;
/**
* Send a message using C2DM.
*/
public class SendMessage {
private static final Logger log = Logger.getLogger(SendMessage.class.getName());
public static String sendMessage(ServletContext context, String recipient, String message) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String sender = "nobody";
if (user != null) {
sender = user.getEmail();
}
log.info("sendMessage: sender = " + sender);
log.info("sendMessage: recipient = " + recipient);
log.info("sendMessage: message = " + message);
// ok = we sent to at least one device.
boolean ok = false;
// Send push message to phone
C2DMessaging push = C2DMessaging.get(context);
boolean res = false;
String collapseKey = "" + message.hashCode();
// delete will fail if the pm is different than the one used to
// load the object - we must close the object when we're done
List<DeviceInfo> registrations = null;
registrations = DeviceInfo.getDeviceInfoForUser(recipient);
log.info("sendMessage: got " + registrations.size() + " registrations");
// Deal with upgrades and multi-device:
// If user has one device with an old version and few new ones -
// the old registration will be deleted.
if (registrations.size() > 1) {
// Make sure there is no 'bare' registration
// Keys are sorted - check the first
DeviceInfo first = registrations.get(0);
Key oldKey = first.getKey();
if (oldKey.toString().indexOf("#") < 0) {
// multiple devices, first is old-style.
registrations.remove(0); // don't send to it
pm.deletePersistent(first);
}
}
int numSendAttempts = 0;
for (DeviceInfo deviceInfo : registrations) {
if (!"ac2dm".equals(deviceInfo.getType())) {
continue; // user-specified device type
}
res = doSendViaC2dm(message, sender, push, collapseKey, deviceInfo);
numSendAttempts++;
if (res) {
ok = true;
}
}
if (ok) {
return "Success: Message sent";
} else if (numSendAttempts == 0) {
return "Failure: User " + recipient + " not registered";
} else {
return "Failure: Unable to send message";
}
} catch (Exception e) {
return "Failure: Got exception " + e;
} finally {
pm.close();
}
}
private static boolean doSendViaC2dm(String message, String sender, C2DMessaging push,
String collapseKey, DeviceInfo deviceInfo) {
// Trim message if needed.
if (message.length() > 1000) {
message = message.substring(0, 1000) + "[...]";
}
return push.sendNoRetry(deviceInfo.getDeviceRegistrationID(), collapseKey, "sender", sender,
"message", message);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/SendMessage.java | Java | asf20 | 4,042 |
/*
* Copyright 2011 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.
*/
package org.dodgybits.shuffle.server;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
public class Message {
private static final Logger log = Logger.getLogger(Message.class.getName());
private final ServletContext context;
String recipient;
String message;
public Message(ServletContext context) {
this.context = context;
}
public String getRecipient() {
return recipient;
}
public String getMessage() {
return message;
}
public String send() {
log.info("send " + this);
try {
return SendMessage.sendMessage(context, recipient, message);
} catch (Exception e) {
return "Failure: Got exception in send: " + e.getMessage();
}
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "Message [recipient=" + recipient + ", message=" + message + "]";
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/Message.java | Java | asf20 | 1,603 |
package org.dodgybits.shuffle.server.model;
import javax.persistence.Id;
import javax.persistence.PrePersist;
public class DatastoreObject
{
@Id
private Long id;
private Integer version = 0;
/**
* Auto-increment version # whenever persisted
*/
@PrePersist
void onPersist()
{
this.version++;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public Integer getVersion()
{
return version;
}
public void setVersion(Integer version)
{
this.version = version;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/model/DatastoreObject.java | Java | asf20 | 533 |
package org.dodgybits.shuffle.server.model;
import java.util.Date;
import org.dodgybits.shuffle.server.service.AppUserDao;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
@Entity
public class Task extends DatastoreObject {
String description;
String details;
Date createdDate;
Date modifiedDate;
boolean active = true;
boolean deleted;
// 0-indexed order within a project.
int order;
boolean complete;
private Key<AppUser> owner;
public final String getDescription() {
return description;
}
public final void setDescription(String description) {
this.description = description;
}
public final String getDetails() {
return details;
}
public final void setDetails(String details) {
this.details = details;
}
public final Date getCreatedDate() {
return createdDate;
}
public final void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public final Date getModifiedDate() {
return modifiedDate;
}
public final void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public final boolean isActive() {
return active;
}
public final void setActive(boolean active) {
this.active = active;
}
public final boolean isDeleted() {
return deleted;
}
public final void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public final int getOrder() {
return order;
}
public final void setOrder(int order) {
this.order = order;
}
public final boolean isComplete() {
return complete;
}
public final void setComplete(boolean complete) {
this.complete = complete;
}
public AppUser getOwner()
{
try
{
return new AppUserDao().get(owner);
} catch (EntityNotFoundException e)
{
throw new RuntimeException(e);
}
}
public void setOwner(AppUser owner)
{
this.owner = new AppUserDao().key(owner);
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/model/Task.java | Java | asf20 | 2,241 |
package org.dodgybits.shuffle.server.model;
import com.googlecode.objectify.annotation.Entity;
/**
* An application user, named with a prefix to avoid confusion with GAE User type
*/
@Entity
public class AppUser extends DatastoreObject
{
private String email;
public AppUser()
{
// No-arg constructor required by Objectify
}
public AppUser(String userEmail)
{
this.email = userEmail;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
}
| 1012607376-daihanlong | shuffle-app-engine/src/main/java/org/dodgybits/shuffle/server/model/AppUser.java | Java | asf20 | 520 |
#!/bin/sh
# Create a backup tar gzip file of the cwd with the date appended
# located in the parent directory.
FILENAME=../`pwd|xargs basename`-`date -j "+%Y-%m-%d"`.tgz
echo Will create $FILENAME
tar cfz $FILENAME .
echo Done.
| 1012607376-daihanlong | createBackup.sh | Shell | asf20 | 232 |
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/WEB-INF/facelets/template.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core">
<ui:param name="title" value="View Cart"/>
<ui:define name="form">
<h:form>
<p>
<h:commandButton value="View Products" action="onViewProducts"/>
<h:commandButton value="Empty Shopping Cart and View Products" action="#{viewCartControllerBean.emptyCart()}"/>
</p>
</h:form>
<h:form>
<p>
<p:dataTable var="product" value="#{viewCartControllerBean.productsInCart}">
<p:column parser="number" sortBy="#{product.id}">
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:outputText value="#{product.id}" />
</p:column>
<p:column sortBy="#{product.cat}">
<f:facet name="header">
<h:outputText value="Category" />
</f:facet>
<h:outputText value="#{product.cat}" />
</p:column>
<p:column sortBy="#{product.name}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{product.name}" />
</p:column>
<p:column parser="number" sortBy="#{product.price}">
<f:facet name="header">
<h:outputText value="Price" />
</f:facet>
<h:outputText value="#{product.price}" />
</p:column>
<p:column>
<p:commandButton value="Remove" actionListener="#{shoppingCartModelBean.removeProduct(product)}" update="@form" />
</p:column>
</p:dataTable>
</p>
<p>The number of items currently in the shopping cart: #{shoppingCartModelBean.getNumberOfProducts()}</p>
</h:form>
</ui:define>
<ui:param name="h1" value="View Cart"/>
</ui:composition> | 076-jsfproducts | trunk/jsfproducts.nbp/src/main/webapp/viewCart.xhtml | HTML | gpl2 | 2,412 |
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/WEB-INF/facelets/template.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<ui:param name="title" value="Add product"/>
<ui:define name="form">
<h:form>
<p:panel id="namePanel">
<h:panelGrid id="grid" columns="3">
<h:outputLabel for="productName" value="Product Name:"/>
<h:inputText id="productName" value="#{addProductControllerBean.product.name}"
required="true" requiredMessage="Can't be empty" >
<f:validateLength minimum="3" />
<f:ajax event="blur" render="pMsg" />
</h:inputText>
<p:message id="pMsg" for="productName" display="text"/>
<h:outputLabel for="productCategory" value="Product Category:"/>
<h:inputText id="productCategory" value="#{addProductControllerBean.product.cat}"/>
<p></p>
<h:outputLabel for="productPrice" value="Price:"/>
<h:inputText id="productPrice" value="#{addProductControllerBean.product.price}"
required="true" requiredMessage="Can't be empty"
validatorMessage="Must be 1-8 chars">
<f:validateDoubleRange for="productPrice" minimum="0">
<f:ajax event="blur" render="prMsg" />
</f:validateDoubleRange>
</h:inputText>
<p:message id="prMsg" for="productPrice" display="text" showSummary="true" showDetail="false" />
</h:panelGrid>
</p:panel>
<p>
<p:commandButton value="Add Product" id="submit" update="@namePanel" ajax="false"
action="#{addProductControllerBean.addProduct()}" />
</p>
</h:form>
</ui:define>
<ui:param name="h1" value="Add product"/>
</ui:composition> | 076-jsfproducts | trunk/jsfproducts.nbp/src/main/webapp/addProduct.xhtml | HTML | gpl2 | 2,329 |
body {
text-align: center;
}
table {
text-align: left;
margin-left: auto;
margin-right: auto;
}
.ui-message-error-detail,
.ui-message-error-summary {
font-size: smaller;
font-weight: 800;
}
.ui-datatable {
background: black;
width: 50em;
margin-left: auto;
margin-right: auto;
}
.ui-datatable table {
width: 100%;
}
.ui-datatable .ui-button {
}
.ui-datatable .ui-button:hover {
background: #D8D8D8;
}
.ui-panel {
width: 50em;
margin-left: auto;
margin-right: auto;
}
#footer {
color: sienna;
font-size: smaller;
} | 076-jsfproducts | trunk/jsfproducts.nbp/src/main/webapp/resources/css/styles.css | CSS | gpl2 | 594 |
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/WEB-INF/facelets/template.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core">
<ui:param name="title" value="View Products"/>
<ui:define name="form">
<h:form>
<p>
<h:commandButton value="Add Product" action="onViewAddProduct"/>
<h:commandButton value="View Cart" action="onViewCart"/>
<h:commandButton value="Empty Shopping Cart" action="#{viewProductsControllerBean.emptyCart()}"/>
</p>
</h:form>
<h:form>
<p>
<p:dataTable var="product" value="#{viewProductsControllerBean.products}">
<p:column parser="number" sortBy="#{product.id}">
<f:facet name="header">
<h:outputText value="ID" />
</f:facet>
<h:outputText value="#{product.id}" />
</p:column>
<p:column sortBy="#{product.cat}">
<f:facet name="header">
<h:outputText value="Category" />
</f:facet>
<h:outputText value="#{product.cat}" />
</p:column>
<p:column sortBy="#{product.name}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{product.name}" />
</p:column>
<p:column parser="number" sortBy="#{product.price}">
<f:facet name="header">
<h:outputText value="Price" />
</f:facet>
<h:outputText value="#{product.price}" />
</p:column>
<p:column>
<p:commandButton value="Remove" actionListener="#{viewProductsControllerBean.removeProduct(product)}" update="@form" />
</p:column>
<p:column>
<p:commandButton value="Add to cart" actionListener="#{viewProductsControllerBean.addToCart(product)}" update="@form"/>
</p:column>
</p:dataTable>
</p>
<p>The number of items currently in the shopping cart: #{shoppingCartModelBean.getNumberOfProducts()}</p>
</h:form>
</ui:define>
<ui:param name="h1" value="View Products"/>
</ui:composition> | 076-jsfproducts | trunk/jsfproducts.nbp/src/main/webapp/viewProducts.xhtml | HTML | gpl2 | 2,659 |
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:util="http://java.sun.com/jsf/composite/components/util">
<p>Hej!!!</p>
<p>?????+</p>
</ui> | 076-jsfproducts | trunk/jsfproducts.nbp/src/main/webapp/contents/cont.xhtml | HTML | gpl2 | 345 |
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:outputStylesheet library="css" name="styles.css" />
<h:head>
<title>#{title}</title>
</h:head>
<h:body>
<div id="header">
<h:graphicImage id="shop"
alt="shop"
url="http://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Shop.svg/109px-Shop.svg.png">
</h:graphicImage>
</div>
<div id="contents">
<h1>#{h1}</h1>
<ui:insert name="form"/>
</div>
<div id="footer">
<h:form>
<h:commandButton value="Update footer">
<f:ajax event="click" render="time"></f:ajax>
</h:commandButton>
<p>
<h:outputText id="time" value="#{dateTimeSupportBean.getCurrentDateTime()}"></h:outputText>
</p>
</h:form>
</div>
</h:body>
</html>
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/webapp/WEB-INF/facelets/template.xhtml | HTML | gpl2 | 1,295 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author Daniel
*/
@Entity
@Table(name = "PRODUCT")
@NamedQueries({
@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Size(max = 255)
@Column(name = "CAT")
private String cat;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "PRICE")
private Double price;
@Size(max = 255)
@Column(name = "NAME")
private String name;
public Product() {
}
public Product(long id, String name, String cat, double price){
this.id = id;
this.name = name;
this.cat = cat;
this.price = price;
}
public Product(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCat() {
return cat;
}
public void setCat(String cat) {
this.cat = cat;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Product)) {
return false;
}
Product other = (Product) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "edu.chl.tdaniel.jpa5.Product[ id=" + id + " ]";
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/Product.java | Java | gpl2 | 2,789 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts.controllerbeans;
import edu.chl.cid.jsfproducts.Product;
import edu.chl.cid.jsfproducts.ProductJpaCtrl;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
/**
*
* @author Mikey
*/
@ManagedBean
public class AddProductControllerBean {
@EJB
private ProductJpaCtrl productJpaCtrl;
private Product product = new Product();
/** Creates a new instance of AddProductControllerBean */
public AddProductControllerBean() {
}
public String addProduct(){
System.out.println("Addproduct anrooped! "+product.getName()+", "+product.getCat()+", "+product.getPrice());
product = productJpaCtrl.create(product);
return "onAddProduct";
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/controllerbeans/AddProductControllerBean.java | Java | gpl2 | 997 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts.controllerbeans;
import edu.chl.cid.jsfproducts.NonexistentEntityException;
import edu.chl.cid.jsfproducts.Product;
import edu.chl.cid.jsfproducts.ProductJpaCtrl;
import edu.chl.cid.jsfproducts.modelbeans.ShoppingCartModelBean;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
/**
*
* @author Mikey
*/
@ManagedBean
@ViewScoped
public class ViewProductsControllerBean {
@EJB
private ProductJpaCtrl productJpaCtrl;
@ManagedProperty("#{shoppingCartModelBean}")
private ShoppingCartModelBean cart;
/** Creates a new instance of ViewProductsControllerBean */
public ViewProductsControllerBean() {
}
public List<Product> getProducts(){
return productJpaCtrl.findEntities();
}
public ShoppingCartModelBean getCart() {
return cart;
}
public void setCart(ShoppingCartModelBean cart) {
this.cart = cart;
}
public void addToCart(Product p) {
cart.addProduct(p);
}
public void removeProduct(Product product) throws NonexistentEntityException {
cart.removeProducts(product);
productJpaCtrl.destroy(product.getId());
}
public String emptyCart(){
((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).invalidate();
return "onViewProducts";
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/controllerbeans/ViewProductsControllerBean.java | Java | gpl2 | 1,705 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts.controllerbeans;
import edu.chl.cid.jsfproducts.Product;
import edu.chl.cid.jsfproducts.modelbeans.ShoppingCartModelBean;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author Mikey
*/
@ManagedBean
@ViewScoped
public class ViewCartControllerBean {
@ManagedProperty("#{shoppingCartModelBean}")
private ShoppingCartModelBean cart;
/** Creates a new instance of ViewCartControllerBean */
public ViewCartControllerBean() {
}
public List<Product> getProductsInCart() {
return cart.getProducts();
}
public ShoppingCartModelBean getCart() {
return cart;
}
public void setCart(ShoppingCartModelBean cart) {
this.cart = cart;
}
public String emptyCart() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().
getExternalContext().getRequest();
request.getSession().invalidate();
return "onEmptyCart";
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/controllerbeans/ViewCartControllerBean.java | Java | gpl2 | 1,303 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
/**
* A lot to do here Use supplied exceptions if method should throw!!
* @author hajo
*/
@Stateless
public class ProductJpaCtrl {
@PersistenceContext(unitName="webshop_pu")
private EntityManager em;
public Product create(Product t) {
System.out.println("Persisting : "+t.toString());
em.persist(t);
return t;
}
public void destroy(Long id) throws NonexistentEntityException {
Product p = em.getReference(Product.class, id);
p.getId();
em.remove(p);
}
public void edit(Product t) throws NonexistentEntityException, Exception {
try {
em.getTransaction().begin();
t = em.merge(t);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = t.getId();
if (findEntity(id) == null) {
throw new NonexistentEntityException("The product with id "
+ id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public Product findEntity(Long id) {
try {
return em.find(Product.class, id);
} finally {
em.close();
}
}
public List<Product> findEntities() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Product.class));
return em.createQuery(cq).getResultList();
}
public List<Product> findEntities(int maxResults, int firstResult) {
Query q = em.createQuery("select p from Product p", Product.class);
List l = q.getResultList();
int begin = (0 <= firstResult && firstResult < l.size() ? firstResult : l.size());
int end = (firstResult + maxResults < l.size() ? firstResult + maxResults : l.size());
return q.getResultList().subList(begin, end);
}
public int getEntityCount() {
return em.createQuery("select count(p) from Product p", Integer.class).getSingleResult();
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/ProductJpaCtrl.java | Java | gpl2 | 2,761 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author hajo
*/
public interface IJpaCtrl<T> {
void create(T t);
void destroy(Long id) throws NonexistentEntityException;
void edit(T t) throws NonexistentEntityException, Exception;
T findEntity(Long id);
List<T> findEntities();
List<T> findEntities(int maxResults, int firstResult);
EntityManager getEntityManager();
int getEntityCount();
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/IJpaCtrl.java | Java | gpl2 | 597 |
package edu.chl.cid.jsfproducts;
public class NonexistentEntityException extends Exception {
public NonexistentEntityException(String message, Throwable cause) {
super(message, cause);
}
public NonexistentEntityException(String message) {
super(message);
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/NonexistentEntityException.java | Java | gpl2 | 292 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts.modelbeans;
import edu.chl.cid.jsfproducts.Product;
import edu.chl.cid.jsfproducts.Product;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* @author Mikey
*/
@ManagedBean
@SessionScoped
public class ShoppingCartModelBean {
private ArrayList<Product> products;
public ArrayList<Product> getProducts() {
return products;
}
public void addProduct(Product product) {
products.add(product);
}
public void removeProduct(Product p){
products.remove(p);
}
public void removeProducts(Product p) {
products.removeAll(Arrays.asList(new Product[]{p}));
}
public int getNumberOfProducts() {
return products.size();
}
/** Creates a new instance of ShoppingCartModelBean */
public ShoppingCartModelBean() {
products = new ArrayList<Product>();
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/modelbeans/ShoppingCartModelBean.java | Java | gpl2 | 1,101 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chl.cid.jsfproducts.supportbeans;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;
/**
*
* @author Mikey
*/
@ManagedBean
@ApplicationScoped
public class DateTimeSupportBean {
/** Creates a new instance of DateTimeSupportBean */
public DateTimeSupportBean() {
}
public String getCurrentDateTime() {
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(currentDate.getTime());
}
}
| 076-jsfproducts | trunk/jsfproducts.nbp/src/main/java/edu/chl/cid/jsfproducts/supportbeans/DateTimeSupportBean.java | Java | gpl2 | 730 |
'''
Created on 21-03-2011
@author: maciek
'''
def formatString(format, **kwargs):
'''
'''
if not format: return ''
for arg in kwargs.keys():
format = format.replace("{" + arg + "}", "##" + arg + "##")
format = format.replace ("{", "{{")
format = format.replace("}", "}}")
for arg in kwargs.keys():
format = format.replace("##" + arg + "##", "{" + arg + "}")
res = format.format(**kwargs)
res = res.replace("{{", "{")
res = res.replace("}}", "}")
return res | 0812398-clonetreeview | Android-OTA/formater.py | Python | bsd | 530 |
'''
Created on 21-03-2011
@author: maciek
'''
from IndexGenerator import IndexGenerator
from optparse import OptionParser
import os
import tempfile
import shutil
import logging
logging.basicConfig(level = logging.DEBUG)
parser = OptionParser()
parser.add_option('-n', '--app-name', action='store', dest='appName', help='aplication name')
parser.add_option('-u', '--release-urls', action='store', dest='releaseUrls', help='URLs of download files - as coma separated list of entrires')
parser.add_option('-d', '--destination-directory', action='store', dest='otaAppDir', help='Directory where OTA files are created')
parser.add_option('-v', '--version', action='store', dest='version', help='Version of the application')
parser.add_option('-r', '--releases', action='store', dest='releases', help='Release names of the application')
parser.add_option('-R', '--release-notes', action='store', dest='releaseNotes', help='Release notes of the application (in txt2tags format)')
parser.add_option('-D', '--description', action='store', dest='description', help='Description of the application (in txt2tags format)')
(options, args) = parser.parse_args()
if options.appName == None:
parser.error("Please specify the appName.")
elif options.releaseUrls == None:
parser.error("Please specify releaseUrls")
elif options.otaAppDir == None:
parser.error("Please specify destination directory")
elif options.version == None:
parser.error("Please specify version")
elif options.releases == None:
parser.error("Please specify releases")
elif options.releaseNotes == None:
parser.error("Please specify releaseNotes")
elif options.description == None:
parser.error("Please specify description")
appName = options.appName
releaseUrls = options.releaseUrls
otaAppDir = options.otaAppDir
version = options.version
releases = options.releases
releaseNotes = options.releaseNotes
description = options.description
def findIconFilename():
iconPath = "res/drawable-hdpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable-mdpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable-ldpi/icon.png"
if not os.path.exists(iconPath):
iconPath = "res/drawable/icon.png"
logging.debug("IconPath: "+iconPath)
return iconPath
def createOTApackage():
'''
crates all needed files in tmp dir
'''
releaseNotesContent = open(releaseNotes).read()
descriptionContent = open(description).read()
indexGenerator = IndexGenerator(appName, releaseUrls, releaseNotesContent, descriptionContent, version, releases)
index = indexGenerator.get();
tempIndexFile = tempfile.TemporaryFile()
tempIndexFile.write(index)
tempIndexFile.flush()
tempIndexFile.seek(0)
return tempIndexFile
tempIndexFile = createOTApackage()
if not os.path.isdir(otaAppDir):
logging.debug("creating dir: "+otaAppDir)
os.mkdir(otaAppDir)
else:
logging.warning("dir: "+otaAppDir+" exists")
indexFile = open(os.path.join(otaAppDir,"index.html"),'w')
shutil.copyfileobj(tempIndexFile, indexFile)
srcIconFileName = findIconFilename()
disIconFileName = os.path.join(otaAppDir,"Icon.png")
shutil.copy(srcIconFileName,disIconFileName)
| 0812398-clonetreeview | Android-OTA/CreateOTA.py | Python | bsd | 3,230 |
'''
Created on 21-03-2011
@author: maciek
'''
from formater import formatString
import os
class IndexGenerator(object):
'''
Generates Index.html for iOS app OTA distribution
'''
basePath = os.path.dirname(__file__)
templateFile = os.path.join(basePath,"templates/index.tmpl")
releaseUrls = ""
appName = ""
changeLog = ""
description = ""
version = ""
release = ""
def __init__(self,appName, releaseUrls, changeLog, description, version, releases):
'''
Constructor
'''
self.appName = appName
self.releaseUrls = releaseUrls
self.changeLog = changeLog
self.description = description
self.version = version
self.releases = releases
def get(self):
'''
returns index.html source code from template file
'''
urlList = self.releaseUrls.split(",")
releaseList = self.releases.split(",")
generatedHtml=""
count=0;
for release in releaseList:
generatedHtml += " <li>\n"
generatedHtml += " <h3><a href=\"javascript:load('" + urlList[count] + "')\">" + release + "</a></h3>\n"
generatedHtml += " </li>\n"
count += 1
template = open(self.templateFile).read()
index = formatString(template, downloads=generatedHtml,
changeLog=self.changeLog,
appName=self.appName,
description=self.description,
version = self.version);
return index | 0812398-clonetreeview | Android-OTA/IndexGenerator.py | Python | bsd | 1,655 |
package pl.polidea.treeview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* Tree view, expandable multi-level.
*
* <pre>
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background
* attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background
* </pre>
*/
public class TreeViewList extends ListView {
private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed;
private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded;
private static final int DEFAULT_INDENT = 0;
private static final int DEFAULT_GRAVITY = Gravity.LEFT
| Gravity.CENTER_VERTICAL;
private Drawable expandedDrawable;
private Drawable collapsedDrawable;
private Drawable rowBackgroundDrawable;
private Drawable indicatorBackgroundDrawable;
private int indentWidth = 0;
private int indicatorGravity = 0;
private AbstractTreeViewAdapter< ? > treeAdapter;
private boolean collapsible;
private boolean handleTrackballPress;
public TreeViewList(final Context context, final AttributeSet attrs) {
this(context, attrs, R.style.treeViewListStyle);
}
public TreeViewList(final Context context) {
this(context, null);
}
public TreeViewList(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
parseAttributes(context, attrs);
}
private void parseAttributes(final Context context, final AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TreeViewList);
expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded);
if (expandedDrawable == null) {
expandedDrawable = context.getResources().getDrawable(
DEFAULT_EXPANDED_RESOURCE);
}
collapsedDrawable = a
.getDrawable(R.styleable.TreeViewList_src_collapsed);
if (collapsedDrawable == null) {
collapsedDrawable = context.getResources().getDrawable(
DEFAULT_COLLAPSED_RESOURCE);
}
indentWidth = a.getDimensionPixelSize(
R.styleable.TreeViewList_indent_width, DEFAULT_INDENT);
indicatorGravity = a.getInteger(
R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY);
indicatorBackgroundDrawable = a
.getDrawable(R.styleable.TreeViewList_indicator_background);
rowBackgroundDrawable = a
.getDrawable(R.styleable.TreeViewList_row_background);
collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true);
handleTrackballPress = a.getBoolean(
R.styleable.TreeViewList_handle_trackball_press, true);
}
@Override
public void setAdapter(final ListAdapter adapter) {
if (!(adapter instanceof AbstractTreeViewAdapter)) {
throw new TreeConfigurationException(
"The adapter is not of TreeViewAdapter type");
}
treeAdapter = (AbstractTreeViewAdapter< ? >) adapter;
syncAdapter();
super.setAdapter(treeAdapter);
}
private void syncAdapter() {
treeAdapter.setCollapsedDrawable(collapsedDrawable);
treeAdapter.setExpandedDrawable(expandedDrawable);
treeAdapter.setIndicatorGravity(indicatorGravity);
treeAdapter.setIndentWidth(indentWidth);
treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable);
treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable);
treeAdapter.setCollapsible(collapsible);
if (handleTrackballPress) {
setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(final AdapterView< ? > parent,
final View view, final int position, final long id) {
treeAdapter.handleItemClick(view, view.getTag());
}
});
} else {
setOnClickListener(null);
}
}
public void setExpandedDrawable(final Drawable expandedDrawable) {
this.expandedDrawable = expandedDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setCollapsedDrawable(final Drawable collapsedDrawable) {
this.collapsedDrawable = collapsedDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) {
this.rowBackgroundDrawable = rowBackgroundDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setIndicatorBackgroundDrawable(
final Drawable indicatorBackgroundDrawable) {
this.indicatorBackgroundDrawable = indicatorBackgroundDrawable;
syncAdapter();
treeAdapter.refresh();
}
public void setIndentWidth(final int indentWidth) {
this.indentWidth = indentWidth;
syncAdapter();
treeAdapter.refresh();
}
public void setIndicatorGravity(final int indicatorGravity) {
this.indicatorGravity = indicatorGravity;
syncAdapter();
treeAdapter.refresh();
}
public void setCollapsible(final boolean collapsible) {
this.collapsible = collapsible;
syncAdapter();
treeAdapter.refresh();
}
public void setHandleTrackballPress(final boolean handleTrackballPress) {
this.handleTrackballPress = handleTrackballPress;
syncAdapter();
treeAdapter.refresh();
}
public Drawable getExpandedDrawable() {
return expandedDrawable;
}
public Drawable getCollapsedDrawable() {
return collapsedDrawable;
}
public Drawable getRowBackgroundDrawable() {
return rowBackgroundDrawable;
}
public Drawable getIndicatorBackgroundDrawable() {
return indicatorBackgroundDrawable;
}
public int getIndentWidth() {
return indentWidth;
}
public int getIndicatorGravity() {
return indicatorGravity;
}
public boolean isCollapsible() {
return collapsible;
}
public boolean isHandleTrackballPress() {
return handleTrackballPress;
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/TreeViewList.java | Java | bsd | 6,990 |
package pl.polidea.treeview;
import android.util.Log;
/**
* Allows to build tree easily in sequential mode (you have to know levels of
* all the tree elements upfront). You should rather use this class rather than
* manager if you build initial tree from some external data source.
*
* @param <T>
*/
public class TreeBuilder<T> {
private static final String TAG = TreeBuilder.class.getSimpleName();
private final TreeStateManager<T> manager;
private T lastAddedId = null;
private int lastLevel = -1;
public TreeBuilder(final TreeStateManager<T> manager) {
this.manager = manager;
}
public void clear() {
manager.clear();
}
/**
* Adds new relation to existing tree. Child is set as the last child of the
* parent node. Parent has to already exist in the tree, child cannot yet
* exist. This method is mostly useful in case you add entries layer by
* layer - i.e. first top level entries, then children for all parents, then
* grand-children and so on.
*
* @param parent
* parent id
* @param child
* child id
*/
public synchronized void addRelation(final T parent, final T child) {
Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child);
manager.addAfterChild(parent, child, null);
lastAddedId = child;
lastLevel = manager.getLevel(child);
}
/**
* Adds sequentially new node. Using this method is the simplest way of
* building tree - if you have all the elements in the sequence as they
* should be displayed in fully-expanded tree. You can combine it with add
* relation - for example you can add information about few levels using
* {@link addRelation} and then after the right level is added as parent,
* you can continue adding them using sequential operation.
*
* @param id
* id of the node
* @param level
* its level
*/
public synchronized void sequentiallyAddNextNode(final T id, final int level) {
Log.d(TAG, "Adding sequentiall node " + id + " at level " + level);
if (lastAddedId == null) {
addNodeToParentOneLevelDown(null, id, level);
} else {
if (level <= lastLevel) {
final T parent = findParentAtLevel(lastAddedId, level - 1);
addNodeToParentOneLevelDown(parent, id, level);
} else {
addNodeToParentOneLevelDown(lastAddedId, id, level);
}
}
}
/**
* Find parent of the node at the level specified.
*
* @param node
* node from which we start
* @param levelToFind
* level which we are looking for
* @return the node found (null if it is topmost node).
*/
private T findParentAtLevel(final T node, final int levelToFind) {
T parent = manager.getParent(node);
while (parent != null) {
if (manager.getLevel(parent) == levelToFind) {
break;
}
parent = manager.getParent(parent);
}
return parent;
}
/**
* Adds note to parent at the level specified. But it verifies that the
* level is one level down than the parent!
*
* @param parent
* parent parent
* @param id
* new node id
* @param level
* should always be parent's level + 1
*/
private void addNodeToParentOneLevelDown(final T parent, final T id,
final int level) {
if (parent == null && level != 0) {
throw new TreeConfigurationException("Trying to add new id " + id
+ " to top level with level != 0 (" + level + ")");
}
if (parent != null && manager.getLevel(parent) != level - 1) {
throw new TreeConfigurationException("Trying to add new id " + id
+ " <" + level + "> to " + parent + " <"
+ manager.getLevel(parent)
+ ">. The difference in levels up is bigger than 1.");
}
manager.addAfterChild(parent, id, null);
setLastAdded(id, level);
}
private void setLastAdded(final T id, final int level) {
lastAddedId = id;
lastLevel = level;
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/TreeBuilder.java | Java | bsd | 4,374 |
package pl.polidea.treeview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.database.DataSetObserver;
import android.util.Log;
/**
* In-memory manager of tree state.
*
* @param <T>
* type of identifier
*/
public class InMemoryTreeStateManager<T> implements TreeStateManager<T> {
private static final String TAG = InMemoryTreeStateManager.class
.getSimpleName();
private static final long serialVersionUID = 1L;
private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>();
private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>(
null, null, -1, true);
private transient List<T> visibleListCache = null; // lasy initialised
private transient List<T> unmodifiableVisibleList = null;
private boolean visibleByDefault = true;
private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>();
private synchronized void internalDataSetChanged() {
visibleListCache = null;
unmodifiableVisibleList = null;
for (final DataSetObserver observer : observers) {
observer.onChanged();
}
}
/**
* If true new nodes are visible by default.
*
* @param visibleByDefault
* if true, then newly added nodes are expanded by default
*/
public void setVisibleByDefault(final boolean visibleByDefault) {
this.visibleByDefault = visibleByDefault;
}
private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) {
if (id == null) {
throw new NodeNotInTreeException("(null)");
}
final InMemoryTreeNode<T> node = allNodes.get(id);
if (node == null) {
throw new NodeNotInTreeException(id.toString());
}
return node;
}
private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) {
if (id == null) {
return topSentinel;
}
return getNodeFromTreeOrThrow(id);
}
private void expectNodeNotInTreeYet(final T id) {
final InMemoryTreeNode<T> node = allNodes.get(id);
if (node != null) {
throw new NodeAlreadyInTreeException(id.toString(), node.toString());
}
}
@Override
public synchronized TreeNodeInfo<T> getNodeInfo(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id);
final List<InMemoryTreeNode<T>> children = node.getChildren();
boolean expanded = false;
if (!children.isEmpty() && children.get(0).isVisible()) {
expanded = true;
}
return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(),
node.isVisible(), expanded);
}
@Override
public synchronized List<T> getChildren(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
return node.getChildIdList();
}
@Override
public synchronized T getParent(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
return node.getParent();
}
private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) {
boolean visibility;
final List<InMemoryTreeNode<T>> children = node.getChildren();
if (children.isEmpty()) {
visibility = visibleByDefault;
} else {
visibility = children.get(0).isVisible();
}
return visibility;
}
@Override
public synchronized void addBeforeChild(final T parent, final T newChild,
final T beforeChild) {
expectNodeNotInTreeYet(newChild);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent);
final boolean visibility = getChildrenVisibility(node);
// top nodes are always expanded.
if (beforeChild == null) {
final InMemoryTreeNode<T> added = node.add(0, newChild, visibility);
allNodes.put(newChild, added);
} else {
final int index = node.indexOf(beforeChild);
final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index,
newChild, visibility);
allNodes.put(newChild, added);
}
if (visibility) {
internalDataSetChanged();
}
}
@Override
public synchronized void addAfterChild(final T parent, final T newChild,
final T afterChild) {
expectNodeNotInTreeYet(newChild);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent);
final boolean visibility = getChildrenVisibility(node);
if (afterChild == null) {
final InMemoryTreeNode<T> added = node.add(
node.getChildrenListSize(), newChild, visibility);
allNodes.put(newChild, added);
} else {
final int index = node.indexOf(afterChild);
final InMemoryTreeNode<T> added = node.add(
index == -1 ? node.getChildrenListSize() : index + 1, newChild,
visibility);
allNodes.put(newChild, added);
}
if (visibility) {
internalDataSetChanged();
}
}
@Override
public synchronized void removeNodeRecursively(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
final boolean visibleNodeChanged = removeNodeRecursively(node);
final T parent = node.getParent();
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
parentNode.removeChild(id);
if (visibleNodeChanged) {
internalDataSetChanged();
}
}
private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) {
boolean visibleNodeChanged = false;
for (final InMemoryTreeNode<T> child : node.getChildren()) {
if (removeNodeRecursively(child)) {
visibleNodeChanged = true;
}
}
node.clearChildren();
if (node.getId() != null) {
allNodes.remove(node.getId());
if (node.isVisible()) {
visibleNodeChanged = true;
}
}
return visibleNodeChanged;
}
private void setChildrenVisibility(final InMemoryTreeNode<T> node,
final boolean visible, final boolean recursive) {
for (final InMemoryTreeNode<T> child : node.getChildren()) {
child.setVisible(visible);
if (recursive) {
setChildrenVisibility(child, visible, true);
}
}
}
@Override
public synchronized void expandDirectChildren(final T id) {
Log.d(TAG, "Expanding direct children of " + id);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
setChildrenVisibility(node, true, false);
internalDataSetChanged();
}
@Override
public synchronized void expandEverythingBelow(final T id) {
Log.d(TAG, "Expanding all children below " + id);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
setChildrenVisibility(node, true, true);
internalDataSetChanged();
}
@Override
public synchronized void collapseChildren(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
if (node == topSentinel) {
for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) {
setChildrenVisibility(n, false, true);
}
} else {
setChildrenVisibility(node, false, true);
}
internalDataSetChanged();
}
@Override
public synchronized T getNextSibling(final T id) {
final T parent = getParent(id);
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
boolean returnNext = false;
for (final InMemoryTreeNode<T> child : parentNode.getChildren()) {
if (returnNext) {
return child.getId();
}
if (child.getId().equals(id)) {
returnNext = true;
}
}
return null;
}
@Override
public synchronized T getPreviousSibling(final T id) {
final T parent = getParent(id);
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
final T previousSibling = null;
for (final InMemoryTreeNode<T> child : parentNode.getChildren()) {
if (child.getId().equals(id)) {
return previousSibling;
}
}
return null;
}
@Override
public synchronized boolean isInTree(final T id) {
return allNodes.containsKey(id);
}
@Override
public synchronized int getVisibleCount() {
return getVisibleList().size();
}
@Override
public synchronized List<T> getVisibleList() {
T currentId = null;
if (visibleListCache == null) {
visibleListCache = new ArrayList<T>(allNodes.size());
do {
currentId = getNextVisible(currentId);
if (currentId == null) {
break;
} else {
visibleListCache.add(currentId);
}
} while (true);
}
if (unmodifiableVisibleList == null) {
unmodifiableVisibleList = Collections
.unmodifiableList(visibleListCache);
}
return unmodifiableVisibleList;
}
public synchronized T getNextVisible(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
if (!node.isVisible()) {
return null;
}
final List<InMemoryTreeNode<T>> children = node.getChildren();
if (!children.isEmpty()) {
final InMemoryTreeNode<T> firstChild = children.get(0);
if (firstChild.isVisible()) {
return firstChild.getId();
}
}
final T sibl = getNextSibling(id);
if (sibl != null) {
return sibl;
}
T parent = node.getParent();
do {
if (parent == null) {
return null;
}
final T parentSibling = getNextSibling(parent);
if (parentSibling != null) {
return parentSibling;
}
parent = getNodeFromTreeOrThrow(parent).getParent();
} while (true);
}
@Override
public synchronized void registerDataSetObserver(
final DataSetObserver observer) {
observers.add(observer);
}
@Override
public synchronized void unregisterDataSetObserver(
final DataSetObserver observer) {
observers.remove(observer);
}
@Override
public int getLevel(final T id) {
return getNodeFromTreeOrThrow(id).getLevel();
}
@Override
public Integer[] getHierarchyDescription(final T id) {
final int level = getLevel(id);
final Integer[] hierarchy = new Integer[level + 1];
int currentLevel = level;
T currentId = id;
T parent = getParent(currentId);
while (currentLevel >= 0) {
hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId);
currentId = parent;
parent = getParent(parent);
}
return hierarchy;
}
private void appendToSb(final StringBuilder sb, final T id) {
if (id != null) {
final TreeNodeInfo<T> node = getNodeInfo(id);
final int indent = node.getLevel() * 4;
final char[] indentString = new char[indent];
Arrays.fill(indentString, ' ');
sb.append(indentString);
sb.append(node.toString());
sb.append(Arrays.asList(getHierarchyDescription(id)).toString());
sb.append("\n");
}
final List<T> children = getChildren(id);
for (final T child : children) {
appendToSb(sb, child);
}
}
@Override
public synchronized String toString() {
final StringBuilder sb = new StringBuilder();
appendToSb(sb, null);
return sb.toString();
}
@Override
public synchronized void clear() {
allNodes.clear();
topSentinel.clearChildren();
internalDataSetChanged();
}
@Override
public void refresh() {
internalDataSetChanged();
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/InMemoryTreeStateManager.java | Java | bsd | 12,720 |
package pl.polidea.treeview;
/**
* The node being added is already in the tree.
*
*/
public class NodeAlreadyInTreeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NodeAlreadyInTreeException(final String id, final String oldNode) {
super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode);
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/NodeAlreadyInTreeException.java | Java | bsd | 397 |
/**
* Provides expandable Tree View implementation.
*/
package pl.polidea.treeview; | 0812398-clonetreeview | src/pl/polidea/treeview/package-info.java | Java | bsd | 85 |
package pl.polidea.treeview;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
/**
* Adapter used to feed the table view.
*
* @param <T>
* class for ID of the tree
*/
public abstract class AbstractTreeViewAdapter<T> extends BaseAdapter implements
ListAdapter {
private static final String TAG = AbstractTreeViewAdapter.class
.getSimpleName();
private final TreeStateManager<T> treeStateManager;
private final int numberOfLevels;
private final LayoutInflater layoutInflater;
private int indentWidth = 0;
private int indicatorGravity = 0;
private Drawable collapsedDrawable;
private Drawable expandedDrawable;
private Drawable indicatorBackgroundDrawable;
private Drawable rowBackgroundDrawable;
private final OnClickListener indicatorClickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
@SuppressWarnings("unchecked")
final T id = (T) v.getTag();
expandCollapse(id);
}
};
private boolean collapsible;
private final Activity activity;
public Activity getActivity() {
return activity;
}
protected TreeStateManager<T> getManager() {
return treeStateManager;
}
protected void expandCollapse(final T id) {
final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id);
if (!info.isWithChildren()) {
// ignore - no default action
return;
}
if (info.isExpanded()) {
treeStateManager.collapseChildren(id);
} else {
treeStateManager.expandDirectChildren(id);
}
}
private void calculateIndentWidth() {
if (expandedDrawable != null) {
indentWidth = Math.max(getIndentWidth(),
expandedDrawable.getIntrinsicWidth());
}
if (collapsedDrawable != null) {
indentWidth = Math.max(getIndentWidth(),
collapsedDrawable.getIntrinsicWidth());
}
}
public AbstractTreeViewAdapter(final Activity activity,
final TreeStateManager<T> treeStateManager, final int numberOfLevels) {
this.activity = activity;
this.treeStateManager = treeStateManager;
this.layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.numberOfLevels = numberOfLevels;
this.collapsedDrawable = null;
this.expandedDrawable = null;
this.rowBackgroundDrawable = null;
this.indicatorBackgroundDrawable = null;
}
@Override
public void registerDataSetObserver(final DataSetObserver observer) {
treeStateManager.registerDataSetObserver(observer);
}
@Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
treeStateManager.unregisterDataSetObserver(observer);
}
@Override
public int getCount() {
return treeStateManager.getVisibleCount();
}
@Override
public Object getItem(final int position) {
return getItemId(position);
}
public T getTreeId(final int position) {
return treeStateManager.getVisibleList().get(position);
}
public TreeNodeInfo<T> getTreeNodeInfo(final int position) {
return treeStateManager.getNodeInfo(getTreeId(position));
}
@Override
public boolean hasStableIds() { // NOPMD
return true;
}
@Override
public int getItemViewType(final int position) {
return getTreeNodeInfo(position).getLevel();
}
@Override
public int getViewTypeCount() {
return numberOfLevels;
}
@Override
public boolean isEmpty() {
return getCount() == 0;
}
@Override
public boolean areAllItemsEnabled() { // NOPMD
return true;
}
@Override
public boolean isEnabled(final int position) { // NOPMD
return true;
}
protected int getTreeListItemWrapperId() {
return R.layout.tree_list_item_wrapper;
}
@Override
public final View getView(final int position, final View convertView,
final ViewGroup parent) {
Log.d(TAG, "Creating a view based on " + convertView
+ " with position " + position);
final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position);
if (convertView == null) {
Log.d(TAG, "Creating the view a new");
final LinearLayout layout = (LinearLayout) layoutInflater.inflate(
getTreeListItemWrapperId(), null);
return populateTreeItem(layout, getNewChildView(nodeInfo),
nodeInfo, true);
} else {
Log.d(TAG, "Reusing the view");
final LinearLayout linear = (LinearLayout) convertView;
final FrameLayout frameLayout = (FrameLayout) linear
.findViewById(R.id.treeview_list_item_frame);
final View childView = frameLayout.getChildAt(0);
updateView(childView, nodeInfo);
return populateTreeItem(linear, childView, nodeInfo, false);
}
}
/**
* Called when new view is to be created.
*
* @param treeNodeInfo
* node info
* @return view that should be displayed as tree content
*/
public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo);
/**
* Called when new view is going to be reused. You should update the view
* and fill it in with the data required to display the new information. You
* can also create a new view, which will mean that the old view will not be
* reused.
*
* @param view
* view that should be updated with the new values
* @param treeNodeInfo
* node info used to populate the view
* @return view to used as row indented content
*/
public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo);
/**
* Retrieves background drawable for the node.
*
* @param treeNodeInfo
* node info
* @return drawable returned as background for the whole row. Might be null,
* then default background is used
*/
public Drawable getBackgroundDrawable(final TreeNodeInfo<T> treeNodeInfo) { // NOPMD
return null;
}
private Drawable getDrawableOrDefaultBackground(final Drawable r) {
if (r == null) {
return activity.getResources()
.getDrawable(R.drawable.list_selector_background).mutate();
} else {
return r;
}
}
public final LinearLayout populateTreeItem(final LinearLayout layout,
final View childView, final TreeNodeInfo<T> nodeInfo,
final boolean newChildView) {
final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo);
layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable)
: individualRowDrawable);
final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams(
calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT);
final LinearLayout indicatorLayout = (LinearLayout) layout
.findViewById(R.id.treeview_list_item_image_layout);
indicatorLayout.setGravity(indicatorGravity);
indicatorLayout.setLayoutParams(indicatorLayoutParams);
final ImageView image = (ImageView) layout
.findViewById(R.id.treeview_list_item_image);
image.setImageDrawable(getDrawable(nodeInfo));
image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable));
image.setScaleType(ScaleType.CENTER);
image.setTag(nodeInfo.getId());
if (nodeInfo.isWithChildren() && collapsible) {
image.setOnClickListener(indicatorClickListener);
} else {
image.setOnClickListener(null);
}
layout.setTag(nodeInfo.getId());
final FrameLayout frameLayout = (FrameLayout) layout
.findViewById(R.id.treeview_list_item_frame);
final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
if (newChildView) {
frameLayout.addView(childView, childParams);
}
frameLayout.setTag(nodeInfo.getId());
return layout;
}
protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) {
return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0));
}
protected Drawable getDrawable(final TreeNodeInfo<T> nodeInfo) {
if (!nodeInfo.isWithChildren() || !collapsible) {
return getDrawableOrDefaultBackground(indicatorBackgroundDrawable);
}
if (nodeInfo.isExpanded()) {
return expandedDrawable;
} else {
return collapsedDrawable;
}
}
public void setIndicatorGravity(final int indicatorGravity) {
this.indicatorGravity = indicatorGravity;
}
public void setCollapsedDrawable(final Drawable collapsedDrawable) {
this.collapsedDrawable = collapsedDrawable;
calculateIndentWidth();
}
public void setExpandedDrawable(final Drawable expandedDrawable) {
this.expandedDrawable = expandedDrawable;
calculateIndentWidth();
}
public void setIndentWidth(final int indentWidth) {
this.indentWidth = indentWidth;
calculateIndentWidth();
}
public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) {
this.rowBackgroundDrawable = rowBackgroundDrawable;
}
public void setIndicatorBackgroundDrawable(
final Drawable indicatorBackgroundDrawable) {
this.indicatorBackgroundDrawable = indicatorBackgroundDrawable;
}
public void setCollapsible(final boolean collapsible) {
this.collapsible = collapsible;
}
public void refresh() {
treeStateManager.refresh();
}
private int getIndentWidth() {
return indentWidth;
}
@SuppressWarnings("unchecked")
public void handleItemClick(final View view, final Object id) {
expandCollapse((T) id);
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/AbstractTreeViewAdapter.java | Java | bsd | 10,894 |
package pl.polidea.treeview;
/**
* Exception thrown when there is a problem with configuring tree.
*
*/
public class TreeConfigurationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TreeConfigurationException(final String detailMessage) {
super(detailMessage);
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/TreeConfigurationException.java | Java | bsd | 338 |
package pl.polidea.treeview;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
/**
* Node. It is package protected so that it cannot be used outside.
*
* @param <T>
* type of the identifier used by the tree
*/
class InMemoryTreeNode<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final T id;
private final T parent;
private final int level;
private boolean visible = true;
private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>();
private List<T> childIdListCache = null;
public InMemoryTreeNode(final T id, final T parent, final int level,
final boolean visible) {
super();
this.id = id;
this.parent = parent;
this.level = level;
this.visible = visible;
}
public int indexOf(final T id) {
return getChildIdList().indexOf(id);
}
/**
* Cache is built lasily only if needed. The cache is cleaned on any
* structure change for that node!).
*
* @return list of ids of children
*/
public synchronized List<T> getChildIdList() {
if (childIdListCache == null) {
childIdListCache = new LinkedList<T>();
for (final InMemoryTreeNode<T> n : children) {
childIdListCache.add(n.getId());
}
}
return childIdListCache;
}
public boolean isVisible() {
return visible;
}
public void setVisible(final boolean visible) {
this.visible = visible;
}
public int getChildrenListSize() {
return children.size();
}
public synchronized InMemoryTreeNode<T> add(final int index, final T child,
final boolean visible) {
childIdListCache = null;
// Note! top levell children are always visible (!)
final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child,
getId(), getLevel() + 1, getId() == null ? true : visible);
children.add(index, newNode);
return newNode;
}
/**
* Note. This method should technically return unmodifiable collection, but
* for performance reason on small devices we do not do it.
*
* @return children list
*/
public List<InMemoryTreeNode<T>> getChildren() {
return children;
}
public synchronized void clearChildren() {
children.clear();
childIdListCache = null;
}
public synchronized void removeChild(final T child) {
final int childIndex = indexOf(child);
if (childIndex != -1) {
children.remove(childIndex);
childIdListCache = null;
}
}
@Override
public String toString() {
return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent()
+ ", level=" + getLevel() + ", visible=" + visible
+ ", children=" + children + ", childIdListCache="
+ childIdListCache + "]";
}
T getId() {
return id;
}
T getParent() {
return parent;
}
int getLevel() {
return level;
}
} | 0812398-clonetreeview | src/pl/polidea/treeview/InMemoryTreeNode.java | Java | bsd | 3,187 |
package pl.polidea.treeview;
import java.io.Serializable;
import java.util.List;
import android.database.DataSetObserver;
/**
* Manages information about state of the tree. It only keeps information about
* tree elements, not the elements themselves.
*
* @param <T>
* type of the identifier for nodes in the tree
*/
public interface TreeStateManager<T> extends Serializable {
/**
* Returns array of integers showing the location of the node in hierarchy.
* It corresponds to heading numbering. {0,0,0} in 3 level node is the first
* node {0,0,1} is second leaf (assuming that there are two leaves in first
* subnode of the first node).
*
* @param id
* id of the node
* @return textual description of the hierarchy in tree for the node.
*/
Integer[] getHierarchyDescription(T id);
/**
* Returns level of the node.
*
* @param id
* id of the node
* @return level in the tree
*/
int getLevel(T id);
/**
* Returns information about the node.
*
* @param id
* node id
* @return node info
*/
TreeNodeInfo<T> getNodeInfo(T id);
/**
* Returns children of the node.
*
* @param id
* id of the node or null if asking for top nodes
* @return children of the node
*/
List<T> getChildren(T id);
/**
* Returns parent of the node.
*
* @param id
* id of the node
* @return parent id or null if no parent
*/
T getParent(T id);
/**
* Adds the node before child or at the beginning.
*
* @param parent
* id of the parent node. If null - adds at the top level
* @param newChild
* new child to add if null - adds at the beginning.
* @param beforeChild
* child before which to add the new child
*/
void addBeforeChild(T parent, T newChild, T beforeChild);
/**
* Adds the node after child or at the end.
*
* @param parent
* id of the parent node. If null - adds at the top level.
* @param newChild
* new child to add. If null - adds at the end.
* @param afterChild
* child after which to add the new child
*/
void addAfterChild(T parent, T newChild, T afterChild);
/**
* Removes the node and all children from the tree.
*
* @param id
* id of the node to remove or null if all nodes are to be
* removed.
*/
void removeNodeRecursively(T id);
/**
* Expands all children of the node.
*
* @param id
* node which children should be expanded. cannot be null (top
* nodes are always expanded!).
*/
void expandDirectChildren(T id);
/**
* Expands everything below the node specified. Might be null - then expands
* all.
*
* @param id
* node which children should be expanded or null if all nodes
* are to be expanded.
*/
void expandEverythingBelow(T id);
/**
* Collapse children.
*
* @param id
* id collapses everything below node specified. If null,
* collapses everything but top-level nodes.
*/
void collapseChildren(T id);
/**
* Returns next sibling of the node (or null if no further sibling).
*
* @param id
* node id
* @return the sibling (or null if no next)
*/
T getNextSibling(T id);
/**
* Returns previous sibling of the node (or null if no previous sibling).
*
* @param id
* node id
* @return the sibling (or null if no previous)
*/
T getPreviousSibling(T id);
/**
* Checks if given node is already in tree.
*
* @param id
* id of the node
* @return true if node is already in tree.
*/
boolean isInTree(T id);
/**
* Count visible elements.
*
* @return number of currently visible elements.
*/
int getVisibleCount();
/**
* Returns visible node list.
*
* @return return the list of all visible nodes in the right sequence
*/
List<T> getVisibleList();
/**
* Registers observers with the manager.
*
* @param observer
* observer
*/
void registerDataSetObserver(final DataSetObserver observer);
/**
* Unregisters observers with the manager.
*
* @param observer
* observer
*/
void unregisterDataSetObserver(final DataSetObserver observer);
/**
* Cleans tree stored in manager. After this operation the tree is empty.
*
*/
void clear();
/**
* Refreshes views connected to the manager.
*/
void refresh();
}
| 0812398-clonetreeview | src/pl/polidea/treeview/TreeStateManager.java | Java | bsd | 4,940 |
<html>
<body>
This is a small utility that provides quite configurable tree view list.
It is based on standard android list view. It separates out different
aspects of the tree: there is a separate list view, tree adapter, tree
state manager and tree state builder.
<p>
<ul>
<li>Tree view provides the frame to display the view.</li>
<li>Adapter allows to create visual representation of each tree
node.</li>
<li>State manager provides storage for tree state (connections
between parents and children, collapsed/expanded state). It provides
all the low-level tree manipulation methods.</li>
<li>Tree builder allows to build tree easily providing higher
level methods. The tree can be build either from prepared sequentially
prepared list of nodes (node id, level) or using (parent/child
relationships).</li>
<p>For now only in-memory state manager is provided, but Tree State
Manger interface is done in the way that database tree manager even for
large trees is potentially supported.
</ul>
</body>
</html> | 0812398-clonetreeview | src/pl/polidea/treeview/overview.html | HTML | bsd | 1,020 |
package pl.polidea.treeview;
/**
* This exception is thrown when the tree does not contain node requested.
*
*/
public class NodeNotInTreeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NodeNotInTreeException(final String id) {
super("The tree does not contain the node specified: " + id);
}
}
| 0812398-clonetreeview | src/pl/polidea/treeview/NodeNotInTreeException.java | Java | bsd | 367 |
package pl.polidea.treeview;
/**
* Information about the node.
*
* @param <T>
* type of the id for the tree
*/
public class TreeNodeInfo<T> {
private final T id;
private final int level;
private final boolean withChildren;
private final boolean visible;
private final boolean expanded;
/**
* Creates the node information.
*
* @param id
* id of the node
* @param level
* level of the node
* @param withChildren
* whether the node has children.
* @param visible
* whether the tree node is visible.
* @param expanded
* whether the tree node is expanded
*
*/
public TreeNodeInfo(final T id, final int level,
final boolean withChildren, final boolean visible,
final boolean expanded) {
super();
this.id = id;
this.level = level;
this.withChildren = withChildren;
this.visible = visible;
this.expanded = expanded;
}
public T getId() {
return id;
}
public boolean isWithChildren() {
return withChildren;
}
public boolean isVisible() {
return visible;
}
public boolean isExpanded() {
return expanded;
}
public int getLevel() {
return level;
}
@Override
public String toString() {
return "TreeNodeInfo [id=" + id + ", level=" + level
+ ", withChildren=" + withChildren + ", visible=" + visible
+ ", expanded=" + expanded + "]";
}
} | 0812398-clonetreeview | src/pl/polidea/treeview/TreeNodeInfo.java | Java | bsd | 1,611 |
/**
* Provides just demo of the TreeView widget.
*/
package pl.polidea.treeview.demo; | 0812398-clonetreeview | src/pl/polidea/treeview/demo/package-info.java | Java | bsd | 87 |