code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.controllers;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.ttrssreader.R;
import org.ttrssreader.model.pojos.Article;
import org.ttrssreader.model.pojos.Category;
import org.ttrssreader.model.pojos.Feed;
import org.ttrssreader.model.pojos.Label;
import org.ttrssreader.net.IArticleOmitter;
import org.ttrssreader.net.IdUpdatedArticleOmitter;
import org.ttrssreader.net.JSONConnector;
import org.ttrssreader.net.StopJsonParsingException;
import org.ttrssreader.utils.Utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
@SuppressLint("UseSparseArrays")
public class Data {
protected static final String TAG = Data.class.getSimpleName();
/** uncategorized */
public static final int VCAT_UNCAT = 0;
/** starred */
public static final int VCAT_STAR = -1;
/** published */
public static final int VCAT_PUB = -2;
/** fresh */
public static final int VCAT_FRESH = -3;
/** all articles */
public static final int VCAT_ALL = -4;
/** read articles */
public static final int VCAT_READ = -6;
public static final int TIME_CATEGORY = 1;
public static final int TIME_FEED = 2;
public static final int TIME_FEEDHEADLINE = 3;
private static final String VIEW_ALL = "all_articles";
private static final String VIEW_UNREAD = "unread";
private Context context;
private long time = 0;
private long articlesCached;
private Map<Integer, Long> articlesChanged = new HashMap<Integer, Long>();
/** map of category id to last changed time */
private Map<Integer, Long> feedsChanged = new HashMap<Integer, Long>();
private long virtCategoriesChanged = 0;
private long categoriesChanged = 0;
private ConnectivityManager cm;
// Singleton (see http://stackoverflow.com/a/11165926)
private Data() {
}
private static class InstanceHolder {
private static final Data instance = new Data();
}
public static Data getInstance() {
return InstanceHolder.instance;
}
public synchronized void checkAndInitializeData(final Context context) {
this.context = context;
if (context != null)
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
// *** ARTICLES *********************************************************************
/**
* cache all articles
*
* @param overrideOffline
* do not check connected state
* @param overrideDelay
* if set to {@code true} enforces the update,
* otherwise the time from last update will be
* considered
*/
public void cacheArticles(boolean overrideOffline, boolean overrideDelay) {
int limit = 400;
if (Controller.getInstance().isLowMemory())
limit = limit / 2;
if (!overrideDelay && (time > (System.currentTimeMillis() - Utils.UPDATE_TIME))) {
return;
} else if (!Utils.isConnected(cm) && !(overrideOffline && Utils.checkConnected(cm))) {
return;
}
Set<Article> articles = new HashSet<Article>();
int sinceId = Controller.getInstance().getSinceId();
IdUpdatedArticleOmitter unreadUpdatedFilter = new IdUpdatedArticleOmitter("isUnread>0", null);
Controller
.getInstance()
.getConnector()
.getHeadlines(articles, VCAT_ALL, limit, VIEW_UNREAD, true, 0, null, null,
unreadUpdatedFilter.getIdUpdatedMap().isEmpty() ? null : unreadUpdatedFilter);
final Article newestCachedArticle = DBHelper.getInstance().getArticle(sinceId);
IArticleOmitter updatedFilter = (newestCachedArticle == null) ? null : new IArticleOmitter() {
public Date lastUpdated = newestCachedArticle.updated;
@Override
public boolean omitArticle(Article.ArticleField field, Article a) throws StopJsonParsingException {
boolean skip = false;
switch (field) {
case unread:
if (a.isUnread)
skip = true;
break;
case updated:
if (a.updated != null && lastUpdated.after(a.updated))
throw new StopJsonParsingException("Stop processing on article ID=" + a.id + " updated on "
+ lastUpdated);
default:
break;
}
return skip;
}
};
Controller.getInstance().getConnector()
.getHeadlines(articles, VCAT_ALL, limit, VIEW_ALL, true, sinceId, null, null, updatedFilter);
handleInsertArticles(articles, true);
// Only mark as updated if the calls were successful
if (!articles.isEmpty() || !unreadUpdatedFilter.getOmittedArticles().isEmpty()) {
time = System.currentTimeMillis();
notifyListeners();
// Store all category-ids and ids of all feeds for this category in db
articlesCached = time;
for (Category c : DBHelper.getInstance().getAllCategories()) {
feedsChanged.put(c.id, time);
}
Set<Integer> articleUnreadIds = new HashSet<Integer>();
for (Article a : articles) {
if (a.isUnread) {
articleUnreadIds.add(Integer.valueOf(a.id));
}
}
articleUnreadIds.addAll(unreadUpdatedFilter.getOmittedArticles());
Log.d(TAG, "Amount of unread articles: " + articleUnreadIds.size());
DBHelper.getInstance().markRead(VCAT_ALL, false);
DBHelper.getInstance().markArticles(articleUnreadIds, "isUnread", 1);
}
}
/**
* update articles for specified feed/category
*
* @param feedId
* feed/category to be updated
* @param displayOnlyUnread
* flag, that indicates, that only unread
* articles should be shown
* @param isCat
* if set to {@code true}, then {@code feedId} is actually the category ID
* @param overrideOffline
* should the "work offline" state be ignored?
* @param overrideDelay
* should the last update time be ignored?
*/
public void updateArticles(int feedId, boolean displayOnlyUnread, boolean isCat, boolean overrideOffline, boolean overrideDelay) {
Long time = articlesChanged.get(feedId);
if (isCat) // Category-Ids are in feedsChanged
time = feedsChanged.get(feedId);
if (time == null)
time = Long.valueOf(0);
if (articlesCached > time && !(feedId == VCAT_PUB || feedId == VCAT_STAR))
time = articlesCached;
if (!overrideDelay && time > System.currentTimeMillis() - Utils.UPDATE_TIME) {
return;
} else if (!Utils.isConnected(cm) && !(overrideOffline && Utils.checkConnected(cm))) {
return;
}
boolean isVcat = (feedId == VCAT_PUB || feedId == VCAT_STAR);
int sinceId = 0;
IArticleOmitter filter;
if (isVcat) {
// Display all articles for Starred/Published:
displayOnlyUnread = false;
// Don't omit any articles, isPublished should never be < 0:
filter = new IdUpdatedArticleOmitter("isPublished<0", null);
} else {
sinceId = Controller.getInstance().getSinceId();
// TODO: passing null adds all(!) articles to the map, this can take a second or two on slow devices...
filter = new IdUpdatedArticleOmitter(null, null);
}
// Calculate an appropriate upper limit for the number of articles
int limit = calculateLimit(feedId, displayOnlyUnread, isCat);
if (Controller.getInstance().isLowMemory())
limit = limit / 2;
Log.d(TAG, "UPDATE limit: " + limit);
Set<Article> articles = new HashSet<Article>();
if (!displayOnlyUnread) {
// If not displaying only unread articles: Refresh unread articles to get them too.
Controller.getInstance().getConnector()
.getHeadlines(articles, feedId, limit, VIEW_UNREAD, isCat, 0, null, null, filter);
}
String viewMode = (displayOnlyUnread ? VIEW_UNREAD : VIEW_ALL);
Controller.getInstance().getConnector()
.getHeadlines(articles, feedId, limit, viewMode, isCat, sinceId, null, null, filter);
if (isVcat)
handlePurgeMarked(articles, feedId);
handleInsertArticles(articles, false);
long currentTime = System.currentTimeMillis();
// Store requested feed-/category-id and ids of all feeds in db for this category if a category was requested
articlesChanged.put(feedId, currentTime);
notifyListeners();
if (isCat) {
for (Feed f : DBHelper.getInstance().getFeeds(feedId)) {
articlesChanged.put(f.id, currentTime);
}
}
}
/**
* Calculate an appropriate upper limit for the number of articles
*/
private int calculateLimit(int feedId, boolean displayOnlyUnread, boolean isCat) {
int limit = -1;
switch (feedId) {
case VCAT_STAR: // Starred
case VCAT_PUB: // Published
limit = JSONConnector.PARAM_LIMIT_MAX_VALUE;
break;
case VCAT_FRESH: // Fresh
limit = DBHelper.getInstance().getUnreadCount(feedId, true);
break;
case VCAT_ALL: // All Articles
limit = DBHelper.getInstance().getUnreadCount(feedId, true);
break;
default: // Normal categories
limit = DBHelper.getInstance().getUnreadCount(feedId, isCat);
}
if (feedId < -10 && limit <= 0) // Unread-count in DB is wrong for Labels since we only count articles with
// feedid = ?
limit = 50;
return limit;
}
private void handlePurgeMarked(Set<Article> articles, int feedId) {
// TODO Alle Artikel mit ID > minId als nicht starred und nicht published markieren
// Search min and max ids
int minId = Integer.MAX_VALUE;
Set<String> idSet = new HashSet<String>();
for (Article article : articles) {
if (article.id < minId)
minId = article.id;
idSet.add(article.id + "");
}
String idList = Utils.separateItems(idSet, ",");
String vcat = "";
if (feedId == VCAT_STAR)
vcat = "isStarred";
else if (feedId == VCAT_PUB)
vcat = "isPublished";
else
return;
DBHelper.getInstance().handlePurgeMarked(idList, minId, vcat);
}
/**
* prepare the DB and store given articles
*
* @param articles
* articles to be stored
* @param isCategory
*/
private void handleInsertArticles(final Collection<Article> articles, boolean isCaching) {
if (!articles.isEmpty()) {
// Search min and max ids
int minId = Integer.MAX_VALUE;
int maxId = Integer.MIN_VALUE;
for (Article article : articles) {
if (article.id > maxId)
maxId = article.id;
if (article.id < minId)
minId = article.id;
}
DBHelper.getInstance().purgeLastArticles(articles.size());
DBHelper.getInstance().insertArticles(articles);
// correct counters according to real local DB-Data
DBHelper.getInstance().calculateCounters();
notifyListeners();
// Only store sinceId when doing a full cache of new articles, else it doesn't work.
if (isCaching) {
Controller.getInstance().setSinceId(maxId);
Controller.getInstance().setLastSync(System.currentTimeMillis());
}
}
}
// *** FEEDS ************************************************************************
/**
* update DB (delete/insert) with actual feeds information from server
*
* @param categoryId
* id of category, which feeds should be returned
* @param overrideOffline
* do not check connected state
*
* @return actual feeds for given category
*/
public Set<Feed> updateFeeds(int categoryId, boolean overrideOffline) {
Long time = feedsChanged.get(categoryId);
if (time == null)
time = Long.valueOf(0);
if (time > System.currentTimeMillis() - Utils.UPDATE_TIME) {
return null;
} else if (Utils.isConnected(cm) || (overrideOffline && Utils.checkConnected(cm))) {
Set<Feed> ret = new LinkedHashSet<Feed>();
Set<Feed> feeds = Controller.getInstance().getConnector().getFeeds();
// Only delete feeds if we got new feeds...
if (!feeds.isEmpty()) {
for (Feed f : feeds) {
if (categoryId == VCAT_ALL || f.categoryId == categoryId)
ret.add(f);
feedsChanged.put(f.categoryId, System.currentTimeMillis());
}
DBHelper.getInstance().deleteFeeds();
DBHelper.getInstance().insertFeeds(feeds);
// Store requested category-id and ids of all received feeds
feedsChanged.put(categoryId, System.currentTimeMillis());
notifyListeners();
}
return ret;
}
return null;
}
// *** CATEGORIES *******************************************************************
public Set<Category> updateVirtualCategories() {
if (virtCategoriesChanged > System.currentTimeMillis() - Utils.UPDATE_TIME)
return null;
String vCatAllArticles = "";
String vCatFreshArticles = "";
String vCatPublishedArticles = "";
String vCatStarredArticles = "";
String uncatFeeds = "";
if (context != null) {
vCatAllArticles = (String) context.getText(R.string.VCategory_AllArticles);
vCatFreshArticles = (String) context.getText(R.string.VCategory_FreshArticles);
vCatPublishedArticles = (String) context.getText(R.string.VCategory_PublishedArticles);
vCatStarredArticles = (String) context.getText(R.string.VCategory_StarredArticles);
uncatFeeds = (String) context.getText(R.string.Feed_UncategorizedFeeds);
}
Set<Category> vCats = new LinkedHashSet<Category>();
vCats.add(new Category(VCAT_ALL, vCatAllArticles, DBHelper.getInstance().getUnreadCount(VCAT_ALL, true)));
vCats.add(new Category(VCAT_FRESH, vCatFreshArticles, DBHelper.getInstance().getUnreadCount(VCAT_FRESH, true)));
vCats.add(new Category(VCAT_PUB, vCatPublishedArticles, DBHelper.getInstance().getUnreadCount(VCAT_PUB, true)));
vCats.add(new Category(VCAT_STAR, vCatStarredArticles, DBHelper.getInstance().getUnreadCount(VCAT_STAR, true)));
vCats.add(new Category(VCAT_UNCAT, uncatFeeds, DBHelper.getInstance().getUnreadCount(VCAT_UNCAT, true)));
DBHelper.getInstance().insertCategories(vCats);
notifyListeners();
virtCategoriesChanged = System.currentTimeMillis();
return vCats;
}
/**
* update DB (delete/insert) with actual categories information from server
*
* @param overrideOffline
* do not check connected state
*
* @return actual categories
*/
public Set<Category> updateCategories(boolean overrideOffline) {
if (categoriesChanged > System.currentTimeMillis() - Utils.UPDATE_TIME) {
return null;
} else if (Utils.isConnected(cm) || overrideOffline) {
Set<Category> categories = Controller.getInstance().getConnector().getCategories();
if (!categories.isEmpty()) {
DBHelper.getInstance().deleteCategories(false);
DBHelper.getInstance().insertCategories(categories);
categoriesChanged = System.currentTimeMillis();
notifyListeners();
}
return categories;
}
return null;
}
// *** STATUS *******************************************************************
public void setArticleRead(Set<Integer> ids, int articleState) {
boolean erg = false;
if (Utils.isConnected(cm))
erg = Controller.getInstance().getConnector().setArticleRead(ids, articleState);
if (!erg)
DBHelper.getInstance().markUnsynchronizedStates(ids, DBHelper.MARK_READ, articleState);
}
public void setArticleStarred(int articleId, int articleState) {
boolean erg = false;
Set<Integer> ids = new HashSet<Integer>();
ids.add(articleId);
if (Utils.isConnected(cm))
erg = Controller.getInstance().getConnector().setArticleStarred(ids, articleState);
if (!erg)
DBHelper.getInstance().markUnsynchronizedStates(ids, DBHelper.MARK_STAR, articleState);
}
public void setArticlePublished(int articleId, int articleState, String note) {
boolean erg = false;
Map<Integer, String> ids = new HashMap<Integer, String>();
ids.put(articleId, note);
if (Utils.isConnected(cm))
erg = Controller.getInstance().getConnector().setArticlePublished(ids, articleState);
// Write changes to cache if calling the server failed
if (!erg) {
DBHelper.getInstance().markUnsynchronizedStates(ids.keySet(), DBHelper.MARK_PUBLISH, articleState);
DBHelper.getInstance().markUnsynchronizedNotes(ids, DBHelper.MARK_PUBLISH);
}
}
/**
* mark all articles in given category/feed as read
*
* @param id
* category/feed ID
* @param isCategory
* if set to {@code true}, then given id is category
* ID, otherwise - feed ID
*/
public void setRead(int id, boolean isCategory) {
Collection<Integer> markedArticleIds = DBHelper.getInstance().markRead(id, isCategory);
if (markedArticleIds != null) {
notifyListeners();
boolean isSync = false;
if (Utils.isConnected(cm)) {
isSync = Controller.getInstance().getConnector().setRead(id, isCategory);
}
if (!isSync) {
DBHelper.getInstance().markUnsynchronizedStates(markedArticleIds, DBHelper.MARK_READ, 0);
}
}
}
public boolean shareToPublished(String title, String url, String content) {
if (Utils.isConnected(cm))
return Controller.getInstance().getConnector().shareToPublished(title, url, content);
return false;
}
public JSONConnector.SubscriptionResponse feedSubscribe(String feed_url, int category_id) {
if (Utils.isConnected(cm))
return Controller.getInstance().getConnector().feedSubscribe(feed_url, category_id);
return null;
}
public boolean feedUnsubscribe(int feed_id) {
if (Utils.isConnected(cm))
return Controller.getInstance().getConnector().feedUnsubscribe(feed_id);
return false;
}
public String getPref(String pref) {
if (Utils.isConnected(cm))
return Controller.getInstance().getConnector().getPref(pref);
return null;
}
public int getVersion() {
if (Utils.isConnected(cm))
return Controller.getInstance().getConnector().getVersion();
return -1;
}
public Set<Label> getLabels(int articleId) {
Set<Label> ret = DBHelper.getInstance().getLabelsForArticle(articleId);
return ret;
}
public boolean setLabel(Integer articleId, Label label) {
Set<Integer> set = new HashSet<Integer>();
set.add(articleId);
return setLabel(set, label);
}
public boolean setLabel(Set<Integer> articleIds, Label label) {
DBHelper.getInstance().insertLabels(articleIds, label, label.checked);
notifyListeners();
boolean erg = false;
if (Utils.isConnected(cm)) {
Log.d(TAG, "Calling connector with Label: " + label + ") and ids.size() " + articleIds.size());
erg = Controller.getInstance().getConnector().setArticleLabel(articleIds, label.id, label.checked);
}
return erg;
}
/**
* syncronize read, starred, published articles and notes with server
*/
public void synchronizeStatus() {
if (!Utils.isConnected(cm))
return;
long time = System.currentTimeMillis();
String[] marks = new String[] { DBHelper.MARK_READ, DBHelper.MARK_STAR, DBHelper.MARK_PUBLISH,
DBHelper.MARK_NOTE };
for (String mark : marks) {
Map<Integer, String> idsMark = DBHelper.getInstance().getMarked(mark, 1);
Map<Integer, String> idsUnmark = DBHelper.getInstance().getMarked(mark, 0);
if (DBHelper.MARK_READ.equals(mark)) {
if (Controller.getInstance().getConnector().setArticleRead(idsMark.keySet(), 1))
DBHelper.getInstance().setMarked(idsMark, mark);
if (Controller.getInstance().getConnector().setArticleRead(idsUnmark.keySet(), 0))
DBHelper.getInstance().setMarked(idsUnmark, mark);
}
if (DBHelper.MARK_STAR.equals(mark)) {
if (Controller.getInstance().getConnector().setArticleStarred(idsMark.keySet(), 1))
DBHelper.getInstance().setMarked(idsMark, mark);
if (Controller.getInstance().getConnector().setArticleStarred(idsUnmark.keySet(), 0))
DBHelper.getInstance().setMarked(idsUnmark, mark);
}
if (DBHelper.MARK_PUBLISH.equals(mark)) {
if (Controller.getInstance().getConnector().setArticlePublished(idsMark, 1))
DBHelper.getInstance().setMarked(idsMark, mark);
if (Controller.getInstance().getConnector().setArticlePublished(idsUnmark, 0))
DBHelper.getInstance().setMarked(idsUnmark, mark);
}
// TODO: Add synchronization of labels
}
/*
* Server doesn't seem to support ID -6 for "read articles" so I'll stick with the already fetched articles. In
* the case that we had a cache-run before we can just mark everything as read, then mark all cached articles as
* unread and we're done.
*/
// get read articles from server
// articles = new HashSet<Article>();
// int minUnread = DBHelper.getInstance().getMinUnreadId();
// Set<String> skipProperties = new HashSet<String>(Arrays.asList(new String[] { JSONConnector.TITLE,
// JSONConnector.UNREAD, JSONConnector.UPDATED, JSONConnector.FEED_ID, JSONConnector.CONTENT,
// JSONConnector.URL, JSONConnector.COMMENT_URL, JSONConnector.ATTACHMENTS, JSONConnector.STARRED,
// JSONConnector.PUBLISHED }));
//
// Controller.getInstance().getConnector()
// .getHeadlines(articles, VCAT_ALL, 400, VIEW_ALL, true, minUnread, null, skipProperties);
Log.d(TAG, String.format("Syncing Status took %sms", (System.currentTimeMillis() - time)));
}
public void purgeOrphanedArticles() {
if (Controller.getInstance().getLastCleanup() > System.currentTimeMillis() - Utils.CLEANUP_TIME)
return;
DBHelper.getInstance().purgeOrphanedArticles();
Controller.getInstance().setLastCleanup(System.currentTimeMillis());
}
private void notifyListeners() {
if (!Controller.getInstance().isHeadless())
UpdateController.getInstance().notifyListeners();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.controllers;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.ttrssreader.gui.dialogs.ErrorDialog;
import org.ttrssreader.imageCache.ImageCache;
import org.ttrssreader.model.pojos.Article;
import org.ttrssreader.model.pojos.Category;
import org.ttrssreader.model.pojos.Feed;
import org.ttrssreader.model.pojos.Label;
import org.ttrssreader.model.pojos.RemoteFile;
import org.ttrssreader.utils.StringSupport;
import org.ttrssreader.utils.Utils;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.os.Build;
import android.text.Html;
import android.util.Log;
import android.widget.Toast;
public class DBHelper {
protected static final String TAG = DBHelper.class.getSimpleName();
private volatile boolean initialized = false;
private static final Object lock = new Object();
public static final String DATABASE_NAME = "ttrss.db";
public static final String DATABASE_BACKUP_NAME = "_backup_";
public static final int DATABASE_VERSION = 60;
public static final String TABLE_CATEGORIES = "categories";
public static final String TABLE_FEEDS = "feeds";
public static final String TABLE_ARTICLES = "articles";
public static final String TABLE_ARTICLES2LABELS = "articles2labels";
public static final String TABLE_LABELS = "labels";
public static final String TABLE_MARK = "marked";
public static final String TABLE_REMOTEFILES = "remotefiles";
public static final String TABLE_REMOTEFILE2ARTICLE = "remotefile2article";
public static final String MARK_READ = "isUnread";
public static final String MARK_STAR = "isStarred";
public static final String MARK_PUBLISH = "isPublished";
public static final String MARK_NOTE = "note";
// @formatter:off
private static final String CREATE_TABLE_CATEGORIES =
"CREATE TABLE "
+ TABLE_CATEGORIES
+ " (_id INTEGER PRIMARY KEY,"
+ " title TEXT,"
+ " unread INTEGER)";
private static final String CREATE_TABLE_FEEDS =
"CREATE TABLE "
+ TABLE_FEEDS
+ " (_id INTEGER PRIMARY KEY,"
+ " categoryId INTEGER,"
+ " title TEXT,"
+ " url TEXT,"
+ " unread INTEGER)";
private static final String CREATE_TABLE_ARTICLES =
"CREATE TABLE "
+ TABLE_ARTICLES
+ " (_id INTEGER PRIMARY KEY,"
+ " feedId INTEGER,"
+ " title TEXT,"
+ " isUnread INTEGER,"
+ " articleUrl TEXT,"
+ " articleCommentUrl TEXT,"
+ " updateDate INTEGER,"
+ " content TEXT,"
+ " attachments TEXT,"
+ " isStarred INTEGER,"
+ " isPublished INTEGER,"
+ " cachedImages INTEGER DEFAULT 0,"
+ " articleLabels TEXT,"
+ " author TEXT)";
private static final String CREATE_TABLE_ARTICLES2LABELS =
"CREATE TABLE "
+ TABLE_ARTICLES2LABELS
+ " (articleId INTEGER,"
+ " labelId INTEGER, PRIMARY KEY(articleId, labelId))";
private static final String CREATE_TABLE_MARK =
"CREATE TABLE "
+ TABLE_MARK
+ " (id INTEGER,"
+ " type INTEGER,"
+ " " + MARK_READ + " INTEGER,"
+ " " + MARK_STAR + " INTEGER,"
+ " " + MARK_PUBLISH + " INTEGER,"
+ " " + MARK_NOTE + " TEXT,"
+ " PRIMARY KEY(id, type))";
private static final String INSERT_CATEGORY =
"REPLACE INTO "
+ TABLE_CATEGORIES
+ " (_id, title, unread)"
+ " VALUES (?, ?, ?)";
private static final String INSERT_FEED =
"REPLACE INTO "
+ TABLE_FEEDS
+ " (_id, categoryId, title, url, unread)"
+ " VALUES (?, ?, ?, ?, ?)";
private static final String INSERT_ARTICLE =
"INSERT OR REPLACE INTO "
+ TABLE_ARTICLES
+ " (_id, feedId, title, isUnread, articleUrl, articleCommentUrl, updateDate, content, attachments, isStarred, isPublished, cachedImages, articleLabels, author)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, coalesce((SELECT cachedImages FROM " + TABLE_ARTICLES + " WHERE _id=?), NULL), ?, ?)";
// This should insert new values or replace existing values but should always keep an already inserted value for "cachedImages".
// When inserting it is set to the default value which is 0 (not "NULL").
private static final String INSERT_LABEL =
"REPLACE INTO "
+ TABLE_ARTICLES2LABELS
+ " (articleId, labelId)"
+ " VALUES (?, ?)";
private static final String INSERT_REMOTEFILE =
"INSERT OR FAIL INTO "
+ TABLE_REMOTEFILES
+ " (url, ext)"
+ " VALUES (?, ?)";
private static final String INSERT_REMOTEFILE2ARTICLE =
"INSERT OR IGNORE INTO "
+ TABLE_REMOTEFILE2ARTICLE
+ " (remotefileId, articleId)"
+ " VALUES (?, ?)";
// @formatter:on
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertCategory;
private SQLiteStatement insertFeed;
private SQLiteStatement insertArticle;
private SQLiteStatement insertLabel;
private SQLiteStatement insertRemoteFile;
private SQLiteStatement insertRemoteFile2Article;
private static boolean specialUpgradeSuccessful = false;
// Singleton (see http://stackoverflow.com/a/11165926)
private DBHelper() {
}
private static class InstanceHolder {
private static final DBHelper instance = new DBHelper();
}
public static DBHelper getInstance() {
return InstanceHolder.instance;
}
public void checkAndInitializeDB(final Context context) {
synchronized (lock) {
this.context = context;
// Check if deleteDB is scheduled or if DeleteOnStartup is set
if (Controller.getInstance().isDeleteDBScheduled()) {
if (deleteDB()) {
Controller.getInstance().setDeleteDBScheduled(false);
initializeDBHelper();
return; // Don't need to check if DB is corrupted, it is NEW!
}
}
// Initialize DB
if (!initialized) {
initializeDBHelper();
} else if (db == null || !db.isOpen()) {
initializeDBHelper();
} else {
return; // DB was already initialized, no need to check anything.
}
// Test if DB is accessible, backup and delete if not
if (initialized) {
Cursor c = null;
try {
// Try to access the DB
c = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_CATEGORIES, null);
c.getCount();
if (c.moveToFirst())
c.getInt(0);
} catch (Exception e) {
Log.e(TAG, "Database was corrupted, creating a new one...", e);
closeDB();
File dbFile = context.getDatabasePath(DATABASE_NAME);
if (dbFile.delete())
initializeDBHelper();
ErrorDialog
.getInstance(
context,
"The Database was corrupted and had to be recreated. If this happened more than once to you please let me know under what circumstances this happened.");
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
}
}
@SuppressWarnings("deprecation")
private boolean initializeDBHelper() {
synchronized (lock) {
if (context == null) {
Log.e(TAG, "Can't handle internal DB without Context-Object.");
return false;
}
if (db != null)
closeDB();
OpenHelper openHelper = new OpenHelper(context);
db = openHelper.getWritableDatabase();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
db.setLockingEnabled(true);
if (specialUpgradeSuccessful) {
// Re-open DB for final usage:
db.close();
openHelper = new OpenHelper(context);
db = openHelper.getWritableDatabase();
Toast.makeText(context, "ImageCache is beeing cleaned...", Toast.LENGTH_LONG).show();
new org.ttrssreader.utils.AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
// Clear ImageCache since no files are in REMOTE_FILES anymore and we dont want to leave them
// there forever:
ImageCache imageCache = Controller.getInstance().getImageCache();
imageCache.fillMemoryCacheFromDisk();
File cacheFolder = new File(imageCache.getDiskCacheDirectory());
if (cacheFolder.isDirectory()) {
try {
FileUtils.deleteDirectory(cacheFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
};
protected void onPostExecute(Void result) {
Toast.makeText(context, "ImageCache has been cleaned up...", Toast.LENGTH_LONG).show();
};
}.execute();
}
insertCategory = db.compileStatement(INSERT_CATEGORY);
insertFeed = db.compileStatement(INSERT_FEED);
insertArticle = db.compileStatement(INSERT_ARTICLE);
insertLabel = db.compileStatement(INSERT_LABEL);
insertRemoteFile = db.compileStatement(INSERT_REMOTEFILE);
insertRemoteFile2Article = db.compileStatement(INSERT_REMOTEFILE2ARTICLE);
db.acquireReference();
initialized = true;
return true;
}
}
private boolean deleteDB() {
synchronized (lock) {
if (context == null)
return false;
Log.i(TAG, "Deleting Database as requested by preferences.");
File f = context.getDatabasePath(DATABASE_NAME);
if (f.exists()) {
if (db != null) {
closeDB();
}
return f.delete();
}
return false;
}
}
private void closeDB() {
synchronized (lock) {
db.releaseReference();
db.close();
db = null;
}
}
private boolean isDBAvailable() {
synchronized (lock) {
if (db != null && db.isOpen())
return true;
if (db != null) {
OpenHelper openHelper = new OpenHelper(context);
db = openHelper.getWritableDatabase();
initialized = db.isOpen();
return initialized;
} else {
Log.i(TAG, "Controller not initialized, trying to do that now...");
initializeDBHelper();
return true;
}
}
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* set wished DB modes on DB
*
* @param db
* DB to be used
*/
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
/**
* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_CATEGORIES);
db.execSQL(CREATE_TABLE_FEEDS);
db.execSQL(CREATE_TABLE_ARTICLES);
db.execSQL(CREATE_TABLE_ARTICLES2LABELS);
db.execSQL(CREATE_TABLE_MARK);
createRemoteFilesSupportDBObjects(db);
}
/**
* upgrade the DB
*
* @param db
* The database.
* @param oldVersion
* The old database version.
* @param newVersion
* The new database version.
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean didUpgrade = false;
if (oldVersion < 40) {
String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN isStarred INTEGER";
Log.i(TAG, String.format("Upgrading database from %s to 40.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 42) {
String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN isPublished INTEGER";
Log.i(TAG, String.format("Upgrading database from %s to 42.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 45) {
// @formatter:off
String sql = "CREATE TABLE IF NOT EXISTS "
+ TABLE_MARK
+ " (id INTEGER,"
+ " type INTEGER,"
+ " " + MARK_READ + " INTEGER,"
+ " " + MARK_STAR + " INTEGER,"
+ " " + MARK_PUBLISH + " INTEGER,"
+ " PRIMARY KEY(id, type))";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 45.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 46) {
// @formatter:off
String sql = "DROP TABLE IF EXISTS "
+ TABLE_MARK;
String sql2 = "CREATE TABLE IF NOT EXISTS "
+ TABLE_MARK
+ " (id INTEGER PRIMARY KEY,"
+ " " + MARK_READ + " INTEGER,"
+ " " + MARK_STAR + " INTEGER,"
+ " " + MARK_PUBLISH + " INTEGER)";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 46.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
Log.i(TAG, String.format(" (Executing: %s", sql2));
db.execSQL(sql);
db.execSQL(sql2);
didUpgrade = true;
}
if (oldVersion < 47) {
String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN cachedImages INTEGER DEFAULT 0";
Log.i(TAG, String.format("Upgrading database from %s to 47.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 48) {
// @formatter:off
String sql = "CREATE TABLE IF NOT EXISTS "
+ TABLE_MARK
+ " (id INTEGER,"
+ " type INTEGER,"
+ " " + MARK_READ + " INTEGER,"
+ " " + MARK_STAR + " INTEGER,"
+ " " + MARK_PUBLISH + " INTEGER,"
+ " PRIMARY KEY(id, type))";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 48.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 49) {
// @formatter:off
String sql = "CREATE TABLE "
+ TABLE_ARTICLES2LABELS
+ " (articleId INTEGER,"
+ " labelId INTEGER, PRIMARY KEY(articleId, labelId))";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 49.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 50) {
Log.i(TAG, String.format("Upgrading database from %s to 50.", oldVersion));
ContentValues cv = new ContentValues(1);
cv.put("cachedImages", 0);
db.update(TABLE_ARTICLES, cv, "cachedImages IS null", null);
didUpgrade = true;
}
if (oldVersion < 51) {
// @formatter:off
String sql = "DROP TABLE IF EXISTS "
+ TABLE_MARK;
String sql2 = "CREATE TABLE "
+ TABLE_MARK
+ " (id INTEGER,"
+ " type INTEGER,"
+ " " + MARK_READ + " INTEGER,"
+ " " + MARK_STAR + " INTEGER,"
+ " " + MARK_PUBLISH + " INTEGER,"
+ " " + MARK_NOTE + " TEXT,"
+ " PRIMARY KEY(id, type))";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 51.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
Log.i(TAG, String.format(" (Executing: %s", sql2));
db.execSQL(sql);
db.execSQL(sql2);
didUpgrade = true;
}
if (oldVersion < 52) {
// @formatter:off
String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN articleLabels TEXT";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 52.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 53) {
Log.i(TAG, String.format("Upgrading database from %s to 53.", oldVersion));
didUpgrade = createRemoteFilesSupportDBObjects(db);
if (didUpgrade) {
ContentValues cv = new ContentValues(1);
cv.putNull("cachedImages");
db.update(TABLE_ARTICLES, cv, null, null);
ImageCache ic = Controller.getInstance().getImageCache();
if (ic != null) {
ic.clear();
}
}
}
if (oldVersion < 58) {
Log.i(TAG, String.format("Upgrading database from %s to 58.", oldVersion));
// Rename columns "id" to "_id" by modifying the table structure:
db.beginTransaction();
try {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMOTEFILES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMOTEFILE2ARTICLE);
db.execSQL("PRAGMA writable_schema=1;");
String sql = "UPDATE SQLITE_MASTER SET SQL = '%s' WHERE NAME = '%s';";
db.execSQL(String.format(sql, CREATE_TABLE_CATEGORIES, TABLE_CATEGORIES));
db.execSQL(String.format(sql, CREATE_TABLE_FEEDS, TABLE_FEEDS));
db.execSQL(String.format(sql, CREATE_TABLE_ARTICLES, TABLE_ARTICLES));
db.execSQL("PRAGMA writable_schema=0;");
if (createRemoteFilesSupportDBObjects(db)) {
db.setTransactionSuccessful();
didUpgrade = true;
}
} finally {
db.execSQL("PRAGMA foreign_keys=ON;");
db.endTransaction();
specialUpgradeSuccessful = true;
}
}
if (oldVersion < 59) {
// @formatter:off
String sql = "ALTER TABLE " + TABLE_ARTICLES + " ADD COLUMN author TEXT";
// @formatter:on
Log.i(TAG, String.format("Upgrading database from %s to 59.", oldVersion));
Log.i(TAG, String.format(" (Executing: %s", sql));
db.execSQL(sql);
didUpgrade = true;
}
if (oldVersion < 60) {
Log.i(TAG, String.format("Upgrading database from %s to 59.", oldVersion));
Log.i(TAG, String.format(" (Re-Creating View: remotefiles_sequence )"));
createRemotefilesView(db);
didUpgrade = true;
}
if (didUpgrade == false) {
Log.i(TAG, "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FEEDS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ARTICLES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MARK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMOTEFILES);
onCreate(db);
}
}
/**
* create DB objects (tables, triggers, views) which
* are necessary for file cache support
*
* @param db
* current database
*/
private boolean createRemoteFilesSupportDBObjects(SQLiteDatabase db) {
boolean success = false;
try {
createRemotefiles(db);
createRemotefiles2Articles(db);
createRemotefilesView(db);
success = true;
} catch (SQLException e) {
Log.e(TAG, "Creation of remote file support DB objects failed.\n" + e);
}
return success;
}
private void createRemotefiles(SQLiteDatabase db) {
// @formatter:off
// remote files (images, attachments, etc) belonging to articles,
// which are locally stored (cached)
db.execSQL("CREATE TABLE "
+ TABLE_REMOTEFILES
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,"
// remote file URL
+ " url TEXT UNIQUE NOT NULL,"
// file size
+ " length INTEGER DEFAULT 0,"
// extension - some kind of additional info
// (i.e. file extension)
+ " ext TEXT NOT NULL,"
// unix timestamp of last change
// (set automatically by triggers)
+ " updateDate INTEGER,"
// boolean flag determining if the file is locally stored
+ " cached INTEGER DEFAULT 0)");
// index for quiicker search by by URL
db.execSQL("DROP INDEX IF EXISTS idx_remotefiles_by_url");
db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS idx_remotefiles_by_url"
+ " ON " + TABLE_REMOTEFILES
+ " (url)");
// sets last change unix timestamp after row creation
db.execSQL("DROP TRIGGER IF EXISTS insert_remotefiles");
db.execSQL("CREATE TRIGGER IF NOT EXISTS insert_remotefiles AFTER INSERT"
+ " ON " + TABLE_REMOTEFILES
+ " BEGIN"
+ " UPDATE " + TABLE_REMOTEFILES
+ " SET updateDate = strftime('%s', 'now')"
+ " WHERE id = new.id;"
+ " END");
// sets last change unix timestamp after row update
db.execSQL("DROP TRIGGER IF EXISTS update_remotefiles_lastchanged");
db.execSQL("CREATE TRIGGER IF NOT EXISTS update_remotefiles_lastchanged AFTER UPDATE"
+ " ON " + TABLE_REMOTEFILES
+ " BEGIN"
+ " UPDATE " + TABLE_REMOTEFILES
+ " SET updateDate = strftime('%s', 'now')"
+ " WHERE id = new.id;"
+ " END");
// @formatter:on
}
private void createRemotefiles2Articles(SQLiteDatabase db) {
// @formatter:off
// m to n relations between articles and remote files
db.execSQL("CREATE TABLE "
+ TABLE_REMOTEFILE2ARTICLE
// ID of remote file
+ "(remotefileId INTEGER"
+ " REFERENCES " + TABLE_REMOTEFILES + "(id)"
+ " ON DELETE CASCADE,"
// ID of article
+ " articleId INTEGER"
+ " REFERENCES " + TABLE_ARTICLES + "(_id)"
+ " ON UPDATE CASCADE"
+ " ON DELETE NO ACTION,"
// if both IDs are known, then the row should be found faster
+ " PRIMARY KEY(remotefileId, articleId))");
// update count of cached images for article on change of "cached"
// field of remotefiles
db.execSQL("DROP TRIGGER IF EXISTS update_remotefiles_articlefiles");
db.execSQL("CREATE TRIGGER IF NOT EXISTS update_remotefiles_articlefiles AFTER UPDATE"
+ " OF cached"
+ " ON " + TABLE_REMOTEFILES
+ " BEGIN"
+ " UPDATE " + TABLE_ARTICLES + ""
+ " SET"
+ " cachedImages = ("
+ " SELECT"
+ " COUNT(r.id)"
+ " FROM " + TABLE_REMOTEFILES + " r,"
+ TABLE_REMOTEFILE2ARTICLE + " m"
+ " WHERE"
+ " m.remotefileId=r.id"
+ " AND m.articleId=" + TABLE_ARTICLES + "._id"
+ " AND r.cached=1)"
+ " WHERE _id IN ("
+ " SELECT"
+ " a._id"
+ " FROM " + TABLE_REMOTEFILE2ARTICLE + " m,"
+ TABLE_ARTICLES + " a"
+ " WHERE"
+ " m.remotefileId=new.id AND m.articleId=a._id);"
+ " END");
// @formatter:on
}
private void createRemotefilesView(SQLiteDatabase db) {
// @formatter:off
// represents importance of cached files
// the sequence is defined by
// 1. the article to which the remote file belongs to is not read
// 2. update date of the article to which the remote file belongs to
// 3. the file length
db.execSQL("DROP VIEW IF EXISTS remotefile_sequence");
db.execSQL("CREATE VIEW IF NOT EXISTS remotefile_sequence AS"
+ " SELECT r.*, MAX(a.isUnread) AS isUnread,"
+ " MAX(a.updateDate) AS articleUpdateDate,"
+ " MAX(a.isUnread)||MAX(a.updateDate)||(100000000000-r.length)"
+ " AS ord"
+ " FROM " + TABLE_REMOTEFILES + " r,"
+ TABLE_REMOTEFILE2ARTICLE + " m,"
+ TABLE_ARTICLES + " a"
+ " WHERE m.remotefileId=r.id AND m.articleId=a._id"
+ " GROUP BY r.id");
// @formatter:on
}
}
/**
* Used by SubscribeActivity to directly access the DB and get a cursor for the List of Categories.<br>
* PLEASE NOTE: Don't forget to close the received cursor!
*
* @see android.database.sqlite.SQLiteDatabase#rawQuery(String, String[])
*/
@Deprecated
public Cursor query(String sql, String[] selectionArgs) {
if (!isDBAvailable())
return null;
Cursor cursor = db.rawQuery(sql, selectionArgs);
return cursor;
}
// *******| INSERT |*******************************************************************
private void insertCategory(int id, String title, int unread) {
if (title == null)
title = "";
synchronized (insertCategory) {
insertCategory.bindLong(1, id);
insertCategory.bindString(2, title);
insertCategory.bindLong(3, unread);
if (!isDBAvailable())
return;
insertCategory.execute();
}
}
public void insertCategories(Set<Category> set) {
if (!isDBAvailable() || set == null)
return;
db.beginTransaction();
try {
for (Category c : set) {
insertCategory(c.id, c.title, c.unread);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
private void insertFeed(int id, int categoryId, String title, String url, int unread) {
if (title == null)
title = "";
if (url == null)
url = "";
synchronized (insertFeed) {
insertFeed.bindLong(1, Integer.valueOf(id).longValue());
insertFeed.bindLong(2, Integer.valueOf(categoryId).longValue());
insertFeed.bindString(3, title);
insertFeed.bindString(4, url);
insertFeed.bindLong(5, unread);
if (!isDBAvailable())
return;
insertFeed.execute();
}
}
public void insertFeeds(Set<Feed> set) {
if (!isDBAvailable() || set == null)
return;
db.beginTransaction();
try {
for (Feed f : set) {
insertFeed(f.id, f.categoryId, f.title, f.url, f.unread);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
private void insertArticleIntern(Article a) {
if (a.title == null)
a.title = "";
if (a.content == null)
a.content = "";
if (a.url == null)
a.url = "";
if (a.commentUrl == null)
a.commentUrl = "";
if (a.updated == null)
a.updated = new Date();
if (a.attachments == null)
a.attachments = new LinkedHashSet<String>();
if (a.labels == null)
a.labels = new LinkedHashSet<Label>();
if (a.author == null)
a.author = "";
// articleLabels
long retId = -1;
synchronized (insertArticle) {
insertArticle.bindLong(1, a.id);
insertArticle.bindLong(2, a.feedId);
insertArticle.bindString(3, Html.fromHtml(a.title).toString());
insertArticle.bindLong(4, (a.isUnread ? 1 : 0));
insertArticle.bindString(5, a.url);
insertArticle.bindString(6, a.commentUrl);
insertArticle.bindLong(7, a.updated.getTime());
insertArticle.bindString(8, a.content);
insertArticle.bindString(9, Utils.separateItems(a.attachments, ";"));
insertArticle.bindLong(10, (a.isStarred ? 1 : 0));
insertArticle.bindLong(11, (a.isPublished ? 1 : 0));
insertArticle.bindLong(12, a.id); // ID again for the where-clause
insertArticle.bindString(13, Utils.separateItems(a.labels, "---"));
insertArticle.bindString(14, a.author);
if (!isDBAvailable())
return;
retId = insertArticle.executeInsert();
}
if (retId != -1)
insertLabels(a.id, a.labels);
}
public void insertArticle(Article a) {
if (isDBAvailable())
insertArticleIntern(a);
}
public void insertArticles(Collection<Article> articles) {
if (!isDBAvailable() || articles == null || articles.isEmpty())
return;
db.beginTransaction();
try {
for (Article a : articles) {
insertArticleIntern(a);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
private void insertLabels(int articleId, Set<Label> labels) {
for (Label label : labels) {
insertLabel(articleId, label);
}
}
private void insertLabel(int articleId, Label label) {
if (label.id < -10) {
if (!isDBAvailable())
return;
synchronized (insertLabel) {
insertLabel.bindLong(1, articleId);
insertLabel.bindLong(2, label.id);
insertLabel.executeInsert();
}
}
}
public void removeLabel(int articleId, Label label) {
if (label.id < -10) {
String[] args = new String[] { articleId + "", label.id + "" };
if (!isDBAvailable())
return;
db.delete(TABLE_ARTICLES2LABELS, "articleId=? AND labelId=?", args);
}
}
public void insertLabels(Set<Integer> articleIds, Label label, boolean assign) {
if (!isDBAvailable())
return;
for (Integer articleId : articleIds) {
if (assign)
insertLabel(articleId, label);
else
removeLabel(articleId, label);
}
}
/**
* insert given remote file into DB
*
* @param url
* remote file URL
* @return remote file id, which was inserted or already exist in DB
*/
private long insertRemoteFile(String url) {
long ret = 0;
try {
synchronized (insertRemoteFile) {
insertRemoteFile.bindString(1, url);
// extension (reserved for future)
insertRemoteFile.bindString(2, "");
if (isDBAvailable())
ret = insertRemoteFile.executeInsert();
}
} catch (SQLException e) {
// if this remote file already in DB, get its ID
ret = getRemoteFile(url).id;
}
return ret;
}
/**
* insert given relation (remotefileId <-> articleId) into DB
*
* @param rfId
* remote file ID
* @param aId
* article ID
*/
private void insertRemoteFile2Article(long rfId, long aId) {
synchronized (insertRemoteFile2Article) {
insertRemoteFile2Article.bindLong(1, rfId);
// extension (reserved for future)
insertRemoteFile2Article.bindLong(2, aId);
if (isDBAvailable())
insertRemoteFile2Article.executeInsert();
}
}
// *******| UPDATE |*******************************************************************
/**
* set read status in DB for given category/feed
*
* @param id
* category/feed ID
* @param isCategory
* if set to {@code true}, then given id is category
* ID, otherwise - feed ID
*
* @return collection of article IDs, which was marked as read or {@code null} if nothing was changed
*/
public Collection<Integer> markRead(int id, boolean isCategory) {
Set<Integer> markedIds = null;
if (isDBAvailable()) {
StringBuilder where = new StringBuilder();
StringBuilder feedIds = new StringBuilder();
switch (id) {
case Data.VCAT_ALL:
where.append(" 1 "); // Select everything...
break;
case Data.VCAT_FRESH:
long time = System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge();
where.append(" updateDate > ").append(time);
break;
case Data.VCAT_PUB:
where.append(" isPublished > 0 ");
break;
case Data.VCAT_STAR:
where.append(" isStarred > 0 ");
break;
default:
if (isCategory) {
feedIds.append("SELECT _id FROM ").append(TABLE_FEEDS).append(" WHERE categoryId=").append(id);
} else {
feedIds.append(id);
}
where.append(" feedId IN (").append(feedIds).append(") ");
break;
}
where.append(" and isUnread>0 ");
Cursor c = null;
db.beginTransaction();
try {
// select id from articles where categoryId in (...)
c = db.query(TABLE_ARTICLES, new String[] { "_id" }, where.toString(), null, null, null, null);
int count = c.getCount();
if (count > 0) {
markedIds = new HashSet<Integer>(count);
while (c.moveToNext()) {
markedIds.add(c.getInt(0));
}
}
db.setTransactionSuccessful();
} finally {
if (c != null && !c.isClosed())
c.close();
db.endTransaction();
}
}
if (markedIds != null && !markedIds.isEmpty()) {
markArticles(markedIds, "isUnread", 0);
}
return markedIds;
}
public void markLabelRead(int labelId) {
ContentValues cv = new ContentValues(1);
cv.put("isUnread", 0);
String idList = "SELECT _id id FROM " + TABLE_ARTICLES + " AS a, " + TABLE_ARTICLES2LABELS
+ " as l WHERE a._id=l.articleId AND l.labelId=" + labelId;
if (!isDBAvailable())
return;
db.update(TABLE_ARTICLES, cv, "isUnread>0 AND _id IN(" + idList + ")", null);
}
/**
* mark given property of given articles with given state
*
* @param idList
* set of article IDs, which should be processed
* @param mark
* mark to be set
* @param state
* value for the mark
*/
public void markArticles(Set<Integer> idList, String mark, int state) {
if (isDBAvailable() && idList != null && !idList.isEmpty()) {
db.beginTransaction();
try {
for (String ids : StringSupport.convertListToString(idList, 400)) {
markArticles(ids, mark, state);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
calculateCounters();
}
}
/**
* mark given property of given article with given state
*
* @param id
* set of article IDs, which should be processed
* @param mark
* mark to be set
* @param state
* value for the mark
*/
public void markArticle(int id, String mark, int state) {
if (!isDBAvailable())
return;
db.beginTransaction();
try {
markArticles("" + id, mark, state);
calculateCounters();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* mark given property of given articles with given state
*
* @param idList
* set of article IDs, which should be processed
* @param mark
* mark to be set
* @param state
* value for the mark
* @return the number of rows affected
*/
public int markArticles(String idList, String mark, int state) {
int rowCount = 0;
if (isDBAvailable()) {
ContentValues cv = new ContentValues(1);
cv.put(mark, state);
rowCount = db.update(TABLE_ARTICLES, cv, "_id IN (" + idList + ") AND ? != ?",
new String[] { mark, String.valueOf(state) });
}
return rowCount;
}
public void markUnsynchronizedStates(Collection<Integer> ids, String mark, int state) {
// Disabled until further testing and proper SQL has been built. Tries to do the UPDATE and INSERT without
// looping over the ids but instead with a list of ids:
// Set<String> idList = StringSupport.convertListToString(ids);
// for (String s : idList) {
// db.execSQL(String.format("UPDATE %s SET %s=%s WHERE id in %s", TABLE_MARK, mark, state, s));
// db.execSQL(String.format("INSERT OR IGNORE INTO %s (id, %s) VALUES (%s, %s)", TABLE_MARK, mark, id, state));
// <- WRONG!
// }
if (!isDBAvailable())
return;
db.beginTransaction();
try {
for (Integer id : ids) {
// First update, then insert. If row exists it gets updated and second call ignores it, else the second
// call inserts it.
db.execSQL(String.format("UPDATE %s SET %s=%s WHERE id=%s", TABLE_MARK, mark, state, id));
db.execSQL(String.format("INSERT OR IGNORE INTO %s (id, %s) VALUES (%s, %s)", TABLE_MARK, mark, id,
state));
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
// Special treatment for notes since the method markUnsynchronizedStates(...) doesn't support inserting any
// additional data.
public void markUnsynchronizedNotes(Map<Integer, String> ids, String markPublish) {
if (!isDBAvailable())
return;
db.beginTransaction();
try {
for (Integer id : ids.keySet()) {
String note = ids.get(id);
if (note == null || note.equals(""))
continue;
ContentValues cv = new ContentValues(1);
cv.put(MARK_NOTE, note);
db.update(TABLE_MARK, cv, "id=" + id, null);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* set unread counters for feeds and categories according to real amount
* of unread articles
*
* @return {@code true} if counters was successfully updated, {@code false} otherwise
*/
public void calculateCounters() {
long time = System.currentTimeMillis();
int total = 0;
Cursor c = null;
ContentValues cv = null;
if (!isDBAvailable())
return;
db.beginTransaction();
try {
cv = new ContentValues(1);
cv.put("unread", 0);
db.update(TABLE_FEEDS, cv, null, null);
db.update(TABLE_CATEGORIES, cv, null, null);
try {
// select feedId, count(*) from articles where isUnread>0 group by feedId
c = db.query(TABLE_ARTICLES, new String[] { "feedId", "count(*)" }, "isUnread>0", null, "feedId", null,
null, null);
// update feeds
while (c.moveToNext()) {
int feedId = c.getInt(0);
int unreadCount = c.getInt(1);
total += unreadCount;
cv.put("unread", unreadCount);
db.update(TABLE_FEEDS, cv, "_id=" + feedId, null);
}
} finally {
if (c != null && !c.isClosed())
c.close();
}
try {
// select categoryId, sum(unread) from feeds where categoryId >= 0 group by categoryId
c = db.query(TABLE_FEEDS, new String[] { "categoryId", "sum(unread)" }, "categoryId>=0", null,
"categoryId", null, null, null);
// update real categories
while (c.moveToNext()) {
int categoryId = c.getInt(0);
int unreadCount = c.getInt(1);
cv.put("unread", unreadCount);
db.update(TABLE_CATEGORIES, cv, "_id=" + categoryId, null);
}
} finally {
if (c != null && !c.isClosed())
c.close();
}
cv.put("unread", total);
db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_ALL, null);
cv.put("unread", getUnreadCount(Data.VCAT_FRESH, true));
db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_FRESH, null);
cv.put("unread", getUnreadCount(Data.VCAT_PUB, true));
db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_PUB, null);
cv.put("unread", getUnreadCount(Data.VCAT_STAR, true));
db.update(TABLE_CATEGORIES, cv, "_id=" + Data.VCAT_STAR, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Log.i(TAG, String.format("Fixed counters, total unread: %s (took %sms)", total,
(System.currentTimeMillis() - time)));
}
/**
* update amount of remote file references for article.
* normally should only be used with {@code null} ("unknown") and {@code 0} (no references)
*
* @param id
* ID of article, which should be updated
* @param filesCount
* new value for remote file references (may be {@code null})
*/
public void updateArticleCachedImages(int id, Integer filesCount) {
if (isDBAvailable()) {
ContentValues cv = new ContentValues(1);
if (filesCount == null) {
cv.putNull("cachedImages");
} else {
cv.put("cachedImages", filesCount);
}
db.update(TABLE_ARTICLES, cv, "_id=?", new String[] { String.valueOf(id) });
}
}
public void deleteCategories(boolean withVirtualCategories) {
String wherePart = "";
if (!withVirtualCategories)
wherePart = "_id > 0";
if (!isDBAvailable())
return;
db.delete(TABLE_CATEGORIES, wherePart, null);
}
/**
* delete all rows from feeds table
*/
public void deleteFeeds() {
if (!isDBAvailable())
return;
db.delete(TABLE_FEEDS, null, null);
}
/**
* delete articles and all its resources (e.g. remote files, labels etc.)
*
* @param whereClause
* the optional WHERE clause to apply when deleting.
* Passing null will delete all rows.
* @param whereArgs
* You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
*
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int safelyDeleteArticles(String whereClause, String[] whereArgs) {
int deletedCount = 0;
Collection<RemoteFile> rfs = getRemoteFilesForArticles(whereClause, whereArgs, true);
if (!rfs.isEmpty()) {
Set<Integer> rfIds = new HashSet<Integer>(rfs.size());
for (RemoteFile rf : rfs) {
rfIds.add(rf.id);
Controller.getInstance().getImageCache().getCacheFile(rf.url).delete();
}
deleteRemoteFiles(rfIds);
}
StringBuilder query = new StringBuilder();
// @formatter:off
query.append (
" articleId IN (" ).append(
" SELECT _id" ).append(
" FROM " ).append(
TABLE_ARTICLES ).append(
" WHERE " ).append(
whereClause ).append(
" )" );
// @formatter:on
db.beginTransaction();
try {
// first, delete article referencies from linking table to preserve foreign key constraint on the next step
db.delete(TABLE_REMOTEFILE2ARTICLE, query.toString(), whereArgs);
deletedCount = db.delete(TABLE_ARTICLES, whereClause, whereArgs); // TODO Foreign-key constraint failed from
// purgeOrphanedArticles() and
// safelyDeleteArticles()
purgeLabels();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return deletedCount;
}
/**
* Delete given amount of last updated articles from DB. Published and Starred articles are ignored
* so the configured limit is not an exact upper limit to the number of articles in the database.
*
* @param amountToPurge
* amount of articles to be purged
*/
public void purgeLastArticles(int amountToPurge) {
long time = System.currentTimeMillis();
if (isDBAvailable()) {
String query = "_id IN ( SELECT _id FROM " + TABLE_ARTICLES
+ " WHERE isPublished=0 AND isStarred=0 ORDER BY updateDate DESC LIMIT -1 OFFSET "
+ (Utils.ARTICLE_LIMIT - amountToPurge + ")");
safelyDeleteArticles(query, null);
}
Log.d(TAG, "purgeLastArticles took " + (System.currentTimeMillis() - time) + "ms");
}
/**
* delete articles, which belongs to non-existent feeds
*/
public void purgeOrphanedArticles() {
long time = System.currentTimeMillis();
if (isDBAvailable()) {
safelyDeleteArticles("feedId NOT IN (SELECT _id FROM " + TABLE_FEEDS + ")", null);
}
Log.d(TAG, "purgeOrphanedArticles took " + (System.currentTimeMillis() - time) + "ms");
}
private void purgeLabels() {
if (isDBAvailable()) {
// @formatter:off
String idsArticles = "SELECT a2l.articleId FROM "
+ TABLE_ARTICLES2LABELS + " AS a2l LEFT OUTER JOIN "
+ TABLE_ARTICLES + " AS a"
+ " ON a2l.articleId = a._id WHERE a._id IS null";
String idsFeeds = "SELECT a2l.labelId FROM "
+ TABLE_ARTICLES2LABELS + " AS a2l LEFT OUTER JOIN "
+ TABLE_FEEDS + " AS f"
+ " ON a2l.labelId = f._id WHERE f._id IS null";
// @formatter:on
db.delete(TABLE_ARTICLES2LABELS, "articleId IN(" + idsArticles + ")", null);
db.delete(TABLE_ARTICLES2LABELS, "labelId IN(" + idsFeeds + ")", null);
}
}
public void handlePurgeMarked(String idList, int minId, String vcat) {
if (isDBAvailable()) {
long time = System.currentTimeMillis();
ContentValues cv = new ContentValues(1);
cv.put(vcat, 0);
int count = db.update(TABLE_ARTICLES, cv,
vcat + ">0 AND _id>" + minId + " AND _id NOT IN (" + idList + ")", null);
Log.d(TAG, "Marked " + count + " articles " + vcat + "=0 (" + (System.currentTimeMillis() - time) + "ms)");
}
}
// *******| SELECT |*******************************************************************
/**
* get minimal ID of unread article, stored in DB
*
* @return minimal ID of unread article
*/
public int getMinUnreadId() {
int ret = 0;
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(TABLE_ARTICLES, new String[] { "min(_id)" }, "isUnread>0", null, null, null, null, null);
if (c.moveToFirst())
ret = c.getInt(0);
else
return 0;
} finally {
if (c != null && !c.isClosed())
c.close();
}
return ret;
}
/**
* get amount of articles stored in the DB
*
* @return amount of articles stored in the DB
*/
public int countArticles() {
int ret = -1;
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(TABLE_ARTICLES, new String[] { "count(*)" }, null, null, null, null, null, null);
if (c.moveToFirst())
ret = c.getInt(0);
} finally {
if (c != null && !c.isClosed())
c.close();
}
return ret;
}
// Takes about 2 to 6 ms on Motorola Milestone
public Article getArticle(int id) {
Article ret = null;
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(TABLE_ARTICLES, null, "_id=?", new String[] { id + "" }, null, null, null, null);
if (c.moveToFirst())
ret = handleArticleCursor(c);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null && !c.isClosed())
c.close();
}
return ret;
}
public Set<Label> getLabelsForArticle(int articleId) {
Cursor c = null;
try {
// @formatter:off
String sql = "SELECT f._id, f.title, 0 checked FROM " + TABLE_FEEDS + " f "
+ " WHERE f._id <= -11 AND"
+ " NOT EXISTS (SELECT * FROM " + TABLE_ARTICLES2LABELS + " a2l where f._id = a2l.labelId AND a2l.articleId = " + articleId + ")"
+ " UNION"
+ " SELECT f._id, f.title, 1 checked FROM " + TABLE_FEEDS + " f, " + TABLE_ARTICLES2LABELS + " a2l "
+ " WHERE f._id <= -11 AND f._id = a2l.labelId AND a2l.articleId = " + articleId;
// @formatter:on
if (!isDBAvailable())
return new HashSet<Label>();
c = db.rawQuery(sql, null);
Set<Label> ret = new HashSet<Label>(c.getCount());
while (c.moveToNext()) {
Label label = new Label();
label.id = c.getInt(0);
label.caption = c.getString(1);
label.checked = c.getInt(2) == 1;
ret.add(label);
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
public Feed getFeed(int id) {
Feed ret = new Feed();
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(TABLE_FEEDS, null, "_id=?", new String[] { id + "" }, null, null, null, null);
if (c.moveToFirst())
ret = handleFeedCursor(c);
} finally {
if (c != null && !c.isClosed())
c.close();
}
return ret;
}
public Category getCategory(int id) {
Category ret = new Category();
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(TABLE_CATEGORIES, null, "_id=?", new String[] { id + "" }, null, null, null, null);
if (c.moveToFirst())
ret = handleCategoryCursor(c);
} finally {
if (c != null && !c.isClosed())
c.close();
}
return ret;
}
public Set<Article> getUnreadArticles(int feedId) {
Cursor c = null;
try {
if (!isDBAvailable())
return new LinkedHashSet<Article>();
c = db.query(TABLE_ARTICLES, null, "feedId=? AND isUnread>0", new String[] { feedId + "" }, null, null,
null, null);
Set<Article> ret = new LinkedHashSet<Article>(c.getCount());
while (c.moveToNext()) {
ret.add(handleArticleCursor(c));
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
/**
* get the map of article IDs to its update date from DB
*
* @param selection
* A filter declaring which articles should be considered, formatted as an SQL WHERE clause (excluding
* the WHERE
* itself). Passing null will return all rows.
* @param selectionArgs
* You may include ?s in selection, which will be replaced by the values from selectionArgs, in order
* that they appear in the selection. The values will be bound as Strings.
* @return map of unread article IDs to its update date (may be {@code null})
*/
@SuppressLint("UseSparseArrays")
public Map<Integer, Long> getArticleIdUpdatedMap(String selection, String[] selectionArgs) {
Map<Integer, Long> unreadUpdated = null;
if (isDBAvailable()) {
Cursor c = null;
try {
c = db.query(TABLE_ARTICLES, new String[] { "_id", "updateDate" }, selection, selectionArgs, null,
null, null);
unreadUpdated = new HashMap<Integer, Long>(c.getCount());
while (c.moveToNext()) {
unreadUpdated.put(c.getInt(0), c.getLong(1));
}
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return unreadUpdated;
}
/**
* 0 - Uncategorized
* -1 - Special (e.g. Starred, Published, Archived, etc.) <- these are categories here o.O
* -2 - Labels
* -3 - All feeds, excluding virtual feeds (e.g. Labels and such)
* -4 - All feeds, including virtual feeds
*
* @param categoryId
* @return
*/
public Set<Feed> getFeeds(int categoryId) {
Cursor c = null;
try {
String where = null; // categoryId = 0
if (categoryId >= 0)
where = "categoryId=" + categoryId;
switch (categoryId) {
case -1:
where = "_id IN (0, -2, -3)";
break;
case -2:
where = "_id < -10";
break;
case -3:
where = "categoryId >= 0";
break;
case -4:
where = null;
break;
}
if (!isDBAvailable())
return new LinkedHashSet<Feed>();
c = db.query(TABLE_FEEDS, null, where, null, null, null, "UPPER(title) ASC");
Set<Feed> ret = new LinkedHashSet<Feed>(c.getCount());
while (c.moveToNext()) {
ret.add(handleFeedCursor(c));
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
public Set<Category> getVirtualCategories() {
Cursor c = null;
try {
if (!isDBAvailable())
return new LinkedHashSet<Category>();
c = db.query(TABLE_CATEGORIES, null, "_id<1", null, null, null, "_id ASC");
Set<Category> ret = new LinkedHashSet<Category>(c.getCount());
while (c.moveToNext()) {
ret.add(handleCategoryCursor(c));
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
public Set<Category> getAllCategories() {
Cursor c = null;
try {
if (!isDBAvailable())
return new LinkedHashSet<Category>();
c = db.query(TABLE_CATEGORIES, null, "_id>=0", null, null, null, "title ASC");
Set<Category> ret = new LinkedHashSet<Category>(c.getCount());
while (c.moveToNext()) {
ret.add(handleCategoryCursor(c));
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
public int getUnreadCountOld(int id, boolean isCat) {
int ret = 0;
if (isCat && id >= 0) { // Only do this for real categories for now
for (Feed f : getFeeds(id)) {
// Recurse into all feeds of this category and add the unread-count
ret += getUnreadCount(f.id, false);
}
} else {
// Read count for given feed
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(isCat ? TABLE_CATEGORIES : TABLE_FEEDS, new String[] { "unread" }, "_id=" + id, null,
null, null, null, null);
if (c.moveToFirst())
ret = c.getInt(0);
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return ret;
}
public int getUnreadCount(int id, boolean isCat) {
int ret = 0;
StringBuilder selection = new StringBuilder("isUnread>0");
String[] selectionArgs = new String[] { String.valueOf(id) };
if (isCat && id >= 0) {
// real categories
selection.append(" and feedId in (select _id from feeds where categoryId=?)");
} else {
if (id < 0) {
// virtual categories
switch (id) {
// All Articles
case Data.VCAT_ALL:
selectionArgs = null;
break;
// Fresh Articles
case Data.VCAT_FRESH:
selection.append(" and updateDate>?");
selectionArgs = new String[] { String.valueOf(new Date().getTime()
- Controller.getInstance().getFreshArticleMaxAge()) };
break;
// Published Articles
case Data.VCAT_PUB:
selection.append(" and isPublished>0");
selectionArgs = null;
break;
// Starred Articles
case Data.VCAT_STAR:
selection.append(" and isStarred>0");
selectionArgs = null;
break;
default:
// Probably a label...
selection.append(" and feedId=?");
}
} else {
// feeds
selection.append(" and feedId=?");
}
}
// Read count for given feed
Cursor c = null;
try {
if (!isDBAvailable())
return ret;
c = db.query(TABLE_ARTICLES, new String[] { "count(*)" }, selection.toString(), selectionArgs, null, null,
null, null);
if (c.moveToFirst())
ret = c.getInt(0);
} finally {
if (c != null && !c.isClosed())
c.close();
}
return ret;
}
@SuppressLint("UseSparseArrays")
public Map<Integer, String> getMarked(String mark, int status) {
Cursor c = null;
try {
if (!isDBAvailable())
return new HashMap<Integer, String>();
c = db.query(TABLE_MARK, new String[] { "id", MARK_NOTE }, mark + "=" + status, null, null, null, null,
null);
Map<Integer, String> ret = new HashMap<Integer, String>(c.getCount());
while (c.moveToNext()) {
ret.put(c.getInt(0), c.getString(1));
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
/**
* remove specified mark in the temporary mark table for specified
* articles and then cleanup this table
*
* @param ids
* article IDs, which mark should be reseted
* @param mark
* article mark to be reseted
*/
public void setMarked(Map<Integer, String> ids, String mark) {
if (!isDBAvailable())
return;
db.beginTransaction();
try {
ContentValues cv = new ContentValues(1);
for (String idList : StringSupport.convertListToString(ids.keySet(), 1000)) {
cv.putNull(mark);
db.update(TABLE_MARK, cv, "id IN(" + idList + ")", null);
db.delete(TABLE_MARK, "isUnread IS null AND isStarred IS null AND isPublished IS null", null);
}
// Insert notes afterwards and only if given note is not null
cv = new ContentValues(1);
for (Integer id : ids.keySet()) {
String note = ids.get(id);
if (note == null || note.equals(""))
continue;
cv.put(MARK_NOTE, note);
db.update(TABLE_MARK, cv, "id=" + id, null);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
// *******************************************
private static Article handleArticleCursor(Cursor c) {
// @formatter:off
Article ret = new Article(
c.getInt(0), // _id
c.getInt(1), // feedId
c.getString(2), // title
(c.getInt(3) != 0), // isUnread
c.getString(4), // articleUrl
c.getString(5), // articleCommentUrl
new Date(c.getLong(6)), // updateDate
c.getString(7), // content
parseAttachments(c.getString(8)), // attachments
(c.getInt(9) != 0), // isStarred
(c.getInt(10) != 0), // isPublished
c.getInt(11), // cachedImages,
parseArticleLabels(c.getString(12)),// Labels
c.getString(13) // Author
);
// @formatter:on
try {
ret.cachedImages = c.getInt(11);
} catch (Exception e) {
// skip
}
return ret;
}
private static Feed handleFeedCursor(Cursor c) {
// @formatter:off
Feed ret = new Feed(
c.getInt(0), // _id
c.getInt(1), // categoryId
c.getString(2), // title
c.getString(3), // url
c.getInt(4)); // unread
// @formatter:on
return ret;
}
private static Category handleCategoryCursor(Cursor c) {
// @formatter:off
Category ret = new Category(
c.getInt(0), // _id
c.getString(1), // title
c.getInt(2)); // unread
// @formatter:on
return ret;
}
private static RemoteFile handleRemoteFileCursor(Cursor c) {
// @formatter:off
RemoteFile ret = new RemoteFile(
c.getInt(0), // id
c.getString(1), // url
c.getInt (2), // length
c.getString (3), // ext
new Date(c.getLong(4)), // updateDate
(c.getInt (5) != 0) // cached
);
// @formatter:on
return ret;
}
private static Set<String> parseAttachments(String att) {
Set<String> ret = new LinkedHashSet<String>();
if (att == null)
return ret;
for (String s : att.split(";")) {
ret.add(s);
}
return ret;
}
/*
* Parse labels from string of the form "label;;label;;...;;label" where each label is of the following format:
* "caption;forground;background"
*/
private static Set<Label> parseArticleLabels(String labelStr) {
Set<Label> ret = new LinkedHashSet<Label>();
if (labelStr == null)
return ret;
int i = 0;
for (String s : labelStr.split("---")) {
String[] l = s.split(";");
if (l.length > 0) {
i++;
Label label = new Label();
label.id = i;
label.checked = true;
label.caption = l[0];
if (l.length > 1 && l[1].startsWith("#"))
label.foregroundColor = l[1];
if (l.length > 2 && l[1].startsWith("#"))
label.backgroundColor = l[2];
ret.add(label);
}
}
return ret;
}
public ArrayList<Article> queryArticlesForImagecache() {
if (!isDBAvailable())
return null;
Cursor c = null;
try {
c = db.query(TABLE_ARTICLES, new String[] { "_id", "content", "attachments" },
"cachedImages IS NULL AND isUnread>0", null, null, null, null, "1000");
ArrayList<Article> ret = new ArrayList<Article>(c.getCount());
while (c.moveToNext()) {
Article a = new Article();
a.id = c.getInt(0);
a.content = c.getString(1);
a.attachments = parseAttachments(c.getString(2));
ret.add(a);
}
return ret;
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
/**
* insert given remote files into DB and link them with given article
*
* @param articleId
* "parent" article
* @param fileUrls
* array of remote file URLs
*/
public void insertArticleFiles(int articleId, String[] fileUrls) {
if (isDBAvailable()) {
db.beginTransaction();
try {
for (String url : fileUrls) {
long remotefileId = insertRemoteFile(url);
if (remotefileId != 0)
insertRemoteFile2Article(remotefileId, articleId);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
}
/**
* get the DB object representing remote file by its URL
*
* @param url
* remote file URL
*
* @return remote file object from DB
*/
public RemoteFile getRemoteFile(String url) {
RemoteFile rf = null;
if (isDBAvailable()) {
Cursor c = null;
try {
c = db.query(TABLE_REMOTEFILES, null, "url=?", new String[] { url }, null, null, null, null);
if (c.moveToFirst())
rf = handleRemoteFileCursor(c);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return rf;
}
/**
* get remote files for given article
*
* @param articleId
* article, which remote files should be found
*
* @return collection of remote file objects from DB or {@code null}
*/
public Collection<RemoteFile> getRemoteFiles(int articleId) {
ArrayList<RemoteFile> rfs = null;
if (isDBAvailable()) {
Cursor c = null;
try {
c = db.rawQuery(" SELECT r.*"
// @formatter:off
+ " FROM "
+ TABLE_REMOTEFILES + " r,"
+ TABLE_REMOTEFILE2ARTICLE + " m, "
+ TABLE_ARTICLES + " a"
+ " WHERE m.remotefileId=r.id"
+ " AND m.articleId=a._id"
+ " AND a._id=?",
// @formatter:on
new String[] { String.valueOf(articleId) });
rfs = new ArrayList<RemoteFile>(c.getCount());
while (c.moveToNext()) {
rfs.add(handleRemoteFileCursor(c));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return rfs;
}
/**
* get remote files for given articles
*
* @param whereClause
* the WHERE clause to apply when selecting.
* @param whereArgs
* You may include ?s in the where clause, which
* will be replaced by the values from whereArgs. The values
* will be bound as Strings.
*
* @param uniqOnly
* if set to {@code true}, then only remote files, which are referenced by given articles only will be
* returned, otherwise all remote files referenced by given articles will be found (even those, which are
* referenced also by some other articles)
*
* @return collection of remote file objects from DB or {@code null}
*/
public Collection<RemoteFile> getRemoteFilesForArticles(String whereClause, String[] whereArgs, boolean uniqOnly) {
ArrayList<RemoteFile> rfs = null;
if (isDBAvailable()) {
Cursor c = null;
try {
StringBuilder uniqRestriction = new StringBuilder();
String[] queryArgs = whereArgs;
if (uniqOnly) {
// @formatter:off
uniqRestriction.append (
" AND m.remotefileId NOT IN (" ).append(
" SELECT remotefileId" ).append(
" FROM " ).append(
TABLE_REMOTEFILE2ARTICLE ).append(
" WHERE remotefileId IN (" ).append(
" SELECT remotefileId" ).append(
" FROM " ).append(
TABLE_REMOTEFILE2ARTICLE ).append(
" WHERE articleId IN (" ).append(
" SELECT _id" ).append(
" FROM " ).append(
TABLE_ARTICLES ).append(
" WHERE " ).append(
whereClause ).append(
" )" ).append(
" GROUP BY remotefileId)" ).append(
" AND articleId NOT IN (" ).append(
" SELECT _id" ).append(
" FROM " ).append(
TABLE_ARTICLES ).append(
" WHERE " ).append(
whereClause ).append(
" )" ).append(
" GROUP by remotefileId)" );
// @formatter:on
// because we are using whereClause twice in uniqRestriction, then we should also extend queryArgs,
// which will be used in query
if (whereArgs != null) {
int initialArgLength = whereArgs.length;
queryArgs = new String[initialArgLength * 3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < initialArgLength; j++)
queryArgs[i * initialArgLength + j] = whereArgs[j];
}
}
}
StringBuilder query = new StringBuilder();
// @formatter:off
query.append (
" SELECT r.*" ).append(
" FROM " ).append(
TABLE_REMOTEFILES + " r," ).append(
TABLE_REMOTEFILE2ARTICLE + " m, " ).append(
TABLE_ARTICLES + " a" ).append(
" WHERE m.remotefileId=r.id" ).append(
" AND m.articleId=a._id" ).append(
" AND a._id IN (" ).append(
" SELECT _id FROM " ).append(
TABLE_ARTICLES ).append(
" WHERE " ).append(
whereClause ).append(
" )" ).append(
uniqRestriction ).append(
" GROUP BY r.id" );
// @formatter:on
long time = System.currentTimeMillis();
c = db.rawQuery(query.toString(), queryArgs);
rfs = new ArrayList<RemoteFile>();
while (c.moveToNext()) {
rfs.add(handleRemoteFileCursor(c));
}
Log.d(TAG, "Query in getRemoteFilesForArticles took " + (System.currentTimeMillis() - time)
+ "ms... (remotefiles: " + rfs.size() + ")");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return rfs;
}
/**
* mark given remote file as cached/uncached and optionally specify it's file size
*
* @param url
* remote file URL
* @param cached
* the cached flag
* @param size
* file size may be {@code null}, if so, then it will not be updated in DB
*/
public void markRemoteFileCached(String url, boolean cached, Long size) {
if (isDBAvailable()) {
db.beginTransaction();
try {
ContentValues cv = new ContentValues(2);
cv.put("cached", cached);
if (size != null) {
cv.put("length", size);
}
db.update(TABLE_REMOTEFILES, cv, "url=?", new String[] { url });
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
}
/**
* mark remote files with given IDs as non cached (cached=0)
*
* @param rfIds
* IDs of remote files to be marked as non-cached
*/
public void markRemoteFilesNonCached(Collection<Integer> rfIds) {
if (isDBAvailable()) {
db.beginTransaction();
try {
ContentValues cv = new ContentValues(1);
cv.put("cached", 0);
for (String ids : StringSupport.convertListToString(rfIds, 1000)) {
db.update(TABLE_REMOTEFILES, cv, "id in (" + ids + ")", null);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
}
/**
* get summary length of remote files, which are cached
*
* @return summary length of remote files
*/
public long getCachedFilesSize() {
long ret = 0;
if (isDBAvailable()) {
Cursor c = null;
try {
c = db.query(TABLE_REMOTEFILES, new String[] { "SUM(length)" }, "cached=1", null, null, null, null);
if (c.moveToFirst())
ret = c.getLong(0);
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return ret;
}
/**
* get remote files which should be deleted to free given amount of space
*
* @param spaceToBeFreed
* amount of space (summary file size) to be freed
*
* @return collection of remote files, which can be deleted
* to free given amount of space
*/
public Collection<RemoteFile> getUncacheFiles(long spaceToBeFreed) {
ArrayList<RemoteFile> rfs = new ArrayList<RemoteFile>();
if (isDBAvailable()) {
Cursor c = null;
try {
c = db.query("remotefile_sequence", null, "cached = 1", null, null, null, "ord");
long spaceToFree = spaceToBeFreed;
while (spaceToFree > 0 && c.moveToNext()) {
RemoteFile rf = handleRemoteFileCursor(c);
spaceToFree -= rf.length;
rfs.add(rf);
}
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
return rfs;
}
/**
* delete remote files with given IDs
*
* @param idList
* set of remote file IDs, which should be deleted
*
* @return the number of deleted rows
*/
public int deleteRemoteFiles(Set<Integer> idList) {
int deletedCount = 0;
if (isDBAvailable() && idList != null && !idList.isEmpty()) {
for (String ids : StringSupport.convertListToString(idList, 400)) {
deletedCount += db.delete(TABLE_REMOTEFILES, "id IN (" + ids + ")", null);
}
}
return deletedCount;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.controllers;
import android.app.Activity;
public class ProgressBarManager {
protected static final String TAG = ProgressBarManager.class.getSimpleName();
private static ProgressBarManager instance = null;
private int progressIndeterminateCount = 0;
// Singleton
private ProgressBarManager() {
}
public static ProgressBarManager getInstance() {
if (instance == null) {
synchronized (ProgressBarManager.class) {
if (instance == null) {
instance = new ProgressBarManager();
}
}
}
return instance;
}
public void addProgress(Activity activity) {
progressIndeterminateCount++;
setIndeterminateVisibility(activity);
}
public void removeProgress(Activity activity) {
progressIndeterminateCount--;
if (progressIndeterminateCount <= 0)
progressIndeterminateCount = 0;
setIndeterminateVisibility(activity);
}
public void resetProgress(Activity activity) {
progressIndeterminateCount = 0;
setIndeterminateVisibility(activity);
}
public void setIndeterminateVisibility(Activity activity) {
boolean visible = (progressIndeterminateCount > 0);
activity.setProgressBarIndeterminateVisibility(visible);
if (!visible) {
activity.setProgress(0);
activity.setProgressBarVisibility(false);
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.controllers;
import java.util.ArrayList;
import java.util.List;
import org.ttrssreader.gui.interfaces.IDataChangedListener;
import android.os.Handler;
import android.os.Message;
public class UpdateController {
protected static final String TAG = UpdateController.class.getSimpleName();
private static UpdateController instance = null;
private static List<IDataChangedListener> listeners = new ArrayList<IDataChangedListener>();
// Singleton
private UpdateController() {
}
private static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
for (IDataChangedListener listener : listeners) {
listener.dataChanged();
}
}
};
public static UpdateController getInstance() {
if (instance == null) {
synchronized (UpdateController.class) {
if (instance == null) {
instance = new UpdateController();
}
}
}
return instance;
}
public void registerActivity(IDataChangedListener listener) {
listeners.add(listener);
}
public void unregisterActivity(IDataChangedListener listener) {
listeners.remove(listener);
}
public void notifyListeners() {
handler.sendEmptyMessage(0);
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.controllers;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import org.stringtemplate.v4.ST;
import org.ttrssreader.R;
import org.ttrssreader.gui.CategoryActivity;
import org.ttrssreader.gui.FeedHeadlineActivity;
import org.ttrssreader.gui.MenuActivity;
import org.ttrssreader.imageCache.ImageCache;
import org.ttrssreader.net.JSONConnector;
import org.ttrssreader.net.JavaJSONConnector;
import org.ttrssreader.net.deprecated.ApacheJSONConnector;
import org.ttrssreader.preferences.Constants;
import org.ttrssreader.utils.AsyncTask;
import org.ttrssreader.utils.SSLUtils;
import org.ttrssreader.utils.Utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
/**
* Not entirely sure why this is called the "Controller". Actually, in terms of MVC, it isn't the controller. There
* isn't one in here but it's called like that and I don't have a better name so we stay with it.
*/
public class Controller implements OnSharedPreferenceChangeListener {
protected static final String TAG = Controller.class.getSimpleName();
public final static String JSON_END_URL = "api/index.php";
private final static char TEMPLATE_DELIMITER_START = '$';
private final static char TEMPLATE_DELIMITER_END = '$';
private static final String MARKER_ALIGN = "TEXT_ALIGN_MARKER";
private static final String MARKER_CACHE_DIR = "CACHE_DIR_MARKER";
private static final String MARKER_CACHED_IMAGES = "CACHED_IMAGES_MARKER";
private static final String MARKER_JS = "JS_MARKER";
private static final String MARKER_THEME = "THEME_MARKER";
private static final String MARKER_LANG = "LANG_MARKER";
private static final String MARKER_TOP_NAV = "TOP_NAVIGATION_MARKER";
private static final String MARKER_CONTENT = "CONTENT_MARKER";
private static final String MARKER_BOTTOM_NAV = "BOTTOM_NAVIGATION_MARKER";
public static final int THEME_DARK = 1;
public static final int THEME_LIGHT = 2;
public static final int THEME_BLACK = 3;
public static final int THEME_WHITE = 4;
private Context context;
private WifiManager wifiManager;
private JSONConnector ttrssConnector;
private static final Object lockConnector = new Object();
private ImageCache imageCache = null;
private boolean isHeadless = false;
private static final Object lockImageCache = new Object();
private static Boolean initialized = false;
private static final Object lockInitialize = new Object();
private SharedPreferences prefs = null;
private static boolean preferencesChanged = false;
private String url = null;
private String username = null;
private String password = null;
private String httpUsername = null;
private String httpPassword = null;
private Boolean useHttpAuth = null;
private Boolean trustAllSsl = null;
private Boolean trustAllHosts = null;
private Boolean useOldConnector;
private Boolean useKeystore = null;
private String keystorePassword = null;
private Boolean useOfALazyServer = null;
private Boolean openUrlEmptyArticle = null;
private Boolean useVolumeKeys = null;
private Boolean loadImages = null;
private Boolean invertBrowsing = null;
private Boolean goBackAfterMarkAllRead = null;
private Boolean hideActionbar = null;
private Boolean workOffline = null;
private Boolean allowTabletLayout = null;
private Integer textZoom = null;
private Boolean supportZoomControls = null;
private Boolean allowHyphenation = null;
private String hyphenationLanguage = null;
private Boolean showVirtual = null;
private Integer showButtonsMode = null;
private Boolean onlyUnread = null;
private Boolean onlyDisplayCachedImages = null;
private Boolean invertSortArticlelist = null;
private Boolean invertSortFeedscats = null;
private Boolean alignFlushLeft = null;
private Boolean dateTimeSystem = null;
private String dateString = null;
private String timeString = null;
private String dateTimeString = null;
private Integer theme = null;
private String saveAttachment = null;
private String cacheFolder = null;
private Integer cacheFolderMaxSize = null;
private Integer cacheImageMaxSize = null;
private Integer cacheImageMinSize = null;
private Boolean deleteDbScheduled = null;
private Boolean cacheImagesOnStartup = null;
private Boolean cacheImagesOnlyWifi = null;
private Boolean onlyUseWifi = null;
private Boolean noCrashreports = null;
private Boolean noCrashreportsUntilUpdate = null;
private Long appVersionCheckTime = null;
private Integer appLatestVersion = null;
private String lastVersionRun = null;
private Boolean newInstallation = false;
private Long freshArticleMaxAge = null;
private Long freshArticleMaxAgeDate = null;
private Integer sinceId = null;
private Long lastSync = null;
private Long lastCleanup = null;
private Boolean lowMemory = false;
public volatile Set<Integer> lastOpenedFeeds = new HashSet<Integer>();
public volatile Set<Integer> lastOpenedArticles = new HashSet<Integer>();
// Article-View-Stuff
public static String htmlTemplate = "";
private static final Object lockHtmlTemplate = new Object();
public static int relSwipeMinDistance;
public static int relSwipeMaxOffPath;
public static int relSwipteThresholdVelocity;
public static int displayHeight;
public static int displayWidth;
public static boolean isTablet = false;
private boolean scheduledRestart = false;
// Singleton (see http://stackoverflow.com/a/11165926)
private Controller() {
}
private static class InstanceHolder {
private static final Controller instance = new Controller();
}
public static Controller getInstance() {
return InstanceHolder.instance;
}
public void checkAndInitializeController(final Context context, final Display display) {
synchronized (lockInitialize) {
this.context = context;
this.wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!initialized) {
initializeController(display);
initialized = true;
}
}
}
private void initializeController(final Display display) {
prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Initially read absolutely necessary preferences:
sizeVerticalCategory = prefs.getInt(SIZE_VERTICAL_CATEGORY, -1);
sizeHorizontalCategory = prefs.getInt(SIZE_HORIZONTAL_CATEGORY, -1);
sizeVerticalHeadline = prefs.getInt(SIZE_VERTICAL_HEADLINE, -1);
sizeHorizontalHeadline = prefs.getInt(SIZE_HORIZONTAL_HEADLINE, -1);
// Check for new installation
if (!prefs.contains(Constants.URL) && !prefs.contains(Constants.LAST_VERSION_RUN)) {
newInstallation = true;
}
// Attempt to initialize some stuff in a background-thread to reduce loading time. Start a login-request
// separately because this takes some time. Also initialize SSL-Stuff since the login needs this.
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
if (Controller.getInstance().trustAllHosts()) {
// Ignore if Certificate matches host:
SSLUtils.trustAllHost();
}
if (Controller.getInstance().useKeystore()) {
// Trust certificates from keystore:
SSLUtils.initPrivateKeystore(Controller.getInstance().getKeystorePassword());
} else if (Controller.getInstance().trustAllSsl()) {
// Trust all certificates:
SSLUtils.trustAllCert();
} else {
// Normal certificate-checks:
SSLUtils.initSslSocketFactory(null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
// This will be accessed when displaying an article or starting the imageCache. When caching it is done
// anyway so we can just do it in background and the ImageCache starts once it is done.
getImageCache();
// Only need once we are displaying the feed-list or an article...
refreshDisplayMetrics(display);
// Loads all article and webview related resources
reloadTheme();
enableHttpResponseCache(context);
return null;
}
}.execute();
}
private void reloadTheme() {
// Article-Prefetch-Stuff from Raw-Ressources and System
ST htmlTmpl = new ST(context.getResources().getString(R.string.HTML_TEMPLATE), TEMPLATE_DELIMITER_START,
TEMPLATE_DELIMITER_END);
// Replace alignment-marker with the requested layout, align:left or justified
String replaceAlign;
if (alignFlushLeft()) {
replaceAlign = context.getResources().getString(R.string.ALIGN_LEFT);
} else {
replaceAlign = context.getResources().getString(R.string.ALIGN_JUSTIFY);
}
String javascript = "";
String lang = "";
if (allowHyphenation()) {
ST javascriptST = new ST(context.getResources().getString(R.string.JAVASCRIPT_HYPHENATION_TEMPLATE),
TEMPLATE_DELIMITER_START, TEMPLATE_DELIMITER_END);
lang = hyphenationLanguage();
javascriptST.add(MARKER_LANG, lang);
javascript = javascriptST.render();
}
String buttons = "";
if (showButtonsMode() == Constants.SHOW_BUTTONS_MODE_HTML)
buttons = context.getResources().getString(R.string.BOTTOM_NAVIGATION_TEMPLATE);
htmlTmpl.add(MARKER_ALIGN, replaceAlign);
htmlTmpl.add(MARKER_THEME, context.getResources().getString(getThemeHTML()));
htmlTmpl.add(MARKER_CACHE_DIR, cacheFolder());
htmlTmpl.add(MARKER_CACHED_IMAGES, context.getResources().getString(R.string.CACHED_IMAGES_TEMPLATE));
htmlTmpl.add(MARKER_JS, javascript);
htmlTmpl.add(MARKER_LANG, lang);
htmlTmpl.add(MARKER_TOP_NAV, context.getResources().getString(R.string.TOP_NAVIGATION_TEMPLATE));
htmlTmpl.add(MARKER_CONTENT, context.getResources().getString(R.string.CONTENT_TEMPLATE));
htmlTmpl.add(MARKER_BOTTOM_NAV, buttons);
// This is only needed once an article is displayed
synchronized (lockHtmlTemplate) {
htmlTemplate = htmlTmpl.render();
}
}
/**
* Enables HTTP response caching on devices that support it, see
* http://android-developers.blogspot.de/2011/09/androids-http-clients.html
*
* @param context
*/
private void enableHttpResponseCache(Context context) {
try {
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
File httpCacheDir = new File(context.getCacheDir(), "http");
Class.forName("android.net.http.HttpResponseCache").getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
} catch (Exception httpResponseCacheNotAvailable) {
}
}
public static void refreshDisplayMetrics(Display display) {
if (display == null)
return;
DisplayMetrics dm = new DisplayMetrics();
display.getMetrics(dm);
int SWIPE_MIN_DISTANCE = 120;
int SWIPE_MAX_OFF_PATH = 250;
int SWIPE_THRESHOLD_VELOCITY = 200;
relSwipeMinDistance = (int) (SWIPE_MIN_DISTANCE * dm.densityDpi / 160.0f);
relSwipeMaxOffPath = (int) (SWIPE_MAX_OFF_PATH * dm.densityDpi / 160.0f);
relSwipteThresholdVelocity = (int) (SWIPE_THRESHOLD_VELOCITY * dm.densityDpi / 160.0f);
displayHeight = dm.heightPixels;
displayWidth = dm.widthPixels;
}
// ******* CONNECTION-Options ****************************
public URI uri() throws URISyntaxException {
return new URI(hostname());
}
public URL url() throws MalformedURLException {
return new URL(hostname());
}
public String hostname() {
// Load from Wifi-Preferences:
String key = getStringWithSSID(Constants.URL, getCurrentSSID(wifiManager));
if (prefs.contains(key))
url = prefs.getString(key, Constants.URL_DEFAULT);
else
url = prefs.getString(Constants.URL, Constants.URL_DEFAULT);
if (!url.endsWith(JSON_END_URL)) {
if (!url.endsWith("/")) {
url += "/";
}
url += JSON_END_URL;
}
return url;
}
public String username() {
// Load from Wifi-Preferences:
String key = getStringWithSSID(Constants.USERNAME, getCurrentSSID(wifiManager));
if (prefs.contains(key))
username = prefs.getString(key, Constants.EMPTY);
else
username = prefs.getString(Constants.USERNAME, Constants.EMPTY);
return username;
}
public String password() {
// Load from Wifi-Preferences:
String key = getStringWithSSID(Constants.PASSWORD, getCurrentSSID(wifiManager));
if (prefs.contains(key))
password = prefs.getString(key, Constants.EMPTY);
else
password = prefs.getString(Constants.PASSWORD, Constants.EMPTY);
return password;
}
public boolean useHttpAuth() {
if (useHttpAuth == null)
useHttpAuth = prefs.getBoolean(Constants.USE_HTTP_AUTH, Constants.USE_HTTP_AUTH_DEFAULT);
return useHttpAuth;
}
public String httpUsername() {
if (httpUsername == null)
httpUsername = prefs.getString(Constants.HTTP_USERNAME, Constants.EMPTY);
return httpUsername;
}
public String httpPassword() {
if (httpPassword == null)
httpPassword = prefs.getString(Constants.HTTP_PASSWORD, Constants.EMPTY);
return httpPassword;
}
public boolean useKeystore() {
if (useKeystore == null)
useKeystore = prefs.getBoolean(Constants.USE_KEYSTORE, Constants.USE_KEYSTORE_DEFAULT);
return useKeystore;
}
public boolean trustAllSsl() {
if (trustAllSsl == null)
trustAllSsl = prefs.getBoolean(Constants.TRUST_ALL_SSL, Constants.TRUST_ALL_SSL_DEFAULT);
return trustAllSsl;
}
public boolean trustAllHosts() {
if (trustAllHosts == null)
trustAllHosts = prefs.getBoolean(Constants.TRUST_ALL_HOSTS, Constants.TRUST_ALL_HOSTS_DEFAULT);
return trustAllHosts;
}
private boolean useOldConnector() {
if (useOldConnector == null)
useOldConnector = prefs.getBoolean(Constants.USE_OLD_CONNECTOR, Constants.USE_OLD_CONNECTOR_DEFAULT);
return useOldConnector;
}
public JSONConnector getConnector() {
// Initialized inside initializeController();
if (ttrssConnector != null) {
return ttrssConnector;
} else {
synchronized (lockConnector) {
if (ttrssConnector == null) {
if (useOldConnector()) {
ttrssConnector = new ApacheJSONConnector(context);
} else {
ttrssConnector = new JavaJSONConnector(context);
}
}
}
if (ttrssConnector != null)
return ttrssConnector;
else
throw new RuntimeException("Connector could not be initialized.");
}
}
public ImageCache getImageCache() {
return getImageCache(true);
}
public ImageCache getImageCache(boolean wait) {
if (imageCache == null && wait) {
synchronized (lockImageCache) {
if (imageCache == null) {
imageCache = new ImageCache(1000, cacheFolder());
if (!imageCache.enableDiskCache()) {
imageCache = null;
}
}
}
}
return imageCache;
}
public String getKeystorePassword() {
if (keystorePassword == null)
keystorePassword = prefs.getString(Constants.KEYSTORE_PASSWORD, Constants.EMPTY);
return keystorePassword;
}
public boolean isHeadless() {
return isHeadless;
}
public void setHeadless(boolean isHeadless) {
this.isHeadless = isHeadless;
}
// ******* USAGE-Options ****************************
public boolean lazyServer() {
// Load from Wifi-Preferences:
String key = getStringWithSSID(Constants.USE_OF_A_LAZY_SERVER, getCurrentSSID(wifiManager));
if (prefs.contains(key))
useOfALazyServer = prefs.getBoolean(key, Constants.USE_OF_A_LAZY_SERVER_DEFAULT);
else
useOfALazyServer = prefs.getBoolean(Constants.USE_OF_A_LAZY_SERVER, Constants.USE_OF_A_LAZY_SERVER_DEFAULT);
return useOfALazyServer;
}
public boolean openUrlEmptyArticle() {
if (openUrlEmptyArticle == null)
openUrlEmptyArticle = prefs.getBoolean(Constants.OPEN_URL_EMPTY_ARTICLE,
Constants.OPEN_URL_EMPTY_ARTICLE_DEFAULT);
return openUrlEmptyArticle;
}
public void setOpenUrlEmptyArticle(boolean openUrlEmptyArticle) {
put(Constants.OPEN_URL_EMPTY_ARTICLE, openUrlEmptyArticle);
this.openUrlEmptyArticle = openUrlEmptyArticle;
}
public boolean useVolumeKeys() {
if (useVolumeKeys == null)
useVolumeKeys = prefs.getBoolean(Constants.USE_VOLUME_KEYS, Constants.USE_VOLUME_KEYS_DEFAULT);
return useVolumeKeys;
}
public void setUseVolumeKeys(boolean useVolumeKeys) {
put(Constants.USE_VOLUME_KEYS, useVolumeKeys);
this.useVolumeKeys = useVolumeKeys;
}
public boolean loadImages() {
if (loadImages == null)
loadImages = prefs.getBoolean(Constants.LOAD_IMAGES, Constants.LOAD_IMAGES_DEFAULT);
return loadImages;
}
public void setLoadImages(boolean loadImages) {
put(Constants.LOAD_IMAGES, loadImages);
this.loadImages = loadImages;
}
public boolean invertBrowsing() {
if (invertBrowsing == null)
invertBrowsing = prefs.getBoolean(Constants.INVERT_BROWSING, Constants.INVERT_BROWSING_DEFAULT);
return invertBrowsing;
}
public void setInvertBrowsing(boolean invertBrowsing) {
put(Constants.INVERT_BROWSING, invertBrowsing);
this.invertBrowsing = invertBrowsing;
}
public boolean workOffline() {
if (workOffline == null)
workOffline = prefs.getBoolean(Constants.WORK_OFFLINE, Constants.WORK_OFFLINE_DEFAULT);
return workOffline;
}
public void setWorkOffline(boolean workOffline) {
put(Constants.WORK_OFFLINE, workOffline);
this.workOffline = workOffline;
}
public boolean goBackAfterMarkAllRead() {
if (goBackAfterMarkAllRead == null)
goBackAfterMarkAllRead = prefs.getBoolean(Constants.GO_BACK_AFTER_MARK_ALL_READ,
Constants.GO_BACK_AFTER_MARK_ALL_READ_DEFAULT);
return goBackAfterMarkAllRead;
}
public void setGoBackAfterMarkAllRead(boolean goBackAfterMarkAllRead) {
put(Constants.GO_BACK_AFTER_MARK_ALL_READ, goBackAfterMarkAllRead);
this.goBackAfterMarkAllRead = goBackAfterMarkAllRead;
}
public boolean hideActionbar() {
if (hideActionbar == null)
hideActionbar = prefs.getBoolean(Constants.HIDE_ACTIONBAR, Constants.HIDE_ACTIONBAR_DEFAULT);
return hideActionbar;
}
public void setHideActionbar(boolean hideActionbar) {
put(Constants.HIDE_ACTIONBAR, hideActionbar);
this.hideActionbar = hideActionbar;
}
public boolean allowTabletLayout() {
if (allowTabletLayout == null)
allowTabletLayout = prefs.getBoolean(Constants.ALLOW_TABLET_LAYOUT, Constants.ALLOW_TABLET_LAYOUT_DEFAULT);
return allowTabletLayout;
}
public void setAllowTabletLayout(boolean allowTabletLayout) {
put(Constants.ALLOW_TABLET_LAYOUT, allowTabletLayout);
this.allowTabletLayout = allowTabletLayout;
}
// ******* DISPLAY-Options ****************************
public int textZoom() {
if (textZoom == null)
textZoom = prefs.getInt(Constants.TEXT_ZOOM, Constants.TEXT_ZOOM_DEFAULT);
return textZoom;
}
public void setTextZoom(int textZoom) {
put(Constants.TEXT_ZOOM, textZoom);
this.textZoom = textZoom;
}
public boolean supportZoomControls() {
if (supportZoomControls == null)
supportZoomControls = prefs.getBoolean(Constants.SUPPORT_ZOOM_CONTROLS,
Constants.SUPPORT_ZOOM_CONTROLS_DEFAULT);
return supportZoomControls;
}
public void setSupportZoomControls(boolean supportZoomControls) {
put(Constants.SUPPORT_ZOOM_CONTROLS, supportZoomControls);
this.supportZoomControls = supportZoomControls;
}
public boolean allowHyphenation() {
if (allowHyphenation == null)
allowHyphenation = prefs.getBoolean(Constants.ALLOW_HYPHENATION, Constants.ALLOW_HYPHENATION_DEFAULT);
return allowHyphenation;
}
public void setAllowHyphenation(boolean allowHyphenation) {
put(Constants.ALLOW_HYPHENATION, allowHyphenation);
this.allowHyphenation = allowHyphenation;
}
public String hyphenationLanguage() {
if (hyphenationLanguage == null)
hyphenationLanguage = prefs.getString(Constants.HYPHENATION_LANGUAGE,
Constants.HYPHENATION_LANGUAGE_DEFAULT);
return hyphenationLanguage;
}
public void setHyphenationLanguage(String hyphenationLanguage) {
put(Constants.HYPHENATION_LANGUAGE, hyphenationLanguage);
this.hyphenationLanguage = hyphenationLanguage;
}
public boolean showVirtual() {
if (showVirtual == null)
showVirtual = prefs.getBoolean(Constants.SHOW_VIRTUAL, Constants.SHOW_VIRTUAL_DEFAULT);
return showVirtual;
}
public void setDisplayVirtuals(boolean displayVirtuals) {
put(Constants.SHOW_VIRTUAL, displayVirtuals);
this.showVirtual = displayVirtuals;
}
public Integer showButtonsMode() {
if (showButtonsMode == null)
showButtonsMode = Integer.parseInt(prefs.getString(Constants.SHOW_BUTTONS_MODE,
Constants.SHOW_BUTTONS_MODE_DEFAULT));
return showButtonsMode;
}
public void setShowButtonsMode(Integer showButtonsMode) {
put(Constants.SHOW_BUTTONS_MODE, showButtonsMode);
this.showButtonsMode = showButtonsMode;
}
public boolean onlyUnread() {
if (onlyUnread == null)
onlyUnread = prefs.getBoolean(Constants.ONLY_UNREAD, Constants.ONLY_UNREAD_DEFAULT);
return onlyUnread;
}
public void setDisplayOnlyUnread(boolean displayOnlyUnread) {
put(Constants.ONLY_UNREAD, displayOnlyUnread);
this.onlyUnread = displayOnlyUnread;
}
public boolean onlyDisplayCachedImages() {
if (onlyDisplayCachedImages == null)
onlyDisplayCachedImages = prefs.getBoolean(Constants.ONLY_CACHED_IMAGES,
Constants.ONLY_CACHED_IMAGES_DEFAULT);
return onlyDisplayCachedImages;
}
public void setDisplayCachedImages(boolean onlyDisplayCachedImages) {
put(Constants.ONLY_CACHED_IMAGES, onlyDisplayCachedImages);
this.onlyDisplayCachedImages = onlyDisplayCachedImages;
}
public boolean invertSortArticlelist() {
if (invertSortArticlelist == null)
invertSortArticlelist = prefs.getBoolean(Constants.INVERT_SORT_ARTICLELIST,
Constants.INVERT_SORT_ARTICLELIST_DEFAULT);
return invertSortArticlelist;
}
public void setInvertSortArticleList(boolean invertSortArticleList) {
put(Constants.INVERT_SORT_ARTICLELIST, invertSortArticleList);
this.invertSortArticlelist = invertSortArticleList;
}
public boolean invertSortFeedscats() {
if (invertSortFeedscats == null)
invertSortFeedscats = prefs.getBoolean(Constants.INVERT_SORT_FEEDSCATS,
Constants.INVERT_SORT_FEEDSCATS_DEFAULT);
return invertSortFeedscats;
}
public void setInvertSortFeedsCats(boolean invertSortFeedsCats) {
put(Constants.INVERT_SORT_FEEDSCATS, invertSortFeedsCats);
this.invertSortFeedscats = invertSortFeedsCats;
}
public boolean alignFlushLeft() {
if (alignFlushLeft == null)
alignFlushLeft = prefs.getBoolean(Constants.ALIGN_FLUSH_LEFT, Constants.ALIGN_FLUSH_LEFT_DEFAULT);
return alignFlushLeft;
}
public void setAlignFlushLeft(boolean alignFlushLeft) {
put(Constants.ALIGN_FLUSH_LEFT, alignFlushLeft);
this.alignFlushLeft = alignFlushLeft;
}
public boolean dateTimeSystem() {
if (dateTimeSystem == null)
dateTimeSystem = prefs.getBoolean(Constants.DATE_TIME_SYSTEM, Constants.DATE_TIME_SYSTEM_DEFAULT);
return dateTimeSystem;
}
public void setDateTimeSystem(boolean dateTimeSystem) {
put(Constants.DATE_TIME_SYSTEM, dateTimeSystem);
this.dateTimeSystem = dateTimeSystem;
}
public String dateString() {
if (dateString == null)
dateString = prefs.getString(Constants.DATE_STRING, Constants.DATE_STRING_DEFAULT);
return dateString;
}
public void setDateString(String dateString) {
put(Constants.DATE_STRING, dateString);
this.dateString = dateString;
}
public String timeString() {
if (timeString == null)
timeString = prefs.getString(Constants.TIME_STRING, Constants.TIME_STRING_DEFAULT);
return timeString;
}
public void setTimeString(String timeString) {
put(Constants.TIME_STRING, timeString);
this.timeString = timeString;
}
public String dateTimeString() {
if (dateTimeString == null)
dateTimeString = prefs.getString(Constants.DATE_TIME_STRING, Constants.DATE_TIME_STRING_DEFAULT);
return dateTimeString;
}
public void setDateTimeString(String dateTimeString) {
put(Constants.DATE_TIME_STRING, dateTimeString);
this.dateTimeString = dateTimeString;
}
public int getTheme() {
switch (getThemeInternal()) {
case THEME_LIGHT:
return R.style.Theme_Light;
case THEME_BLACK:
return R.style.Theme_Black;
case THEME_WHITE:
return R.style.Theme_White;
case THEME_DARK:
default:
return R.style.Theme_Dark;
}
}
public int getThemeInternal() {
if (theme == null)
theme = Integer.parseInt(prefs.getString(Constants.THEME, Constants.THEME_DEFAULT));
return theme;
}
public void setTheme(int theme) {
this.theme = theme;
put(Constants.THEME, theme + "");
}
public int getThemeBackground() {
switch (getThemeInternal()) {
case THEME_LIGHT:
return R.color.background_light;
case THEME_BLACK:
return R.color.background_black;
case THEME_WHITE:
return R.color.background_white;
case THEME_DARK:
default:
return R.color.background_dark;
}
}
public int getThemeFont() {
switch (getThemeInternal()) {
case THEME_LIGHT:
return R.color.font_color_light;
case THEME_BLACK:
return R.color.font_color_black;
case THEME_WHITE:
return R.color.font_color_white;
case THEME_DARK:
default:
return R.color.font_color_dark;
}
}
public int getThemeHTML() {
switch (getThemeInternal()) {
case THEME_LIGHT:
return R.string.HTML_THEME_LIGHT;
case THEME_BLACK:
return R.string.HTML_THEME_BLACK;
case THEME_WHITE:
return R.string.HTML_THEME_WHITE;
case THEME_DARK:
default:
return R.string.HTML_THEME_DARK;
}
}
public boolean isScheduledRestart() {
return scheduledRestart;
}
public void setScheduledRestart(boolean scheduledRestart) {
this.scheduledRestart = scheduledRestart;
}
// SYSTEM
public String saveAttachmentPath() {
if (saveAttachment == null)
saveAttachment = prefs.getString(Constants.SAVE_ATTACHMENT, Constants.SAVE_ATTACHMENT_DEFAULT);
return saveAttachment;
}
public void setSaveAttachmentPath(String saveAttachment) {
put(Constants.SAVE_ATTACHMENT, saveAttachment);
this.saveAttachment = saveAttachment;
}
public String cacheFolder() {
if (cacheFolder == null)
cacheFolder = prefs.getString(Constants.CACHE_FOLDER, Constants.CACHE_FOLDER_DEFAULT);
if (!cacheFolder.endsWith("/"))
setCacheFolder(cacheFolder + "/");
return cacheFolder;
}
public void setCacheFolder(String cacheFolder) {
put(Constants.CACHE_FOLDER, cacheFolder);
this.cacheFolder = cacheFolder;
}
public Integer cacheFolderMaxSize() {
if (cacheFolderMaxSize == null)
cacheFolderMaxSize = prefs.getInt(Constants.CACHE_FOLDER_MAX_SIZE, Constants.CACHE_FOLDER_MAX_SIZE_DEFAULT);
return cacheFolderMaxSize;
}
public void setCacheFolderMaxSize(Integer cacheFolderMaxSize) {
put(Constants.CACHE_FOLDER_MAX_SIZE, cacheFolderMaxSize);
this.cacheFolderMaxSize = cacheFolderMaxSize;
}
public Integer cacheImageMaxSize() {
if (cacheImageMaxSize == null)
cacheImageMaxSize = prefs.getInt(Constants.CACHE_IMAGE_MAX_SIZE, Constants.CACHE_IMAGE_MAX_SIZE_DEFAULT);
return cacheImageMaxSize;
}
public void setCacheImageMaxSize(Integer cacheImageMaxSize) {
put(Constants.CACHE_IMAGE_MAX_SIZE, cacheImageMaxSize);
this.cacheImageMaxSize = cacheImageMaxSize;
}
public Integer cacheImageMinSize() {
if (cacheImageMinSize == null)
cacheImageMinSize = prefs.getInt(Constants.CACHE_IMAGE_MIN_SIZE, Constants.CACHE_IMAGE_MIN_SIZE_DEFAULT);
return cacheImageMinSize;
}
public void setCacheImageMinSize(Integer cacheImageMinSize) {
put(Constants.CACHE_IMAGE_MIN_SIZE, cacheImageMinSize);
this.cacheImageMinSize = cacheImageMinSize;
}
public boolean isDeleteDBScheduled() {
if (deleteDbScheduled == null)
deleteDbScheduled = prefs.getBoolean(Constants.DELETE_DB_SCHEDULED, Constants.DELETE_DB_SCHEDULED_DEFAULT);
return deleteDbScheduled;
}
public void setDeleteDBScheduled(boolean isDeleteDBScheduled) {
put(Constants.DELETE_DB_SCHEDULED, isDeleteDBScheduled);
this.deleteDbScheduled = isDeleteDBScheduled;
}
public boolean cacheImagesOnStartup() {
if (cacheImagesOnStartup == null)
cacheImagesOnStartup = prefs.getBoolean(Constants.CACHE_IMAGES_ON_STARTUP,
Constants.CACHE_IMAGES_ON_STARTUP_DEFAULT);
return cacheImagesOnStartup;
}
public void setCacheImagesOnStartup(boolean cacheImagesOnStartup) {
put(Constants.CACHE_IMAGES_ON_STARTUP, cacheImagesOnStartup);
this.cacheImagesOnStartup = cacheImagesOnStartup;
}
public boolean cacheImagesOnlyWifi() {
if (cacheImagesOnlyWifi == null)
cacheImagesOnlyWifi = prefs.getBoolean(Constants.CACHE_IMAGES_ONLY_WIFI,
Constants.CACHE_IMAGES_ONLY_WIFI_DEFAULT);
return cacheImagesOnlyWifi;
}
public void setCacheImagesOnlyWifi(boolean cacheImagesOnlyWifi) {
put(Constants.CACHE_IMAGES_ONLY_WIFI, cacheImagesOnlyWifi);
this.cacheImagesOnlyWifi = cacheImagesOnlyWifi;
}
public boolean onlyUseWifi() {
if (onlyUseWifi == null)
onlyUseWifi = prefs.getBoolean(Constants.ONLY_USE_WIFI, Constants.ONLY_USE_WIFI_DEFAULT);
return onlyUseWifi;
}
public void setOnlyUseWifi(boolean onlyUseWifi) {
put(Constants.ONLY_USE_WIFI, onlyUseWifi);
this.onlyUseWifi = onlyUseWifi;
}
// Returns true if noCrashreports OR noCrashreportsUntilUpdate is true.
public boolean isNoCrashreports() {
if (noCrashreports == null)
noCrashreports = prefs.getBoolean(Constants.NO_CRASHREPORTS, Constants.NO_CRASHREPORTS_DEFAULT);
if (noCrashreportsUntilUpdate == null)
noCrashreportsUntilUpdate = prefs.getBoolean(Constants.NO_CRASHREPORTS_UNTIL_UPDATE,
Constants.NO_CRASHREPORTS_UNTIL_UPDATE_DEFAULT);
return noCrashreports || noCrashreportsUntilUpdate;
}
public void setNoCrashreports(boolean noCrashreports) {
put(Constants.NO_CRASHREPORTS, noCrashreports);
this.noCrashreports = noCrashreports;
}
public void setNoCrashreportsUntilUpdate(boolean noCrashreportsUntilUpdate) {
put(Constants.NO_CRASHREPORTS_UNTIL_UPDATE, noCrashreportsUntilUpdate);
this.noCrashreportsUntilUpdate = noCrashreportsUntilUpdate;
}
// ******* INTERNAL Data ****************************
public long appVersionCheckTime() {
if (appVersionCheckTime == null)
appVersionCheckTime = prefs.getLong(Constants.APP_VERSION_CHECK_TIME,
Constants.APP_VERSION_CHECK_TIME_DEFAULT);
return appVersionCheckTime;
}
private void setAppVersionCheckTime(long appVersionCheckTime) {
put(Constants.APP_VERSION_CHECK_TIME, appVersionCheckTime);
this.appVersionCheckTime = appVersionCheckTime;
}
public int appLatestVersion() {
if (appLatestVersion == null)
appLatestVersion = prefs.getInt(Constants.APP_LATEST_VERSION, Constants.APP_LATEST_VERSION_DEFAULT);
return appLatestVersion;
}
public void setAppLatestVersion(int appLatestVersion) {
put(Constants.APP_LATEST_VERSION, appLatestVersion);
this.appLatestVersion = appLatestVersion;
setAppVersionCheckTime(System.currentTimeMillis());
// Set current time, this only changes when it has been fetched from the server
}
public String getLastVersionRun() {
if (lastVersionRun == null)
lastVersionRun = prefs.getString(Constants.LAST_VERSION_RUN, Constants.LAST_VERSION_RUN_DEFAULT);
return lastVersionRun;
}
public void setLastVersionRun(String lastVersionRun) {
put(Constants.LAST_VERSION_RUN, lastVersionRun);
this.lastVersionRun = lastVersionRun;
}
public boolean newInstallation() {
// Initialized inside initializeController();
return newInstallation;
}
public void setSinceId(int sinceId) {
put(Constants.SINCE_ID, sinceId);
this.sinceId = sinceId;
}
public int getSinceId() {
if (sinceId == null)
sinceId = prefs.getInt(Constants.SINCE_ID, Constants.SINCE_ID_DEFAULT);
return sinceId;
}
public void setLastSync(long lastSync) {
put(Constants.LAST_SYNC, lastSync);
this.lastSync = lastSync;
}
public long getLastSync() {
if (lastSync == null)
lastSync = prefs.getLong(Constants.LAST_SYNC, Constants.LAST_SYNC_DEFAULT);
return lastSync;
}
public void lowMemory(boolean lowMemory) {
if (lowMemory && !this.lowMemory)
Log.w(TAG, "lowMemory-Situation detected, trying to reduce memory footprint...");
this.lowMemory = lowMemory;
}
public boolean isLowMemory() {
return lowMemory;
}
public void setLastCleanup(long lastCleanup) {
put(Constants.LAST_CLEANUP, lastCleanup);
this.lastCleanup = lastSync;
}
public long getLastCleanup() {
if (lastCleanup == null)
lastCleanup = prefs.getLong(Constants.LAST_CLEANUP, Constants.LAST_CLEANUP_DEFAULT);
return lastCleanup;
}
private AsyncTask<Void, Void, Void> refreshPrefTask;
public long getFreshArticleMaxAge() {
if (freshArticleMaxAge == null)
freshArticleMaxAge = prefs
.getLong(Constants.FRESH_ARTICLE_MAX_AGE, Constants.FRESH_ARTICLE_MAX_AGE_DEFAULT);
if (freshArticleMaxAgeDate == null)
freshArticleMaxAgeDate = prefs.getLong(Constants.FRESH_ARTICLE_MAX_AGE_DATE,
Constants.FRESH_ARTICLE_MAX_AGE_DATE_DEFAULT);
if (freshArticleMaxAgeDate < System.currentTimeMillis() - (Utils.DAY * 2)) {
// Only start task if none existing yet
if (refreshPrefTask == null) {
refreshPrefTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
String s = "";
try {
s = Data.getInstance().getPref("FRESH_ARTICLE_MAX_AGE");
freshArticleMaxAge = Long.parseLong(s) * Utils.HOUR;
put(Constants.FRESH_ARTICLE_MAX_AGE, freshArticleMaxAge);
freshArticleMaxAgeDate = System.currentTimeMillis();
put(Constants.FRESH_ARTICLE_MAX_AGE_DATE, freshArticleMaxAgeDate);
} catch (Exception e) {
Log.d(TAG, "Pref \"FRESH_ARTICLE_MAX_AGE\" could not be fetched from server: " + s);
}
return null;
}
};
refreshPrefTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
return freshArticleMaxAge;
}
/*
* Generic method to insert values into the preferences store
*/
private void put(String constant, Object o) {
SharedPreferences.Editor editor = prefs.edit();
if (o instanceof String) {
editor.putString(constant, (String) o);
} else if (o instanceof Integer) {
editor.putInt(constant, (Integer) o);
} else if (o instanceof Long) {
editor.putLong(constant, (Long) o);
} else if (o instanceof Boolean) {
editor.putBoolean(constant, (Boolean) o);
}
/*
* The following Code is extracted from
* https://code.google.com/p/zippy-android/source/browse/trunk/examples/SharedPreferencesCompat.java
*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Uses faster apply() instead of commit() if method is available
if (sApplyMethod != null) {
try {
sApplyMethod.invoke(editor);
return;
} catch (InvocationTargetException unused) {
// fall through
} catch (IllegalAccessException unused) {
// fall through
}
}
editor.commit();
}
private static final Method sApplyMethod = findApplyMethod();
private static Method findApplyMethod() {
try {
Class<?> cls = SharedPreferences.Editor.class;
return cls.getMethod("apply");
} catch (NoSuchMethodException unused) {
// fall through
}
return null;
}
/**
* If provided "key" resembles a setting as declared in Constants.java the corresponding variable in this class will
* be reset to null. Variable-Name ist built from the name of the field in Contants.java which holds the value from
* "key" which was changed lately.
*/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Indicate Restart of App is necessary if Theme-Pref is changed and value differs from old value:
if (key.equals(Constants.THEME)) {
int newTheme = Integer.parseInt(prefs.getString(key, Constants.THEME_DEFAULT));
if (newTheme != getThemeInternal()) {
setTheme(newTheme);
reloadTheme();
scheduledRestart = true;
}
}
for (Field field : Constants.class.getDeclaredFields()) {
// No default-values
if (field.getName().endsWith(Constants.APPENDED_DEFAULT))
continue;
// Only use public static fields
if (!Modifier.isStatic(field.getModifiers()) || !Modifier.isPublic(field.getModifiers()))
continue;
String fieldName = "";
try {
Object f = field.get(this);
if (!(f instanceof String))
continue;
if (!key.equals((String) f))
continue;
// reset variable, it will be re-read on next access
fieldName = Constants.constant2Var(field.getName());
Controller.class.getDeclaredField(fieldName).set(this, null); // "Declared" so also private
setPreferencesChanged(true);
} catch (Exception e) {
Log.e(TAG, "Field not found: " + fieldName);
}
}
}
public boolean isPreferencesChanged() {
return preferencesChanged;
}
public void setPreferencesChanged(boolean preferencesChanged) {
Controller.preferencesChanged = preferencesChanged;
}
private static String getCurrentSSID(WifiManager wifiManager) {
if (wifiManager != null && wifiManager.isWifiEnabled()) {
WifiInfo info = wifiManager.getConnectionInfo();
final String ssid = info.getSSID();
return ssid == null ? "" : ssid.replace("\"", "");
} else {
return null;
}
}
private static String getStringWithSSID(String param, String wifiSSID) {
if (wifiSSID == null)
return param;
else
return wifiSSID + param;
}
private static final String SIZE_VERTICAL_CATEGORY = "sizeVerticalCategory";
private static final String SIZE_HORIZONTAL_CATEGORY = "sizeHorizontalCategory";
private static final String SIZE_VERTICAL_HEADLINE = "sizeVerticalHeadline";
private static final String SIZE_HORIZONTAL_HEADLINE = "sizeHorizontalHeadline";
private Integer sizeVerticalCategory;
private Integer sizeHorizontalCategory;
private Integer sizeVerticalHeadline;
private Integer sizeHorizontalHeadline;
public int getMainFrameSize(MenuActivity activity, boolean isVertical, int min, int max) {
int ret = -1;
if (activity instanceof CategoryActivity) {
if (isVertical) {
ret = sizeVerticalCategory;
} else {
ret = sizeHorizontalCategory;
}
} else if (activity instanceof FeedHeadlineActivity) {
if (isVertical) {
ret = sizeVerticalHeadline;
} else {
ret = sizeHorizontalHeadline;
}
}
if (ret < min || ret > max)
ret = (min + max) / 2;
return ret;
}
public void setViewSize(MenuActivity activity, boolean isVertical, int size) {
if (size <= 0)
return;
if (activity instanceof CategoryActivity) {
if (isVertical) {
sizeVerticalCategory = size;
put(SIZE_VERTICAL_CATEGORY, size);
} else {
sizeHorizontalCategory = size;
put(SIZE_HORIZONTAL_CATEGORY, size);
}
} else if (activity instanceof FeedHeadlineActivity) {
if (isVertical) {
sizeVerticalHeadline = size;
put(SIZE_VERTICAL_HEADLINE, size);
} else {
sizeHorizontalHeadline = size;
put(SIZE_HORIZONTAL_HEADLINE, size);
}
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.preferences;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
import android.util.Log;
/**
* Just implement a BackupAgent for the SharedPreferences, nothing else is of importance to us.
*
* @author Nils Braden
*/
public class MyPrefsBackupAgent extends BackupAgentHelper {
protected static final String TAG = MyPrefsBackupAgent.class.getSimpleName();
static final String PREFS = "org.ttrssreader_preferences";
static final String PREFS_BACKUP_KEY = "prefs";
@Override
public void onCreate() {
Log.e(TAG, "== DEBUG: MyPrefsBackupAgent started...");
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.preferences;
import java.util.Map;
import org.ttrssreader.R;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
@SuppressWarnings("deprecation")
public class ConnectionSettings extends PreferenceActivity {
protected static final String TAG = ConnectionSettings.class.getSimpleName();
private static final String KEY_CONNECTION_CATEGORY = "connectionCategory";
public static final String KEY_SSID = "SSID";
private static final int MENU_DELETE = 1;
private String sSID;
private PreferenceCategory category;
private SharedPreferences prefs = null;
private Map<String, ?> prefsCache = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs_main_top);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
category = (PreferenceCategory) preferenceScreen.findPreference(KEY_CONNECTION_CATEGORY);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsCache = prefs.getAll();
if (getIntent().getStringExtra(KEY_SSID) != null) {
// WiFi-Based Settings
sSID = getIntent().getStringExtra(KEY_SSID);
createDynamicSettings(sSID);
} else {
// Default settings
createDynamicSettings("");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, R.string.ConnectionWifiDeletePref);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (item != null && item.getItemId() == MENU_DELETE) {
Editor edit = prefs.edit();
for (int i = 0; i < category.getPreferenceCount(); i++) {
Preference pref = category.getPreference(i);
if (prefs.contains(pref.getKey())) {
edit.remove(pref.getKey());
// Remove and add again to reinitialize default values
category.removePreference(pref);
category.addPreference(pref);
}
}
edit.commit();
prefsCache = prefs.getAll();
}
return super.onMenuItemSelected(featureId, item);
}
private void createDynamicSettings(String keyPrefix) {
category.setTitle(category.getTitle() + " ( Network: " + keyPrefix + " )");
Log.d(TAG, "Adding WifiPreferences...");
for (int i = 0; i < category.getPreferenceCount(); i++) {
Preference pref = category.getPreference(i);
String oldKey = pref.getKey();
String newKey = keyPrefix + oldKey;
pref.setKey(newKey);
Object defaultValue = null;
if (prefsCache.containsKey(newKey))
defaultValue = prefsCache.get(newKey);
pref.setDefaultValue(defaultValue);
// Remove and add again to reinitialize default values
category.removePreference(pref);
category.addPreference(pref);
Log.d(TAG, String.format(" oldKey: \"%s\" newKey: \"%s\"", oldKey, newKey));
}
onContentChanged();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.preferences;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public class EditIntegerPreference extends EditTextPreference {
public EditIntegerPreference(Context context) {
super(context);
}
public EditIntegerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditIntegerPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected String getPersistedString(String defaultReturnValue) {
return String.valueOf(getPersistedInt(-1));
}
@Override
protected boolean persistString(String value) {
if (value == null || value.length() == 0)
return false;
return persistInt(Integer.valueOf(value));
}
}
| Java |
package org.ttrssreader.preferences;
import java.io.File;
import org.ttrssreader.R;
import org.ttrssreader.controllers.Controller;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.InputType;
import android.widget.EditText;
/**
* Copied from https://code.google.com/p/k9mail/
*/
public class FileBrowserHelper {
/**
* A string array that specifies the name of the intent to use, and the scheme to use with it
* when setting the data for the intent.
*/
private static final String[][] PICK_DIRECTORY_INTENTS = { { "org.openintents.action.PICK_DIRECTORY", "file://" }, // OI
// File
// Manager
{ "com.estrongs.action.PICK_DIRECTORY", "file://" }, // ES File Explorer
{ Intent.ACTION_PICK, "folder://" }, // Blackmoon File Browser (maybe others)
{ "com.androidworkz.action.PICK_DIRECTORY", "file://" } }; // SystemExplorer
private static FileBrowserHelper instance;
/**
* callbackDownloadPath class to provide the result of the fallback textedit path dialog
*/
public interface FileBrowserFailOverCallback {
/**
* the user has entered a path
*
* @param path
* the path as String
*/
public void onPathEntered(String path);
/**
* the user has cancel the inputtext dialog
*/
public void onCancel();
}
// Singleton
private FileBrowserHelper() {
}
public synchronized static FileBrowserHelper getInstance() {
if (instance == null) {
instance = new FileBrowserHelper();
}
return instance;
}
/**
* tries to open known filebrowsers.
* If no filebrowser is found and fallback textdialog is shown
*
* @param c
* the context as activity
* @param startPath
* : the default value, where the filebrowser will start.
* if startPath = null => the default path is used
* @param requestcode
* : the int you will get as requestcode in onActivityResult
* (only used if there is a filebrowser installed)
* @param callbackDownloadPath
* : the callbackDownloadPath (only used when no filebrowser is installed.
* if a filebrowser is installed => override the onActivtyResult Method
*
* @return true: if a filebrowser has been found (the result will be in the onActivityResult
* false: a fallback textinput has been shown. The Result will be sent with the callbackDownloadPath method
*
*
*/
public boolean showFileBrowserActivity(Activity c, File startPath, int requestcode, FileBrowserFailOverCallback callback) {
boolean success = false;
if (startPath == null) {
startPath = new File(Controller.getInstance().saveAttachmentPath());
}
int listIndex = 0;
do {
String intentAction = PICK_DIRECTORY_INTENTS[listIndex][0];
String uriPrefix = PICK_DIRECTORY_INTENTS[listIndex][1];
Intent intent = new Intent(intentAction);
intent.setData(Uri.parse(uriPrefix + startPath.getPath()));
try {
c.startActivityForResult(intent, requestcode);
success = true;
} catch (ActivityNotFoundException e) {
// Try the next intent in the list
listIndex++;
};
} while (!success && (listIndex < PICK_DIRECTORY_INTENTS.length));
if (listIndex == PICK_DIRECTORY_INTENTS.length) {
// No Filebrowser is installed => show a fallback textdialog
showPathTextInput(c, startPath, callback);
success = false;
}
return success;
}
private void showPathTextInput(final Activity c, final File startPath, final FileBrowserFailOverCallback callback) {
AlertDialog.Builder alert = new AlertDialog.Builder(c);
alert.setTitle(c.getString(R.string.Utils_FileSaveTitle));
alert.setMessage(c.getString(R.string.Utils_FileSaveMessage));
final EditText input = new EditText(c);
input.setInputType(InputType.TYPE_CLASS_TEXT);
if (startPath != null)
input.setText(startPath.toString());
alert.setView(input);
alert.setPositiveButton(c.getString(R.string.Utils_OkayAction), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String path = input.getText().toString();
callback.onPathEntered(path);
}
});
alert.setNegativeButton(c.getString(R.string.Utils_CancelAction), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
callback.onCancel();
}
});
alert.show();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.preferences;
import java.util.List;
import org.ttrssreader.R;
import org.ttrssreader.controllers.Controller;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
public class WifiConnectionSettings extends PreferenceActivity {
private PreferenceCategory mWifibasedCategory;
private List<WifiConfiguration> mWifiList;
private WifiManager mWifiManager;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(Controller.getInstance().getTheme());
super.onCreate(savedInstanceState); // IMPORTANT!
addPreferencesFromResource(R.xml.prefs_wifibased);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
mWifibasedCategory = (PreferenceCategory) preferenceScreen.findPreference("wifibasedCategory");
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiList = mWifiManager.getConfiguredNetworks();
if (mWifiList == null)
return;
for (WifiConfiguration wifi : mWifiList) {
// Friendly SSID-Name
String ssid = wifi.SSID.replaceAll("\"", "");
// Add PreferenceScreen for each network
PreferenceScreen pref = getPreferenceManager().createPreferenceScreen(this);
pref.setPersistent(false);
pref.setKey("wifiNetwork" + ssid);
pref.setTitle(ssid);
Intent intent = new Intent(this, ConnectionSettings.class);
intent.putExtra(ConnectionSettings.KEY_SSID, ssid);
pref.setIntent(intent);
if (WifiConfiguration.Status.CURRENT == wifi.status)
pref.setSummary(getResources().getString(R.string.ConnectionWifiConnected));
else
pref.setSummary(getResources().getString(R.string.ConnectionWifiNotInRange));
mWifibasedCategory.addPreference(pref);
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.preferences;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.ttrssreader.utils.FileUtils;
import org.ttrssreader.utils.Utils;
import android.content.SharedPreferences;
import android.os.Environment;
public class Constants {
public static final String EMPTY = "";
public static final String APPENDED_DEFAULT = "_DEFAULT";
static {
StringBuilder sbAttachments = new StringBuilder();
sbAttachments.append(Environment.getExternalStorageDirectory()).append(File.separator)
.append(FileUtils.SDCARD_PATH_FILES);
SAVE_ATTACHMENT_DEFAULT = sbAttachments.toString();
StringBuilder sbCache = new StringBuilder();
sbCache.append(Environment.getExternalStorageDirectory()).append(File.separator)
.append(FileUtils.SDCARD_PATH_CACHE);
CACHE_FOLDER_DEFAULT = sbCache.toString();
}
// Connection
public static final String URL = "ConnectionUrlPreference";
public static final String USERNAME = "ConnectionUsernamePreference";
public static final String PASSWORD = "ConnectionPasswordPreference";
public static final String USE_HTTP_AUTH = "ConnectionHttpPreference";
public static final String HTTP_USERNAME = "ConnectionHttpUsernamePreference";
public static final String HTTP_PASSWORD = "ConnectionHttpPasswordPreference";
public static final String TRUST_ALL_SSL = "ConnectionSSLPreference";
public static final String TRUST_ALL_HOSTS = "ConnectionTrustHostsPreference";
public static final String USE_OLD_CONNECTOR = "ConnectionUseOldConnector";
public static final String USE_KEYSTORE = "ConnectionUseKeystorePreference";
public static final String KEYSTORE_PASSWORD = "ConnectionKeystorePasswordPreference";
public static final String USE_OF_A_LAZY_SERVER = "ConnectionLazyServerPreference";
// Connection Default Values
public static final String URL_DEFAULT = "http://localhost/";
public static final boolean USE_HTTP_AUTH_DEFAULT = false;
public static final boolean TRUST_ALL_SSL_DEFAULT = false;
public static final boolean TRUST_ALL_HOSTS_DEFAULT = false;
public static final boolean USE_OLD_CONNECTOR_DEFAULT = false;
public static final boolean USE_KEYSTORE_DEFAULT = false;
public static final boolean USE_OF_A_LAZY_SERVER_DEFAULT = false;
// Usage
public static final String OPEN_URL_EMPTY_ARTICLE = "UsageOpenUrlEmptyArticlePreference";
public static final String USE_VOLUME_KEYS = "UsageUseVolumeKeysPreference";
public static final String LOAD_IMAGES = "DisplayLoadImagesPreference";
public static final String INVERT_BROWSING = "InvertBrowseArticlesPreference";
public static final String WORK_OFFLINE = "UsageWorkOfflinePreference";
public static final String GO_BACK_AFTER_MARK_ALL_READ = "GoBackAfterMarkAllReadPreference";
public static final String HIDE_ACTIONBAR = "HideActionbarPreference";
public static final String ALLOW_TABLET_LAYOUT = "AllowTabletLayoutPreference";
// Usage Default Values
public static final boolean OPEN_URL_EMPTY_ARTICLE_DEFAULT = false;
public static final boolean USE_VOLUME_KEYS_DEFAULT = false;
public static final boolean LOAD_IMAGES_DEFAULT = true;
public static final boolean INVERT_BROWSING_DEFAULT = false;
public static final boolean WORK_OFFLINE_DEFAULT = false;
public static final boolean GO_BACK_AFTER_MARK_ALL_READ_DEFAULT = false;
public static final boolean HIDE_ACTIONBAR_DEFAULT = true;
public static final boolean ALLOW_TABLET_LAYOUT_DEFAULT = true;
// Display
public static final String HEADLINE_SIZE = "HeadlineSizePreference";
public static final String TEXT_ZOOM = "TextZoomPreference";
public static final String SUPPORT_ZOOM_CONTROLS = "SupportZoomControlsPreference";
public static final String ALLOW_HYPHENATION = "AllowHyphenationPreference";
public static final String HYPHENATION_LANGUAGE = "HyphenationLanguagePreference";
public static final String SHOW_VIRTUAL = "DisplayShowVirtualPreference";
public static final String SHOW_BUTTONS_MODE = "ShowButtonsModePreference";
public static final String ONLY_UNREAD = "DisplayShowUnreadOnlyPreference";
public static final String ONLY_CACHED_IMAGES = "DisplayShowCachedImagesPreference";
public static final String INVERT_SORT_ARTICLELIST = "InvertSortArticlelistPreference";
public static final String INVERT_SORT_FEEDSCATS = "InvertSortFeedscatsPreference";
public static final String ALIGN_FLUSH_LEFT = "DisplayAlignFlushLeftPreference";
public static final String DATE_TIME_SYSTEM = "DisplayDateTimeFormatSystemPreference";
public static final String DATE_STRING = "DisplayDateFormatPreference";
public static final String TIME_STRING = "DisplayTimeFormatPreference";
public static final String DATE_TIME_STRING = "DisplayDateTimeFormatPreference";
public static final String THEME = "DisplayThemePreference";
// Display Default Values
public static final int HEADLINE_SIZE_DEFAULT = 16;
public static final int TEXT_ZOOM_DEFAULT = 100;
public static final boolean SUPPORT_ZOOM_CONTROLS_DEFAULT = true;
public static final boolean ALLOW_HYPHENATION_DEFAULT = false;
public static final String HYPHENATION_LANGUAGE_DEFAULT = "en-gb";
public static final boolean SHOW_VIRTUAL_DEFAULT = true;
public static final String SHOW_BUTTONS_MODE_DEFAULT = "0";
public static final int SHOW_BUTTONS_MODE_NONE = 0;
public static final int SHOW_BUTTONS_MODE_ALLWAYS = 1;
public static final int SHOW_BUTTONS_MODE_HTML = 2;
public static final boolean ONLY_UNREAD_DEFAULT = false;
public static final boolean ONLY_CACHED_IMAGES_DEFAULT = false;
public static final boolean INVERT_SORT_ARTICLELIST_DEFAULT = false;
public static final boolean INVERT_SORT_FEEDSCATS_DEFAULT = false;
public static final boolean ALIGN_FLUSH_LEFT_DEFAULT = false;
public static final boolean DATE_TIME_SYSTEM_DEFAULT = true;
public static final String DATE_STRING_DEFAULT = "dd.MM.yyyy";
public static final String TIME_STRING_DEFAULT = "kk:mm";
public static final String DATE_TIME_STRING_DEFAULT = "dd.MM.yyyy kk:mm";
public static final String THEME_DEFAULT = "1";
// System
public static final String SAVE_ATTACHMENT = "SaveAttachmentPreference";
public static final String CACHE_FOLDER = "CacheFolderPreference";
public static final String CACHE_FOLDER_MAX_SIZE = "CacheFolderMaxSizePreference";
public static final String CACHE_IMAGE_MAX_SIZE = "CacheImageMaxSizePreference";
public static final String CACHE_IMAGE_MIN_SIZE = "CacheImageMinSizePreference";
public static final String DELETE_DB_SCHEDULED = "DeleteDBScheduledPreference";
public static final String CACHE_IMAGES_ON_STARTUP = "CacheImagesOnStartupPreference";
public static final String CACHE_IMAGES_ONLY_WIFI = "CacheImagesOnlyWifiPreference";
public static final String ONLY_USE_WIFI = "OnlyUseWifiPreference";
public static final String NO_CRASHREPORTS = "NoCrashreportsPreference";
public static final String NO_CRASHREPORTS_UNTIL_UPDATE = "NoCrashreportsUntilUpdatePreference";
// System Default Values
public static final String SAVE_ATTACHMENT_DEFAULT;
public static final String CACHE_FOLDER_DEFAULT;
public static final Integer CACHE_FOLDER_MAX_SIZE_DEFAULT = 80;
public static final Integer CACHE_IMAGE_MAX_SIZE_DEFAULT = 6 * (int) Utils.MB; // 6 MB
public static final Integer CACHE_IMAGE_MIN_SIZE_DEFAULT = 32 * (int) Utils.KB; // 64 KB
public static final boolean DELETE_DB_SCHEDULED_DEFAULT = false;
public static final boolean CACHE_IMAGES_ON_STARTUP_DEFAULT = false;
public static final boolean CACHE_IMAGES_ONLY_WIFI_DEFAULT = false;
public static final boolean ONLY_USE_WIFI_DEFAULT = false;
public static final boolean NO_CRASHREPORTS_DEFAULT = false;
public static final boolean NO_CRASHREPORTS_UNTIL_UPDATE_DEFAULT = false;
// Internal
public static final String API_LEVEL_UPDATED = "apiLevelUpdated";
public static final String API_LEVEL = "apiLevel";
public static final String APP_VERSION_CHECK_TIME = "appVersionCheckTime";
public static final String APP_LATEST_VERSION = "appLatestVersion";
public static final String LAST_UPDATE_TIME = "LastUpdateTime";
public static final String LAST_VERSION_RUN = "LastVersionRun";
public static final String FRESH_ARTICLE_MAX_AGE = "freshArticleMaxAge";
public static final String FRESH_ARTICLE_MAX_AGE_DATE = "freshArticleMaxAgeDate";
public static final String SINCE_ID = "sinceId";
public static final String LAST_SYNC = "lastSync";
public static final String LAST_CLEANUP = "lastCleanup";
// Internal Default Values
public static final long API_LEVEL_UPDATED_DEFAULT = -1;
public static final int API_LEVEL_DEFAULT = -1;
public static final long APP_VERSION_CHECK_TIME_DEFAULT = 0;
public static final int APP_LATEST_VERSION_DEFAULT = 0;
public static final long LAST_UPDATE_TIME_DEFAULT = 1;
public static final String LAST_VERSION_RUN_DEFAULT = "1";
public static final long FRESH_ARTICLE_MAX_AGE_DEFAULT = Utils.DAY;
public static final long FRESH_ARTICLE_MAX_AGE_DATE_DEFAULT = 0;
public static final int SINCE_ID_DEFAULT = 0;
public static final long LAST_SYNC_DEFAULT = 0l;
public static final long LAST_CLEANUP_DEFAULT = 0l;
/*
* Returns a list of the values of all constants in this class which represent preferences. Allows for easier
* watching the changes in the preferences-activity.
*/
public static List<String> getConstants() {
List<String> ret = new ArrayList<String>();
// Iterate over all fields
for (Field field : Constants.class.getDeclaredFields()) {
// Continue on "_DEFAULT"-Fields, these hold only the default values for a preference
if (field.getName().endsWith(APPENDED_DEFAULT))
continue;
try {
// Return all String-Fields, these hold the preference-name
if (field.get(null) instanceof String) {
ret.add((String) field.get(null));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
/*
* Resets all preferences to their default values. Only preferences which are mentioned in this class are reset, old
* or unsused values don't get reset.
*/
public static void resetPreferences(SharedPreferences prefs) {
SharedPreferences.Editor editor = prefs.edit();
// Iterate over all fields
for (Field field : Constants.class.getDeclaredFields()) {
// Continue on "_DEFAULT"-Fields, these hold only the default values for a preference
if (field.getName().endsWith(APPENDED_DEFAULT))
continue;
try {
// Get the default value
Field fieldDefault = Constants.class.getDeclaredField(field.getName() + APPENDED_DEFAULT);
String value = (String) field.get(new Constants());
// Get the default type and store value for the specific type
String type = fieldDefault.getType().getSimpleName();
if (type.equals("String")) {
String defaultValue = (String) fieldDefault.get(null);
editor.putString(value, defaultValue);
} else if (type.equals("boolean")) {
boolean defaultValue = fieldDefault.getBoolean(null);
editor.putBoolean(value, defaultValue);
} else if (type.equals("int")) {
int defaultValue = fieldDefault.getInt(null);
editor.putInt(value, defaultValue);
} else if (type.equals("long")) {
long defaultValue = fieldDefault.getLong(null);
editor.putLong(value, defaultValue);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
// Ignore, occurrs if a search for field like EMPTY_DEFAULT is started, this isn't there and shall never
// be there.
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// Commit when finished
editor.commit();
}
public static String constant2Var(String s) {
String[] parts = s.split("_");
String camelCaseString = "";
for (String part : parts) {
camelCaseString = camelCaseString + toProperCase(part);
}
// We want the String to starrt with a lower-case letter...
return camelCaseString.substring(0, 1).toLowerCase(Locale.getDefault()) + camelCaseString.substring(1);
}
static String toProperCase(String s) {
return s.substring(0, 1).toUpperCase(Locale.getDefault()) + s.substring(1).toLowerCase(Locale.getDefault());
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import java.util.Date;
import org.ttrssreader.R;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.model.pojos.Article;
import org.ttrssreader.model.pojos.Feed;
import org.ttrssreader.utils.DateUtils;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FeedHeadlineAdapter extends MainAdapter {
protected static final String TAG = FeedHeadlineAdapter.class.getSimpleName();
private int feedId;
private boolean selectArticlesForCategory;
public FeedHeadlineAdapter(Context context, int feedId, boolean selectArticlesForCategory) {
super(context);
this.feedId = feedId;
this.selectArticlesForCategory = selectArticlesForCategory;
}
@Override
public Object getItem(int position) {
Article ret = new Article();
Cursor cur = getCursor();
if (cur == null)
return ret;
if (cur.getCount() >= position) {
if (cur.moveToPosition(position)) {
ret.id = cur.getInt(0);
ret.feedId = cur.getInt(1);
ret.title = cur.getString(2);
ret.isUnread = cur.getInt(3) != 0;
ret.updated = new Date(cur.getLong(4));
ret.isStarred = cur.getInt(5) != 0;
ret.isPublished = cur.getInt(6) != 0;
}
}
return ret;
}
@SuppressWarnings("deprecation")
private void getImage(ImageView icon, Article a) {
if (a.isUnread) {
icon.setBackgroundResource(R.drawable.articleunread48);
} else {
icon.setBackgroundResource(R.drawable.articleread48);
}
if (a.isStarred && a.isPublished) {
icon.setImageResource(R.drawable.published_and_starred48);
} else if (a.isStarred) {
icon.setImageResource(R.drawable.star_yellow48);
} else if (a.isPublished) {
icon.setImageResource(R.drawable.published_blue48);
} else {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
icon.setBackgroundDrawable(null);
} else {
icon.setBackground(null);
}
if (a.isUnread) {
icon.setImageResource(R.drawable.articleunread48);
} else {
icon.setImageResource(R.drawable.articleread48);
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position >= getCount() || position < 0)
return new View(context);
Article a = (Article) getItem(position);
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = null;
if (convertView == null) {
layout = (LinearLayout) inflater.inflate(R.layout.item_feedheadline, parent, false);
} else {
if (convertView instanceof LinearLayout) {
layout = (LinearLayout) convertView;
}
}
if (layout == null)
return new View(context);
ImageView icon = (ImageView) layout.findViewById(R.id.icon);
getImage(icon, a);
TextView title = (TextView) layout.findViewById(R.id.title);
title.setText(a.title);
if (a.isUnread)
title.setTypeface(Typeface.DEFAULT_BOLD);
TextView updateDate = (TextView) layout.findViewById(R.id.updateDate);
String date = DateUtils.getDateTime(context, a.updated);
updateDate.setText(date.length() > 0 ? "(" + date + ")" : "");
TextView dataSource = (TextView) layout.findViewById(R.id.dataSource);
// Display Feed-Title in Virtual-Categories or when displaying all Articles in a Category
if ((feedId < 0 && feedId >= -4) || (selectArticlesForCategory)) {
Feed f = DBHelper.getInstance().getFeed(a.feedId);
if (f != null) {
dataSource.setText(f.title);
}
}
return layout;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import java.util.List;
import org.ttrssreader.R;
import android.content.Context;
import android.preference.PreferenceActivity.Header;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* <a href=
* "http://stackoverflow.com/questions/15551673/android-headers-categories-in-preferenceactivity-with-preferencefragment"
* >stackoverflow.com</a>
*/
public class HeaderAdapter extends ArrayAdapter<Header> {
protected static final String TAG = HeaderAdapter.class.getSimpleName();
static final int HEADER_TYPE_CATEGORY = 0;
static final int HEADER_TYPE_NORMAL = 1;
private static final int HEADER_TYPE_COUNT = HEADER_TYPE_NORMAL + 1;
private LayoutInflater mInflater;
private static class HeaderViewHolder {
ImageView icon;
TextView title;
TextView summary;
}
public HeaderAdapter(Context context, List<Header> objects) {
super(context, 0, objects);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static int getHeaderType(Header header) {
if (header.fragment == null && header.intent == null)
return HEADER_TYPE_CATEGORY;
else
return HEADER_TYPE_NORMAL;
}
@Override
public int getItemViewType(int position) {
Header header = getItem(position);
return getHeaderType(header);
}
@Override
public boolean areAllItemsEnabled() {
return false; /* because of categories */
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) != HEADER_TYPE_CATEGORY;
}
@Override
public int getViewTypeCount() {
return HEADER_TYPE_COUNT;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
Header header = getItem(position);
int headerType = getHeaderType(header);
View view = null;
if (convertView == null) {
holder = new HeaderViewHolder();
switch (headerType) {
case HEADER_TYPE_CATEGORY:
view = new TextView(getContext(), null, android.R.attr.listSeparatorTextViewStyle);
holder.title = (TextView) view;
break;
case HEADER_TYPE_NORMAL:
view = mInflater.inflate(R.layout.item_preferenceheader, parent, false);
holder.icon = (ImageView) view.findViewById(R.id.ph_icon);
holder.title = (TextView) view.findViewById(R.id.ph_title);
holder.summary = (TextView) view.findViewById(R.id.ph_summary);
break;
}
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
switch (headerType) {
case HEADER_TYPE_CATEGORY:
holder.title.setText(header.getTitle(getContext().getResources()));
break;
case HEADER_TYPE_NORMAL:
holder.icon.setImageResource(header.iconRes);
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
break;
}
return view;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import java.util.ArrayList;
import java.util.List;
import org.ttrssreader.R;
import org.ttrssreader.controllers.Data;
import org.ttrssreader.model.pojos.Category;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CategoryAdapter extends MainAdapter {
protected static final String TAG = CategoryAdapter.class.getSimpleName();
public CategoryAdapter(Context context) {
super(context);
}
@Override
public Object getItem(int position) {
Category ret = new Category();
Cursor cur = getCursor();
if (cur == null)
return ret;
if (cur.getCount() >= position) {
if (cur.moveToPosition(position)) {
ret.id = cur.getInt(0);
ret.title = cur.getString(1);
ret.unread = cur.getInt(2);
}
}
return ret;
}
public List<Category> getCategories() {
List<Category> ret = new ArrayList<Category>();
Cursor cur = getCursor();
if (cur == null)
return ret;
if (cur.moveToFirst()) {
while (!cur.isAfterLast()) {
Category c = new Category();
c.id = cur.getInt(0);
c.title = cur.getString(1);
c.unread = cur.getInt(2);
ret.add(c);
cur.move(1);
}
}
return ret;
}
private int getImage(int id, boolean unread) {
if (id == Data.VCAT_STAR) {
return R.drawable.star48;
} else if (id == Data.VCAT_PUB) {
return R.drawable.published48;
} else if (id == Data.VCAT_FRESH) {
return R.drawable.fresh48;
} else if (id == Data.VCAT_ALL) {
return R.drawable.all48;
} else if (id < -10) {
if (unread) {
return R.drawable.label;
} else {
return R.drawable.label_read;
}
} else {
if (unread) {
return R.drawable.categoryunread48;
} else {
return R.drawable.categoryread48;
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position >= getCount() || position < 0)
return new View(context);
Category c = (Category) getItem(position);
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = null;
if (convertView == null) {
layout = (LinearLayout) inflater.inflate(R.layout.item_category, parent, false);
} else {
if (convertView instanceof LinearLayout) {
layout = (LinearLayout) convertView;
}
}
if (layout == null)
return new View(context);
ImageView icon = (ImageView) layout.findViewById(R.id.icon);
icon.setImageResource(getImage(c.id, c.unread > 0));
TextView title = (TextView) layout.findViewById(R.id.title);
title.setText(formatItemTitle(c.title, c.unread));
if (c.unread > 0)
title.setTypeface(Typeface.DEFAULT_BOLD);
return layout;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE;
import org.ttrssreader.model.CategoryCursorHelper.MemoryDBOpenHelper;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class CustomCursorLoader extends CursorLoader {
protected static final String TAG = CustomCursorLoader.class.getSimpleName();
TYPE type;
int categoryId;
int feedId;
boolean selectArticlesForCategory;
public CustomCursorLoader(Context context, TYPE type, int categoryId, int feedId, boolean selectArticlesForCategory) {
super(context);
this.type = type;
this.categoryId = categoryId;
this.feedId = feedId;
this.selectArticlesForCategory = selectArticlesForCategory;
}
private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver();
@Override
public Cursor loadInBackground() {
MainCursorHelper cursorHelper = null;
SQLiteOpenHelper openHelper = new SQLiteOpenHelper(getContext(), DBHelper.DATABASE_NAME, null,
DBHelper.DATABASE_VERSION) {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new RuntimeException("Upgrade not implemented here!");
}
@Override
public void onCreate(SQLiteDatabase db) {
throw new RuntimeException("Create not implemented here!");
}
};
SQLiteDatabase db = openHelper.getReadableDatabase();
switch (type) {
case CATEGORY: {
MemoryDBOpenHelper memoryDbOpenHelper = new MemoryDBOpenHelper(getContext());
SQLiteDatabase memoryDb = memoryDbOpenHelper.getWritableDatabase();
cursorHelper = new CategoryCursorHelper(getContext(), memoryDb);
break;
}
case FEED:
cursorHelper = new FeedCursorHelper(getContext(), categoryId);
break;
case FEEDHEADLINE:
cursorHelper = new FeedHeadlineCursorHelper(getContext(), feedId, categoryId, selectArticlesForCategory);
break;
default:
return null;
}
Cursor cursor = cursorHelper.makeQuery(db);
if (cursor != null) {
// Ensure the cursor window is filled
cursor.getCount();
cursor.registerContentObserver(mObserver);
}
return cursor;
}
};
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.R;
import org.ttrssreader.model.pojos.Feed;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FeedAdapter extends MainAdapter {
protected static final String TAG = FeedAdapter.class.getSimpleName();
public FeedAdapter(Context context) {
super(context);
}
@Override
public Object getItem(int position) {
Feed ret = new Feed();
Cursor cur = getCursor();
if (cur == null)
return ret;
if (cur.getCount() >= position) {
if (cur.moveToPosition(position)) {
ret.id = cur.getInt(0);
ret.title = cur.getString(1);
ret.unread = cur.getInt(2);
}
}
return ret;
}
private int getImage(boolean unread) {
if (unread) {
return R.drawable.feedheadlinesunread48;
} else {
return R.drawable.feedheadlinesread48;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position >= getCount() || position < 0)
return new View(context);
Feed f = (Feed) getItem(position);
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = null;
if (convertView == null) {
layout = (LinearLayout) inflater.inflate(R.layout.item_feed, parent, false);
} else {
if (convertView instanceof LinearLayout) {
layout = (LinearLayout) convertView;
}
}
if (layout == null)
return new View(context);
ImageView icon = (ImageView) layout.findViewById(R.id.icon);
icon.setImageResource(getImage(f.unread > 0));
TextView title = (TextView) layout.findViewById(R.id.title);
title.setText(formatItemTitle(f.title, f.unread));
if (f.unread > 0)
title.setTypeface(Typeface.DEFAULT_BOLD);
return layout;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.model.CategoryCursorHelper.MemoryDBOpenHelper;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
public class ListContentProvider extends ContentProvider {
protected static final String TAG = ListContentProvider.class.getSimpleName();
private OpenHelper dbOpenHelper;
private static final String AUTHORITY = "org.ttrssreader";
// Uri path segments
private static final int CATS = 1;
private static final int FEEDS = 2;
private static final int HEADLINES = 3;
// Params
public static final String PARAM_CAT_ID = "categoryId";
public static final String PARAM_FEED_ID = "feedId";
public static final String PARAM_SELECT_FOR_CAT = "selectArticlesForCategory";
// Public information:
private static final String BASE_PATH_CATEGORIES = "categories";
private static final String BASE_PATH_FEEDS = "feeds";
private static final String BASE_PATH_HEADLINES = "headlines";
public static final Uri CONTENT_URI_CAT = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_CATEGORIES);
public static final Uri CONTENT_URI_FEED = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_FEEDS);
public static final Uri CONTENT_URI_HEAD = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_HEADLINES);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/listitems";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/listitem";
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
// Request all items:
sURIMatcher.addURI(AUTHORITY, BASE_PATH_CATEGORIES, CATS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS, FEEDS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH_HEADLINES, HEADLINES);
}
@Override
public boolean onCreate() {
dbOpenHelper = new OpenHelper(getContext(), DBHelper.DATABASE_NAME, DBHelper.DATABASE_VERSION);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// Parse parameters:
int categoryId = -1;
int feedId = -1;
boolean selectArticlesForCategory = false;
String paramCat = uri.getQueryParameter(PARAM_CAT_ID);
if (paramCat != null)
categoryId = Integer.parseInt(paramCat);
String paramFeedId = uri.getQueryParameter(PARAM_FEED_ID);
if (paramFeedId != null)
feedId = Integer.parseInt(paramFeedId);
String paramSelectArticles = uri.getQueryParameter(PARAM_SELECT_FOR_CAT);
if (paramSelectArticles != null)
selectArticlesForCategory = ("1".equals(paramSelectArticles));
// Retrieve CursorHelper:
MainCursorHelper cursorHelper = null;
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case CATS: {
MemoryDBOpenHelper memoryDbOpenHelper = new MemoryDBOpenHelper(getContext());
SQLiteDatabase memoryDb = memoryDbOpenHelper.getWritableDatabase();
cursorHelper = new CategoryCursorHelper(getContext(), memoryDb);
break;
}
case FEEDS:
cursorHelper = new FeedCursorHelper(getContext(), categoryId);
break;
case HEADLINES:
cursorHelper = new FeedHeadlineCursorHelper(getContext(), feedId, categoryId, selectArticlesForCategory);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
// Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
Cursor cursor = cursorHelper.makeQuery(db);
// make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new NoSuchMethodError(); // Not implemented!
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new NoSuchMethodError(); // Not implemented!
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new NoSuchMethodError(); // Not implemented!
}
class OpenHelper extends SQLiteOpenHelper {
public OpenHelper(Context context, String databaseName, int databaseVersion) {
super(context, databaseName, null, databaseVersion);
}
@Override
public void onCreate(SQLiteDatabase database) {
throw new NoSuchMethodError(); // Not implemented!
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
throw new NoSuchMethodError(); // Not implemented!
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.controllers.Data;
import org.ttrssreader.controllers.UpdateController;
import org.ttrssreader.model.pojos.Article;
import org.ttrssreader.model.pojos.Category;
import org.ttrssreader.model.pojos.Feed;
public class ReadStateUpdater implements IUpdatable {
protected static final String TAG = ReadStateUpdater.class.getSimpleName();
private int state;
private Collection<Category> categories = null;
private Collection<Feed> feeds = null;
private Collection<Article> articles = null;
public static enum TYPE {
ALL_CATEGORIES, ALL_FEEDS
}
public ReadStateUpdater(TYPE type) {
this(type, -1);
}
public ReadStateUpdater(TYPE type, int id) {
switch (type) {
case ALL_CATEGORIES:
categories = DBHelper.getInstance().getAllCategories();
break;
case ALL_FEEDS:
feeds = DBHelper.getInstance().getFeeds(id);
break;
}
}
public ReadStateUpdater(int categoryId) {
categories = new HashSet<Category>();
Category ci = DBHelper.getInstance().getCategory(categoryId);
if (ci != null) {
categories.add(ci);
}
}
public ReadStateUpdater(int feedId, int dummy) {
if (feedId <= 0 && feedId >= -4) { // Virtual Category...
categories = new HashSet<Category>();
Category ci = DBHelper.getInstance().getCategory(feedId);
if (ci != null)
categories.add(ci);
} else {
feeds = new HashSet<Feed>();
Feed fi = DBHelper.getInstance().getFeed(feedId);
if (fi != null)
feeds.add(fi);
}
}
/* articleState: 0 = mark as read, 1 = mark as unread */
public ReadStateUpdater(Article article, int pid, int articleState) {
articles = new ArrayList<Article>();
articles.add(article);
state = articleState;
article.isUnread = (articleState > 0);
}
/* articleState: 0 = mark as read, 1 = mark as unread */
public ReadStateUpdater(Collection<Article> articlesList, int pid, int articleState) {
articles = new ArrayList<Article>();
articles.addAll(articlesList);
state = articleState;
for (Article article : articles) {
article.isUnread = (articleState > 0);
}
}
@Override
public void update(Updater parent) {
if (categories != null) {
for (Category ci : categories) {
// VirtualCats are actually Feeds (the server handles them as such) so we have to set isCat to false
if (ci.id >= 0) {
Data.getInstance().setRead(ci.id, true);
} else {
Data.getInstance().setRead(ci.id, false);
}
UpdateController.getInstance().notifyListeners();
}
} else if (feeds != null) {
for (Feed fi : feeds) {
Data.getInstance().setRead(fi.id, false);
UpdateController.getInstance().notifyListeners();
}
} else if (articles != null) {
Set<Integer> ids = new HashSet<Integer>();
for (Article article : articles) {
ids.add(article.id);
article.isUnread = (state > 0);
}
if (!ids.isEmpty()) {
DBHelper.getInstance().markArticles(ids, "isUnread", state);
UpdateController.getInstance().notifyListeners();
Data.getInstance().setArticleRead(ids, state);
}
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
import org.ttrssreader.controllers.Data;
public class UnsubscribeUpdater implements IUpdatable {
protected static final String TAG = UnsubscribeUpdater.class.getSimpleName();
private int feed_id;
public UnsubscribeUpdater(int feed_id) {
this.feed_id = feed_id;
}
@Override
public void update(Updater parent) {
Data.getInstance().feedUnsubscribe(feed_id);
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.ttrssreader.gui.interfaces.IUpdateEndListener;
import org.ttrssreader.utils.AsyncTask;
import org.ttrssreader.utils.WeakReferenceHandler;
import android.app.Activity;
import android.os.Message;
public class Updater extends AsyncTask<Void, Void, Void> {
private IUpdatable updatable;
public Updater(Activity parent, IUpdatable updatable) {
this(parent, updatable, false);
}
public Updater(Activity parent, IUpdatable updatable, boolean goBackAfterUpdate) {
this.updatable = updatable;
if (parent instanceof IUpdateEndListener)
this.handler = new MsgHandler((IUpdateEndListener) parent, goBackAfterUpdate);
}
// Use handler with weak reference on parent object
private static class MsgHandler extends WeakReferenceHandler<IUpdateEndListener> {
boolean goBackAfterUpdate;
public MsgHandler(IUpdateEndListener parent, boolean goBackAfterUpdate) {
super(parent);
this.goBackAfterUpdate = goBackAfterUpdate;
}
@Override
public void handleMessage(IUpdateEndListener parent, Message msg) {
parent.onUpdateEnd(goBackAfterUpdate);
}
}
private MsgHandler handler;
@Override
protected Void doInBackground(Void... params) {
updatable.update(this);
if (handler != null)
handler.sendEmptyMessage(0);
return null;
}
@SuppressWarnings("unchecked")
public AsyncTask<Void, Void, Void> exec() {
if (sExecuteMethod != null) {
try {
return (AsyncTask<Void, Void, Void>) sExecuteMethod.invoke(this, AsyncTask.THREAD_POOL_EXECUTOR,
(Void[]) null);
} catch (InvocationTargetException unused) {
} catch (IllegalAccessException unused) {
}
}
return this.execute();
}
private Method sExecuteMethod = findExecuteMethod();
// Why do we use this here though we have a method for this in Controller.isExecuteOnExecutorAvailable()?
// -> There are many places we would have to alter and it would be the same code over and over again, so just leave
// this here, it works.
private Method findExecuteMethod() {
// Didn't get Class.getMethod() to work so I just search for the right method-name and take the first hit.
Class<?> cls = AsyncTask.class;
for (Method m : cls.getMethods()) {
if ("executeOnExecutor".equals(m.getName()))
return m;
}
return null;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
public interface IUpdatable {
public void update(Updater parent);
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.controllers.Data;
import org.ttrssreader.controllers.UpdateController;
import org.ttrssreader.model.pojos.Article;
public class StarredStateUpdater implements IUpdatable {
protected static final String TAG = StarredStateUpdater.class.getSimpleName();
private Article article;
private int articleState;
/**
* Sets the articles' Starred-Status according to articleState
*/
public StarredStateUpdater(Article article, int articleState) {
this.article = article;
this.articleState = articleState;
}
@Override
public void update(Updater parent) {
if (articleState >= 0) {
article.isStarred = articleState > 0 ? true : false;
DBHelper.getInstance().markArticle(article.id, "isStarred", articleState);
UpdateController.getInstance().notifyListeners();
Data.getInstance().setArticleStarred(article.id, articleState);
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.controllers.Data;
import org.ttrssreader.controllers.UpdateController;
import org.ttrssreader.model.pojos.Article;
public class PublishedStateUpdater implements IUpdatable {
protected static final String TAG = PublishedStateUpdater.class.getSimpleName();
private Article article;
private int articleState;
private String note;
/**
* Sets the articles' Published-Status according to articleState
*/
public PublishedStateUpdater(Article article, int articleState) {
this.article = article;
this.articleState = articleState;
this.note = null;
}
/**
* Sets the articles' Published-Status according to articleState and adds the given note to the article.
*/
public PublishedStateUpdater(Article article, int articleState, String note) {
this.article = article;
this.articleState = articleState;
this.note = note;
}
@Override
public void update(Updater parent) {
if (articleState >= 0) {
article.isPublished = articleState > 0 ? true : false;
DBHelper.getInstance().markArticle(article.id, "isPublished", articleState);
UpdateController.getInstance().notifyListeners();
Data.getInstance().setArticlePublished(article.id, articleState, note);
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.updaters;
import org.ttrssreader.controllers.Data;
public class StateSynchronisationUpdater implements IUpdatable {
protected static final String TAG = StateSynchronisationUpdater.class.getSimpleName();
@Override
public void update(Updater parent) {
Data.getInstance().synchronizeStatus();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.controllers.Controller;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.utils.Utils;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class FeedCursorHelper extends MainCursorHelper {
protected static final String TAG = FeedCursorHelper.class.getSimpleName();
public FeedCursorHelper(Context context, int categoryId) {
super(context);
this.categoryId = categoryId;
}
@Override
public Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery) {
StringBuilder query = new StringBuilder();
String lastOpenedFeedsList = Utils.separateItems(Controller.getInstance().lastOpenedFeeds, ",");
boolean displayUnread = Controller.getInstance().onlyUnread();
boolean invertSortFeedCats = Controller.getInstance().invertSortFeedscats();
if (overrideDisplayUnread)
displayUnread = false;
if (lastOpenedFeedsList.length() > 0 && !buildSafeQuery) {
query.append("SELECT _id,title,unread FROM (");
}
query.append("SELECT _id,title,unread FROM ");
query.append(DBHelper.TABLE_FEEDS);
query.append(" WHERE categoryId=");
query.append(categoryId);
query.append(displayUnread ? " AND unread>0" : "");
if (lastOpenedFeedsList.length() > 0 && !buildSafeQuery) {
query.append(" UNION SELECT _id,title,unread");
query.append(" FROM feeds WHERE _id IN (");
query.append(lastOpenedFeedsList);
query.append(" ))");
}
query.append(" ORDER BY UPPER(title) ");
query.append(invertSortFeedCats ? "DESC" : "ASC");
query.append(buildSafeQuery ? " LIMIT 200" : " LIMIT 600");
return db.rawQuery(query.toString(), null);
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.pojos;
public class Category implements Comparable<Category> {
public int id;
public String title;
public int unread;
public Category() {
this.id = 0;
this.title = "";
this.unread = 0;
}
public Category(int id, String title, int unread) {
this.id = id;
this.title = title;
this.unread = unread;
}
@Override
public int compareTo(Category ci) {
// Sort by Id if Id is 0 or smaller, else sort by Title
if (id <= 0 || ci.id <= 0) {
Integer thisInt = id;
Integer thatInt = ci.id;
return thisInt.compareTo(thatInt);
}
return title.compareToIgnoreCase(ci.title);
}
@Override
public boolean equals(Object o) {
if (o instanceof Category) {
Category other = (Category) o;
return (id == other.id);
} else {
return false;
}
}
@Override
public int hashCode() {
return id + "".hashCode();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.pojos;
public class Feed implements Comparable<Feed> {
public int id;
public int categoryId;
public String title;
public String url;
public int unread;
public Feed() {
this.id = 0;
this.categoryId = 0;
this.title = "";
this.url = "";
this.unread = 0;
}
public Feed(int id, int categoryId, String title, String url, int unread) {
this.id = id;
this.categoryId = categoryId;
this.title = title;
this.url = url;
this.unread = unread;
}
@Override
public int compareTo(Feed fi) {
return title.compareToIgnoreCase(fi.title);
}
@Override
public boolean equals(Object o) {
if (o instanceof Feed) {
Feed other = (Feed) o;
return (id == other.id);
} else {
return false;
}
}
@Override
public int hashCode() {
return id + "".hashCode();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2013 I. Lubimov.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.pojos;
import java.util.Date;
/**
* this class represents remote file (image, attachment, etc)
* belonging to article(s), which may be locally stored (cached)
*
* @author igor
*/
public class RemoteFile implements Comparable<RemoteFile> {
/** numerical ID */
public int id;
/** remote file URL */
public String url;
/** file size */
public int length;
/** extension - some kind of additional info (i.e. file extension) */
public String ext;
/** last change date */
public Date updated;
/** boolean flag determining if the file is locally stored */
public volatile boolean cached;
/**
* default constructor
*/
public RemoteFile() {
}
/**
* constructor with parameters
*
* @param id
* numerical ID
* @param url
* remote file URL
* @param length
* file size
* @param ext
* extension - some kind of additional info
* @param updated
* last change date
* @param cached
* boolean flag determining if the file is locally stored
*/
public RemoteFile(int id, String url, int length, String ext, Date updated, boolean cached) {
this.id = id;
this.url = url;
this.length = length;
this.ext = ext;
this.updated = updated;
this.cached = cached;
}
@Override
public int compareTo(RemoteFile rf) {
return rf.updated.compareTo(this.updated);
}
@Override
public boolean equals(Object o) {
boolean isEqual = false;
if (o != null && o instanceof RemoteFile) {
RemoteFile rf = (RemoteFile) o;
isEqual = (id == rf.id);
}
return isEqual;
}
@Override
public int hashCode() {
return id;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.pojos;
public class Label implements Comparable<Label> {
public Integer id;
public String caption;
public boolean checked;
public boolean checkedChanged = false;
public String foregroundColor;
public String backgroundColor;
@Override
public int compareTo(Label l) {
return id.compareTo(l.id);
}
@Override
public boolean equals(Object o) {
if (o instanceof Label) {
Label other = (Label) o;
return (id == other.id);
} else {
return false;
}
}
@Override
public int hashCode() {
return id + "".hashCode();
}
@Override
public String toString() {
return caption + ";" + foregroundColor + ";" + backgroundColor;
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
* Copyright (C) 2009-2010 J. Devauchelle.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model.pojos;
import java.util.Date;
import java.util.Set;
public class Article implements Comparable<Article> {
public int id;
public String title;
public int feedId;
public volatile boolean isUnread;
public String url;
public String commentUrl;
public Date updated;
public String content;
public Set<String> attachments;
public boolean isStarred;
public boolean isPublished;
public Integer cachedImages;
public Set<Label> labels;
public String author;
public Article() {
id = -1;
title = null;
isUnread = false;
updated = null;
feedId = 0;
content = null;
url = null;
commentUrl = null;
attachments = null;
labels = null;
isStarred = false;
isPublished = false;
author = null;
}
public Article(int id, int feedId, String title, boolean isUnread, String articleUrl, String articleCommentUrl,
Date updateDate, String content, Set<String> attachments, boolean isStarred, boolean isPublished,
int cachedImages, Set<Label> labels, String author) {
this.id = id;
this.title = title;
this.feedId = feedId;
this.isUnread = isUnread;
this.updated = updateDate;
this.url = articleUrl.trim();
this.commentUrl = articleCommentUrl;
if (content == null || content.equals("null")) {
this.content = null;
} else {
this.content = content;
}
this.attachments = attachments;
this.isStarred = isStarred;
this.isPublished = isPublished;
this.labels = labels;
this.cachedImages = cachedImages;
this.author = author;
}
@Override
public int compareTo(Article ai) {
return ai.updated.compareTo(this.updated);
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (o instanceof Article) {
Article ac = (Article) o;
return id == ac.id;
}
return false;
}
@Override
public int hashCode() {
return id;
}
public enum ArticleField {
id, title, unread, updated, feed_id, content, link, comments, attachments, marked, published, labels,
is_updated, tags, feed_title, comments_count, comments_link, always_display_attachments, author, score, lang,
note
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.controllers.Controller;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public abstract class MainCursorHelper {
protected static final String TAG = MainCursorHelper.class.getSimpleName();
protected Context context;
protected int categoryId = Integer.MIN_VALUE;
protected int feedId = Integer.MIN_VALUE;
protected boolean selectArticlesForCategory;
public MainCursorHelper(Context context) {
this.context = context;
}
/**
* Creates a new query
*
* @param force
* forces the creation of a new query
*/
public Cursor makeQuery(SQLiteDatabase db) {
Cursor cursor = null;
try {
if (categoryId == 0 && (feedId == -1 || feedId == -2)) {
// Starred/Published
cursor = createCursor(db, true, false);
} else {
// normal query
cursor = createCursor(db, false, false);
// (categoryId == -2 || feedId >= 0): Normal feeds
// (categoryId == 0 || feedId == Integer.MIN_VALUE): Uncategorized Feeds
if ((categoryId == -2 || feedId >= 0) || (categoryId == 0 || feedId == Integer.MIN_VALUE)) {
if (Controller.getInstance().onlyUnread() && !checkUnread(cursor)) {
// Override unread if query was empty
cursor = createCursor(db, true, false);
}
}
}
} catch (Exception e) {
// Fail-safe-query
cursor = createCursor(db, false, true);
}
return cursor;
}
/**
* Tries to find out if the given cursor points to a dataset with unread articles in it, returns true if it does.
*
* @param cursor
* the cursor.
* @return true if there are unread articles in the dataset, else false.
*/
private static final boolean checkUnread(Cursor cursor) {
if (cursor == null || cursor.isClosed())
return false; // Check null or closed
if (!cursor.moveToFirst())
return false; // Check empty
do {
if (cursor.getInt(cursor.getColumnIndex("unread")) > 0)
return cursor.moveToFirst(); // One unread article found, move to first entry
} while (cursor.moveToNext());
cursor.moveToFirst();
return false;
}
abstract Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery);
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.controllers.Controller;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.controllers.Data;
import org.ttrssreader.utils.Utils;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class FeedHeadlineCursorHelper extends MainCursorHelper {
protected static final String TAG = FeedHeadlineCursorHelper.class.getSimpleName();
public FeedHeadlineCursorHelper(Context context, int feedId, int categoryId, boolean selectArticlesForCategory) {
super(context);
this.feedId = feedId;
this.categoryId = categoryId;
this.selectArticlesForCategory = selectArticlesForCategory;
}
@Override
public Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery) {
String query;
if (feedId > -10)
query = buildFeedQuery(overrideDisplayUnread, buildSafeQuery);
else
query = buildLabelQuery(overrideDisplayUnread, buildSafeQuery);
return db.rawQuery(query, null);
}
private String buildFeedQuery(boolean overrideDisplayUnread, boolean buildSafeQuery) {
String lastOpenedArticlesList = Utils.separateItems(Controller.getInstance().lastOpenedArticles, ",");
boolean displayUnread = Controller.getInstance().onlyUnread();
boolean displayCachedImages = Controller.getInstance().onlyDisplayCachedImages();
boolean invertSortArticles = Controller.getInstance().invertSortArticlelist();
if (overrideDisplayUnread)
displayUnread = false;
StringBuilder query = new StringBuilder();
query.append("SELECT a._id AS _id, a.feedId AS feedId, a.title AS title, a.isUnread AS unread, a.updateDate AS updateDate, a.isStarred AS isStarred, a.isPublished AS isPublished FROM ");
query.append(DBHelper.TABLE_ARTICLES);
query.append(" a, ");
query.append(DBHelper.TABLE_FEEDS);
query.append(" b WHERE a.feedId=b._id");
switch (feedId) {
case Data.VCAT_STAR:
query.append(" AND a.isStarred=1");
break;
case Data.VCAT_PUB:
query.append(" AND a.isPublished=1");
break;
case Data.VCAT_FRESH:
query.append(" AND a.updateDate>");
query.append(System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge());
query.append(" AND a.isUnread>0");
break;
case Data.VCAT_ALL:
query.append(displayUnread ? " AND a.isUnread>0" : "");
break;
default:
// User selected to display all articles of a category directly
query.append(selectArticlesForCategory ? (" AND b.categoryId=" + categoryId)
: (" AND a.feedId=" + feedId));
query.append(displayUnread ? " AND a.isUnread>0" : "");
if (displayCachedImages) {
query.append(" AND 0 < (SELECT SUM(r.cached) FROM ");
query.append(DBHelper.TABLE_REMOTEFILE2ARTICLE);
query.append(" r2a, ");
query.append(DBHelper.TABLE_REMOTEFILES);
query.append(" r WHERE a._id=r2a.articleId and r2a.remotefileId=r.id) ");
}
}
if (lastOpenedArticlesList.length() > 0 && !buildSafeQuery) {
query.append(" UNION SELECT c._id AS _id, c.feedId AS feedId, c.title AS title, c.isUnread AS unread, c.updateDate AS updateDate, c.isStarred AS isStarred, c.isPublished AS isPublished FROM ");
query.append(DBHelper.TABLE_ARTICLES);
query.append(" c, ");
query.append(DBHelper.TABLE_FEEDS);
query.append(" d WHERE c.feedId=d._id AND c._id IN (");
query.append(lastOpenedArticlesList);
query.append(" )");
}
query.append(" ORDER BY a.updateDate ");
query.append(invertSortArticles ? "ASC" : "DESC");
query.append(" LIMIT 600 ");
return query.toString();
}
private String buildLabelQuery(boolean overrideDisplayUnread, boolean buildSafeQuery) {
String lastOpenedArticlesList = Utils.separateItems(Controller.getInstance().lastOpenedArticles, ",");
boolean displayUnread = Controller.getInstance().onlyUnread();
boolean invertSortArticles = Controller.getInstance().invertSortArticlelist();
if (overrideDisplayUnread)
displayUnread = false;
StringBuilder query = new StringBuilder();
query.append("SELECT a._id AS _id, a.feedId AS feedId, a.title AS title, a.isUnread AS unread, a.updateDate AS updateDate, a.isStarred AS isStarred, a.isPublished AS isPublished FROM ");
query.append(DBHelper.TABLE_ARTICLES);
query.append(" a, ");
query.append(DBHelper.TABLE_ARTICLES2LABELS);
query.append(" a2l, ");
query.append(DBHelper.TABLE_FEEDS);
query.append(" l WHERE a._id=a2l.articleId AND a2l.labelId=l._id");
query.append(" AND a2l.labelId=" + feedId);
query.append(displayUnread ? " AND isUnread>0" : "");
if (lastOpenedArticlesList.length() > 0 && !buildSafeQuery) {
query.append(" UNION SELECT b._id AS _id, b.feedId AS feedId, b.title AS title, b.isUnread AS unread, b.updateDate AS updateDate, b.isStarred AS isStarred, b.isPublished AS isPublished FROM ");
query.append(DBHelper.TABLE_ARTICLES);
query.append(" b, ");
query.append(DBHelper.TABLE_ARTICLES2LABELS);
query.append(" b2m, ");
query.append(DBHelper.TABLE_FEEDS);
query.append(" m WHERE b2m.labelId=m._id AND b2m.articleId=b._id");
query.append(" AND b._id IN (");
query.append(lastOpenedArticlesList);
query.append(" )");
}
query.append(" ORDER BY updateDate ");
query.append(invertSortArticles ? "ASC" : "DESC");
query.append(" LIMIT 600 ");
return query.toString();
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import org.ttrssreader.controllers.Controller;
import org.ttrssreader.controllers.DBHelper;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
public class CategoryCursorHelper extends MainCursorHelper {
protected static final String TAG = CategoryCursorHelper.class.getSimpleName();
/*
* This is quite a hack. Since partial-sorting of sql-results is not possible I wasn't able to sort virtual
* categories by id, Labels by title, insert uncategorized feeds there and sort categories by title again.
* No I insert these results one by one in a memory-table in the right order, add an auto-increment-column
* ("sortId INTEGER PRIMARY KEY") and afterwards select everything from this memory-table sorted by sortId.
* Works fine!
*/
private static final String INSERT = "REPLACE INTO " + MemoryDBOpenHelper.TABLE_NAME
+ " (_id, title, unread, sortId) VALUES (?, ?, ?, null)";
SQLiteDatabase memoryDb;
SQLiteStatement insert;
public CategoryCursorHelper(Context context, SQLiteDatabase memoryDb) {
super(context);
this.memoryDb = memoryDb;
insert = memoryDb.compileStatement(INSERT);
}
@Override
public Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery) {
boolean displayUnread = Controller.getInstance().onlyUnread();
boolean invertSortFeedCats = Controller.getInstance().invertSortFeedscats();
if (overrideDisplayUnread)
displayUnread = false;
memoryDb.delete(MemoryDBOpenHelper.TABLE_NAME, null, null);
StringBuilder query;
// Virtual Feeds
if (Controller.getInstance().showVirtual()) {
query = new StringBuilder();
query.append("SELECT _id,title,unread FROM ");
query.append(DBHelper.TABLE_CATEGORIES);
query.append(" WHERE _id>=-4 AND _id<0 ORDER BY _id");
insertValues(db, query.toString());
}
// Labels
query = new StringBuilder();
query.append("SELECT _id,title,unread FROM ");
query.append(DBHelper.TABLE_FEEDS);
query.append(" WHERE _id<-10");
query.append(displayUnread ? " AND unread>0" : "");
query.append(" ORDER BY UPPER(title) ASC");
query.append(" LIMIT 500 ");
insertValues(db, query.toString());
// "Uncategorized Feeds"
query = new StringBuilder();
query.append("SELECT _id,title,unread FROM ");
query.append(DBHelper.TABLE_CATEGORIES);
query.append(" WHERE _id=0");
insertValues(db, query.toString());
// Categories
query = new StringBuilder();
query.append("SELECT _id,title,unread FROM ");
query.append(DBHelper.TABLE_CATEGORIES);
query.append(" WHERE _id>0");
query.append(displayUnread ? " AND unread>0" : "");
query.append(" ORDER BY UPPER(title) ");
query.append(invertSortFeedCats ? "DESC" : "ASC");
query.append(" LIMIT 500 ");
insertValues(db, query.toString());
String[] columns = { "_id", "title", "unread" };
return memoryDb.query(MemoryDBOpenHelper.TABLE_NAME, columns, null, null, null, null, null, "600");
}
private void insertValues(SQLiteDatabase db, String query) {
Cursor c = null;
try {
c = db.rawQuery(query, null);
if (c == null)
return;
if (c.isBeforeFirst() && !c.moveToFirst())
return;
while (true) {
insert.bindLong(1, c.getInt(0)); // id
insert.bindString(2, c.getString(1)); // title
insert.bindLong(3, c.getInt(2)); // unread
insert.executeInsert();
if (!c.moveToNext())
break;
}
} finally {
if (c != null && !c.isClosed())
c.close();
}
}
static class MemoryDBOpenHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "categories_memory_db";
MemoryDBOpenHelper(Context context) {
super(context, null, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (_id INTEGER, title TEXT, unread INTEGER, sortId INTEGER PRIMARY KEY)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader.model;
import java.util.ArrayList;
import java.util.List;
import org.ttrssreader.R;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
public abstract class MainAdapter extends SimpleCursorAdapter {
protected static final String TAG = MainAdapter.class.getSimpleName();
private static final int layout = R.layout.main;
protected Context context;
public MainAdapter(Context context) {
super(context, layout, null, new String[] {}, new int[] {}, 0);
this.context = context;
}
@Override
public final long getItemId(int position) {
return position;
}
public final int getId(int position) {
int ret = Integer.MIN_VALUE;
Cursor cur = getCursor();
if (cur == null)
return ret;
if (cur.getCount() >= position)
if (cur.moveToPosition(position))
ret = cur.getInt(0);
return ret;
}
public final List<Integer> getIds() {
List<Integer> ret = new ArrayList<Integer>();
Cursor cur = getCursor();
if (cur == null)
return ret;
if (cur.moveToFirst()) {
while (!cur.isAfterLast()) {
ret.add(cur.getInt(0));
cur.move(1);
}
}
return ret;
}
protected static final CharSequence formatItemTitle(String title, int unread) {
if (unread > 0) {
return title + " (" + unread + ")";
} else {
return title;
}
}
@Override
public abstract Object getItem(int position);
@Override
public abstract View getView(int position, View convertView, ViewGroup parent);
}
| Java |
/*
* ttrss-reader-fork for Android
*
* Copyright (C) 2010 Nils Braden
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.ttrssreader;
import org.ttrssreader.controllers.Controller;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.controllers.Data;
import org.ttrssreader.controllers.ProgressBarManager;
import org.ttrssreader.controllers.UpdateController;
import org.ttrssreader.utils.AsyncTask;
import android.app.Application;
import android.content.Context;
import android.view.WindowManager;
public class MyApplication extends Application {
protected static final String TAG = MyApplication.class.getSimpleName();
public void onCreate() {
super.onCreate();
// make sure AsyncTask is loaded in the Main thread
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
return null;
}
}.execute();
initSingletons();
}
protected void initSingletons() {
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
ProgressBarManager.getInstance();
Controller.getInstance().checkAndInitializeController(this, wm.getDefaultDisplay());
DBHelper.getInstance().checkAndInitializeDB(this);
Data.getInstance().checkAndInitializeData(this);
UpdateController.getInstance().notifyListeners(); // Notify once to make sure the handler is initialized
}
@Override
public void onLowMemory() {
Controller.getInstance().lowMemory(true);
super.onLowMemory();
}
}
| Java |
Hola Mundo!!! | Java |
package hocusPocus.Controllers;
import hocusPocus.IHM.NombreJoueurs;
import hocusPocus.IHM.TypeDePartie;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ControllerTypeDePartie implements ActionListener {
TypeDePartie typePartie;
NombreJoueurs nbJoueur;
public ControllerTypeDePartie(TypeDePartie typePartie) {
this.typePartie = typePartie;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == typePartie.normale){
TypeDePartie.partieNormale = true;
TypeDePartie.partieRapide = false;
}
if(e.getSource() == typePartie.rapide){
TypeDePartie.partieRapide = true;
TypeDePartie.partieNormale = false;
}
if(e.getSource()==typePartie.ok){
if(TypeDePartie.partieRapide == false && TypeDePartie.partieNormale == false)
JOptionPane.showMessageDialog(null,"Erreur : pas de Type de partie choisi", "Erreur", JOptionPane.ERROR_MESSAGE);
else{
if(TypeDePartie.partieRapide)
System.out.println("Selection : partie rapide");
else
System.out.println("Selection : partie normale");
typePartie.dispose();
new NombreJoueurs(); // Demander le nombre de joueurs
}
}
if(e.getSource() == typePartie.annuler){
typePartie.dispose();
}
}
}
| Java |
package hocusPocus.Controllers;
import hocusPocus.IHM.ChoixFinTour;
import hocusPocus.IHM.EchangerMainGrimoire;
import hocusPocus.IHM.LimiteCarteMain;
import hocusPocus.IHM.InteractionJoueur;
import hocusPocus.IHM.InterfacePlateau;
import hocusPocus.Partie.AnalyseZoneDeJeu;
import hocusPocus.Partie.Plateau;
import hocusPocus.Partie.ResoudrePouvoirHocus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ControllerInterfacePlateau implements ActionListener{
private InterfacePlateau interfacePlateau;
private boolean isPossible;
private Plateau plateau;
public ControllerInterfacePlateau(InterfacePlateau interfacePlateau) {
this.interfacePlateau = interfacePlateau;
this.plateau = Plateau.getInstance();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()!=null) {
if(e.getSource() == interfacePlateau.btnJouerCarte) { // Clic sur JouerCarte
isPossible = plateau.getJoueurCourant().jouerCarte(interfacePlateau.getCarteSelectionee());
if(!isPossible) {
JOptionPane.showMessageDialog(null,"Impossible de joueur ce type de carte.\n Pour plus de detail: Aide>RegleDuJeu ","ERREUR",JOptionPane.ERROR_MESSAGE);
}else {
if(plateau.getJoueurReagissant() == null || plateau.getJoueurCourant().equals(plateau.getJoueurReagissant()))
interfacePlateau.rafraichirPanelJoueurCourant(); // On rafraichit apres pose de la carte
else
interfacePlateau.rafraichirPanelJoueurReagissant();
interfacePlateau.rafraichirPanelZoneDeJeu();
interfacePlateau.rafraichirPanelListeJoueurs();
AnalyseZoneDeJeu analyse = new AnalyseZoneDeJeu();
analyse.Analyse(); //
interfacePlateau.btnJouerCarte.setEnabled(false); // On desactive le bouton jusqu'a ce qu'une carte soit selectionnnee
}
}
if(e.getSource() == interfacePlateau.btnPasserTour) {
System.out.println("Terminer le tour");
new ChoixFinTour(interfacePlateau);
}
if(e.getSource() == interfacePlateau.btnEchangerCartes) {
new EchangerMainGrimoire(interfacePlateau);
}
}
}
}
| Java |
package hocusPocus.Controllers;
import hocusPocus.IHM.DesignerJoueur;
import hocusPocus.IHM.InteractionJoueur;
import hocusPocus.Partie.Plateau;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControllerDesignerJoueur implements ActionListener{
DesignerJoueur designerJoueur;
public ControllerDesignerJoueur(DesignerJoueur designerJoueur) {
this.designerJoueur = designerJoueur;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == designerJoueur.btnOk) {
for(javax.swing.JRadioButton button : designerJoueur.bNom) {
if(button.isSelected()) {
Plateau.getInstance().setJoueurCible(designerJoueur.listeJoueurs.get(button));
new InteractionJoueur();
designerJoueur.dispose();
}
}
}
}
}
| Java |
package hocusPocus.Controllers;
import hocusPocus.Cartes.Carte;
import hocusPocus.IHM.InteractionJoueur;
import hocusPocus.IHM.InterfacePlateau;
import hocusPocus.Partie.AnalyseZoneDeJeu;
import hocusPocus.Partie.Jeu;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import hocusPocus.Partie.ResoudrePouvoirHocus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControllerInteractionJoueur implements ActionListener{
private InteractionJoueur interactionJoueur;
private InterfacePlateau interfacePlateau;
public ControllerInteractionJoueur(InteractionJoueur interactionJoueur) {
this.interactionJoueur = interactionJoueur;
this.interfacePlateau = Jeu.getInstance().getInterfacePlateau();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() != null) {
if(e.getSource() == interactionJoueur.btnOk) {
for(int i = 0; i < interactionJoueur.tableIndexJoueur.size(); i ++) {
if(interactionJoueur.tableIndexJoueur.get(i).isSelected()){ // Joueur voulant reagir
Plateau.getInstance().setJoueurReagissant(Jeu.getListeJoueurs().get(i));
interfacePlateau.rafraichirPanelJoueurReagissant();
interfacePlateau.rafraichirPanelActionJoueur();
interactionJoueur.dispose();
}
}
}
if(e.getSource() == interactionJoueur.btnResoudreCartes) { // Resolution des cartes
AnalyseZoneDeJeu analyseZoneDeJeu = new AnalyseZoneDeJeu();
analyseZoneDeJeu.Resolution();
Plateau.getInstance().setJoueurReagissant(Plateau.getInstance().getJoueurCourant());
interfacePlateau.rafraichirPanelJoueurCourant();
interfacePlateau.rafraichirPanelActionJoueur();
interactionJoueur.dispose();
// Pose d'une nouvelle Hocus ou fin du tour
}
}
}
}
| Java |
package hocusPocus.Controllers;
import hocusPocus.IHM.ChoixFinTour;
import hocusPocus.IHM.InterfacePlateau;
import hocusPocus.IHM.LimiteCarteMain;
import hocusPocus.Partie.Plateau;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ControllerChoixFinTour implements ActionListener {
private ChoixFinTour choixFinTour;
private InterfacePlateau interfacePlateau;
private Plateau plateau;
public ControllerChoixFinTour(ChoixFinTour choixFinTour, InterfacePlateau interfacePlateau) {
this.choixFinTour = choixFinTour;
this.interfacePlateau = interfacePlateau;
this.plateau = Plateau.getInstance();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == choixFinTour.cartes){
ChoixFinTour.piocherCarte = true;
ChoixFinTour.piocherGemmes = false;
}
if(e.getSource() == choixFinTour.gemme){
ChoixFinTour.piocherCarte = false;
ChoixFinTour.piocherGemmes = true;
}
if(e.getSource() == choixFinTour.ok){
if(ChoixFinTour.piocherGemmes == false && ChoixFinTour.piocherCarte == false)
JOptionPane.showMessageDialog(null,"Erreur : pas de pioche choisie", "Erreur", JOptionPane.ERROR_MESSAGE);
else{
if(ChoixFinTour.piocherGemmes) {
System.out.println("Selection : pioche gemme");
plateau.getJoueurCourant().ajouterUnGemme(plateau.getChaudron().piocherUnGemme());
}
else {
System.out.println("Selection : pioche cartes");
plateau.getJoueurCourant().ajouterCartesMain(plateau.getBibliotheque().piocherCarte(2));
if(plateau.getJoueurCourant().getMain().size() > 5) {
new LimiteCarteMain(interfacePlateau);
}
}
plateau.joueurSuivant(plateau.getJoueurCourant()); // Changement de joueur courant
plateau.setJoueurReagissant(plateau.getJoueurCourant());
plateau.defausserZDJ(); // ON VIDE LA ZDJ POUR LE MOMENT
choixFinTour.dispose();
ChoixFinTour.piocherCarte = false;
ChoixFinTour.piocherGemmes = false;
}
JOptionPane.showMessageDialog(null, "A " + plateau.getJoueurCourant().getNom() + " de jouer.");
interfacePlateau.rafraichirPlateauEntier();
}
}
}
| Java |
package hocusPocus.Controllers;
import hocusPocus.IHM.InformationJoueur;
import hocusPocus.IHM.NombreJoueurs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControllerNbJoueur implements ActionListener {
public NombreJoueurs nbJoueur;
public InformationJoueur infoJoueur;
public ControllerNbJoueur(NombreJoueurs nbJoueur) {
this.nbJoueur = nbJoueur;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nbJoueur.btnOk) {
if (nbJoueur.radioButton.isSelected())
nbJoueur.setNbJoueurs(2);
if (nbJoueur.radioButton_1.isSelected())
nbJoueur.setNbJoueurs(3);
if (nbJoueur.radioButton_2.isSelected())
nbJoueur.setNbJoueurs(4);
if (nbJoueur.radioButton_3.isSelected())
nbJoueur.setNbJoueurs(5);
if (nbJoueur.radioButton_4.isSelected())
nbJoueur.setNbJoueurs(6);
nbJoueur.dispose();
infoJoueur = new InformationJoueur(nbJoueur.getNbJoueurs());
}
if (e.getSource() == nbJoueur.btnAnnuler) {
nbJoueur.dispose();
}
}
}
| Java |
package hocusPocus.Cartes;
public class PBaguetteMagique extends Carte{
public PBaguetteMagique(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.POCUS;
this.puissance = puissance;
this.infoBulle = "<html>POCUS Baguette Magique<br/>Doublez le chiffre d'une carte HOCUS<br/>(Une seule baguette magique par carte HOCUS)";
}
}
| Java |
package hocusPocus.Cartes;
public class HHibou extends Carte{
public HHibou(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.HOCUS;
this.puissance = puissance;
this.infoBulle = "<html>HOCUS Hiboux<br/>Volez " + getPuissance() + " carte(s) du<br/>grimoire d'un joueur de votre choix.";
}
}
| Java |
package hocusPocus.Cartes;
import java.util.ArrayList;
/**
* Permet de decrire l'ensemble des cartes a instancier
* suivant le nombre de joueurs (nom, nombre, pouvoir)
* @author Quentin
*
*/
public class DescriptionCartes {
public String nomCarte;
public int[] pouvoir;
public int nbExemplaire;
public static ArrayList<DescriptionCartes> partieDeuxJoueurs() {
ArrayList<DescriptionCartes> descriptionGlobale = new ArrayList<DescriptionCartes>();
for(int i = 0; i < 16; i++) {
DescriptionCartes description = new DescriptionCartes();
if(i == 0) {
description.nomCarte = "HAbracadabra";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 1) {
description.nomCarte = "HBouleDeCristal";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 2) {
description.nomCarte = "HHibou";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 3) {
description.nomCarte = "HInspiration";
description.nbExemplaire = 5;
description.pouvoir = new int[] {2, 2, 2, 3, 3};
}
if(i == 4) {
description.nomCarte = "HMalediction";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 5) {
description.nomCarte = "HSacrifice";
description.nbExemplaire = 2;
description.pouvoir = new int[] {2, 2};
}
if(i == 6) {
description.nomCarte = "HSortilege";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 7) {
description.nomCarte = "HVoleur";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 8) {
description.nomCarte = "HVortex";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 9) {
description.nomCarte = "PAmulette";
description.nbExemplaire = 7;
description.pouvoir = new int[] {0, 0, 0, 0, 0, 0, 0};
}
if(i == 10) {
description.nomCarte = "PBaguetteMagique";
description.nbExemplaire = 4;
description.pouvoir = new int[] {0, 0, 0, 0};
}
if(i == 11) {
description.nomCarte = "PChatNoir";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 12) {
description.nomCarte = "PCitrouille";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 13) {
description.nomCarte = "PContreSort";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 14) {
description.nomCarte = "PEclair";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 15) {
description.nomCarte = "PSablier";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
descriptionGlobale.add(description);
}
return descriptionGlobale;
}
public static ArrayList<DescriptionCartes> partiePlusDeDeuxJoueurs() {
ArrayList<DescriptionCartes> descriptionGlobale = new ArrayList<DescriptionCartes>();
for(int i = 0; i < 17; i++) {
DescriptionCartes description = new DescriptionCartes();
if(i == 0) {
description.nomCarte = "HAbracadabra";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 1) {
description.nomCarte = "HBouleDeCristal";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 2) {
description.nomCarte = "HHibou";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 3) {
description.nomCarte = "HInspiration";
description.nbExemplaire = 5;
description.pouvoir = new int[] {2, 2, 2, 3, 3};
}
if(i == 4) {
description.nomCarte = "HMalediction";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 5) {
description.nomCarte = "HSacrifice";
description.nbExemplaire = 2;
description.pouvoir = new int[] {2, 2};
}
if(i == 6) {
description.nomCarte = "HSortilege";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 7) {
description.nomCarte = "HVoleur";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 8) {
description.nomCarte = "HVortex";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 9) {
description.nomCarte = "PAmulette";
description.nbExemplaire = 4; // Retirer 3
description.pouvoir = new int[] {0, 0, 0, 0};
}
if(i == 10) {
description.nomCarte = "PBaguetteMagique";
description.nbExemplaire = 4;
description.pouvoir = new int[] {0, 0, 0, 0};
}
if(i == 11) {
description.nomCarte = "PChatNoir";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 12) {
description.nomCarte = "PCitrouille";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 13) {
description.nomCarte = "PContreSort";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 14) {
description.nomCarte = "PEclair";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 15) {
description.nomCarte = "PMiroirEnchante";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 16) {
description.nomCarte = "PSablier";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
descriptionGlobale.add(description);
}
return descriptionGlobale;
}
}
| Java |
package hocusPocus.Cartes;
public class HAbracadabra extends Carte{
public HAbracadabra(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.HOCUS;
this.puissance = puissance;
this.infoBulle = "<html>HOCUS Abracadabra<br/>Echangez votre main avec celle<br/>d'un joueur de votre choix.";
}
}
| Java |
package hocusPocus.Cartes;
public class HVoleur extends Carte{
public HVoleur(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.HOCUS;
this.puissance = puissance;
this.infoBulle = "<html>HOCUS Voleur<br/>Volez " + getPuissance() + " gemme(s) d'un joueur<br/>de votre choix";
}
}
| Java |
package hocusPocus.Cartes;
import hocusPocus.Partie.Joueur;
public class Carte {
protected int puissance; // Correspond au numero en haut a droite de la carte Hocus -> '0' pour Pocus
protected String recto; // Nom du fichier image de la carte
protected String verso = "verso.png";
protected typeCarte typecarte; // Hocus ou Pocus
protected String localisation; // Stocker l'endroit de la carte : main, grimoire, zonedejeu,bibliotheque
protected boolean estJouable; //permettant de verifier qu'une carte peut etre jouee dans le tour actuel
protected Joueur joueurPossesseur;
protected String infoBulle;
public String getRecto() {
return recto;
}
public String getVerso() {
return verso;
}
public String getLocalisation() {
return localisation;
}
public void setLocalisation(String localisation) {
this.localisation = localisation;
}
public int getPuissance() {
return puissance;
}
public String getInfoBulle() {
return infoBulle;
}
public Joueur getJoueurPossesseur() {
return joueurPossesseur;
}
public void setJoueurPossesseur(Joueur joueurPossesseur) {
this.joueurPossesseur = joueurPossesseur;
}
public typeCarte getTypecarte() {
return typecarte;
}
public void setTypecarte(typeCarte typecarte) {
this.typecarte = typecarte;
}
public void setPuissance(int puissance) {
this.puissance = puissance;
}
@Override
public String toString() {
return "\nCarte [puissance=" + puissance + ",\n recto=" + recto
+ ",\n verso=" + verso + ",\n typecarte=" + typecarte
+ ",\n localisation=" + localisation + ",\n estJouable="
+ estJouable + ",\n joueurPossesseur=" + joueurPossesseur + "]\n";
}
}
| Java |
package hocusPocus.Cartes;
public enum typeCarte {
HOCUS,
POCUS;
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerTypeDePartie;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
import java.awt.Toolkit;
public class TypeDePartie extends JDialog {
private static final long serialVersionUID = 1L;
public static boolean partieNormale = true;
public static boolean partieRapide = false;
public JRadioButton normale;
public JRadioButton rapide;
public ButtonGroup group;
public JButton ok;
public JButton annuler;
/**
* Creer la fenetre qui permet de selectionner le
* type de partie: normale ou rapide
*/
public TypeDePartie(){
setIconImage(Toolkit.getDefaultToolkit().getImage(TypeDePartie.class.getResource("/images/icone.gif")));
setResizable(false);
setTitle("Hocus Pocus");
ControllerTypeDePartie controleTypeDePartie = new ControllerTypeDePartie(this);
this.setBounds(100, 100, 299, 207);
this.setLocationRelativeTo(this.getParent());
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel label = new JLabel("Type de partie : ");
label.setBounds(22, 11, 178, 14);
this.getContentPane().add(label);
group = new ButtonGroup();
normale = new JRadioButton("Normale");
normale.setBounds(97, 37, 109, 23);
normale.setSelected(true);
normale.addActionListener(controleTypeDePartie);
this.getContentPane().add(normale);
rapide= new JRadioButton("Rapide");
rapide.setBounds(97, 74, 109, 23);
rapide.addActionListener(controleTypeDePartie);
this.getContentPane().add(rapide);
group.add(normale);
group.add(rapide);
ok = new JButton("OK");
ok.setBounds(47, 133, 89, 23);
ok.addActionListener(controleTypeDePartie);
this.getContentPane().add(ok);
annuler = new JButton("Annuler");
annuler.setBounds(165, 133, 89, 23);
this.getContentPane().add(annuler);
annuler.addActionListener(controleTypeDePartie);
this.setVisible(true);
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerNbJoueur;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
import java.awt.Toolkit;
/**
* Fenetre permettant de demander a l'utilisateur le nombre
* de joueurs a inclure dans la partie
* @author Quentin
*
*/
public class NombreJoueurs extends JFrame{
private static final long serialVersionUID = 1L;
public int nbJoueurs = 2;
public JButton btnOk;
public JButton btnAnnuler;
public JRadioButton radioButton, radioButton_1, radioButton_2, radioButton_3, radioButton_4;
public NombreJoueurs() throws HeadlessException {
setIconImage(Toolkit.getDefaultToolkit().getImage(NombreJoueurs.class.getResource("/images/icone.gif")));
setResizable(false);
recupererNombreJoueurs();
}
public void recupererNombreJoueurs() {
ControllerNbJoueur controle = new ControllerNbJoueur(this);
final ButtonGroup buttonGroup = new ButtonGroup();
this.setTitle("Hocus Pocus");
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 297, 293);
this.setLocationRelativeTo(this.getParent()); // Centrer la fenetre
getContentPane().setLayout(null);
JLabel lblNbJoueurs = new JLabel("Veuillez s\u00E9lectionner le nombre de joueurs");
lblNbJoueurs.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblNbJoueurs.setBounds(10, 11, 292, 28);
getContentPane().add(lblNbJoueurs);
radioButton = new JRadioButton("2");
radioButton.setSelected(true);
buttonGroup.add(radioButton);
radioButton.setBounds(44, 47, 109, 25);
getContentPane().add(radioButton);
radioButton_1 = new JRadioButton("3");
buttonGroup.add(radioButton_1);
radioButton_1.setBounds(44, 107, 109, 25);
getContentPane().add(radioButton_1);
radioButton_2 = new JRadioButton("4");
buttonGroup.add(radioButton_2);
radioButton_2.setBounds(44, 167, 127, 25);
getContentPane().add(radioButton_2);
radioButton_3 = new JRadioButton("5");
buttonGroup.add(radioButton_3);
radioButton_3.setBounds(156, 47, 127, 25);
getContentPane().add(radioButton_3);
radioButton_4 = new JRadioButton("6");
buttonGroup.add(radioButton_4);
radioButton_4.setBounds(156, 107, 127, 25);
getContentPane().add(radioButton_4);
btnOk = new JButton("Ok");
btnOk.addActionListener(controle);
btnOk.setBounds(25, 219, 97, 25);
getContentPane().add(btnOk);
btnAnnuler = new JButton("Annuler");
btnAnnuler.addActionListener(controle);
btnAnnuler.setBounds(157, 219, 97, 25);
getContentPane().add(btnAnnuler);
this.setVisible(true);
}
public void setNbJoueurs(int nbJoueurs) {
this.nbJoueurs = nbJoueurs;
}
public int getNbJoueurs() {
return nbJoueurs;
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerChoixFinTour;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
import java.awt.Toolkit;
public class ChoixFinTour extends JFrame {
private static final long serialVersionUID = 1L;
public static boolean piocherCarte = false;
public static boolean piocherGemmes = false;
public JRadioButton cartes;
public JRadioButton gemme;
public ButtonGroup group;
public JButton ok;
/**
* Creer la fenetre qui permet de choisir le
* type de pioche du joueur gaganant le tour
*/
public ChoixFinTour(InterfacePlateau interfacePlateau){
setIconImage(Toolkit.getDefaultToolkit().getImage(ChoixFinTour.class.getResource("/images/icone.gif")));
setResizable(false);
setTitle("Hocus Pocus");
ControllerChoixFinTour controleChoixFinTour = new ControllerChoixFinTour(this, interfacePlateau);
this.setBounds(100, 100, 299, 207);
this.setLocationRelativeTo(this.getParent());
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel label = new JLabel("Fin du tour, choisir type de pioche : ");
label.setBounds(22, 11, 219, 14);
this.getContentPane().add(label);
group = new ButtonGroup();
cartes = new JRadioButton("2 cartes");
cartes.setBounds(91, 48, 109, 23);
cartes.addActionListener(controleChoixFinTour);
this.getContentPane().add(cartes);
gemme= new JRadioButton("1 gemme");
gemme.setBounds(91, 85, 109, 23);
gemme.addActionListener(controleChoixFinTour);
this.getContentPane().add(gemme);
group.add(cartes);
group.add(gemme);
ok = new JButton("OK");
ok.setBounds(98, 135, 89, 23);
ok.addActionListener(controleChoixFinTour);
this.getContentPane().add(ok);
this.setVisible(true);
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerEcranAccueil;
import hocusPocus.Partie.Jeu;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
/**
* Affichage de la fenetre d'acceuil au demarrage
*
*/
public class EcranAccueil extends JFrame {
private Jeu jeu;
private static EcranAccueil _instance = null;
public JMenuItem mntmNouvellePartie;
public JMenuBar menuBar;
public JMenu mnPartie;
public JMenuItem mntmQuitter;
public JMenu mnAide;
public JMenuItem mntmRgleDuJeu;
public JMenu menu;
public JMenuItem mntmAPropos;
public JPanel contentPane;
private EcranAccueil() {
this.jeu = Jeu.getInstance();
lancerIHM();
}
public static EcranAccueil getInstance(){
if(_instance == null)
_instance = new EcranAccueil();
return _instance;
}
/**
* Creation de la fenetre principale avec la
* barre de menu
*/
public void lancerIHM() {
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int heigh = Toolkit.getDefaultToolkit().getScreenSize().height;
ControllerEcranAccueil controle = new ControllerEcranAccueil(this);
setIconImage(new ImageIcon(this.getClass().getResource("/images/icone.gif")).getImage());
setResizable(false);
setBackground(Color.WHITE);
setTitle("Hocus Pocus");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
setSize(width, heigh);
setLocation(0, 0);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnPartie = new JMenu("Partie");
menuBar.add(mnPartie);
mntmNouvellePartie = new JMenuItem("Nouvelle Partie");
mnPartie.add(mntmNouvellePartie);
mntmNouvellePartie.addActionListener(controle);
mntmQuitter = new JMenuItem("Quitter");
mntmQuitter.addActionListener(controle);
mnPartie.add(mntmQuitter);
mnAide = new JMenu("Aide");
menuBar.add(mnAide);
mntmRgleDuJeu = new JMenuItem("Regles du jeu");
mntmRgleDuJeu.addActionListener(controle);
mnAide.add(mntmRgleDuJeu);
menu = new JMenu("?");
menuBar.add(menu);
mntmAPropos = new JMenuItem("A Propos");
mntmAPropos.addActionListener(controle);
menu.add(mntmAPropos);
contentPane = new JPanel();
contentPane.setBackground(Color.YELLOW);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setIcon(new ImageIcon(EcranAccueil.class.getResource("/images/BoiteDuJeu.gif")));
contentPane.add(lblNewLabel, BorderLayout.WEST);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon(EcranAccueil.class.getResource("/images/carte.gif")));
contentPane.add(lblNewLabel_1, BorderLayout.EAST);
this.setVisible(true);
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Cartes.Carte;
import hocusPocus.Controllers.ControllerLimiteCarteMain;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
public class LimiteCarteMain extends JFrame {
private static final long serialVersionUID = 1L;
private Plateau plateau;
private Joueur joueurCourant;
public Hashtable<JToggleButton, Carte> tableCorrespondance;
public static Carte carteSelectionneeMain;
public JButton btnDefausser;
public JToggleButton jbutton;
public JPanel panelMain;
private InterfacePlateau interfacePlateau;
private ControllerLimiteCarteMain controller;
public LimiteCarteMain(InterfacePlateau interfacePlateau) {
setIconImage(Toolkit.getDefaultToolkit().getImage(
LimiteCarteMain.class.getResource("/images/icone.gif")));
setResizable(false);
plateau = Plateau.getInstance();
joueurCourant = plateau.getJoueurCourant();
tableCorrespondance = new Hashtable<JToggleButton, Carte>();
this.interfacePlateau = interfacePlateau;
getContentPane().setLayout(new GridLayout(1, 1, 0, 0));
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setSize(990, 506);
this.setTitle("Mettre en Defausse des cartes en Main");
this.setLocationRelativeTo(this.getParent()); // Centrer la fenetre
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(2, 1, 0, 0));
panelMain = new JPanel();
panelMain.setBorder(new TitledBorder(null, "Cartes en Main",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.add(panelMain);
JPanel Boutons = new JPanel();
panel.add(Boutons);
Boutons.setLayout(null);
controller = new ControllerLimiteCarteMain(this, joueurCourant, tableCorrespondance);
btnDefausser = new JButton("D\u00E9fausser");
btnDefausser.addActionListener(controller);
btnDefausser.setBounds(437, 79, 117, 23);
Boutons.add(btnDefausser);
JLabel lblVousNePouvez = new JLabel(
"Vous ne pouvez avoir que 5 cartes en Main Maximum !");
lblVousNePouvez.setHorizontalAlignment(SwingConstants.CENTER);
lblVousNePouvez.setBounds(10, 11, 964, 14);
Boutons.add(lblVousNePouvez);
JLabel lblVeuillezSlectionnerLes = new JLabel(
"Veuillez s\u00E9lectionner les cartes que vous souhaitez mettre sur la pile de d\u00E9fausse.");
lblVeuillezSlectionnerLes.setHorizontalAlignment(SwingConstants.CENTER);
lblVeuillezSlectionnerLes.setBounds(10, 42, 964, 14);
Boutons.add(lblVeuillezSlectionnerLes);
afficherMain();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void afficherMain() {
BufferedImage imageCarte = null;
final ButtonGroup groupeBoutonsCartesMain = new ButtonGroup();
for (int i = 0; i < joueurCourant.getMain().size(); i++) { // Affichage
// main
jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getMain().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getMain().get(i)
.getInfoBulle());
panelMain.add(jbutton);
groupeBoutonsCartesMain.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getMain().get(i));
jbutton.addActionListener(controller);
}
}
public void rafraichirAfficherMain() {
panelMain.removeAll();
panelMain.revalidate();
afficherMain();
}
public static BufferedImage resize(String nomImageCarte, int width,
int height) {
BufferedImage img = null;
ImprovedMultistepRescaleOp resampleOp = new ImprovedMultistepRescaleOp(
width, height);
try {
img = ImageIO.read(new File("./src/images/"
+ nomImageCarte.replace("hocusPocus.Cartes.", "")));
} catch (IOException e) {
e.printStackTrace();
}
return resampleOp.filter(img, null);
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Cartes.Carte;
import hocusPocus.Controllers.ControllerInterfacePlateau;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
import java.awt.Component;
import java.awt.Color;
public class InterfacePlateau extends JPanel{
public JButton btnJouerCarte, btnPasserTour, btnEchangerCartes;
public final HashMap<JToggleButton, Carte> tableCorrespondance = new HashMap<JToggleButton, Carte>();
private Plateau plateau ;
private Joueur joueurCourant, joueurReagissant ;
private JPanel panelListeJoueur, panelCartesJoueurCourant, panelChaudron, panelBibliotheque, panelZoneDeJeu, panelPlateauDeJeu, panelActionJoueur;
private Carte carteSelectionnee;
private int widthGrimoireJoueurAtt = 80; // Largeur cartes grimoire
private int heightGrimoireJoueurAtt = 110; // Hauteur cartes grimoire
private BufferedImage imageCarte ;
private JPanel grimoire;
private JPanel main;
private JPanel panelDefausse;
private JLabel lblCarteDefausse;
private JLabel imageCarteDefausse;
public InterfacePlateau() {
this.plateau = Plateau.getInstance();
this.joueurCourant = plateau.getJoueurCourant();
this.joueurReagissant = plateau.getJoueurReagissant();
setLayout(new BorderLayout(0, 0));
panelListeJoueur = new JPanel();
add(panelListeJoueur, BorderLayout.WEST);
GridBagLayout gbl_listeJoueur = new GridBagLayout();
gbl_listeJoueur.columnWidths = new int[] { 0, 0 };
gbl_listeJoueur.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0 };
gbl_listeJoueur.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gbl_listeJoueur.rowWeights = new double[] { 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, Double.MIN_VALUE };
panelListeJoueur.setLayout(gbl_listeJoueur);
afficherPanelListeJoueurs();
panelPlateauDeJeu = new JPanel();
add(panelPlateauDeJeu, BorderLayout.CENTER);
panelPlateauDeJeu.setLayout(new GridLayout(2, 1, 0, 0));
panelZoneDeJeu = new JPanel();
panelZoneDeJeu.setBackground(new Color(34, 139, 34));
panelZoneDeJeu.setBorder(new TitledBorder(null, "Zone de jeu",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelPlateauDeJeu.add(panelZoneDeJeu);
afficherPanelZoneDeJeu();
panelCartesJoueurCourant = new JPanel();
panelCartesJoueurCourant.setLayout(new GridLayout(2, 1, 0, 0));
grimoire = new JPanel();
grimoire.setBorder(new TitledBorder(null, "Grimoire", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelCartesJoueurCourant.add(grimoire);
main = new JPanel();
main.setBorder(new TitledBorder(null, "Main", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelCartesJoueurCourant.add(main);
afficherJoueurCourant();
JPanel panelDroite = new JPanel();
add(panelDroite, BorderLayout.EAST);
panelDroite.setLayout(new GridLayout(0, 1, 0, 0));
panelChaudron = new JPanel();
panelDroite.add(panelChaudron);
panelChaudron.setBorder(new TitledBorder(null, "Chaudron",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelChaudron.setLayout(new GridLayout(1, 1, 0, 0));
afficherPanelChaudron();
panelBibliotheque = new JPanel();
panelBibliotheque.setBorder(new TitledBorder(null, "Bibliotheque",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelDroite.add(panelBibliotheque);
panelBibliotheque.setLayout(new BoxLayout(panelBibliotheque, BoxLayout.Y_AXIS));
afficherPanelBibliotheque();
panelDefausse = new JPanel();
panelDefausse.setBorder(new TitledBorder(null, "Defausse", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelDroite.add(panelDefausse);
panelDefausse.setLayout(new BoxLayout(panelDefausse, BoxLayout.Y_AXIS));
afficherPanelDefausse();
panelActionJoueur = new JPanel();
panelDroite.add(panelActionJoueur);
panelActionJoueur.setBorder(new TitledBorder(null, "Action Joueur",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelActionJoueur.setLayout(new MigLayout("", "[]", "[][][]"));
afficherPanelActionJoueur();
}
public void afficherPanelActionJoueur() {
this.joueurReagissant = plateau.getJoueurReagissant();
this.joueurCourant = plateau.getJoueurCourant();
btnJouerCarte = new JButton(" Jouer Carte ");
btnJouerCarte.setEnabled(false);
panelActionJoueur.add(btnJouerCarte, "cell 0 0");
btnJouerCarte.addActionListener(new ControllerInterfacePlateau(this));
btnEchangerCartes = new JButton("Echanger Cartes ");
panelActionJoueur.add(btnEchangerCartes, "cell 0 1");
btnEchangerCartes.addActionListener(new ControllerInterfacePlateau(this));
if( joueurReagissant == null || joueurCourant == joueurReagissant)
btnEchangerCartes.setEnabled(true);
else
btnEchangerCartes.setEnabled(false);
btnPasserTour = new JButton(" Terminer Tour ");
panelActionJoueur.add(btnPasserTour, "cell 0 2");
btnPasserTour.addActionListener(new ControllerInterfacePlateau(this));
if( joueurReagissant == null || joueurCourant == joueurReagissant)
btnPasserTour.setEnabled(true);
else
btnPasserTour.setEnabled(false);
}
public void rafraichirPanelActionJoueur() {
panelActionJoueur.removeAll();
panelActionJoueur.revalidate();
afficherPanelActionJoueur();
}
public void afficherPanelListeJoueurs() {
int cpt = 0;
for(int i = 0; i < plateau.getListeJoueurs().size(); i ++) { // Pour chaque joueur
JPanel jpJoueur = new JPanel();
jpJoueur.setBorder(new TitledBorder(null, plateau.listeJoueurs
.get(i).getNom(), TitledBorder.LEADING, TitledBorder.TOP,
null, null));
GridBagConstraints gbc_Joueur = new GridBagConstraints();
gbc_Joueur.insets = new Insets(0, 0, 5, 0);
gbc_Joueur.fill = GridBagConstraints.BOTH;
gbc_Joueur.gridx = 0;
gbc_Joueur.gridy = i;
panelListeJoueur.add(jpJoueur, gbc_Joueur);
jpJoueur.setLayout(new BoxLayout(jpJoueur, BoxLayout.LINE_AXIS));
JLabel lblGrimoire = new JLabel("" + plateau.listeJoueurs.get(i).getNbGemmes());
lblGrimoire.setIcon(new ImageIcon(InterfacePlateau.class.getResource("/images/G.png")));
jpJoueur.add(lblGrimoire);
JPanel CarteGrimoire = new JPanel();
CarteGrimoire.setBorder(new TitledBorder(null, "Grimoire",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
jpJoueur.add(CarteGrimoire);
CarteGrimoire.setLayout(new BoxLayout(CarteGrimoire,
BoxLayout.X_AXIS));
// Affichage des cartes du grimoire
for(int j = 0; j < plateau.listeJoueurs.get(i).getGrimoire().size(); j++) {
JLabel lblCarteGrimoire = new JLabel("");
lblCarteGrimoire.setIcon(new ImageIcon(
imageCarte = resize(plateau.listeJoueurs.get(i)
.getGrimoire().get(j).getRecto(),
widthGrimoireJoueurAtt, heightGrimoireJoueurAtt)));
lblCarteGrimoire.setToolTipText(plateau.listeJoueurs.get(i)
.getGrimoire().get(j).getInfoBulle());
CarteGrimoire.add(lblCarteGrimoire);
}
cpt = plateau.listeJoueurs.get(i).getGrimoire().size();
if(plateau.listeJoueurs.get(i).getGrimoire().size() < 3) {
do {
JLabel lblCarteVide = new JLabel("");
lblCarteVide.setIcon(new ImageIcon(
imageCarte = resize("Vide.png",
widthGrimoireJoueurAtt, heightGrimoireJoueurAtt)));
CarteGrimoire.add(lblCarteVide);
cpt++;
}while (cpt < 3);
}
}
}
public void rafraichirPanelListeJoueurs() {
panelListeJoueur.removeAll();
panelListeJoueur.revalidate();
afficherPanelListeJoueurs();
}
public void afficherJoueurCourant() {
final ButtonGroup groupeBoutonsCartes = new ButtonGroup();
this.joueurCourant = plateau.getJoueurCourant();
panelPlateauDeJeu.add(panelCartesJoueurCourant);
tableCorrespondance.clear();
panelCartesJoueurCourant.setBorder(new TitledBorder(null,
"Joueur courant : " + joueurCourant.getNom() +" | Gemmes : "+joueurCourant.getNbGemmes(),
TitledBorder.LEADING, TitledBorder.TOP, null, null));
//Affichage du grimoire
for (int i = 0; i < joueurCourant.getGrimoire().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getGrimoire().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getGrimoire().get(i).getInfoBulle());
grimoire.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getGrimoire().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
//Affichage de la main
for (int i = 0; i < joueurCourant.getMain().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getMain().get(i).getRecto(),
95, 160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getMain().get(i).getInfoBulle());
main.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getMain().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
}
public void rafraichirPanelJoueurCourant() {
//Rafraichissement du grimoire
grimoire.removeAll();
grimoire.revalidate();
//Rafraichissement de la main
main.removeAll();
main.revalidate();
afficherJoueurCourant();
}
public void afficherJoueurReagissant() {
this.joueurReagissant = plateau.getJoueurReagissant();
final ButtonGroup groupeBoutonsCartes = new ButtonGroup();
panelPlateauDeJeu.add(panelCartesJoueurCourant);
tableCorrespondance.clear();
panelCartesJoueurCourant.setBorder(new TitledBorder(null,
"Joueur reagissant : " + joueurReagissant.getNom(),
TitledBorder.LEADING, TitledBorder.TOP, null, null));
//Affichage du grimoire
for (int i = 0; i < joueurReagissant.getGrimoire().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurReagissant.getGrimoire().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurReagissant.getGrimoire().get(i).getInfoBulle());
grimoire.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurReagissant.getGrimoire().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
//Affichage de la main
for (int i = 0; i < joueurReagissant.getMain().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurReagissant.getMain().get(i).getRecto(),
95, 160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurReagissant.getMain().get(i).getInfoBulle());
main.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurReagissant.getMain().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
}
public void rafraichirPanelJoueurReagissant() {
//Rafraichissement du grimoire
grimoire.removeAll();
grimoire.revalidate();
//Rafraichissement de la main
main.removeAll();
main.revalidate();
afficherJoueurReagissant();
}
public void afficherPanelChaudron() {
JLabel lblValeur = new JLabel("= "+ plateau.getChaudron().recupererNbGemmes());
lblValeur.setIcon(new ImageIcon(InterfacePlateau.class.getResource("/images/gemmes.png")));
panelChaudron.add(lblValeur);
}
public void rafraichirPanelChaudron() {
panelChaudron.removeAll();
panelChaudron.revalidate();
afficherPanelChaudron();
}
public void afficherPanelZoneDeJeu() {
JLabel lblZoneDeJeu = new JLabel("");
if(plateau.zoneDeJeu.isEmpty())
imageCarte = resize("Vide.png", 145, 225);
else {
imageCarte = resize(plateau.zoneDeJeu.get(plateau.zoneDeJeu.size() - 1).getRecto(), 145, 225);
lblZoneDeJeu.setToolTipText(plateau.zoneDeJeu.get(plateau.zoneDeJeu.size() - 1).getInfoBulle());
}
lblZoneDeJeu.setIcon(new ImageIcon(imageCarte));
panelZoneDeJeu.add(lblZoneDeJeu);
}
public void rafraichirPanelZoneDeJeu() {
System.out.println("Size ZDJ: " + plateau.getZoneDeJeu().size());
panelZoneDeJeu.removeAll();
panelZoneDeJeu.revalidate();
afficherPanelZoneDeJeu();
}
public void afficherPanelBibliotheque() {
JLabel lblNombreCarteRestantes = new JLabel("Cartes restantes: "
+ plateau.getBibliotheque().getPile().size());
panelBibliotheque.add(lblNombreCarteRestantes);
JLabel lblBibliotheque = new JLabel("");
lblBibliotheque.setAlignmentY(Component.BOTTOM_ALIGNMENT);
lblBibliotheque.setHorizontalAlignment(SwingConstants.CENTER);
lblBibliotheque.setIcon(new ImageIcon(InterfacePlateau.class
.getResource("/images/Recto_100x142.png")));
panelBibliotheque.add(lblBibliotheque);
}
public void rafraichirPanelBibliotheque() {
panelBibliotheque.removeAll();
panelBibliotheque.revalidate();
afficherPanelBibliotheque();
}
public void afficherPanelDefausse() {
lblCarteDefausse = new JLabel("Cartes defausse: "+ plateau.getDefausse().getPile().size());
lblCarteDefausse.setHorizontalAlignment(SwingConstants.CENTER);
lblCarteDefausse.setAlignmentY(3.0f);
panelDefausse.add(lblCarteDefausse);
imageCarteDefausse = new JLabel("");
imageCarteDefausse.setHorizontalAlignment(SwingConstants.CENTER);
if(plateau.getDefausse().getPile().isEmpty())
imageCarte = resize("Recto_100x142.png", 100, 142);
else {
imageCarte = resize(plateau.getDefausse().getPile().peek().getRecto(), 100, 142);
}
imageCarteDefausse.setIcon(new ImageIcon(imageCarte));
panelDefausse.add(imageCarteDefausse);
}
public void rafraichirPanelDefausse() {
panelDefausse.removeAll();
panelDefausse.revalidate();
afficherPanelDefausse();
}
public void rafraichirPlateauEntier() {
rafraichirPanelBibliotheque();
rafraichirPanelDefausse();
rafraichirPanelChaudron();
rafraichirPanelJoueurCourant();
rafraichirPanelListeJoueurs();
rafraichirPanelZoneDeJeu();
rafraichirPanelActionJoueur();
}
/**
* Fonction pour redimensionner les cartes
*
*/
public static BufferedImage resize(String nomImageCarte, int width,
int height) {
BufferedImage img = null;
ImprovedMultistepRescaleOp resampleOp = new ImprovedMultistepRescaleOp(
width, height);
try {
img = ImageIO.read(new File("./src/images/"
+ nomImageCarte.replace("hocusPocus.Cartes.", "")));
} catch (IOException e) {
e.printStackTrace();
}
return resampleOp.filter(img, null);
}
public Carte getCarteSelectionee() {
return carteSelectionnee;
}
public JPanel getGrimoire() {
return grimoire;
}
public void setGrimoire(JPanel grimoire) {
this.grimoire = grimoire;
}
public JPanel getMain() {
return main;
}
public void setMain(JPanel main) {
this.main = main;
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Cartes.Carte;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import java.awt.Component;
import java.awt.Toolkit;
public class EchangerMainGrimoire extends JFrame {
private Plateau plateau;
private Joueur joueurCourant;
private Hashtable<JToggleButton, Carte> tableCorrespondance;
private Carte carteSelectionneeMain;
private Carte carteSelectionneeGrimoire;
private InterfacePlateau interfacePlateau;
private JButton btnEchanger;
public EchangerMainGrimoire(final InterfacePlateau interfacePlateau) {
setIconImage(Toolkit.getDefaultToolkit().getImage(EchangerMainGrimoire.class.getResource("/images/icone.gif")));
setResizable(false);
final ButtonGroup groupeBoutonsCartesGrimoire = new ButtonGroup();
final ButtonGroup groupeBoutonsCartesMain = new ButtonGroup();
plateau = Plateau.getInstance();
joueurCourant = plateau.getJoueurCourant();
tableCorrespondance = new Hashtable<JToggleButton, Carte>();
this.interfacePlateau = interfacePlateau;
getContentPane().setLayout(new GridLayout(1, 1, 0, 0));
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setResizable(true);
this.setSize(766, 650);
this.setTitle("Echanger carte main grimoire");
BufferedImage imageCarte = null;
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(3, 1, 0, 0));
JPanel panelMain = new JPanel();
panelMain.setBorder(new TitledBorder(null, "Main", TitledBorder.LEFT,
TitledBorder.TOP, null, null));
panel.add(panelMain);
JPanel panelGrimoire = new JPanel();
panelGrimoire.setBorder(new TitledBorder(null, "Grimoire",
TitledBorder.LEFT, TitledBorder.TOP, null, null));
panel.add(panelGrimoire);
JPanel Boutons = new JPanel();
panel.add(Boutons);
GridBagLayout gbl_Boutons = new GridBagLayout();
gbl_Boutons.columnWidths = new int[] { 399, 349, 25 };
gbl_Boutons.rowHeights = new int[] { 110, 23, 0 };
gbl_Boutons.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_Boutons.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
Boutons.setLayout(gbl_Boutons);
btnEchanger = new JButton("Echanger");
btnEchanger.setAlignmentX(Component.CENTER_ALIGNMENT);
btnEchanger.setEnabled(false);
btnEchanger.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (carteSelectionneeGrimoire != null
&& carteSelectionneeMain != null) {
System.out.println("Echange des cartes selectionnees !");
joueurCourant.echangerMainGrimoire(carteSelectionneeMain,
carteSelectionneeGrimoire);
interfacePlateau.rafraichirPanelListeJoueurs();
interfacePlateau.rafraichirPanelJoueurCourant();
dispose();
}
}
});
GridBagConstraints gbc_btnEchanger = new GridBagConstraints();
gbc_btnEchanger.gridx = 0;
gbc_btnEchanger.gridy = 1;
Boutons.add(btnEchanger, gbc_btnEchanger);
JButton btnAnnuler = new JButton("Annuler");
btnAnnuler.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAnnuler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
GridBagConstraints gbc_btnAnnuler = new GridBagConstraints();
gbc_btnAnnuler.gridx = 1;
gbc_btnAnnuler.gridy = 1;
Boutons.add(btnAnnuler, gbc_btnAnnuler);
for (int i = 0; i < joueurCourant.getGrimoire().size(); i++) { // Affichage
// grimoire
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getGrimoire().get(i).getRecto(),
95, 160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getGrimoire().get(i)
.getInfoBulle());
panelGrimoire.add(jbutton);
groupeBoutonsCartesGrimoire.add(jbutton);
tableCorrespondance
.put(jbutton, joueurCourant.getGrimoire().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if ((JToggleButton) arg0.getSource() != null)
carteSelectionneeGrimoire = tableCorrespondance
.get((JToggleButton) arg0.getSource());
if (carteSelectionneeMain != null)
btnEchanger.setEnabled(true);
}
});
}
for (int i = 0; i < joueurCourant.getMain().size(); i++) { // Affichage
// main
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getMain().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getMain().get(i)
.getInfoBulle());
panelMain.add(jbutton);
groupeBoutonsCartesMain.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getMain().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if ((JToggleButton) arg0.getSource() != null)
carteSelectionneeMain = tableCorrespondance
.get((JToggleButton) arg0.getSource());
if (carteSelectionneeGrimoire != null)
btnEchanger.setEnabled(true);
}
});
}
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static BufferedImage resize(String nomImageCarte, int width,
int height) {
BufferedImage img = null;
ImprovedMultistepRescaleOp resampleOp = new ImprovedMultistepRescaleOp(
width, height);
try {
img = ImageIO.read(new File("./src/images/"
+ nomImageCarte.replace("hocusPocus.Cartes.", "")));
} catch (IOException e) {
e.printStackTrace();
}
return resampleOp.filter(img, null);
}
}
| Java |
package hocusPocus.IHM;
import hocusPocus.Partie.Jeu;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.SwingConstants;
public class InformationJoueur extends JFrame implements Observer{
private static HashMap<String, Integer> infosJoueurs = new HashMap<String, Integer>();
private EcranAccueil interfaceGraphique = EcranAccueil.getInstance();
public InformationJoueur() {
}
/**
* Permet de recuperer le nom et l'age des joueurs
*/
public InformationJoueur(int getNbJoueurs){
int retour = -1;
infosJoueurs.clear(); // On vide la liste
for(int i = 0;i < getNbJoueurs; i++){
JTextField nom = new JTextField("Joueur" + (i + 1));
JComboBox age = new JComboBox(); // Pas besoin de <Integer> si JDK < 7
for(int j = 5; j <= 100; j++)
age.addItem(j);
retour = JOptionPane.showOptionDialog(null,
new Object[] {"Votre prenom :", nom, "Votre age :", age},"Hocus Pocus",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.QUESTION_MESSAGE, null,null,null);
if (retour == JOptionPane.CLOSED_OPTION)
return;
infosJoueurs.put(nom.getText(),age.getSelectedIndex()+5);
}
if (retour == JOptionPane.OK_OPTION)
Jeu.getInstance().initPlateau(infosJoueurs); // Lancement du plateau
System.out.println("Infos joueur : " + infosJoueurs.toString());
}
public static HashMap<String, Integer> getInfosJoueurs() {
return infosJoueurs;
}
@Override
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
}
}
| Java |
package hocusPocus.Partie;
import java.util.ArrayList;
import java.util.Stack;
public class Chaudron {
private static Stack<Gemme> gemmes = new Stack<Gemme>();
Chaudron(int nbGemmes) {
for(int i = 0; i < nbGemmes; i++)
gemmes.push(new Gemme());
}
/**
* Retourne le nombre de gemmes
* @return
*/
public int recupererNbGemmes() {
if(gemmes.empty()) return 0;
return gemmes.size();
}
/**
* Ajoute un gemme dans le chaudron
* @param nbGemmes
*/
public void deposerGemmes(Gemme g) {
gemmes.push(g);
}
/**
* Surcharge: ajoute un nombre de gemmes defini dans le chaudron
* @param nbGemmes
*/
public static void deposerGemmes(ArrayList<Gemme> listeGemmes) {
for(Gemme gemme : listeGemmes)
gemmes.push(gemme);
}
/**
* Retourner le nombre de gemmes specifie
* @param nbGemmes
* @return un gemme ou une liste de gemmes
*/
public ArrayList<Gemme> piocherGemmes(int nbGemmes) {
ArrayList<Gemme> gemmesDemandes = new ArrayList<Gemme>();
if(nbGemmes == 1 && !gemmes.empty())
gemmesDemandes.add(gemmes.pop());
else{
for(int i = 0; i < nbGemmes; i++) {
if(!gemmes.isEmpty())
gemmesDemandes.add(gemmes.pop());
}
}
return gemmesDemandes;
}
public Gemme piocherUnGemme() {
return gemmes.pop();
}
}
| Java |
package hocusPocus.Partie;
public class Main {
public static void main(String[] args) {
Jeu jeu = Jeu.getInstance();
jeu.initPartie();
}
}
| Java |
package hocusPocus.Partie;
import hocusPocus.IHM.GagnantPartie;
import java.util.ArrayList;
public class ThreadGagnant extends Thread{
private Plateau plateau;
private ArrayList<Joueur> listeJoueurs;
private Joueur joueurGagnant;
public ThreadGagnant(){
this.plateau = Plateau.getInstance();
this.listeJoueurs = plateau.getListeJoueurs();
this.joueurGagnant = listeJoueurs.get(0);
}
public void run() {
while(true) {
if(plateau.getChaudron().recupererNbGemmes() == 0){
for(int i = 1; i < listeJoueurs.size(); i++) {
if(joueurGagnant.getNbGemmes() < listeJoueurs.get(i).getNbGemmes()){
joueurGagnant = listeJoueurs.get(i);
}
}
break;
}
}
new GagnantPartie(joueurGagnant.getNom());
}
}
| Java |
package hocusPocus.Partie;
import hocusPocus.Cartes.Carte;
import hocusPocus.IHM.DesignerJoueur;
import hocusPocus.IHM.InteractionJoueur;
import java.util.ArrayList;
public class AnalyseZoneDeJeu {
private Plateau plateau;
private ArrayList<Carte> zoneDeJeu;
public AnalyseZoneDeJeu() {
this.plateau = Plateau.getInstance();
this.zoneDeJeu = this.plateau.getZoneDeJeu();
}
public void Analyse() {
String nomCarte = this.zoneDeJeu.get(0).getClass().getSimpleName();
if((this.zoneDeJeu.size() == 1) && (nomCarte.equals("HAbracadabra") || nomCarte.equals("HSacrifice") || nomCarte.equals("HVoleur") || nomCarte.equals("HHibou")))
new DesignerJoueur(); // Designer une cible pour la carte Hocus
else {
System.out.println("Pas de cible pour la carte " + this.zoneDeJeu.get((this.zoneDeJeu.size()) - 1).getClass().getSimpleName());
new InteractionJoueur();
}
}
public void Resolution(){
if(zoneDeJeu.size() == 1) {
new ResoudrePouvoirHocus(zoneDeJeu.get(0), plateau.getJoueurCourant()); // On resout la carte
}
if(zoneDeJeu.size() == 2) {
new ResoudrePouvoirPocus(zoneDeJeu.get(1), plateau.getJoueurCourant());
}
}
}
| Java |
package hocusPocus.Partie;
import hocusPocus.IHM.EcranAccueil;
import hocusPocus.IHM.InterfacePlateau;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
public final class Jeu {
private static Plateau plateau;
private EcranAccueil ihm;
private InterfacePlateau interfacePlateau;
public static boolean partieRapide;
public static boolean partieNormale;
private static Jeu _instance = null; // singleton pattern
private ThreadVerificationGrimoire verificationTailleGrimoire;
private ThreadVerificationBibliotheque verificationTailleBibliotheque;
private ThreadGagnant threadGagnant;
private Jeu(){
}
public static Jeu getInstance(){
if(_instance == null)
_instance = new Jeu();
return _instance;
}
/**
* Methode permettant l'initialisation de la partie
* Initialisation de l'interface graphique
* Initialisation du plateau
*/
public void initPartie() {
ihm = EcranAccueil.getInstance();
}
/**
* Initialiser le plateau de jeu
* @param HashMap<String, Integer> informationsJoueurs
*/
public void initPlateau(HashMap<String, Integer> informationsJoueurs) {
plateau = Plateau.getInstance();
plateau.initJoueurs(informationsJoueurs);
plateau.classerJoueurs(); // Le plus jeune joueur doit commencer
plateau.initCartes(); // Instancier les cartes
plateau.getBibliotheque().melangerCartes();
plateau.distribuerCarte();
plateau.initChaudron();
System.out.println("Cartes instanciees et distribuees");
ihm.getContentPane().removeAll();
ihm.getContentPane().setBackground(Color.GRAY);
interfacePlateau = new InterfacePlateau();
ihm.getContentPane().add(interfacePlateau);
ihm.getContentPane().validate();
verificationTailleGrimoire = new ThreadVerificationGrimoire();
verificationTailleGrimoire.start();
verificationTailleBibliotheque = new ThreadVerificationBibliotheque();
verificationTailleBibliotheque.start();
threadGagnant = new ThreadGagnant();
threadGagnant.start();
}
public void resoudrePouvoirCarte() {
}
public static ArrayList<Joueur> getListeJoueurs() {
return plateau.getListeJoueurs();
}
public InterfacePlateau getInterfacePlateau() {
return this.interfacePlateau;
}
public ThreadVerificationGrimoire getVerificationTailleGrimoire() {
return verificationTailleGrimoire;
}
public ThreadVerificationBibliotheque getVerificationTailleBlibliotheque() {
return verificationTailleBibliotheque;
}
}
| Java |
package hocusPocus.Partie;
import hocusPocus.Cartes.Carte;
import java.util.ArrayList;
import java.util.Stack;
public class Defausse {
Stack<Carte> pile = new Stack<Carte>();
/**
* Empiler les carte sur la pile de defausse
* @param cartesDefaussees
*/
public void defausserCartes(ArrayList<Carte> cartesDefaussees) {
for(Carte carte : cartesDefaussees)
this.pile.push(carte);
}
public void defausserUneCarte(Carte carteDefaussee) {
this.pile.push(carteDefaussee);
}
/**
* Permet de vider la defausse et de retourner l'ensemble des cartes
* qu'elle contient
* @return
*/
public ArrayList<Carte> viderDefausse() {
ArrayList<Carte> cartesDefausse = new ArrayList<Carte>();
for(int i = 0; i < this.pile.size(); i++)
cartesDefausse.add(this.pile.pop());
return cartesDefausse;
}
public Stack<Carte> getPile() {
return pile;
}
}
| Java |
package hocusPocus.Partie;
public class Gemme {
String proprietaire;
}
| Java |
package hocusPocus.Partie;
import java.util.ArrayList;
/**
* Thread permettant de s'assurer qu'il y a toujours,
* dans la mesure du possible, 3 cartes dans le grimoire
* des joueurs
*
*/
public class ThreadVerificationGrimoire extends Thread{
private Plateau plateau;
private ArrayList<Joueur> listeJoueurs;
protected volatile boolean running = true;
public ThreadVerificationGrimoire() {
this.plateau = Plateau.getInstance();
this.listeJoueurs = plateau.getListeJoueurs();
}
public void stopMe() {
this.running = false;
}
public void restartMe() {
this.running = true;
}
public void run() {
while(true) {
while(running) {
for(int i = 0; i < listeJoueurs.size(); i++) {
while(listeJoueurs.get(i).getGrimoire().size() < 3) {
if(listeJoueurs.get(i).getMain().size() > 0 ) {
listeJoueurs.get(i).transfertMainVersGrimoire();
Jeu.getInstance().getInterfacePlateau().rafraichirPanelListeJoueurs();
}
else
break;
}
}
}
}
}
}
| Java |
package gibbs.seibert.CS406.VideoGameApp;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/**
* Called when tag starts ( ex:- <name>AndroidPeople</name> -- <name> )
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("results")) {
/** Start */
sitesList = new SitesList();
} else if (localName.equals("game")) {
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}
}
/**
* Called when tag closing ( ex:- <name>AndroidPeople</name> -- </name> )
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("game"))
sitesList.setName(currentValue);
else if (localName.equalsIgnoreCase("name"))
sitesList.setWebsite(currentValue);
}
/**
* Called to get tag characters ( ex:- <name>AndroidPeople</name> -- to get
* AndroidPeople Character )
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
| Java |
package gibbs.seibert.CS406.VideoGameApp;
import java.util.ArrayList;
/** Contains getter and setter method for variables */
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> website = new ArrayList<String>();
private ArrayList<String> category = new ArrayList<String>();
/**
* In Setter method default it will return arraylist change that to add
*/
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
public ArrayList<String> getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList<String> getCategory() {
return category;
}
public void setCategory(String category) {
this.category.add(category);
}
}
| Java |
package gibbs.seibert.CS406.VideoGameApp;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
static final String RESPONSE = "reponse";
static final String ERROR = "error";
static final String LIMIT = "limit";
static final String PAGE_RESULTS = "page_results";
static final String TOTAL_RESULTS = "total_results";
static final String OFFSET = "offset";
static final String RESULTS = "results";
static final String GAME = "game";
static final String ID = "id";
static final String NAME = "name";
static final String RELEASE_DATE = "release_date";
static final String STATUS_CODE = "status_code";
// static final String RELEASE_MONTH = "release_month";
// static final String RELEASE_QUARTER = "release_month";
// static final String RELEASE_YEAR = "release_month";
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://api.giantbomb.com/games/?api_key=1619975a086e2cb970b415b36ee90c544bb2345e&field_list=name,id,original_release_date&platforms=20&format=xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array length by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getName().size()];
category = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = " + sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = " + sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "
+ sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
} | Java |
package com.plantplaces.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.plantplaces.dao.IPlantDAO;
import com.plantplaces.dao.OfflinePlantDAO;
import com.plantplaces.dao.OnlinePlantDAO;
import com.plantplaces.dto.Plant;
import com.plantplaces.dto.Specimen;
/**
* Plant Service when the mobile network is available.
*
* @author jonesb
*
*/
public class PlantService implements IPlantService {
// create a variable of type IPlantDAO.
IPlantDAO onlinePlantDAO;
IPlantDAO offlinePlantDAO;
public PlantService(Context context) {
onlinePlantDAO = new OnlinePlantDAO();
offlinePlantDAO = new OfflinePlantDAO(context);
}
@Override
public List<String> fetchAllGenus() throws Exception {
// TODO Auto-generated method stub
ArrayList<String> allGenus = new ArrayList<String>();
allGenus.add("Abies");
allGenus.add("Abutilon");
allGenus.add("Abelia");
allGenus.add("Amelanchier");
allGenus.add("Amur");
allGenus.add("Acer");
return allGenus;
}
@Override
public List<String> fetchAllCategories() throws Exception {
// Create a colletion to store our default list of categories.
ArrayList<String> allCategories = new ArrayList<String>();
allCategories.add("Shrub");
allCategories.add("Tree");
allCategories.add("Evergreen");
allCategories.add("Annual");
allCategories.add("Perennial");
allCategories.add("Grass");
allCategories.add("Vine");
// return the collection of categories.
return allCategories;
}
@Override
public List<Plant> fetchPlant(Plant plant) throws Exception {
// find matching plants.
ArrayList<Plant> fetchPlantsBySearch;
try {
fetchPlantsBySearch = onlinePlantDAO.fetchPlantsBySearch(plant);
} catch (IOException e) {
// we are here because there is a network exception. Switch to offline mode.
// TODO create offline support. Meanwhile, rethrow exception.
throw e;
}
return fetchPlantsBySearch;
}
@Override
public List<Specimen> fetchAllSpecimens() throws Exception {
return offlinePlantDAO.fetchAllSpecimens();
}
@Override
public void saveSpecimen(Specimen specimen) throws Exception {
offlinePlantDAO.saveSpecimen(specimen);
}
}
| Java |
package com.plantplaces.service;
import java.util.List;
import com.plantplaces.dto.Plant;
import com.plantplaces.dto.Specimen;
/**
* An interface for logic involving plants.
* @author jonesb
*
*/
public interface IPlantService {
/**
* Fetch all genus
* @return a collection of all genus.
*/
public List<String> fetchAllGenus() throws Exception;
/**
* Fetch all plant categories
* @return all plant categories.
*/
public List<String> fetchAllCategories() throws Exception;
/**
* Search for plants that contain the specified search criteria.
* @param plant an object that contains search terms.
* @return a collection of Plants that match the search criteria.
* @throws Exception
*/
public List<Plant> fetchPlant(Plant plant) throws Exception;
/**
* Fetch all specimens in the database.
* @return a collection of specimens.
* @throws Exception
*/
public List<Specimen> fetchAllSpecimens() throws Exception;
/**
* Save the given Specimen.
* @param specimen
* @throws Exception
*/
public void saveSpecimen(Specimen specimen) throws Exception;
}
| Java |
/*
* Copyright 2012 PlantPlaces.com
*/
package com.plantplaces.dto;
/**
* A specimen is a plant at a location with unique
* values of its attributes.
* @author jonesb
*
*/
public class Specimen {
@Override
public String toString() {
return getDescription() + " " + getLatitude() + " " + getLongitude();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPlantId() {
return plantId;
}
public void setPlantId(int plantId) {
this.plantId = plantId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getLatitude() {
return latitude;
}
public int getPublished() {
return published;
}
public void setPublished(int published) {
this.published = published;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
private int id; // primary key of the specimen.
private int plantId; // foreign key back to the plant.
private String description; // description of the specimen
private double latitude;
private double longitude;
private int published = 0;
}
| Java |
package com.plantplaces.dto;
import java.io.Serializable;
public class Plant implements Serializable {
String genus;
String species;
String cultivar;
String commonName;
String category;
int minimumHeight;
int maximumHeight;
private int id; // the primary key from PlantPlaces.com
@Override
public String toString() {
return genus + " " + species + " " + cultivar;
}
public String getGenus() {
return genus;
}
public void setGenus(String genus) {
this.genus = genus;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getCultivar() {
return cultivar;
}
public void setCultivar(String cultivar) {
this.cultivar = cultivar;
}
public String getCommonName() {
return commonName;
}
public void setCommonName(String commonName) {
this.commonName = commonName;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getMinimumHeight() {
return minimumHeight;
}
public void setMinimumHeight(int minimumHeight) {
this.minimumHeight = minimumHeight;
}
public int getMaximumHeight() {
return maximumHeight;
}
public void setMaximumHeight(int maximumHeight) {
this.maximumHeight = maximumHeight;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
| Java |
/*
* Copyright 2012 PlantPlaces.com
*/
package com.plantplaces.dao;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
/**
* Access data from a network.
*
* @author jonesb
*
*/
public interface INetworkDAO {
/**
* Given a URI, fetch the URI and return the response.
* This method does not have any intelligence about the data it is sending or receiving;
* it simply is in charge of sending the data over a network, and receiving the data
* from the network.
* @param uri The URI you wish to access.
* @return the data returned after accessing the URI.
*/
public String request (String uri) throws ClientProtocolException, IOException ;
}
| Java |
package com.plantplaces.dao;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.client.ClientProtocolException;
import com.plantplaces.dto.Plant;
import com.plantplaces.dto.Specimen;
public class OnlinePlantDAO implements IPlantDAO {
// attribute for our Network DAO.
INetworkDAO networkDAO;
public OnlinePlantDAO() {
// instantiate our network DAO so that we can use it.
networkDAO = new NetworkDAO();
}
@Override
public ArrayList<Plant> fetchPlantsBySearch(Plant searchPlant) throws IOException {
// Create a collection to hold the returned plants.
ArrayList<Plant> allPlants = new ArrayList<Plant>();
// assemble a URI.
String genus = searchPlant.getGenus() != null ? searchPlant.getGenus() : "";
String species = searchPlant.getSpecies() != null ? searchPlant.getSpecies() : "";
String commonName = searchPlant.getCommonName() != null ? searchPlant.getCommonName() : "";
String uri = "http://plantplaces.com/perl/mobile/viewplants.pl?Genus=" + genus + "&Species=" + species + "&Common=" + commonName;
// pass the assembled URI to the network DAO, receive the response.
String response = networkDAO.request(uri);
// split the response into its respective lines. Each line represents a plant.
String[] lines = response.split("\n");
// iterate over each line of the response.
for(String line : lines) {
// parse the response by the delimiter.
String[] plantData = line.split(";");
// make sure we have enough fields returned. if not, we have an invalid object.
if (plantData.length > 4) {
// create a new Plant object, fill it with the data from this line.
Plant thisPlant = new Plant();
thisPlant.setId(Integer.parseInt(plantData[0]));
thisPlant.setGenus(plantData[1]);
thisPlant.setSpecies(plantData[2]);
thisPlant.setCultivar(plantData[3]);
thisPlant.setCommonName(plantData[4]);
// Add the plant object to the ArrayList of all plant objects.
allPlants.add(thisPlant);
}
}
// return the ArrayList of all plant objects.
return allPlants;
}
@Override
public void saveSpecimen(Specimen specimen) throws Exception {
// TODO Auto-generated method stub
}
@Override
public ArrayList<Specimen> fetchAllSpecimens() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| Java |
package com.plantplaces.dao;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class NetworkDAO implements INetworkDAO {
@Override
public String request(String uri) throws ClientProtocolException, IOException {
// Create the return variable.
String returnString = "";
// create a default HttpClient object.
HttpClient httpClient = new DefaultHttpClient();
// Create a get object with the URI that we have been provided.
HttpGet httpGet = new HttpGet(uri);
// Create a ResponseHandler to handle the response.
ResponseHandler<String> responseHandler = new BasicResponseHandler();
// tie together the request and the response.
returnString = httpClient.execute(httpGet, responseHandler);
return returnString;
}
}
| Java |
/*
* Copyright 2012 PlantPlaces.com
*/
package com.plantplaces.dao;
import java.io.IOException;
import java.util.ArrayList;
import com.plantplaces.dto.Plant;
import com.plantplaces.dto.Specimen;
/**
* CRUD operations for a Plant.
* @author jonesb
*
*/
public interface IPlantDAO {
/**
* Fetch plants that match the search criteria.
* @param searchPlant a Plant DTO that contains search criteria.
* @return a collection that contains Plants that match the given search criteria.
*/
public ArrayList<Plant> fetchPlantsBySearch(Plant searchPlant) throws IOException;
/**
* Save the specimen to the persistence layer.
* @param specimen what we want to save.
* @throws Exception in case there is a persistence exception that cannot be handled locally.
*/
public void saveSpecimen(Specimen specimen) throws Exception;
/**
* Return all specimens from the persistence layer.
* @return a collection of Specimens.
* @throws Exception in case there is a persistence exception that cannot be handled locally.
*/
public ArrayList<Specimen> fetchAllSpecimens() throws Exception;
}
| Java |
package com.plantplaces.dao;
import java.io.IOException;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.plantplaces.dto.Plant;
import com.plantplaces.dto.Specimen;
public class OfflinePlantDAO extends SQLiteOpenHelper implements IPlantDAO {
private static final String SPECIMENS_TABLE = "specimens";
private static final String PUBLISHED = "published";
private static final String DESCRIPTION = "description";
private static final String LONGITUDE = "longitude";
public static final String LATITUDE = "latitude";
public static final String PLANT_ID = "plantId";
public OfflinePlantDAO(Context context) {
super(context, "plantplacessummer12", null, 1);
}
@Override
public ArrayList<Plant> fetchPlantsBySearch(Plant searchPlant)
throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+SPECIMENS_TABLE+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + PLANT_ID + " INT, "+ LATITUDE + " TEXT, "+LONGITUDE+" TEXT, "+DESCRIPTION+" TEXT, "+PUBLISHED+" INT);");
db.execSQL("CREATE TABLE plants (_id INTEGER PRIMARY KEY AUTOINCREMENT, genus TEXT, species TEXT, cultivar TEXT, commonName TEXT, category TEXT, minimumHeight INT, maximumHeight INT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void saveSpecimen(Specimen specimen) throws Exception {
// create a ContentValues to hold the data we wish to save.
ContentValues values = new ContentValues();
values.put(PLANT_ID, specimen.getPlantId());
values.put(LATITUDE, specimen.getLatitude());
values.put(LONGITUDE, specimen.getLongitude());
values.put(DESCRIPTION, specimen.getDescription());
values.put(PUBLISHED, specimen.getPlantId());
getWritableDatabase().insert(SPECIMENS_TABLE, LATITUDE, values);
}
@Override
public ArrayList<Specimen> fetchAllSpecimens() throws Exception {
ArrayList<Specimen> allSpecimens = new ArrayList<Specimen>();
// the SQL statement that will fetch specimens.
String selectSQL = "SELECT * FROM " + SPECIMENS_TABLE;
// run the query.
Cursor specimenResults = getReadableDatabase().rawQuery(selectSQL, new String[0]);
// see if we have results.
if(specimenResults.getCount() > 0) {
// move to the first row of the results.
specimenResults.moveToFirst();
// iterate over the query result and populate our Specimen objects.
while (!specimenResults.isAfterLast()) {
// create and instantiate a Specimen object.
Specimen thisSpecimen = new Specimen();
// populate the Specimen object.
thisSpecimen.setId(specimenResults.getInt(0));
thisSpecimen.setPlantId(specimenResults.getInt(1));
thisSpecimen.setLatitude(specimenResults.getDouble(2));
thisSpecimen.setLongitude(specimenResults.getDouble(3));
thisSpecimen.setDescription(specimenResults.getString(4));
thisSpecimen.setPublished(specimenResults.getInt(5));
// add this specimen to the collection that will get returned.
allSpecimens.add(thisSpecimen);
// move to the next record in the results.
specimenResults.moveToNext();
}
}
// return the results.
return allSpecimens;
}
}
| Java |
/*
* Copyright PlantPlaces.com 2012
*/
package com.plantplaces.ui;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.plantplaces.dto.Plant;
import com.plantplaces.service.IPlantService;
import com.plantplaces.service.PlantServiceStub;
/**
* Enable searching of plants by several search criteria
* @author jonesb
*
*/
public class PlantSearchActivity extends PlantPlacesActivity {
public static final String SELECTED_PLANT = "Selected Plant";
public static final String PLANT_SEARCH = "Plant Search";
private AutoCompleteTextView actGenus;
private Spinner spnCategory;
private IPlantService plantService;
private Button btnPlantSearch;
private EditText edtSpecies;
private EditText edtCultivar;
private TextView txtPlantResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// we are associating the plant search layout with this activity.
setContentView(R.layout.plantsearch);
// initialize the plant service
plantService = new PlantServiceStub();
try {
// get a reference to the auto complete text.
actGenus = (AutoCompleteTextView) findViewById(R.id.actGenus);
// populate the auto complete text values from the PlantService
actGenus.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, plantService.fetchAllGenus()));
// get a reference to the spinner for categories.
spnCategory = (Spinner) findViewById(R.id.spnCategory);
// populate the spinner from our PlantService.
spnCategory.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, plantService.fetchAllCategories()));
} catch (Exception e) {
Log.e(this.getClass().getName(), e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
edtSpecies = (EditText) findViewById(R.id.edtSpecies);
edtCultivar = (EditText) findViewById(R.id.edtCultivar);
txtPlantResult = (TextView) findViewById(R.id.txtPlantResult);
// get a reference to the search button.
btnPlantSearch = (Button) findViewById(R.id.btnSearchPlants);
// add a listener to the search button.
btnPlantSearch.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
searchPlants();
}
});
}
private void searchPlants() {
// create a plant object populated with the search terms.
Plant searchPlant = new Plant();
// start calling setters based on the UI elements.
searchPlant.setGenus(actGenus.getText().toString());
searchPlant.setCategory(spnCategory.getSelectedItem().toString());
searchPlant.setSpecies(edtSpecies.getText().toString());
searchPlant.setCultivar(edtCultivar.getText().toString());
// place the Plant object into a bundle, so that we can pass it to the plant results screen.
Bundle bundle = new Bundle();
bundle.putSerializable(PLANT_SEARCH, searchPlant);
// create an intent for the plant results screen.
Intent plantResultsIntent = new Intent(this, PlantResultsActivity.class);
plantResultsIntent.putExtras(bundle);
// call the intent for the plant results screen
startActivityForResult(plantResultsIntent, 1);
}
/**
* This is invoked when the Plant Result activity returns a result.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle bundle = data.getExtras();
Plant selectedPlant = (Plant) bundle.getSerializable(SELECTED_PLANT);
txtPlantResult.setText(selectedPlant.toString());
}
}
| Java |
package com.plantplaces.ui;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.plantplaces.dto.Plant;
import com.plantplaces.service.IPlantService;
import com.plantplaces.service.PlantService;
/**
* PlantResultsAcitivity shows a list of plants.
* @author jonesbr
*
*/
public class PlantResultsActivity extends ListActivity {
IPlantService plantService;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// initialize the plant service.
plantService = new PlantService(this);
Bundle bundle = getIntent().getExtras();
Plant plant = (Plant) bundle.getSerializable(PlantSearchActivity.PLANT_SEARCH);
List<Plant> allPlants;
try {
allPlants = plantService.fetchPlant(plant);
this.setListAdapter(new ArrayAdapter<Plant>(this, android.R.layout.simple_list_item_1, allPlants));
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(this.getClass().getName(), e.getMessage());
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// get the plant that the user selected.
Plant selectedPlant = (Plant) this.getListAdapter().getItem(position);
// send this plant back to the Plant Search Screen.
Bundle bundle = new Bundle();
bundle.putSerializable(PlantSearchActivity.SELECTED_PLANT, selectedPlant);
// get a reference to the current intent.
Intent thisIntent = this.getIntent();
thisIntent.putExtras(bundle);
this.setResult(RESULT_OK, thisIntent);
finish();
}
}
| Java |
package com.plantplaces.ui;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.plantplaces.dto.Specimen;
import com.plantplaces.service.IPlantService;
import com.plantplaces.service.PlantService;
public class ShowSpecimensActivity extends ListActivity {
IPlantService plantService;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// init PlantService.
plantService = new PlantService(this);
// fetch all specimens.
try {
// fetch specimens.
List<Specimen> allSpecimens = plantService.fetchAllSpecimens();
// populate the screen.
this.setListAdapter(new ArrayAdapter<Specimen>(this, android.R.layout.simple_list_item_1, allSpecimens));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// showing a message box confirming the operation is complete.
Toast.makeText(this, "Unable to retrieve specimens. Message: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(this.getClass().getName(), e.getMessage(), e);
}
}
}
| Java |
package com.plantplaces.ui;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.plantplaces.dto.Specimen;
import com.plantplaces.service.IPlantService;
import com.plantplaces.service.PlantService;
/**
* Find a latitude and longitude location.
*
* @author jonesbr
*
*/
public class LocationFinder extends PlantPlacesActivity {
private TextView txtLatitudeValue;
private TextView txtLongitudeValue;
private EditText edtDescription;
private Button btnSaveSpecimen;
private Button btnFindSpecimen;
private Button btnShowSpecimens;
private Button btnUploadSpecimens;
// location coordinates.
private double latitude;
private double longitude;
// LocationManager makes GPS locations available to us.
private LocationManager locationManager;
// LocationListener can listen to location events and perform actions when they occur.
private LocationListener locationListener;
// declare this as a variable, with time measured in seconds, so that we can allow the user to specify this as a preference in a future sprint.
private int gpsInterval = 60;
private IPlantService plantService;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
// initialize our plant service.
plantService = new PlantService(this);
txtLatitudeValue = (TextView) findViewById(R.id.txtLatitudeValue);
txtLongitudeValue = (TextView) findViewById(R.id.txtLongitudeValue);
edtDescription = (EditText) findViewById(R.id.edtDescription);
btnSaveSpecimen = (Button) findViewById(R.id.btnSaveLocation);
btnFindSpecimen = (Button) findViewById(R.id.btnFindSpecimen);
btnShowSpecimens = (Button) findViewById(R.id.btnShowSpecimens);
btnUploadSpecimens = (Button) findViewById(R.id.btnUploadSpecimens);
// make an object of the listener type.
OnClickListener saveListener = new SaveSpecimen();
// associate this button with the SaveSpecimen listener.
// btnSaveSpecimen.setOnClickListener(saveListener);
btnSaveSpecimen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
save();
}
}
);
btnFindSpecimen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
findSpecimen();
}
}
);
btnShowSpecimens.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
showSpecimens();
}
});
btnUploadSpecimens.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
uploadSpecimens();
}
});
// Initialize location manager for updates.
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// initialize location listener.
initLocationListener();
// at this point, we know that both the Manager and Listener have been instantiated and assigned.
// Thus, it is safe to start listeneing for updates.
requestUpdates();
}
/**
* Not yet implemented.
*/
protected void uploadSpecimens() {
// TODO Auto-generated method stub
}
protected void showSpecimens() {
// redirect to an activity that will show specimens.
Intent showSpecimensIntent = new Intent(this, ShowSpecimensActivity.class);
startActivity(showSpecimensIntent);
}
private void initLocationListener() {
// instantiate my location listener.
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// When we are notified of a location event, update the respective attribute values.
latitude = location.getLatitude();
longitude = location.getLongitude();
// also, update the UI TextViews.
txtLatitudeValue.setText("" + latitude);
txtLongitudeValue.setText("" + longitude);
Toast.makeText(LocationFinder.this, "New GPS Location: " + latitude + " " + longitude, Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
};
}
/**
* Find plants from which we can create specimens.
* This will redirect us to the Plant Search screen.
*/
private void findSpecimen() {
// create an intent to navigate to the next screen.
Intent plantSearchIntent = new Intent(this, PlantSearchActivity.class);
// invoke that intent, and indicate that we wish to receive a result.
startActivityForResult(plantSearchIntent, 1);
}
/**
* Save the specimen to the persistence layer.
*/
private void save() {
String strLat = txtLatitudeValue.getText().toString();
String strLng = txtLongitudeValue.getText().toString();
String strDescription = edtDescription.getText().toString();
// create and populate our specimen.
Specimen thisSpecimen = new Specimen();
thisSpecimen.setLatitude(Double.parseDouble(strLat));
thisSpecimen.setLongitude(Double.parseDouble(strLng));
thisSpecimen.setDescription(strDescription);
thisSpecimen.setPlantId(1);
// save the specimen, using the plant service.
try {
plantService.saveSpecimen(thisSpecimen);
// showing a message box confirming the operation is complete.
Toast.makeText(this, "Specimen Saved: " + strDescription, Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// showing a message box confirming the operation is complete.
Toast.makeText(this, "Specimen Not Saved: " + strDescription + " Message: " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(this.getClass().getName(), e.getMessage(), e);
}
}
class SaveSpecimen implements OnClickListener {
@Override
public void onClick(View v) {
save();
}
}
/**
* Stop listening for locations.
*/
protected void removeUpdates() {
locationManager.removeUpdates(locationListener);
}
/**
* Start listening for locations.
*/
protected void requestUpdates() {
// make sure that our publisher and subscriber have both been instantiated.
if (locationListener != null && locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, gpsInterval * 1000, 0, locationListener);
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// turn off locations.
removeUpdates();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// restart updates
requestUpdates();
}
}
| Java |
/*
* Copyright 2012 PlantPlaces.com
*/
package com.plantplaces.ui;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
/**
* Superclass that contains all common functionality for all Activities on the Plant Places mobile application.
* @author jonesb
*
*/
public class PlantPlacesActivity extends Activity {
private static final int MENU_PLANT_SEARCH = 2;
protected static final int MENU_LOCATION_SCREEN = 1;
public PlantPlacesActivity() {
super();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
// start to create menu options.
// find location screen.
menu.add(0, MENU_LOCATION_SCREEN, Menu.NONE, getString(R.string.mnuLocationScreen));
// plant search screen.
menu.add(0, MENU_PLANT_SEARCH, Menu.NONE, getString(R.string.mnuPlantSearchScreen));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_LOCATION_SCREEN:
loadLocationScreen();
break;
case MENU_PLANT_SEARCH:
loadPlantSearchScreen();
break;
}
return true;
}
private void loadPlantSearchScreen() {
// render the plant search screen.
Intent plantSearchIntent = new Intent(this, PlantSearchActivity.class);
startActivity(plantSearchIntent);
}
private void loadLocationScreen() {
// render the location screen.
Intent locationIntent = new Intent(this, LocationFinder.class);
startActivity(locationIntent);
}
} | Java |
import java.io.*;
public class Name2 {
public static void main(String args[]) throws IOException
{
String name;
BufferedReader eingabe = new BufferedReader
(new InputStreamReader(System.in));
System.out.print("Bitte geben Sie Ihren Name ein: ");
name = eingabe.readLine();
System.out.println ("Guten Tag Herr/Frau " + name);
System.out.println(" ");
System.out.println("Programmende HalloName_2");
}
}
| Java |
import java.lang.System.*;
public class Aufgabe1 {
public static void main(String[] args)
{
System.out.println("Hallo Welt!");
}
}
| Java |
import java.io.*;
public class datei {
public static void main(String[] args) throws IOException
{
FileWriter ausgabeStrom = new FileWriter("datei1");
PrintWriter ausgabe = new PrintWriter(ausgabeStrom);
ausgabe.println("Testzeile!");
ausgabe.print("test");
ausgabe.flush();
ausgabe.close();
FileReader eingabeStrom = new FileReader("datei1");
BufferedReader eingabe = new BufferedReader(eingabeStrom);
String gelesen = "";
do
{
gelesen = eingabe.readLine();
System.out.println(gelesen);
if(gelesen == null)
{
break;
}
}
while (gelesen != null);
{
//eingabe.close();
}
System.out.println(eingabe.readLine());
System.out.println(eingabe.readLine());
System.out.println(eingabe.readLine());
}
}
| Java |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Kreis {
public static void main(String args[]) throws IOException
{
int x = 20;
int y = 20;
int ix,iy = 0;
/*while(iy >= y)
{
if(ix== 1 || ix == y)
{
}
}*/
}
}
| Java |
public class Zins_1 {
public static void main(String[] args)
{
double zinssatz = 2.5; // %
double kapital = 1000.00; // Euro
int anzJahre = 5;
double zinsertrag;
/*
* Ein Kapital von 1000.00 Euro erbringt bei einem Zinssatz
von 2.5 % pro Jahr in 5 Jahren einen Gewinn von
125.00 Euro.
*/
zinsertrag = (((kapital/100)*zinssatz)*anzJahre);
System.out.println("Ein Kapital von "+kapital+" Euro erbringt bei einem Zinssatz von "+zinssatz+" % pro Jahr in "+ anzJahre+" Jahren ein Gewinn von "+zinsertrag+" Euro");
}
}
| Java |
public class Aufgabe2
{
public static void main(String[] args)
{
System.out.print("3.3 + 2 = " + (3.3 + 2.0));
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import DAO.MyAttachDAO;
import DTO.MyAttachDTO;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyAttachBUS {
private MyAttachDAO myAttactDAO = new MyAttachDAO();
public ArrayList<MyAttachDTO> layTatCaAttachCuaMailID (int MailID)throws IOException, SQLException{
return myAttactDAO.layTatCaAttachCuaMailID(MailID);
}
public ArrayList<MyAttachDTO> layTatCaAttach () throws IOException, SQLException{
return myAttactDAO.layTatCaAttach();
}
public int themAttach (MyAttachDTO myAttachDTO) throws IOException{
return myAttactDAO.themAttach(myAttachDTO);
}
public int xoaAttach(MyAttachDTO attachDTO) throws IOException{
return myAttactDAO.xoaAttach(attachDTO);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import DAO.MyMailDAO;
import DTO.MyMailDTO;
import doanlythuyet_javaoutlook.MyEmum.JEnum_TinhTrang;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyMailBUS {
private MyMailDAO m_MailDAO = new MyMailDAO();
public ArrayList<MyMailDTO> layTatCaMail () throws IOException{
return m_MailDAO.layTatCaMail();
}
public int themMail (MyMailDTO mailDTO) throws IOException{
return m_MailDAO.themMail(mailDTO);
}
public int xoaMail(MyMailDTO mailDTO) throws IOException{
return m_MailDAO.xoaMail(mailDTO);
}
public ArrayList<MyMailDTO> layTatCaMailVoiDieuKien (String duongDan, Hashtable<String, String> cacDieuKien) throws IOException{
return m_MailDAO.layTatCaMailVoiDieuKien(duongDan, cacDieuKien);
}
public int capNhatMail (MyMailDTO mailDTO) throws IOException{
return m_MailDAO.capNhatMail(mailDTO);
}
public int thayDoiDuongDanThuMuc (String mailId, String thuMucDich) throws IOException{
int soMailCapNhat = 0;
Hashtable<String, String> cacDieuKien = new Hashtable<String, String>();
cacDieuKien.put("Id", mailId);
ArrayList<MyMailDTO> cacMailDTO = layTatCaMailVoiDieuKien(mailId, cacDieuKien);
if (cacMailDTO.size() > 0){
cacMailDTO.get(0).setM_DuongDanThuMuc(thuMucDich);
soMailCapNhat = capNhatMail(cacMailDTO.get(0));
}
return soMailCapNhat;
}
public int xoaMail (String mailId) throws IOException{
int soMailCapNhat = 0;
MyMailDTO mailDTO = layMailVoidMailID(mailId);
if (mailDTO != null){
if (mailDTO.getM_DuongDanThuMuc().equals("Mails\\RecycleBins\\"))
mailDTO.setM_TinhTrang(JEnum_TinhTrang.DaXoa.value());
else
mailDTO.setM_DuongDanThuMuc("Mails\\RecycleBins\\");
soMailCapNhat = capNhatMail(mailDTO);
}
return soMailCapNhat;
}
public int thayDoiTinhTrangMail (String mailId, JEnum_TinhTrang tinhTrangMoi) throws IOException{
int soMailCapNhat = 0;
Hashtable<String, String> cacDieuKien = new Hashtable<String, String>();
cacDieuKien.put("Id", mailId);
ArrayList<MyMailDTO> cacMailDTO = layTatCaMailVoiDieuKien(mailId, cacDieuKien);
if (cacMailDTO.size() > 0){
cacMailDTO.get(0).setM_DuongDanThuMuc(String.valueOf(tinhTrangMoi.value()));
soMailCapNhat = capNhatMail(cacMailDTO.get(0));
}
return soMailCapNhat;
}
public MyMailDTO layMailVoidMailID(String mailId) throws IOException {
Hashtable<String, String> cacDieuKien = new Hashtable<String, String>();
cacDieuKien.put("Id", mailId);
ArrayList<MyMailDTO> cacMailDTO = layTatCaMailVoiDieuKien(mailId, cacDieuKien);
if (cacMailDTO.size() > 0)
return cacMailDTO.get(0);
return null;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import DAO.MyContactDAO;
import DTO.MyContactDTO;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyContactBUS {
private MyContactDAO contactDAO = new MyContactDAO();
public ArrayList<MyContactDTO> layTatCaContact () throws SQLException, IOException{
return contactDAO.layTatCaContact();
}
public MyContactDTO layTatCaContactBangID (String Id) throws SQLException, IOException{
return (contactDAO.layTatCaContactBangID(Id)).get(0);
}
public int themContact (MyContactDTO contactDTO) throws IOException{
return contactDAO.themContact(contactDTO);
}
public MyContactDTO layTatCaContactBangID (int Id) throws SQLException, IOException{
return (contactDAO.layTatCaContactBangID(String.valueOf(Id))).get(0);
}
public int xoaContact(int contactId) throws IOException{
return contactDAO.xoaContact(contactId);
}
public int capNhatContact (MyContactDTO contactDTO) throws IOException{
return contactDAO.capNhatContact(contactDTO);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyContactDTO {
private int m_Id;
private String m_Ten;
private String m_CongTy;
private String m_Hinh;
private String m_Email;
private String m_DienThoai;
private String m_NickName;
private String m_DiaChi;
public MyContactDTO(){}
public MyContactDTO(int id, String ten, String congty,
String hinh, String email, String dienthoai,String nickname, String diachi){
m_Id = id;
m_Ten = ten;
m_CongTy = congty;
m_Hinh = hinh;
m_Email = email;
m_DienThoai = dienthoai;
m_NickName = nickname;
m_DiaChi = diachi;
}
/**
* @return the m_Id
*/
public int getM_Id() {
return m_Id;
}
/**
* @param m_Id the m_Id to set
*/
public void setM_Id(int m_Id) {
this.m_Id = m_Id;
}
/**
* @return the m_Ten
*/
public String getM_Ten() {
return m_Ten;
}
/**
* @param m_Ten the m_Ten to set
*/
public void setM_Ten(String m_Ten) {
this.m_Ten = m_Ten;
}
/**
* @return the m_CongTy
*/
public String getM_CongTy() {
return m_CongTy;
}
/**
* @param m_CongTy the m_CongTy to set
*/
public void setM_CongTy(String m_CongTy) {
this.m_CongTy = m_CongTy;
}
/**
* @return the m_Hinh
*/
public String getM_Hinh() {
return m_Hinh;
}
/**
* @param m_Hinh the m_Hinh to set
*/
public void setM_Hinh(String m_Hinh) {
this.m_Hinh = m_Hinh;
}
/**
* @return the m_Email
*/
public String getM_Email() {
return m_Email;
}
/**
* @param m_Email the m_Email to set
*/
public void setM_Email(String m_Email) {
this.m_Email = m_Email;
}
/**
* @return the m_DienThoai
*/
public String getM_DienThoai() {
return m_DienThoai;
}
/**
* @param m_DienThoai the m_DienThoai to set
*/
public void setM_DienThoai(String m_DienThoai) {
this.m_DienThoai = m_DienThoai;
}
/**
* @return the m_NickName
*/
public String getM_NickName() {
return m_NickName;
}
/**
* @param m_NickName the m_NickName to set
*/
public void setM_NickName(String m_NickName) {
this.m_NickName = m_NickName;
}
/**
* @return the m_DiaChi
*/
public String getM_DiaChi() {
return m_DiaChi;
}
/**
* @param m_DiaChi the m_DiaChi to set
*/
public void setM_DiaChi(String m_DiaChi) {
this.m_DiaChi = m_DiaChi;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyAttachDTO {
private int m_Id;
private int m_IdMail;
private String m_DuongDan;
private String m_TenFile;
public MyAttachDTO(){}
public MyAttachDTO(int id, int idMail, String duongdan, String tenfile){
m_Id = id;
m_IdMail = idMail;
m_DuongDan = duongdan;
m_TenFile = tenfile;
}
/**
* @return the m_Id
*/
public int getM_Id() {
return m_Id;
}
/**
* @param m_Id the m_Id to set
*/
public void setM_Id(int m_Id) {
this.m_Id = m_Id;
}
/**
* @return the m_IdMail
*/
public int getM_IdMail() {
return m_IdMail;
}
/**
* @return the m_ĐuongDan
*/
public String getM_DuongDan() {
return m_DuongDan;
}
/**
* @return the m_TenFile
*/
public String getM_TenFile() {
return m_TenFile;
}
/**
* @param m_TenFile the m_TenFile to set
*/
public void setM_TenFile(String m_TenFile) {
this.m_TenFile = m_TenFile;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
*
* @author Dang Thi Phuong Thao
*/
public class MyMailDTO {
private int m_Id = 0;
private String m_ChuDe = "";
private String m_NguoiGoi = "";
private String m_NguoiNhan = "";
private int m_MucDo = 0;
private int m_TinhTrang = 0;
private String m_CC = "";
private String m_BCC = "";
private Date m_Ngay = new Date();
private String m_DuongDanThuMuc = "";
private String m_DuongDanFileChuaNoiDung = "";
public MyMailDTO(){}
public MyMailDTO(MimeMessage mess){
try {
m_ChuDe = mess.getSubject();
m_NguoiGoi = mess.getFrom()[0].toString();
Address adds[] = mess.getRecipients(Message.RecipientType.TO);
for (int i = 0; i < adds.length; i++) {
m_NguoiNhan += adds[i].toString() + ",";
}
//m_MucDo = mess.get;
//m_TinhTrang = mess.getFlags().;
if(mess.getRecipients(Message.RecipientType.CC) != null){
adds = mess.getRecipients(Message.RecipientType.CC);
for (int i = 0; i < adds.length; i++) {
m_CC += adds[i].toString();
}
}
adds = mess.getRecipients(Message.RecipientType.BCC);
if (adds != null){
for (int i = 0; i < adds.length; i++) {
m_BCC += adds[i].toString();
}
}
m_Ngay = mess.getSentDate();
//m_TinhTrang = mess.getFlags().getSystemFlags()[0].
//m_DuongDanThuMuc = DuongDanThuMuc;
//m_DuongDanFileChuaNoiDung = DuongDanFileChuaNoiDung;
} catch (MessagingException ex) {
Logger.getLogger(MyMailDTO.class.getName()).log(Level.SEVERE, null, ex);
}
}
public MyMailDTO(int Id, String ChuDe, String NguoiGoi, String NguoiNhan, int MucDo, int TinhTrang,
String CC, String BCC, Date Ngay, String DuongDanThuMuc, String DuongDanFileChuaNoiDung ){
m_Id = Id;
m_ChuDe = ChuDe;
m_NguoiGoi = NguoiGoi;
m_NguoiNhan = NguoiNhan;
m_MucDo = MucDo;
m_TinhTrang = TinhTrang;
m_CC = CC;
m_BCC = BCC;
m_Ngay = Ngay;
m_DuongDanThuMuc = DuongDanThuMuc;
m_DuongDanFileChuaNoiDung = DuongDanFileChuaNoiDung;
}
/**
* @return the m_Id
*/
public int getM_Id() {
return m_Id;
}
/**
* @param m_Id the m_Id to set
*/
public void setM_Id(int m_Id) {
this.m_Id = m_Id;
}
/**
* @return the m_ChuDe
*/
public String getM_ChuDe() {
return m_ChuDe;
}
/**
* @param m_ChuDe the m_ChuDe to set
*/
public void setM_ChuDe(String m_ChuDe) {
this.m_ChuDe = m_ChuDe;
}
/**
* @return the m_NguoiGoi
*/
public String getM_NguoiGoi() {
return m_NguoiGoi;
}
/**
* @param m_NguoiGoi the m_NguoiGoi to set
*/
public void setM_NguoiGoi(String m_NguoiGoi) {
this.m_NguoiGoi = m_NguoiGoi;
}
/**
* @return the m_NguoiNhan
*/
public String getM_NguoiNhan() {
return m_NguoiNhan;
}
/**
* @param m_NguoiNhan the m_NguoiNhan to set
*/
public void setM_NguoiNhan(String m_NguoiNhan) {
this.m_NguoiNhan = m_NguoiNhan;
}
/**
* @return the m_MucDo
*/
public int getM_MucDo() {
return m_MucDo;
}
/**
* @param m_MucDo the m_MucDo to set
*/
public void setM_MucDo(int m_MucDo) {
this.m_MucDo = m_MucDo;
}
/**
* @return the m_TinhTrang
*/
public int getM_TinhTrang() {
return m_TinhTrang;
}
/**
* @param m_TinhTrang the m_TinhTrang to set
*/
public void setM_TinhTrang(int m_TinhTrang) {
this.m_TinhTrang = m_TinhTrang;
}
/**
* @return the m_CC
*/
public String getM_CC() {
return m_CC;
}
/**
* @param m_CC the m_CC to set
*/
public void setM_CC(String m_CC) {
this.m_CC = m_CC;
}
/**
* @return the m_BCC
*/
public String getM_BCC() {
return m_BCC;
}
/**
* @param m_BCC the m_BCC to set
*/
public void setM_BCC(String m_BCC) {
this.m_BCC = m_BCC;
}
/**
* @return the m_Ngay
*/
public Date getM_Ngay() {
return m_Ngay;
}
/**
* @param m_Ngay the m_Ngay to set
*/
public void setM_Ngay(Date m_Ngay) {
this.m_Ngay = m_Ngay;
}
/**
* @return the m_DuongDanThuMuc
*/
public String getM_DuongDanThuMuc() {
return m_DuongDanThuMuc;
}
/**
* @param m_DuongDanThuMuc the m_DuongDanThuMuc to set
*/
public void setM_DuongDanThuMuc(String m_DuongDanThuMuc) {
this.m_DuongDanThuMuc = m_DuongDanThuMuc;
}
/**
* @return the m_DuongDanFileChuaNoiDung
*/
public String getM_DuongDanFileChuaNoiDung() {
return m_DuongDanFileChuaNoiDung;
}
/**
* @param m_DuongDanFileChuaNoiDung the m_DuongDanFileChuaNoiDung to set
*/
public void setM_DuongDanFileChuaNoiDung(String m_DuongDanFileChuaNoiDung) {
this.m_DuongDanFileChuaNoiDung = m_DuongDanFileChuaNoiDung;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
/**
*
* @author Administrator
*/
public class FolderVaSoMailChuaDoc {
private String m_DuongDan;
private int m_SoMail;
public FolderVaSoMailChuaDoc(){
m_DuongDan = "";
m_SoMail = 0;
}
/**
* @return the m_DuongDan
*/
public String getM_DuongDan() {
return m_DuongDan;
}
/**
* @param m_DuongDan the m_DuongDan to set
*/
public void setM_DuongDan(String m_DuongDan) {
this.m_DuongDan = m_DuongDan;
}
/**
* @return the m_SoMail
*/
public int getM_SoMail() {
return m_SoMail;
}
/**
* @param m_SoMail the m_SoMail to set
*/
public void setM_SoMail(int m_SoMail) {
this.m_SoMail = m_SoMail;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JDialog_NhapTenThuMuc.java
*
* Created on 17-06-2009, 13:44:59
*/
package doanlythuyet_javaoutlook.MyUserControl;
import javax.swing.JOptionPane;
/**
*
* @author ShineShiao
*/
public class JDialog_NhapTenThuMuc extends javax.swing.JDialog {
private String m_TenThuMuc = "";
/** Creates new form JDialog_NhapTenThuMuc */
public JDialog_NhapTenThuMuc(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public String getTenThuMuc(){
return m_TenThuMuc;
}
JDialog_NhapTenThuMuc() {
throw new UnsupportedOperationException("Not yet implemented");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField_TenThuMuc = new javax.swing.JTextField();
jButton_Chon = new javax.swing.JButton();
jButton_HuyBo = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JDialog_NhapTenThuMuc.class);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_TenThuMuc.setText(resourceMap.getString("jTextField_TenThuMuc.text")); // NOI18N
jTextField_TenThuMuc.setName("jTextField_TenThuMuc"); // NOI18N
jButton_Chon.setText(resourceMap.getString("jButton_Chon.text")); // NOI18N
jButton_Chon.setName("jButton_Chon"); // NOI18N
jButton_Chon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_ChonActionPerformed(evt);
}
});
jButton_HuyBo.setText(resourceMap.getString("jButton_HuyBo.text")); // NOI18N
jButton_HuyBo.setName("jButton_HuyBo"); // NOI18N
jButton_HuyBo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_HuyBoActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton_HuyBo)
.addGap(18, 18, 18)
.addComponent(jButton_Chon))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jTextField_TenThuMuc, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(26, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_TenThuMuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Chon)
.addComponent(jButton_HuyBo))
.addContainerGap(32, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_ChonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ChonActionPerformed
// TODO add your handling code here:
if(jTextField_TenThuMuc.getText().equals("")){
JOptionPane.showMessageDialog(null, "Phải nhập tên thư mục !!!" );
System.exit(0);
}
else{
m_TenThuMuc= jTextField_TenThuMuc.getText();
this.dispose();
}
}//GEN-LAST:event_jButton_ChonActionPerformed
private void jButton_HuyBoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_HuyBoActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_jButton_HuyBoActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog_NhapTenThuMuc dialog = new JDialog_NhapTenThuMuc(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Chon;
private javax.swing.JButton jButton_HuyBo;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField_TenThuMuc;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JFrame_Contact.java
*
* Created on 16-06-2009, 16:46:33
*/
package doanlythuyet_javaoutlook.MyUserControl;
import BUS.MyContactBUS;
import DTO.MyAttachDTO;
import DTO.MyContactDTO;
import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp;
import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author ShineShiao
*/
public class JFrame_Contact extends javax.swing.JFrame {
private ArrayList<String> cacMailDangChon;
public void duaDTOLenHienThiChiTiet(MyContactDTO contactDTO){
jTextField_Address.setText(contactDTO.getM_DiaChi());
jTextField_Company.setText(contactDTO.getM_CongTy());
jTextField_Email.setText(contactDTO.getM_Email());
jTextField_Fullname.setText(contactDTO.getM_Ten());
jTextField_NickName.setText(contactDTO.getM_NickName());
jTextField_PhoneNumber.setText(contactDTO.getM_DiaChi());
//jTextField_Address.setText(contactDTO.getM_DiaChi());
String imDir = DoAnLyThuyet_JavaOutLookApp.getCurdir() + contactDTO.getM_Hinh();
loadAnhLenFrame(imDir);
}
private jTable_HienThiContact conClass_Table = new jTable_HienThiContact();
private void initMyComponents() throws IOException, SQLException{
//conClass_Table.DuaDanhSachMailVaoBang(new ArrayList<MyContactDTO>(0));
jScrollPane1.setViewportView(conClass_Table);
conClass_Table.refreshBang();
conClass_Table.addEventListener_ClickChuotVaoCayDuyetFile(new EventListener_ClickChuotVaoCayDuyetFile() {
public void Event_ClickChuotVaoCayDuyetFile_Occurred(String str_fileduocchon) {
try {
//throw new UnsupportedOperationException("Not supported yet.");
//JOptionPane.showMessageDialog(null, str_fileduocchon);
duaDTOLenHienThiChiTiet(new MyContactBUS().layTatCaContactBangID(str_fileduocchon));
jButton_Luu.setToolTipText(str_fileduocchon);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/** Creates new form JFrame_Contact */
public JFrame_Contact() throws IOException, SQLException {
initComponents();
initMyComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jToolBar1 = new javax.swing.JToolBar();
jButton_New = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField_Fullname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTextField_NickName = new javax.swing.JTextField();
jTextField_PhoneNumber = new javax.swing.JTextField();
jTextField_Address = new javax.swing.JTextField();
jTextField_Company = new javax.swing.JTextField();
jTextField_Email = new javax.swing.JTextField();
jPanel_Image = new javax.swing.JPanel();
jLabel_Image = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton_TimAnh = new javax.swing.JButton();
jButton_Luu = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton5 = new javax.swing.JRadioButton();
jPanel4 = new javax.swing.JPanel();
jButton_GoiMail = new javax.swing.JButton();
jButton_Xoa = new javax.swing.JButton();
jButton_Xoa3 = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
jMenu_New = new javax.swing.JMenu();
jMenuItem_Mail = new javax.swing.JMenuItem();
jMenuItem_Contact = new javax.swing.JMenuItem();
jMenuItem_Task = new javax.swing.JMenuItem();
jMenuItem_Folder = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
jMenuItem_Save = new javax.swing.JMenuItem();
jMenuItem_SaveAs = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jSeparator5 = new javax.swing.JSeparator();
jMenuItem_delete = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
javax.swing.JMenuItem jMenuItem_Close = new javax.swing.JMenuItem();
jMenu_Edit = new javax.swing.JMenu();
jMenuItem_Cut = new javax.swing.JMenuItem();
jMenuItem_Copy = new javax.swing.JMenuItem();
jMenuItem_Paste = new javax.swing.JMenuItem();
jSeparator3 = new javax.swing.JSeparator();
jMenuItem_SelectAll = new javax.swing.JMenuItem();
jSeparator4 = new javax.swing.JSeparator();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu_Tools = new javax.swing.JMenu();
jMenuItem_Find = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
jToolBar1.setRollover(true);
jToolBar1.setName("jToolBar1"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JFrame_Contact.class);
jButton_New.setText(resourceMap.getString("jButton_New.text")); // NOI18N
jButton_New.setFocusable(false);
jButton_New.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_New.setName("jButton_New"); // NOI18N
jButton_New.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(jButton_New);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 868, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
jPanel2.setName("jPanel2"); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jTextField_Fullname.setText(resourceMap.getString("jTextField_Fullname.text")); // NOI18N
jTextField_Fullname.setName("jTextField_Fullname"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // NOI18N
jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
jLabel6.setName("jLabel6"); // NOI18N
jTextField_NickName.setText(resourceMap.getString("jTextField_NickName.text")); // NOI18N
jTextField_NickName.setName("jTextField_NickName"); // NOI18N
jTextField_PhoneNumber.setText(resourceMap.getString("jTextField_PhoneNumber.text")); // NOI18N
jTextField_PhoneNumber.setName("jTextField_PhoneNumber"); // NOI18N
jTextField_Address.setText(resourceMap.getString("jTextField_Address.text")); // NOI18N
jTextField_Address.setName("jTextField_Address"); // NOI18N
jTextField_Company.setText(resourceMap.getString("jTextField_Company.text")); // NOI18N
jTextField_Company.setName("jTextField_Company"); // NOI18N
jTextField_Email.setText(resourceMap.getString("jTextField_Email.text")); // NOI18N
jTextField_Email.setName("jTextField_Email"); // NOI18N
jPanel_Image.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel_Image.setName("jPanel_Image"); // NOI18N
jLabel_Image.setText(resourceMap.getString("jLabel_Image.text")); // NOI18N
jLabel_Image.setName("jLabel_Image"); // NOI18N
javax.swing.GroupLayout jPanel_ImageLayout = new javax.swing.GroupLayout(jPanel_Image);
jPanel_Image.setLayout(jPanel_ImageLayout);
jPanel_ImageLayout.setHorizontalGroup(
jPanel_ImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel_ImageLayout.setVerticalGroup(
jPanel_ImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
jButton1.setName("jButton1"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton_TimAnh.setText(resourceMap.getString("jButton_TimAnh.text")); // NOI18N
jButton_TimAnh.setName("jButton_TimAnh"); // NOI18N
jButton_TimAnh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_TimAnhActionPerformed(evt);
}
});
jButton_Luu.setText(resourceMap.getString("jButton_Luu.text")); // NOI18N
jButton_Luu.setName("jButton_Luu"); // NOI18N
jButton_Luu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_LuuActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Luu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_TimAnh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(jPanel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jTextField_Company)
.addComponent(jTextField_PhoneNumber)
.addComponent(jTextField_Fullname, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(7, 7, 7))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(29, 29, 29)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField_Address, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField_Email, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE))
.addComponent(jTextField_NickName, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_NickName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Fullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_PhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_Company, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jButton_TimAnh)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(jButton_Luu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addComponent(jPanel_Image, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel3.border.title"))); // NOI18N
jPanel3.setName("jPanel3"); // NOI18N
buttonGroup1.add(jRadioButton1);
jRadioButton1.setSelected(true);
jRadioButton1.setText(resourceMap.getString("jRadioButton1.text")); // NOI18N
jRadioButton1.setName("jRadioButton1"); // NOI18N
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText(resourceMap.getString("jRadioButton2.text")); // NOI18N
jRadioButton2.setName("jRadioButton2"); // NOI18N
jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton2ActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButton5);
jRadioButton5.setText(resourceMap.getString("jRadioButton5.text")); // NOI18N
jRadioButton5.setName("jRadioButton5"); // NOI18N
jRadioButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton5ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton1)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton5)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton2)
.addComponent(jRadioButton5)))
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel4.border.title"))); // NOI18N
jPanel4.setName("jPanel4"); // NOI18N
jButton_GoiMail.setText(resourceMap.getString("jButton_GoiMail.text")); // NOI18N
jButton_GoiMail.setName("jButton_GoiMail"); // NOI18N
jButton_GoiMail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_GoiMailActionPerformed(evt);
}
});
jButton_Xoa.setText(resourceMap.getString("jButton_Xoa.text")); // NOI18N
jButton_Xoa.setName("jButton_Xoa"); // NOI18N
jButton_Xoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_XoaActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addComponent(jButton_GoiMail, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Xoa))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_GoiMail)
.addComponent(jButton_Xoa))
);
jButton_Xoa3.setText(resourceMap.getString("jButton_Xoa3.text")); // NOI18N
jButton_Xoa3.setName("jButton_Xoa3"); // NOI18N
jButton_Xoa3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_Xoa3ActionPerformed(evt);
}
});
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
jMenu_New.setText(resourceMap.getString("jMenu_New.text")); // NOI18N
jMenu_New.setName("jMenu_New"); // NOI18N
jMenuItem_Mail.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Mail.setText(resourceMap.getString("jMenuItem_Mail.text")); // NOI18N
jMenuItem_Mail.setName("jMenuItem_Mail"); // NOI18N
jMenu_New.add(jMenuItem_Mail);
jMenuItem_Contact.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Contact.setText(resourceMap.getString("jMenuItem_Contact.text")); // NOI18N
jMenuItem_Contact.setName("jMenuItem_Contact"); // NOI18N
jMenu_New.add(jMenuItem_Contact);
jMenuItem_Task.setText(resourceMap.getString("jMenuItem_Task.text")); // NOI18N
jMenuItem_Task.setName("jMenuItem_Task"); // NOI18N
jMenu_New.add(jMenuItem_Task);
jMenuItem_Folder.setText(resourceMap.getString("jMenuItem_Folder.text")); // NOI18N
jMenuItem_Folder.setName("jMenuItem_Folder"); // NOI18N
jMenu_New.add(jMenuItem_Folder);
fileMenu.add(jMenu_New);
jSeparator1.setName("jSeparator1"); // NOI18N
fileMenu.add(jSeparator1);
jMenuItem_Save.setText(resourceMap.getString("jMenuItem_Save.text")); // NOI18N
jMenuItem_Save.setName("jMenuItem_Save"); // NOI18N
fileMenu.add(jMenuItem_Save);
jMenuItem_SaveAs.setText(resourceMap.getString("jMenuItem_SaveAs.text")); // NOI18N
jMenuItem_SaveAs.setName("jMenuItem_SaveAs"); // NOI18N
fileMenu.add(jMenuItem_SaveAs);
jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
jMenuItem2.setName("jMenuItem2"); // NOI18N
fileMenu.add(jMenuItem2);
jSeparator5.setName("jSeparator5"); // NOI18N
fileMenu.add(jSeparator5);
jMenuItem_delete.setText(resourceMap.getString("jMenuItem_delete.text")); // NOI18N
jMenuItem_delete.setName("jMenuItem_delete"); // NOI18N
fileMenu.add(jMenuItem_delete);
jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
jMenuItem3.setName("jMenuItem3"); // NOI18N
fileMenu.add(jMenuItem3);
jSeparator2.setName("jSeparator2"); // NOI18N
fileMenu.add(jSeparator2);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getActionMap(JFrame_Contact.class, this);
jMenuItem_Close.setAction(actionMap.get("quit")); // NOI18N
jMenuItem_Close.setText(resourceMap.getString("jMenuItem_Close.text")); // NOI18N
jMenuItem_Close.setName("jMenuItem_Close"); // NOI18N
fileMenu.add(jMenuItem_Close);
menuBar.add(fileMenu);
jMenu_Edit.setText(resourceMap.getString("jMenu_Edit.text")); // NOI18N
jMenu_Edit.setName("jMenu_Edit"); // NOI18N
jMenuItem_Cut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Cut.setText(resourceMap.getString("jMenuItem_Cut.text")); // NOI18N
jMenuItem_Cut.setName("jMenuItem_Cut"); // NOI18N
jMenu_Edit.add(jMenuItem_Cut);
jMenuItem_Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Copy.setText(resourceMap.getString("jMenuItem_Copy.text")); // NOI18N
jMenuItem_Copy.setName("jMenuItem_Copy"); // NOI18N
jMenu_Edit.add(jMenuItem_Copy);
jMenuItem_Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Paste.setText(resourceMap.getString("jMenuItem_Paste.text")); // NOI18N
jMenuItem_Paste.setName("jMenuItem_Paste"); // NOI18N
jMenu_Edit.add(jMenuItem_Paste);
jSeparator3.setName("jSeparator3"); // NOI18N
jMenu_Edit.add(jSeparator3);
jMenuItem_SelectAll.setText(resourceMap.getString("jMenuItem_SelectAll.text")); // NOI18N
jMenuItem_SelectAll.setName("jMenuItem_SelectAll"); // NOI18N
jMenu_Edit.add(jMenuItem_SelectAll);
jSeparator4.setName("jSeparator4"); // NOI18N
jMenu_Edit.add(jSeparator4);
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
jMenu_Edit.add(jMenuItem1);
menuBar.add(jMenu_Edit);
jMenu_Tools.setText(resourceMap.getString("jMenu_Tools.text")); // NOI18N
jMenu_Tools.setName("jMenu_Tools"); // NOI18N
jMenuItem_Find.setText(resourceMap.getString("jMenuItem_Find.text")); // NOI18N
jMenuItem_Find.setName("jMenuItem_Find"); // NOI18N
jMenu_Tools.add(jMenuItem_Find);
menuBar.add(jMenu_Tools);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 894, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(749, 749, 749)
.addComponent(jButton_Xoa3, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Xoa3)
.addContainerGap(16, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
// TODO add your handling code here:
MyContactDTO contactDTO = taoDTOTuInputNguoiDung();
if (jLabel_Image.getToolTipText() != null){
String reDir = "\\ContactItems\\" + new Date().getTime() + ".mim";
File dir = new File(DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\ContactItems\\");
if (!(dir.exists())){
dir.mkdirs();
}
copyfile (jLabel_Image.getToolTipText(), DoAnLyThuyet_JavaOutLookApp.getCurdir() + reDir);
contactDTO.setM_Hinh(reDir);
}
int newId = new MyContactBUS().themContact(contactDTO);
if (newId != -1){
JOptionPane.showMessageDialog(null, "Thêm thành công contactID: " + newId);
conClass_Table.refreshBang();
}
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* load anh len khunh hinh tren frame
* @param filePath duong dan tuong doi file anh
*/
private void loadAnhLenFrame(String filePath){
if (new File(filePath).exists()){
ImageIcon icon = new ImageIcon(filePath);
icon.setImage(icon.getImage().getScaledInstance(jLabel_Image.getWidth(), jLabel_Image.getHeight(), Image.SCALE_SMOOTH));
jLabel_Image.setToolTipText(filePath);
jLabel_Image.setIcon(icon);
}
else {
jLabel_Image.setToolTipText(null);
jLabel_Image.setIcon(null);
}
}
private void jButton_TimAnhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_TimAnhActionPerformed
try {
// TODO add your handling code here:
File file = moDialogChonAnh();
if (file != null) {
loadAnhLenFrame(file.getCanonicalPath());
}
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton_TimAnhActionPerformed
public static void copyfile(String srFile, String dtFile) throws FileNotFoundException, IOException{
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
/**
* mo dialog cho phep chon anh
* @return file duoc chon
*/
public File moDialogChonAnh()
{
File Kq = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("image files (*.png, *.jpeg)", "png", "jpeg", "jpg"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setCurrentDirectory(new File("."));
int ketQuaShowOpenDialog = fileChooser.showOpenDialog(null);
if (ketQuaShowOpenDialog == JFileChooser.APPROVE_OPTION){
//fileChooser.getf
Kq = fileChooser.getSelectedFile();
}
return Kq;
}
private void jButton_XoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_XoaActionPerformed
// TODO add your handling code here:
ArrayList<Integer> cacIdDuocChon = LayCacIdMailDuocChon();
for (Integer i : cacIdDuocChon){
try {
new MyContactBUS().xoaContact(i);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}
conClass_Table.refreshBang();
}//GEN-LAST:event_jButton_XoaActionPerformed
private void jButton_LuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_LuuActionPerformed
try {
// TODO add your handling code here:
String Kq = "";
if (capNhatContact() == 1){
Kq = "Cap nhat thanh cong!";
conClass_Table.refreshBang();
}
else
Kq = "Cap nhat that bai!";
JOptionPane.showMessageDialog(null, Kq);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton_LuuActionPerformed
private void jRadioButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton5ActionPerformed
try {
// TODO add your handling code here:
ArrayList<MyContactDTO> conDTOs = new MyContactBUS().layTatCaContact();
//jScrollPane1.removeAll();
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(20);
layout.setVgap(20);
JPanel panel = new JPanel(layout);
for (MyContactDTO con : conDTOs){
JPanel_BusCard busCard = new JPanel_BusCard();
busCard.HienThiThongTin(con.getM_Id());
panel.add(busCard);
}
jScrollPane1.setViewportView(panel);
//busCard.set
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
//busCard.set
}//GEN-LAST:event_jRadioButton5ActionPerformed
private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
ArrayList<MyContactDTO> conDTOs = new MyContactBUS().layTatCaContact();
//jScrollPane1.removeAll();
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(20);
layout.setVgap(20);
JPanel panel = new JPanel(layout);
for (MyContactDTO con : conDTOs){
JPanel_AddCard addCard = new JPanel_AddCard();
addCard.HienThiThongTin(con.getM_Id());
panel.add(addCard);
}
jScrollPane1.setViewportView(panel);
//busCard.set
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jRadioButton2ActionPerformed
private void jButton_GoiMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_GoiMailActionPerformed
// TODO add your handling code here:
setCacMailDangChon(LayCacEMailDuocChon());
JFrame_GuiMail guiMail = new JFrame_GuiMail();
guiMail.getJTextField_to().setText(getCacMailDangChon().get(0));
String cc = "";
for (int i = 1; i < getCacMailDangChon().size(); i++){
cc += getCacMailDangChon().get(i) + ",";
}
guiMail.getJTextField_cc().setText(cc);
//dispose();
//guiMail.getJTextField_to().sett
}//GEN-LAST:event_jButton_GoiMailActionPerformed
private void jButton_Xoa3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Xoa3ActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_jButton_Xoa3ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
try {
// TODO add your handling code here:
initMyComponents();
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jRadioButton1ActionPerformed
public int capNhatContact () throws SQLException, IOException{
MyContactBUS contactBUS = new MyContactBUS();
MyContactDTO contactDTO = taoDTOTuInputNguoiDung();
contactDTO.setM_Id(Integer.parseInt(jButton_Luu.getToolTipText()));
File file = new File (DoAnLyThuyet_JavaOutLookApp.getCurdir() + contactDTO.getM_Hinh());
if (jLabel_Image.getToolTipText() != null && !file.equals(new File(jLabel_Image.getToolTipText()))){
if (file.exists()){
file.delete();
copyfile(jLabel_Image.getToolTipText(), file.getAbsolutePath());
}
else{
String reDir = "\\ContactItems\\" + new Date().getTime() + ".mim";
File dir = new File(DoAnLyThuyet_JavaOutLookApp.getCurdir() + "\\ContactItems\\");
if (!(dir.exists())){
dir.mkdirs();
}
copyfile (jLabel_Image.getToolTipText(), DoAnLyThuyet_JavaOutLookApp.getCurdir() + reDir);
contactDTO.setM_Hinh(reDir);
}
}
return contactBUS.capNhatContact(contactDTO);
}
public ArrayList<Integer> LayCacIdMailDuocChon (){
ArrayList<Integer> Kq = new ArrayList<Integer>();
for (int i = 0; i < conClass_Table.getRowCount(); i++)
if (conClass_Table.getValueAt(i, 0) != null && (Boolean)conClass_Table.getValueAt(i, 0))
Kq.add(Integer.parseInt(conClass_Table.getValueAt(i, conClass_Table.getColumnCount() - 1).toString()));
return Kq;
}
public ArrayList<String> LayCacEMailDuocChon (){
ArrayList<String> Kq = new ArrayList<String>();
for (int i = 0; i < conClass_Table.getRowCount(); i++)
if (conClass_Table.getValueAt(i, 0) != null && (Boolean)conClass_Table.getValueAt(i, 0)
&& conClass_Table.getValueAt(i, 3) != null)
Kq.add(conClass_Table.getValueAt(i, 3).toString());
return Kq;
}
private MyContactDTO taoDTOTuInputNguoiDung(){
MyContactDTO Kq = new MyContactDTO();
Kq.setM_CongTy(jTextField_Company.getText());
Kq.setM_DiaChi(jTextField_Address.getText());
Kq.setM_Email(jTextField_Email.getText());
Kq.setM_Ten(jTextField_Fullname.getText());
Kq.setM_NickName(jTextField_NickName.getText());
Kq.setM_DienThoai(jTextField_PhoneNumber.getText());
return Kq;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new JFrame_Contact().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JFrame_Contact.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_GoiMail;
private javax.swing.JButton jButton_Luu;
private javax.swing.JButton jButton_New;
private javax.swing.JButton jButton_TimAnh;
private javax.swing.JButton jButton_Xoa;
private javax.swing.JButton jButton_Xoa3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel_Image;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem_Contact;
private javax.swing.JMenuItem jMenuItem_Copy;
private javax.swing.JMenuItem jMenuItem_Cut;
private javax.swing.JMenuItem jMenuItem_Find;
private javax.swing.JMenuItem jMenuItem_Folder;
private javax.swing.JMenuItem jMenuItem_Mail;
private javax.swing.JMenuItem jMenuItem_Paste;
private javax.swing.JMenuItem jMenuItem_Save;
private javax.swing.JMenuItem jMenuItem_SaveAs;
private javax.swing.JMenuItem jMenuItem_SelectAll;
private javax.swing.JMenuItem jMenuItem_Task;
private javax.swing.JMenuItem jMenuItem_delete;
private javax.swing.JMenu jMenu_Edit;
private javax.swing.JMenu jMenu_New;
private javax.swing.JMenu jMenu_Tools;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel_Image;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JTextField jTextField_Address;
private javax.swing.JTextField jTextField_Company;
private javax.swing.JTextField jTextField_Email;
private javax.swing.JTextField jTextField_Fullname;
private javax.swing.JTextField jTextField_NickName;
private javax.swing.JTextField jTextField_PhoneNumber;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
/**
* @return the jButton_GoiMail
*/
public javax.swing.JButton getJButton_GoiMail() {
return jButton_GoiMail;
}
/**
* @param jButton_GoiMail the jButton_GoiMail to set
*/
public void setJButton_GoiMail(javax.swing.JButton jButton_GoiMail) {
this.jButton_GoiMail = jButton_GoiMail;
}
/**
* @return the cacMailDangChon
*/
public ArrayList<String> getCacMailDangChon() {
return cacMailDangChon;
}
/**
* @param cacMailDangChon the cacMailDangChon to set
*/
public void setCacMailDangChon(ArrayList<String> cacMailDangChon) {
this.cacMailDangChon = cacMailDangChon;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JTreeFromXMLFile.java
*
* Created on 10-06-2009, 14:28:32
*/
package doanlythuyet_javaoutlook.MyUserControl;
import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp;
import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.*;
import java.io.IOException;
//import javax.swing.;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.Enumeration;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.MouseInputListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
/**
*
* @author ShineShiao
*/
public class JTreeFromXMLFile extends javax.swing.JPanel {
private boolean m_chiDoc;
private final JPopupMenu m_popupMenu;
private String m_fileName;// = "C:\\Documents and Settings\\Administrator\\Desktop\\JavaMail\\ 0512324-0512328-0512333-mailclient\\DoAnLyThuyet_JavaOutLook\\src\\Database\\XML_ThuMucNguoiDung.xml";
/** Creates new form JTreeFromXMLFile */
public void expandTree (TreePath path){
jTreeThuMucNguoiDung.expandPath(path);
}
// If expand is true, expands all nodes in the tree.
// Otherwise, collapses all nodes in the tree.
public static void expandAll(JTree tree, boolean expand) {
TreeNode root = (TreeNode)tree.getModel().getRoot();
// Traverse tree from root
expandAll(tree, new TreePath(root), expand);
}
private static void expandAll(JTree tree, TreePath parent, boolean expand) {
// Traverse children
TreeNode node = (TreeNode)parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration e=node.children(); e.hasMoreElements(); ) {
TreeNode n = (TreeNode)e.nextElement();
TreePath path = parent.pathByAddingChild(n);
expandAll(tree, path, expand);
}
}
// Expansion or collapse must be done bottom-up
if (expand) {
tree.expandPath(parent);
} else {
tree.collapsePath(parent);
}
}
public JTreeFromXMLFile(String xmlFilePath, Boolean chiDoc) {
m_chiDoc = chiDoc;
m_fileName = xmlFilePath;
m_popupMenu = new JPopupMenu();
//m_popupMenu.
if (!chiDoc){
String cacHanhViThayDoiCauTruc[] = {"Thêm mới", "Xóa", "Đổi Tên"};
for (String HanhVi : cacHanhViThayDoiCauTruc)
{
JMenuItem menuItem = new JMenuItem(HanhVi);
menuItem.addMouseListener(new PopupMenu_MouseListerner_MyCayHienThiThuMuc(menuItem.getText()));
m_popupMenu.add(menuItem);
}
m_popupMenu.addSeparator();
}
String cacHanhViKhongThayDoiCauTruc[] = {"Đánh dấu đã đọc", "Đánh dấu chưa đọc", "Gỡ dấu"};
for (String HanhVi : cacHanhViKhongThayDoiCauTruc)
{
JMenuItem menuItem = new JMenuItem(HanhVi);
menuItem.addMouseListener(new PopupMenu_MouseListerner_MyCayHienThiThuMuc(menuItem.getText()));
m_popupMenu.add(menuItem);
}
initComponents();
try {
thayDoiIconCuaTree();
TaoCay();
//expandTree(new TreePath(jTreeThuMucNguoiDung.getModel().getRoot()));
expandAll(jTreeThuMucNguoiDung, true);
} catch (SAXException ex) {
Logger.getLogger(JTreeFromXMLFile.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Tao cay thu muc tu file XML loi: " + ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(JTreeFromXMLFile.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Tao cay thu muc tu file XML loi: " + ex.getMessage());
} catch (ParserConfigurationException ex) {
Logger.getLogger(JTreeFromXMLFile.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Tao cay thu muc tu file XML loi: " + ex.getMessage());
}
jTreeThuMucNguoiDung.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
if (jTreeThuMucNguoiDung.getSelectionPath() == null)
return;
String strPath = StringPathFromTreePath(jTreeThuMucNguoiDung.getSelectionPath());
getM_popupMenu().setToolTipText(strPath);
if (e.getButton() == MouseEvent.BUTTON3) {
getM_popupMenu().show(e.getComponent(), e.getX(), e.getY());
//return;
}
}
public void mousePressed(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
public void mouseExited(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
});
}
public static TreePath TreePathFromStringPath (String stringPath){
String cacPath[] = stringPath.split("\\\\");
MutableTreeNode cacNode[] = new MutableTreeNode[cacPath.length];
for (int i = 0; i < cacPath.length; i++)
cacNode[i] = new DefaultMutableTreeNode(cacPath[i]);
return new TreePath(cacNode);
}
public static String StringPathFromTreePath (TreePath treePath){
String Kq = "";
if (treePath == null)
return Kq;
Object cacNode[] = treePath.getPath();
for (int i = 0; i < cacNode.length; i++)
Kq += ((DefaultMutableTreeNode)cacNode[i]).getUserObject().toString() + "\\";
return Kq;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTreeThuMucNguoiDung = new javax.swing.JTree();
setName("Form"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
jTreeThuMucNguoiDung.setName("jTreeThuMucNguoiDung"); // NOI18N
jTreeThuMucNguoiDung.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
jTreeThuMucNguoiDungValueChanged(evt);
}
});
jScrollPane1.setViewportView(jTreeThuMucNguoiDung);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void jTreeThuMucNguoiDungValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeThuMucNguoiDungValueChanged
// TODO add your handling code here:
String strPath = StringPathFromTreePath(jTreeThuMucNguoiDung.getSelectionPath());
initEvent_ClickChuotVaoCayDuyetFile(strPath);
}//GEN-LAST:event_jTreeThuMucNguoiDungValueChanged
public void TaoCay() throws SAXException, IOException, ParserConfigurationException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setIgnoringElementContentWhitespace(true);
//factory.setIgnoringComments(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
DefaultTreeModel model = (DefaultTreeModel)getJTreeThuMucNguoiDung().getModel();
MutableTreeNode newNode = new DefaultMutableTreeNode(root.getAttribute("name"));
model.setRoot(newNode);
NodeList list = root.getChildNodes();
for(int i=0;i<list.getLength();++i)
{
// xử lý từng node
if (list.item(i) instanceof Element){
Element ele = (Element)list.item(i);
ThemXMLElementVaoTree(model, ele, newNode);
}
}
}
public void ThemXMLElementVaoTree(DefaultTreeModel model,Element ele,MutableTreeNode nodeCha){
MutableTreeNode newNode = new DefaultMutableTreeNode(ele.getAttribute("name"));
model.insertNodeInto(newNode, nodeCha, nodeCha.getChildCount());
for (int i =0;i<ele.getChildNodes().getLength();i++){
ThemXMLElementVaoTree(model, (Element)ele.getChildNodes().item(i), newNode);
}
}
/** Thêm 1 thư mục vào vây
* strPath:đường dẫn thư mục cha
* strName:Tên thư mục cần thêm
* strFileName:Tên file xml
*/
public void ThemThuMucMoiVaoXML(String strPath,String strName,String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{
String[] strCacChuoi = null;
strCacChuoi = strPath.split("\\\\");
//doc file xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
Element ElementCha = root;
//String maSach = root.getAttribute("Inbox");
for (int i=1;i<strCacChuoi.length;i++){
ElementCha = LayNodeTuXML(ElementCha,strCacChuoi[i]);
}
Element ThuMuc = doc.createElement("ThuMuc");
ThuMuc.setAttribute("name", strName);
ElementCha.appendChild(ThuMuc);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(strFileName)));
TaoCay();
// ElementCha.insertBefore(ThuMuc, ElementCha.getFirstChild());
}
/** xóa 1 thư mục khỏi cây
* strPath:đường dẫn thư mục cần xóa
* strFileName:Tên file xml
*/
public void XoaThuMucTrongXML(String strPath,String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{
String[] strCacChuoi = null;
strCacChuoi = strPath.split("\\\\");
//doc file xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
Element ElementCha = root;
//String maSach = root.getAttribute("Inbox");
if(strCacChuoi.length==1){ //thu muc root
JOptionPane.showMessageDialog(null, "Không Thể Xóa Thư Mục Này " );
return;
}
for (int i=1;i<strCacChuoi.length;i++){
ElementCha = LayNodeTuXML(ElementCha,strCacChuoi[i]);
}
ElementCha.getParentNode().removeChild(ElementCha);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(strFileName)));
TaoCay();
}
/** Đổi Tên 1 thư mục vào vây
* strPath:đường dẫn thư mục cần đổi
* strName:Tên thư mục cần đổi
* strFileName:Tên file xml
*/
public void DoiTenThuMucTrongXML(String strPath,String strName,String strFileName) throws ParserConfigurationException, IOException, SAXException, TransformerConfigurationException, TransformerException{
String[] strCacChuoi = null;
strCacChuoi = strPath.split("\\\\");
//doc file xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(m_fileName));
Element root = (Element) doc.getDocumentElement();
Element ElementCha = root;
//String maSach = root.getAttribute("Inbox");
for (int i=1;i<strCacChuoi.length;i++){
ElementCha = LayNodeTuXML(ElementCha,strCacChuoi[i]);
}
ElementCha.setAttribute("name", strName);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(strFileName)));
TaoCay();
}
/** tìm Element con có tên tương ứng
* Element:node cha
* strName:Tên thư mục cần thêm
* return Element tương ứng
*/
public Element LayNodeTuXML(Element NodeCha,String strName) {
NodeList List = NodeCha.getChildNodes();
// String maSach = root.getAttribute("Inbox");
for(int i=0;i<List.getLength();i++)
{
// xử lý từng node
Element ele =(Element) List.item(i);
String tennode = ele.getAttribute("name");
if(tennode.equals(strName))
return ele;
}
return null;
}
/** Thay đổi icon của cây
*
*
*/
public void thayDoiIconCuaTree(){
// Retrieve the three icons
Icon leafIcon = new ImageIcon("leaf.gif");
Icon openIcon = new ImageIcon("open.gif");
Icon closedIcon = new ImageIcon("closed.gif");
// Update only one tree instance
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTreeThuMucNguoiDung.getCellRenderer();
renderer.setLeafIcon(leafIcon);
renderer.setClosedIcon(closedIcon);
renderer.setOpenIcon(openIcon);
// Remove the icons
renderer.setLeafIcon(null);
renderer.setClosedIcon(null);
renderer.setOpenIcon(null);
// Change defaults so that all new tree components will have new icons
UIManager.put("Tree.leafIcon", leafIcon);
UIManager.put("Tree.openIcon", openIcon);
UIManager.put("Tree.closedIcon", closedIcon);
// Create tree with new icons
//setJTreeThuMucNguoiDung(tree);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTree jTreeThuMucNguoiDung;
// End of variables declaration//GEN-END:variables
/**
* @return the jTreeThuMucNguoiDung
*/
public javax.swing.JTree getJTreeThuMucNguoiDung() {
return jTreeThuMucNguoiDung;
}
/**
* @param jTreeThuMucNguoiDung the jTreeThuMucNguoiDung to set
*/
public void setJTreeThuMucNguoiDung(javax.swing.JTree jTreeThuMucNguoiDung) {
this.jTreeThuMucNguoiDung = jTreeThuMucNguoiDung;
}
//<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien">
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện click chuột vào tree
* @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn)
*/
// This private class is used to fire MyEvents
void initEvent_ClickChuotVaoCayDuyetFile(String evt) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) {
((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
}
/**
* @return the m_popupMenu
*/
public JPopupMenu getM_popupMenu() {
return m_popupMenu;
}
//</editor-fold>
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JFrame_ChiTietMail.java
*
* Created on May 28, 2009, 7:55:46 AM
*/
package doanlythuyet_javaoutlook.MyUserControl;
import BUS.MyAttachBUS;
import BUS.MyMailBUS;
import DTO.MyAttachDTO;
import DTO.MyMailDTO;
import doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp;
import doanlythuyet_javaoutlook.EventListener_ClickChuotVaoCayDuyetFile;
import doanlythuyet_javaoutlook.MyMail;
import java.awt.Desktop;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
/**
*
* @author Dang Thi Phuong Thao
*/
public class JFrame_ChiTietMail extends javax.swing.JFrame {
private int m_MailID;
/** Creates new form JFrame_ChiTietMail */
public JFrame_ChiTietMail() {
initComponents();
}
public JFrame_ChiTietMail (int MailId){
m_MailID = MailId;
initComponents();
//jEditorPane_noidung.setText("Doc va load noi dung mail: " + MailID + " (JFrame_ChiTietMail.java dong 27)");
FileInputStream inputStream = null;
try {
MyMailDTO mailDTO = new MyMailBUS().layMailVoidMailID(String.valueOf(MailId));
jLabel_chude.setText(mailDTO.getM_ChuDe());
jLabel_goi.setText(mailDTO.getM_NguoiGoi());
jLabel_den.setText(mailDTO.getM_NguoiNhan());
jLabel_ngay.setText(mailDTO.getM_Ngay().toString());
inputStream = new FileInputStream(new File(DoAnLyThuyet_JavaOutLookApp.getCurdir() + mailDTO.getM_DuongDanFileChuaNoiDung()));
MyMail mail = new MyMail(DoAnLyThuyet_JavaOutLookApp.getSmtp_host(), DoAnLyThuyet_JavaOutLookApp.getPop3_host(), DoAnLyThuyet_JavaOutLookApp.getUser()
, DoAnLyThuyet_JavaOutLookApp.getPass(), DoAnLyThuyet_JavaOutLookApp.getProxy(), DoAnLyThuyet_JavaOutLookApp.getPort());MimeMessage mess = new MimeMessage(mail.getMailSession(false), inputStream);
Part textPart = MyMail.layPartNoiDung(mess);
if (textPart != null){
jEditorPane_noidung.setContentType(textPart.getContentType());
jEditorPane_noidung.setText(textPart.getContent().toString());
}
DefaultListModel listModel = new DefaultListModel();
listModel.clear();
ArrayList<MyAttachDTO> attachDTOs = new MyAttachBUS().layTatCaAttachCuaMailID(MailId);
for (MyAttachDTO part : attachDTOs){
listModel.addElement(part.getM_TenFile() + ">" + DoAnLyThuyet_JavaOutLookApp.getCurdir() + part.getM_DuongDan());
}
jList1.setModel(listModel);
} catch (Exception ex) {
Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, ex.toString());
}
try {
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(JPanel_XemMail.class.getName()).log(Level.SEVERE, null, ex);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
jScrollPane1 = new javax.swing.JScrollPane();
jToolBar2 = new javax.swing.JToolBar();
jButton_Reply = new javax.swing.JButton();
jButton_ReplyAll = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton_Delete = new javax.swing.JButton();
jScrollPane_noidung = new javax.swing.JScrollPane();
jEditorPane_noidung = new javax.swing.JEditorPane();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel_chude = new javax.swing.JLabel();
jLabel_goi = new javax.swing.JLabel();
jLabel_ngay = new javax.swing.JLabel();
jLabel_den = new javax.swing.JLabel();
jLabel_cc = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
jMenu_New = new javax.swing.JMenu();
jMenuItem_Mail = new javax.swing.JMenuItem();
jMenuItem_Contact = new javax.swing.JMenuItem();
jMenuItem_Task = new javax.swing.JMenuItem();
jMenuItem_Folder = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
jMenuItem_Save = new javax.swing.JMenuItem();
jMenuItem_SaveAs = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jSeparator5 = new javax.swing.JSeparator();
jMenuItem_delete = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
javax.swing.JMenuItem jMenuItem_Close = new javax.swing.JMenuItem();
jMenu_Edit = new javax.swing.JMenu();
jMenuItem_Cut = new javax.swing.JMenuItem();
jMenuItem_Copy = new javax.swing.JMenuItem();
jMenuItem_Paste = new javax.swing.JMenuItem();
jSeparator3 = new javax.swing.JSeparator();
jMenuItem_SelectAll = new javax.swing.JMenuItem();
jSeparator4 = new javax.swing.JSeparator();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu_Tools = new javax.swing.JMenu();
jMenuItem_Find = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
jToolBar1.setRollover(true);
jToolBar1.setName("jToolBar1"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setName("Form"); // NOI18N
jToolBar2.setRollover(true);
jToolBar2.setName("jToolBar2"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getResourceMap(JFrame_ChiTietMail.class);
jButton_Reply.setIcon(resourceMap.getIcon("jButton_Reply.icon")); // NOI18N
jButton_Reply.setText(resourceMap.getString("jButton_Reply.text")); // NOI18N
jButton_Reply.setFocusable(false);
jButton_Reply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_Reply.setName("jButton_Reply"); // NOI18N
jButton_Reply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton_Reply);
jButton_ReplyAll.setIcon(resourceMap.getIcon("jButton_ReplyAll.icon")); // NOI18N
jButton_ReplyAll.setText(resourceMap.getString("jButton_ReplyAll.text")); // NOI18N
jButton_ReplyAll.setFocusable(false);
jButton_ReplyAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_ReplyAll.setName("jButton_ReplyAll"); // NOI18N
jButton_ReplyAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton_ReplyAll);
jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
jButton1.setFocusable(false);
jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton1.setName("jButton1"); // NOI18N
jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton1);
jButton_Delete.setIcon(resourceMap.getIcon("jButton_Delete.icon")); // NOI18N
jButton_Delete.setText(resourceMap.getString("jButton_Delete.text")); // NOI18N
jButton_Delete.setFocusable(false);
jButton_Delete.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButton_Delete.setName("jButton_Delete"); // NOI18N
jButton_Delete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar2.add(jButton_Delete);
jScrollPane_noidung.setName("jScrollPane_noidung"); // NOI18N
jEditorPane_noidung.setEditable(false);
jEditorPane_noidung.setName("jEditorPane_noidung"); // NOI18N
jScrollPane_noidung.setViewportView(jEditorPane_noidung);
jEditorPane_noidung.getAccessibleContext().setAccessibleDescription(resourceMap.getString("jEditorPane1.AccessibleContext.accessibleDescription")); // NOI18N
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
jLabel2.setName("jLabel2"); // NOI18N
jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
jLabel3.setName("jLabel3"); // NOI18N
jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
jLabel4.setName("jLabel4"); // NOI18N
jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
jLabel5.setName("jLabel5"); // NOI18N
jLabel_chude.setFont(resourceMap.getFont("jLabel_chude.font")); // NOI18N
jLabel_chude.setForeground(resourceMap.getColor("jLabel_chude.foreground")); // NOI18N
jLabel_chude.setText(resourceMap.getString("jLabel_chude.text")); // NOI18N
jLabel_chude.setName("jLabel_chude"); // NOI18N
jLabel_goi.setFont(resourceMap.getFont("jLabel_goi.font")); // NOI18N
jLabel_goi.setForeground(resourceMap.getColor("jLabel_goi.foreground")); // NOI18N
jLabel_goi.setText(resourceMap.getString("jLabel_goi.text")); // NOI18N
jLabel_goi.setName("jLabel_goi"); // NOI18N
jLabel_ngay.setFont(resourceMap.getFont("jLabel_ngay.font")); // NOI18N
jLabel_ngay.setForeground(resourceMap.getColor("jLabel_ngay.foreground")); // NOI18N
jLabel_ngay.setText(resourceMap.getString("jLabel_ngay.text")); // NOI18N
jLabel_ngay.setName("jLabel_ngay"); // NOI18N
jLabel_den.setFont(resourceMap.getFont("jLabel_den.font")); // NOI18N
jLabel_den.setForeground(resourceMap.getColor("jLabel_den.foreground")); // NOI18N
jLabel_den.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel_den.setText(resourceMap.getString("jLabel_den.text")); // NOI18N
jLabel_den.setName("jLabel_den"); // NOI18N
jLabel_cc.setFont(resourceMap.getFont("jLabel_cc.font")); // NOI18N
jLabel_cc.setForeground(resourceMap.getColor("jLabel_cc.foreground")); // NOI18N
jLabel_cc.setText(resourceMap.getString("jLabel_cc.text")); // NOI18N
jLabel_cc.setName("jLabel_cc"); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
jList1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jList1.border.title"))); // NOI18N
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jList1.setName("jList1"); // NOI18N
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane2.setViewportView(jList1);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
jMenu_New.setText(resourceMap.getString("jMenu_New.text")); // NOI18N
jMenu_New.setName("jMenu_New"); // NOI18N
jMenuItem_Mail.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Mail.setText(resourceMap.getString("jMenuItem_Mail.text")); // NOI18N
jMenuItem_Mail.setName("jMenuItem_Mail"); // NOI18N
jMenu_New.add(jMenuItem_Mail);
jMenuItem_Contact.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Contact.setText(resourceMap.getString("jMenuItem_Contact.text")); // NOI18N
jMenuItem_Contact.setName("jMenuItem_Contact"); // NOI18N
jMenu_New.add(jMenuItem_Contact);
jMenuItem_Task.setText(resourceMap.getString("jMenuItem_Task.text")); // NOI18N
jMenuItem_Task.setName("jMenuItem_Task"); // NOI18N
jMenu_New.add(jMenuItem_Task);
jMenuItem_Folder.setText(resourceMap.getString("jMenuItem_Folder.text")); // NOI18N
jMenuItem_Folder.setName("jMenuItem_Folder"); // NOI18N
jMenu_New.add(jMenuItem_Folder);
fileMenu.add(jMenu_New);
jSeparator1.setName("jSeparator1"); // NOI18N
fileMenu.add(jSeparator1);
jMenuItem_Save.setText(resourceMap.getString("jMenuItem_Save.text")); // NOI18N
jMenuItem_Save.setName("jMenuItem_Save"); // NOI18N
fileMenu.add(jMenuItem_Save);
jMenuItem_SaveAs.setText(resourceMap.getString("jMenuItem_SaveAs.text")); // NOI18N
jMenuItem_SaveAs.setName("jMenuItem_SaveAs"); // NOI18N
fileMenu.add(jMenuItem_SaveAs);
jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
jMenuItem2.setName("jMenuItem2"); // NOI18N
fileMenu.add(jMenuItem2);
jSeparator5.setName("jSeparator5"); // NOI18N
fileMenu.add(jSeparator5);
jMenuItem_delete.setText(resourceMap.getString("jMenuItem_delete.text")); // NOI18N
jMenuItem_delete.setName("jMenuItem_delete"); // NOI18N
fileMenu.add(jMenuItem_delete);
jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
jMenuItem3.setName("jMenuItem3"); // NOI18N
fileMenu.add(jMenuItem3);
jSeparator2.setName("jSeparator2"); // NOI18N
fileMenu.add(jSeparator2);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanlythuyet_javaoutlook.DoAnLyThuyet_JavaOutLookApp.class).getContext().getActionMap(JFrame_ChiTietMail.class, this);
jMenuItem_Close.setAction(actionMap.get("quit")); // NOI18N
jMenuItem_Close.setText(resourceMap.getString("jMenuItem_Close.text")); // NOI18N
jMenuItem_Close.setName("jMenuItem_Close"); // NOI18N
fileMenu.add(jMenuItem_Close);
menuBar.add(fileMenu);
jMenu_Edit.setText(resourceMap.getString("jMenu_Edit.text")); // NOI18N
jMenu_Edit.setName("jMenu_Edit"); // NOI18N
jMenuItem_Cut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Cut.setText(resourceMap.getString("jMenuItem_Cut.text")); // NOI18N
jMenuItem_Cut.setName("jMenuItem_Cut"); // NOI18N
jMenu_Edit.add(jMenuItem_Cut);
jMenuItem_Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Copy.setText(resourceMap.getString("jMenuItem_Copy.text")); // NOI18N
jMenuItem_Copy.setName("jMenuItem_Copy"); // NOI18N
jMenu_Edit.add(jMenuItem_Copy);
jMenuItem_Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_Paste.setText(resourceMap.getString("jMenuItem_Paste.text")); // NOI18N
jMenuItem_Paste.setName("jMenuItem_Paste"); // NOI18N
jMenu_Edit.add(jMenuItem_Paste);
jSeparator3.setName("jSeparator3"); // NOI18N
jMenu_Edit.add(jSeparator3);
jMenuItem_SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem_SelectAll.setText(resourceMap.getString("jMenuItem_SelectAll.text")); // NOI18N
jMenuItem_SelectAll.setName("jMenuItem_SelectAll"); // NOI18N
jMenu_Edit.add(jMenuItem_SelectAll);
jSeparator4.setName("jSeparator4"); // NOI18N
jMenu_Edit.add(jSeparator4);
jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
jMenuItem1.setName("jMenuItem1"); // NOI18N
jMenu_Edit.add(jMenuItem1);
menuBar.add(jMenu_Edit);
jMenu_Tools.setText(resourceMap.getString("jMenu_Tools.text")); // NOI18N
jMenu_Tools.setName("jMenu_Tools"); // NOI18N
jMenuItem_Find.setText(resourceMap.getString("jMenuItem_Find.text")); // NOI18N
jMenuItem_Find.setName("jMenuItem_Find"); // NOI18N
jMenu_Tools.add(jMenuItem_Find);
menuBar.add(jMenu_Tools);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_den, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_ngay, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_goi, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_chude, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
.addGap(38, 38, 38))
.addComponent(jScrollPane_noidung))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel_chude))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel_goi))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel_ngay))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel_den))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel_cc)))
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane_noidung, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
// TODO add your handling code here:
if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() ==2){
try {
Object sel = jList1.getSelectedValue();
if (sel != null) {
Desktop.getDesktop().open(new File(sel.toString().split(">")[1]));
}
} catch (IOException ex) {
Logger.getLogger(JFrame_ChiTietMail.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jList1MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrame_ChiTietMail().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_Delete;
private javax.swing.JButton jButton_Reply;
private javax.swing.JButton jButton_ReplyAll;
private javax.swing.JEditorPane jEditorPane_noidung;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel_cc;
private javax.swing.JLabel jLabel_chude;
private javax.swing.JLabel jLabel_den;
private javax.swing.JLabel jLabel_goi;
private javax.swing.JLabel jLabel_ngay;
private javax.swing.JList jList1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem_Contact;
private javax.swing.JMenuItem jMenuItem_Copy;
private javax.swing.JMenuItem jMenuItem_Cut;
private javax.swing.JMenuItem jMenuItem_Find;
private javax.swing.JMenuItem jMenuItem_Folder;
private javax.swing.JMenuItem jMenuItem_Mail;
private javax.swing.JMenuItem jMenuItem_Paste;
private javax.swing.JMenuItem jMenuItem_Save;
private javax.swing.JMenuItem jMenuItem_SaveAs;
private javax.swing.JMenuItem jMenuItem_SelectAll;
private javax.swing.JMenuItem jMenuItem_Task;
private javax.swing.JMenuItem jMenuItem_delete;
private javax.swing.JMenu jMenu_Edit;
private javax.swing.JMenu jMenu_New;
private javax.swing.JMenu jMenu_Tools;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane_noidung;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JToolBar jToolBar2;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
/**
* @return the m_MailID
*/
public int getMailID() {
return m_MailID;
}
/**
* @param m_MailID the m_MailID to set
*/
public void setMailID(int mailID) {
this.m_MailID = mailID;
}
//<editor-fold defaultstate="collapsed" desc="Dung de phat sinh su kien">
//Các hàm sau phục vụ cho việc gởi sự kiện click chuột vào bảng ra ngoài (tham khảo từ nhiều nguồn trên mạng)
//http://www.exampledepot.com/egs/java.util/CustEvent.html
// Tạo một listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();
/**
* Phát sinh sử kiện click chuột vào tree
* @param evt tham số cho sự kiện click chuột vào tree (ở đây là tên của file đang được chọn)
*/
// This private class is used to fire MyEvents
void initEvent_ClickChuotVaoCayDuyetFile(String evt) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i = 0; i < listeners.length; i += 2) {
if (listeners[i] == EventListener_ClickChuotVaoCayDuyetFile.class) {
((EventListener_ClickChuotVaoCayDuyetFile) listeners[i + 1]).Event_ClickChuotVaoCayDuyetFile_Occurred(evt);
}
}
}
/**
* Đăng ký sự kiện cho classes
* @param listener Sự kiện cần đăng ký
*/
public void addEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
listenerList.add(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
}
/**
* Gỡ bỏ sự kiện khỏi classes
* @param listener Sự kiện cần gỡ bỏ
*/
public void delEventListener_ClickChuotVaoCayDuyetFile(EventListener_ClickChuotVaoCayDuyetFile listener) {
listenerList.remove(EventListener_ClickChuotVaoCayDuyetFile.class, listener);
}
//</editor-fold>
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* WelcomePanel.java
*
* Created on May 27, 2009, 9:21:30 AM
*/
package doanlythuyet_javaoutlook.usercontrol.resources;
/**
*
* @author Dang Thi Phuong Thao
*/
public class WelcomePanel extends javax.swing.JPanel {
/** Creates new form WelcomePanel */
public WelcomePanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setName("Form"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.