repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
} } finally { cursor.close(); } return token; } private void saveSyncInfo(String syncToken) { AutoEscapeValues values = new AutoEscapeValues(); values.put("token", syncToken); db.delete(TABLE_SYNC_INFO, null, null); db.insert(TABLE_SYNC_INFO, null, values.get()); } private void processResource(CDAResource resource) { CDAType type = resource.type(); LocalizedResource localized = (LocalizedResource) resource; if (type == ASSET) { saveAsset((CDAAsset) resource); } else if (type == ENTRY) { Class<?> modelClass = spaceHelper.getTypes().get(((CDAEntry) localized).contentType().id()); if (modelClass == null) { return; } ModelHelper<?> modelHelper = spaceHelper.getModels().get(modelClass); saveEntry((CDAEntry) resource, modelHelper.getTableName(), modelHelper.getFields()); } } private void deleteAsset(String id) {
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; } } finally { cursor.close(); } return token; } private void saveSyncInfo(String syncToken) { AutoEscapeValues values = new AutoEscapeValues(); values.put("token", syncToken); db.delete(TABLE_SYNC_INFO, null, null); db.insert(TABLE_SYNC_INFO, null, values.get()); } private void processResource(CDAResource resource) { CDAType type = resource.type(); LocalizedResource localized = (LocalizedResource) resource; if (type == ASSET) { saveAsset((CDAAsset) resource); } else if (type == ENTRY) { Class<?> modelClass = spaceHelper.getTypes().get(((CDAEntry) localized).contentType().id()); if (modelClass == null) { return; } ModelHelper<?> modelHelper = spaceHelper.getModels().get(modelClass); saveEntry((CDAEntry) resource, modelHelper.getTableName(), modelHelper.getFields()); } } private void deleteAsset(String id) {
deleteResource(id, TABLE_ASSETS);
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
CDAType type = resource.type(); LocalizedResource localized = (LocalizedResource) resource; if (type == ASSET) { saveAsset((CDAAsset) resource); } else if (type == ENTRY) { Class<?> modelClass = spaceHelper.getTypes().get(((CDAEntry) localized).contentType().id()); if (modelClass == null) { return; } ModelHelper<?> modelHelper = spaceHelper.getModels().get(modelClass); saveEntry((CDAEntry) resource, modelHelper.getTableName(), modelHelper.getFields()); } } private void deleteAsset(String id) { deleteResource(id, TABLE_ASSETS); } private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) {
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; CDAType type = resource.type(); LocalizedResource localized = (LocalizedResource) resource; if (type == ASSET) { saveAsset((CDAAsset) resource); } else if (type == ENTRY) { Class<?> modelClass = spaceHelper.getTypes().get(((CDAEntry) localized).contentType().id()); if (modelClass == null) { return; } ModelHelper<?> modelHelper = spaceHelper.getModels().get(modelClass); saveEntry((CDAEntry) resource, modelHelper.getTableName(), modelHelper.getFields()); } } private void deleteAsset(String id) { deleteResource(id, TABLE_ASSETS); } private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) {
String whereClause = REMOTE_ID + " = ?";
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
if (type == ASSET) { saveAsset((CDAAsset) resource); } else if (type == ENTRY) { Class<?> modelClass = spaceHelper.getTypes().get(((CDAEntry) localized).contentType().id()); if (modelClass == null) { return; } ModelHelper<?> modelHelper = spaceHelper.getModels().get(modelClass); saveEntry((CDAEntry) resource, modelHelper.getTableName(), modelHelper.getFields()); } } private void deleteAsset(String id) { deleteResource(id, TABLE_ASSETS); } private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId};
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; if (type == ASSET) { saveAsset((CDAAsset) resource); } else if (type == ENTRY) { Class<?> modelClass = spaceHelper.getTypes().get(((CDAEntry) localized).contentType().id()); if (modelClass == null) { return; } ModelHelper<?> modelHelper = spaceHelper.getModels().get(modelClass); saveEntry((CDAEntry) resource, modelHelper.getTableName(), modelHelper.getFields()); } } private void deleteAsset(String id) { deleteResource(id, TABLE_ASSETS); } private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId};
db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs);
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId}; db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs); } private void deleteResource(String remoteId, String tableName) { // resource String resWhere = REMOTE_ID + " = ?"; String resArgs[] = new String[]{remoteId}; // links String linksWhere = "`parent` = ? OR `child` = ?"; String linkArgs[] = new String[]{ remoteId, remoteId }; for (String locale : spaceHelper.getLocales()) {
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId}; db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs); } private void deleteResource(String remoteId, String tableName) { // resource String resWhere = REMOTE_ID + " = ?"; String resArgs[] = new String[]{remoteId}; // links String linksWhere = "`parent` = ? OR `child` = ?"; String linkArgs[] = new String[]{ remoteId, remoteId }; for (String locale : spaceHelper.getLocales()) {
db.delete(escape(localizeName(tableName, locale)), resWhere, resArgs);
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId}; db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs); } private void deleteResource(String remoteId, String tableName) { // resource String resWhere = REMOTE_ID + " = ?"; String resArgs[] = new String[]{remoteId}; // links String linksWhere = "`parent` = ? OR `child` = ?"; String linkArgs[] = new String[]{ remoteId, remoteId }; for (String locale : spaceHelper.getLocales()) {
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private void deleteEntry(String id) { String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId}; db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs); } private void deleteResource(String remoteId, String tableName) { // resource String resWhere = REMOTE_ID + " = ?"; String resArgs[] = new String[]{remoteId}; // links String linksWhere = "`parent` = ? OR `child` = ?"; String linkArgs[] = new String[]{ remoteId, remoteId }; for (String locale : spaceHelper.getLocales()) {
db.delete(escape(localizeName(tableName, locale)), resWhere, resArgs);
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId}; db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs); } private void deleteResource(String remoteId, String tableName) { // resource String resWhere = REMOTE_ID + " = ?"; String resArgs[] = new String[]{remoteId}; // links String linksWhere = "`parent` = ? OR `child` = ?"; String linkArgs[] = new String[]{ remoteId, remoteId }; for (String locale : spaceHelper.getLocales()) { db.delete(escape(localizeName(tableName, locale)), resWhere, resArgs);
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; String contentTypeId = LinkResolver.fetchEntryType(db, id); if (contentTypeId != null) { Class<?> clazz = spaceHelper.getTypes().get(contentTypeId); if (clazz != null) { deleteResource(id, spaceHelper.getModels().get(clazz).getTableName()); deleteEntryType(id); } } } private void deleteEntryType(String remoteId) { String whereClause = REMOTE_ID + " = ?"; String[] whereArgs = new String[]{remoteId}; db.delete(TABLE_ENTRY_TYPES, whereClause, whereArgs); } private void deleteResource(String remoteId, String tableName) { // resource String resWhere = REMOTE_ID + " = ?"; String resArgs[] = new String[]{remoteId}; // links String linksWhere = "`parent` = ? OR `child` = ?"; String linkArgs[] = new String[]{ remoteId, remoteId }; for (String locale : spaceHelper.getLocales()) { db.delete(escape(localizeName(tableName, locale)), resWhere, resArgs);
db.delete(escape(localizeName(TABLE_LINKS, locale)), linksWhere, linkArgs);
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private void saveLink(String parentId, String fieldId, String linkType, String targetId, int position, String locale) { AutoEscapeValues values = new AutoEscapeValues(); values.put("parent", parentId); values.put("field", fieldId); values.put("child", targetId); values.put("position", position); values.put("is_asset", CDAType.valueOf(linkType.toUpperCase(Vault.LOCALE)) == ASSET); db.insertWithOnConflict(escape(localizeName(TABLE_LINKS, locale)), null, values.get(), CONFLICT_REPLACE); } private void deleteResourceLinks(String parentId, String field) { for (String locale : spaceHelper.getLocales()) { deleteResourceLinks(parentId, field, locale); } } private void deleteResourceLinks(String parentId, String field, String locale) { String where = "parent = ? AND field = ?"; String[] args = new String[]{parentId, field}; db.delete(escape(localizeName(TABLE_LINKS, locale)), where, args); } private static void putResourceFields(CDAResource resource, AutoEscapeValues values) { values.put(REMOTE_ID, resource.id());
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private void saveLink(String parentId, String fieldId, String linkType, String targetId, int position, String locale) { AutoEscapeValues values = new AutoEscapeValues(); values.put("parent", parentId); values.put("field", fieldId); values.put("child", targetId); values.put("position", position); values.put("is_asset", CDAType.valueOf(linkType.toUpperCase(Vault.LOCALE)) == ASSET); db.insertWithOnConflict(escape(localizeName(TABLE_LINKS, locale)), null, values.get(), CONFLICT_REPLACE); } private void deleteResourceLinks(String parentId, String field) { for (String locale : spaceHelper.getLocales()) { deleteResourceLinks(parentId, field, locale); } } private void deleteResourceLinks(String parentId, String field, String locale) { String where = "parent = ? AND field = ?"; String[] args = new String[]{parentId, field}; db.delete(escape(localizeName(TABLE_LINKS, locale)), where, args); } private static void putResourceFields(CDAResource resource, AutoEscapeValues values) { values.put(REMOTE_ID, resource.id());
values.put(CREATED_AT, (String) resource.getAttribute("createdAt"));
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private void saveLink(String parentId, String fieldId, String linkType, String targetId, int position, String locale) { AutoEscapeValues values = new AutoEscapeValues(); values.put("parent", parentId); values.put("field", fieldId); values.put("child", targetId); values.put("position", position); values.put("is_asset", CDAType.valueOf(linkType.toUpperCase(Vault.LOCALE)) == ASSET); db.insertWithOnConflict(escape(localizeName(TABLE_LINKS, locale)), null, values.get(), CONFLICT_REPLACE); } private void deleteResourceLinks(String parentId, String field) { for (String locale : spaceHelper.getLocales()) { deleteResourceLinks(parentId, field, locale); } } private void deleteResourceLinks(String parentId, String field, String locale) { String where = "parent = ? AND field = ?"; String[] args = new String[]{parentId, field}; db.delete(escape(localizeName(TABLE_LINKS, locale)), where, args); } private static void putResourceFields(CDAResource resource, AutoEscapeValues values) { values.put(REMOTE_ID, resource.id()); values.put(CREATED_AT, (String) resource.getAttribute("createdAt"));
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private void saveLink(String parentId, String fieldId, String linkType, String targetId, int position, String locale) { AutoEscapeValues values = new AutoEscapeValues(); values.put("parent", parentId); values.put("field", fieldId); values.put("child", targetId); values.put("position", position); values.put("is_asset", CDAType.valueOf(linkType.toUpperCase(Vault.LOCALE)) == ASSET); db.insertWithOnConflict(escape(localizeName(TABLE_LINKS, locale)), null, values.get(), CONFLICT_REPLACE); } private void deleteResourceLinks(String parentId, String field) { for (String locale : spaceHelper.getLocales()) { deleteResourceLinks(parentId, field, locale); } } private void deleteResourceLinks(String parentId, String field, String locale) { String where = "parent = ? AND field = ?"; String[] args = new String[]{parentId, field}; db.delete(escape(localizeName(TABLE_LINKS, locale)), where, args); } private static void putResourceFields(CDAResource resource, AutoEscapeValues values) { values.put(REMOTE_ID, resource.id()); values.put(CREATED_AT, (String) resource.getAttribute("createdAt"));
values.put(UPDATED_AT, (String) resource.getAttribute("updatedAt"));
contentful/vault
core/src/main/java/com/contentful/vault/SyncConfig.java
// Path: core/src/main/templates/com/contentful/vault/build/GeneratedBuildParameters.java // public static final String PROJECT_VERSION = "${project.version}";
import com.contentful.java.cda.CDAClient; import static com.contentful.vault.build.GeneratedBuildParameters.PROJECT_VERSION; import static java.text.MessageFormat.format;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class SyncConfig { private final CDAClient client; private final boolean invalidate; SyncConfig(Builder builder) { this.invalidate = builder.invalidate; if (builder.client == null) { if (builder.accessToken == null) { throw new IllegalStateException("Cannot create a CDA client with no access token. " + "Please set it."); } if (builder.spaceId == null) { throw new IllegalStateException("Cannot create a CDA client with no space id. " + "Please set it."); } this.client = CDAClient .builder() .setToken(builder.accessToken) .setSpace(builder.spaceId) .setEnvironment(builder.environment)
// Path: core/src/main/templates/com/contentful/vault/build/GeneratedBuildParameters.java // public static final String PROJECT_VERSION = "${project.version}"; // Path: core/src/main/java/com/contentful/vault/SyncConfig.java import com.contentful.java.cda.CDAClient; import static com.contentful.vault.build.GeneratedBuildParameters.PROJECT_VERSION; import static java.text.MessageFormat.format; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class SyncConfig { private final CDAClient client; private final boolean invalidate; SyncConfig(Builder builder) { this.invalidate = builder.invalidate; if (builder.client == null) { if (builder.accessToken == null) { throw new IllegalStateException("Cannot create a CDA client with no access token. " + "Please set it."); } if (builder.spaceId == null) { throw new IllegalStateException("Cannot create a CDA client with no space id. " + "Please set it."); } this.client = CDAClient .builder() .setToken(builder.accessToken) .setSpace(builder.spaceId) .setEnvironment(builder.environment)
.setIntegration("Vault", PROJECT_VERSION)
contentful/vault
core/src/main/java/com/contentful/vault/Sql.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at";
import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class Sql { private Sql() { throw new AssertionError(); } public static final String[] RESOURCE_COLUMNS = new String[] {
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // Path: core/src/main/java/com/contentful/vault/Sql.java import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class Sql { private Sql() { throw new AssertionError(); } public static final String[] RESOURCE_COLUMNS = new String[] {
declareField(REMOTE_ID, "STRING", false, " UNIQUE"),
contentful/vault
core/src/main/java/com/contentful/vault/Sql.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at";
import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class Sql { private Sql() { throw new AssertionError(); } public static final String[] RESOURCE_COLUMNS = new String[] { declareField(REMOTE_ID, "STRING", false, " UNIQUE"),
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // Path: core/src/main/java/com/contentful/vault/Sql.java import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class Sql { private Sql() { throw new AssertionError(); } public static final String[] RESOURCE_COLUMNS = new String[] { declareField(REMOTE_ID, "STRING", false, " UNIQUE"),
declareField(CREATED_AT, "STRING", false, null),
contentful/vault
core/src/main/java/com/contentful/vault/Sql.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at";
import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class Sql { private Sql() { throw new AssertionError(); } public static final String[] RESOURCE_COLUMNS = new String[] { declareField(REMOTE_ID, "STRING", false, " UNIQUE"), declareField(CREATED_AT, "STRING", false, null),
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // Path: core/src/main/java/com/contentful/vault/Sql.java import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; public final class Sql { private Sql() { throw new AssertionError(); } public static final String[] RESOURCE_COLUMNS = new String[] { declareField(REMOTE_ID, "STRING", false, " UNIQUE"), declareField(CREATED_AT, "STRING", false, null),
declareField(UPDATED_AT, "STRING", true, null),
contentful/vault
core/src/main/java/com/contentful/vault/LinkResolver.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; final class LinkResolver { private static final String LINKS_WHERE_CLAUSE = "l.parent = ? AND l.is_asset = ? AND l.field = ?"; private static final String QUERY_ENTRY_TYPE = String.format(
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/LinkResolver.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; final class LinkResolver { private static final String LINKS_WHERE_CLAUSE = "l.parent = ? AND l.is_asset = ? AND l.field = ?"; private static final String QUERY_ENTRY_TYPE = String.format(
"SELECT `type_id` FROM %s WHERE %s = ?", TABLE_ENTRY_TYPES, REMOTE_ID);
contentful/vault
core/src/main/java/com/contentful/vault/LinkResolver.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; final class LinkResolver { private static final String LINKS_WHERE_CLAUSE = "l.parent = ? AND l.is_asset = ? AND l.field = ?"; private static final String QUERY_ENTRY_TYPE = String.format(
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/LinkResolver.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; final class LinkResolver { private static final String LINKS_WHERE_CLAUSE = "l.parent = ? AND l.is_asset = ? AND l.field = ?"; private static final String QUERY_ENTRY_TYPE = String.format(
"SELECT `type_id` FROM %s WHERE %s = ?", TABLE_ENTRY_TYPES, REMOTE_ID);
contentful/vault
core/src/main/java/com/contentful/vault/LinkResolver.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private List<Link> fetchLinks(String parentId, FieldMeta field, String locale) { List<Link> result; boolean linksToAssets = isLinkForAssets(field); String sql = linksToAssets ? queryAssetLinks(locale) : queryEntryLinks(locale); String[] args = new String[] { parentId, linksToAssets ? "1" : "0", field.id() }; Cursor cursor = query.vault().getReadableDatabase().rawQuery(sql, args); try { result = new ArrayList<>(); if (cursor.moveToFirst()) { do { String childId = cursor.getString(0); String childContentType = cursor.getString(1); result.add(new Link(parentId, childId, field.id(), childContentType)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private String queryAssetLinks(String locale) { return String.format("SELECT l.child, null FROM %s l WHERE %s ORDER BY l.position",
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/LinkResolver.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private List<Link> fetchLinks(String parentId, FieldMeta field, String locale) { List<Link> result; boolean linksToAssets = isLinkForAssets(field); String sql = linksToAssets ? queryAssetLinks(locale) : queryEntryLinks(locale); String[] args = new String[] { parentId, linksToAssets ? "1" : "0", field.id() }; Cursor cursor = query.vault().getReadableDatabase().rawQuery(sql, args); try { result = new ArrayList<>(); if (cursor.moveToFirst()) { do { String childId = cursor.getString(0); String childContentType = cursor.getString(1); result.add(new Link(parentId, childId, field.id(), childContentType)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private String queryAssetLinks(String locale) { return String.format("SELECT l.child, null FROM %s l WHERE %s ORDER BY l.position",
escape(localizeName(TABLE_LINKS, locale)),
contentful/vault
core/src/main/java/com/contentful/vault/LinkResolver.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private List<Link> fetchLinks(String parentId, FieldMeta field, String locale) { List<Link> result; boolean linksToAssets = isLinkForAssets(field); String sql = linksToAssets ? queryAssetLinks(locale) : queryEntryLinks(locale); String[] args = new String[] { parentId, linksToAssets ? "1" : "0", field.id() }; Cursor cursor = query.vault().getReadableDatabase().rawQuery(sql, args); try { result = new ArrayList<>(); if (cursor.moveToFirst()) { do { String childId = cursor.getString(0); String childContentType = cursor.getString(1); result.add(new Link(parentId, childId, field.id(), childContentType)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private String queryAssetLinks(String locale) { return String.format("SELECT l.child, null FROM %s l WHERE %s ORDER BY l.position",
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/LinkResolver.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private List<Link> fetchLinks(String parentId, FieldMeta field, String locale) { List<Link> result; boolean linksToAssets = isLinkForAssets(field); String sql = linksToAssets ? queryAssetLinks(locale) : queryEntryLinks(locale); String[] args = new String[] { parentId, linksToAssets ? "1" : "0", field.id() }; Cursor cursor = query.vault().getReadableDatabase().rawQuery(sql, args); try { result = new ArrayList<>(); if (cursor.moveToFirst()) { do { String childId = cursor.getString(0); String childContentType = cursor.getString(1); result.add(new Link(parentId, childId, field.id(), childContentType)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private String queryAssetLinks(String locale) { return String.format("SELECT l.child, null FROM %s l WHERE %s ORDER BY l.position",
escape(localizeName(TABLE_LINKS, locale)),
contentful/vault
core/src/main/java/com/contentful/vault/LinkResolver.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
private List<Link> fetchLinks(String parentId, FieldMeta field, String locale) { List<Link> result; boolean linksToAssets = isLinkForAssets(field); String sql = linksToAssets ? queryAssetLinks(locale) : queryEntryLinks(locale); String[] args = new String[] { parentId, linksToAssets ? "1" : "0", field.id() }; Cursor cursor = query.vault().getReadableDatabase().rawQuery(sql, args); try { result = new ArrayList<>(); if (cursor.moveToFirst()) { do { String childId = cursor.getString(0); String childContentType = cursor.getString(1); result.add(new Link(parentId, childId, field.id(), childContentType)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private String queryAssetLinks(String locale) { return String.format("SELECT l.child, null FROM %s l WHERE %s ORDER BY l.position",
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/LinkResolver.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; private List<Link> fetchLinks(String parentId, FieldMeta field, String locale) { List<Link> result; boolean linksToAssets = isLinkForAssets(field); String sql = linksToAssets ? queryAssetLinks(locale) : queryEntryLinks(locale); String[] args = new String[] { parentId, linksToAssets ? "1" : "0", field.id() }; Cursor cursor = query.vault().getReadableDatabase().rawQuery(sql, args); try { result = new ArrayList<>(); if (cursor.moveToFirst()) { do { String childId = cursor.getString(0); String childContentType = cursor.getString(1); result.add(new Link(parentId, childId, field.id(), childContentType)); } while (cursor.moveToNext()); } } finally { cursor.close(); } return result; } private String queryAssetLinks(String locale) { return String.format("SELECT l.child, null FROM %s l WHERE %s ORDER BY l.position",
escape(localizeName(TABLE_LINKS, locale)),
contentful/vault
compiler/src/test/java/com/contentful/vault/compiler/ContentTypeTest.java
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // }
import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class ContentTypeTest { @Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.SpaceHelper;", "import java.util.List;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class AwesomeModel extends Resource {", " @Field String textField;", " @Field Boolean booleanField;", " @Field Integer integerField;", " @Field Double doubleField;", " @Field Map mapField;", " @Field Asset assetLink;", " @Field AwesomeModel entryLink;", " @Field List<Asset> arrayOfAssets;", " @Field List<AwesomeModel> arrayOfModels;", " @Field List<String> arrayOfSymbols;", " }", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeModel$$ModelHelper",
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // } // Path: compiler/src/test/java/com/contentful/vault/compiler/ContentTypeTest.java import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class ContentTypeTest { @Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.SpaceHelper;", "import java.util.List;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class AwesomeModel extends Resource {", " @Field String textField;", " @Field Boolean booleanField;", " @Field Integer integerField;", " @Field Double doubleField;", " @Field Map mapField;", " @Field Asset assetLink;", " @Field AwesomeModel entryLink;", " @Field List<Asset> arrayOfAssets;", " @Field List<AwesomeModel> arrayOfModels;", " @Field List<String> arrayOfSymbols;", " }", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeModel$$ModelHelper",
readTestResource("ModelInjection.java"));
contentful/vault
compiler/src/test/java/com/contentful/vault/compiler/ContentTypeTest.java
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // }
import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.SpaceHelper;", "import java.util.List;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class AwesomeModel extends Resource {", " @Field String textField;", " @Field Boolean booleanField;", " @Field Integer integerField;", " @Field Double doubleField;", " @Field Map mapField;", " @Field Asset assetLink;", " @Field AwesomeModel entryLink;", " @Field List<Asset> arrayOfAssets;", " @Field List<AwesomeModel> arrayOfModels;", " @Field List<String> arrayOfSymbols;", " }", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeModel$$ModelHelper", readTestResource("ModelInjection.java")); assert_().about(javaSource()).that(source)
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // } // Path: compiler/src/test/java/com/contentful/vault/compiler/ContentTypeTest.java import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.SpaceHelper;", "import java.util.List;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class AwesomeModel extends Resource {", " @Field String textField;", " @Field Boolean booleanField;", " @Field Integer integerField;", " @Field Double doubleField;", " @Field Map mapField;", " @Field Asset assetLink;", " @Field AwesomeModel entryLink;", " @Field List<Asset> arrayOfAssets;", " @Field List<AwesomeModel> arrayOfModels;", " @Field List<String> arrayOfSymbols;", " }", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeModel$$ModelHelper", readTestResource("ModelInjection.java")); assert_().about(javaSource()).that(source)
.processedWith(processors())
contentful/vault
compiler/src/test/java/com/contentful/vault/compiler/FieldTest.java
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // }
import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class FieldTest { @Test public void testListTypes() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import java.util.List;", "@ContentType(\"cid\")", "class Test extends Resource {", " @Field List<String> listOfStrings;", " @Field List<Asset> listOfAssets;", "}")); assert_().about(javaSource()).that(source)
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // } // Path: compiler/src/test/java/com/contentful/vault/compiler/FieldTest.java import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class FieldTest { @Test public void testListTypes() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import java.util.List;", "@ContentType(\"cid\")", "class Test extends Resource {", " @Field List<String> listOfStrings;", " @Field List<Asset> listOfAssets;", "}")); assert_().about(javaSource()).that(source)
.processedWith(processors())
contentful/vault
compiler/src/test/java/com/contentful/vault/compiler/FieldTest.java
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // }
import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
assert_().about(javaSource()).that(source) .processedWith(processors()) .failsToCompile() .withErrorContaining( "Invalid list type \"java.lang.Integer\" specified. (Test.list)"); } @Test public void testFieldsInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.SpaceHelper;", "import java.util.List;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String foo;", " @Field String bar;", " @Field String baz;", " @Field String baz2;", " @Field String b_a_z_123;", " }", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$Model$Fields",
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // } // Path: compiler/src/test/java/com/contentful/vault/compiler/FieldTest.java import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; assert_().about(javaSource()).that(source) .processedWith(processors()) .failsToCompile() .withErrorContaining( "Invalid list type \"java.lang.Integer\" specified. (Test.list)"); } @Test public void testFieldsInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.SpaceHelper;", "import java.util.List;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String foo;", " @Field String bar;", " @Field String baz;", " @Field String baz2;", " @Field String b_a_z_123;", " }", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$Model$Fields",
readTestResource("FieldsInjection.java"));
contentful/vault
compiler/src/main/java/com/contentful/vault/compiler/SpaceInjection.java
// Path: core/src/main/java/com/contentful/vault/ModelHelper.java // public abstract class ModelHelper<T extends Resource> { // public abstract String getTableName(); // // public abstract List<FieldMeta> getFields(); // // public abstract List<String> getCreateStatements(SpaceHelper spaceHelper); // // public abstract T fromCursor(Cursor cursor); // // protected abstract boolean setField(T resource, String name, Object value); // // protected final <E extends Serializable> E fieldFromBlob(Class<E> clazz, Cursor cursor, // int columnIndex) { // byte[] blob = cursor.getBlob(columnIndex); // if (blob == null || blob.length == 0) { // return null; // } // E result = null; // Exception exception = null; // try { // result = BlobUtils.fromBlob(clazz, blob); // } catch (IOException | ClassNotFoundException e) { // exception = e; // } // if (exception != null) { // throw new RuntimeException(String.format("Failed creating BLOB from column %d of %s.", // columnIndex, getTableName()), exception); // } // return result; // } // // protected final void setContentType(T resource, String type) { // resource.setContentType(type); // } // } // // Path: core/src/main/java/com/contentful/vault/Resource.java // public abstract class Resource { // String remoteId; // // String createdAt; // // String updatedAt; // // String contentType; // // public String remoteId() { // return remoteId; // } // // public String createdAt() { // return createdAt; // } // // public String updatedAt() { // return updatedAt; // } // // void setRemoteId(String remoteId) { // this.remoteId = remoteId; // } // // void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // void setUpdatedAt(String updatedAt) { // this.updatedAt = updatedAt; // } // // void setContentType(String contentType) { // this.contentType = contentType; // } // // String contentType() { // return contentType; // } // // String getIdPrefix() { // return null; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Resource)) return false; // // Resource resource = (Resource) o; // String prefix = StringUtils.defaultString(getIdPrefix(), ""); // if (!prefix.equals(StringUtils.defaultString(resource.getIdPrefix(), ""))) return false; // return (prefix + remoteId()).equals(prefix + resource.remoteId()); // } // // @Override public int hashCode() { // return (StringUtils.defaultString(getIdPrefix(), "") + remoteId).hashCode(); // } // } // // Path: core/src/main/java/com/contentful/vault/SpaceHelper.java // public abstract class SpaceHelper { // public abstract String getDatabaseName(); // // public abstract int getDatabaseVersion(); // // public abstract Map<Class<?>, ModelHelper<?>> getModels(); // // public abstract Map<String, Class<? extends Resource>> getTypes(); // // public abstract String getCopyPath(); // // public abstract String getSpaceId(); // // public abstract List<String> getLocales(); // // public final String getDefaultLocale() { // return getLocales().get(0); // } // }
import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import com.contentful.vault.ModelHelper; import com.contentful.vault.Resource; import com.contentful.vault.SpaceHelper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; final class SpaceInjection extends Injection { private final List<ModelInjection> models; private final String dbName; private final int dbVersion; private final String copyPath; private final List<String> locales; private FieldSpec specModels; private FieldSpec specTypes; public SpaceInjection(String remoteId, ClassName className, TypeElement originatingElement, List<ModelInjection> models, String dbName, int dbVersion, String copyPath, List<String> locales) { super(remoteId, className, originatingElement); this.models = models; this.dbName = dbName; this.dbVersion = dbVersion; this.copyPath = copyPath; this.locales = locales; } @Override TypeSpec.Builder getTypeSpecBuilder() { TypeSpec.Builder builder = TypeSpec.classBuilder(className.simpleName())
// Path: core/src/main/java/com/contentful/vault/ModelHelper.java // public abstract class ModelHelper<T extends Resource> { // public abstract String getTableName(); // // public abstract List<FieldMeta> getFields(); // // public abstract List<String> getCreateStatements(SpaceHelper spaceHelper); // // public abstract T fromCursor(Cursor cursor); // // protected abstract boolean setField(T resource, String name, Object value); // // protected final <E extends Serializable> E fieldFromBlob(Class<E> clazz, Cursor cursor, // int columnIndex) { // byte[] blob = cursor.getBlob(columnIndex); // if (blob == null || blob.length == 0) { // return null; // } // E result = null; // Exception exception = null; // try { // result = BlobUtils.fromBlob(clazz, blob); // } catch (IOException | ClassNotFoundException e) { // exception = e; // } // if (exception != null) { // throw new RuntimeException(String.format("Failed creating BLOB from column %d of %s.", // columnIndex, getTableName()), exception); // } // return result; // } // // protected final void setContentType(T resource, String type) { // resource.setContentType(type); // } // } // // Path: core/src/main/java/com/contentful/vault/Resource.java // public abstract class Resource { // String remoteId; // // String createdAt; // // String updatedAt; // // String contentType; // // public String remoteId() { // return remoteId; // } // // public String createdAt() { // return createdAt; // } // // public String updatedAt() { // return updatedAt; // } // // void setRemoteId(String remoteId) { // this.remoteId = remoteId; // } // // void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // void setUpdatedAt(String updatedAt) { // this.updatedAt = updatedAt; // } // // void setContentType(String contentType) { // this.contentType = contentType; // } // // String contentType() { // return contentType; // } // // String getIdPrefix() { // return null; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Resource)) return false; // // Resource resource = (Resource) o; // String prefix = StringUtils.defaultString(getIdPrefix(), ""); // if (!prefix.equals(StringUtils.defaultString(resource.getIdPrefix(), ""))) return false; // return (prefix + remoteId()).equals(prefix + resource.remoteId()); // } // // @Override public int hashCode() { // return (StringUtils.defaultString(getIdPrefix(), "") + remoteId).hashCode(); // } // } // // Path: core/src/main/java/com/contentful/vault/SpaceHelper.java // public abstract class SpaceHelper { // public abstract String getDatabaseName(); // // public abstract int getDatabaseVersion(); // // public abstract Map<Class<?>, ModelHelper<?>> getModels(); // // public abstract Map<String, Class<? extends Resource>> getTypes(); // // public abstract String getCopyPath(); // // public abstract String getSpaceId(); // // public abstract List<String> getLocales(); // // public final String getDefaultLocale() { // return getLocales().get(0); // } // } // Path: compiler/src/main/java/com/contentful/vault/compiler/SpaceInjection.java import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import com.contentful.vault.ModelHelper; import com.contentful.vault.Resource; import com.contentful.vault.SpaceHelper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; final class SpaceInjection extends Injection { private final List<ModelInjection> models; private final String dbName; private final int dbVersion; private final String copyPath; private final List<String> locales; private FieldSpec specModels; private FieldSpec specTypes; public SpaceInjection(String remoteId, ClassName className, TypeElement originatingElement, List<ModelInjection> models, String dbName, int dbVersion, String copyPath, List<String> locales) { super(remoteId, className, originatingElement); this.models = models; this.dbName = dbName; this.dbVersion = dbVersion; this.copyPath = copyPath; this.locales = locales; } @Override TypeSpec.Builder getTypeSpecBuilder() { TypeSpec.Builder builder = TypeSpec.classBuilder(className.simpleName())
.superclass(ClassName.get(SpaceHelper.class))
contentful/vault
compiler/src/main/java/com/contentful/vault/compiler/SpaceInjection.java
// Path: core/src/main/java/com/contentful/vault/ModelHelper.java // public abstract class ModelHelper<T extends Resource> { // public abstract String getTableName(); // // public abstract List<FieldMeta> getFields(); // // public abstract List<String> getCreateStatements(SpaceHelper spaceHelper); // // public abstract T fromCursor(Cursor cursor); // // protected abstract boolean setField(T resource, String name, Object value); // // protected final <E extends Serializable> E fieldFromBlob(Class<E> clazz, Cursor cursor, // int columnIndex) { // byte[] blob = cursor.getBlob(columnIndex); // if (blob == null || blob.length == 0) { // return null; // } // E result = null; // Exception exception = null; // try { // result = BlobUtils.fromBlob(clazz, blob); // } catch (IOException | ClassNotFoundException e) { // exception = e; // } // if (exception != null) { // throw new RuntimeException(String.format("Failed creating BLOB from column %d of %s.", // columnIndex, getTableName()), exception); // } // return result; // } // // protected final void setContentType(T resource, String type) { // resource.setContentType(type); // } // } // // Path: core/src/main/java/com/contentful/vault/Resource.java // public abstract class Resource { // String remoteId; // // String createdAt; // // String updatedAt; // // String contentType; // // public String remoteId() { // return remoteId; // } // // public String createdAt() { // return createdAt; // } // // public String updatedAt() { // return updatedAt; // } // // void setRemoteId(String remoteId) { // this.remoteId = remoteId; // } // // void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // void setUpdatedAt(String updatedAt) { // this.updatedAt = updatedAt; // } // // void setContentType(String contentType) { // this.contentType = contentType; // } // // String contentType() { // return contentType; // } // // String getIdPrefix() { // return null; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Resource)) return false; // // Resource resource = (Resource) o; // String prefix = StringUtils.defaultString(getIdPrefix(), ""); // if (!prefix.equals(StringUtils.defaultString(resource.getIdPrefix(), ""))) return false; // return (prefix + remoteId()).equals(prefix + resource.remoteId()); // } // // @Override public int hashCode() { // return (StringUtils.defaultString(getIdPrefix(), "") + remoteId).hashCode(); // } // } // // Path: core/src/main/java/com/contentful/vault/SpaceHelper.java // public abstract class SpaceHelper { // public abstract String getDatabaseName(); // // public abstract int getDatabaseVersion(); // // public abstract Map<Class<?>, ModelHelper<?>> getModels(); // // public abstract Map<String, Class<? extends Resource>> getTypes(); // // public abstract String getCopyPath(); // // public abstract String getSpaceId(); // // public abstract List<String> getLocales(); // // public final String getDefaultLocale() { // return getLocales().get(0); // } // }
import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import com.contentful.vault.ModelHelper; import com.contentful.vault.Resource; import com.contentful.vault.SpaceHelper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List;
appendDbVersion(builder); appendModels(builder); appendTypes(builder); appendCopyPath(builder); appendSpaceId(builder); appendLocales(builder); appendConstructor(builder); return builder; } private void appendConstructor(TypeSpec.Builder builder) { MethodSpec.Builder ctor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC); for (ModelInjection model : models) { ClassName enclosingClassName = ClassName.get(model.originatingElement); ctor.addStatement("$N.put($L.class, new $L())", specModels, enclosingClassName, model.className); ctor.addStatement("$N.put($S, $L.class)", specTypes, model.remoteId, enclosingClassName); } builder.addMethod(ctor.build()); } private void appendTypes(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
// Path: core/src/main/java/com/contentful/vault/ModelHelper.java // public abstract class ModelHelper<T extends Resource> { // public abstract String getTableName(); // // public abstract List<FieldMeta> getFields(); // // public abstract List<String> getCreateStatements(SpaceHelper spaceHelper); // // public abstract T fromCursor(Cursor cursor); // // protected abstract boolean setField(T resource, String name, Object value); // // protected final <E extends Serializable> E fieldFromBlob(Class<E> clazz, Cursor cursor, // int columnIndex) { // byte[] blob = cursor.getBlob(columnIndex); // if (blob == null || blob.length == 0) { // return null; // } // E result = null; // Exception exception = null; // try { // result = BlobUtils.fromBlob(clazz, blob); // } catch (IOException | ClassNotFoundException e) { // exception = e; // } // if (exception != null) { // throw new RuntimeException(String.format("Failed creating BLOB from column %d of %s.", // columnIndex, getTableName()), exception); // } // return result; // } // // protected final void setContentType(T resource, String type) { // resource.setContentType(type); // } // } // // Path: core/src/main/java/com/contentful/vault/Resource.java // public abstract class Resource { // String remoteId; // // String createdAt; // // String updatedAt; // // String contentType; // // public String remoteId() { // return remoteId; // } // // public String createdAt() { // return createdAt; // } // // public String updatedAt() { // return updatedAt; // } // // void setRemoteId(String remoteId) { // this.remoteId = remoteId; // } // // void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // void setUpdatedAt(String updatedAt) { // this.updatedAt = updatedAt; // } // // void setContentType(String contentType) { // this.contentType = contentType; // } // // String contentType() { // return contentType; // } // // String getIdPrefix() { // return null; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Resource)) return false; // // Resource resource = (Resource) o; // String prefix = StringUtils.defaultString(getIdPrefix(), ""); // if (!prefix.equals(StringUtils.defaultString(resource.getIdPrefix(), ""))) return false; // return (prefix + remoteId()).equals(prefix + resource.remoteId()); // } // // @Override public int hashCode() { // return (StringUtils.defaultString(getIdPrefix(), "") + remoteId).hashCode(); // } // } // // Path: core/src/main/java/com/contentful/vault/SpaceHelper.java // public abstract class SpaceHelper { // public abstract String getDatabaseName(); // // public abstract int getDatabaseVersion(); // // public abstract Map<Class<?>, ModelHelper<?>> getModels(); // // public abstract Map<String, Class<? extends Resource>> getTypes(); // // public abstract String getCopyPath(); // // public abstract String getSpaceId(); // // public abstract List<String> getLocales(); // // public final String getDefaultLocale() { // return getLocales().get(0); // } // } // Path: compiler/src/main/java/com/contentful/vault/compiler/SpaceInjection.java import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import com.contentful.vault.ModelHelper; import com.contentful.vault.Resource; import com.contentful.vault.SpaceHelper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; appendDbVersion(builder); appendModels(builder); appendTypes(builder); appendCopyPath(builder); appendSpaceId(builder); appendLocales(builder); appendConstructor(builder); return builder; } private void appendConstructor(TypeSpec.Builder builder) { MethodSpec.Builder ctor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC); for (ModelInjection model : models) { ClassName enclosingClassName = ClassName.get(model.originatingElement); ctor.addStatement("$N.put($L.class, new $L())", specModels, enclosingClassName, model.className); ctor.addStatement("$N.put($S, $L.class)", specTypes, model.remoteId, enclosingClassName); } builder.addMethod(ctor.build()); } private void appendTypes(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
WildcardTypeName.subtypeOf(Resource.class));
contentful/vault
compiler/src/main/java/com/contentful/vault/compiler/SpaceInjection.java
// Path: core/src/main/java/com/contentful/vault/ModelHelper.java // public abstract class ModelHelper<T extends Resource> { // public abstract String getTableName(); // // public abstract List<FieldMeta> getFields(); // // public abstract List<String> getCreateStatements(SpaceHelper spaceHelper); // // public abstract T fromCursor(Cursor cursor); // // protected abstract boolean setField(T resource, String name, Object value); // // protected final <E extends Serializable> E fieldFromBlob(Class<E> clazz, Cursor cursor, // int columnIndex) { // byte[] blob = cursor.getBlob(columnIndex); // if (blob == null || blob.length == 0) { // return null; // } // E result = null; // Exception exception = null; // try { // result = BlobUtils.fromBlob(clazz, blob); // } catch (IOException | ClassNotFoundException e) { // exception = e; // } // if (exception != null) { // throw new RuntimeException(String.format("Failed creating BLOB from column %d of %s.", // columnIndex, getTableName()), exception); // } // return result; // } // // protected final void setContentType(T resource, String type) { // resource.setContentType(type); // } // } // // Path: core/src/main/java/com/contentful/vault/Resource.java // public abstract class Resource { // String remoteId; // // String createdAt; // // String updatedAt; // // String contentType; // // public String remoteId() { // return remoteId; // } // // public String createdAt() { // return createdAt; // } // // public String updatedAt() { // return updatedAt; // } // // void setRemoteId(String remoteId) { // this.remoteId = remoteId; // } // // void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // void setUpdatedAt(String updatedAt) { // this.updatedAt = updatedAt; // } // // void setContentType(String contentType) { // this.contentType = contentType; // } // // String contentType() { // return contentType; // } // // String getIdPrefix() { // return null; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Resource)) return false; // // Resource resource = (Resource) o; // String prefix = StringUtils.defaultString(getIdPrefix(), ""); // if (!prefix.equals(StringUtils.defaultString(resource.getIdPrefix(), ""))) return false; // return (prefix + remoteId()).equals(prefix + resource.remoteId()); // } // // @Override public int hashCode() { // return (StringUtils.defaultString(getIdPrefix(), "") + remoteId).hashCode(); // } // } // // Path: core/src/main/java/com/contentful/vault/SpaceHelper.java // public abstract class SpaceHelper { // public abstract String getDatabaseName(); // // public abstract int getDatabaseVersion(); // // public abstract Map<Class<?>, ModelHelper<?>> getModels(); // // public abstract Map<String, Class<? extends Resource>> getTypes(); // // public abstract String getCopyPath(); // // public abstract String getSpaceId(); // // public abstract List<String> getLocales(); // // public final String getDefaultLocale() { // return getLocales().get(0); // } // }
import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import com.contentful.vault.ModelHelper; import com.contentful.vault.Resource; import com.contentful.vault.SpaceHelper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List;
model.className); ctor.addStatement("$N.put($S, $L.class)", specTypes, model.remoteId, enclosingClassName); } builder.addMethod(ctor.build()); } private void appendTypes(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Resource.class)); specTypes = createMapWithInitializer("types", LinkedHashMap.class, ClassName.get(String.class), classTypeName) .addModifiers(Modifier.FINAL) .build(); builder.addField(specTypes); // Getter builder.addMethod(createGetterImpl(specTypes, "getTypes").build()); } private void appendModels(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class));
// Path: core/src/main/java/com/contentful/vault/ModelHelper.java // public abstract class ModelHelper<T extends Resource> { // public abstract String getTableName(); // // public abstract List<FieldMeta> getFields(); // // public abstract List<String> getCreateStatements(SpaceHelper spaceHelper); // // public abstract T fromCursor(Cursor cursor); // // protected abstract boolean setField(T resource, String name, Object value); // // protected final <E extends Serializable> E fieldFromBlob(Class<E> clazz, Cursor cursor, // int columnIndex) { // byte[] blob = cursor.getBlob(columnIndex); // if (blob == null || blob.length == 0) { // return null; // } // E result = null; // Exception exception = null; // try { // result = BlobUtils.fromBlob(clazz, blob); // } catch (IOException | ClassNotFoundException e) { // exception = e; // } // if (exception != null) { // throw new RuntimeException(String.format("Failed creating BLOB from column %d of %s.", // columnIndex, getTableName()), exception); // } // return result; // } // // protected final void setContentType(T resource, String type) { // resource.setContentType(type); // } // } // // Path: core/src/main/java/com/contentful/vault/Resource.java // public abstract class Resource { // String remoteId; // // String createdAt; // // String updatedAt; // // String contentType; // // public String remoteId() { // return remoteId; // } // // public String createdAt() { // return createdAt; // } // // public String updatedAt() { // return updatedAt; // } // // void setRemoteId(String remoteId) { // this.remoteId = remoteId; // } // // void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // void setUpdatedAt(String updatedAt) { // this.updatedAt = updatedAt; // } // // void setContentType(String contentType) { // this.contentType = contentType; // } // // String contentType() { // return contentType; // } // // String getIdPrefix() { // return null; // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Resource)) return false; // // Resource resource = (Resource) o; // String prefix = StringUtils.defaultString(getIdPrefix(), ""); // if (!prefix.equals(StringUtils.defaultString(resource.getIdPrefix(), ""))) return false; // return (prefix + remoteId()).equals(prefix + resource.remoteId()); // } // // @Override public int hashCode() { // return (StringUtils.defaultString(getIdPrefix(), "") + remoteId).hashCode(); // } // } // // Path: core/src/main/java/com/contentful/vault/SpaceHelper.java // public abstract class SpaceHelper { // public abstract String getDatabaseName(); // // public abstract int getDatabaseVersion(); // // public abstract Map<Class<?>, ModelHelper<?>> getModels(); // // public abstract Map<String, Class<? extends Resource>> getTypes(); // // public abstract String getCopyPath(); // // public abstract String getSpaceId(); // // public abstract List<String> getLocales(); // // public final String getDefaultLocale() { // return getLocales().get(0); // } // } // Path: compiler/src/main/java/com/contentful/vault/compiler/SpaceInjection.java import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import com.contentful.vault.ModelHelper; import com.contentful.vault.Resource; import com.contentful.vault.SpaceHelper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; model.className); ctor.addStatement("$N.put($S, $L.class)", specTypes, model.remoteId, enclosingClassName); } builder.addMethod(ctor.build()); } private void appendTypes(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Resource.class)); specTypes = createMapWithInitializer("types", LinkedHashMap.class, ClassName.get(String.class), classTypeName) .addModifiers(Modifier.FINAL) .build(); builder.addField(specTypes); // Getter builder.addMethod(createGetterImpl(specTypes, "getTypes").build()); } private void appendModels(TypeSpec.Builder builder) { // Field TypeName classTypeName = ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(Object.class));
TypeName helperTypeName = ParameterizedTypeName.get(ClassName.get(ModelHelper.class),
contentful/vault
compiler/src/test/java/com/contentful/vault/compiler/SpaceTest.java
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // }
import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class SpaceTest { @Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.Space;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String fText;", " @Field Boolean fBoolean;", " @Field Integer fInteger;", " @Field Double fDouble;", " @Field Map fMap;", " @Field Model fLinkedModel;", " @Field Asset fLinkedAsset;", " }", "", " @Space(value = \"sid\", models = Model.class, locales = { \"foo\", \"bar\" })", " static class AwesomeSpace {", " }", "}")); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeSpace$$SpaceHelper",
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // } // Path: compiler/src/test/java/com/contentful/vault/compiler/SpaceTest.java import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class SpaceTest { @Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.Space;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String fText;", " @Field Boolean fBoolean;", " @Field Integer fInteger;", " @Field Double fDouble;", " @Field Map fMap;", " @Field Model fLinkedModel;", " @Field Asset fLinkedAsset;", " }", "", " @Space(value = \"sid\", models = Model.class, locales = { \"foo\", \"bar\" })", " static class AwesomeSpace {", " }", "}")); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeSpace$$SpaceHelper",
readTestResource("SpaceInjection.java"));
contentful/vault
compiler/src/test/java/com/contentful/vault/compiler/SpaceTest.java
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // }
import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class SpaceTest { @Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.Space;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String fText;", " @Field Boolean fBoolean;", " @Field Integer fInteger;", " @Field Double fDouble;", " @Field Map fMap;", " @Field Model fLinkedModel;", " @Field Asset fLinkedAsset;", " }", "", " @Space(value = \"sid\", models = Model.class, locales = { \"foo\", \"bar\" })", " static class AwesomeSpace {", " }", "}")); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeSpace$$SpaceHelper", readTestResource("SpaceInjection.java")); assert_().about(javaSource()).that(source)
// Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static Iterable<? extends Processor> processors() { // return Arrays.asList(new Processor()); // } // // Path: compiler/src/test/java/com/contentful/vault/compiler/lib/TestUtils.java // public static String readTestResource(String fileName) throws IOException { // URL resource = TestUtils.class.getClassLoader().getResource(fileName); // return FileUtils.readFileToString(new File(resource.getPath()), Charset.defaultCharset()); // } // Path: compiler/src/test/java/com/contentful/vault/compiler/SpaceTest.java import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import org.junit.Test; import javax.tools.JavaFileObject; import static com.contentful.vault.compiler.lib.TestUtils.processors; import static com.contentful.vault.compiler.lib.TestUtils.readTestResource; import static com.google.common.truth.Truth.assert_; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; public class SpaceTest { @Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.Space;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String fText;", " @Field Boolean fBoolean;", " @Field Integer fInteger;", " @Field Double fDouble;", " @Field Map fMap;", " @Field Model fLinkedModel;", " @Field Asset fLinkedAsset;", " }", "", " @Space(value = \"sid\", models = Model.class, locales = { \"foo\", \"bar\" })", " static class AwesomeSpace {", " }", "}")); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeSpace$$SpaceHelper", readTestResource("SpaceInjection.java")); assert_().about(javaSource()).that(source)
.processedWith(processors())
contentful/vault
compiler/src/main/java/com/contentful/vault/compiler/FieldsInjection.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public abstract class BaseFields { // public static final String REMOTE_ID = "remote_id"; // // public static final String CREATED_AT = "created_at"; // // public static final String UPDATED_AT = "updated_at"; // } // // Path: core/src/main/java/com/contentful/vault/FieldMeta.java // public final class FieldMeta { // private final String id; // // private final String name; // // private final TypeMirror type; // // private final String sqliteType; // // private final String linkType; // // private final String arrayType; // // FieldMeta(Builder builder) { // this.id = builder.id; // this.name = builder.name; // this.type = builder.type; // this.sqliteType = builder.sqliteType; // this.linkType = builder.linkType; // this.arrayType = builder.arrayType; // } // // public String id() { // return id; // } // // public String name() { // return name; // } // // public TypeMirror type() { // return type; // } // // public String sqliteType() { // return sqliteType; // } // // public String linkType() { // return linkType; // } // // public String arrayType() { // return arrayType; // } // // public boolean isLink() { // return linkType != null; // } // // public boolean isArray() { // return arrayType != null; // } // // public boolean isArrayOfSymbols() { // return isArray() && String.class.getName().equals(arrayType); // } // // public boolean isArrayOfLinks() { // return isArray() && !isArrayOfSymbols(); // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof FieldMeta)) return false; // // FieldMeta fieldMeta = (FieldMeta) o; // // return id.equals(fieldMeta.id); // } // // @Override public int hashCode() { // return id.hashCode(); // } // // public static class Builder { // String id; // String name; // TypeMirror type; // String sqliteType; // String linkType; // String arrayType; // // public Builder setId(String id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setType(TypeMirror type) { // this.type = type; // return this; // } // // public Builder setSqliteType(String sqliteType) { // this.sqliteType = sqliteType; // return this; // } // // public Builder setLinkType(String linkType) { // this.linkType = linkType; // return this; // } // // public Builder setArrayType(String arrayType) { // this.arrayType = arrayType; // return this; // } // // public FieldMeta build() { // return new FieldMeta(this); // } // } // // public static Builder builder() { // return new Builder(); // } // }
import com.contentful.vault.BaseFields; import com.contentful.vault.FieldMeta; import com.google.common.base.CaseFormat; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.TypeSpec; import java.util.Set; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; final class FieldsInjection extends Injection { private final Set<FieldMeta> fields; public FieldsInjection(String remoteId, ClassName className, TypeElement originatingElement, Set<FieldMeta> fields) { super(remoteId, className, originatingElement); this.fields = fields; } @Override TypeSpec.Builder getTypeSpecBuilder() { TypeSpec.Builder builder = TypeSpec.classBuilder(className.simpleName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public abstract class BaseFields { // public static final String REMOTE_ID = "remote_id"; // // public static final String CREATED_AT = "created_at"; // // public static final String UPDATED_AT = "updated_at"; // } // // Path: core/src/main/java/com/contentful/vault/FieldMeta.java // public final class FieldMeta { // private final String id; // // private final String name; // // private final TypeMirror type; // // private final String sqliteType; // // private final String linkType; // // private final String arrayType; // // FieldMeta(Builder builder) { // this.id = builder.id; // this.name = builder.name; // this.type = builder.type; // this.sqliteType = builder.sqliteType; // this.linkType = builder.linkType; // this.arrayType = builder.arrayType; // } // // public String id() { // return id; // } // // public String name() { // return name; // } // // public TypeMirror type() { // return type; // } // // public String sqliteType() { // return sqliteType; // } // // public String linkType() { // return linkType; // } // // public String arrayType() { // return arrayType; // } // // public boolean isLink() { // return linkType != null; // } // // public boolean isArray() { // return arrayType != null; // } // // public boolean isArrayOfSymbols() { // return isArray() && String.class.getName().equals(arrayType); // } // // public boolean isArrayOfLinks() { // return isArray() && !isArrayOfSymbols(); // } // // @Override public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof FieldMeta)) return false; // // FieldMeta fieldMeta = (FieldMeta) o; // // return id.equals(fieldMeta.id); // } // // @Override public int hashCode() { // return id.hashCode(); // } // // public static class Builder { // String id; // String name; // TypeMirror type; // String sqliteType; // String linkType; // String arrayType; // // public Builder setId(String id) { // this.id = id; // return this; // } // // public Builder setName(String name) { // this.name = name; // return this; // } // // public Builder setType(TypeMirror type) { // this.type = type; // return this; // } // // public Builder setSqliteType(String sqliteType) { // this.sqliteType = sqliteType; // return this; // } // // public Builder setLinkType(String linkType) { // this.linkType = linkType; // return this; // } // // public Builder setArrayType(String arrayType) { // this.arrayType = arrayType; // return this; // } // // public FieldMeta build() { // return new FieldMeta(this); // } // } // // public static Builder builder() { // return new Builder(); // } // } // Path: compiler/src/main/java/com/contentful/vault/compiler/FieldsInjection.java import com.contentful.vault.BaseFields; import com.contentful.vault.FieldMeta; import com.google.common.base.CaseFormat; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.TypeSpec; import java.util.Set; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault.compiler; final class FieldsInjection extends Injection { private final Set<FieldMeta> fields; public FieldsInjection(String remoteId, ClassName className, TypeElement originatingElement, Set<FieldMeta> fields) { super(remoteId, className, originatingElement); this.fields = fields; } @Override TypeSpec.Builder getTypeSpecBuilder() { TypeSpec.Builder builder = TypeSpec.classBuilder(className.simpleName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.superclass(BaseFields.class);
contentful/vault
core/src/main/java/com/contentful/vault/AutoEscapeValues.java
// Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // }
import android.content.ContentValues; import java.util.Map; import java.util.Set; import static com.contentful.vault.Sql.escape;
/* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; final class AutoEscapeValues { private final ContentValues values = new ContentValues(); public void put(String key, String value) {
// Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // Path: core/src/main/java/com/contentful/vault/AutoEscapeValues.java import android.content.ContentValues; import java.util.Map; import java.util.Set; import static com.contentful.vault.Sql.escape; /* * Copyright (C) 2018 Contentful GmbH * * 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 com.contentful.vault; final class AutoEscapeValues { private final ContentValues values = new ContentValues(); public void put(String key, String value) {
values.put(escape(key), value);
contentful/vault
core/src/main/java/com/contentful/vault/QueryResolver.java
// Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.text.TextUtils.join; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
} private Map<String, Resource> cacheForType(Class<T> type) { if (type == Asset.class) { return assets; } return entries; } private void resolveLinks(List<T> resources, String locale) { LinkResolver resolver = new LinkResolver(query, assets, entries); for (T resource : resources) { resolver.resolveLinks(resource, helperForEntry(resource).getFields(), locale); } } private ModelHelper<?> helperForEntry(T resource) { SpaceHelper spaceHelper = vault.getSqliteHelper().getSpaceHelper(); Class<?> modelType = spaceHelper.getTypes().get(resource.contentType()); return spaceHelper.getModels().get(modelType); } private Cursor cursorFromQuery(AbsQuery<T, ?> query, String locale) { String[] orderArray = query.params().order(); String order = null; if (orderArray != null && orderArray.length > 0) { order = join(", ", orderArray); } String tableName; if (query.type() == Asset.class) {
// Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/QueryResolver.java import android.database.Cursor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.text.TextUtils.join; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; } private Map<String, Resource> cacheForType(Class<T> type) { if (type == Asset.class) { return assets; } return entries; } private void resolveLinks(List<T> resources, String locale) { LinkResolver resolver = new LinkResolver(query, assets, entries); for (T resource : resources) { resolver.resolveLinks(resource, helperForEntry(resource).getFields(), locale); } } private ModelHelper<?> helperForEntry(T resource) { SpaceHelper spaceHelper = vault.getSqliteHelper().getSpaceHelper(); Class<?> modelType = spaceHelper.getTypes().get(resource.contentType()); return spaceHelper.getModels().get(modelType); } private Cursor cursorFromQuery(AbsQuery<T, ?> query, String locale) { String[] orderArray = query.params().order(); String order = null; if (orderArray != null && orderArray.length > 0) { order = join(", ", orderArray); } String tableName; if (query.type() == Asset.class) {
tableName = TABLE_ASSETS;
contentful/vault
core/src/main/java/com/contentful/vault/QueryResolver.java
// Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.text.TextUtils.join; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
LinkResolver resolver = new LinkResolver(query, assets, entries); for (T resource : resources) { resolver.resolveLinks(resource, helperForEntry(resource).getFields(), locale); } } private ModelHelper<?> helperForEntry(T resource) { SpaceHelper spaceHelper = vault.getSqliteHelper().getSpaceHelper(); Class<?> modelType = spaceHelper.getTypes().get(resource.contentType()); return spaceHelper.getModels().get(modelType); } private Cursor cursorFromQuery(AbsQuery<T, ?> query, String locale) { String[] orderArray = query.params().order(); String order = null; if (orderArray != null && orderArray.length > 0) { order = join(", ", orderArray); } String tableName; if (query.type() == Asset.class) { tableName = TABLE_ASSETS; } else { tableName = query.vault() .getSqliteHelper() .getSpaceHelper() .getModels() .get(query.type()) .getTableName(); } return query.vault().getReadableDatabase().query(
// Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/QueryResolver.java import android.database.Cursor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.text.TextUtils.join; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; LinkResolver resolver = new LinkResolver(query, assets, entries); for (T resource : resources) { resolver.resolveLinks(resource, helperForEntry(resource).getFields(), locale); } } private ModelHelper<?> helperForEntry(T resource) { SpaceHelper spaceHelper = vault.getSqliteHelper().getSpaceHelper(); Class<?> modelType = spaceHelper.getTypes().get(resource.contentType()); return spaceHelper.getModels().get(modelType); } private Cursor cursorFromQuery(AbsQuery<T, ?> query, String locale) { String[] orderArray = query.params().order(); String order = null; if (orderArray != null && orderArray.length > 0) { order = join(", ", orderArray); } String tableName; if (query.type() == Asset.class) { tableName = TABLE_ASSETS; } else { tableName = query.vault() .getSqliteHelper() .getSpaceHelper() .getModels() .get(query.type()) .getTableName(); } return query.vault().getReadableDatabase().query(
escape(localizeName(tableName, locale)),
contentful/vault
core/src/main/java/com/contentful/vault/QueryResolver.java
// Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.database.Cursor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.text.TextUtils.join; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
LinkResolver resolver = new LinkResolver(query, assets, entries); for (T resource : resources) { resolver.resolveLinks(resource, helperForEntry(resource).getFields(), locale); } } private ModelHelper<?> helperForEntry(T resource) { SpaceHelper spaceHelper = vault.getSqliteHelper().getSpaceHelper(); Class<?> modelType = spaceHelper.getTypes().get(resource.contentType()); return spaceHelper.getModels().get(modelType); } private Cursor cursorFromQuery(AbsQuery<T, ?> query, String locale) { String[] orderArray = query.params().order(); String order = null; if (orderArray != null && orderArray.length > 0) { order = join(", ", orderArray); } String tableName; if (query.type() == Asset.class) { tableName = TABLE_ASSETS; } else { tableName = query.vault() .getSqliteHelper() .getSpaceHelper() .getModels() .get(query.type()) .getTableName(); } return query.vault().getReadableDatabase().query(
// Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/QueryResolver.java import android.database.Cursor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.text.TextUtils.join; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; LinkResolver resolver = new LinkResolver(query, assets, entries); for (T resource : resources) { resolver.resolveLinks(resource, helperForEntry(resource).getFields(), locale); } } private ModelHelper<?> helperForEntry(T resource) { SpaceHelper spaceHelper = vault.getSqliteHelper().getSpaceHelper(); Class<?> modelType = spaceHelper.getTypes().get(resource.contentType()); return spaceHelper.getModels().get(modelType); } private Cursor cursorFromQuery(AbsQuery<T, ?> query, String locale) { String[] orderArray = query.params().order(); String order = null; if (orderArray != null && orderArray.length > 0) { order = join(", ", orderArray); } String tableName; if (query.type() == Asset.class) { tableName = TABLE_ASSETS; } else { tableName = query.vault() .getSqliteHelper() .getSpaceHelper() .getModels() .get(query.type()) .getTableName(); } return query.vault().getReadableDatabase().query(
escape(localizeName(tableName, locale)),
nhaarman/ListViewAnimations
lib-core/src/main/java/com/nhaarman/listviewanimations/BaseAdapterDecorator.java
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/Insertable.java // public interface Insertable<T> { // // /** // * Will be called to insert given {@code item} at given {@code index} in the list. // * // * @param index the index the new item should be inserted at // * @param item the item to insert // */ // void add(int index, @NonNull T item); // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapper.java // public interface ListViewWrapper { // // @NonNull // ViewGroup getListView(); // // @Nullable // View getChildAt(int index); // // int getFirstVisiblePosition(); // // int getLastVisiblePosition(); // // int getCount(); // // int getChildCount(); // // int getHeaderViewsCount(); // // int getPositionForView(@NonNull View view); // // @Nullable // ListAdapter getAdapter(); // // void smoothScrollBy(int distance, int duration); // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapperSetter.java // public interface ListViewWrapperSetter { // // void setListViewWrapper(@NonNull final ListViewWrapper listViewWrapper); // }
import android.database.DataSetObserver; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.SectionIndexer; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import com.nhaarman.listviewanimations.util.Insertable; import com.nhaarman.listviewanimations.util.ListViewWrapper; import com.nhaarman.listviewanimations.util.ListViewWrapperSetter; import com.nhaarman.listviewanimations.util.Swappable;
/* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations; /** * A decorator class that enables decoration of an instance of the {@link BaseAdapter} class. * <p/> * Classes extending this class can override methods and provide extra functionality before or after calling the super method. */ public abstract class BaseAdapterDecorator extends BaseAdapter implements SectionIndexer, Swappable, Insertable, ListViewWrapperSetter { /** * The {@link android.widget.BaseAdapter} this {@code BaseAdapterDecorator} decorates. */ @NonNull private final BaseAdapter mDecoratedBaseAdapter; /** * The {@link com.nhaarman.listviewanimations.util.ListViewWrapper} containing the ListView this {@code BaseAdapterDecorator} will be bound to. */ @Nullable
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/Insertable.java // public interface Insertable<T> { // // /** // * Will be called to insert given {@code item} at given {@code index} in the list. // * // * @param index the index the new item should be inserted at // * @param item the item to insert // */ // void add(int index, @NonNull T item); // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapper.java // public interface ListViewWrapper { // // @NonNull // ViewGroup getListView(); // // @Nullable // View getChildAt(int index); // // int getFirstVisiblePosition(); // // int getLastVisiblePosition(); // // int getCount(); // // int getChildCount(); // // int getHeaderViewsCount(); // // int getPositionForView(@NonNull View view); // // @Nullable // ListAdapter getAdapter(); // // void smoothScrollBy(int distance, int duration); // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapperSetter.java // public interface ListViewWrapperSetter { // // void setListViewWrapper(@NonNull final ListViewWrapper listViewWrapper); // } // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/BaseAdapterDecorator.java import android.database.DataSetObserver; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.SectionIndexer; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import com.nhaarman.listviewanimations.util.Insertable; import com.nhaarman.listviewanimations.util.ListViewWrapper; import com.nhaarman.listviewanimations.util.ListViewWrapperSetter; import com.nhaarman.listviewanimations.util.Swappable; /* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations; /** * A decorator class that enables decoration of an instance of the {@link BaseAdapter} class. * <p/> * Classes extending this class can override methods and provide extra functionality before or after calling the super method. */ public abstract class BaseAdapterDecorator extends BaseAdapter implements SectionIndexer, Swappable, Insertable, ListViewWrapperSetter { /** * The {@link android.widget.BaseAdapter} this {@code BaseAdapterDecorator} decorates. */ @NonNull private final BaseAdapter mDecoratedBaseAdapter; /** * The {@link com.nhaarman.listviewanimations.util.ListViewWrapper} containing the ListView this {@code BaseAdapterDecorator} will be bound to. */ @Nullable
private ListViewWrapper mListViewWrapper;
nhaarman/ListViewAnimations
lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTestActivity.java
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // }
import com.nhaarman.listviewanimations.ArrayAdapter; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Debug; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView;
for (int i = 0; i < 20; i++) { integers.add(i); } ListAdapter myListAdapter = new MyListAdapter(this, integers); mListView.setAdapter(myListAdapter); setContentView(mListView); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int[] location = new int[2]; mListView.getLocationOnScreen(location); ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); boolean handled = mListView.onInterceptTouchEvent(ev); if (!handled) { handled = mListView.dispatchTouchEvent(ev); } if (!handled) { handled = onTouchEvent(ev); } return handled; } public AbsListView getAbsListView() { return mListView; }
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // } // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTestActivity.java import com.nhaarman.listviewanimations.ArrayAdapter; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Debug; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; for (int i = 0; i < 20; i++) { integers.add(i); } ListAdapter myListAdapter = new MyListAdapter(this, integers); mListView.setAdapter(myListAdapter); setContentView(mListView); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int[] location = new int[2]; mListView.getLocationOnScreen(location); ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); boolean handled = mListView.onInterceptTouchEvent(ev); if (!handled) { handled = mListView.dispatchTouchEvent(ev); } if (!handled) { handled = onTouchEvent(ev); } return handled; } public AbsListView getAbsListView() { return mListView; }
private static class MyListAdapter extends ArrayAdapter<Integer> {
nhaarman/ListViewAnimations
example/src/main/java/com/haarman/listviewanimations/gridview/GridViewAdapter.java
// Path: example/src/main/java/com/haarman/listviewanimations/util/BitmapCache.java // public class BitmapCache extends LruCache<Integer, Bitmap> { // // private static final int KILO = 1024; // private static final int MEMORY_FACTOR = 2 * KILO; // // public BitmapCache() { // super((int) (Runtime.getRuntime().maxMemory() / MEMORY_FACTOR)); // } // // @Override // protected int sizeOf(final Integer key, final Bitmap value) { // return value.getRowBytes() * value.getHeight() / KILO; // } // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.haarman.listviewanimations.R; import com.haarman.listviewanimations.util.BitmapCache; import com.nhaarman.listviewanimations.ArrayAdapter;
/* * Copyright 2014 Niek Haarman * * 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 com.haarman.listviewanimations.gridview; public class GridViewAdapter extends ArrayAdapter<Integer> { private final Context mContext;
// Path: example/src/main/java/com/haarman/listviewanimations/util/BitmapCache.java // public class BitmapCache extends LruCache<Integer, Bitmap> { // // private static final int KILO = 1024; // private static final int MEMORY_FACTOR = 2 * KILO; // // public BitmapCache() { // super((int) (Runtime.getRuntime().maxMemory() / MEMORY_FACTOR)); // } // // @Override // protected int sizeOf(final Integer key, final Bitmap value) { // return value.getRowBytes() * value.getHeight() / KILO; // } // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // } // Path: example/src/main/java/com/haarman/listviewanimations/gridview/GridViewAdapter.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.haarman.listviewanimations.R; import com.haarman.listviewanimations.util.BitmapCache; import com.nhaarman.listviewanimations.ArrayAdapter; /* * Copyright 2014 Niek Haarman * * 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 com.haarman.listviewanimations.gridview; public class GridViewAdapter extends ArrayAdapter<Integer> { private final Context mContext;
private final BitmapCache mMemoryCache;
nhaarman/ListViewAnimations
example/src/main/java/com/haarman/listviewanimations/googlecards/GoogleCardsAdapter.java
// Path: example/src/main/java/com/haarman/listviewanimations/util/BitmapCache.java // public class BitmapCache extends LruCache<Integer, Bitmap> { // // private static final int KILO = 1024; // private static final int MEMORY_FACTOR = 2 * KILO; // // public BitmapCache() { // super((int) (Runtime.getRuntime().maxMemory() / MEMORY_FACTOR)); // } // // @Override // protected int sizeOf(final Integer key, final Bitmap value) { // return value.getRowBytes() * value.getHeight() / KILO; // } // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.haarman.listviewanimations.R; import com.haarman.listviewanimations.util.BitmapCache; import com.nhaarman.listviewanimations.ArrayAdapter;
/* * Copyright 2014 Niek Haarman * * 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 com.haarman.listviewanimations.googlecards; public class GoogleCardsAdapter extends ArrayAdapter<Integer> { private final Context mContext;
// Path: example/src/main/java/com/haarman/listviewanimations/util/BitmapCache.java // public class BitmapCache extends LruCache<Integer, Bitmap> { // // private static final int KILO = 1024; // private static final int MEMORY_FACTOR = 2 * KILO; // // public BitmapCache() { // super((int) (Runtime.getRuntime().maxMemory() / MEMORY_FACTOR)); // } // // @Override // protected int sizeOf(final Integer key, final Bitmap value) { // return value.getRowBytes() * value.getHeight() / KILO; // } // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // } // Path: example/src/main/java/com/haarman/listviewanimations/googlecards/GoogleCardsAdapter.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.haarman.listviewanimations.R; import com.haarman.listviewanimations.util.BitmapCache; import com.nhaarman.listviewanimations.ArrayAdapter; /* * Copyright 2014 Niek Haarman * * 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 com.haarman.listviewanimations.googlecards; public class GoogleCardsAdapter extends ArrayAdapter<Integer> { private final Context mContext;
private final BitmapCache mMemoryCache;
nhaarman/ListViewAnimations
lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/dragdrop/DynamicListViewTestActivity.java
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // }
import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ListAdapter; import android.widget.TextView; import com.nhaarman.listviewanimations.ArrayAdapter; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView;
for (int i = 0; i < 20; i++) { integers.add(i); } ListAdapter myListAdapter = new MyListAdapter(this, integers); mListView.setAdapter(myListAdapter); setContentView(mListView); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int[] location = new int[2]; mListView.getLocationOnScreen(location); ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); boolean handled = mListView.onInterceptTouchEvent(ev); if (!handled) { handled = mListView.dispatchTouchEvent(ev); } if (!handled) { handled = onTouchEvent(ev); } return handled; } public DynamicListView getDynamicListView() { return mListView; }
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/ArrayAdapter.java // @SuppressWarnings("UnusedDeclaration") // public abstract class ArrayAdapter<T> extends BaseAdapter implements Swappable, Insertable<T> { // // @NonNull // private final List<T> mItems; // // private BaseAdapter mDataSetChangedSlavedAdapter; // // /** // * Creates a new ArrayAdapter with an empty {@code List}. // */ // protected ArrayAdapter() { // this(null); // } // // /** // * Creates a new ArrayAdapter, using (a copy of) given {@code List}, or an empty {@code List} if objects = null. // */ // protected ArrayAdapter(@Nullable final List<T> objects) { // if (objects != null) { // mItems = objects; // } else { // mItems = new ArrayList<>(); // } // } // // @Override // public int getCount() { // return mItems.size(); // } // // @Override // public long getItemId(final int position) { // return position; // } // // @Override // @NonNull // public T getItem(final int position) { // return mItems.get(position); // } // // /** // * Returns the items. // */ // @NonNull // public List<T> getItems() { // return mItems; // } // // /** // * Appends the specified element to the end of the {@code List}. // * // * @param object the object to add. // * // * @return always true. // */ // public boolean add(@NonNull final T object) { // boolean result = mItems.add(object); // notifyDataSetChanged(); // return result; // } // // @Override // public void add(final int index, @NonNull final T item) { // mItems.add(index, item); // notifyDataSetChanged(); // } // // /** // * Adds the objects in the specified collection to the end of this List. The objects are added in the order in which they are returned from the collection's iterator. // * // * @param collection the collection of objects. // * // * @return {@code true} if this {@code List} is modified, {@code false} otherwise. // */ // public boolean addAll(@NonNull final Collection<? extends T> collection) { // boolean result = mItems.addAll(collection); // notifyDataSetChanged(); // return result; // } // // public boolean contains(final T object) { // return mItems.contains(object); // } // // public void clear() { // mItems.clear(); // notifyDataSetChanged(); // } // // public boolean remove(@NonNull final Object object) { // boolean result = mItems.remove(object); // notifyDataSetChanged(); // return result; // } // // @NonNull // public T remove(final int location) { // T result = mItems.remove(location); // notifyDataSetChanged(); // return result; // } // // @Override // public void swapItems(final int positionOne, final int positionTwo) { // T firstItem = mItems.set(positionOne, getItem(positionTwo)); // notifyDataSetChanged(); // mItems.set(positionTwo, firstItem); // } // // public void propagateNotifyDataSetChanged(@NonNull final BaseAdapter slavedAdapter) { // mDataSetChangedSlavedAdapter = slavedAdapter; // } // // @Override // public void notifyDataSetChanged() { // super.notifyDataSetChanged(); // if (mDataSetChangedSlavedAdapter != null) { // mDataSetChangedSlavedAdapter.notifyDataSetChanged(); // } // } // } // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/dragdrop/DynamicListViewTestActivity.java import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ListAdapter; import android.widget.TextView; import com.nhaarman.listviewanimations.ArrayAdapter; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView; for (int i = 0; i < 20; i++) { integers.add(i); } ListAdapter myListAdapter = new MyListAdapter(this, integers); mListView.setAdapter(myListAdapter); setContentView(mListView); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int[] location = new int[2]; mListView.getLocationOnScreen(location); ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); boolean handled = mListView.onInterceptTouchEvent(ev); if (!handled) { handled = mListView.dispatchTouchEvent(ev); } if (!handled) { handled = onTouchEvent(ev); } return handled; } public DynamicListView getDynamicListView() { return mListView; }
private static class MyListAdapter extends ArrayAdapter<Integer> {
nhaarman/ListViewAnimations
lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/undo/SwipeUndoTouchListenerTest.java
// Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTestActivity.java // public class SwipeTouchListenerTestActivity extends Activity { // // private ListView mListView; // // @Override // protected void onCreate(final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Window window = getWindow(); // window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // // mListView = new ListView(this); // List<Integer> integers = new ArrayList<Integer>(); // for (int i = 0; i < 20; i++) { // integers.add(i); // } // // ListAdapter myListAdapter = new MyListAdapter(this, integers); // mListView.setAdapter(myListAdapter); // // setContentView(mListView); // } // // @Override // public boolean dispatchTouchEvent(MotionEvent ev) { // int[] location = new int[2]; // mListView.getLocationOnScreen(location); // // ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); // boolean handled = mListView.onInterceptTouchEvent(ev); // if (!handled) { // handled = mListView.dispatchTouchEvent(ev); // } // if (!handled) { // handled = onTouchEvent(ev); // } // return handled; // } // // public AbsListView getAbsListView() { // return mListView; // } // // private static class MyListAdapter extends ArrayAdapter<Integer> { // // private final Context mContext; // // MyListAdapter(final Context context, final List<Integer> items) { // super(items); // mContext = context; // } // // @Override // public long getItemId(final int location) { // return getItem(location).hashCode(); // } // // @Override // public boolean hasStableIds() { // return true; // } // // @Override // public View getView(final int position, final View convertView, final ViewGroup parent) { // TextView view = (TextView) convertView; // if (view == null) { // view = new TextView(mContext); // view.setTextSize(30); // } // // view.setText("This is row number " + getItem(position)); // return view; // } // } // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEvents(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEvents(instrumentation, createSwipeMotionEvents(absListView, position)); // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEventsAndWait(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEventsAndWait(instrumentation, createSwipeMotionEvents(absListView, position)); // }
import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.widget.AbsListView; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListenerTestActivity; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import org.mockito.*; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEvents; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait; import static org.mockito.AdditionalMatchers.*; import static org.mockito.Mockito.*;
/* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo; public class SwipeUndoTouchListenerTest extends ActivityInstrumentationTestCase2<SwipeTouchListenerTestActivity> { /** * An Activity hosting a ListView with items. */ private SwipeTouchListenerTestActivity mActivity; /** * The AbsListView that is hosted in mActivity. */ private AbsListView mAbsListView; @Mock private UndoCallback mUndoCallback; private SwipeUndoTouchListener mSwipeUndoTouchListener; public SwipeUndoTouchListenerTest() { super(SwipeTouchListenerTestActivity.class); } @Override public void setUp() throws Exception { super.setUp(); MockitoAnnotations.initMocks(this); when(mUndoCallback.getUndoView(any(View.class))).thenReturn(new View(getActivity())); when(mUndoCallback.getPrimaryView(any(View.class))).thenReturn(new View(getActivity())); mActivity = getActivity(); mAbsListView = mActivity.getAbsListView(); mSwipeUndoTouchListener = new SwipeUndoTouchListener(new AbsListViewWrapper(mAbsListView), mUndoCallback); mAbsListView.setOnTouchListener(mSwipeUndoTouchListener); getInstrumentation().waitForIdleSync(); } /** * Tests whether swiping an item once triggers UndoCallback#onUndoShown. */ public void testUndoShown() throws InterruptedException {
// Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTestActivity.java // public class SwipeTouchListenerTestActivity extends Activity { // // private ListView mListView; // // @Override // protected void onCreate(final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Window window = getWindow(); // window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // // mListView = new ListView(this); // List<Integer> integers = new ArrayList<Integer>(); // for (int i = 0; i < 20; i++) { // integers.add(i); // } // // ListAdapter myListAdapter = new MyListAdapter(this, integers); // mListView.setAdapter(myListAdapter); // // setContentView(mListView); // } // // @Override // public boolean dispatchTouchEvent(MotionEvent ev) { // int[] location = new int[2]; // mListView.getLocationOnScreen(location); // // ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); // boolean handled = mListView.onInterceptTouchEvent(ev); // if (!handled) { // handled = mListView.dispatchTouchEvent(ev); // } // if (!handled) { // handled = onTouchEvent(ev); // } // return handled; // } // // public AbsListView getAbsListView() { // return mListView; // } // // private static class MyListAdapter extends ArrayAdapter<Integer> { // // private final Context mContext; // // MyListAdapter(final Context context, final List<Integer> items) { // super(items); // mContext = context; // } // // @Override // public long getItemId(final int location) { // return getItem(location).hashCode(); // } // // @Override // public boolean hasStableIds() { // return true; // } // // @Override // public View getView(final int position, final View convertView, final ViewGroup parent) { // TextView view = (TextView) convertView; // if (view == null) { // view = new TextView(mContext); // view.setTextSize(30); // } // // view.setText("This is row number " + getItem(position)); // return view; // } // } // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEvents(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEvents(instrumentation, createSwipeMotionEvents(absListView, position)); // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEventsAndWait(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEventsAndWait(instrumentation, createSwipeMotionEvents(absListView, position)); // } // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/undo/SwipeUndoTouchListenerTest.java import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.widget.AbsListView; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListenerTestActivity; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import org.mockito.*; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEvents; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait; import static org.mockito.AdditionalMatchers.*; import static org.mockito.Mockito.*; /* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo; public class SwipeUndoTouchListenerTest extends ActivityInstrumentationTestCase2<SwipeTouchListenerTestActivity> { /** * An Activity hosting a ListView with items. */ private SwipeTouchListenerTestActivity mActivity; /** * The AbsListView that is hosted in mActivity. */ private AbsListView mAbsListView; @Mock private UndoCallback mUndoCallback; private SwipeUndoTouchListener mSwipeUndoTouchListener; public SwipeUndoTouchListenerTest() { super(SwipeTouchListenerTestActivity.class); } @Override public void setUp() throws Exception { super.setUp(); MockitoAnnotations.initMocks(this); when(mUndoCallback.getUndoView(any(View.class))).thenReturn(new View(getActivity())); when(mUndoCallback.getPrimaryView(any(View.class))).thenReturn(new View(getActivity())); mActivity = getActivity(); mAbsListView = mActivity.getAbsListView(); mSwipeUndoTouchListener = new SwipeUndoTouchListener(new AbsListViewWrapper(mAbsListView), mUndoCallback); mAbsListView.setOnTouchListener(mSwipeUndoTouchListener); getInstrumentation().waitForIdleSync(); } /** * Tests whether swiping an item once triggers UndoCallback#onUndoShown. */ public void testUndoShown() throws InterruptedException {
dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 0);
nhaarman/ListViewAnimations
lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/undo/SwipeUndoTouchListenerTest.java
// Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTestActivity.java // public class SwipeTouchListenerTestActivity extends Activity { // // private ListView mListView; // // @Override // protected void onCreate(final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Window window = getWindow(); // window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // // mListView = new ListView(this); // List<Integer> integers = new ArrayList<Integer>(); // for (int i = 0; i < 20; i++) { // integers.add(i); // } // // ListAdapter myListAdapter = new MyListAdapter(this, integers); // mListView.setAdapter(myListAdapter); // // setContentView(mListView); // } // // @Override // public boolean dispatchTouchEvent(MotionEvent ev) { // int[] location = new int[2]; // mListView.getLocationOnScreen(location); // // ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); // boolean handled = mListView.onInterceptTouchEvent(ev); // if (!handled) { // handled = mListView.dispatchTouchEvent(ev); // } // if (!handled) { // handled = onTouchEvent(ev); // } // return handled; // } // // public AbsListView getAbsListView() { // return mListView; // } // // private static class MyListAdapter extends ArrayAdapter<Integer> { // // private final Context mContext; // // MyListAdapter(final Context context, final List<Integer> items) { // super(items); // mContext = context; // } // // @Override // public long getItemId(final int location) { // return getItem(location).hashCode(); // } // // @Override // public boolean hasStableIds() { // return true; // } // // @Override // public View getView(final int position, final View convertView, final ViewGroup parent) { // TextView view = (TextView) convertView; // if (view == null) { // view = new TextView(mContext); // view.setTextSize(30); // } // // view.setText("This is row number " + getItem(position)); // return view; // } // } // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEvents(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEvents(instrumentation, createSwipeMotionEvents(absListView, position)); // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEventsAndWait(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEventsAndWait(instrumentation, createSwipeMotionEvents(absListView, position)); // }
import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.widget.AbsListView; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListenerTestActivity; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import org.mockito.*; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEvents; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait; import static org.mockito.AdditionalMatchers.*; import static org.mockito.Mockito.*;
verify(mUndoCallback, never()).onDismiss(any(View.class), anyInt()); dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 0); verify(mUndoCallback).onDismiss(any(View.class), eq(0)); } /** * Tests whether swiping multiple items triggers onUndoShown, but not onDismiss. */ public void testMultipleUndo() throws InterruptedException { dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 0); verify(mUndoCallback).onUndoShown(any(View.class), eq(0)); dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 1); verify(mUndoCallback).onUndoShown(any(View.class), eq(1)); dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 2); verify(mUndoCallback).onUndoShown(any(View.class), eq(2)); verify(mUndoCallback, never()).onDismiss(any(View.class), anyInt()); } /** * Tests whether multiple dismisses are correctly handled. */ public void testMultipleDismisses() throws InterruptedException {
// Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTestActivity.java // public class SwipeTouchListenerTestActivity extends Activity { // // private ListView mListView; // // @Override // protected void onCreate(final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Window window = getWindow(); // window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // // mListView = new ListView(this); // List<Integer> integers = new ArrayList<Integer>(); // for (int i = 0; i < 20; i++) { // integers.add(i); // } // // ListAdapter myListAdapter = new MyListAdapter(this, integers); // mListView.setAdapter(myListAdapter); // // setContentView(mListView); // } // // @Override // public boolean dispatchTouchEvent(MotionEvent ev) { // int[] location = new int[2]; // mListView.getLocationOnScreen(location); // // ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), ev.getX() - location[0], ev.getY() - location[1], ev.getMetaState()); // boolean handled = mListView.onInterceptTouchEvent(ev); // if (!handled) { // handled = mListView.dispatchTouchEvent(ev); // } // if (!handled) { // handled = onTouchEvent(ev); // } // return handled; // } // // public AbsListView getAbsListView() { // return mListView; // } // // private static class MyListAdapter extends ArrayAdapter<Integer> { // // private final Context mContext; // // MyListAdapter(final Context context, final List<Integer> items) { // super(items); // mContext = context; // } // // @Override // public long getItemId(final int location) { // return getItem(location).hashCode(); // } // // @Override // public boolean hasStableIds() { // return true; // } // // @Override // public View getView(final int position, final View convertView, final ViewGroup parent) { // TextView view = (TextView) convertView; // if (view == null) { // view = new TextView(mContext); // view.setTextSize(30); // } // // view.setText("This is row number " + getItem(position)); // return view; // } // } // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEvents(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEvents(instrumentation, createSwipeMotionEvents(absListView, position)); // } // // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEventsAndWait(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEventsAndWait(instrumentation, createSwipeMotionEvents(absListView, position)); // } // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/undo/SwipeUndoTouchListenerTest.java import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.widget.AbsListView; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeTouchListenerTestActivity; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import org.mockito.*; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEvents; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait; import static org.mockito.AdditionalMatchers.*; import static org.mockito.Mockito.*; verify(mUndoCallback, never()).onDismiss(any(View.class), anyInt()); dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 0); verify(mUndoCallback).onDismiss(any(View.class), eq(0)); } /** * Tests whether swiping multiple items triggers onUndoShown, but not onDismiss. */ public void testMultipleUndo() throws InterruptedException { dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 0); verify(mUndoCallback).onUndoShown(any(View.class), eq(0)); dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 1); verify(mUndoCallback).onUndoShown(any(View.class), eq(1)); dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 2); verify(mUndoCallback).onUndoShown(any(View.class), eq(2)); verify(mUndoCallback, never()).onDismiss(any(View.class), anyInt()); } /** * Tests whether multiple dismisses are correctly handled. */ public void testMultipleDismisses() throws InterruptedException {
dispatchSwipeMotionEvents(getInstrumentation(), mAbsListView, 0);
nhaarman/ListViewAnimations
lib-manipulation/src/main/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/undo/SwipeUndoTouchListener.java
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/AdapterViewUtil.java // public class AdapterViewUtil { // // private AdapterViewUtil() { // } // // /** // * Returns the position within the adapter's dataset for the view, where view is an adapter item or a descendant of an adapter item. // * Unlike {@link AdapterView#getPositionForView(android.view.View)}, returned position will reflect the position of the item given view is representing, // * by subtracting the header views count. // * // * @param listViewWrapper the IListViewWrapper wrapping the ListView containing the view. // * @param view an adapter item or a descendant of an adapter item. This must be visible in given AdapterView at the time of the call. // * // * @return the position of the item in the AdapterView represented by given view, or {@link AdapterView#INVALID_POSITION} if the view does not // * correspond to a list item (or it is not visible). // */ // public static int getPositionForView(@NonNull final ListViewWrapper listViewWrapper, @NonNull final View view) { // return listViewWrapper.getPositionForView(view) - listViewWrapper.getHeaderViewsCount(); // } // // /** // * Returns the position within the adapter's dataset for the view, where view is an adapter item or a descendant of an adapter item. // * Unlike {@link AdapterView#getPositionForView(android.view.View)}, returned position will reflect the position of the item given view is representing, // * by subtracting the header views count. // * // * @param absListView the ListView containing the view. // * @param view an adapter item or a descendant of an adapter item. This must be visible in given AdapterView at the time of the call. // * // * @return the position of the item in the AdapterView represented by given view, or {@link AdapterView#INVALID_POSITION} if the view does not // * correspond to a list item (or it is not visible). // */ // public static int getPositionForView(@NonNull final AbsListView absListView, @NonNull final View view) { // int position = absListView.getPositionForView(view); // if (absListView instanceof ListView) { // position -= ((ListView) absListView).getHeaderViewsCount(); // } // return position; // } // // /** // * Returns the {@link View} that represents the item for given position. // * // * @param listViewWrapper the {@link ListViewWrapper} wrapping the ListView that should be examined // * @param position the position for which the {@code View} should be returned. // * // * @return the {@code View}, or {@code null} if the position is not currently visible. // */ // @Nullable // public static View getViewForPosition(@NonNull final ListViewWrapper listViewWrapper, final int position) { // int childCount = listViewWrapper.getChildCount(); // View downView = null; // for (int i = 0; i < childCount && downView == null; i++) { // View child = listViewWrapper.getChildAt(i); // if (child != null && getPositionForView(listViewWrapper, child) == position) { // downView = child; // } // } // return downView; // } // // /** // * Returns the {@link View} that represents the item for given position. // * // * @param absListView the ListView that should be examined // * @param position the position for which the {@code View} should be returned. // * // * @return the {@code View}, or {@code null} if the position is not currently visible. // */ // @Nullable // public static View getViewForPosition(@NonNull final AbsListView absListView, final int position) { // int childCount = absListView.getChildCount(); // View downView = null; // for (int i = 0; i < childCount && downView == null; i++) { // View child = absListView.getChildAt(i); // if (child != null && getPositionForView(absListView, child) == position) { // downView = child; // } // } // return downView; // } // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapper.java // public interface ListViewWrapper { // // @NonNull // ViewGroup getListView(); // // @Nullable // View getChildAt(int index); // // int getFirstVisiblePosition(); // // int getLastVisiblePosition(); // // int getCount(); // // int getChildCount(); // // int getHeaderViewsCount(); // // int getPositionForView(@NonNull View view); // // @Nullable // ListAdapter getAdapter(); // // void smoothScrollBy(int distance, int duration); // }
import java.util.List; import java.util.Map; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissTouchListener; import com.nhaarman.listviewanimations.util.AdapterViewUtil; import com.nhaarman.listviewanimations.util.ListViewWrapper; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.animation.ObjectAnimator; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList;
restoreViewPresentations(mDismissedViews); notifyCallback(mDismissedPositions); Collection<Integer> newUndoPositions = Util.processDeletions(mUndoPositions, mDismissedPositions); mUndoPositions.clear(); mUndoPositions.addAll(newUndoPositions); mDismissedViews.clear(); mDismissedPositions.clear(); } } /** * Restores the height of given {@code View}. * Also calls its super implementation. */ @Override protected void restoreViewPresentation(@NonNull final View view) { super.restoreViewPresentation(view); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.height = 0; view.setLayoutParams(layoutParams); } /** * Performs the undo animation and restores the original state for given {@link android.view.View}. * * @param view the parent {@code View} which contains both primary and undo {@code View}s. */ public void undo(@NonNull final View view) {
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/AdapterViewUtil.java // public class AdapterViewUtil { // // private AdapterViewUtil() { // } // // /** // * Returns the position within the adapter's dataset for the view, where view is an adapter item or a descendant of an adapter item. // * Unlike {@link AdapterView#getPositionForView(android.view.View)}, returned position will reflect the position of the item given view is representing, // * by subtracting the header views count. // * // * @param listViewWrapper the IListViewWrapper wrapping the ListView containing the view. // * @param view an adapter item or a descendant of an adapter item. This must be visible in given AdapterView at the time of the call. // * // * @return the position of the item in the AdapterView represented by given view, or {@link AdapterView#INVALID_POSITION} if the view does not // * correspond to a list item (or it is not visible). // */ // public static int getPositionForView(@NonNull final ListViewWrapper listViewWrapper, @NonNull final View view) { // return listViewWrapper.getPositionForView(view) - listViewWrapper.getHeaderViewsCount(); // } // // /** // * Returns the position within the adapter's dataset for the view, where view is an adapter item or a descendant of an adapter item. // * Unlike {@link AdapterView#getPositionForView(android.view.View)}, returned position will reflect the position of the item given view is representing, // * by subtracting the header views count. // * // * @param absListView the ListView containing the view. // * @param view an adapter item or a descendant of an adapter item. This must be visible in given AdapterView at the time of the call. // * // * @return the position of the item in the AdapterView represented by given view, or {@link AdapterView#INVALID_POSITION} if the view does not // * correspond to a list item (or it is not visible). // */ // public static int getPositionForView(@NonNull final AbsListView absListView, @NonNull final View view) { // int position = absListView.getPositionForView(view); // if (absListView instanceof ListView) { // position -= ((ListView) absListView).getHeaderViewsCount(); // } // return position; // } // // /** // * Returns the {@link View} that represents the item for given position. // * // * @param listViewWrapper the {@link ListViewWrapper} wrapping the ListView that should be examined // * @param position the position for which the {@code View} should be returned. // * // * @return the {@code View}, or {@code null} if the position is not currently visible. // */ // @Nullable // public static View getViewForPosition(@NonNull final ListViewWrapper listViewWrapper, final int position) { // int childCount = listViewWrapper.getChildCount(); // View downView = null; // for (int i = 0; i < childCount && downView == null; i++) { // View child = listViewWrapper.getChildAt(i); // if (child != null && getPositionForView(listViewWrapper, child) == position) { // downView = child; // } // } // return downView; // } // // /** // * Returns the {@link View} that represents the item for given position. // * // * @param absListView the ListView that should be examined // * @param position the position for which the {@code View} should be returned. // * // * @return the {@code View}, or {@code null} if the position is not currently visible. // */ // @Nullable // public static View getViewForPosition(@NonNull final AbsListView absListView, final int position) { // int childCount = absListView.getChildCount(); // View downView = null; // for (int i = 0; i < childCount && downView == null; i++) { // View child = absListView.getChildAt(i); // if (child != null && getPositionForView(absListView, child) == position) { // downView = child; // } // } // return downView; // } // } // // Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapper.java // public interface ListViewWrapper { // // @NonNull // ViewGroup getListView(); // // @Nullable // View getChildAt(int index); // // int getFirstVisiblePosition(); // // int getLastVisiblePosition(); // // int getCount(); // // int getChildCount(); // // int getHeaderViewsCount(); // // int getPositionForView(@NonNull View view); // // @Nullable // ListAdapter getAdapter(); // // void smoothScrollBy(int distance, int duration); // } // Path: lib-manipulation/src/main/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/undo/SwipeUndoTouchListener.java import java.util.List; import java.util.Map; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissTouchListener; import com.nhaarman.listviewanimations.util.AdapterViewUtil; import com.nhaarman.listviewanimations.util.ListViewWrapper; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.animation.ObjectAnimator; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; restoreViewPresentations(mDismissedViews); notifyCallback(mDismissedPositions); Collection<Integer> newUndoPositions = Util.processDeletions(mUndoPositions, mDismissedPositions); mUndoPositions.clear(); mUndoPositions.addAll(newUndoPositions); mDismissedViews.clear(); mDismissedPositions.clear(); } } /** * Restores the height of given {@code View}. * Also calls its super implementation. */ @Override protected void restoreViewPresentation(@NonNull final View view) { super.restoreViewPresentation(view); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.height = 0; view.setLayoutParams(layoutParams); } /** * Performs the undo animation and restores the original state for given {@link android.view.View}. * * @param view the parent {@code View} which contains both primary and undo {@code View}s. */ public void undo(@NonNull final View view) {
int position = AdapterViewUtil.getPositionForView(getListViewWrapper(), view);
nhaarman/ListViewAnimations
lib-manipulation/src/main/java/com/nhaarman/listviewanimations/itemmanipulation/animateaddition/InsertQueue.java
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/Insertable.java // public interface Insertable<T> { // // /** // * Will be called to insert given {@code item} at given {@code index} in the list. // * // * @param index the index the new item should be inserted at // * @param item the item to insert // */ // void add(int index, @NonNull T item); // }
import android.support.annotation.NonNull; import android.util.Pair; import com.nhaarman.listviewanimations.util.Insertable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger;
/* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations.itemmanipulation.animateaddition; /** * A class to insert items only when there are no active items. * A pending index-item pair can have two states: active and pending. When inserting new items, the {@link com.nhaarman.listviewanimations.itemmanipulation * .AnimateAdditionAdapter.Insertable#add * (int, Object)} method will be called directly if there are no active index-item pairs. * Otherwise, pairs will be queued until the active list is empty. */ public class InsertQueue<T> { @NonNull
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/Insertable.java // public interface Insertable<T> { // // /** // * Will be called to insert given {@code item} at given {@code index} in the list. // * // * @param index the index the new item should be inserted at // * @param item the item to insert // */ // void add(int index, @NonNull T item); // } // Path: lib-manipulation/src/main/java/com/nhaarman/listviewanimations/itemmanipulation/animateaddition/InsertQueue.java import android.support.annotation.NonNull; import android.util.Pair; import com.nhaarman.listviewanimations.util.Insertable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations.itemmanipulation.animateaddition; /** * A class to insert items only when there are no active items. * A pending index-item pair can have two states: active and pending. When inserting new items, the {@link com.nhaarman.listviewanimations.itemmanipulation * .AnimateAdditionAdapter.Insertable#add * (int, Object)} method will be called directly if there are no active index-item pairs. * Otherwise, pairs will be queued until the active list is empty. */ public class InsertQueue<T> { @NonNull
private final Insertable<T> mInsertable;
nhaarman/ListViewAnimations
lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTest.java
// Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEventsAndWait(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEventsAndWait(instrumentation, createSwipeMotionEvents(absListView, position)); // }
import android.support.annotation.NonNull; import android.test.ActivityInstrumentationTestCase2; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import java.util.List; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations.itemmanipulation.swipedismiss; @SuppressWarnings({"AnonymousInnerClass", "AnonymousInnerClassMayBeStatic"}) public class SwipeTouchListenerTest extends ActivityInstrumentationTestCase2<SwipeTouchListenerTestActivity> { /** * The SwipeTouchListener under test. */ private TestSwipeTouchListener mSwipeTouchListener; /** * An Activity hosting a ListView with items. */ private SwipeTouchListenerTestActivity mActivity; /** * The AbsListView that is hosted in mActivity. */ private AbsListView mAbsListView; /** * The width of the AbsListView. */ private float mViewWidth; public SwipeTouchListenerTest() { super(SwipeTouchListenerTestActivity.class); } @Override public void setUp() throws Exception { super.setUp(); mActivity = getActivity(); mAbsListView = mActivity.getAbsListView(); mViewWidth = mAbsListView.getWidth(); mSwipeTouchListener = new TestSwipeTouchListener(new AbsListViewWrapper(mAbsListView)); mAbsListView.setOnTouchListener(mSwipeTouchListener); getInstrumentation().waitForIdleSync(); } /** * Tests whether retrieving the AbsListView yields the original AbsListView that was set. */ public void testAbsListViewSet() { assertThat(mSwipeTouchListener.getListViewWrapper().getListView(), is((ViewGroup) mAbsListView)); } /** * Tests whether swiping the first View triggers a call to SwipeTouchListener#afterViewFling. */ public void testSwipeFirstViewCallback() throws InterruptedException {
// Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/MotionEventUtils.java // public static void dispatchSwipeMotionEventsAndWait(final Instrumentation instrumentation, final AbsListView absListView, final int position) throws InterruptedException { // dispatchMotionEventsAndWait(instrumentation, createSwipeMotionEvents(absListView, position)); // } // Path: lib-manipulation/src/androidTest/java/com/nhaarman/listviewanimations/itemmanipulation/swipedismiss/SwipeTouchListenerTest.java import android.support.annotation.NonNull; import android.test.ActivityInstrumentationTestCase2; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import java.util.List; import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright 2014 Niek Haarman * * 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 com.nhaarman.listviewanimations.itemmanipulation.swipedismiss; @SuppressWarnings({"AnonymousInnerClass", "AnonymousInnerClassMayBeStatic"}) public class SwipeTouchListenerTest extends ActivityInstrumentationTestCase2<SwipeTouchListenerTestActivity> { /** * The SwipeTouchListener under test. */ private TestSwipeTouchListener mSwipeTouchListener; /** * An Activity hosting a ListView with items. */ private SwipeTouchListenerTestActivity mActivity; /** * The AbsListView that is hosted in mActivity. */ private AbsListView mAbsListView; /** * The width of the AbsListView. */ private float mViewWidth; public SwipeTouchListenerTest() { super(SwipeTouchListenerTestActivity.class); } @Override public void setUp() throws Exception { super.setUp(); mActivity = getActivity(); mAbsListView = mActivity.getAbsListView(); mViewWidth = mAbsListView.getWidth(); mSwipeTouchListener = new TestSwipeTouchListener(new AbsListViewWrapper(mAbsListView)); mAbsListView.setOnTouchListener(mSwipeTouchListener); getInstrumentation().waitForIdleSync(); } /** * Tests whether retrieving the AbsListView yields the original AbsListView that was set. */ public void testAbsListViewSet() { assertThat(mSwipeTouchListener.getListViewWrapper().getListView(), is((ViewGroup) mAbsListView)); } /** * Tests whether swiping the first View triggers a call to SwipeTouchListener#afterViewFling. */ public void testSwipeFirstViewCallback() throws InterruptedException {
dispatchSwipeMotionEventsAndWait(getInstrumentation(), mAbsListView, 0);
nhaarman/ListViewAnimations
lib-core/src/androidTest/java/com/nhaarman/listviewanimations/BaseAdapterDecoratorTest.java
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapper.java // public interface ListViewWrapper { // // @NonNull // ViewGroup getListView(); // // @Nullable // View getChildAt(int index); // // int getFirstVisiblePosition(); // // int getLastVisiblePosition(); // // int getCount(); // // int getChildCount(); // // int getHeaderViewsCount(); // // int getPositionForView(@NonNull View view); // // @Nullable // ListAdapter getAdapter(); // // void smoothScrollBy(int distance, int duration); // }
import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import com.nhaarman.listviewanimations.util.ListViewWrapper; import junit.framework.TestCase; import org.mockito.*; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*;
package com.nhaarman.listviewanimations; @SuppressWarnings({"AnonymousInnerClass", "EmptyClass", "ConstantConditions"}) public class BaseAdapterDecoratorTest extends TestCase { private BaseAdapterDecorator mBaseAdapterDecorator; private BaseAdapter mBaseAdapter; @Mock private View mView; @Mock private ListView mAbsListView; @Mock
// Path: lib-core/src/main/java/com/nhaarman/listviewanimations/util/ListViewWrapper.java // public interface ListViewWrapper { // // @NonNull // ViewGroup getListView(); // // @Nullable // View getChildAt(int index); // // int getFirstVisiblePosition(); // // int getLastVisiblePosition(); // // int getCount(); // // int getChildCount(); // // int getHeaderViewsCount(); // // int getPositionForView(@NonNull View view); // // @Nullable // ListAdapter getAdapter(); // // void smoothScrollBy(int distance, int duration); // } // Path: lib-core/src/androidTest/java/com/nhaarman/listviewanimations/BaseAdapterDecoratorTest.java import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import com.nhaarman.listviewanimations.util.AbsListViewWrapper; import com.nhaarman.listviewanimations.util.ListViewWrapper; import junit.framework.TestCase; import org.mockito.*; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.*; package com.nhaarman.listviewanimations; @SuppressWarnings({"AnonymousInnerClass", "EmptyClass", "ConstantConditions"}) public class BaseAdapterDecoratorTest extends TestCase { private BaseAdapterDecorator mBaseAdapterDecorator; private BaseAdapter mBaseAdapter; @Mock private View mView; @Mock private ListView mAbsListView; @Mock
private ListViewWrapper mListViewWrapper;
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/Command.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployApplicationRequest.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class DeployApplicationRequest extends ModuleRequest { // // private boolean running = false; // private String javaOpts = ""; // private String instances = "1"; // private String configLocation = ""; // private boolean installed = false; // private boolean testScope = false; // private String mainService; // // @JsonCreator // public DeployApplicationRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // private DeployApplicationRequest(final String groupId, final String artifactId, // final String version, final String classifier, final String type, boolean testScope) { // this(groupId, artifactId, version, classifier, type); // this.testScope = testScope; // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return false; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_ARTIFACT_REQUEST; // } // // public boolean isRunning() { // return running; // } // // public void setRunning(boolean running) { // this.running = running; // } // // public void withJavaOpts(String javaOpts) { // this.javaOpts = javaOpts != null ? javaOpts : ""; // } // // public void withConfigLocation(String configLocation) { // this.configLocation = configLocation != null ? configLocation : ""; // } // // public void withInstances(String instances) { // this.instances = instances; // } // // public void withTestScope(boolean testScope) { // this.testScope = testScope; // } // // public DeployApplicationRequest withMainService(String mainService) { // this.mainService = mainService; // return this; // } // // public boolean isTestScope() { // return this.testScope; // } // // public String getJavaOpts() { // return javaOpts; // } // // public String getInstances() { // return instances; // } // // public String getConfigLocation() { // return this.configLocation; // } // // public String getMainService() { // return mainService; // } // // public boolean isInstalled() { // return installed; // } // // public void setInstalled(boolean installed) { // this.installed = installed; // } // // public static DeployApplicationRequest build(String groupId, String artifactId, String version, String classifier, boolean testScope) { // return new DeployApplicationRequest(groupId, artifactId, version, classifier, "jar", testScope); // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ExitCodes.java // public enum ExitCodes { // ZERO("Normal startup"), // ONE("Vertx Initialization Issue"), // TWO("Process Issue"), // THREE("System Configuration Issue"), // FOUR(""), // FIVE("Vertx Deployment Issue"); // // private final String explanation; // // ExitCodes(String explanation) { // // this.explanation = explanation; // } // // @Override // public String toString() { // return explanation; // } // // }
import nl.jpoint.vertx.deploy.agent.request.DeployApplicationRequest; import nl.jpoint.vertx.deploy.agent.util.ExitCodes; import rx.Observable; import static rx.Observable.just;
package nl.jpoint.vertx.deploy.agent.command; @FunctionalInterface public interface Command<T> { Observable<T> executeAsync(T request);
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployApplicationRequest.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class DeployApplicationRequest extends ModuleRequest { // // private boolean running = false; // private String javaOpts = ""; // private String instances = "1"; // private String configLocation = ""; // private boolean installed = false; // private boolean testScope = false; // private String mainService; // // @JsonCreator // public DeployApplicationRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // private DeployApplicationRequest(final String groupId, final String artifactId, // final String version, final String classifier, final String type, boolean testScope) { // this(groupId, artifactId, version, classifier, type); // this.testScope = testScope; // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return false; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_ARTIFACT_REQUEST; // } // // public boolean isRunning() { // return running; // } // // public void setRunning(boolean running) { // this.running = running; // } // // public void withJavaOpts(String javaOpts) { // this.javaOpts = javaOpts != null ? javaOpts : ""; // } // // public void withConfigLocation(String configLocation) { // this.configLocation = configLocation != null ? configLocation : ""; // } // // public void withInstances(String instances) { // this.instances = instances; // } // // public void withTestScope(boolean testScope) { // this.testScope = testScope; // } // // public DeployApplicationRequest withMainService(String mainService) { // this.mainService = mainService; // return this; // } // // public boolean isTestScope() { // return this.testScope; // } // // public String getJavaOpts() { // return javaOpts; // } // // public String getInstances() { // return instances; // } // // public String getConfigLocation() { // return this.configLocation; // } // // public String getMainService() { // return mainService; // } // // public boolean isInstalled() { // return installed; // } // // public void setInstalled(boolean installed) { // this.installed = installed; // } // // public static DeployApplicationRequest build(String groupId, String artifactId, String version, String classifier, boolean testScope) { // return new DeployApplicationRequest(groupId, artifactId, version, classifier, "jar", testScope); // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ExitCodes.java // public enum ExitCodes { // ZERO("Normal startup"), // ONE("Vertx Initialization Issue"), // TWO("Process Issue"), // THREE("System Configuration Issue"), // FOUR(""), // FIVE("Vertx Deployment Issue"); // // private final String explanation; // // ExitCodes(String explanation) { // // this.explanation = explanation; // } // // @Override // public String toString() { // return explanation; // } // // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/Command.java import nl.jpoint.vertx.deploy.agent.request.DeployApplicationRequest; import nl.jpoint.vertx.deploy.agent.util.ExitCodes; import rx.Observable; import static rx.Observable.just; package nl.jpoint.vertx.deploy.agent.command; @FunctionalInterface public interface Command<T> { Observable<T> executeAsync(T request);
default Observable<Integer> handleExitCode(DeployApplicationRequest request, Integer exitCode) {
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/Command.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployApplicationRequest.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class DeployApplicationRequest extends ModuleRequest { // // private boolean running = false; // private String javaOpts = ""; // private String instances = "1"; // private String configLocation = ""; // private boolean installed = false; // private boolean testScope = false; // private String mainService; // // @JsonCreator // public DeployApplicationRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // private DeployApplicationRequest(final String groupId, final String artifactId, // final String version, final String classifier, final String type, boolean testScope) { // this(groupId, artifactId, version, classifier, type); // this.testScope = testScope; // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return false; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_ARTIFACT_REQUEST; // } // // public boolean isRunning() { // return running; // } // // public void setRunning(boolean running) { // this.running = running; // } // // public void withJavaOpts(String javaOpts) { // this.javaOpts = javaOpts != null ? javaOpts : ""; // } // // public void withConfigLocation(String configLocation) { // this.configLocation = configLocation != null ? configLocation : ""; // } // // public void withInstances(String instances) { // this.instances = instances; // } // // public void withTestScope(boolean testScope) { // this.testScope = testScope; // } // // public DeployApplicationRequest withMainService(String mainService) { // this.mainService = mainService; // return this; // } // // public boolean isTestScope() { // return this.testScope; // } // // public String getJavaOpts() { // return javaOpts; // } // // public String getInstances() { // return instances; // } // // public String getConfigLocation() { // return this.configLocation; // } // // public String getMainService() { // return mainService; // } // // public boolean isInstalled() { // return installed; // } // // public void setInstalled(boolean installed) { // this.installed = installed; // } // // public static DeployApplicationRequest build(String groupId, String artifactId, String version, String classifier, boolean testScope) { // return new DeployApplicationRequest(groupId, artifactId, version, classifier, "jar", testScope); // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ExitCodes.java // public enum ExitCodes { // ZERO("Normal startup"), // ONE("Vertx Initialization Issue"), // TWO("Process Issue"), // THREE("System Configuration Issue"), // FOUR(""), // FIVE("Vertx Deployment Issue"); // // private final String explanation; // // ExitCodes(String explanation) { // // this.explanation = explanation; // } // // @Override // public String toString() { // return explanation; // } // // }
import nl.jpoint.vertx.deploy.agent.request.DeployApplicationRequest; import nl.jpoint.vertx.deploy.agent.util.ExitCodes; import rx.Observable; import static rx.Observable.just;
package nl.jpoint.vertx.deploy.agent.command; @FunctionalInterface public interface Command<T> { Observable<T> executeAsync(T request); default Observable<Integer> handleExitCode(DeployApplicationRequest request, Integer exitCode) { if (exitCode != 0) {
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployApplicationRequest.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class DeployApplicationRequest extends ModuleRequest { // // private boolean running = false; // private String javaOpts = ""; // private String instances = "1"; // private String configLocation = ""; // private boolean installed = false; // private boolean testScope = false; // private String mainService; // // @JsonCreator // public DeployApplicationRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // private DeployApplicationRequest(final String groupId, final String artifactId, // final String version, final String classifier, final String type, boolean testScope) { // this(groupId, artifactId, version, classifier, type); // this.testScope = testScope; // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return false; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_ARTIFACT_REQUEST; // } // // public boolean isRunning() { // return running; // } // // public void setRunning(boolean running) { // this.running = running; // } // // public void withJavaOpts(String javaOpts) { // this.javaOpts = javaOpts != null ? javaOpts : ""; // } // // public void withConfigLocation(String configLocation) { // this.configLocation = configLocation != null ? configLocation : ""; // } // // public void withInstances(String instances) { // this.instances = instances; // } // // public void withTestScope(boolean testScope) { // this.testScope = testScope; // } // // public DeployApplicationRequest withMainService(String mainService) { // this.mainService = mainService; // return this; // } // // public boolean isTestScope() { // return this.testScope; // } // // public String getJavaOpts() { // return javaOpts; // } // // public String getInstances() { // return instances; // } // // public String getConfigLocation() { // return this.configLocation; // } // // public String getMainService() { // return mainService; // } // // public boolean isInstalled() { // return installed; // } // // public void setInstalled(boolean installed) { // this.installed = installed; // } // // public static DeployApplicationRequest build(String groupId, String artifactId, String version, String classifier, boolean testScope) { // return new DeployApplicationRequest(groupId, artifactId, version, classifier, "jar", testScope); // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ExitCodes.java // public enum ExitCodes { // ZERO("Normal startup"), // ONE("Vertx Initialization Issue"), // TWO("Process Issue"), // THREE("System Configuration Issue"), // FOUR(""), // FIVE("Vertx Deployment Issue"); // // private final String explanation; // // ExitCodes(String explanation) { // // this.explanation = explanation; // } // // @Override // public String toString() { // return explanation; // } // // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/Command.java import nl.jpoint.vertx.deploy.agent.request.DeployApplicationRequest; import nl.jpoint.vertx.deploy.agent.util.ExitCodes; import rx.Observable; import static rx.Observable.just; package nl.jpoint.vertx.deploy.agent.command; @FunctionalInterface public interface Command<T> { Observable<T> executeAsync(T request); default Observable<Integer> handleExitCode(DeployApplicationRequest request, Integer exitCode) { if (exitCode != 0) {
throw new IllegalStateException("Error while initializing container " + request.getModuleId() + " with error " + ExitCodes.values()[exitCode]);
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/AwsDeployApplication.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // }
import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import nl.jpoint.vertx.deploy.agent.handler.*; import nl.jpoint.vertx.deploy.agent.service.*; import nl.jpoint.vertx.deploy.agent.util.LogConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC;
if (deployconfig.isAwsEnabled()) { awsService = new AwsService(getVertx(), deployconfig); autoDiscoverDeployService = new AutoDiscoverDeployService(deployconfig, defaultDeployService, getVertx()); } Router router = Router.router(getVertx()); router.post("/deploy/deploy").handler(new RestDeployHandler(defaultDeployService, awsService, deployconfig.getAuthToken())); router.post("/deploy/module*").handler(new RestDeployModuleHandler(deployApplicationService)); router.post("/deploy/artifact*").handler(new RestDeployArtifactHandler(deployArtifactService)); router.get("/deploy/update*").handler(new StatusUpdateHandler(deployApplicationService)); if (deployconfig.isAwsEnabled()) { router.get("/deploy/status/:id").handler(new RestDeployStatusHandler(awsService, deployApplicationService)); } router.get("/status").handler(event -> { if (initiated) { event.response().setStatusCode(HttpResponseStatus.FORBIDDEN.code()); } else { event.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } event.response().end(); event.response().close(); }); HttpServer server = vertx.createHttpServer().requestHandler(router::accept); server.listen(deployconfig.getHttpPort()); initiated = true;
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/AwsDeployApplication.java import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import nl.jpoint.vertx.deploy.agent.handler.*; import nl.jpoint.vertx.deploy.agent.service.*; import nl.jpoint.vertx.deploy.agent.util.LogConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; if (deployconfig.isAwsEnabled()) { awsService = new AwsService(getVertx(), deployconfig); autoDiscoverDeployService = new AutoDiscoverDeployService(deployconfig, defaultDeployService, getVertx()); } Router router = Router.router(getVertx()); router.post("/deploy/deploy").handler(new RestDeployHandler(defaultDeployService, awsService, deployconfig.getAuthToken())); router.post("/deploy/module*").handler(new RestDeployModuleHandler(deployApplicationService)); router.post("/deploy/artifact*").handler(new RestDeployArtifactHandler(deployArtifactService)); router.get("/deploy/update*").handler(new StatusUpdateHandler(deployApplicationService)); if (deployconfig.isAwsEnabled()) { router.get("/deploy/status/:id").handler(new RestDeployStatusHandler(awsService, deployApplicationService)); } router.get("/status").handler(event -> { if (initiated) { event.response().setStatusCode(HttpResponseStatus.FORBIDDEN.code()); } else { event.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } event.response().end(); event.response().close(); }); HttpServer server = vertx.createHttpServer().requestHandler(router::accept); server.listen(deployconfig.getHttpPort()); initiated = true;
LOG.info("{}: Instantiated module.", LogConstants.CLUSTER_MANAGER);
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/HttpUtils.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployState.java // public enum DeployState { // WAITING_FOR_AS_DEREGISTER, // WAITING_FOR_ELB_DEREGISTER, // DEPLOYING_CONFIGS, // STOPPING_CONTAINER, // DEPLOYING_ARTIFACTS, // DEPLOYING_APPLICATIONS, // UNKNOWN, // FAILED, // SUCCESS, // CONTINUE, // WAITING_FOR_AS_REGISTER, // WAITING_FOR_ELB_REGISTER // }
import com.amazonaws.util.StringUtils; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import nl.jpoint.vertx.deploy.agent.request.DeployState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map;
private static void respond(HttpServerResponse response, HttpResponseStatus code, JsonObject status) { response.setStatusCode(code.code()); if (status != null) { response.end(status.encode()); } else { response.end(); } } public static void respondOk(HttpServerRequest request, JsonObject status) { respond(request.response(), HttpResponseStatus.OK, status); } public static void respondOk(HttpServerRequest request) { respondOk(request, null); } public static void respondFailed(HttpServerRequest request, JsonObject status) { respond(request.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR, status); } public static void respondFailed(HttpServerRequest request) { respondFailed(request, null); } public static void respondBadRequest(HttpServerRequest request) { respond(request.response(), HttpResponseStatus.BAD_REQUEST, null); }
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployState.java // public enum DeployState { // WAITING_FOR_AS_DEREGISTER, // WAITING_FOR_ELB_DEREGISTER, // DEPLOYING_CONFIGS, // STOPPING_CONTAINER, // DEPLOYING_ARTIFACTS, // DEPLOYING_APPLICATIONS, // UNKNOWN, // FAILED, // SUCCESS, // CONTINUE, // WAITING_FOR_AS_REGISTER, // WAITING_FOR_ELB_REGISTER // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/HttpUtils.java import com.amazonaws.util.StringUtils; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; import nl.jpoint.vertx.deploy.agent.request.DeployState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; private static void respond(HttpServerResponse response, HttpResponseStatus code, JsonObject status) { response.setStatusCode(code.code()); if (status != null) { response.end(status.encode()); } else { response.end(); } } public static void respondOk(HttpServerRequest request, JsonObject status) { respond(request.response(), HttpResponseStatus.OK, status); } public static void respondOk(HttpServerRequest request) { respondOk(request, null); } public static void respondFailed(HttpServerRequest request, JsonObject status) { respond(request.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR, status); } public static void respondFailed(HttpServerRequest request) { respondFailed(request, null); } public static void respondBadRequest(HttpServerRequest request) { respond(request.response(), HttpResponseStatus.BAD_REQUEST, null); }
public static void respondContinue(HttpServerRequest request, DeployState state) {
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ArtifactContextUtil.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/ModuleRequest.java // public abstract class ModuleRequest { // // public static final String CONFIG_TYPE = "config"; // public static final String ZIP_TYPE = "zip"; // public static final String GZIP_TYPE = "tar.gz"; // // private final UUID id = UUID.randomUUID(); // private final String groupId; // private final String artifactId; // private final String classifier; // private final String type; // private final String remoteBase; // private final boolean snapshot; // private String version; // // private boolean restart = false; // // private Optional<String> restartCommand; // private Optional<String> testCommand; // private Path baseLocation; // // // ModuleRequest(final String groupId, final String artifactId, final String version, final String classifier, final String type) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // this.classifier = classifier; // this.type = type != null ? type : "jar"; // this.snapshot = version.endsWith("-SNAPSHOT"); // this.remoteBase = groupId.replaceAll("\\.", "/") + "/" + artifactId + "/" + version + "/"; // } // // public String getGroupId() { // return groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public UUID getId() { // return id; // } // // public String getModuleId() { // return this.groupId + ":" + this.artifactId + ":" + this.version; // } // // public String getMavenArtifactId() { // return this.groupId + ":" + this.artifactId; // } // // public String getRemoteLocation() { // return remoteBase + getFileName(); // } // // public Path getLocalPath(Path localRepo) { // if (!Objects.equals(type, "jar")) { // return localRepo.resolve(getFileName()); // } // return null; // } // // public String getFileName() { // StringBuilder builder = new StringBuilder() // .append(getArtifactId()).append("-"); // builder.append(version); // if (classifier != null && !classifier.isEmpty()) { // builder.append("-") // .append(classifier); // } // builder.append("."); // builder.append(type); // // return builder.toString(); // // } // // public boolean isSnapshot() { // return snapshot; // } // // public String getMetadataLocation() { // return remoteBase + "maven-metadata.xml"; // // } // // public String getType() { // return type; // } // // public boolean restart() { // return restart; // } // // public void setRestart(boolean restart) { // this.restart = restart; // } // // public Optional<String> getRestartCommand() { // return restartCommand; // } // // public void setRestartCommand(String restartCommand) { // this.restartCommand = (restartCommand == null || restartCommand.isEmpty()) ? Optional.empty() : Optional.of(restartCommand); // } // // public Optional<String> getTestCommand() { // return testCommand; // } // // public void setTestCommand(String testCommand) { // this.testCommand = (testCommand == null || testCommand.isEmpty()) ? Optional.empty() : Optional.of(testCommand); // } // // public Path getBaseLocation() { // return baseLocation; // } // // public void setBaseLocation(String baseLocation) { // this.baseLocation = Paths.get(baseLocation); // } // // public abstract boolean deleteBase(); // // public abstract boolean checkConfig(); // // public abstract String getLogName(); // // }
import nl.jpoint.vertx.deploy.agent.request.ModuleRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.nio.file.*; import java.util.HashMap;
package nl.jpoint.vertx.deploy.agent.util; public class ArtifactContextUtil { public static final String ARTIFACT_CONTEXT = "artifact_context.xml"; private static final Logger LOG = LoggerFactory.getLogger(ArtifactContextUtil.class); private static final String BASE_LOCATION = "/artifact/baselocation/text()"; private static final String RESTART_ON_CHANGED_CONTENT = "/artifact/checkContent/text()"; private static final String RESTART_COMMAND = "/artifact/restartCommand/text()"; private static final String TEST_COMMAND = "/artifact/testCommand/text()"; private final XPath xPath = XPathFactory.newInstance().newXPath(); private Document document;
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/ModuleRequest.java // public abstract class ModuleRequest { // // public static final String CONFIG_TYPE = "config"; // public static final String ZIP_TYPE = "zip"; // public static final String GZIP_TYPE = "tar.gz"; // // private final UUID id = UUID.randomUUID(); // private final String groupId; // private final String artifactId; // private final String classifier; // private final String type; // private final String remoteBase; // private final boolean snapshot; // private String version; // // private boolean restart = false; // // private Optional<String> restartCommand; // private Optional<String> testCommand; // private Path baseLocation; // // // ModuleRequest(final String groupId, final String artifactId, final String version, final String classifier, final String type) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // this.classifier = classifier; // this.type = type != null ? type : "jar"; // this.snapshot = version.endsWith("-SNAPSHOT"); // this.remoteBase = groupId.replaceAll("\\.", "/") + "/" + artifactId + "/" + version + "/"; // } // // public String getGroupId() { // return groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public UUID getId() { // return id; // } // // public String getModuleId() { // return this.groupId + ":" + this.artifactId + ":" + this.version; // } // // public String getMavenArtifactId() { // return this.groupId + ":" + this.artifactId; // } // // public String getRemoteLocation() { // return remoteBase + getFileName(); // } // // public Path getLocalPath(Path localRepo) { // if (!Objects.equals(type, "jar")) { // return localRepo.resolve(getFileName()); // } // return null; // } // // public String getFileName() { // StringBuilder builder = new StringBuilder() // .append(getArtifactId()).append("-"); // builder.append(version); // if (classifier != null && !classifier.isEmpty()) { // builder.append("-") // .append(classifier); // } // builder.append("."); // builder.append(type); // // return builder.toString(); // // } // // public boolean isSnapshot() { // return snapshot; // } // // public String getMetadataLocation() { // return remoteBase + "maven-metadata.xml"; // // } // // public String getType() { // return type; // } // // public boolean restart() { // return restart; // } // // public void setRestart(boolean restart) { // this.restart = restart; // } // // public Optional<String> getRestartCommand() { // return restartCommand; // } // // public void setRestartCommand(String restartCommand) { // this.restartCommand = (restartCommand == null || restartCommand.isEmpty()) ? Optional.empty() : Optional.of(restartCommand); // } // // public Optional<String> getTestCommand() { // return testCommand; // } // // public void setTestCommand(String testCommand) { // this.testCommand = (testCommand == null || testCommand.isEmpty()) ? Optional.empty() : Optional.of(testCommand); // } // // public Path getBaseLocation() { // return baseLocation; // } // // public void setBaseLocation(String baseLocation) { // this.baseLocation = Paths.get(baseLocation); // } // // public abstract boolean deleteBase(); // // public abstract boolean checkConfig(); // // public abstract String getLogName(); // // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ArtifactContextUtil.java import nl.jpoint.vertx.deploy.agent.request.ModuleRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.nio.file.*; import java.util.HashMap; package nl.jpoint.vertx.deploy.agent.util; public class ArtifactContextUtil { public static final String ARTIFACT_CONTEXT = "artifact_context.xml"; private static final Logger LOG = LoggerFactory.getLogger(ArtifactContextUtil.class); private static final String BASE_LOCATION = "/artifact/baselocation/text()"; private static final String RESTART_ON_CHANGED_CONTENT = "/artifact/checkContent/text()"; private static final String RESTART_COMMAND = "/artifact/restartCommand/text()"; private static final String TEST_COMMAND = "/artifact/testCommand/text()"; private final XPath xPath = XPathFactory.newInstance().newXPath(); private Document document;
public ArtifactContextUtil(ModuleRequest request, Path location) {
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/RunConsoleCommand.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployConfigRequest.java // public class DeployConfigRequest extends ModuleRequest { // // @JsonCreator // private DeployConfigRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, // @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // public static DeployConfigRequest build(String groupId, String artifactId, String version, String classifier) { // return new DeployConfigRequest(groupId, artifactId, version, classifier, "config"); // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return true; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_CONFIG_REQUEST; // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ObservableCommand.java // public class ObservableCommand<R extends ModuleRequest> { // // private static final Logger LOG = LoggerFactory.getLogger(ObservableCommand.class); // private static final Long POLLING_INTERVAL_IN_MS = 500L; // private final Integer expectedResultCode; // private final Vertx rxVertx; // private final R request; // private Process process; // // public ObservableCommand(R request, Integer expectedResultCode, Vertx vertx) { // this.request = request; // this.expectedResultCode = expectedResultCode; // this.rxVertx = vertx; // } // // public Observable<Integer> execute(ProcessBuilder builder) { // return observableCommand(builder) // .flatMap(x -> waitForExit()) // .flatMap(x -> { // if (process.exitValue() != expectedResultCode) { // throw new IllegalStateException("Error executing process"); // } // return just(x); // }); // } // // private Observable<Integer> waitForExit() { // return rxVertx.timerStream(POLLING_INTERVAL_IN_MS).toObservable() // .flatMap(x -> { // if (process.isAlive()) { // return waitForExit(); // } else { // if (process.exitValue() != expectedResultCode) { // printStream(process.getInputStream(), false); // throw new IllegalStateException(printStream(process.getErrorStream(), true)); // } else { // printStream(process.getInputStream(), false); // } // return just(process.exitValue()); // } // }); // } // // private Observable<String> observableCommand(ProcessBuilder builder) { // return Observable.create(subscriber -> { // process = null; // try { // builder.directory(new File(System.getProperty("java.io.tmpdir"))); // process = builder.start(); // } catch (IOException e) { // subscriber.onError(e); // } // subscriber.onNext("Done"); // subscriber.onCompleted(); // }, Emitter.BackpressureMode.NONE); // } // // private String printStream(InputStream stream, boolean error) { // if (stream == null) { // return null; // } // String line; // try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { // while ((line = reader.readLine()) != null) { // if (error) { // LOG.error("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } else { // LOG.info("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } // } // return line; // } catch (Exception e) { // LOG.error(e.getMessage(), e); // throw new IllegalStateException(e); // } // } // }
import io.vertx.rxjava.core.Vertx; import nl.jpoint.vertx.deploy.agent.request.DeployConfigRequest; import nl.jpoint.vertx.deploy.agent.util.LogConstants; import nl.jpoint.vertx.deploy.agent.util.ObservableCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import static rx.Observable.just;
package nl.jpoint.vertx.deploy.agent.command; public class RunConsoleCommand implements Command<DeployConfigRequest> { private static final Logger LOG = LoggerFactory.getLogger(RunConsoleCommand.class); private final String command; private final Vertx rxVertx; public RunConsoleCommand(io.vertx.core.Vertx vertx, String command) { this.command = command; this.rxVertx = new Vertx(vertx); } @Override public Observable<DeployConfigRequest> executeAsync(DeployConfigRequest deployConfigRequest) { if (command == null || command.isEmpty()) {
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployConfigRequest.java // public class DeployConfigRequest extends ModuleRequest { // // @JsonCreator // private DeployConfigRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, // @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // public static DeployConfigRequest build(String groupId, String artifactId, String version, String classifier) { // return new DeployConfigRequest(groupId, artifactId, version, classifier, "config"); // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return true; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_CONFIG_REQUEST; // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ObservableCommand.java // public class ObservableCommand<R extends ModuleRequest> { // // private static final Logger LOG = LoggerFactory.getLogger(ObservableCommand.class); // private static final Long POLLING_INTERVAL_IN_MS = 500L; // private final Integer expectedResultCode; // private final Vertx rxVertx; // private final R request; // private Process process; // // public ObservableCommand(R request, Integer expectedResultCode, Vertx vertx) { // this.request = request; // this.expectedResultCode = expectedResultCode; // this.rxVertx = vertx; // } // // public Observable<Integer> execute(ProcessBuilder builder) { // return observableCommand(builder) // .flatMap(x -> waitForExit()) // .flatMap(x -> { // if (process.exitValue() != expectedResultCode) { // throw new IllegalStateException("Error executing process"); // } // return just(x); // }); // } // // private Observable<Integer> waitForExit() { // return rxVertx.timerStream(POLLING_INTERVAL_IN_MS).toObservable() // .flatMap(x -> { // if (process.isAlive()) { // return waitForExit(); // } else { // if (process.exitValue() != expectedResultCode) { // printStream(process.getInputStream(), false); // throw new IllegalStateException(printStream(process.getErrorStream(), true)); // } else { // printStream(process.getInputStream(), false); // } // return just(process.exitValue()); // } // }); // } // // private Observable<String> observableCommand(ProcessBuilder builder) { // return Observable.create(subscriber -> { // process = null; // try { // builder.directory(new File(System.getProperty("java.io.tmpdir"))); // process = builder.start(); // } catch (IOException e) { // subscriber.onError(e); // } // subscriber.onNext("Done"); // subscriber.onCompleted(); // }, Emitter.BackpressureMode.NONE); // } // // private String printStream(InputStream stream, boolean error) { // if (stream == null) { // return null; // } // String line; // try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { // while ((line = reader.readLine()) != null) { // if (error) { // LOG.error("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } else { // LOG.info("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } // } // return line; // } catch (Exception e) { // LOG.error(e.getMessage(), e); // throw new IllegalStateException(e); // } // } // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/RunConsoleCommand.java import io.vertx.rxjava.core.Vertx; import nl.jpoint.vertx.deploy.agent.request.DeployConfigRequest; import nl.jpoint.vertx.deploy.agent.util.LogConstants; import nl.jpoint.vertx.deploy.agent.util.ObservableCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import static rx.Observable.just; package nl.jpoint.vertx.deploy.agent.command; public class RunConsoleCommand implements Command<DeployConfigRequest> { private static final Logger LOG = LoggerFactory.getLogger(RunConsoleCommand.class); private final String command; private final Vertx rxVertx; public RunConsoleCommand(io.vertx.core.Vertx vertx, String command) { this.command = command; this.rxVertx = new Vertx(vertx); } @Override public Observable<DeployConfigRequest> executeAsync(DeployConfigRequest deployConfigRequest) { if (command == null || command.isEmpty()) {
LOG.error("[{} - {}]: Failed to run empty command.", LogConstants.CONSOLE_COMMAND, deployConfigRequest.getId());
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/RunConsoleCommand.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployConfigRequest.java // public class DeployConfigRequest extends ModuleRequest { // // @JsonCreator // private DeployConfigRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, // @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // public static DeployConfigRequest build(String groupId, String artifactId, String version, String classifier) { // return new DeployConfigRequest(groupId, artifactId, version, classifier, "config"); // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return true; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_CONFIG_REQUEST; // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ObservableCommand.java // public class ObservableCommand<R extends ModuleRequest> { // // private static final Logger LOG = LoggerFactory.getLogger(ObservableCommand.class); // private static final Long POLLING_INTERVAL_IN_MS = 500L; // private final Integer expectedResultCode; // private final Vertx rxVertx; // private final R request; // private Process process; // // public ObservableCommand(R request, Integer expectedResultCode, Vertx vertx) { // this.request = request; // this.expectedResultCode = expectedResultCode; // this.rxVertx = vertx; // } // // public Observable<Integer> execute(ProcessBuilder builder) { // return observableCommand(builder) // .flatMap(x -> waitForExit()) // .flatMap(x -> { // if (process.exitValue() != expectedResultCode) { // throw new IllegalStateException("Error executing process"); // } // return just(x); // }); // } // // private Observable<Integer> waitForExit() { // return rxVertx.timerStream(POLLING_INTERVAL_IN_MS).toObservable() // .flatMap(x -> { // if (process.isAlive()) { // return waitForExit(); // } else { // if (process.exitValue() != expectedResultCode) { // printStream(process.getInputStream(), false); // throw new IllegalStateException(printStream(process.getErrorStream(), true)); // } else { // printStream(process.getInputStream(), false); // } // return just(process.exitValue()); // } // }); // } // // private Observable<String> observableCommand(ProcessBuilder builder) { // return Observable.create(subscriber -> { // process = null; // try { // builder.directory(new File(System.getProperty("java.io.tmpdir"))); // process = builder.start(); // } catch (IOException e) { // subscriber.onError(e); // } // subscriber.onNext("Done"); // subscriber.onCompleted(); // }, Emitter.BackpressureMode.NONE); // } // // private String printStream(InputStream stream, boolean error) { // if (stream == null) { // return null; // } // String line; // try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { // while ((line = reader.readLine()) != null) { // if (error) { // LOG.error("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } else { // LOG.info("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } // } // return line; // } catch (Exception e) { // LOG.error(e.getMessage(), e); // throw new IllegalStateException(e); // } // } // }
import io.vertx.rxjava.core.Vertx; import nl.jpoint.vertx.deploy.agent.request.DeployConfigRequest; import nl.jpoint.vertx.deploy.agent.util.LogConstants; import nl.jpoint.vertx.deploy.agent.util.ObservableCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import static rx.Observable.just;
package nl.jpoint.vertx.deploy.agent.command; public class RunConsoleCommand implements Command<DeployConfigRequest> { private static final Logger LOG = LoggerFactory.getLogger(RunConsoleCommand.class); private final String command; private final Vertx rxVertx; public RunConsoleCommand(io.vertx.core.Vertx vertx, String command) { this.command = command; this.rxVertx = new Vertx(vertx); } @Override public Observable<DeployConfigRequest> executeAsync(DeployConfigRequest deployConfigRequest) { if (command == null || command.isEmpty()) { LOG.error("[{} - {}]: Failed to run empty command.", LogConstants.CONSOLE_COMMAND, deployConfigRequest.getId()); throw new IllegalStateException(); }
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployConfigRequest.java // public class DeployConfigRequest extends ModuleRequest { // // @JsonCreator // private DeployConfigRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, // @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, // @JsonProperty("type") final String type) { // super(groupId, artifactId, version, classifier, type); // } // // public static DeployConfigRequest build(String groupId, String artifactId, String version, String classifier) { // return new DeployConfigRequest(groupId, artifactId, version, classifier, "config"); // } // // @Override // public boolean deleteBase() { // return false; // } // // @Override // public boolean checkConfig() { // return true; // } // // @Override // public String getLogName() { // return LogConstants.DEPLOY_CONFIG_REQUEST; // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/ObservableCommand.java // public class ObservableCommand<R extends ModuleRequest> { // // private static final Logger LOG = LoggerFactory.getLogger(ObservableCommand.class); // private static final Long POLLING_INTERVAL_IN_MS = 500L; // private final Integer expectedResultCode; // private final Vertx rxVertx; // private final R request; // private Process process; // // public ObservableCommand(R request, Integer expectedResultCode, Vertx vertx) { // this.request = request; // this.expectedResultCode = expectedResultCode; // this.rxVertx = vertx; // } // // public Observable<Integer> execute(ProcessBuilder builder) { // return observableCommand(builder) // .flatMap(x -> waitForExit()) // .flatMap(x -> { // if (process.exitValue() != expectedResultCode) { // throw new IllegalStateException("Error executing process"); // } // return just(x); // }); // } // // private Observable<Integer> waitForExit() { // return rxVertx.timerStream(POLLING_INTERVAL_IN_MS).toObservable() // .flatMap(x -> { // if (process.isAlive()) { // return waitForExit(); // } else { // if (process.exitValue() != expectedResultCode) { // printStream(process.getInputStream(), false); // throw new IllegalStateException(printStream(process.getErrorStream(), true)); // } else { // printStream(process.getInputStream(), false); // } // return just(process.exitValue()); // } // }); // } // // private Observable<String> observableCommand(ProcessBuilder builder) { // return Observable.create(subscriber -> { // process = null; // try { // builder.directory(new File(System.getProperty("java.io.tmpdir"))); // process = builder.start(); // } catch (IOException e) { // subscriber.onError(e); // } // subscriber.onNext("Done"); // subscriber.onCompleted(); // }, Emitter.BackpressureMode.NONE); // } // // private String printStream(InputStream stream, boolean error) { // if (stream == null) { // return null; // } // String line; // try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { // while ((line = reader.readLine()) != null) { // if (error) { // LOG.error("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } else { // LOG.info("[{} - {}]: Command output -> '{}'", LogConstants.CONSOLE_COMMAND, request.getId(), line); // } // } // return line; // } catch (Exception e) { // LOG.error(e.getMessage(), e); // throw new IllegalStateException(e); // } // } // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/command/RunConsoleCommand.java import io.vertx.rxjava.core.Vertx; import nl.jpoint.vertx.deploy.agent.request.DeployConfigRequest; import nl.jpoint.vertx.deploy.agent.util.LogConstants; import nl.jpoint.vertx.deploy.agent.util.ObservableCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import static rx.Observable.just; package nl.jpoint.vertx.deploy.agent.command; public class RunConsoleCommand implements Command<DeployConfigRequest> { private static final Logger LOG = LoggerFactory.getLogger(RunConsoleCommand.class); private final String command; private final Vertx rxVertx; public RunConsoleCommand(io.vertx.core.Vertx vertx, String command) { this.command = command; this.rxVertx = new Vertx(vertx); } @Override public Observable<DeployConfigRequest> executeAsync(DeployConfigRequest deployConfigRequest) { if (command == null || command.isEmpty()) { LOG.error("[{} - {}]: Failed to run empty command.", LogConstants.CONSOLE_COMMAND, deployConfigRequest.getId()); throw new IllegalStateException(); }
ObservableCommand<DeployConfigRequest> observableCommand = new ObservableCommand<>(deployConfigRequest, 0, rxVertx);
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployApplicationRequest.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.jpoint.vertx.deploy.agent.util.LogConstants;
package nl.jpoint.vertx.deploy.agent.request; @JsonIgnoreProperties(ignoreUnknown = true) public class DeployApplicationRequest extends ModuleRequest { private boolean running = false; private String javaOpts = ""; private String instances = "1"; private String configLocation = ""; private boolean installed = false; private boolean testScope = false; private String mainService; @JsonCreator public DeployApplicationRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { super(groupId, artifactId, version, classifier, type); } private DeployApplicationRequest(final String groupId, final String artifactId, final String version, final String classifier, final String type, boolean testScope) { this(groupId, artifactId, version, classifier, type); this.testScope = testScope; } @Override public boolean deleteBase() { return false; } @Override public boolean checkConfig() { return false; } @Override public String getLogName() {
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployApplicationRequest.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.jpoint.vertx.deploy.agent.util.LogConstants; package nl.jpoint.vertx.deploy.agent.request; @JsonIgnoreProperties(ignoreUnknown = true) public class DeployApplicationRequest extends ModuleRequest { private boolean running = false; private String javaOpts = ""; private String instances = "1"; private String configLocation = ""; private boolean installed = false; private boolean testScope = false; private String mainService; @JsonCreator public DeployApplicationRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { super(groupId, artifactId, version, classifier, type); } private DeployApplicationRequest(final String groupId, final String artifactId, final String version, final String classifier, final String type, boolean testScope) { this(groupId, artifactId, version, classifier, type); this.testScope = testScope; } @Override public boolean deleteBase() { return false; } @Override public boolean checkConfig() { return false; } @Override public String getLogName() {
return LogConstants.DEPLOY_ARTIFACT_REQUEST;
msoute/vertx-deploy-tools
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/executor/DefaultRequestExecutor.java
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployRequest.java // @SuppressWarnings("unused") // @JsonIgnoreProperties({"endpoint"}) // public class DeployRequest { // // private static final ObjectWriter writer = new ObjectMapper().writer(); // private static final String ENDPOINT = "/deploy/deploy"; // // @JsonProperty // private final List<Request> modules; // @JsonProperty // private final List<Request> artifacts; // @JsonProperty // private final List<Request> configs; // // @JsonProperty("with_elb") // private final boolean elb; // @JsonProperty("with_as") // private final boolean autoScaling; // @JsonProperty("restart") // private final boolean restart; // @JsonProperty(value = "as_group_id") // private final String asGroupId; // @JsonProperty(value = "as_decrement_desired_capacity") // private final boolean decrementDesiredCapacity; // @JsonProperty(value = "test_scope") // private final boolean testScope; // // private DeployRequest(List<Request> modules, List<Request> artifacts, List<Request> configs, boolean elb, boolean restart, String asGroupId, boolean decrementDesiredCapacity, boolean testScope) { // this.modules = modules; // this.artifacts = artifacts; // this.configs = configs; // this.elb = elb; // this.restart = restart; // this.asGroupId = asGroupId; // this.decrementDesiredCapacity = decrementDesiredCapacity; // this.autoScaling = (asGroupId != null); // this.testScope = testScope; // } // // public String toJson(boolean pretty) { // try { // if (pretty) { // return writer.withDefaultPrettyPrinter().writeValueAsString(this); // } // return writer.writeValueAsString(this); // // } catch (JsonProcessingException e) { // return ""; // } // } // // public String getEndpoint() { // return ENDPOINT; // } // // public static class Builder { // // private List<Request> modules = new ArrayList<>(); // private List<Request> artifacts = new ArrayList<>(); // private List<Request> configs = new ArrayList<>(); // private boolean elb = false; // private boolean restart = true; // private boolean decrementDesiredCapacity = true; // private String autoScalingGroup = ""; // private boolean testScope = false; // // public Builder withElb(final boolean elb) { // this.elb = elb; // return this; // } // // public Builder withRestart(final boolean restart) { // this.restart = restart; // return this; // } // // public Builder withModules(final List<Request> modules) { // this.modules = modules; // return this; // } // // public Builder withArtifacts(final List<Request> artifacts) { // this.artifacts = artifacts; // return this; // } // // public Builder withConfigs(final List<Request> configs) { // this.configs = configs; // return this; // } // // public Builder withTestScope(boolean testScope) { // this.testScope = testScope; // return this; // } // // public Builder withAutoScalingGroup(final String autoScalingGroup) { // this.autoScalingGroup = autoScalingGroup; // return this; // } // // public Builder withDecrementDesiredCapacity(final boolean decrementDesiredCapacity) { // this.decrementDesiredCapacity = decrementDesiredCapacity; // return this; // } // // // public DeployRequest build() { // return new DeployRequest(modules, artifacts, configs, elb, restart, autoScalingGroup, decrementDesiredCapacity, testScope); // } // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsState.java // public enum AwsState { // UNKNOWN, // TERMINATING, // NOTREGISTERED, // OUTOFSERVICE, // ENTERINGSTANDBY, // STANDBY, // PENDING, // RUNNING, // INSERVICE; // // public static AwsState map(String state) { // if (state == null || state.isEmpty()) { // return UNKNOWN; // } // try { // return AwsState.valueOf(state.toUpperCase()); // } catch (IllegalArgumentException e) { // return UNKNOWN; // } // } // }
import nl.jpoint.maven.vertx.request.DeployRequest; import nl.jpoint.maven.vertx.utils.AwsState; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
package nl.jpoint.maven.vertx.executor; public class DefaultRequestExecutor extends RequestExecutor { public DefaultRequestExecutor(Log log, Integer requestTimeout, Integer port, String authToken) { super(log, requestTimeout, port, authToken); }
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployRequest.java // @SuppressWarnings("unused") // @JsonIgnoreProperties({"endpoint"}) // public class DeployRequest { // // private static final ObjectWriter writer = new ObjectMapper().writer(); // private static final String ENDPOINT = "/deploy/deploy"; // // @JsonProperty // private final List<Request> modules; // @JsonProperty // private final List<Request> artifacts; // @JsonProperty // private final List<Request> configs; // // @JsonProperty("with_elb") // private final boolean elb; // @JsonProperty("with_as") // private final boolean autoScaling; // @JsonProperty("restart") // private final boolean restart; // @JsonProperty(value = "as_group_id") // private final String asGroupId; // @JsonProperty(value = "as_decrement_desired_capacity") // private final boolean decrementDesiredCapacity; // @JsonProperty(value = "test_scope") // private final boolean testScope; // // private DeployRequest(List<Request> modules, List<Request> artifacts, List<Request> configs, boolean elb, boolean restart, String asGroupId, boolean decrementDesiredCapacity, boolean testScope) { // this.modules = modules; // this.artifacts = artifacts; // this.configs = configs; // this.elb = elb; // this.restart = restart; // this.asGroupId = asGroupId; // this.decrementDesiredCapacity = decrementDesiredCapacity; // this.autoScaling = (asGroupId != null); // this.testScope = testScope; // } // // public String toJson(boolean pretty) { // try { // if (pretty) { // return writer.withDefaultPrettyPrinter().writeValueAsString(this); // } // return writer.writeValueAsString(this); // // } catch (JsonProcessingException e) { // return ""; // } // } // // public String getEndpoint() { // return ENDPOINT; // } // // public static class Builder { // // private List<Request> modules = new ArrayList<>(); // private List<Request> artifacts = new ArrayList<>(); // private List<Request> configs = new ArrayList<>(); // private boolean elb = false; // private boolean restart = true; // private boolean decrementDesiredCapacity = true; // private String autoScalingGroup = ""; // private boolean testScope = false; // // public Builder withElb(final boolean elb) { // this.elb = elb; // return this; // } // // public Builder withRestart(final boolean restart) { // this.restart = restart; // return this; // } // // public Builder withModules(final List<Request> modules) { // this.modules = modules; // return this; // } // // public Builder withArtifacts(final List<Request> artifacts) { // this.artifacts = artifacts; // return this; // } // // public Builder withConfigs(final List<Request> configs) { // this.configs = configs; // return this; // } // // public Builder withTestScope(boolean testScope) { // this.testScope = testScope; // return this; // } // // public Builder withAutoScalingGroup(final String autoScalingGroup) { // this.autoScalingGroup = autoScalingGroup; // return this; // } // // public Builder withDecrementDesiredCapacity(final boolean decrementDesiredCapacity) { // this.decrementDesiredCapacity = decrementDesiredCapacity; // return this; // } // // // public DeployRequest build() { // return new DeployRequest(modules, artifacts, configs, elb, restart, autoScalingGroup, decrementDesiredCapacity, testScope); // } // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsState.java // public enum AwsState { // UNKNOWN, // TERMINATING, // NOTREGISTERED, // OUTOFSERVICE, // ENTERINGSTANDBY, // STANDBY, // PENDING, // RUNNING, // INSERVICE; // // public static AwsState map(String state) { // if (state == null || state.isEmpty()) { // return UNKNOWN; // } // try { // return AwsState.valueOf(state.toUpperCase()); // } catch (IllegalArgumentException e) { // return UNKNOWN; // } // } // } // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/executor/DefaultRequestExecutor.java import nl.jpoint.maven.vertx.request.DeployRequest; import nl.jpoint.maven.vertx.utils.AwsState; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; package nl.jpoint.maven.vertx.executor; public class DefaultRequestExecutor extends RequestExecutor { public DefaultRequestExecutor(Log log, Integer requestTimeout, Integer port, String authToken) { super(log, requestTimeout, port, authToken); }
private AwsState executeRequest(final HttpPost postRequest) throws MojoExecutionException {
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/MetadataXPathUtil.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/ModuleRequest.java // public abstract class ModuleRequest { // // public static final String CONFIG_TYPE = "config"; // public static final String ZIP_TYPE = "zip"; // public static final String GZIP_TYPE = "tar.gz"; // // private final UUID id = UUID.randomUUID(); // private final String groupId; // private final String artifactId; // private final String classifier; // private final String type; // private final String remoteBase; // private final boolean snapshot; // private String version; // // private boolean restart = false; // // private Optional<String> restartCommand; // private Optional<String> testCommand; // private Path baseLocation; // // // ModuleRequest(final String groupId, final String artifactId, final String version, final String classifier, final String type) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // this.classifier = classifier; // this.type = type != null ? type : "jar"; // this.snapshot = version.endsWith("-SNAPSHOT"); // this.remoteBase = groupId.replaceAll("\\.", "/") + "/" + artifactId + "/" + version + "/"; // } // // public String getGroupId() { // return groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public UUID getId() { // return id; // } // // public String getModuleId() { // return this.groupId + ":" + this.artifactId + ":" + this.version; // } // // public String getMavenArtifactId() { // return this.groupId + ":" + this.artifactId; // } // // public String getRemoteLocation() { // return remoteBase + getFileName(); // } // // public Path getLocalPath(Path localRepo) { // if (!Objects.equals(type, "jar")) { // return localRepo.resolve(getFileName()); // } // return null; // } // // public String getFileName() { // StringBuilder builder = new StringBuilder() // .append(getArtifactId()).append("-"); // builder.append(version); // if (classifier != null && !classifier.isEmpty()) { // builder.append("-") // .append(classifier); // } // builder.append("."); // builder.append(type); // // return builder.toString(); // // } // // public boolean isSnapshot() { // return snapshot; // } // // public String getMetadataLocation() { // return remoteBase + "maven-metadata.xml"; // // } // // public String getType() { // return type; // } // // public boolean restart() { // return restart; // } // // public void setRestart(boolean restart) { // this.restart = restart; // } // // public Optional<String> getRestartCommand() { // return restartCommand; // } // // public void setRestartCommand(String restartCommand) { // this.restartCommand = (restartCommand == null || restartCommand.isEmpty()) ? Optional.empty() : Optional.of(restartCommand); // } // // public Optional<String> getTestCommand() { // return testCommand; // } // // public void setTestCommand(String testCommand) { // this.testCommand = (testCommand == null || testCommand.isEmpty()) ? Optional.empty() : Optional.of(testCommand); // } // // public Path getBaseLocation() { // return baseLocation; // } // // public void setBaseLocation(String baseLocation) { // this.baseLocation = Paths.get(baseLocation); // } // // public abstract boolean deleteBase(); // // public abstract boolean checkConfig(); // // public abstract String getLogName(); // // }
import nl.jpoint.vertx.deploy.agent.request.ModuleRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException;
package nl.jpoint.vertx.deploy.agent.util; public class MetadataXPathUtil { private static final String TIMESTAMP = "/metadata/versioning/snapshot/timestamp/text()"; private static final String BUILD_NUMBER = "/metadata/versioning/snapshot/buildNumber/text()"; private static final Logger LOG = LoggerFactory.getLogger(MetadataXPathUtil.class);
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/ModuleRequest.java // public abstract class ModuleRequest { // // public static final String CONFIG_TYPE = "config"; // public static final String ZIP_TYPE = "zip"; // public static final String GZIP_TYPE = "tar.gz"; // // private final UUID id = UUID.randomUUID(); // private final String groupId; // private final String artifactId; // private final String classifier; // private final String type; // private final String remoteBase; // private final boolean snapshot; // private String version; // // private boolean restart = false; // // private Optional<String> restartCommand; // private Optional<String> testCommand; // private Path baseLocation; // // // ModuleRequest(final String groupId, final String artifactId, final String version, final String classifier, final String type) { // this.groupId = groupId; // this.artifactId = artifactId; // this.version = version; // this.classifier = classifier; // this.type = type != null ? type : "jar"; // this.snapshot = version.endsWith("-SNAPSHOT"); // this.remoteBase = groupId.replaceAll("\\.", "/") + "/" + artifactId + "/" + version + "/"; // } // // public String getGroupId() { // return groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public UUID getId() { // return id; // } // // public String getModuleId() { // return this.groupId + ":" + this.artifactId + ":" + this.version; // } // // public String getMavenArtifactId() { // return this.groupId + ":" + this.artifactId; // } // // public String getRemoteLocation() { // return remoteBase + getFileName(); // } // // public Path getLocalPath(Path localRepo) { // if (!Objects.equals(type, "jar")) { // return localRepo.resolve(getFileName()); // } // return null; // } // // public String getFileName() { // StringBuilder builder = new StringBuilder() // .append(getArtifactId()).append("-"); // builder.append(version); // if (classifier != null && !classifier.isEmpty()) { // builder.append("-") // .append(classifier); // } // builder.append("."); // builder.append(type); // // return builder.toString(); // // } // // public boolean isSnapshot() { // return snapshot; // } // // public String getMetadataLocation() { // return remoteBase + "maven-metadata.xml"; // // } // // public String getType() { // return type; // } // // public boolean restart() { // return restart; // } // // public void setRestart(boolean restart) { // this.restart = restart; // } // // public Optional<String> getRestartCommand() { // return restartCommand; // } // // public void setRestartCommand(String restartCommand) { // this.restartCommand = (restartCommand == null || restartCommand.isEmpty()) ? Optional.empty() : Optional.of(restartCommand); // } // // public Optional<String> getTestCommand() { // return testCommand; // } // // public void setTestCommand(String testCommand) { // this.testCommand = (testCommand == null || testCommand.isEmpty()) ? Optional.empty() : Optional.of(testCommand); // } // // public Path getBaseLocation() { // return baseLocation; // } // // public void setBaseLocation(String baseLocation) { // this.baseLocation = Paths.get(baseLocation); // } // // public abstract boolean deleteBase(); // // public abstract boolean checkConfig(); // // public abstract String getLogName(); // // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/MetadataXPathUtil.java import nl.jpoint.vertx.deploy.agent.request.ModuleRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; package nl.jpoint.vertx.deploy.agent.util; public class MetadataXPathUtil { private static final String TIMESTAMP = "/metadata/versioning/snapshot/timestamp/text()"; private static final String BUILD_NUMBER = "/metadata/versioning/snapshot/buildNumber/text()"; private static final Logger LOG = LoggerFactory.getLogger(MetadataXPathUtil.class);
public static String getRealSnapshotVersionFromMetadata(byte[] metadata, ModuleRequest request) {
msoute/vertx-deploy-tools
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/executor/RequestExecutor.java
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployRequest.java // @SuppressWarnings("unused") // @JsonIgnoreProperties({"endpoint"}) // public class DeployRequest { // // private static final ObjectWriter writer = new ObjectMapper().writer(); // private static final String ENDPOINT = "/deploy/deploy"; // // @JsonProperty // private final List<Request> modules; // @JsonProperty // private final List<Request> artifacts; // @JsonProperty // private final List<Request> configs; // // @JsonProperty("with_elb") // private final boolean elb; // @JsonProperty("with_as") // private final boolean autoScaling; // @JsonProperty("restart") // private final boolean restart; // @JsonProperty(value = "as_group_id") // private final String asGroupId; // @JsonProperty(value = "as_decrement_desired_capacity") // private final boolean decrementDesiredCapacity; // @JsonProperty(value = "test_scope") // private final boolean testScope; // // private DeployRequest(List<Request> modules, List<Request> artifacts, List<Request> configs, boolean elb, boolean restart, String asGroupId, boolean decrementDesiredCapacity, boolean testScope) { // this.modules = modules; // this.artifacts = artifacts; // this.configs = configs; // this.elb = elb; // this.restart = restart; // this.asGroupId = asGroupId; // this.decrementDesiredCapacity = decrementDesiredCapacity; // this.autoScaling = (asGroupId != null); // this.testScope = testScope; // } // // public String toJson(boolean pretty) { // try { // if (pretty) { // return writer.withDefaultPrettyPrinter().writeValueAsString(this); // } // return writer.writeValueAsString(this); // // } catch (JsonProcessingException e) { // return ""; // } // } // // public String getEndpoint() { // return ENDPOINT; // } // // public static class Builder { // // private List<Request> modules = new ArrayList<>(); // private List<Request> artifacts = new ArrayList<>(); // private List<Request> configs = new ArrayList<>(); // private boolean elb = false; // private boolean restart = true; // private boolean decrementDesiredCapacity = true; // private String autoScalingGroup = ""; // private boolean testScope = false; // // public Builder withElb(final boolean elb) { // this.elb = elb; // return this; // } // // public Builder withRestart(final boolean restart) { // this.restart = restart; // return this; // } // // public Builder withModules(final List<Request> modules) { // this.modules = modules; // return this; // } // // public Builder withArtifacts(final List<Request> artifacts) { // this.artifacts = artifacts; // return this; // } // // public Builder withConfigs(final List<Request> configs) { // this.configs = configs; // return this; // } // // public Builder withTestScope(boolean testScope) { // this.testScope = testScope; // return this; // } // // public Builder withAutoScalingGroup(final String autoScalingGroup) { // this.autoScalingGroup = autoScalingGroup; // return this; // } // // public Builder withDecrementDesiredCapacity(final boolean decrementDesiredCapacity) { // this.decrementDesiredCapacity = decrementDesiredCapacity; // return this; // } // // // public DeployRequest build() { // return new DeployRequest(modules, artifacts, configs, elb, restart, autoScalingGroup, decrementDesiredCapacity, testScope); // } // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsState.java // public enum AwsState { // UNKNOWN, // TERMINATING, // NOTREGISTERED, // OUTOFSERVICE, // ENTERINGSTANDBY, // STANDBY, // PENDING, // RUNNING, // INSERVICE; // // public static AwsState map(String state) { // if (state == null || state.isEmpty()) { // return UNKNOWN; // } // try { // return AwsState.valueOf(state.toUpperCase()); // } catch (IllegalArgumentException e) { // return UNKNOWN; // } // } // }
import com.amazonaws.util.StringUtils; import nl.jpoint.maven.vertx.request.DeployRequest; import nl.jpoint.maven.vertx.utils.AwsState; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.BasicHttpEntity; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import java.io.ByteArrayInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Date;
package nl.jpoint.maven.vertx.executor; public abstract class RequestExecutor { final Log log; private final Integer port; private final String authToken; private final long timeout; RequestExecutor(Log log, Integer requestTimeout, Integer port, String authToken) { this.log = log; this.port = port; this.authToken = authToken != null ? authToken : ""; this.timeout = System.currentTimeMillis() + (60000L * requestTimeout); log.info("Setting timeout to : " + new Date(timeout)); }
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployRequest.java // @SuppressWarnings("unused") // @JsonIgnoreProperties({"endpoint"}) // public class DeployRequest { // // private static final ObjectWriter writer = new ObjectMapper().writer(); // private static final String ENDPOINT = "/deploy/deploy"; // // @JsonProperty // private final List<Request> modules; // @JsonProperty // private final List<Request> artifacts; // @JsonProperty // private final List<Request> configs; // // @JsonProperty("with_elb") // private final boolean elb; // @JsonProperty("with_as") // private final boolean autoScaling; // @JsonProperty("restart") // private final boolean restart; // @JsonProperty(value = "as_group_id") // private final String asGroupId; // @JsonProperty(value = "as_decrement_desired_capacity") // private final boolean decrementDesiredCapacity; // @JsonProperty(value = "test_scope") // private final boolean testScope; // // private DeployRequest(List<Request> modules, List<Request> artifacts, List<Request> configs, boolean elb, boolean restart, String asGroupId, boolean decrementDesiredCapacity, boolean testScope) { // this.modules = modules; // this.artifacts = artifacts; // this.configs = configs; // this.elb = elb; // this.restart = restart; // this.asGroupId = asGroupId; // this.decrementDesiredCapacity = decrementDesiredCapacity; // this.autoScaling = (asGroupId != null); // this.testScope = testScope; // } // // public String toJson(boolean pretty) { // try { // if (pretty) { // return writer.withDefaultPrettyPrinter().writeValueAsString(this); // } // return writer.writeValueAsString(this); // // } catch (JsonProcessingException e) { // return ""; // } // } // // public String getEndpoint() { // return ENDPOINT; // } // // public static class Builder { // // private List<Request> modules = new ArrayList<>(); // private List<Request> artifacts = new ArrayList<>(); // private List<Request> configs = new ArrayList<>(); // private boolean elb = false; // private boolean restart = true; // private boolean decrementDesiredCapacity = true; // private String autoScalingGroup = ""; // private boolean testScope = false; // // public Builder withElb(final boolean elb) { // this.elb = elb; // return this; // } // // public Builder withRestart(final boolean restart) { // this.restart = restart; // return this; // } // // public Builder withModules(final List<Request> modules) { // this.modules = modules; // return this; // } // // public Builder withArtifacts(final List<Request> artifacts) { // this.artifacts = artifacts; // return this; // } // // public Builder withConfigs(final List<Request> configs) { // this.configs = configs; // return this; // } // // public Builder withTestScope(boolean testScope) { // this.testScope = testScope; // return this; // } // // public Builder withAutoScalingGroup(final String autoScalingGroup) { // this.autoScalingGroup = autoScalingGroup; // return this; // } // // public Builder withDecrementDesiredCapacity(final boolean decrementDesiredCapacity) { // this.decrementDesiredCapacity = decrementDesiredCapacity; // return this; // } // // // public DeployRequest build() { // return new DeployRequest(modules, artifacts, configs, elb, restart, autoScalingGroup, decrementDesiredCapacity, testScope); // } // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsState.java // public enum AwsState { // UNKNOWN, // TERMINATING, // NOTREGISTERED, // OUTOFSERVICE, // ENTERINGSTANDBY, // STANDBY, // PENDING, // RUNNING, // INSERVICE; // // public static AwsState map(String state) { // if (state == null || state.isEmpty()) { // return UNKNOWN; // } // try { // return AwsState.valueOf(state.toUpperCase()); // } catch (IllegalArgumentException e) { // return UNKNOWN; // } // } // } // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/executor/RequestExecutor.java import com.amazonaws.util.StringUtils; import nl.jpoint.maven.vertx.request.DeployRequest; import nl.jpoint.maven.vertx.utils.AwsState; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.BasicHttpEntity; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import java.io.ByteArrayInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; package nl.jpoint.maven.vertx.executor; public abstract class RequestExecutor { final Log log; private final Integer port; private final String authToken; private final long timeout; RequestExecutor(Log log, Integer requestTimeout, Integer port, String authToken) { this.log = log; this.port = port; this.authToken = authToken != null ? authToken : ""; this.timeout = System.currentTimeMillis() + (60000L * requestTimeout); log.info("Setting timeout to : " + new Date(timeout)); }
HttpPost createPost(DeployRequest deployRequest, String host) {
msoute/vertx-deploy-tools
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/executor/RequestExecutor.java
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployRequest.java // @SuppressWarnings("unused") // @JsonIgnoreProperties({"endpoint"}) // public class DeployRequest { // // private static final ObjectWriter writer = new ObjectMapper().writer(); // private static final String ENDPOINT = "/deploy/deploy"; // // @JsonProperty // private final List<Request> modules; // @JsonProperty // private final List<Request> artifacts; // @JsonProperty // private final List<Request> configs; // // @JsonProperty("with_elb") // private final boolean elb; // @JsonProperty("with_as") // private final boolean autoScaling; // @JsonProperty("restart") // private final boolean restart; // @JsonProperty(value = "as_group_id") // private final String asGroupId; // @JsonProperty(value = "as_decrement_desired_capacity") // private final boolean decrementDesiredCapacity; // @JsonProperty(value = "test_scope") // private final boolean testScope; // // private DeployRequest(List<Request> modules, List<Request> artifacts, List<Request> configs, boolean elb, boolean restart, String asGroupId, boolean decrementDesiredCapacity, boolean testScope) { // this.modules = modules; // this.artifacts = artifacts; // this.configs = configs; // this.elb = elb; // this.restart = restart; // this.asGroupId = asGroupId; // this.decrementDesiredCapacity = decrementDesiredCapacity; // this.autoScaling = (asGroupId != null); // this.testScope = testScope; // } // // public String toJson(boolean pretty) { // try { // if (pretty) { // return writer.withDefaultPrettyPrinter().writeValueAsString(this); // } // return writer.writeValueAsString(this); // // } catch (JsonProcessingException e) { // return ""; // } // } // // public String getEndpoint() { // return ENDPOINT; // } // // public static class Builder { // // private List<Request> modules = new ArrayList<>(); // private List<Request> artifacts = new ArrayList<>(); // private List<Request> configs = new ArrayList<>(); // private boolean elb = false; // private boolean restart = true; // private boolean decrementDesiredCapacity = true; // private String autoScalingGroup = ""; // private boolean testScope = false; // // public Builder withElb(final boolean elb) { // this.elb = elb; // return this; // } // // public Builder withRestart(final boolean restart) { // this.restart = restart; // return this; // } // // public Builder withModules(final List<Request> modules) { // this.modules = modules; // return this; // } // // public Builder withArtifacts(final List<Request> artifacts) { // this.artifacts = artifacts; // return this; // } // // public Builder withConfigs(final List<Request> configs) { // this.configs = configs; // return this; // } // // public Builder withTestScope(boolean testScope) { // this.testScope = testScope; // return this; // } // // public Builder withAutoScalingGroup(final String autoScalingGroup) { // this.autoScalingGroup = autoScalingGroup; // return this; // } // // public Builder withDecrementDesiredCapacity(final boolean decrementDesiredCapacity) { // this.decrementDesiredCapacity = decrementDesiredCapacity; // return this; // } // // // public DeployRequest build() { // return new DeployRequest(modules, artifacts, configs, elb, restart, autoScalingGroup, decrementDesiredCapacity, testScope); // } // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsState.java // public enum AwsState { // UNKNOWN, // TERMINATING, // NOTREGISTERED, // OUTOFSERVICE, // ENTERINGSTANDBY, // STANDBY, // PENDING, // RUNNING, // INSERVICE; // // public static AwsState map(String state) { // if (state == null || state.isEmpty()) { // return UNKNOWN; // } // try { // return AwsState.valueOf(state.toUpperCase()); // } catch (IllegalArgumentException e) { // return UNKNOWN; // } // } // }
import com.amazonaws.util.StringUtils; import nl.jpoint.maven.vertx.request.DeployRequest; import nl.jpoint.maven.vertx.utils.AwsState; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.BasicHttpEntity; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import java.io.ByteArrayInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Date;
log.info("Deploying to host : " + deployUri.toString()); HttpPost post = new HttpPost(deployUri); if (!StringUtils.isNullOrEmpty(authToken)) { log.info("Adding authToken to request header."); post.addHeader("authToken", authToken); } ByteArrayInputStream bos = new ByteArrayInputStream(deployRequest.toJson(false).getBytes()); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(bos); entity.setContentLength(deployRequest.toJson(false).getBytes().length); post.setEntity(entity); return post; } private URI createDeployUri(String host, String endpoint) { try { return new URIBuilder().setScheme("http").setHost(host).setPort(port).setPath(endpoint).build(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } long getTimeout() { return timeout; }
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployRequest.java // @SuppressWarnings("unused") // @JsonIgnoreProperties({"endpoint"}) // public class DeployRequest { // // private static final ObjectWriter writer = new ObjectMapper().writer(); // private static final String ENDPOINT = "/deploy/deploy"; // // @JsonProperty // private final List<Request> modules; // @JsonProperty // private final List<Request> artifacts; // @JsonProperty // private final List<Request> configs; // // @JsonProperty("with_elb") // private final boolean elb; // @JsonProperty("with_as") // private final boolean autoScaling; // @JsonProperty("restart") // private final boolean restart; // @JsonProperty(value = "as_group_id") // private final String asGroupId; // @JsonProperty(value = "as_decrement_desired_capacity") // private final boolean decrementDesiredCapacity; // @JsonProperty(value = "test_scope") // private final boolean testScope; // // private DeployRequest(List<Request> modules, List<Request> artifacts, List<Request> configs, boolean elb, boolean restart, String asGroupId, boolean decrementDesiredCapacity, boolean testScope) { // this.modules = modules; // this.artifacts = artifacts; // this.configs = configs; // this.elb = elb; // this.restart = restart; // this.asGroupId = asGroupId; // this.decrementDesiredCapacity = decrementDesiredCapacity; // this.autoScaling = (asGroupId != null); // this.testScope = testScope; // } // // public String toJson(boolean pretty) { // try { // if (pretty) { // return writer.withDefaultPrettyPrinter().writeValueAsString(this); // } // return writer.writeValueAsString(this); // // } catch (JsonProcessingException e) { // return ""; // } // } // // public String getEndpoint() { // return ENDPOINT; // } // // public static class Builder { // // private List<Request> modules = new ArrayList<>(); // private List<Request> artifacts = new ArrayList<>(); // private List<Request> configs = new ArrayList<>(); // private boolean elb = false; // private boolean restart = true; // private boolean decrementDesiredCapacity = true; // private String autoScalingGroup = ""; // private boolean testScope = false; // // public Builder withElb(final boolean elb) { // this.elb = elb; // return this; // } // // public Builder withRestart(final boolean restart) { // this.restart = restart; // return this; // } // // public Builder withModules(final List<Request> modules) { // this.modules = modules; // return this; // } // // public Builder withArtifacts(final List<Request> artifacts) { // this.artifacts = artifacts; // return this; // } // // public Builder withConfigs(final List<Request> configs) { // this.configs = configs; // return this; // } // // public Builder withTestScope(boolean testScope) { // this.testScope = testScope; // return this; // } // // public Builder withAutoScalingGroup(final String autoScalingGroup) { // this.autoScalingGroup = autoScalingGroup; // return this; // } // // public Builder withDecrementDesiredCapacity(final boolean decrementDesiredCapacity) { // this.decrementDesiredCapacity = decrementDesiredCapacity; // return this; // } // // // public DeployRequest build() { // return new DeployRequest(modules, artifacts, configs, elb, restart, autoScalingGroup, decrementDesiredCapacity, testScope); // } // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsState.java // public enum AwsState { // UNKNOWN, // TERMINATING, // NOTREGISTERED, // OUTOFSERVICE, // ENTERINGSTANDBY, // STANDBY, // PENDING, // RUNNING, // INSERVICE; // // public static AwsState map(String state) { // if (state == null || state.isEmpty()) { // return UNKNOWN; // } // try { // return AwsState.valueOf(state.toUpperCase()); // } catch (IllegalArgumentException e) { // return UNKNOWN; // } // } // } // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/executor/RequestExecutor.java import com.amazonaws.util.StringUtils; import nl.jpoint.maven.vertx.request.DeployRequest; import nl.jpoint.maven.vertx.utils.AwsState; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.BasicHttpEntity; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import java.io.ByteArrayInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; log.info("Deploying to host : " + deployUri.toString()); HttpPost post = new HttpPost(deployUri); if (!StringUtils.isNullOrEmpty(authToken)) { log.info("Adding authToken to request header."); post.addHeader("authToken", authToken); } ByteArrayInputStream bos = new ByteArrayInputStream(deployRequest.toJson(false).getBytes()); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(bos); entity.setContentLength(deployRequest.toJson(false).getBytes().length); post.setEntity(entity); return post; } private URI createDeployUri(String host, String endpoint) { try { return new URIBuilder().setScheme("http").setHost(host).setPort(port).setPath(endpoint).build(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } long getTimeout() { return timeout; }
public abstract AwsState executeRequest(DeployRequest deployRequest, String host, boolean ignoreFailure) throws MojoExecutionException, MojoFailureException;
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployArtifactRequest.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.jpoint.vertx.deploy.agent.util.LogConstants;
package nl.jpoint.vertx.deploy.agent.request; @JsonIgnoreProperties(ignoreUnknown = true) public class DeployArtifactRequest extends ModuleRequest { @JsonCreator private DeployArtifactRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { super(groupId, artifactId, version, classifier, type); } @Override public boolean deleteBase() { return true; } @Override public boolean checkConfig() { return false; } @Override public String getLogName() {
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployArtifactRequest.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.jpoint.vertx.deploy.agent.util.LogConstants; package nl.jpoint.vertx.deploy.agent.request; @JsonIgnoreProperties(ignoreUnknown = true) public class DeployArtifactRequest extends ModuleRequest { @JsonCreator private DeployArtifactRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { super(groupId, artifactId, version, classifier, type); } @Override public boolean deleteBase() { return true; } @Override public boolean checkConfig() { return false; } @Override public String getLogName() {
return LogConstants.DEPLOY_ARTIFACT_REQUEST;
msoute/vertx-deploy-tools
vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployConfigRequest.java
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import nl.jpoint.vertx.deploy.agent.util.LogConstants;
package nl.jpoint.vertx.deploy.agent.request; public class DeployConfigRequest extends ModuleRequest { @JsonCreator private DeployConfigRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { super(groupId, artifactId, version, classifier, type); } public static DeployConfigRequest build(String groupId, String artifactId, String version, String classifier) { return new DeployConfigRequest(groupId, artifactId, version, classifier, "config"); } @Override public boolean deleteBase() { return false; } @Override public boolean checkConfig() { return true; } @Override public String getLogName() {
// Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/util/LogConstants.java // public final class LogConstants { // public static final String ERROR_EXECUTING_REQUEST = "Error executing request {}."; // public static final String REQUEST_ALREADY_REGISTERED = "[{} - {}]: Request already registered."; // public static final String REQUEST_NOT_REGISTERED = "[{} - {}]: Request not registered."; // // // public static final String INVOKE_CONTAINER = "InvokeContainer"; // public static final String CONSOLE_COMMAND = "ConsoleCommand"; // public static final String CLUSTER_MANAGER = "ClusterManager"; // public static final String DEPLOY_REQUEST = "DeployRequest"; // public static final String DEPLOY_CONFIG_REQUEST = "DeployConfigRequest"; // public static final String DEPLOY_ARTIFACT_REQUEST = "DeployArtifactRequest"; // public static final String AWS_ELB_REQUEST = "ConfigureAwsElb"; // public static final String AWS_AS_REQUEST = "ConfigureAwsAutoScaling"; // public static final String STARTUP = "Startup"; // // private LogConstants() { // // hide // } // } // Path: vertx-deploy-agent/src/main/java/nl/jpoint/vertx/deploy/agent/request/DeployConfigRequest.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import nl.jpoint.vertx.deploy.agent.util.LogConstants; package nl.jpoint.vertx.deploy.agent.request; public class DeployConfigRequest extends ModuleRequest { @JsonCreator private DeployConfigRequest(@JsonProperty("group_id") final String groupId, @JsonProperty("artifact_id") final String artifactId, @JsonProperty("version") final String version, @JsonProperty("classifier") final String classifier, @JsonProperty("type") final String type) { super(groupId, artifactId, version, classifier, type); } public static DeployConfigRequest build(String groupId, String artifactId, String version, String classifier) { return new DeployConfigRequest(groupId, artifactId, version, classifier, "config"); } @Override public boolean deleteBase() { return false; } @Override public boolean checkConfig() { return true; } @Override public String getLogName() {
return LogConstants.DEPLOY_CONFIG_REQUEST;
msoute/vertx-deploy-tools
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/mojo/DeployConfiguration.java
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/DeployType.java // public enum DeployType { // APPLICATION("application:"), // ARTIFACT("artifact:"), // DEFAULT(""); // // private static final String LATEST_REQUEST_TAG = "latest:version"; // private static final String SCOPE_TAG = "scope:tst"; // private static final String EXCLUSION_TAG = "exclusions"; // private static final String PROPERTIES_TAG = "classifier:properties"; // // private final String type; // private final String prefix = "deploy"; // // DeployType(String type) { // this.type = type; // } // // public String getLatestRequestTag() { // return prefix + ":" + type + LATEST_REQUEST_TAG; // } // // public String getScopeTag() { // return prefix + ":" + type + SCOPE_TAG; // } // // public String getExclusionTag() { // return prefix + ":" + type + EXCLUSION_TAG; // } // // public String getPropertiesTag() { // return prefix + ":" + type + PROPERTIES_TAG; // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/deploy/strategy/DeployStrategyType.java // public enum DeployStrategyType { // WHATEVER, // DEFAULT, // GUARANTEE_MINIMUM, // SPIN_AND_REMOVE, // KEEP_CAPACITY // }
import nl.jpoint.maven.vertx.utils.DeployType; import nl.jpoint.maven.vertx.utils.deploy.strategy.DeployStrategyType; import org.apache.maven.model.Exclusion; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors;
package nl.jpoint.maven.vertx.mojo; public class DeployConfiguration { /** * The maven project version as String (groupId:artifactId:version) */ private String projectVersion; /** * The configuration target id **/ private String target; /** * List of hosts to deploy to **/ private final List<String> hosts = new ArrayList<>(); /** * The port where the agent is listening on */ private int port = 6789; /** * Enable / disable deploy of config objects **/ private boolean deployConfig = true; /** * List of artifacts to exclude **/ private List<Exclusion> exclusions = new ArrayList<>(); /** * Deploy artifacts in test scope **/ private boolean testScope = false; /** * restart all modules on host **/ private boolean restart = false; /** * Allow deploy of snapshots **/ private boolean deploySnapshots = false; /** * AWS Generic Properties * Use public / private AWS ip's **/ private boolean awsPrivateIp = false; private boolean useAutoScaling = false; private boolean elb = false; private boolean stickiness = false; private List<String> stickyPorts = new ArrayList<>(Collections.singletonList("443")); /** * AWS AutoScaling Properties **/ private String autoScalingGroupId; private boolean ignoreInStandby = false; private boolean decrementDesiredCapacity = true;
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/DeployType.java // public enum DeployType { // APPLICATION("application:"), // ARTIFACT("artifact:"), // DEFAULT(""); // // private static final String LATEST_REQUEST_TAG = "latest:version"; // private static final String SCOPE_TAG = "scope:tst"; // private static final String EXCLUSION_TAG = "exclusions"; // private static final String PROPERTIES_TAG = "classifier:properties"; // // private final String type; // private final String prefix = "deploy"; // // DeployType(String type) { // this.type = type; // } // // public String getLatestRequestTag() { // return prefix + ":" + type + LATEST_REQUEST_TAG; // } // // public String getScopeTag() { // return prefix + ":" + type + SCOPE_TAG; // } // // public String getExclusionTag() { // return prefix + ":" + type + EXCLUSION_TAG; // } // // public String getPropertiesTag() { // return prefix + ":" + type + PROPERTIES_TAG; // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/deploy/strategy/DeployStrategyType.java // public enum DeployStrategyType { // WHATEVER, // DEFAULT, // GUARANTEE_MINIMUM, // SPIN_AND_REMOVE, // KEEP_CAPACITY // } // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/mojo/DeployConfiguration.java import nl.jpoint.maven.vertx.utils.DeployType; import nl.jpoint.maven.vertx.utils.deploy.strategy.DeployStrategyType; import org.apache.maven.model.Exclusion; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; package nl.jpoint.maven.vertx.mojo; public class DeployConfiguration { /** * The maven project version as String (groupId:artifactId:version) */ private String projectVersion; /** * The configuration target id **/ private String target; /** * List of hosts to deploy to **/ private final List<String> hosts = new ArrayList<>(); /** * The port where the agent is listening on */ private int port = 6789; /** * Enable / disable deploy of config objects **/ private boolean deployConfig = true; /** * List of artifacts to exclude **/ private List<Exclusion> exclusions = new ArrayList<>(); /** * Deploy artifacts in test scope **/ private boolean testScope = false; /** * restart all modules on host **/ private boolean restart = false; /** * Allow deploy of snapshots **/ private boolean deploySnapshots = false; /** * AWS Generic Properties * Use public / private AWS ip's **/ private boolean awsPrivateIp = false; private boolean useAutoScaling = false; private boolean elb = false; private boolean stickiness = false; private List<String> stickyPorts = new ArrayList<>(Collections.singletonList("443")); /** * AWS AutoScaling Properties **/ private String autoScalingGroupId; private boolean ignoreInStandby = false; private boolean decrementDesiredCapacity = true;
private DeployStrategyType deployStrategy = DeployStrategyType.KEEP_CAPACITY;
msoute/vertx-deploy-tools
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/mojo/DeployConfiguration.java
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/DeployType.java // public enum DeployType { // APPLICATION("application:"), // ARTIFACT("artifact:"), // DEFAULT(""); // // private static final String LATEST_REQUEST_TAG = "latest:version"; // private static final String SCOPE_TAG = "scope:tst"; // private static final String EXCLUSION_TAG = "exclusions"; // private static final String PROPERTIES_TAG = "classifier:properties"; // // private final String type; // private final String prefix = "deploy"; // // DeployType(String type) { // this.type = type; // } // // public String getLatestRequestTag() { // return prefix + ":" + type + LATEST_REQUEST_TAG; // } // // public String getScopeTag() { // return prefix + ":" + type + SCOPE_TAG; // } // // public String getExclusionTag() { // return prefix + ":" + type + EXCLUSION_TAG; // } // // public String getPropertiesTag() { // return prefix + ":" + type + PROPERTIES_TAG; // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/deploy/strategy/DeployStrategyType.java // public enum DeployStrategyType { // WHATEVER, // DEFAULT, // GUARANTEE_MINIMUM, // SPIN_AND_REMOVE, // KEEP_CAPACITY // }
import nl.jpoint.maven.vertx.utils.DeployType; import nl.jpoint.maven.vertx.utils.deploy.strategy.DeployStrategyType; import org.apache.maven.model.Exclusion; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors;
package nl.jpoint.maven.vertx.mojo; public class DeployConfiguration { /** * The maven project version as String (groupId:artifactId:version) */ private String projectVersion; /** * The configuration target id **/ private String target; /** * List of hosts to deploy to **/ private final List<String> hosts = new ArrayList<>(); /** * The port where the agent is listening on */ private int port = 6789; /** * Enable / disable deploy of config objects **/ private boolean deployConfig = true; /** * List of artifacts to exclude **/ private List<Exclusion> exclusions = new ArrayList<>(); /** * Deploy artifacts in test scope **/ private boolean testScope = false; /** * restart all modules on host **/ private boolean restart = false; /** * Allow deploy of snapshots **/ private boolean deploySnapshots = false; /** * AWS Generic Properties * Use public / private AWS ip's **/ private boolean awsPrivateIp = false; private boolean useAutoScaling = false; private boolean elb = false; private boolean stickiness = false; private List<String> stickyPorts = new ArrayList<>(Collections.singletonList("443")); /** * AWS AutoScaling Properties **/ private String autoScalingGroupId; private boolean ignoreInStandby = false; private boolean decrementDesiredCapacity = true; private DeployStrategyType deployStrategy = DeployStrategyType.KEEP_CAPACITY; private Integer maxCapacity = -1; private Integer minCapacity = 1; private final List<String> autoScalingProperties = new ArrayList<>(); private boolean spindown = true; private boolean withMetrics = false; private MetricsConfiguration metricsConfiguration = null;
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/DeployType.java // public enum DeployType { // APPLICATION("application:"), // ARTIFACT("artifact:"), // DEFAULT(""); // // private static final String LATEST_REQUEST_TAG = "latest:version"; // private static final String SCOPE_TAG = "scope:tst"; // private static final String EXCLUSION_TAG = "exclusions"; // private static final String PROPERTIES_TAG = "classifier:properties"; // // private final String type; // private final String prefix = "deploy"; // // DeployType(String type) { // this.type = type; // } // // public String getLatestRequestTag() { // return prefix + ":" + type + LATEST_REQUEST_TAG; // } // // public String getScopeTag() { // return prefix + ":" + type + SCOPE_TAG; // } // // public String getExclusionTag() { // return prefix + ":" + type + EXCLUSION_TAG; // } // // public String getPropertiesTag() { // return prefix + ":" + type + PROPERTIES_TAG; // } // } // // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/deploy/strategy/DeployStrategyType.java // public enum DeployStrategyType { // WHATEVER, // DEFAULT, // GUARANTEE_MINIMUM, // SPIN_AND_REMOVE, // KEEP_CAPACITY // } // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/mojo/DeployConfiguration.java import nl.jpoint.maven.vertx.utils.DeployType; import nl.jpoint.maven.vertx.utils.deploy.strategy.DeployStrategyType; import org.apache.maven.model.Exclusion; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; package nl.jpoint.maven.vertx.mojo; public class DeployConfiguration { /** * The maven project version as String (groupId:artifactId:version) */ private String projectVersion; /** * The configuration target id **/ private String target; /** * List of hosts to deploy to **/ private final List<String> hosts = new ArrayList<>(); /** * The port where the agent is listening on */ private int port = 6789; /** * Enable / disable deploy of config objects **/ private boolean deployConfig = true; /** * List of artifacts to exclude **/ private List<Exclusion> exclusions = new ArrayList<>(); /** * Deploy artifacts in test scope **/ private boolean testScope = false; /** * restart all modules on host **/ private boolean restart = false; /** * Allow deploy of snapshots **/ private boolean deploySnapshots = false; /** * AWS Generic Properties * Use public / private AWS ip's **/ private boolean awsPrivateIp = false; private boolean useAutoScaling = false; private boolean elb = false; private boolean stickiness = false; private List<String> stickyPorts = new ArrayList<>(Collections.singletonList("443")); /** * AWS AutoScaling Properties **/ private String autoScalingGroupId; private boolean ignoreInStandby = false; private boolean decrementDesiredCapacity = true; private DeployStrategyType deployStrategy = DeployStrategyType.KEEP_CAPACITY; private Integer maxCapacity = -1; private Integer minCapacity = 1; private final List<String> autoScalingProperties = new ArrayList<>(); private boolean spindown = true; private boolean withMetrics = false; private MetricsConfiguration metricsConfiguration = null;
private DeployType deployType = DeployType.DEFAULT;
msoute/vertx-deploy-tools
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/LogUtil.java
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployResult.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class DeployResult { // // // private final List<String> success; // private final Map<String, String> error; // // @JsonCreator // public DeployResult(@JsonProperty("OK") List<String> success, // @JsonProperty("ERROR") Map<String, String> error) { // this.success = success; // this.error = error; // } // // public List<String> getSuccess() { // return success; // } // // public Map<String, String> getError() { // return error; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import nl.jpoint.maven.vertx.request.DeployResult; import org.apache.maven.plugin.logging.Log; import java.io.IOException;
package nl.jpoint.maven.vertx.utils; public final class LogUtil { private LogUtil() { //hide } public static void logDeployResult(Log log, String result) { if (result == null || result.isEmpty()) { return; }
// Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/request/DeployResult.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class DeployResult { // // // private final List<String> success; // private final Map<String, String> error; // // @JsonCreator // public DeployResult(@JsonProperty("OK") List<String> success, // @JsonProperty("ERROR") Map<String, String> error) { // this.success = success; // this.error = error; // } // // public List<String> getSuccess() { // return success; // } // // public Map<String, String> getError() { // return error; // } // } // Path: vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/LogUtil.java import com.fasterxml.jackson.databind.ObjectMapper; import nl.jpoint.maven.vertx.request.DeployResult; import org.apache.maven.plugin.logging.Log; import java.io.IOException; package nl.jpoint.maven.vertx.utils; public final class LogUtil { private LogUtil() { //hide } public static void logDeployResult(Log log, String result) { if (result == null || result.isEmpty()) { return; }
DeployResult deployResult;
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherMainView.java
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import android.content.DialogInterface; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-27. */ public interface IWeatherMainView extends IBaseView { @Override void init(); @Override void start(); @Override void finish(); void goToSelectLocationActivity(); void loadWeatherError(String message); void showAlertDialog(String title, String message, String negativeString, String positiveString, DialogInterface.OnClickListener listener);
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherMainView.java import android.content.DialogInterface; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-27. */ public interface IWeatherMainView extends IBaseView { @Override void init(); @Override void start(); @Override void finish(); void goToSelectLocationActivity(); void loadWeatherError(String message); void showAlertDialog(String title, String message, String negativeString, String positiveString, DialogInterface.OnClickListener listener);
void loadWeatherDataSourceFinish(List<Forecast> forecasts, ForecastInfo info);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherMainView.java
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import android.content.DialogInterface; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-27. */ public interface IWeatherMainView extends IBaseView { @Override void init(); @Override void start(); @Override void finish(); void goToSelectLocationActivity(); void loadWeatherError(String message); void showAlertDialog(String title, String message, String negativeString, String positiveString, DialogInterface.OnClickListener listener);
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherMainView.java import android.content.DialogInterface; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-27. */ public interface IWeatherMainView extends IBaseView { @Override void init(); @Override void start(); @Override void finish(); void goToSelectLocationActivity(); void loadWeatherError(String message); void showAlertDialog(String title, String message, String negativeString, String positiveString, DialogInterface.OnClickListener listener);
void loadWeatherDataSourceFinish(List<Forecast> forecasts, ForecastInfo info);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/App.java
// Path: app/src/main/java/com/kuahusg/weather/util/CrashHandler.java // public class CrashHandler implements Thread.UncaughtExceptionHandler { // private Thread.UncaughtExceptionHandler exceptionHandler; // // @Override // public void uncaughtException(Thread thread, Throwable throwable) { // if (throwable != null && exceptionHandler != null) { // handleException(throwable); // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // // } // exceptionHandler.uncaughtException(thread, throwable); // //这个好像要这个方法处理,不然会调用多次handleException()?? // } else { // // Process.killProcess(Process.myPid()); // System.exit(10); // } // // } // // private CrashHandler() { // // } // // public void init() { // InstanceHolder.INSTANCE.exceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); // Thread.setDefaultUncaughtExceptionHandler(this); // // } // // private void handleException(final Throwable e) { // final StackTraceElement[] elements = e.getStackTrace(); // final String message = "Message:\n" + e.getMessage() + "\n"; // final String fileName = "crash-" + System.currentTimeMillis() + ".log"; // // // StringBuilder sb = new StringBuilder(); // for (StackTraceElement element : elements) { // sb.append(element.toString()).append("\n"); // } // final String stackMessage = "\nTraceMessage: " + sb.toString(); // // // final String toastMessage = App.getContext().getString(R.string.crash_message); // // // setNotification(message + stackMessage + getDeviceInfo()); // new Thread(new Runnable() { // @Override // public void run() { // Looper.prepare(); // Toast.makeText(App.getContext(), toastMessage, Toast.LENGTH_LONG).show(); // try { // final FileOutputStream fos = new FileOutputStream(new File(App.getContext() // .getExternalFilesDir(null), fileName), true); // fos.write((message).getBytes()); // // fos.write((stackMessage).getBytes()); // fos.write(getDeviceInfo().getBytes()); // // // fos.flush(); // fos.close(); // } catch (IOException e1) { // e1.printStackTrace(); // Toast.makeText(App.getContext(), e1.getMessage(), Toast.LENGTH_LONG).show(); // } // Looper.loop(); // // // } // }).start(); // } // // public static CrashHandler getInstance() { // return InstanceHolder.INSTANCE; // // } // // // private void setNotification(String message) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // Intent intent = new Intent(Intent.ACTION_SEND); // intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); // intent.putExtra(Intent.EXTRA_TEXT, message); // intent.putExtra(Intent.EXTRA_SUBJECT, "Crash Report"); // intent.setType("text/plain"); // // // PendingIntent pendingIntent = PendingIntent.getActivity(App.getContext(), 0, // intent, PendingIntent.FLAG_CANCEL_CURRENT); // Notification notification = null; // Notification.Builder builder; // builder = new Notification.Builder(App.getContext()) // .setSmallIcon(R.mipmap.ic_launcher) // .setContentTitle(App.getContext().getString(R.string.solve_crash_message)) // .setContentIntent(pendingIntent) // .setAutoCancel(true); // // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // builder.setLargeIcon(Icon.createWithResource(App.getContext(), R.mipmap.ic_launcher)); // } // notification = builder.build(); // // NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE); // notificationManager.notify(0, notification); // } // // } // // private String getDeviceInfo() { // PackageManager packageManager = App.getContext().getPackageManager(); // StringBuilder stringBuilder = new StringBuilder(); // try { // stringBuilder.append("\nDevices Info:") // .append("\nSDK_INT: ").append(Build.VERSION.SDK_INT) // .append("\nDEVICE: ").append(Build.DEVICE) // .append("\nPackageVersionName: ").append(packageManager.getPackageInfo(App.getContext().getPackageName(), 0).versionName) // .append("\nPackageVersionCode: ").append(packageManager.getPackageInfo(App.getContext().getPackageName(), 0).versionCode); // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // } // // return stringBuilder.toString(); // } // // private static class InstanceHolder { // static final CrashHandler INSTANCE = new CrashHandler(); // } // }
import android.app.Application; import android.content.Context; import com.kuahusg.weather.util.CrashHandler; import java.util.IllegalFormatException;
package com.kuahusg.weather; /** * Created by kuahusg on 16-4-30. */ public class App extends Application { private static Context context; // private RefWatcher watcher; @Override public void onCreate() { super.onCreate(); context = getApplicationContext();
// Path: app/src/main/java/com/kuahusg/weather/util/CrashHandler.java // public class CrashHandler implements Thread.UncaughtExceptionHandler { // private Thread.UncaughtExceptionHandler exceptionHandler; // // @Override // public void uncaughtException(Thread thread, Throwable throwable) { // if (throwable != null && exceptionHandler != null) { // handleException(throwable); // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // // } // exceptionHandler.uncaughtException(thread, throwable); // //这个好像要这个方法处理,不然会调用多次handleException()?? // } else { // // Process.killProcess(Process.myPid()); // System.exit(10); // } // // } // // private CrashHandler() { // // } // // public void init() { // InstanceHolder.INSTANCE.exceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); // Thread.setDefaultUncaughtExceptionHandler(this); // // } // // private void handleException(final Throwable e) { // final StackTraceElement[] elements = e.getStackTrace(); // final String message = "Message:\n" + e.getMessage() + "\n"; // final String fileName = "crash-" + System.currentTimeMillis() + ".log"; // // // StringBuilder sb = new StringBuilder(); // for (StackTraceElement element : elements) { // sb.append(element.toString()).append("\n"); // } // final String stackMessage = "\nTraceMessage: " + sb.toString(); // // // final String toastMessage = App.getContext().getString(R.string.crash_message); // // // setNotification(message + stackMessage + getDeviceInfo()); // new Thread(new Runnable() { // @Override // public void run() { // Looper.prepare(); // Toast.makeText(App.getContext(), toastMessage, Toast.LENGTH_LONG).show(); // try { // final FileOutputStream fos = new FileOutputStream(new File(App.getContext() // .getExternalFilesDir(null), fileName), true); // fos.write((message).getBytes()); // // fos.write((stackMessage).getBytes()); // fos.write(getDeviceInfo().getBytes()); // // // fos.flush(); // fos.close(); // } catch (IOException e1) { // e1.printStackTrace(); // Toast.makeText(App.getContext(), e1.getMessage(), Toast.LENGTH_LONG).show(); // } // Looper.loop(); // // // } // }).start(); // } // // public static CrashHandler getInstance() { // return InstanceHolder.INSTANCE; // // } // // // private void setNotification(String message) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // Intent intent = new Intent(Intent.ACTION_SEND); // intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); // intent.putExtra(Intent.EXTRA_TEXT, message); // intent.putExtra(Intent.EXTRA_SUBJECT, "Crash Report"); // intent.setType("text/plain"); // // // PendingIntent pendingIntent = PendingIntent.getActivity(App.getContext(), 0, // intent, PendingIntent.FLAG_CANCEL_CURRENT); // Notification notification = null; // Notification.Builder builder; // builder = new Notification.Builder(App.getContext()) // .setSmallIcon(R.mipmap.ic_launcher) // .setContentTitle(App.getContext().getString(R.string.solve_crash_message)) // .setContentIntent(pendingIntent) // .setAutoCancel(true); // // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // builder.setLargeIcon(Icon.createWithResource(App.getContext(), R.mipmap.ic_launcher)); // } // notification = builder.build(); // // NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE); // notificationManager.notify(0, notification); // } // // } // // private String getDeviceInfo() { // PackageManager packageManager = App.getContext().getPackageManager(); // StringBuilder stringBuilder = new StringBuilder(); // try { // stringBuilder.append("\nDevices Info:") // .append("\nSDK_INT: ").append(Build.VERSION.SDK_INT) // .append("\nDEVICE: ").append(Build.DEVICE) // .append("\nPackageVersionName: ").append(packageManager.getPackageInfo(App.getContext().getPackageName(), 0).versionName) // .append("\nPackageVersionCode: ").append(packageManager.getPackageInfo(App.getContext().getPackageName(), 0).versionCode); // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // } // // return stringBuilder.toString(); // } // // private static class InstanceHolder { // static final CrashHandler INSTANCE = new CrashHandler(); // } // } // Path: app/src/main/java/com/kuahusg/weather/App.java import android.app.Application; import android.content.Context; import com.kuahusg.weather.util.CrashHandler; import java.util.IllegalFormatException; package com.kuahusg.weather; /** * Created by kuahusg on 16-4-30. */ public class App extends Application { private static Context context; // private RefWatcher watcher; @Override public void onCreate() { super.onCreate(); context = getApplicationContext();
CrashHandler crashHandler = CrashHandler.getInstance();
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/remote/WeatherService.java
// Path: app/src/main/java/com/kuahusg/weather/model/bean/AllCityResult.java // public class AllCityResult { // private String id; // private String name; // private String en; // private String parent1; // private String parent2; // private String parent3; // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEn() { // return en; // } // // public String getParent1() { // return parent1; // } // // public String getParent2() { // return parent2; // } // // public String getParent3() { // return parent3; // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/CitySearchResult.java // public class CitySearchResult { // private Query query; // // public Query getQuery() { // return query; // } // // public static class Query{ // private String count; // private String created; // private String landg; // private Results results; // // public Results getResults() { // return results; // } // } // // // public static class Results{ // private Place place; // // public Place getPlace() { // return place; // } // } // public static class Place{ // private String name; // private String country; // private String admin1; // private String admin2; // private String admin3; // private String woeid; // // public String getName() { // return name; // } // // public String getCountry() { // return country; // } // // public String getAdmin1() { // return admin1; // } // // public String getAdmin2() { // return admin2; // } // // public String getAdmin3() { // return admin3; // } // // public String getWoeid() { // return woeid; // } // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/WeatherResult.java // public class WeatherResult { // Query query; // // public Query getQuery() { // return query; // } // // // public static class Query { // Result results; // // public Result getResults() { // return results; // } // } // // // public static class Result { // Channel channel; // // public Channel getChannel() { // return channel; // } // } // // public static class Channel { // String link; // Wind wind; // Astronomy astronomy; // Item item; // String lastBuildDate; // // public String getLink() { // return link; // } // // public Wind getWind() { // return wind; // } // // public Astronomy getAstronomy() { // return astronomy; // } // // public Item getItem() { // // return item; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // } // // // public static class Wind { // String chill; // String direction; // String speed; // // public String getChill() { // return chill; // } // // public String getDirection() { // return direction; // } // // public String getSpeed() { // return speed; // } // } // // public static class Astronomy { // String sunrise; // String sunset; // // public String getSunrise() { // return sunrise; // } // // public String getSunset() { // return sunset; // } // } // // public static class Item { // String link; // String pubDate; // Condition condition; // Forecast[] forecast; // // public String getLink() { // return link; // } // // public String getPubDate() { // return pubDate; // } // // public Condition getCondition() { // return condition; // } // // public Forecast[] getForecast() { // return forecast; // } // } // // public static class Condition { // String date; // String temp; // String text; // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // return text; // } // } // /*public static class Forecast{ // String date; // String day; // String high; // String low; // String text; // // public String getDate() { // return date; // } // // public String getDay() { // return day; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // }*/ // // }
import com.kuahusg.weather.model.bean.AllCityResult; import com.kuahusg.weather.model.bean.CitySearchResult; import com.kuahusg.weather.model.bean.WeatherResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url;
package com.kuahusg.weather.data.remote; /** * Created by kuahusg on 16-9-28. */ public interface WeatherService { @GET("/v1/public/yql")
// Path: app/src/main/java/com/kuahusg/weather/model/bean/AllCityResult.java // public class AllCityResult { // private String id; // private String name; // private String en; // private String parent1; // private String parent2; // private String parent3; // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEn() { // return en; // } // // public String getParent1() { // return parent1; // } // // public String getParent2() { // return parent2; // } // // public String getParent3() { // return parent3; // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/CitySearchResult.java // public class CitySearchResult { // private Query query; // // public Query getQuery() { // return query; // } // // public static class Query{ // private String count; // private String created; // private String landg; // private Results results; // // public Results getResults() { // return results; // } // } // // // public static class Results{ // private Place place; // // public Place getPlace() { // return place; // } // } // public static class Place{ // private String name; // private String country; // private String admin1; // private String admin2; // private String admin3; // private String woeid; // // public String getName() { // return name; // } // // public String getCountry() { // return country; // } // // public String getAdmin1() { // return admin1; // } // // public String getAdmin2() { // return admin2; // } // // public String getAdmin3() { // return admin3; // } // // public String getWoeid() { // return woeid; // } // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/WeatherResult.java // public class WeatherResult { // Query query; // // public Query getQuery() { // return query; // } // // // public static class Query { // Result results; // // public Result getResults() { // return results; // } // } // // // public static class Result { // Channel channel; // // public Channel getChannel() { // return channel; // } // } // // public static class Channel { // String link; // Wind wind; // Astronomy astronomy; // Item item; // String lastBuildDate; // // public String getLink() { // return link; // } // // public Wind getWind() { // return wind; // } // // public Astronomy getAstronomy() { // return astronomy; // } // // public Item getItem() { // // return item; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // } // // // public static class Wind { // String chill; // String direction; // String speed; // // public String getChill() { // return chill; // } // // public String getDirection() { // return direction; // } // // public String getSpeed() { // return speed; // } // } // // public static class Astronomy { // String sunrise; // String sunset; // // public String getSunrise() { // return sunrise; // } // // public String getSunset() { // return sunset; // } // } // // public static class Item { // String link; // String pubDate; // Condition condition; // Forecast[] forecast; // // public String getLink() { // return link; // } // // public String getPubDate() { // return pubDate; // } // // public Condition getCondition() { // return condition; // } // // public Forecast[] getForecast() { // return forecast; // } // } // // public static class Condition { // String date; // String temp; // String text; // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // return text; // } // } // /*public static class Forecast{ // String date; // String day; // String high; // String low; // String text; // // public String getDate() { // return date; // } // // public String getDay() { // return day; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // }*/ // // } // Path: app/src/main/java/com/kuahusg/weather/data/remote/WeatherService.java import com.kuahusg.weather.model.bean.AllCityResult; import com.kuahusg.weather.model.bean.CitySearchResult; import com.kuahusg.weather.model.bean.WeatherResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; package com.kuahusg.weather.data.remote; /** * Created by kuahusg on 16-9-28. */ public interface WeatherService { @GET("/v1/public/yql")
Call<WeatherResult> queryWeather(@Query("q") String queryString, @Query("format") String format);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/remote/WeatherService.java
// Path: app/src/main/java/com/kuahusg/weather/model/bean/AllCityResult.java // public class AllCityResult { // private String id; // private String name; // private String en; // private String parent1; // private String parent2; // private String parent3; // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEn() { // return en; // } // // public String getParent1() { // return parent1; // } // // public String getParent2() { // return parent2; // } // // public String getParent3() { // return parent3; // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/CitySearchResult.java // public class CitySearchResult { // private Query query; // // public Query getQuery() { // return query; // } // // public static class Query{ // private String count; // private String created; // private String landg; // private Results results; // // public Results getResults() { // return results; // } // } // // // public static class Results{ // private Place place; // // public Place getPlace() { // return place; // } // } // public static class Place{ // private String name; // private String country; // private String admin1; // private String admin2; // private String admin3; // private String woeid; // // public String getName() { // return name; // } // // public String getCountry() { // return country; // } // // public String getAdmin1() { // return admin1; // } // // public String getAdmin2() { // return admin2; // } // // public String getAdmin3() { // return admin3; // } // // public String getWoeid() { // return woeid; // } // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/WeatherResult.java // public class WeatherResult { // Query query; // // public Query getQuery() { // return query; // } // // // public static class Query { // Result results; // // public Result getResults() { // return results; // } // } // // // public static class Result { // Channel channel; // // public Channel getChannel() { // return channel; // } // } // // public static class Channel { // String link; // Wind wind; // Astronomy astronomy; // Item item; // String lastBuildDate; // // public String getLink() { // return link; // } // // public Wind getWind() { // return wind; // } // // public Astronomy getAstronomy() { // return astronomy; // } // // public Item getItem() { // // return item; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // } // // // public static class Wind { // String chill; // String direction; // String speed; // // public String getChill() { // return chill; // } // // public String getDirection() { // return direction; // } // // public String getSpeed() { // return speed; // } // } // // public static class Astronomy { // String sunrise; // String sunset; // // public String getSunrise() { // return sunrise; // } // // public String getSunset() { // return sunset; // } // } // // public static class Item { // String link; // String pubDate; // Condition condition; // Forecast[] forecast; // // public String getLink() { // return link; // } // // public String getPubDate() { // return pubDate; // } // // public Condition getCondition() { // return condition; // } // // public Forecast[] getForecast() { // return forecast; // } // } // // public static class Condition { // String date; // String temp; // String text; // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // return text; // } // } // /*public static class Forecast{ // String date; // String day; // String high; // String low; // String text; // // public String getDate() { // return date; // } // // public String getDay() { // return day; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // }*/ // // }
import com.kuahusg.weather.model.bean.AllCityResult; import com.kuahusg.weather.model.bean.CitySearchResult; import com.kuahusg.weather.model.bean.WeatherResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url;
package com.kuahusg.weather.data.remote; /** * Created by kuahusg on 16-9-28. */ public interface WeatherService { @GET("/v1/public/yql") Call<WeatherResult> queryWeather(@Query("q") String queryString, @Query("format") String format); @GET()
// Path: app/src/main/java/com/kuahusg/weather/model/bean/AllCityResult.java // public class AllCityResult { // private String id; // private String name; // private String en; // private String parent1; // private String parent2; // private String parent3; // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEn() { // return en; // } // // public String getParent1() { // return parent1; // } // // public String getParent2() { // return parent2; // } // // public String getParent3() { // return parent3; // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/CitySearchResult.java // public class CitySearchResult { // private Query query; // // public Query getQuery() { // return query; // } // // public static class Query{ // private String count; // private String created; // private String landg; // private Results results; // // public Results getResults() { // return results; // } // } // // // public static class Results{ // private Place place; // // public Place getPlace() { // return place; // } // } // public static class Place{ // private String name; // private String country; // private String admin1; // private String admin2; // private String admin3; // private String woeid; // // public String getName() { // return name; // } // // public String getCountry() { // return country; // } // // public String getAdmin1() { // return admin1; // } // // public String getAdmin2() { // return admin2; // } // // public String getAdmin3() { // return admin3; // } // // public String getWoeid() { // return woeid; // } // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/WeatherResult.java // public class WeatherResult { // Query query; // // public Query getQuery() { // return query; // } // // // public static class Query { // Result results; // // public Result getResults() { // return results; // } // } // // // public static class Result { // Channel channel; // // public Channel getChannel() { // return channel; // } // } // // public static class Channel { // String link; // Wind wind; // Astronomy astronomy; // Item item; // String lastBuildDate; // // public String getLink() { // return link; // } // // public Wind getWind() { // return wind; // } // // public Astronomy getAstronomy() { // return astronomy; // } // // public Item getItem() { // // return item; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // } // // // public static class Wind { // String chill; // String direction; // String speed; // // public String getChill() { // return chill; // } // // public String getDirection() { // return direction; // } // // public String getSpeed() { // return speed; // } // } // // public static class Astronomy { // String sunrise; // String sunset; // // public String getSunrise() { // return sunrise; // } // // public String getSunset() { // return sunset; // } // } // // public static class Item { // String link; // String pubDate; // Condition condition; // Forecast[] forecast; // // public String getLink() { // return link; // } // // public String getPubDate() { // return pubDate; // } // // public Condition getCondition() { // return condition; // } // // public Forecast[] getForecast() { // return forecast; // } // } // // public static class Condition { // String date; // String temp; // String text; // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // return text; // } // } // /*public static class Forecast{ // String date; // String day; // String high; // String low; // String text; // // public String getDate() { // return date; // } // // public String getDay() { // return day; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // }*/ // // } // Path: app/src/main/java/com/kuahusg/weather/data/remote/WeatherService.java import com.kuahusg.weather.model.bean.AllCityResult; import com.kuahusg.weather.model.bean.CitySearchResult; import com.kuahusg.weather.model.bean.WeatherResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; package com.kuahusg.weather.data.remote; /** * Created by kuahusg on 16-9-28. */ public interface WeatherService { @GET("/v1/public/yql") Call<WeatherResult> queryWeather(@Query("q") String queryString, @Query("format") String format); @GET()
Call<List<AllCityResult>> queryAllMainCity(@Url String url);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/remote/WeatherService.java
// Path: app/src/main/java/com/kuahusg/weather/model/bean/AllCityResult.java // public class AllCityResult { // private String id; // private String name; // private String en; // private String parent1; // private String parent2; // private String parent3; // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEn() { // return en; // } // // public String getParent1() { // return parent1; // } // // public String getParent2() { // return parent2; // } // // public String getParent3() { // return parent3; // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/CitySearchResult.java // public class CitySearchResult { // private Query query; // // public Query getQuery() { // return query; // } // // public static class Query{ // private String count; // private String created; // private String landg; // private Results results; // // public Results getResults() { // return results; // } // } // // // public static class Results{ // private Place place; // // public Place getPlace() { // return place; // } // } // public static class Place{ // private String name; // private String country; // private String admin1; // private String admin2; // private String admin3; // private String woeid; // // public String getName() { // return name; // } // // public String getCountry() { // return country; // } // // public String getAdmin1() { // return admin1; // } // // public String getAdmin2() { // return admin2; // } // // public String getAdmin3() { // return admin3; // } // // public String getWoeid() { // return woeid; // } // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/WeatherResult.java // public class WeatherResult { // Query query; // // public Query getQuery() { // return query; // } // // // public static class Query { // Result results; // // public Result getResults() { // return results; // } // } // // // public static class Result { // Channel channel; // // public Channel getChannel() { // return channel; // } // } // // public static class Channel { // String link; // Wind wind; // Astronomy astronomy; // Item item; // String lastBuildDate; // // public String getLink() { // return link; // } // // public Wind getWind() { // return wind; // } // // public Astronomy getAstronomy() { // return astronomy; // } // // public Item getItem() { // // return item; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // } // // // public static class Wind { // String chill; // String direction; // String speed; // // public String getChill() { // return chill; // } // // public String getDirection() { // return direction; // } // // public String getSpeed() { // return speed; // } // } // // public static class Astronomy { // String sunrise; // String sunset; // // public String getSunrise() { // return sunrise; // } // // public String getSunset() { // return sunset; // } // } // // public static class Item { // String link; // String pubDate; // Condition condition; // Forecast[] forecast; // // public String getLink() { // return link; // } // // public String getPubDate() { // return pubDate; // } // // public Condition getCondition() { // return condition; // } // // public Forecast[] getForecast() { // return forecast; // } // } // // public static class Condition { // String date; // String temp; // String text; // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // return text; // } // } // /*public static class Forecast{ // String date; // String day; // String high; // String low; // String text; // // public String getDate() { // return date; // } // // public String getDay() { // return day; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // }*/ // // }
import com.kuahusg.weather.model.bean.AllCityResult; import com.kuahusg.weather.model.bean.CitySearchResult; import com.kuahusg.weather.model.bean.WeatherResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url;
package com.kuahusg.weather.data.remote; /** * Created by kuahusg on 16-9-28. */ public interface WeatherService { @GET("/v1/public/yql") Call<WeatherResult> queryWeather(@Query("q") String queryString, @Query("format") String format); @GET() Call<List<AllCityResult>> queryAllMainCity(@Url String url); @GET("/v1/public/yql")
// Path: app/src/main/java/com/kuahusg/weather/model/bean/AllCityResult.java // public class AllCityResult { // private String id; // private String name; // private String en; // private String parent1; // private String parent2; // private String parent3; // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getEn() { // return en; // } // // public String getParent1() { // return parent1; // } // // public String getParent2() { // return parent2; // } // // public String getParent3() { // return parent3; // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/CitySearchResult.java // public class CitySearchResult { // private Query query; // // public Query getQuery() { // return query; // } // // public static class Query{ // private String count; // private String created; // private String landg; // private Results results; // // public Results getResults() { // return results; // } // } // // // public static class Results{ // private Place place; // // public Place getPlace() { // return place; // } // } // public static class Place{ // private String name; // private String country; // private String admin1; // private String admin2; // private String admin3; // private String woeid; // // public String getName() { // return name; // } // // public String getCountry() { // return country; // } // // public String getAdmin1() { // return admin1; // } // // public String getAdmin2() { // return admin2; // } // // public String getAdmin3() { // return admin3; // } // // public String getWoeid() { // return woeid; // } // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/WeatherResult.java // public class WeatherResult { // Query query; // // public Query getQuery() { // return query; // } // // // public static class Query { // Result results; // // public Result getResults() { // return results; // } // } // // // public static class Result { // Channel channel; // // public Channel getChannel() { // return channel; // } // } // // public static class Channel { // String link; // Wind wind; // Astronomy astronomy; // Item item; // String lastBuildDate; // // public String getLink() { // return link; // } // // public Wind getWind() { // return wind; // } // // public Astronomy getAstronomy() { // return astronomy; // } // // public Item getItem() { // // return item; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // } // // // public static class Wind { // String chill; // String direction; // String speed; // // public String getChill() { // return chill; // } // // public String getDirection() { // return direction; // } // // public String getSpeed() { // return speed; // } // } // // public static class Astronomy { // String sunrise; // String sunset; // // public String getSunrise() { // return sunrise; // } // // public String getSunset() { // return sunset; // } // } // // public static class Item { // String link; // String pubDate; // Condition condition; // Forecast[] forecast; // // public String getLink() { // return link; // } // // public String getPubDate() { // return pubDate; // } // // public Condition getCondition() { // return condition; // } // // public Forecast[] getForecast() { // return forecast; // } // } // // public static class Condition { // String date; // String temp; // String text; // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // return text; // } // } // /*public static class Forecast{ // String date; // String day; // String high; // String low; // String text; // // public String getDate() { // return date; // } // // public String getDay() { // return day; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // }*/ // // } // Path: app/src/main/java/com/kuahusg/weather/data/remote/WeatherService.java import com.kuahusg.weather.model.bean.AllCityResult; import com.kuahusg.weather.model.bean.CitySearchResult; import com.kuahusg.weather.model.bean.WeatherResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; package com.kuahusg.weather.data.remote; /** * Created by kuahusg on 16-9-28. */ public interface WeatherService { @GET("/v1/public/yql") Call<WeatherResult> queryWeather(@Query("q") String queryString, @Query("format") String format); @GET() Call<List<AllCityResult>> queryAllMainCity(@Url String url); @GET("/v1/public/yql")
Call<CitySearchResult> queryCity(@Query("q") String queryString, @Query("format") String format);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // }
import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; import com.kuahusg.weather.data.IDataSource;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-27. */ public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { private IAboutMeView mView;
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; import com.kuahusg.weather.data.IDataSource; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-27. */ public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { private IAboutMeView mView;
public AboutMePresenterImpl(IBaseView view) {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // }
import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; import com.kuahusg.weather.data.IDataSource;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-27. */ public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { private IAboutMeView mView; public AboutMePresenterImpl(IBaseView view) { super(view); mView = (IAboutMeView) view; } @Override public void init() { super.init(); } @Override
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; import com.kuahusg.weather.data.IDataSource; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-27. */ public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { private IAboutMeView mView; public AboutMePresenterImpl(IBaseView view) { super(view); mView = (IAboutMeView) view; } @Override public void init() { super.init(); } @Override
protected IDataSource setDataSource() {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/receiver/BootCompleteReciver.java
// Path: app/src/main/java/com/kuahusg/weather/service/AutoUpdateService.java // public class AutoUpdateService extends Service { // private double time = 2; // // // private IDataSource dataSource = new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()); // private WeakReference<IDataSource> dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // // // @Override // public void onCreate() { // super.onCreate(); // LogUtil.v(this.toString(), "Service onCreate()"); // // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // // // time = Double.valueOf(PreferenceUtil.getInstance().getSharedPreferences().getString(SettingFragment.UPDATE_TIME, "0")); // if (time <= 0) // time = 2; // // TODO: 16-10-8 ?? // dataSourceWeakReference.get().queryWeather(null, new RequestWeatherCallback() { // @Override // public void success(List<Forecast> forecasts, ForecastInfo forecastInfo) { // } // // @Override // public void error(String message) { // // } // }); // // AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // long hours = (long) (time * 60 * 60 * 1000 + SystemClock.elapsedRealtime()); // Intent i = new Intent(this, AutoUpdateReceiver.class); // PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, hours, pi); // return super.onStartCommand(intent, flags, startId); // } // // @Override // public void onDestroy() { // super.onDestroy(); // LogUtil.v(this.toString(), "Service onDestroy()"); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/util/PreferenceUtil.java // public class PreferenceUtil { // SharedPreferences sharedPreferences; // SharedPreferences.Editor editor; // public static final String PREF_HAS_LOAD_ALL_CITY = "hasLoadAllCity"; // public static final String PREF_SELECTED_CITY = "selectCity"; // public static final String PREF_WOEID = "woeid"; // public static final String PREF_CITY_SIMPLE_NAME = "selectCitySimpleName"; // public static final String PREF_AUTO_UPDATE = "auto_update"; // // private PreferenceUtil() { // // } // // public static PreferenceUtil getInstance() { // return InstanceHolder.INSTANCE; // } // // // public SharedPreferences getSharedPreferences() { // if (sharedPreferences == null) // sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext()); // return sharedPreferences; // } // // public SharedPreferences.Editor getSharedPreferencesEditor() { // if (editor == null) { // editor = getSharedPreferences().edit(); // } // // return editor; // } // // public static String getWoeid() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_WOEID, null); // } // // public static String getCitySimpleName() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_CITY_SIMPLE_NAME, null); // } // // public static boolean getCanAutoUpdate() { // return InstanceHolder.INSTANCE.getSharedPreferences().getBoolean(PREF_AUTO_UPDATE, false); // } // // // private static final class InstanceHolder { // static final PreferenceUtil INSTANCE = new PreferenceUtil(); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kuahusg.weather.service.AutoUpdateService; import com.kuahusg.weather.util.PreferenceUtil;
package com.kuahusg.weather.receiver; /** * Created by kuahusg on 16-6-21. * com.kuahusg.weather.receiver */ public class BootCompleteReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // LogUtil.v(this.toString(), "boot complete,start service");
// Path: app/src/main/java/com/kuahusg/weather/service/AutoUpdateService.java // public class AutoUpdateService extends Service { // private double time = 2; // // // private IDataSource dataSource = new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()); // private WeakReference<IDataSource> dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // // // @Override // public void onCreate() { // super.onCreate(); // LogUtil.v(this.toString(), "Service onCreate()"); // // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // // // time = Double.valueOf(PreferenceUtil.getInstance().getSharedPreferences().getString(SettingFragment.UPDATE_TIME, "0")); // if (time <= 0) // time = 2; // // TODO: 16-10-8 ?? // dataSourceWeakReference.get().queryWeather(null, new RequestWeatherCallback() { // @Override // public void success(List<Forecast> forecasts, ForecastInfo forecastInfo) { // } // // @Override // public void error(String message) { // // } // }); // // AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // long hours = (long) (time * 60 * 60 * 1000 + SystemClock.elapsedRealtime()); // Intent i = new Intent(this, AutoUpdateReceiver.class); // PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, hours, pi); // return super.onStartCommand(intent, flags, startId); // } // // @Override // public void onDestroy() { // super.onDestroy(); // LogUtil.v(this.toString(), "Service onDestroy()"); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/util/PreferenceUtil.java // public class PreferenceUtil { // SharedPreferences sharedPreferences; // SharedPreferences.Editor editor; // public static final String PREF_HAS_LOAD_ALL_CITY = "hasLoadAllCity"; // public static final String PREF_SELECTED_CITY = "selectCity"; // public static final String PREF_WOEID = "woeid"; // public static final String PREF_CITY_SIMPLE_NAME = "selectCitySimpleName"; // public static final String PREF_AUTO_UPDATE = "auto_update"; // // private PreferenceUtil() { // // } // // public static PreferenceUtil getInstance() { // return InstanceHolder.INSTANCE; // } // // // public SharedPreferences getSharedPreferences() { // if (sharedPreferences == null) // sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext()); // return sharedPreferences; // } // // public SharedPreferences.Editor getSharedPreferencesEditor() { // if (editor == null) { // editor = getSharedPreferences().edit(); // } // // return editor; // } // // public static String getWoeid() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_WOEID, null); // } // // public static String getCitySimpleName() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_CITY_SIMPLE_NAME, null); // } // // public static boolean getCanAutoUpdate() { // return InstanceHolder.INSTANCE.getSharedPreferences().getBoolean(PREF_AUTO_UPDATE, false); // } // // // private static final class InstanceHolder { // static final PreferenceUtil INSTANCE = new PreferenceUtil(); // } // } // Path: app/src/main/java/com/kuahusg/weather/receiver/BootCompleteReciver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kuahusg.weather.service.AutoUpdateService; import com.kuahusg.weather.util.PreferenceUtil; package com.kuahusg.weather.receiver; /** * Created by kuahusg on 16-6-21. * com.kuahusg.weather.receiver */ public class BootCompleteReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // LogUtil.v(this.toString(), "boot complete,start service");
if (PreferenceUtil.getCanAutoUpdate()) {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/receiver/BootCompleteReciver.java
// Path: app/src/main/java/com/kuahusg/weather/service/AutoUpdateService.java // public class AutoUpdateService extends Service { // private double time = 2; // // // private IDataSource dataSource = new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()); // private WeakReference<IDataSource> dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // // // @Override // public void onCreate() { // super.onCreate(); // LogUtil.v(this.toString(), "Service onCreate()"); // // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // // // time = Double.valueOf(PreferenceUtil.getInstance().getSharedPreferences().getString(SettingFragment.UPDATE_TIME, "0")); // if (time <= 0) // time = 2; // // TODO: 16-10-8 ?? // dataSourceWeakReference.get().queryWeather(null, new RequestWeatherCallback() { // @Override // public void success(List<Forecast> forecasts, ForecastInfo forecastInfo) { // } // // @Override // public void error(String message) { // // } // }); // // AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // long hours = (long) (time * 60 * 60 * 1000 + SystemClock.elapsedRealtime()); // Intent i = new Intent(this, AutoUpdateReceiver.class); // PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, hours, pi); // return super.onStartCommand(intent, flags, startId); // } // // @Override // public void onDestroy() { // super.onDestroy(); // LogUtil.v(this.toString(), "Service onDestroy()"); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/util/PreferenceUtil.java // public class PreferenceUtil { // SharedPreferences sharedPreferences; // SharedPreferences.Editor editor; // public static final String PREF_HAS_LOAD_ALL_CITY = "hasLoadAllCity"; // public static final String PREF_SELECTED_CITY = "selectCity"; // public static final String PREF_WOEID = "woeid"; // public static final String PREF_CITY_SIMPLE_NAME = "selectCitySimpleName"; // public static final String PREF_AUTO_UPDATE = "auto_update"; // // private PreferenceUtil() { // // } // // public static PreferenceUtil getInstance() { // return InstanceHolder.INSTANCE; // } // // // public SharedPreferences getSharedPreferences() { // if (sharedPreferences == null) // sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext()); // return sharedPreferences; // } // // public SharedPreferences.Editor getSharedPreferencesEditor() { // if (editor == null) { // editor = getSharedPreferences().edit(); // } // // return editor; // } // // public static String getWoeid() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_WOEID, null); // } // // public static String getCitySimpleName() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_CITY_SIMPLE_NAME, null); // } // // public static boolean getCanAutoUpdate() { // return InstanceHolder.INSTANCE.getSharedPreferences().getBoolean(PREF_AUTO_UPDATE, false); // } // // // private static final class InstanceHolder { // static final PreferenceUtil INSTANCE = new PreferenceUtil(); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kuahusg.weather.service.AutoUpdateService; import com.kuahusg.weather.util.PreferenceUtil;
package com.kuahusg.weather.receiver; /** * Created by kuahusg on 16-6-21. * com.kuahusg.weather.receiver */ public class BootCompleteReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // LogUtil.v(this.toString(), "boot complete,start service"); if (PreferenceUtil.getCanAutoUpdate()) {
// Path: app/src/main/java/com/kuahusg/weather/service/AutoUpdateService.java // public class AutoUpdateService extends Service { // private double time = 2; // // // private IDataSource dataSource = new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()); // private WeakReference<IDataSource> dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // // // @Override // public void onCreate() { // super.onCreate(); // LogUtil.v(this.toString(), "Service onCreate()"); // // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // // // time = Double.valueOf(PreferenceUtil.getInstance().getSharedPreferences().getString(SettingFragment.UPDATE_TIME, "0")); // if (time <= 0) // time = 2; // // TODO: 16-10-8 ?? // dataSourceWeakReference.get().queryWeather(null, new RequestWeatherCallback() { // @Override // public void success(List<Forecast> forecasts, ForecastInfo forecastInfo) { // } // // @Override // public void error(String message) { // // } // }); // // AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // long hours = (long) (time * 60 * 60 * 1000 + SystemClock.elapsedRealtime()); // Intent i = new Intent(this, AutoUpdateReceiver.class); // PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, hours, pi); // return super.onStartCommand(intent, flags, startId); // } // // @Override // public void onDestroy() { // super.onDestroy(); // LogUtil.v(this.toString(), "Service onDestroy()"); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/util/PreferenceUtil.java // public class PreferenceUtil { // SharedPreferences sharedPreferences; // SharedPreferences.Editor editor; // public static final String PREF_HAS_LOAD_ALL_CITY = "hasLoadAllCity"; // public static final String PREF_SELECTED_CITY = "selectCity"; // public static final String PREF_WOEID = "woeid"; // public static final String PREF_CITY_SIMPLE_NAME = "selectCitySimpleName"; // public static final String PREF_AUTO_UPDATE = "auto_update"; // // private PreferenceUtil() { // // } // // public static PreferenceUtil getInstance() { // return InstanceHolder.INSTANCE; // } // // // public SharedPreferences getSharedPreferences() { // if (sharedPreferences == null) // sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext()); // return sharedPreferences; // } // // public SharedPreferences.Editor getSharedPreferencesEditor() { // if (editor == null) { // editor = getSharedPreferences().edit(); // } // // return editor; // } // // public static String getWoeid() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_WOEID, null); // } // // public static String getCitySimpleName() { // return InstanceHolder.INSTANCE.getSharedPreferences().getString(PREF_CITY_SIMPLE_NAME, null); // } // // public static boolean getCanAutoUpdate() { // return InstanceHolder.INSTANCE.getSharedPreferences().getBoolean(PREF_AUTO_UPDATE, false); // } // // // private static final class InstanceHolder { // static final PreferenceUtil INSTANCE = new PreferenceUtil(); // } // } // Path: app/src/main/java/com/kuahusg/weather/receiver/BootCompleteReciver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kuahusg.weather.service.AutoUpdateService; import com.kuahusg.weather.util.PreferenceUtil; package com.kuahusg.weather.receiver; /** * Created by kuahusg on 16-6-21. * com.kuahusg.weather.receiver */ public class BootCompleteReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // LogUtil.v(this.toString(), "boot complete,start service"); if (PreferenceUtil.getCanAutoUpdate()) {
Intent intent1 = new Intent(context, AutoUpdateService.class);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/ISelectLocationPresenter.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/City.java // public class City implements Serializable{ // private String city_name; // private String woeid; // private String fullNmae; // // public City(String city_name, String woeid, String fullNmae) { // this.city_name = city_name; // this.woeid = woeid; // this.fullNmae = fullNmae; // } // // public String getCity_name() { // return city_name; // } // // public String getWoeid() { // return woeid; // } // // public String getFullNmae() { // return fullNmae; // } // }
import android.app.Activity; import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.model.bean.City;
package com.kuahusg.weather.Presenter.interfaceOfPresenter; /** * Created by kuahusg on 16-9-27. */ public interface ISelectLocationPresenter extends IBasePresenter { @Override void init(); @Override void start(); @Override void onDestroy(); void onClickQueryButton(String cityNameToSearch);
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/City.java // public class City implements Serializable{ // private String city_name; // private String woeid; // private String fullNmae; // // public City(String city_name, String woeid, String fullNmae) { // this.city_name = city_name; // this.woeid = woeid; // this.fullNmae = fullNmae; // } // // public String getCity_name() { // return city_name; // } // // public String getWoeid() { // return woeid; // } // // public String getFullNmae() { // return fullNmae; // } // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/ISelectLocationPresenter.java import android.app.Activity; import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.model.bean.City; package com.kuahusg.weather.Presenter.interfaceOfPresenter; /** * Created by kuahusg on 16-9-27. */ public interface ISelectLocationPresenter extends IBasePresenter { @Override void init(); @Override void start(); @Override void onDestroy(); void onClickQueryButton(String cityNameToSearch);
void onClickResultCityItem(City selectedCity, Activity activity);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/WeatherFragPresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherMainFragPresenter.java // public interface IWeatherMainFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickBackgroundPic(ImageView imageViewToLoadImage); // // void checkForecastSource(String link, Context context); // // void initBackgroundPic(ImageView imageViewToInit); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java // public interface IWeatherFragView extends IBaseView { // // void showWeather(List<Forecast> forecastList); // // void showForecastInfo(ForecastInfo info); // // void scrollToTop(); // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // // Path: app/src/main/java/com/kuahusg/weather/util/DateUtil.java // public class DateUtil { // private static Date date; // private static SimpleDateFormat format; // public static String getDate(String formatString){ // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(date); // } // // public static String getDate(String formatString, int howLongFromToday) { // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(new Date(date.getTime() - (howLongFromToday * 24 * 60 * 60 * 1000))); // // } // // // public static int getDatePart(int field,int offSet) { // Calendar calendar = Calendar.getInstance(); // return calendar.get(field) - offSet; // // } // // /* public static String getFormatDate(String formatString, String date_string) { // date = new Date(date_string); // format = new SimpleDateFormat(formatString); // return format.format(date); // // }*/ // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IWeatherMainFragPresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IWeatherFragView; import com.kuahusg.weather.data.IDataSource; import com.kuahusg.weather.util.DateUtil; import java.util.Random;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class WeatherFragPresenterImpl extends BasePresenter implements IWeatherMainFragPresenter { private IWeatherFragView mView;
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherMainFragPresenter.java // public interface IWeatherMainFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickBackgroundPic(ImageView imageViewToLoadImage); // // void checkForecastSource(String link, Context context); // // void initBackgroundPic(ImageView imageViewToInit); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java // public interface IWeatherFragView extends IBaseView { // // void showWeather(List<Forecast> forecastList); // // void showForecastInfo(ForecastInfo info); // // void scrollToTop(); // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // // Path: app/src/main/java/com/kuahusg/weather/util/DateUtil.java // public class DateUtil { // private static Date date; // private static SimpleDateFormat format; // public static String getDate(String formatString){ // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(date); // } // // public static String getDate(String formatString, int howLongFromToday) { // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(new Date(date.getTime() - (howLongFromToday * 24 * 60 * 60 * 1000))); // // } // // // public static int getDatePart(int field,int offSet) { // Calendar calendar = Calendar.getInstance(); // return calendar.get(field) - offSet; // // } // // /* public static String getFormatDate(String formatString, String date_string) { // date = new Date(date_string); // format = new SimpleDateFormat(formatString); // return format.format(date); // // }*/ // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/WeatherFragPresenterImpl.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IWeatherMainFragPresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IWeatherFragView; import com.kuahusg.weather.data.IDataSource; import com.kuahusg.weather.util.DateUtil; import java.util.Random; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class WeatherFragPresenterImpl extends BasePresenter implements IWeatherMainFragPresenter { private IWeatherFragView mView;
public WeatherFragPresenterImpl(IBaseView view) {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/WeatherFragPresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherMainFragPresenter.java // public interface IWeatherMainFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickBackgroundPic(ImageView imageViewToLoadImage); // // void checkForecastSource(String link, Context context); // // void initBackgroundPic(ImageView imageViewToInit); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java // public interface IWeatherFragView extends IBaseView { // // void showWeather(List<Forecast> forecastList); // // void showForecastInfo(ForecastInfo info); // // void scrollToTop(); // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // // Path: app/src/main/java/com/kuahusg/weather/util/DateUtil.java // public class DateUtil { // private static Date date; // private static SimpleDateFormat format; // public static String getDate(String formatString){ // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(date); // } // // public static String getDate(String formatString, int howLongFromToday) { // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(new Date(date.getTime() - (howLongFromToday * 24 * 60 * 60 * 1000))); // // } // // // public static int getDatePart(int field,int offSet) { // Calendar calendar = Calendar.getInstance(); // return calendar.get(field) - offSet; // // } // // /* public static String getFormatDate(String formatString, String date_string) { // date = new Date(date_string); // format = new SimpleDateFormat(formatString); // return format.format(date); // // }*/ // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IWeatherMainFragPresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IWeatherFragView; import com.kuahusg.weather.data.IDataSource; import com.kuahusg.weather.util.DateUtil; import java.util.Random;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class WeatherFragPresenterImpl extends BasePresenter implements IWeatherMainFragPresenter { private IWeatherFragView mView; public WeatherFragPresenterImpl(IBaseView view) { super(view); mView = (IWeatherFragView) view; } @Override public void init() { super.init(); if (hasView()) mView.init(); } @Override
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherMainFragPresenter.java // public interface IWeatherMainFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickBackgroundPic(ImageView imageViewToLoadImage); // // void checkForecastSource(String link, Context context); // // void initBackgroundPic(ImageView imageViewToInit); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java // public interface IWeatherFragView extends IBaseView { // // void showWeather(List<Forecast> forecastList); // // void showForecastInfo(ForecastInfo info); // // void scrollToTop(); // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // // Path: app/src/main/java/com/kuahusg/weather/util/DateUtil.java // public class DateUtil { // private static Date date; // private static SimpleDateFormat format; // public static String getDate(String formatString){ // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(date); // } // // public static String getDate(String formatString, int howLongFromToday) { // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(new Date(date.getTime() - (howLongFromToday * 24 * 60 * 60 * 1000))); // // } // // // public static int getDatePart(int field,int offSet) { // Calendar calendar = Calendar.getInstance(); // return calendar.get(field) - offSet; // // } // // /* public static String getFormatDate(String formatString, String date_string) { // date = new Date(date_string); // format = new SimpleDateFormat(formatString); // return format.format(date); // // }*/ // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/WeatherFragPresenterImpl.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IWeatherMainFragPresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IWeatherFragView; import com.kuahusg.weather.data.IDataSource; import com.kuahusg.weather.util.DateUtil; import java.util.Random; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class WeatherFragPresenterImpl extends BasePresenter implements IWeatherMainFragPresenter { private IWeatherFragView mView; public WeatherFragPresenterImpl(IBaseView view) { super(view); mView = (IWeatherFragView) view; } @Override public void init() { super.init(); if (hasView()) mView.init(); } @Override
protected IDataSource setDataSource() {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/WeatherFragPresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherMainFragPresenter.java // public interface IWeatherMainFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickBackgroundPic(ImageView imageViewToLoadImage); // // void checkForecastSource(String link, Context context); // // void initBackgroundPic(ImageView imageViewToInit); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java // public interface IWeatherFragView extends IBaseView { // // void showWeather(List<Forecast> forecastList); // // void showForecastInfo(ForecastInfo info); // // void scrollToTop(); // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // // Path: app/src/main/java/com/kuahusg/weather/util/DateUtil.java // public class DateUtil { // private static Date date; // private static SimpleDateFormat format; // public static String getDate(String formatString){ // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(date); // } // // public static String getDate(String formatString, int howLongFromToday) { // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(new Date(date.getTime() - (howLongFromToday * 24 * 60 * 60 * 1000))); // // } // // // public static int getDatePart(int field,int offSet) { // Calendar calendar = Calendar.getInstance(); // return calendar.get(field) - offSet; // // } // // /* public static String getFormatDate(String formatString, String date_string) { // date = new Date(date_string); // format = new SimpleDateFormat(formatString); // return format.format(date); // // }*/ // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IWeatherMainFragPresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IWeatherFragView; import com.kuahusg.weather.data.IDataSource; import com.kuahusg.weather.util.DateUtil; import java.util.Random;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class WeatherFragPresenterImpl extends BasePresenter implements IWeatherMainFragPresenter { private IWeatherFragView mView; public WeatherFragPresenterImpl(IBaseView view) { super(view); mView = (IWeatherFragView) view; } @Override public void init() { super.init(); if (hasView()) mView.init(); } @Override protected IDataSource setDataSource() { return null; } @Override public void start() { } @Override public void onClickBackgroundPic(ImageView imageViewToLoadImage) { int i = getRandomNum(7, 17);
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherMainFragPresenter.java // public interface IWeatherMainFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickBackgroundPic(ImageView imageViewToLoadImage); // // void checkForecastSource(String link, Context context); // // void initBackgroundPic(ImageView imageViewToInit); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java // public interface IWeatherFragView extends IBaseView { // // void showWeather(List<Forecast> forecastList); // // void showForecastInfo(ForecastInfo info); // // void scrollToTop(); // // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // // Path: app/src/main/java/com/kuahusg/weather/util/DateUtil.java // public class DateUtil { // private static Date date; // private static SimpleDateFormat format; // public static String getDate(String formatString){ // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(date); // } // // public static String getDate(String formatString, int howLongFromToday) { // date = new Date(); // DateUtil.format = new SimpleDateFormat(formatString); // return format.format(new Date(date.getTime() - (howLongFromToday * 24 * 60 * 60 * 1000))); // // } // // // public static int getDatePart(int field,int offSet) { // Calendar calendar = Calendar.getInstance(); // return calendar.get(field) - offSet; // // } // // /* public static String getFormatDate(String formatString, String date_string) { // date = new Date(date_string); // format = new SimpleDateFormat(formatString); // return format.format(date); // // }*/ // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/WeatherFragPresenterImpl.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IWeatherMainFragPresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IWeatherFragView; import com.kuahusg.weather.data.IDataSource; import com.kuahusg.weather.util.DateUtil; import java.util.Random; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class WeatherFragPresenterImpl extends BasePresenter implements IWeatherMainFragPresenter { private IWeatherFragView mView; public WeatherFragPresenterImpl(IBaseView view) { super(view); mView = (IWeatherFragView) view; } @Override public void init() { super.init(); if (hasView()) mView.init(); } @Override protected IDataSource setDataSource() { return null; } @Override public void start() { } @Override public void onClickBackgroundPic(ImageView imageViewToLoadImage) { int i = getRandomNum(7, 17);
loadPicture(DateUtil.getDate("yy-MM-dd", i), imageViewToLoadImage);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/util/CrashHandler.java
// Path: app/src/main/java/com/kuahusg/weather/App.java // public class App extends Application { // private static Context context; // // private RefWatcher watcher; // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // // CrashHandler crashHandler = CrashHandler.getInstance(); // crashHandler.init(); // // /* if (LeakCanary.isInAnalyzerProcess(this)) { // return; // } // watcher = LeakCanary.install(this);*/ // } // // public static Context getContext() { // return context; // } // // /* public static RefWatcher getWatcher(Context context) { // App app = (App) context.getApplicationContext(); // return app.watcher; // }*/ // }
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.drawable.Icon; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Looper; import android.os.Message; import android.os.Process; import android.os.StrictMode; import android.support.annotation.RequiresApi; import android.widget.Toast; import com.kuahusg.weather.App; import com.kuahusg.weather.R; import java.io.File; import java.io.FileOutputStream; import java.io.IOException;
Process.killProcess(Process.myPid()); System.exit(10); } } private CrashHandler() { } public void init() { InstanceHolder.INSTANCE.exceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } private void handleException(final Throwable e) { final StackTraceElement[] elements = e.getStackTrace(); final String message = "Message:\n" + e.getMessage() + "\n"; final String fileName = "crash-" + System.currentTimeMillis() + ".log"; StringBuilder sb = new StringBuilder(); for (StackTraceElement element : elements) { sb.append(element.toString()).append("\n"); } final String stackMessage = "\nTraceMessage: " + sb.toString();
// Path: app/src/main/java/com/kuahusg/weather/App.java // public class App extends Application { // private static Context context; // // private RefWatcher watcher; // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // // CrashHandler crashHandler = CrashHandler.getInstance(); // crashHandler.init(); // // /* if (LeakCanary.isInAnalyzerProcess(this)) { // return; // } // watcher = LeakCanary.install(this);*/ // } // // public static Context getContext() { // return context; // } // // /* public static RefWatcher getWatcher(Context context) { // App app = (App) context.getApplicationContext(); // return app.watcher; // }*/ // } // Path: app/src/main/java/com/kuahusg/weather/util/CrashHandler.java import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.drawable.Icon; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Looper; import android.os.Message; import android.os.Process; import android.os.StrictMode; import android.support.annotation.RequiresApi; import android.widget.Toast; import com.kuahusg.weather.App; import com.kuahusg.weather.R; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; Process.killProcess(Process.myPid()); System.exit(10); } } private CrashHandler() { } public void init() { InstanceHolder.INSTANCE.exceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } private void handleException(final Throwable e) { final StackTraceElement[] elements = e.getStackTrace(); final String message = "Message:\n" + e.getMessage() + "\n"; final String fileName = "crash-" + System.currentTimeMillis() + ".log"; StringBuilder sb = new StringBuilder(); for (StackTraceElement element : elements) { sb.append(element.toString()).append("\n"); } final String stackMessage = "\nTraceMessage: " + sb.toString();
final String toastMessage = App.getContext().getString(R.string.crash_message);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/activities/SettingActivity.java
// Path: app/src/main/java/com/kuahusg/weather/UI/Fragment/SettingFragment.java // public class SettingFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { // public static final String AUTO_UPDATE = "auto_update"; // public static final String UPDATE_TIME = "update_time"; // public static final String OPEN_SOURCE = "open_source"; // public static final String ABOUT = "about"; // public static final String UPDATE_APP = "update_app"; // private SwitchPreference autoUpdatePreference; // private EditTextPreference updateTimePreference; // private Activity activity; // // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activity = getActivity(); // // addPreferencesFromResource(R.xml.preference); // // // autoUpdatePreference = (SwitchPreference) findPreference(AUTO_UPDATE); // updateTimePreference = (EditTextPreference) findPreference(UPDATE_TIME); // autoUpdatePreference.setOnPreferenceChangeListener(this); // updateTimePreference.setOnPreferenceChangeListener(this); // // updateTimePreference.setEnabled(autoUpdatePreference.isChecked()); // } // // // @Override // public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { // switch (preference.getKey()) { // case AUTO_UPDATE: // updateTimePreference.setEnabled(autoUpdatePreference.isChecked()); // break; // case ABOUT: // Intent intent = new Intent(activity, AboutMeActivity.class); // activity.startActivity(intent); // break; // case OPEN_SOURCE: // Intent intent1 = new Intent(Intent.ACTION_VIEW); // intent1.setData(Uri.parse("https://github.com/Kuanghusing/Weather")); // activity.startActivity(intent1); // break; // case UPDATE_APP: // Intent i = new Intent(Intent.ACTION_VIEW); // i.setData(Uri.parse("http://fir.im/eync")); // startActivity(i); // break; // } // return super.onPreferenceTreeClick(preferenceScreen, preference); // } // // // @Override // public boolean onPreferenceChange(Preference preference, Object newValue) { // Intent intent = new Intent(activity, AutoUpdateService.class); // LogUtil.v(this.toString(), "onPreferenceChange()"); // if (preference.getKey().equals(SettingFragment.UPDATE_TIME)) { // LogUtil.v(this.toString(), "onPreferenceChange() -> UPDATE"); // if (TextUtils.isEmpty((String) newValue)) { // Toast.makeText(activity, activity.getString(R.string.no_value_error), Toast.LENGTH_LONG).show(); // return false; // } // activity.stopService(intent); // activity.startService(intent); // } else if (preference.getKey().equals(SettingFragment.AUTO_UPDATE)) { // LogUtil.v(this.toString(), "onPreferenceChange() -> AUTO"); // // if ((boolean) newValue) { // activity.startService(intent); // } else { // activity.stopService(intent); // } // } // return true; // } // // // }
import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.Fragment.SettingFragment;
package com.kuahusg.weather.UI.activities; /** * Created by kuahusg on 16-6-10. * com.kuahusg.weather.UI.activities */ public class SettingActivity extends AppCompatActivity { private Toolbar toolbar; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.preference); setContentView(R.layout.activity_setting); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionbar = getSupportActionBar(); if (actionbar != null) { actionbar.setDisplayHomeAsUpEnabled(true); } /* ViewGroup viewRoot = (ViewGroup) findViewById(android.R.id.content); View content = viewRoot.getChildAt(0); LinearLayout toolbarLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.activity_setting, null); viewRoot.removeAllViews(); toolbarLayout.addView(content); viewRoot.addView(toolbarLayout);*/
// Path: app/src/main/java/com/kuahusg/weather/UI/Fragment/SettingFragment.java // public class SettingFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { // public static final String AUTO_UPDATE = "auto_update"; // public static final String UPDATE_TIME = "update_time"; // public static final String OPEN_SOURCE = "open_source"; // public static final String ABOUT = "about"; // public static final String UPDATE_APP = "update_app"; // private SwitchPreference autoUpdatePreference; // private EditTextPreference updateTimePreference; // private Activity activity; // // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activity = getActivity(); // // addPreferencesFromResource(R.xml.preference); // // // autoUpdatePreference = (SwitchPreference) findPreference(AUTO_UPDATE); // updateTimePreference = (EditTextPreference) findPreference(UPDATE_TIME); // autoUpdatePreference.setOnPreferenceChangeListener(this); // updateTimePreference.setOnPreferenceChangeListener(this); // // updateTimePreference.setEnabled(autoUpdatePreference.isChecked()); // } // // // @Override // public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { // switch (preference.getKey()) { // case AUTO_UPDATE: // updateTimePreference.setEnabled(autoUpdatePreference.isChecked()); // break; // case ABOUT: // Intent intent = new Intent(activity, AboutMeActivity.class); // activity.startActivity(intent); // break; // case OPEN_SOURCE: // Intent intent1 = new Intent(Intent.ACTION_VIEW); // intent1.setData(Uri.parse("https://github.com/Kuanghusing/Weather")); // activity.startActivity(intent1); // break; // case UPDATE_APP: // Intent i = new Intent(Intent.ACTION_VIEW); // i.setData(Uri.parse("http://fir.im/eync")); // startActivity(i); // break; // } // return super.onPreferenceTreeClick(preferenceScreen, preference); // } // // // @Override // public boolean onPreferenceChange(Preference preference, Object newValue) { // Intent intent = new Intent(activity, AutoUpdateService.class); // LogUtil.v(this.toString(), "onPreferenceChange()"); // if (preference.getKey().equals(SettingFragment.UPDATE_TIME)) { // LogUtil.v(this.toString(), "onPreferenceChange() -> UPDATE"); // if (TextUtils.isEmpty((String) newValue)) { // Toast.makeText(activity, activity.getString(R.string.no_value_error), Toast.LENGTH_LONG).show(); // return false; // } // activity.stopService(intent); // activity.startService(intent); // } else if (preference.getKey().equals(SettingFragment.AUTO_UPDATE)) { // LogUtil.v(this.toString(), "onPreferenceChange() -> AUTO"); // // if ((boolean) newValue) { // activity.startService(intent); // } else { // activity.stopService(intent); // } // } // return true; // } // // // } // Path: app/src/main/java/com/kuahusg/weather/UI/activities/SettingActivity.java import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.Fragment.SettingFragment; package com.kuahusg.weather.UI.activities; /** * Created by kuahusg on 16-6-10. * com.kuahusg.weather.UI.activities */ public class SettingActivity extends AppCompatActivity { private Toolbar toolbar; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; } return super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.preference); setContentView(R.layout.activity_setting); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionbar = getSupportActionBar(); if (actionbar != null) { actionbar.setDisplayHomeAsUpEnabled(true); } /* ViewGroup viewRoot = (ViewGroup) findViewById(android.R.id.content); View content = viewRoot.getChildAt(0); LinearLayout toolbarLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.activity_setting, null); viewRoot.removeAllViews(); toolbarLayout.addView(content); viewRoot.addView(toolbarLayout);*/
getFragmentManager().beginTransaction().replace(R.id.setting_part, new SettingFragment()).commit();
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/receiver/AutoUpdateReceiver.java
// Path: app/src/main/java/com/kuahusg/weather/service/AutoUpdateService.java // public class AutoUpdateService extends Service { // private double time = 2; // // // private IDataSource dataSource = new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()); // private WeakReference<IDataSource> dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // // // @Override // public void onCreate() { // super.onCreate(); // LogUtil.v(this.toString(), "Service onCreate()"); // // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // // // time = Double.valueOf(PreferenceUtil.getInstance().getSharedPreferences().getString(SettingFragment.UPDATE_TIME, "0")); // if (time <= 0) // time = 2; // // TODO: 16-10-8 ?? // dataSourceWeakReference.get().queryWeather(null, new RequestWeatherCallback() { // @Override // public void success(List<Forecast> forecasts, ForecastInfo forecastInfo) { // } // // @Override // public void error(String message) { // // } // }); // // AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // long hours = (long) (time * 60 * 60 * 1000 + SystemClock.elapsedRealtime()); // Intent i = new Intent(this, AutoUpdateReceiver.class); // PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, hours, pi); // return super.onStartCommand(intent, flags, startId); // } // // @Override // public void onDestroy() { // super.onDestroy(); // LogUtil.v(this.toString(), "Service onDestroy()"); // } // // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kuahusg.weather.service.AutoUpdateService;
package com.kuahusg.weather.receiver; /** * Created by kuahusg on 16-5-10. */ public class AutoUpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
// Path: app/src/main/java/com/kuahusg/weather/service/AutoUpdateService.java // public class AutoUpdateService extends Service { // private double time = 2; // // // private IDataSource dataSource = new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()); // private WeakReference<IDataSource> dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // // // @Override // public void onCreate() { // super.onCreate(); // LogUtil.v(this.toString(), "Service onCreate()"); // // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // // // time = Double.valueOf(PreferenceUtil.getInstance().getSharedPreferences().getString(SettingFragment.UPDATE_TIME, "0")); // if (time <= 0) // time = 2; // // TODO: 16-10-8 ?? // dataSourceWeakReference.get().queryWeather(null, new RequestWeatherCallback() { // @Override // public void success(List<Forecast> forecasts, ForecastInfo forecastInfo) { // } // // @Override // public void error(String message) { // // } // }); // // AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // long hours = (long) (time * 60 * 60 * 1000 + SystemClock.elapsedRealtime()); // Intent i = new Intent(this, AutoUpdateReceiver.class); // PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0); // alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, hours, pi); // return super.onStartCommand(intent, flags, startId); // } // // @Override // public void onDestroy() { // super.onDestroy(); // LogUtil.v(this.toString(), "Service onDestroy()"); // } // // // } // Path: app/src/main/java/com/kuahusg/weather/receiver/AutoUpdateReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.kuahusg.weather.service.AutoUpdateService; package com.kuahusg.weather.receiver; /** * Created by kuahusg on 16-5-10. */ public class AutoUpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, AutoUpdateService.class);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-29. */ public interface IWeatherFragView extends IBaseView { void showWeather(List<Forecast> forecastList);
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IWeatherFragView.java import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-29. */ public interface IWeatherFragView extends IBaseView { void showWeather(List<Forecast> forecastList);
void showForecastInfo(ForecastInfo info);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IFutureWeatherFragView.java
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // }
import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import java.util.List;
package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-29. */ public interface IFutureWeatherFragView extends IBaseView { @Override void start(); @Override void error(String message); @Override void finish(); @Override void init();
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IFutureWeatherFragView.java import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.Forecast; import java.util.List; package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-29. */ public interface IFutureWeatherFragView extends IBaseView { @Override void start(); @Override void error(String message); @Override void finish(); @Override void init();
void showForecast(List<Forecast> forecastList);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/util/PreferenceUtil.java
// Path: app/src/main/java/com/kuahusg/weather/App.java // public class App extends Application { // private static Context context; // // private RefWatcher watcher; // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // // CrashHandler crashHandler = CrashHandler.getInstance(); // crashHandler.init(); // // /* if (LeakCanary.isInAnalyzerProcess(this)) { // return; // } // watcher = LeakCanary.install(this);*/ // } // // public static Context getContext() { // return context; // } // // /* public static RefWatcher getWatcher(Context context) { // App app = (App) context.getApplicationContext(); // return app.watcher; // }*/ // }
import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.kuahusg.weather.App;
package com.kuahusg.weather.util; /** * Created by kuahusg on 16-9-27. */ public class PreferenceUtil { SharedPreferences sharedPreferences; SharedPreferences.Editor editor; public static final String PREF_HAS_LOAD_ALL_CITY = "hasLoadAllCity"; public static final String PREF_SELECTED_CITY = "selectCity"; public static final String PREF_WOEID = "woeid"; public static final String PREF_CITY_SIMPLE_NAME = "selectCitySimpleName"; public static final String PREF_AUTO_UPDATE = "auto_update"; private PreferenceUtil() { } public static PreferenceUtil getInstance() { return InstanceHolder.INSTANCE; } public SharedPreferences getSharedPreferences() { if (sharedPreferences == null)
// Path: app/src/main/java/com/kuahusg/weather/App.java // public class App extends Application { // private static Context context; // // private RefWatcher watcher; // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // // CrashHandler crashHandler = CrashHandler.getInstance(); // crashHandler.init(); // // /* if (LeakCanary.isInAnalyzerProcess(this)) { // return; // } // watcher = LeakCanary.install(this);*/ // } // // public static Context getContext() { // return context; // } // // /* public static RefWatcher getWatcher(Context context) { // App app = (App) context.getApplicationContext(); // return app.watcher; // }*/ // } // Path: app/src/main/java/com/kuahusg/weather/util/PreferenceUtil.java import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.kuahusg.weather.App; package com.kuahusg.weather.util; /** * Created by kuahusg on 16-9-27. */ public class PreferenceUtil { SharedPreferences sharedPreferences; SharedPreferences.Editor editor; public static final String PREF_HAS_LOAD_ALL_CITY = "hasLoadAllCity"; public static final String PREF_SELECTED_CITY = "selectCity"; public static final String PREF_WOEID = "woeid"; public static final String PREF_CITY_SIMPLE_NAME = "selectCitySimpleName"; public static final String PREF_AUTO_UPDATE = "auto_update"; private PreferenceUtil() { } public static PreferenceUtil getInstance() { return InstanceHolder.INSTANCE; } public SharedPreferences getSharedPreferences() { if (sharedPreferences == null)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext());
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/Adapter/RvAdapter.java
// Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/App.java // public static Context getContext() { // return context; // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.kuahusg.weather.R; import com.kuahusg.weather.model.bean.Forecast; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Random; import static com.kuahusg.weather.App.getContext;
if (info.contains("Thunderstorms")) { img.setImageResource(R.drawable.thunderstorm); } else if (info.contains("Cloudy")) { img.setImageResource(R.drawable.cloud_sun); } else if (info.contains("Sunny")) { img.setImageResource(R.drawable.sunny); } else if (info.contains("Showers") || info.contains("Rain")) { img.setImageResource(R.drawable.rain3); } else if (info.contains("Breezy")) { img.setImageResource(R.drawable.wind); } else if (info.contains("snow")) { img.setImageResource(R.drawable.snow2); } else { img.setImageResource(R.drawable.sun); } } private int getRandomImgPlaceHolder() { int random = new Random().nextInt(2); if (random == 0) { return R.drawable.bg0; } else return R.drawable.back; } private void showAnim(View view, int animId) {
// Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/App.java // public static Context getContext() { // return context; // } // Path: app/src/main/java/com/kuahusg/weather/UI/Adapter/RvAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.kuahusg.weather.R; import com.kuahusg.weather.model.bean.Forecast; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Random; import static com.kuahusg.weather.App.getContext; if (info.contains("Thunderstorms")) { img.setImageResource(R.drawable.thunderstorm); } else if (info.contains("Cloudy")) { img.setImageResource(R.drawable.cloud_sun); } else if (info.contains("Sunny")) { img.setImageResource(R.drawable.sunny); } else if (info.contains("Showers") || info.contains("Rain")) { img.setImageResource(R.drawable.rain3); } else if (info.contains("Breezy")) { img.setImageResource(R.drawable.wind); } else if (info.contains("snow")) { img.setImageResource(R.drawable.snow2); } else { img.setImageResource(R.drawable.sun); } } private int getRandomImgPlaceHolder() { int random = new Random().nextInt(2); if (random == 0) { return R.drawable.bg0; } else return R.drawable.back; } private void showAnim(View view, int animId) {
Animation animation = AnimationUtils.loadAnimation(getContext(), animId);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/activities/AboutMeActivity.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java // public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { // private IAboutMeView mView; // // public AboutMePresenterImpl(IBaseView view) { // super(view); // mView = (IAboutMeView) view; // } // // @Override // public void init() { // super.init(); // } // // @Override // protected IDataSource setDataSource() { // return null; // } // // @Override // public void start() { // // } // // @Override // public void onClickFab(Activity activity) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse(activity.getString(R.string.open_source_text))); // activity.startActivity(intent); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity implements IBaseView { // private IBasePresenter mPresenter; // // // public IBasePresenter getPresenter() { // if (mPresenter != null) { // return mPresenter; // } // // return null; // } // // // public boolean hasPresenter() { // return mPresenter != null; // } // // // protected abstract IBasePresenter setPresenter(); // // protected abstract int setLayoutId(); // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mPresenter = setPresenter(); // // setContentView(setLayoutId()); // // // } // // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.d(this.getClass().getSimpleName(), "Activity onDestroy"); // // RefWatcher watcher = App.getWatcher(this); // // watcher.watch(this); // if (hasPresenter()) // mPresenter.onDestroy(); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.View; import com.kuahusg.weather.Presenter.AboutMePresenterImpl; import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.BaseActivity; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView;
package com.kuahusg.weather.UI.activities; /** * Created by kuahusg on 16-9-27. */ public class AboutMeActivity extends BaseActivity implements IAboutMeView { private IAboutMePresenter mPresenter; private Toolbar mToolbar; private FloatingActionButton mFab; private CollapsingToolbarLayout mCollapsingToolbarLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); } private void initView() { mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); ActionBar ab = getSupportActionBar(); assert ab != null; ab.setDisplayHomeAsUpEnabled(true); mFab = (FloatingActionButton) findViewById(R.id.fab); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasPresenter()) mPresenter.onClickFab(AboutMeActivity.this); } }); mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout); mCollapsingToolbarLayout.setTitle(getString(R.string.about)); } @Override
// Path: app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java // public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { // private IAboutMeView mView; // // public AboutMePresenterImpl(IBaseView view) { // super(view); // mView = (IAboutMeView) view; // } // // @Override // public void init() { // super.init(); // } // // @Override // protected IDataSource setDataSource() { // return null; // } // // @Override // public void start() { // // } // // @Override // public void onClickFab(Activity activity) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse(activity.getString(R.string.open_source_text))); // activity.startActivity(intent); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity implements IBaseView { // private IBasePresenter mPresenter; // // // public IBasePresenter getPresenter() { // if (mPresenter != null) { // return mPresenter; // } // // return null; // } // // // public boolean hasPresenter() { // return mPresenter != null; // } // // // protected abstract IBasePresenter setPresenter(); // // protected abstract int setLayoutId(); // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mPresenter = setPresenter(); // // setContentView(setLayoutId()); // // // } // // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.d(this.getClass().getSimpleName(), "Activity onDestroy"); // // RefWatcher watcher = App.getWatcher(this); // // watcher.watch(this); // if (hasPresenter()) // mPresenter.onDestroy(); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // } // Path: app/src/main/java/com/kuahusg/weather/UI/activities/AboutMeActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.View; import com.kuahusg.weather.Presenter.AboutMePresenterImpl; import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.BaseActivity; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; package com.kuahusg.weather.UI.activities; /** * Created by kuahusg on 16-9-27. */ public class AboutMeActivity extends BaseActivity implements IAboutMeView { private IAboutMePresenter mPresenter; private Toolbar mToolbar; private FloatingActionButton mFab; private CollapsingToolbarLayout mCollapsingToolbarLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); } private void initView() { mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); ActionBar ab = getSupportActionBar(); assert ab != null; ab.setDisplayHomeAsUpEnabled(true); mFab = (FloatingActionButton) findViewById(R.id.fab); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasPresenter()) mPresenter.onClickFab(AboutMeActivity.this); } }); mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout); mCollapsingToolbarLayout.setTitle(getString(R.string.about)); } @Override
protected IBasePresenter setPresenter() {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/activities/AboutMeActivity.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java // public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { // private IAboutMeView mView; // // public AboutMePresenterImpl(IBaseView view) { // super(view); // mView = (IAboutMeView) view; // } // // @Override // public void init() { // super.init(); // } // // @Override // protected IDataSource setDataSource() { // return null; // } // // @Override // public void start() { // // } // // @Override // public void onClickFab(Activity activity) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse(activity.getString(R.string.open_source_text))); // activity.startActivity(intent); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity implements IBaseView { // private IBasePresenter mPresenter; // // // public IBasePresenter getPresenter() { // if (mPresenter != null) { // return mPresenter; // } // // return null; // } // // // public boolean hasPresenter() { // return mPresenter != null; // } // // // protected abstract IBasePresenter setPresenter(); // // protected abstract int setLayoutId(); // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mPresenter = setPresenter(); // // setContentView(setLayoutId()); // // // } // // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.d(this.getClass().getSimpleName(), "Activity onDestroy"); // // RefWatcher watcher = App.getWatcher(this); // // watcher.watch(this); // if (hasPresenter()) // mPresenter.onDestroy(); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.View; import com.kuahusg.weather.Presenter.AboutMePresenterImpl; import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.BaseActivity; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView;
package com.kuahusg.weather.UI.activities; /** * Created by kuahusg on 16-9-27. */ public class AboutMeActivity extends BaseActivity implements IAboutMeView { private IAboutMePresenter mPresenter; private Toolbar mToolbar; private FloatingActionButton mFab; private CollapsingToolbarLayout mCollapsingToolbarLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); } private void initView() { mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); ActionBar ab = getSupportActionBar(); assert ab != null; ab.setDisplayHomeAsUpEnabled(true); mFab = (FloatingActionButton) findViewById(R.id.fab); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasPresenter()) mPresenter.onClickFab(AboutMeActivity.this); } }); mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout); mCollapsingToolbarLayout.setTitle(getString(R.string.about)); } @Override protected IBasePresenter setPresenter() {
// Path: app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java // public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { // private IAboutMeView mView; // // public AboutMePresenterImpl(IBaseView view) { // super(view); // mView = (IAboutMeView) view; // } // // @Override // public void init() { // super.init(); // } // // @Override // protected IDataSource setDataSource() { // return null; // } // // @Override // public void start() { // // } // // @Override // public void onClickFab(Activity activity) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.setData(Uri.parse(activity.getString(R.string.open_source_text))); // activity.startActivity(intent); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IAboutMePresenter.java // public interface IAboutMePresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // // void onClickFab(Activity activity); // // // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity implements IBaseView { // private IBasePresenter mPresenter; // // // public IBasePresenter getPresenter() { // if (mPresenter != null) { // return mPresenter; // } // // return null; // } // // // public boolean hasPresenter() { // return mPresenter != null; // } // // // protected abstract IBasePresenter setPresenter(); // // protected abstract int setLayoutId(); // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mPresenter = setPresenter(); // // setContentView(setLayoutId()); // // // } // // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.d(this.getClass().getSimpleName(), "Activity onDestroy"); // // RefWatcher watcher = App.getWatcher(this); // // watcher.watch(this); // if (hasPresenter()) // mPresenter.onDestroy(); // // } // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IAboutMeView.java // public interface IAboutMeView extends IBaseView { // @Override // void init(); // // @Override // void start(); // // @Override // void finish(); // // @Override // void error(String message); // // // } // Path: app/src/main/java/com/kuahusg/weather/UI/activities/AboutMeActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.View; import com.kuahusg.weather.Presenter.AboutMePresenterImpl; import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.BaseActivity; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; package com.kuahusg.weather.UI.activities; /** * Created by kuahusg on 16-9-27. */ public class AboutMeActivity extends BaseActivity implements IAboutMeView { private IAboutMePresenter mPresenter; private Toolbar mToolbar; private FloatingActionButton mFab; private CollapsingToolbarLayout mCollapsingToolbarLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); } private void initView() { mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); ActionBar ab = getSupportActionBar(); assert ab != null; ab.setDisplayHomeAsUpEnabled(true); mFab = (FloatingActionButton) findViewById(R.id.fab); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasPresenter()) mPresenter.onClickFab(AboutMeActivity.this); } }); mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_layout); mCollapsingToolbarLayout.setTitle(getString(R.string.about)); } @Override protected IBasePresenter setPresenter() {
mPresenter = new AboutMePresenterImpl(this);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/FutureWeatherFragPresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IFutureWeatherFragPresenter.java // public interface IFutureWeatherFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IFutureWeatherFragView.java // public interface IFutureWeatherFragView extends IBaseView { // @Override // void start(); // // @Override // void error(String message); // // @Override // void finish(); // // @Override // void init(); // // void showForecast(List<Forecast> forecastList); // // void scrollToTop(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // }
import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IFutureWeatherFragPresenter; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IFutureWeatherFragView; import com.kuahusg.weather.data.IDataSource;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class FutureWeatherFragPresenterImpl extends BasePresenter implements IFutureWeatherFragPresenter { private IFutureWeatherFragView mView;
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IFutureWeatherFragPresenter.java // public interface IFutureWeatherFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IFutureWeatherFragView.java // public interface IFutureWeatherFragView extends IBaseView { // @Override // void start(); // // @Override // void error(String message); // // @Override // void finish(); // // @Override // void init(); // // void showForecast(List<Forecast> forecastList); // // void scrollToTop(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/FutureWeatherFragPresenterImpl.java import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IFutureWeatherFragPresenter; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IFutureWeatherFragView; import com.kuahusg.weather.data.IDataSource; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class FutureWeatherFragPresenterImpl extends BasePresenter implements IFutureWeatherFragPresenter { private IFutureWeatherFragView mView;
public FutureWeatherFragPresenterImpl(IBaseView view) {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/FutureWeatherFragPresenterImpl.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IFutureWeatherFragPresenter.java // public interface IFutureWeatherFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IFutureWeatherFragView.java // public interface IFutureWeatherFragView extends IBaseView { // @Override // void start(); // // @Override // void error(String message); // // @Override // void finish(); // // @Override // void init(); // // void showForecast(List<Forecast> forecastList); // // void scrollToTop(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // }
import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IFutureWeatherFragPresenter; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IFutureWeatherFragView; import com.kuahusg.weather.data.IDataSource;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class FutureWeatherFragPresenterImpl extends BasePresenter implements IFutureWeatherFragPresenter { private IFutureWeatherFragView mView; public FutureWeatherFragPresenterImpl(IBaseView view) { super(view); mView = (IFutureWeatherFragView) view; } @Override public void init() { super.init(); if (hasView()) mView.init(); } @Override
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/BasePresenter.java // public abstract class BasePresenter implements IBasePresenter { // // private IBaseView mView; // // private IDataSource dataSource; // private WeakReference<IDataSource> dataSourceWeakReference; // // public BasePresenter(IBaseView view) { // this.mView = view; // } // // public IBaseView getView() { // return mView; // } // // public boolean hasView() { // return mView != null; // } // // // protected abstract IDataSource setDataSource(); // // public IDataSource getDataSource() { // if (dataSourceWeakReference.get() == null) { // getDatasource(); // } // return dataSourceWeakReference.get(); // } // // @Override // public void init() { // dataSourceWeakReference = new WeakReference<>(setDataSource()); // } // // @Override // public void onDestroy() { // mView = null; // if (dataSourceWeakReference != null) { // dataSourceWeakReference.clear(); // dataSourceWeakReference = null; // } // } // // private void getDatasource() { // this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource())); // } // // // } // // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IFutureWeatherFragPresenter.java // public interface IFutureWeatherFragPresenter extends IBasePresenter { // @Override // void init(); // // @Override // void start(); // // @Override // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/IFutureWeatherFragView.java // public interface IFutureWeatherFragView extends IBaseView { // @Override // void start(); // // @Override // void error(String message); // // @Override // void finish(); // // @Override // void init(); // // void showForecast(List<Forecast> forecastList); // // void scrollToTop(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java // public interface IDataSource { // void queryWeather(String woeid, RequestWeatherCallback callback); // // void queryWeather(RequestWeatherCallback callback); // // // void saveWeather(List<Forecast> forecastList, ForecastInfo info); // // void loadAllCity(RequestCityCallback cityCallback); // // void saveAllCity(List<String> cityList); // // void queryCity(RequestCityResultCallback callback, String cityName); // // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/FutureWeatherFragPresenterImpl.java import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IFutureWeatherFragPresenter; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IFutureWeatherFragView; import com.kuahusg.weather.data.IDataSource; package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-29. */ public class FutureWeatherFragPresenterImpl extends BasePresenter implements IFutureWeatherFragPresenter { private IFutureWeatherFragView mView; public FutureWeatherFragPresenterImpl(IBaseView view) { super(view); mView = (IFutureWeatherFragView) view; } @Override public void init() { super.init(); if (hasView()) mView.init(); } @Override
protected IDataSource setDataSource() {
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherViewPresenter.java
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/City.java // public class City implements Serializable{ // private String city_name; // private String woeid; // private String fullNmae; // // public City(String city_name, String woeid, String fullNmae) { // this.city_name = city_name; // this.woeid = woeid; // this.fullNmae = fullNmae; // } // // public String getCity_name() { // return city_name; // } // // public String getWoeid() { // return woeid; // } // // public String getFullNmae() { // return fullNmae; // } // }
import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.model.bean.City;
package com.kuahusg.weather.Presenter.interfaceOfPresenter; /** * Created by kuahusg on 16-9-27. */ public interface IWeatherViewPresenter extends IBasePresenter { @Override void init(); @Override void start(); @Override void onDestroy(); void startAutoUpdateService(); void onClickFab(); void refreshWeather();
// Path: app/src/main/java/com/kuahusg/weather/Presenter/base/IBasePresenter.java // public interface IBasePresenter { // // void init(); // // void start(); // // void onDestroy(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/City.java // public class City implements Serializable{ // private String city_name; // private String woeid; // private String fullNmae; // // public City(String city_name, String woeid, String fullNmae) { // this.city_name = city_name; // this.woeid = woeid; // this.fullNmae = fullNmae; // } // // public String getCity_name() { // return city_name; // } // // public String getWoeid() { // return woeid; // } // // public String getFullNmae() { // return fullNmae; // } // } // Path: app/src/main/java/com/kuahusg/weather/Presenter/interfaceOfPresenter/IWeatherViewPresenter.java import com.kuahusg.weather.Presenter.base.IBasePresenter; import com.kuahusg.weather.model.bean.City; package com.kuahusg.weather.Presenter.interfaceOfPresenter; /** * Created by kuahusg on 16-9-27. */ public interface IWeatherViewPresenter extends IBasePresenter { @Override void init(); @Override void start(); @Override void onDestroy(); void startAutoUpdateService(); void onClickFab(); void refreshWeather();
void refreshWeather(City city);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/IDataSource.java
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback);
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback);
void saveWeather(List<Forecast> forecastList, ForecastInfo info);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/IDataSource.java
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback);
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback);
void saveWeather(List<Forecast> forecastList, ForecastInfo info);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/IDataSource.java
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback); void saveWeather(List<Forecast> forecastList, ForecastInfo info);
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback); void saveWeather(List<Forecast> forecastList, ForecastInfo info);
void loadAllCity(RequestCityCallback cityCallback);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/data/IDataSource.java
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // }
import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List;
package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback); void saveWeather(List<Forecast> forecastList, ForecastInfo info); void loadAllCity(RequestCityCallback cityCallback); void saveAllCity(List<String> cityList);
// Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityCallback.java // public interface RequestCityCallback { // void success(List<String> cityList); // // void error(); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestCityResultCallback.java // public interface RequestCityResultCallback { // void success(List<City> cityList); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/data/callback/RequestWeatherCallback.java // public interface RequestWeatherCallback { // void success(List<Forecast> forecasts, ForecastInfo forecastInfo); // // void error(String message); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/Forecast.java // public class Forecast implements Parcelable{ // public static final Parcelable.Creator<Forecast> CREATOR = new Creator<Forecast>() { // @Override // public Forecast createFromParcel(Parcel source) { // Forecast forecast = new Forecast(source.readString(), source.readString(), source.readString(), // source.readString(), source.readString()); // // return null; // } // // @Override // public Forecast[] newArray(int size) { // return new Forecast[size]; // } // }; // private String date; // private String high; // private String low; // private String text; // private String woeid; // // public Forecast(String date, String high, String low, String text, String woeid) { // this.date = date; // this.high = high; // this.low = low; // this.text = text; // this.woeid = woeid; // } // // // // public String getDate() { // return date; // } // // public String getHigh() { // return high; // } // // public String getLow() { // return low; // } // // public String getText() { // return text; // } // // public String getWoeid() { // return woeid; // } // // public void setWoeid(String woeid) { // this.woeid = woeid; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // // dest.writeString(date); // dest.writeString(high); // dest.writeString(low); // dest.writeString(text); // dest.writeString(woeid); // } // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/ForecastInfo.java // public class ForecastInfo implements Serializable { // private String link; // private String lastBuildDate; // private String windDirection; // private String windSpeed; // private String date; // private String temp; // private String text; // private String sunrise; // private String sunset; // private String woeid; // // public ForecastInfo(String link, String lastBuildDate, String windDirection, String windSpeed, // String date, String temp, String text, String woeid, String sunrise, String sunset) { // // this.link = link; // this.lastBuildDate = lastBuildDate; // this.windDirection = windDirection; // this.windSpeed = windSpeed; // this.date = date; // this.temp = temp; // this.text = text; // this.woeid = woeid; // this.sunrise = sunrise; // this.sunset = sunset; // } // // // public String getLink() { // return link; // } // // public String getLastBuildDate() { // return lastBuildDate; // } // // public String getWindDirection() { // return windDirection; // } // // public String getWindSpeed() { // return windSpeed; // } // // public String getDate() { // return date; // } // // public String getTemp() { // return temp; // } // // public String getText() { // // return text; // } // // public String getWoeid() { // return woeid; // } // // public String getSunset() { // return sunset; // } // // public String getSunrise() { // return sunrise; // } // } // Path: app/src/main/java/com/kuahusg/weather/data/IDataSource.java import com.kuahusg.weather.data.callback.RequestCityCallback; import com.kuahusg.weather.data.callback.RequestCityResultCallback; import com.kuahusg.weather.data.callback.RequestWeatherCallback; import com.kuahusg.weather.model.bean.Forecast; import com.kuahusg.weather.model.bean.ForecastInfo; import java.util.List; package com.kuahusg.weather.data; /** * Created by kuahusg on 16-9-28. */ public interface IDataSource { void queryWeather(String woeid, RequestWeatherCallback callback); void queryWeather(RequestWeatherCallback callback); void saveWeather(List<Forecast> forecastList, ForecastInfo info); void loadAllCity(RequestCityCallback cityCallback); void saveAllCity(List<String> cityList);
void queryCity(RequestCityResultCallback callback, String cityName);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/ISelectLocationView.java
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/City.java // public class City implements Serializable{ // private String city_name; // private String woeid; // private String fullNmae; // // public City(String city_name, String woeid, String fullNmae) { // this.city_name = city_name; // this.woeid = woeid; // this.fullNmae = fullNmae; // } // // public String getCity_name() { // return city_name; // } // // public String getWoeid() { // return woeid; // } // // public String getFullNmae() { // return fullNmae; // } // }
import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.City; import java.util.List;
package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-27. */ public interface ISelectLocationView extends IBaseView { @Override void start(); @Override void finish(); @Override void init(); @Override void error(String message); void queryCityError(String message);
// Path: app/src/main/java/com/kuahusg/weather/UI/base/IBaseView.java // public interface IBaseView { // void init(); // // void start(); // // void error(String message); // // void finish(); // } // // Path: app/src/main/java/com/kuahusg/weather/model/bean/City.java // public class City implements Serializable{ // private String city_name; // private String woeid; // private String fullNmae; // // public City(String city_name, String woeid, String fullNmae) { // this.city_name = city_name; // this.woeid = woeid; // this.fullNmae = fullNmae; // } // // public String getCity_name() { // return city_name; // } // // public String getWoeid() { // return woeid; // } // // public String getFullNmae() { // return fullNmae; // } // } // Path: app/src/main/java/com/kuahusg/weather/UI/interfaceOfView/ISelectLocationView.java import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.model.bean.City; import java.util.List; package com.kuahusg.weather.UI.interfaceOfView; /** * Created by kuahusg on 16-9-27. */ public interface ISelectLocationView extends IBaseView { @Override void start(); @Override void finish(); @Override void init(); @Override void error(String message); void queryCityError(String message);
void finishQueryCity(List<City> list);
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/UI/Widget/BackgroundPictureView.java
// Path: app/src/main/java/com/kuahusg/weather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2; // public static final int INFO = 3; // public static final int WARN = 4; // public static final int ERROR = 5; // public static final int NOTHING = 6; // public static final int LEVEL_NOW = VERBOSE; // // public static void v(String tag, String msg) { // // if (LEVEL_NOW <= VERBOSE) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (LEVEL_NOW <= DEBUG) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (LEVEL_NOW <= INFO) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (LEVEL_NOW <= WARN) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (LEVEL_NOW <= ERROR) { // Log.e(tag, msg); // } // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.kuahusg.weather.R; import com.kuahusg.weather.util.LogUtil;
package com.kuahusg.weather.UI.Widget; /** * Created by kuahusg on 16-6-29. * com.kuahusg.weather.UI */ public class BackgroundPictureView extends LinearLayout implements View.OnClickListener { // TODO: 16-10-12 这个View应该添加更多其他控件,并设计成可复用 LinearLayout container; Context mContext; ImageView imageView; OnBackgroundPicClickListener listener; public BackgroundPictureView(Context context) { super(context); init(context); } public BackgroundPictureView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public BackgroundPictureView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { mContext = context; container = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.include_background_picture, null); // TODO: 16-10-12 null? imageView = (ImageView) container.findViewById(R.id.back_pic); addView(container); imageView.setOnClickListener(this); } @Override public void onClick(View v) {
// Path: app/src/main/java/com/kuahusg/weather/util/LogUtil.java // public class LogUtil { // public static final int VERBOSE = 1; // public static final int DEBUG = 2; // public static final int INFO = 3; // public static final int WARN = 4; // public static final int ERROR = 5; // public static final int NOTHING = 6; // public static final int LEVEL_NOW = VERBOSE; // // public static void v(String tag, String msg) { // // if (LEVEL_NOW <= VERBOSE) { // Log.v(tag, msg); // } // } // // public static void d(String tag, String msg) { // if (LEVEL_NOW <= DEBUG) { // Log.d(tag, msg); // } // } // // public static void i(String tag, String msg) { // if (LEVEL_NOW <= INFO) { // Log.i(tag, msg); // } // } // // public static void w(String tag, String msg) { // if (LEVEL_NOW <= WARN) { // Log.w(tag, msg); // } // } // // public static void e(String tag, String msg) { // if (LEVEL_NOW <= ERROR) { // Log.e(tag, msg); // } // } // } // Path: app/src/main/java/com/kuahusg/weather/UI/Widget/BackgroundPictureView.java import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.kuahusg.weather.R; import com.kuahusg.weather.util.LogUtil; package com.kuahusg.weather.UI.Widget; /** * Created by kuahusg on 16-6-29. * com.kuahusg.weather.UI */ public class BackgroundPictureView extends LinearLayout implements View.OnClickListener { // TODO: 16-10-12 这个View应该添加更多其他控件,并设计成可复用 LinearLayout container; Context mContext; ImageView imageView; OnBackgroundPicClickListener listener; public BackgroundPictureView(Context context) { super(context); init(context); } public BackgroundPictureView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public BackgroundPictureView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { mContext = context; container = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.include_background_picture, null); // TODO: 16-10-12 null? imageView = (ImageView) container.findViewById(R.id.back_pic); addView(container); imageView.setOnClickListener(this); } @Override public void onClick(View v) {
LogUtil.v(this.toString(),"onClick()");
ivargrimstad/snoopee
snoopee-config/snoopee-config-service/src/main/java/eu/agilejava/snoopee/config/ApplicationConfig.java
// Path: snoopee-config/snoopee-config-service/src/main/java/eu/agilejava/snoopee/config/api/ConfigurationsResource.java // @Path("services") // public class ConfigurationsResource { // // @GET // @Path("{serviceName}/configurations") // @Produces(MediaType.APPLICATION_JSON) // public Response getConfigurationsForService(@PathParam("serviceName") String serviceName) { // // List<Configuration> configurations = new ArrayList<>(); // configurations.add(new Configuration("message", "Duke")); // // return Response.ok(new GenericEntity<List<Configuration>>(configurations) {}).build(); // } // }
import eu.agilejava.snoopee.annotation.EnableSnoopEEClient; import eu.agilejava.snoopee.config.api.ConfigurationsResource; import java.util.HashSet; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application;
/* * The MIT License * * Copyright 2017 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.config; /** * * @author Ivar Grimstad ([email protected]) */ @EnableSnoopEEClient(serviceName = "snoopee-config") @ApplicationPath("api") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new HashSet<>();
// Path: snoopee-config/snoopee-config-service/src/main/java/eu/agilejava/snoopee/config/api/ConfigurationsResource.java // @Path("services") // public class ConfigurationsResource { // // @GET // @Path("{serviceName}/configurations") // @Produces(MediaType.APPLICATION_JSON) // public Response getConfigurationsForService(@PathParam("serviceName") String serviceName) { // // List<Configuration> configurations = new ArrayList<>(); // configurations.add(new Configuration("message", "Duke")); // // return Response.ok(new GenericEntity<List<Configuration>>(configurations) {}).build(); // } // } // Path: snoopee-config/snoopee-config-service/src/main/java/eu/agilejava/snoopee/config/ApplicationConfig.java import eu.agilejava.snoopee.annotation.EnableSnoopEEClient; import eu.agilejava.snoopee.config.api.ConfigurationsResource; import java.util.HashSet; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /* * The MIT License * * Copyright 2017 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.config; /** * * @author Ivar Grimstad ([email protected]) */ @EnableSnoopEEClient(serviceName = "snoopee-config") @ApplicationPath("api") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new HashSet<>();
resources.add(ConfigurationsResource.class);
ivargrimstad/snoopee
snoopee-discovery/snoopee/src/main/java/eu/agilejava/snoopee/scan/SnoopEERegistrationClient.java
// Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEExtensionHelper.java // public final class SnoopEEExtensionHelper { // // private String serviceName; // private boolean snoopEnabled; // // private static final SnoopEEExtensionHelper INSTANCE = new SnoopEEExtensionHelper(); // // public static String getServiceName() { // return INSTANCE.serviceName; // } // // public static void setServiceName(String serviceName) { // INSTANCE.serviceName = serviceName; // } // // public static boolean isSnoopEnabled() { // return INSTANCE.snoopEnabled; // } // // public static void setSnoopEnabled(final boolean snoopEnabled) { // INSTANCE.snoopEnabled = snoopEnabled; // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEConfigurationException.java // public class SnoopEEConfigurationException extends RuntimeException { // // public SnoopEEConfigurationException(String message) { // super(message); // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/client/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // }
import eu.agilejava.snoopee.SnoopEEExtensionHelper; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException; import eu.agilejava.snoopee.SnoopEEConfigurationException; import eu.agilejava.snoopee.client.SnoopEEConfig; import java.io.IOException; import java.net.URI; import java.util.Calendar; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.scan; /** * Registers with SnoopEE and gives heartbeats every 10 second. * * @author Ivar Grimstad ([email protected]) */ @ClientEndpoint @Singleton @Startup public class SnoopEERegistrationClient { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); private static final String REGISTER_ENDPOINT = "snoopee"; private static final String STATUS_ENDPOINT = "snoopeestatus/"; private String serviceUrl;
// Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEExtensionHelper.java // public final class SnoopEEExtensionHelper { // // private String serviceName; // private boolean snoopEnabled; // // private static final SnoopEEExtensionHelper INSTANCE = new SnoopEEExtensionHelper(); // // public static String getServiceName() { // return INSTANCE.serviceName; // } // // public static void setServiceName(String serviceName) { // INSTANCE.serviceName = serviceName; // } // // public static boolean isSnoopEnabled() { // return INSTANCE.snoopEnabled; // } // // public static void setSnoopEnabled(final boolean snoopEnabled) { // INSTANCE.snoopEnabled = snoopEnabled; // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEConfigurationException.java // public class SnoopEEConfigurationException extends RuntimeException { // // public SnoopEEConfigurationException(String message) { // super(message); // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/client/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // } // Path: snoopee-discovery/snoopee/src/main/java/eu/agilejava/snoopee/scan/SnoopEERegistrationClient.java import eu.agilejava.snoopee.SnoopEEExtensionHelper; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException; import eu.agilejava.snoopee.SnoopEEConfigurationException; import eu.agilejava.snoopee.client.SnoopEEConfig; import java.io.IOException; import java.net.URI; import java.util.Calendar; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.scan; /** * Registers with SnoopEE and gives heartbeats every 10 second. * * @author Ivar Grimstad ([email protected]) */ @ClientEndpoint @Singleton @Startup public class SnoopEERegistrationClient { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); private static final String REGISTER_ENDPOINT = "snoopee"; private static final String STATUS_ENDPOINT = "snoopeestatus/"; private String serviceUrl;
private final SnoopEEConfig applicationConfig = new SnoopEEConfig();
ivargrimstad/snoopee
snoopee-discovery/snoopee/src/main/java/eu/agilejava/snoopee/scan/SnoopEERegistrationClient.java
// Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEExtensionHelper.java // public final class SnoopEEExtensionHelper { // // private String serviceName; // private boolean snoopEnabled; // // private static final SnoopEEExtensionHelper INSTANCE = new SnoopEEExtensionHelper(); // // public static String getServiceName() { // return INSTANCE.serviceName; // } // // public static void setServiceName(String serviceName) { // INSTANCE.serviceName = serviceName; // } // // public static boolean isSnoopEnabled() { // return INSTANCE.snoopEnabled; // } // // public static void setSnoopEnabled(final boolean snoopEnabled) { // INSTANCE.snoopEnabled = snoopEnabled; // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEConfigurationException.java // public class SnoopEEConfigurationException extends RuntimeException { // // public SnoopEEConfigurationException(String message) { // super(message); // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/client/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // }
import eu.agilejava.snoopee.SnoopEEExtensionHelper; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException; import eu.agilejava.snoopee.SnoopEEConfigurationException; import eu.agilejava.snoopee.client.SnoopEEConfig; import java.io.IOException; import java.net.URI; import java.util.Calendar; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.scan; /** * Registers with SnoopEE and gives heartbeats every 10 second. * * @author Ivar Grimstad ([email protected]) */ @ClientEndpoint @Singleton @Startup public class SnoopEERegistrationClient { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); private static final String REGISTER_ENDPOINT = "snoopee"; private static final String STATUS_ENDPOINT = "snoopeestatus/"; private String serviceUrl; private final SnoopEEConfig applicationConfig = new SnoopEEConfig(); @Resource private TimerService timerService; @PostConstruct private void init() { LOGGER.config("Checking if SnoopEE is enabled");
// Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEExtensionHelper.java // public final class SnoopEEExtensionHelper { // // private String serviceName; // private boolean snoopEnabled; // // private static final SnoopEEExtensionHelper INSTANCE = new SnoopEEExtensionHelper(); // // public static String getServiceName() { // return INSTANCE.serviceName; // } // // public static void setServiceName(String serviceName) { // INSTANCE.serviceName = serviceName; // } // // public static boolean isSnoopEnabled() { // return INSTANCE.snoopEnabled; // } // // public static void setSnoopEnabled(final boolean snoopEnabled) { // INSTANCE.snoopEnabled = snoopEnabled; // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEConfigurationException.java // public class SnoopEEConfigurationException extends RuntimeException { // // public SnoopEEConfigurationException(String message) { // super(message); // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/client/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // } // Path: snoopee-discovery/snoopee/src/main/java/eu/agilejava/snoopee/scan/SnoopEERegistrationClient.java import eu.agilejava.snoopee.SnoopEEExtensionHelper; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException; import eu.agilejava.snoopee.SnoopEEConfigurationException; import eu.agilejava.snoopee.client.SnoopEEConfig; import java.io.IOException; import java.net.URI; import java.util.Calendar; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.scan; /** * Registers with SnoopEE and gives heartbeats every 10 second. * * @author Ivar Grimstad ([email protected]) */ @ClientEndpoint @Singleton @Startup public class SnoopEERegistrationClient { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); private static final String REGISTER_ENDPOINT = "snoopee"; private static final String STATUS_ENDPOINT = "snoopeestatus/"; private String serviceUrl; private final SnoopEEConfig applicationConfig = new SnoopEEConfig(); @Resource private TimerService timerService; @PostConstruct private void init() { LOGGER.config("Checking if SnoopEE is enabled");
if (SnoopEEExtensionHelper.isSnoopEnabled()) {
ivargrimstad/snoopee
snoopee-discovery/snoopee/src/main/java/eu/agilejava/snoopee/scan/SnoopEERegistrationClient.java
// Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEExtensionHelper.java // public final class SnoopEEExtensionHelper { // // private String serviceName; // private boolean snoopEnabled; // // private static final SnoopEEExtensionHelper INSTANCE = new SnoopEEExtensionHelper(); // // public static String getServiceName() { // return INSTANCE.serviceName; // } // // public static void setServiceName(String serviceName) { // INSTANCE.serviceName = serviceName; // } // // public static boolean isSnoopEnabled() { // return INSTANCE.snoopEnabled; // } // // public static void setSnoopEnabled(final boolean snoopEnabled) { // INSTANCE.snoopEnabled = snoopEnabled; // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEConfigurationException.java // public class SnoopEEConfigurationException extends RuntimeException { // // public SnoopEEConfigurationException(String message) { // super(message); // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/client/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // }
import eu.agilejava.snoopee.SnoopEEExtensionHelper; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException; import eu.agilejava.snoopee.SnoopEEConfigurationException; import eu.agilejava.snoopee.client.SnoopEEConfig; import java.io.IOException; import java.net.URI; import java.util.Calendar; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.scan; /** * Registers with SnoopEE and gives heartbeats every 10 second. * * @author Ivar Grimstad ([email protected]) */ @ClientEndpoint @Singleton @Startup public class SnoopEERegistrationClient { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); private static final String REGISTER_ENDPOINT = "snoopee"; private static final String STATUS_ENDPOINT = "snoopeestatus/"; private String serviceUrl; private final SnoopEEConfig applicationConfig = new SnoopEEConfig(); @Resource private TimerService timerService; @PostConstruct private void init() { LOGGER.config("Checking if SnoopEE is enabled"); if (SnoopEEExtensionHelper.isSnoopEnabled()) { try { readConfiguration(); LOGGER.config(() -> "Registering " + applicationConfig.getServiceName()); register(applicationConfig.getServiceName());
// Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEExtensionHelper.java // public final class SnoopEEExtensionHelper { // // private String serviceName; // private boolean snoopEnabled; // // private static final SnoopEEExtensionHelper INSTANCE = new SnoopEEExtensionHelper(); // // public static String getServiceName() { // return INSTANCE.serviceName; // } // // public static void setServiceName(String serviceName) { // INSTANCE.serviceName = serviceName; // } // // public static boolean isSnoopEnabled() { // return INSTANCE.snoopEnabled; // } // // public static void setSnoopEnabled(final boolean snoopEnabled) { // INSTANCE.snoopEnabled = snoopEnabled; // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/SnoopEEConfigurationException.java // public class SnoopEEConfigurationException extends RuntimeException { // // public SnoopEEConfigurationException(String message) { // super(message); // } // } // // Path: snoopee-discovery/snoopee-client/src/main/java/eu/agilejava/snoopee/client/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // } // Path: snoopee-discovery/snoopee/src/main/java/eu/agilejava/snoopee/scan/SnoopEERegistrationClient.java import eu.agilejava.snoopee.SnoopEEExtensionHelper; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.YAMLException; import eu.agilejava.snoopee.SnoopEEConfigurationException; import eu.agilejava.snoopee.client.SnoopEEConfig; import java.io.IOException; import java.net.URI; import java.util.Calendar; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.ScheduleExpression; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.scan; /** * Registers with SnoopEE and gives heartbeats every 10 second. * * @author Ivar Grimstad ([email protected]) */ @ClientEndpoint @Singleton @Startup public class SnoopEERegistrationClient { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); private static final String REGISTER_ENDPOINT = "snoopee"; private static final String STATUS_ENDPOINT = "snoopeestatus/"; private String serviceUrl; private final SnoopEEConfig applicationConfig = new SnoopEEConfig(); @Resource private TimerService timerService; @PostConstruct private void init() { LOGGER.config("Checking if SnoopEE is enabled"); if (SnoopEEExtensionHelper.isSnoopEnabled()) { try { readConfiguration(); LOGGER.config(() -> "Registering " + applicationConfig.getServiceName()); register(applicationConfig.getServiceName());
} catch (SnoopEEConfigurationException e) {
ivargrimstad/snoopee
snoopee-config/snoopee-config-service/src/main/java/eu/agilejava/snoopee/config/api/ConfigurationsResource.java
// Path: snoopee-config/snoopee-config-client/src/main/java/eu/agilejava/snoopee/config/Configuration.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Configuration { // // private String key; // private String value; // // Configuration() { // } // // public Configuration(final String key, final String value) { // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // // public String getValue() { // return value; // } // // @Override // public int hashCode() { // int hash = 7; // hash = 79 * hash + Objects.hashCode(this.key); // hash = 79 * hash + Objects.hashCode(this.value); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Configuration other = (Configuration) obj; // if (!Objects.equals(this.key, other.key)) { // return false; // } // if (!Objects.equals(this.value, other.value)) { // return false; // } // return true; // } // // @Override // public String toString() { // return "Configuration{" + "key=" + key + ", value=" + value + '}'; // } // }
import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import eu.agilejava.snoopee.config.Configuration; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces;
/* * The MIT License * * Copyright 2017 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.config.api; /** * * @author Ivar Grimstad ([email protected]) */ @Path("services") public class ConfigurationsResource { @GET @Path("{serviceName}/configurations") @Produces(MediaType.APPLICATION_JSON) public Response getConfigurationsForService(@PathParam("serviceName") String serviceName) {
// Path: snoopee-config/snoopee-config-client/src/main/java/eu/agilejava/snoopee/config/Configuration.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Configuration { // // private String key; // private String value; // // Configuration() { // } // // public Configuration(final String key, final String value) { // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // // public String getValue() { // return value; // } // // @Override // public int hashCode() { // int hash = 7; // hash = 79 * hash + Objects.hashCode(this.key); // hash = 79 * hash + Objects.hashCode(this.value); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Configuration other = (Configuration) obj; // if (!Objects.equals(this.key, other.key)) { // return false; // } // if (!Objects.equals(this.value, other.value)) { // return false; // } // return true; // } // // @Override // public String toString() { // return "Configuration{" + "key=" + key + ", value=" + value + '}'; // } // } // Path: snoopee-config/snoopee-config-service/src/main/java/eu/agilejava/snoopee/config/api/ConfigurationsResource.java import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import eu.agilejava.snoopee.config.Configuration; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; /* * The MIT License * * Copyright 2017 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.config.api; /** * * @author Ivar Grimstad ([email protected]) */ @Path("services") public class ConfigurationsResource { @GET @Path("{serviceName}/configurations") @Produces(MediaType.APPLICATION_JSON) public Response getConfigurationsForService(@PathParam("serviceName") String serviceName) {
List<Configuration> configurations = new ArrayList<>();
ivargrimstad/snoopee
snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEStatusEndpoint.java
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // }
import static eu.agilejava.snoopee.SnoopEEConfig.fromJSON; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.websocket.OnMessage; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee; /** * WebSocket endpoint for heartbeats. * * @author Ivar Grimstad ([email protected]) */ @ServerEndpoint("/snoopeestatus/{clientId}") @Stateless public class SnoopEEStatusEndpoint { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); @EJB private SnoopEEClientRegistry clients; /** * Heartbeat endpoint. * Registers that the client is still there and updates configuration * if changed. * * @param clientId The client id * @param applicationConfig The updated configuration */ @OnMessage public void onMessage(@PathParam("clientId") String clientId, String applicationConfig) { LOGGER.config(() -> "Client: " + clientId + ", status: " + applicationConfig); if (applicationConfig != null && !applicationConfig.isEmpty()) {
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEStatusEndpoint.java import static eu.agilejava.snoopee.SnoopEEConfig.fromJSON; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.websocket.OnMessage; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee; /** * WebSocket endpoint for heartbeats. * * @author Ivar Grimstad ([email protected]) */ @ServerEndpoint("/snoopeestatus/{clientId}") @Stateless public class SnoopEEStatusEndpoint { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); @EJB private SnoopEEClientRegistry clients; /** * Heartbeat endpoint. * Registers that the client is still there and updates configuration * if changed. * * @param clientId The client id * @param applicationConfig The updated configuration */ @OnMessage public void onMessage(@PathParam("clientId") String clientId, String applicationConfig) { LOGGER.config(() -> "Client: " + clientId + ", status: " + applicationConfig); if (applicationConfig != null && !applicationConfig.isEmpty()) {
clients.register(fromJSON(applicationConfig));
ivargrimstad/snoopee
snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/ui/SnoopController.java
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEClientRegistry.java // @Singleton // public class SnoopEEClientRegistry { // // private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); // // private final Map<String, Long> clients = new ConcurrentHashMap<>(); // private final Map<String, SnoopEEConfig> clientConfigurations = new ConcurrentHashMap<>(); // // public void register(final SnoopEEConfig client) { // Calendar now = getInstance(); // clients.put(client.getServiceName(), now.getTimeInMillis()); // clientConfigurations.put(client.getServiceName(), client); // // LOGGER.config(() -> "Client: " + client.getServiceName() + " registered up at " + now.getTime()); // } // // public void deRegister(final String clientId) { // clients.remove(clientId); // clientConfigurations.remove(clientId); // // LOGGER.warning(() -> "Client: " + clientId + " deregistered at " + Calendar.getInstance().getTime()); // } // // public Set<String> getClients() { // // return clients.keySet().stream() // .filter(c -> clients.get(c) > System.currentTimeMillis() - 60000) // .collect(Collectors.toSet()); // } // // public Collection<SnoopEEConfig> getServiceConfigs() { // return clientConfigurations.values(); // } // // public Optional<SnoopEEConfig> getClientConfig(String clientId) { // // if (getClients().contains(clientId)) { // // return Optional.ofNullable(clientConfigurations.get(clientId)); // // } else { // return Optional.empty(); // } // } // } // // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // }
import javax.inject.Named; import eu.agilejava.snoopee.SnoopEEClientRegistry; import eu.agilejava.snoopee.SnoopEEConfig; import java.util.Collection; import java.util.Set; import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.ui; /** * Controller for the SnoopEE service UI. * * @author Ivar Grimstad ([email protected]) */ @Named @RequestScoped public class SnoopController { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); @EJB
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEClientRegistry.java // @Singleton // public class SnoopEEClientRegistry { // // private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); // // private final Map<String, Long> clients = new ConcurrentHashMap<>(); // private final Map<String, SnoopEEConfig> clientConfigurations = new ConcurrentHashMap<>(); // // public void register(final SnoopEEConfig client) { // Calendar now = getInstance(); // clients.put(client.getServiceName(), now.getTimeInMillis()); // clientConfigurations.put(client.getServiceName(), client); // // LOGGER.config(() -> "Client: " + client.getServiceName() + " registered up at " + now.getTime()); // } // // public void deRegister(final String clientId) { // clients.remove(clientId); // clientConfigurations.remove(clientId); // // LOGGER.warning(() -> "Client: " + clientId + " deregistered at " + Calendar.getInstance().getTime()); // } // // public Set<String> getClients() { // // return clients.keySet().stream() // .filter(c -> clients.get(c) > System.currentTimeMillis() - 60000) // .collect(Collectors.toSet()); // } // // public Collection<SnoopEEConfig> getServiceConfigs() { // return clientConfigurations.values(); // } // // public Optional<SnoopEEConfig> getClientConfig(String clientId) { // // if (getClients().contains(clientId)) { // // return Optional.ofNullable(clientConfigurations.get(clientId)); // // } else { // return Optional.empty(); // } // } // } // // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // } // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/ui/SnoopController.java import javax.inject.Named; import eu.agilejava.snoopee.SnoopEEClientRegistry; import eu.agilejava.snoopee.SnoopEEConfig; import java.util.Collection; import java.util.Set; import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.ui; /** * Controller for the SnoopEE service UI. * * @author Ivar Grimstad ([email protected]) */ @Named @RequestScoped public class SnoopController { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); @EJB
private SnoopEEClientRegistry clients;
ivargrimstad/snoopee
snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/ui/SnoopController.java
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEClientRegistry.java // @Singleton // public class SnoopEEClientRegistry { // // private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); // // private final Map<String, Long> clients = new ConcurrentHashMap<>(); // private final Map<String, SnoopEEConfig> clientConfigurations = new ConcurrentHashMap<>(); // // public void register(final SnoopEEConfig client) { // Calendar now = getInstance(); // clients.put(client.getServiceName(), now.getTimeInMillis()); // clientConfigurations.put(client.getServiceName(), client); // // LOGGER.config(() -> "Client: " + client.getServiceName() + " registered up at " + now.getTime()); // } // // public void deRegister(final String clientId) { // clients.remove(clientId); // clientConfigurations.remove(clientId); // // LOGGER.warning(() -> "Client: " + clientId + " deregistered at " + Calendar.getInstance().getTime()); // } // // public Set<String> getClients() { // // return clients.keySet().stream() // .filter(c -> clients.get(c) > System.currentTimeMillis() - 60000) // .collect(Collectors.toSet()); // } // // public Collection<SnoopEEConfig> getServiceConfigs() { // return clientConfigurations.values(); // } // // public Optional<SnoopEEConfig> getClientConfig(String clientId) { // // if (getClients().contains(clientId)) { // // return Optional.ofNullable(clientConfigurations.get(clientId)); // // } else { // return Optional.empty(); // } // } // } // // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // }
import javax.inject.Named; import eu.agilejava.snoopee.SnoopEEClientRegistry; import eu.agilejava.snoopee.SnoopEEConfig; import java.util.Collection; import java.util.Set; import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.ui; /** * Controller for the SnoopEE service UI. * * @author Ivar Grimstad ([email protected]) */ @Named @RequestScoped public class SnoopController { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); @EJB private SnoopEEClientRegistry clients; public Set<String> getClients() { return clients.getClients(); }
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEClientRegistry.java // @Singleton // public class SnoopEEClientRegistry { // // private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); // // private final Map<String, Long> clients = new ConcurrentHashMap<>(); // private final Map<String, SnoopEEConfig> clientConfigurations = new ConcurrentHashMap<>(); // // public void register(final SnoopEEConfig client) { // Calendar now = getInstance(); // clients.put(client.getServiceName(), now.getTimeInMillis()); // clientConfigurations.put(client.getServiceName(), client); // // LOGGER.config(() -> "Client: " + client.getServiceName() + " registered up at " + now.getTime()); // } // // public void deRegister(final String clientId) { // clients.remove(clientId); // clientConfigurations.remove(clientId); // // LOGGER.warning(() -> "Client: " + clientId + " deregistered at " + Calendar.getInstance().getTime()); // } // // public Set<String> getClients() { // // return clients.keySet().stream() // .filter(c -> clients.get(c) > System.currentTimeMillis() - 60000) // .collect(Collectors.toSet()); // } // // public Collection<SnoopEEConfig> getServiceConfigs() { // return clientConfigurations.values(); // } // // public Optional<SnoopEEConfig> getClientConfig(String clientId) { // // if (getClients().contains(clientId)) { // // return Optional.ofNullable(clientConfigurations.get(clientId)); // // } else { // return Optional.empty(); // } // } // } // // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // } // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/ui/SnoopController.java import javax.inject.Named; import eu.agilejava.snoopee.SnoopEEClientRegistry; import eu.agilejava.snoopee.SnoopEEConfig; import java.util.Collection; import java.util.Set; import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.ui; /** * Controller for the SnoopEE service UI. * * @author Ivar Grimstad ([email protected]) */ @Named @RequestScoped public class SnoopController { private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); @EJB private SnoopEEClientRegistry clients; public Set<String> getClients() { return clients.getClients(); }
public Collection<SnoopEEConfig> getClientConfigurations() {
ivargrimstad/snoopee
snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/api/ServicesResource.java
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEClientRegistry.java // @Singleton // public class SnoopEEClientRegistry { // // private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); // // private final Map<String, Long> clients = new ConcurrentHashMap<>(); // private final Map<String, SnoopEEConfig> clientConfigurations = new ConcurrentHashMap<>(); // // public void register(final SnoopEEConfig client) { // Calendar now = getInstance(); // clients.put(client.getServiceName(), now.getTimeInMillis()); // clientConfigurations.put(client.getServiceName(), client); // // LOGGER.config(() -> "Client: " + client.getServiceName() + " registered up at " + now.getTime()); // } // // public void deRegister(final String clientId) { // clients.remove(clientId); // clientConfigurations.remove(clientId); // // LOGGER.warning(() -> "Client: " + clientId + " deregistered at " + Calendar.getInstance().getTime()); // } // // public Set<String> getClients() { // // return clients.keySet().stream() // .filter(c -> clients.get(c) > System.currentTimeMillis() - 60000) // .collect(Collectors.toSet()); // } // // public Collection<SnoopEEConfig> getServiceConfigs() { // return clientConfigurations.values(); // } // // public Optional<SnoopEEConfig> getClientConfig(String clientId) { // // if (getClients().contains(clientId)) { // // return Optional.ofNullable(clientConfigurations.get(clientId)); // // } else { // return Optional.empty(); // } // } // } // // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // }
import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import eu.agilejava.snoopee.SnoopEEClientRegistry; import eu.agilejava.snoopee.SnoopEEConfig; import java.util.Collection; import javax.ejb.EJB; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException;
/* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.api; /** * * @author Ivar Grimstad ([email protected]) */ @Path("services") public class ServicesResource { @Context private UriInfo uriInfo; @EJB
// Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEClientRegistry.java // @Singleton // public class SnoopEEClientRegistry { // // private static final Logger LOGGER = Logger.getLogger("eu.agilejava.snoopee"); // // private final Map<String, Long> clients = new ConcurrentHashMap<>(); // private final Map<String, SnoopEEConfig> clientConfigurations = new ConcurrentHashMap<>(); // // public void register(final SnoopEEConfig client) { // Calendar now = getInstance(); // clients.put(client.getServiceName(), now.getTimeInMillis()); // clientConfigurations.put(client.getServiceName(), client); // // LOGGER.config(() -> "Client: " + client.getServiceName() + " registered up at " + now.getTime()); // } // // public void deRegister(final String clientId) { // clients.remove(clientId); // clientConfigurations.remove(clientId); // // LOGGER.warning(() -> "Client: " + clientId + " deregistered at " + Calendar.getInstance().getTime()); // } // // public Set<String> getClients() { // // return clients.keySet().stream() // .filter(c -> clients.get(c) > System.currentTimeMillis() - 60000) // .collect(Collectors.toSet()); // } // // public Collection<SnoopEEConfig> getServiceConfigs() { // return clientConfigurations.values(); // } // // public Optional<SnoopEEConfig> getClientConfig(String clientId) { // // if (getClients().contains(clientId)) { // // return Optional.ofNullable(clientConfigurations.get(clientId)); // // } else { // return Optional.empty(); // } // } // } // // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/SnoopEEConfig.java // public class SnoopEEConfig { // // private String serviceName; // private String serviceHome; // private String serviceRoot; // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // public String getServiceHome() { // return serviceHome; // } // // public void setServiceHome(String serviceHome) { // this.serviceHome = serviceHome; // } // // public String getServiceRoot() { // return serviceRoot; // } // // public void setServiceRoot(String serviceRoot) { // this.serviceRoot = serviceRoot; // } // // public String toJSON() { // // Writer w = new StringWriter(); // try (JsonGenerator generator = Json.createGenerator(w)) { // // generator.writeStartObject() // .write("serviceName", serviceName) // .write("serviceHome", serviceHome) // .write("serviceRoot", serviceRoot) // .writeEnd(); // } // // return w.toString(); // } // // public static SnoopEEConfig fromJSON(String json) { // // SnoopEEConfig config = new SnoopEEConfig(); // // try (JsonReader reader = Json.createReader(new StringReader(json))) { // // JsonObject configJson = reader.readObject(); // // config.setServiceName(configJson.getString("serviceName")); // config.setServiceHome(configJson.getString("serviceHome")); // config.setServiceRoot(configJson.getString("serviceRoot")); // } // // return config; // } // } // Path: snoopee-discovery/snoopee-service/src/main/java/eu/agilejava/snoopee/api/ServicesResource.java import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import eu.agilejava.snoopee.SnoopEEClientRegistry; import eu.agilejava.snoopee.SnoopEEConfig; import java.util.Collection; import javax.ejb.EJB; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; /* * The MIT License * * Copyright 2015 Ivar Grimstad ([email protected]). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.agilejava.snoopee.api; /** * * @author Ivar Grimstad ([email protected]) */ @Path("services") public class ServicesResource { @Context private UriInfo uriInfo; @EJB
private SnoopEEClientRegistry snoopeeClientRegistry;