code
stringlengths
3
1.18M
language
stringclasses
1 value
package agent.planners; import java.util.ArrayList; import java.util.List; import java.util.Random; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import constants.Constants; import constants.Constants.dir; import datastructures.ActionSequence; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class AgentProgressionPlanner extends AgentPlanner { Level level; Random rand; private static final String name = "Planner"; public String getName() { return name; } public AgentProgressionPlanner(Level l) { this.level = l; rand = new Random(); } @Override public boolean goalABox(Agent agent, Box box, Goal goal) { // if this is not possible due to box in the way call: //agent.getHelpToMove(boxInTheWay) //reinsert the objective ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(box.getAtField()); // for (Agent tempAgent : level.agents) { // if(agent != tempAgent && agent.isNooping) blockedFields.add(agent.getAtField()); // } for (Agent tempAgent : level.agents) { if(!tempAgent.getAtField().equals(agent.getAtField())) blockedFields.add(tempAgent.getAtField()); } for (Box tempBox : level.boxes) { blockedFields.add(tempBox.getAtField()); } State newState = null; boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); if(!Utils.boxFitsGoal(box, goal))// Maybe this is the error? && (Field)goal != b.f) { // fits goal but is not the same goal as the box may be at already! continue; for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null || !blockedFields.contains(goalNeighbor)) continue; GoalActionSequence routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), goal, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } if (newState == null){ for (Agent tempAgent : level.agents) { blockedFields.remove(tempAgent.getAtField()); } for (Box tempBox : level.boxes) { blockedFields.remove(tempBox.getAtField()); } boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) moveAction = Utils.findRouteIgnoreObstacles(level, agent, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); if(!Utils.boxFitsGoal(box, goal))// Maybe this is the error? && (Field)goal != b.f) { // fits goal but is not the same goal as the box may be at already! continue; for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; GoalActionSequence routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), goal, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } if (newState == null) return false; } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } return true; } @Override public boolean move(Agent agent, List<Field> escapeFromFields, List<Field> blockedFields, int numberOfRounds) { Field toField = Utils.getFirstFreeField(agent.getAtField(), escapeFromFields, blockedFields, 20, true); if (toField == null) return false; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), toField); if (moveAction == null) return false; for (Command command : moveAction.getCommands()) { agent.commandQueue.add(command); } return true; } @Override public boolean dock(Agent agent, Box box, Field field, List<Field> fieldsToAvoid, List<Field> blockedFields, int moveTheBoxFieldsFurther, int numberOfRounds) { // We want to consider moving the box another place Field freeField = null; while(freeField == null){ freeField = Utils.getNthFreeField(box.getAtField(), fieldsToAvoid, blockedFields, moveTheBoxFieldsFurther, 15, false); moveTheBoxFieldsFurther++; } blockedFields.remove(box.getAtField()); State newState = null; boxLoop: for (dir d : dir.values()) { if(box.getAtField().neighbours[d.ordinal()] == null) continue; MoveActionSequence moveAction = null; // if(Utils.isNeighbor(box.getAtField(), agent.getAtField())){ //The following line will now find a path to adjacent boxes. if(!Utils.isNeighbor(box.getAtField(), agent.getAtField())){ moveAction = Utils.findRoute(level, agent.getAtField(), box.getAtField().neighbours[d.ordinal()], blockedFields); if (moveAction == null){ if(!Utils.isNeighbor(box.getAtField(), agent.getAtField())) continue; } } else{ moveAction = null; } // for (Field freeField : freeFields) { //System.err.println("Free field found for "+b.b.getId()+" at: " + freeField); for (dir goalNeighbourDir : dir.values()) { Field freeNeighbour = freeField.neighbours[goalNeighbourDir.ordinal()]; if (freeNeighbour == null) continue; GoalActionSequence moveBoxAction; if (moveAction == null){ moveBoxAction = Utils.findGoalRoute(level, agent, box, agent.getAtField(), freeNeighbour, box.getAtField(), freeField, blockedFields); }else{ moveBoxAction = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], freeNeighbour, box.getAtField(), freeField, blockedFields); } if (moveBoxAction == null) continue; //If we get here, we have found a route to the goal. newState = new State(); if (moveBoxAction != null) { newState = new State(); if(moveAction != null) newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(moveBoxAction); break boxLoop; } } // } } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } return true; } @Override public boolean wait(Agent agent, int numberOfRounds) { agent.isNooping = true; if (numberOfRounds>0) for(int i=0; i<numberOfRounds; i++) agent.commandQueue.add(Constants.NOOP); return true; } }
Java
package agent.planners; import java.util.List; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; public abstract class AgentPlanner { public abstract boolean goalABox(Agent agent, Box box, Goal goal); public abstract boolean move(Agent agent, List<Field> escapeFromFields, List<Field> blockedFields, int numberOfRounds); // public abstract boolean dock(Agent agent, Box box, Field field, // List<Field> blockedFields, int numberOfRounds); public abstract boolean dock(Agent agent, Box box, Field field, List<Field> fieldsToAvoid, List<Field> blockedFields, int moveTheBoxFieldsFurther, int numberOfRounds); public abstract boolean wait(Agent agent, int numberOfRounds); }
Java
package agent.objectives; import java.util.List; import LevelObjects.*; public class Move extends Objective { public List<Field> blockedFields; public int numberOfRounds; public List<Field> escapeFromFields; public Move(List<Field> escapeFromField, List<Field> blockedFields, int numberOfRounds) { super(); this.blockedFields = blockedFields; this.escapeFromFields = escapeFromField; this.numberOfRounds = numberOfRounds; } }
Java
package agent.objectives; public abstract class Objective { }
Java
package agent.objectives; import LevelObjects.*; public class GoalABox extends Objective { public GoalABox(Box b, Goal g) { goal = g; box = b; } public Goal goal; public Box box; }
Java
package agent.objectives; import java.util.List; import LevelObjects.*; public class DockABox extends Objective { public Field field; public List<Field> blockedFields; public List<Field> fieldsToAvoid; public Box box; public int numberOfRounds; public int moveTheBoxFieldsFurther; public DockABox(Field field, Box box, int numberOfRounds) { super(); this.field = field; this.box = box; this.numberOfRounds = numberOfRounds; } public DockABox(Field field, Box box, List<Field> fieldsToAvoid, List<Field> blockedFields, int moveTheBoxFieldsFurther, int numberOfRounds) { super(); this.field = field; this.box = box; this.fieldsToAvoid = fieldsToAvoid; this.blockedFields = blockedFields; this.moveTheBoxFieldsFurther = moveTheBoxFieldsFurther; this.numberOfRounds = numberOfRounds; } }
Java
package agent.objectives; import java.util.List; import LevelObjects.*; public class Wait extends Objective { public int numberOfRounds; public List<Field> blockedFields; }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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) 2010 N. 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 N. 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 boolean cachedImages; public Article() { } 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) { 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; } @Override public int compareTo(Article ai) { return ai.updated.compareTo(this.updated); } @Override public boolean equals(Object o) { if (o instanceof Article) { Article other = (Article) o; return (this.id == other.id); } else { return false; } } @Override public int hashCode() { return this.id + "".hashCode(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; 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.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 { public FeedHeadlineAdapter(Context context, int feedId) { super(context, feedId, -1, false); } public FeedHeadlineAdapter(Context context, int feedId, int categoryId, boolean selectArticlesForCategory) { super(context, feedId, categoryId, selectArticlesForCategory); } @Override public Object getItem(int position) { if (cursor.isClosed()) { makeQuery(); } Article ret = null; if (cursor.getCount() >= position) { if (cursor.moveToPosition(position)) { ret = new Article(); ret.id = cursor.getInt(0); ret.feedId = cursor.getInt(1); ret.title = cursor.getString(2); ret.isUnread = cursor.getInt(3) != 0; ret.updated = new Date(cursor.getLong(4)); ret.isStarred = cursor.getInt(5) != 0; ret.isPublished = cursor.getInt(6) != 0; } } return ret; } 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 { icon.setBackgroundDrawable(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.feedheadlineitem, null); } else { if (convertView instanceof LinearLayout) { layout = (LinearLayout) convertView; } } 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, 1); } else { title.setTypeface(Typeface.DEFAULT, 0); } TextView updateDate = (TextView) layout.findViewById(R.id.updateDate); String date = DateUtils.getDateTime(context, a.updated); updateDate.setText(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; } protected Cursor executeQuery(boolean overrideDisplayUnread, boolean buildSafeQuery, boolean forceRefresh) { long currentChangedTime = Data.getInstance().getArticlesChanged(feedId); boolean refresh = buildSafeQuery || forceRefresh || (currentChangedTime == -1 && changedTime != -1); if (refresh) { // Create query, currentChangedTime is not initialized or safeQuery requested or forceRefresh requested. } else if (cursor != null && !cursor.isClosed() && changedTime >= currentChangedTime) { // Log.d(Utils.TAG, "FeedHeadline currentChangedTime: " + currentChangedTime + " changedTime: " + // changedTime); return cursor; } String query; if (feedId > -10) query = buildFeedQuery(overrideDisplayUnread, buildSafeQuery); else query = buildLabelQuery(overrideDisplayUnread, buildSafeQuery); closeCursor(); Cursor c = DBHelper.getInstance().query(query, null); changedTime = Data.getInstance().getArticlesChanged(feedId); // Re-fetch changedTime since it can have changed // by now return c; } private String buildFeedQuery(boolean overrideDisplayUnread, boolean buildSafeQuery) { Integer lastOpenedArticle = Controller.getInstance().lastOpenedArticle; boolean displayUnread = displayOnlyUnread; if (overrideDisplayUnread) displayUnread = false; StringBuilder query = new StringBuilder(); query.append("SELECT a.id,feedId,a.title,isUnread AS unread,updateDate,isStarred,isPublished FROM "); query.append(DBHelper.TABLE_ARTICLES); query.append(" a, "); query.append(DBHelper.TABLE_FEEDS); query.append(" b WHERE feedId=b.id"); switch (feedId) { case Data.VCAT_STAR: query.append(" AND isStarred=1"); break; case Data.VCAT_PUB: query.append(" AND isPublished=1"); break; case Data.VCAT_FRESH: query.append(" AND updateDate>"); query.append(Controller.getInstance().getFreshArticleMaxAge()); query.append(" AND isUnread>0"); break; case Data.VCAT_ALL: query.append(displayUnread ? " AND isUnread>0" : ""); break; default: // User selected to display all articles of a category directly query.append(selectArticlesForCategory ? (" AND categoryId=" + categoryId) : (" AND feedId=" + feedId)); query.append(displayUnread ? " AND isUnread>0" : ""); } if (lastOpenedArticle != null && !buildSafeQuery) { query.append(" UNION SELECT c.id,feedId,c.title,isUnread AS unread,updateDate,isStarred,isPublished FROM "); query.append(DBHelper.TABLE_ARTICLES); query.append(" c, feeds d WHERE feedId=d.id AND c.id="); query.append(lastOpenedArticle); } query.append(" ORDER BY updateDate "); query.append(invertSortArticles ? "ASC" : "DESC"); return query.toString(); } private String buildLabelQuery(boolean overrideDisplayUnread, boolean buildSafeQuery) { Integer lastOpenedArticle = Controller.getInstance().lastOpenedArticle; boolean displayUnread = displayOnlyUnread; if (overrideDisplayUnread) displayUnread = false; StringBuilder query = new StringBuilder(); query.append("SELECT a.id,feedId,a.title,isUnread AS unread,updateDate,isStarred,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 (lastOpenedArticle != null && !buildSafeQuery) { query.append(" UNION SELECT b.id,feedId,b.title,isUnread AS unread,updateDate,isStarred,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=" + lastOpenedArticle); } query.append(" ORDER BY updateDate "); query.append(invertSortArticles ? "ASC" : "DESC"); return query.toString(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; 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 { public FeedAdapter(Context context, int categoryId) { super(context, categoryId); } @Override public Object getItem(int position) { if (cursor.isClosed()) { makeQuery(); } Feed ret = null; if (cursor.getCount() >= position) { if (cursor.moveToPosition(position)) { ret = new Feed(); ret.id = cursor.getInt(0); ret.title = cursor.getString(1); ret.unread = cursor.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.feeditem, null); } else { if (convertView instanceof LinearLayout) { layout = (LinearLayout) convertView; } } ImageView icon = (ImageView) layout.findViewById(R.id.icon); icon.setImageResource(getImage(f.unread > 0)); TextView title = (TextView) layout.findViewById(R.id.title); title.setText(formatTitle(f.title, f.unread)); if (f.unread > 0) { title.setTypeface(Typeface.DEFAULT_BOLD, 1); } else { title.setTypeface(Typeface.DEFAULT, 0); } return layout; } protected Cursor executeQuery(boolean overrideDisplayUnread, boolean buildSafeQuery, boolean forceRefresh) { long currentChangedTime = Data.getInstance().getFeedsChanged(categoryId); boolean refresh = buildSafeQuery || forceRefresh || (currentChangedTime == -1 && changedTime != -1); if (refresh) { // Create query, currentChangedTime is not initialized or safeQuery requested or forceRefresh requested. } else if (cursor != null && !cursor.isClosed() && changedTime >= currentChangedTime) { // Log.d(Utils.TAG, "Feed currentChangedTime: " + currentChangedTime + " changedTime: " + changedTime); return cursor; } StringBuilder query = new StringBuilder(); Integer lastOpenedFeed = Controller.getInstance().lastOpenedFeed; boolean displayUnread = displayOnlyUnread; if (overrideDisplayUnread) displayUnread = false; if (lastOpenedFeed != null && !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 (lastOpenedFeed != null && !buildSafeQuery) { query.append(" UNION SELECT id,title,unread"); query.append(" FROM feeds WHERE id="); query.append(lastOpenedFeed); query.append(")"); } query.append(" ORDER BY UPPER(title) "); query.append(invertSortFeedCats ? "DESC" : "ASC"); query.append(buildSafeQuery ? " LIMIT 200" : " LIMIT 1000"); closeCursor(); Cursor c = DBHelper.getInstance().query(query.toString(), null); changedTime = Data.getInstance().getFeedsChanged(categoryId); // Re-fetch changedTime since it can have changed // by now return c; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.Date; import java.util.HashSet; import java.util.Set; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; public class ReadStateUpdater implements IUpdatable { private int pid = 0; private int articleState; private Collection<Category> categories = null; private Collection<Feed> feeds = null; private Collection<Article> articles = null; public ReadStateUpdater(Collection<Category> collection) { this.categories = new HashSet<Category>(collection); } public ReadStateUpdater(int categoryId) { this.categories = new HashSet<Category>(); Category ci = DBHelper.getInstance().getCategory(categoryId); if (ci != null) { this.categories.add(ci); } } public ReadStateUpdater(int feedId, int dummy) { if (feedId <= 0 && feedId >= -4) { // Virtual Category... this.categories = new HashSet<Category>(); Category ci = DBHelper.getInstance().getCategory(feedId); if (ci != null) this.categories.add(ci); } else { this.feeds = new HashSet<Feed>(); Feed fi = DBHelper.getInstance().getFeed(feedId); if (fi != null) this.feeds.add(fi); } } /* articleState: 0 = mark as read, 1 = mark as unread */ public ReadStateUpdater(Article article, int pid, int articleState) { this.articles = new ArrayList<Article>(); this.articles.add(article); this.pid = pid; this.articleState = articleState; } @Override public void update(Updater parent) { if (categories != null) { for (Category ci : categories) { DBHelper.getInstance().markCategoryRead(ci.id); Data.getInstance().setCategoriesChanged(System.currentTimeMillis()); } parent.progress(); 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); } } } else if (feeds != null) { for (Feed fi : feeds) { DBHelper.getInstance().markFeedRead(fi.id); Data.getInstance().setFeedsChanged(fi.categoryId, System.currentTimeMillis()); } parent.progress(); for (Feed fi : feeds) { Data.getInstance().setRead(fi.id, false); } } else if (articles != null) { boolean boolState = articleState == 1 ? true : false; int delta = articleState == 1 ? 1 : -1; Set<Integer> ids = new HashSet<Integer>(); for (Article article : articles) { // Don't check this, sometimes we need to set the state of the object at once before we call this // updater. // if (articleState != 0 && article.isUnread) // continue; // if (articleState == 0 && !article.isUnread) // continue; // Build a list of article ids to update. ids.add(article.id); // Set ArticleItem-State directly because the Activity uses this object article.isUnread = boolState; int feedId = article.feedId; Feed mFeed = DBHelper.getInstance().getFeed(feedId); int categoryId = mFeed.categoryId; DBHelper.getInstance().updateFeedDeltaUnreadCount(feedId, delta); DBHelper.getInstance().updateCategoryDeltaUnreadCount(categoryId, delta); // Check if is a fresh article and modify that count too long ms = System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge(); Date maxAge = new Date(ms); if (article.updated.after(maxAge)) DBHelper.getInstance().updateCategoryDeltaUnreadCount(Data.VCAT_FRESH, delta); // Check if it is a starred article and modify that count too if (article.isStarred && pid != Data.VCAT_STAR) DBHelper.getInstance().updateCategoryDeltaUnreadCount(Data.VCAT_STAR, delta); // Check if it is a published article and modify that count too if (article.isPublished && pid != Data.VCAT_PUB) DBHelper.getInstance().updateCategoryDeltaUnreadCount(Data.VCAT_PUB, delta); // Mark all categories and feeds as "changed" since the counters were changed here Data.getInstance().setArticlesChanged(feedId, System.currentTimeMillis()); Data.getInstance().setFeedsChanged(categoryId, System.currentTimeMillis()); Data.getInstance().setCategoriesChanged(System.currentTimeMillis()); } if (ids.size() > 0) { DBHelper.getInstance().markArticles(ids, "isUnread", articleState); Data.getInstance().setArticlesChanged(pid, System.currentTimeMillis()); int deltaUnread = articleState == 1 ? ids.size() : -ids.size(); DBHelper.getInstance().updateCategoryDeltaUnreadCount(Data.VCAT_ALL, deltaUnread); if (pid < 0 && pid >= -3) { // If on a virtual category also update article state in it. DBHelper.getInstance().updateCategoryDeltaUnreadCount(pid, deltaUnread); } else if (pid < -10) { // Article belongs to a label, modify that count too DBHelper.getInstance().updateFeedDeltaUnreadCount(pid, deltaUnread); } parent.progress(); Data.getInstance().setArticleRead(ids, articleState); } Data.getInstance().updateCounters(false); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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 N. 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.model.pojos.Article; public class StarredStateUpdater implements IUpdatable { 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); Data.getInstance().setArticlesChanged(article.feedId, System.currentTimeMillis()); parent.progress(); Data.getInstance().setArticleStarred(article.id, articleState); } else { // Does it make any sense to toggle the state on the server? Set newState to 2 for toggle. int star = article.isStarred ? 0 : 1; article.isStarred = !article.isStarred; DBHelper.getInstance().markArticle(article.id, "isStarred", star); Data.getInstance().setArticlesChanged(article.feedId, System.currentTimeMillis()); parent.progress(); Data.getInstance().setArticleStarred(article.id, star); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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; import org.ttrssreader.controllers.NotInitializedException; import org.ttrssreader.utils.Utils; import android.util.Log; public class StateSynchronisationUpdater implements IUpdatable { @Override public void update(Updater parent) { Log.i(Utils.TAG, "Reader went online, now synchronizing status of articles..."); try { Data.getInstance().synchronizeStatus(); } catch (NotInitializedException e) { return; } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.interfaces.IUpdateEndListener; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; public class Updater extends AsyncTask<Void, Void, Void> { private static final int END = 0; private static final int PROGRESS = 1; private IUpdateEndListener parent; private IUpdatable updatable; public Updater(IUpdateEndListener parent, IUpdatable updatable) { this.parent = parent; this.updatable = updatable; } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (parent != null) { if (msg.what == END) parent.onUpdateEnd(); if (msg.what == PROGRESS) parent.onUpdateProgress(); } } }; @Override protected Void doInBackground(Void... params) { updatable.update(this); handler.sendEmptyMessage(END); return null; } public void progress() { handler.sendEmptyMessage(PROGRESS); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.model.pojos.Article; public class PublishedStateUpdater implements IUpdatable { 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); Data.getInstance().setArticlesChanged(article.feedId, System.currentTimeMillis()); parent.progress(); Data.getInstance().setArticlePublished(article.id, articleState, note); } else { // Does it make any sense to toggle the state on the server? Set newState to 2 for toggle. int pub = article.isPublished ? 0 : 1; article.isPublished = !article.isPublished; DBHelper.getInstance().markArticle(article.id, "isPublished", pub); Data.getInstance().setArticlesChanged(article.feedId, System.currentTimeMillis()); parent.progress(); Data.getInstance().setArticlePublished(article.id, pub, note); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.controllers.Controller; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public abstract class MainAdapter extends BaseAdapter { protected Context context; protected Cursor cursor; protected boolean displayOnlyUnread; protected boolean invertSortFeedCats; protected boolean invertSortArticles; protected int categoryId; protected int feedId; protected long changedTime; protected boolean selectArticlesForCategory; public MainAdapter() { this.displayOnlyUnread = Controller.getInstance().onlyUnread(); this.invertSortFeedCats = Controller.getInstance().invertSortFeedscats(); this.invertSortArticles = Controller.getInstance().invertSortArticlelist(); } public MainAdapter(Context context) { this(); this.context = context; makeQuery(); } public MainAdapter(Context context, int categoryId) { this(); this.context = context; this.categoryId = categoryId; makeQuery(); } public MainAdapter(Context context, int feedId, int categoryId, boolean selectArticlesForCategory) { this(); this.context = context; this.feedId = feedId; this.categoryId = categoryId; this.selectArticlesForCategory = selectArticlesForCategory; makeQuery(); } public final void closeCursor() { if (cursor == null) return; synchronized (cursor) { if (cursor == null) return; // Catch all SQLiteExceptions to make sure no "unable to close due to unfinalised statements" errors arise try { cursor.close(); } catch (SQLiteException e) { } } } @Override public final int getCount() { synchronized (cursor) { if (cursor.isClosed()) makeQuery(); return cursor.getCount(); } } @Override public final long getItemId(int position) { return position; } public final int getId(int position) { int ret = 0; synchronized (cursor) { if (cursor.isClosed()) makeQuery(); if (cursor.getCount() >= position) if (cursor.moveToPosition(position)) ret = cursor.getInt(0); } return ret; } public final List<Integer> getIds() { List<Integer> result = new ArrayList<Integer>(); synchronized (cursor) { if (cursor.isClosed()) makeQuery(); if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { result.add(cursor.getInt(0)); cursor.move(1); } } } return result; } public final String getTitle(int position) { String ret = ""; synchronized (cursor) { if (cursor.isClosed()) makeQuery(); if (cursor.getCount() >= position) if (cursor.moveToPosition(position)) ret = cursor.getString(1); } return ret; } public static final String formatTitle(String title, int unread) { if (unread > 0) { return title + " (" + unread + ")"; } else { return title; } } public final synchronized void makeQuery() { makeQuery(false); } /** * Only refresh if forceRefresh is true (called from constructor) or one of the display-attributes changed. * * @param forceRefresh * Discards the current cursor and forces a refresh, including a newly built SQL-Query. */ public final synchronized void makeQuery(boolean forceRefresh) { boolean refresh = false || forceRefresh; // Check if display-settings have changed if (displayOnlyUnread != Controller.getInstance().onlyUnread()) { refresh = true; displayOnlyUnread = !displayOnlyUnread; } if (invertSortFeedCats != Controller.getInstance().invertSortFeedscats()) { refresh = true; invertSortFeedCats = !invertSortFeedCats; } if (invertSortArticles != Controller.getInstance().invertSortArticlelist()) { refresh = true; invertSortArticles = !invertSortArticles; } // if: sort-order or display-settings changed // if: forced by explicit call with forceRefresh // if: cursor is closed or null if (refresh || (cursor != null && cursor.isClosed()) || cursor == null) { // if (cursor != null) // Not necessary, child can close it if it issues a new query. // closeCursor(); try { cursor = executeQuery(false, false, refresh); // normal query if (!checkUnread(cursor)) cursor = executeQuery(true, false, true); // Override unread if query was empty } catch (Exception e) { cursor = executeQuery(false, true, refresh); // Fail-safe-query } } else if (cursor != null) { cursor.requery(); } } /** * Tries to find out if the given cursor points to a dataset with unread articles in it, returns true if it does. * * @param c * the cursor. * @return true if there are unread articles in the dataset, else false. */ private final boolean checkUnread(Cursor c) { if (c == null || c.isClosed()) return true; // TODO: Check for concurrency-issues here, to avoid anything strange this should return false. boolean gotUnread = false; if (c.moveToFirst()) { int col = c.getColumnIndex("unread"); if (col > -1) { while (!c.isAfterLast()) { int unread = c.getInt(col); if (unread > 0) { gotUnread = true; break; } c.move(1); } } } c.moveToFirst(); return gotUnread; } @Override public abstract Object getItem(int position); @Override public abstract View getView(int position, View convertView, ViewGroup parent); /** * Builds the query for this adapter as a string and returns it to be invoked on a database object. * * @param overrideDisplayUnread * if true unread articles/feeds/anything won't be filtered as specified by the setting but will be * included in the result. * @param buildSafeQuery * indicates that the query should modified to also display unread content even though displayUnread is * disabled, this is used to get a new query when the current query is empty. * @param forceRefresh * this indicates that a refresh of the cursor should be forced. * @return a valid SQL-Query string for this adapter. */ protected abstract Cursor executeQuery(boolean overrideDisplayUnread, boolean buildSafeQuery, boolean forceRefresh); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Category; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; 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 { public CategoryAdapter(Context context) { super(context); } @Override public Object getItem(int position) { if (cursor.isClosed()) { makeQuery(); } if (cursor.getCount() >= position) { if (cursor.moveToPosition(position)) { Category ret = new Category(); ret.id = cursor.getInt(0); ret.title = cursor.getString(1); ret.unread = cursor.getInt(2); return ret; } } return null; } public List<Category> getCategories() { if (cursor.isClosed()) { makeQuery(); } List<Category> result = new ArrayList<Category>(); if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { Category c = new Category(); c.id = cursor.getInt(0); c.title = cursor.getString(1); c.unread = cursor.getInt(2); result.add(c); cursor.move(1); } } return result; } 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.categoryitem, null); } else { if (convertView instanceof LinearLayout) { layout = (LinearLayout) convertView; } } 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(formatTitle(c.title, c.unread)); if (c.unread > 0) { title.setTypeface(Typeface.DEFAULT_BOLD, 1); } else { title.setTypeface(Typeface.DEFAULT, 0); } return layout; } protected synchronized Cursor executeQuery(boolean overrideDisplayUnread, boolean buildSafeQuery, boolean forceRefresh) { long currentChangedTime = Data.getInstance().getCategoriesChanged(); boolean refresh = buildSafeQuery || forceRefresh || (currentChangedTime == -1 && changedTime != -1); if (refresh) { // Create query, currentChangedTime is not initialized or safeQuery requested or forceRefresh requested. } else if (cursor != null && !cursor.isClosed() && changedTime >= currentChangedTime) { // Log.d(Utils.TAG, "Category currentChangedTime: " + currentChangedTime + " changedTime: " + changedTime); return cursor; } boolean displayUnread = displayOnlyUnread; if (overrideDisplayUnread) displayUnread = false; if (db != null) db.close(); OpenHelper openHelper = new OpenHelper(context); db = openHelper.getWritableDatabase(); insert = db.compileStatement(INSERT); 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(DBHelper.getInstance().query(query.toString(), null)); } // 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"); insertValues(DBHelper.getInstance().query(query.toString(), null)); // "Uncategorized Feeds" 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" : ""); insertValues(DBHelper.getInstance().query(query.toString(), null)); // 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"); insertValues(DBHelper.getInstance().query(query.toString(), null)); closeCursor(); String[] columns = { "id", "title", "unread" }; Cursor c = db.query(TABLE_NAME, columns, null, null, null, null, "sortId " + (invertSortFeedCats ? "DESC" : "ASC")); changedTime = Data.getInstance().getCategoriesChanged(); // Re-fetch changedTime since it can have changed by // now return c; } /* * 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 TABLE_NAME = "categories_memory_db"; private static final String INSERT = "REPLACE INTO " + TABLE_NAME + "(id, title, unread, sortId) VALUES (?, ?, ?, null)"; private SQLiteDatabase db; private SQLiteStatement insert; private static class OpenHelper extends SQLiteOpenHelper { OpenHelper(Context context) { super(context, null, null, 1); } /** * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) */ @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) { } } private void insertValues(Cursor c) { 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; } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.imageCache; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.utils.FileDateComparator; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.content.Context; import android.database.Cursor; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.util.Log; public class ImageCacher extends AsyncTask<Void, Integer, Void> { private static final long maxFileSize = 1024 * 1024 * 6; // Max size for one image is 6 MB private static final int DOWNLOAD_IMAGES_THREADS = 4; private static final int DEFAULT_TASK_COUNT = 3; private ICacheEndListener parent; private Context context; private boolean onlyArticles; private boolean onlyUnreadImages; private long cacheSizeMax; private ImageCache imageCache; private long folderSize; private long downloaded = 0; private int taskCount = 0; public ImageCacher(ICacheEndListener parent, Context context, boolean onlyArticles) { this.parent = parent; this.context = context; this.onlyArticles = onlyArticles; } @Override protected Void doInBackground(Void... params) { long start = System.currentTimeMillis(); while (true) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (!Utils.checkConnected(cm)) { Log.e(Utils.TAG, "Error: No connectivity, aborting..."); break; } // Update all articles long timeArticles = System.currentTimeMillis(); // Only use progress-updates and callbacks for downloading articles, images are done in background // completely Set<Feed> labels = DBHelper.getInstance().getFeeds(-2); taskCount = DEFAULT_TASK_COUNT + labels.size() + 1; // 1 for the caching of all articles int progress = 0; Data.getInstance().updateCounters(true); publishProgress(++progress); // Move progress forward Data.getInstance().updateCategories(true); publishProgress(++progress); // Move progress forward Data.getInstance().updateFeeds(Data.VCAT_ALL, true); // Cache all articles publishProgress(++progress); Data.getInstance().cacheArticles(false); for (Feed f : labels) { if (f.unread == 0) continue; publishProgress(++progress); // Move progress forward Data.getInstance().updateArticles(f.id, true, false, false); } publishProgress(taskCount); // Move progress forward Log.i(Utils.TAG, "Updating articles took " + (System.currentTimeMillis() - timeArticles) + "ms"); if (onlyArticles) // We are done here.. break; // Initialize other preferences this.cacheSizeMax = Controller.getInstance().getImageCacheSize() * 1048576; this.onlyUnreadImages = Controller.getInstance().isImageCacheUnread(); this.imageCache = Controller.getInstance().getImageCache(context); if (imageCache == null) break; imageCache.fillMemoryCacheFromDisk(); downloadImages(); purgeCache(); Log.i(Utils.TAG, String.format("Cache: %s MB (Limit: %s MB, took %s seconds)", folderSize / 1048576, cacheSizeMax / 1048576, (System.currentTimeMillis() - start) / 1000)); break; // Always break in the end, "while" is just useful for the different places in which we leave the // loop } handler.sendEmptyMessage(0); return null; } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (parent != null) parent.onCacheEnd(); } }; @Override protected void onProgressUpdate(Integer... values) { if (parent != null) parent.onCacheProgress(taskCount, values[0]); } private void downloadImages() { long time = System.currentTimeMillis(); DownloadImageTask[] tasks = new DownloadImageTask[DOWNLOAD_IMAGES_THREADS]; Cursor c = DBHelper.getInstance().queryArticlesForImageCache(onlyUnreadImages); if (c.moveToFirst()) { while (!c.isAfterLast()) { // Get images included in HTML Set<String> set = new HashSet<String>(); for (String url : findAllImageUrls(c.getString(1), c.getInt(0))) { if (!imageCache.containsKey(url)) set.add(url); } // Get images from attachments separately for (String url : c.getString(2).split(";")) { for (String ext : FileUtils.IMAGE_EXTENSIONS) { if (url.toLowerCase().contains("." + ext) && !imageCache.containsKey(url)) { set.add(url); break; } } } assignTask(tasks, c.getInt(0), StringSupport.setToArray(set)); if (downloaded > cacheSizeMax) { Log.w(Utils.TAG, "Stopping download, downloaded data exceeds cache-size-limit from options."); break; } c.move(1); } } c.close(); // Wait for all tasks to finish and retrieve results boolean tasksRunning = true; while (tasksRunning) { tasksRunning = false; synchronized (this) { try { wait(200); } catch (InterruptedException e) { } } for (int i = 0; i < DOWNLOAD_IMAGES_THREADS; i++) { DownloadImageTask t = tasks[i]; retrieveResult(t); if (t != null && t.getStatus().equals(AsyncTask.Status.RUNNING)) { tasksRunning = true; } } } Log.i(Utils.TAG, "Downloading images took " + (System.currentTimeMillis() - time) + "ms"); } private void purgeCache() { long time = System.currentTimeMillis(); File cacheFolder = new File(imageCache.getDiskCacheDirectory()); folderSize = 0; if (cacheFolder.listFiles() != null) { for (File f : cacheFolder.listFiles()) { folderSize += f.length(); } } if (folderSize > cacheSizeMax) { // Log.i(Utils.TAG, String.format("Before - Cache: %s bytes (Limit: %s bytes)", folderSize, cacheSizeMax)); // Sort list of files by last access date List<File> list = Arrays.asList(cacheFolder.listFiles()); Collections.sort(list, new FileDateComparator()); int i = 0; while (folderSize > cacheSizeMax) { File f = list.get(i++); folderSize -= f.length(); f.delete(); } // Log.i(Utils.TAG, String.format("After - Cache: %s bytes (Limit: %s bytes)", folderSize, cacheSizeMax)); } Log.i(Utils.TAG, "Purging cache took " + (System.currentTimeMillis() - time) + "ms"); } /** * Returns true if all downloads for this Task have been successful. * * @param t * @return */ private boolean retrieveResult(DownloadImageTask t) { boolean ret = false; if (t != null && t.getStatus().equals(AsyncTask.Status.FINISHED)) { try { downloaded += t.get(); if (t.allOK) ret = true; t = null; // Make sure tasks[i] is null } catch (Exception e) { e.printStackTrace(); } } return ret; } private void assignTask(DownloadImageTask[] tasks, int articleId, String... urls) { if (urls.length == 0) return; if (tasks == null) tasks = new DownloadImageTask[DOWNLOAD_IMAGES_THREADS]; boolean done = false; while (!done) { // Start new Task if task-slot is available for (int i = 0; i < DOWNLOAD_IMAGES_THREADS; i++) { DownloadImageTask t = tasks[i]; // Retrieve result (downloaded size) and reset task if (retrieveResult(t)) DBHelper.getInstance().updateArticleCachedImages(articleId, true); // Assign new task if possible if (t == null || t.getStatus().equals(AsyncTask.Status.FINISHED)) { t = new DownloadImageTask(imageCache, maxFileSize); t.execute(urls); tasks[i] = t; done = true; break; } } if (!done) { // No task-slot available, wait. synchronized (this) { try { wait(100); } catch (InterruptedException e) { } } } } } /** * Searches for cached versions of the given image and returns the local URL to access the file. * * @param url * the original URL * @return the local URL or null if no image in cache or if the file couldn't be found. */ public static String getCachedImageUrl(String url) { ImageCache cache = Controller.getInstance().getImageCache(null); if (cache != null && cache.containsKey(url)) { StringBuffer sb = new StringBuffer(); sb.append(cache.getDiskCacheDirectory()); sb.append(File.separator); sb.append(cache.getFileNameForKey(url)); File file = new File(sb.toString()); if (file.exists()) { sb.insert(0, "file://"); // Add "file:" at the beginning.. return sb.toString(); } else { Log.w(Utils.TAG, "File " + sb.toString() + " is in cache but does not exist."); } } return null; } /** * Searches the given html code for img-Tags and filters out all src-attributes, beeing URLs to images. * * @param html * the html code which is to be searched * @return a set of URLs in their string representation */ public static Set<String> findAllImageUrls(String html, int articleId) { Set<String> ret = new LinkedHashSet<String>(); if (html == null || html.length() < 10) return ret; for (int i = 0; i < html.length();) { i = html.indexOf("<img", i); if (i == -1) break; Matcher m = Utils.findImageUrlsPattern.matcher(html.substring(i, html.length())); // Filter out URLs without leading http, we cannot work with relative URLs yet. boolean found = m.find(); if (found && m.group(1).startsWith("http")) { ret.add(m.group(1)); i += m.group(1).length(); } else if (found) { i++; continue; } else { i++; continue; } // Log.i(Utils.TAG, ret.size() + " URL" + (ret.size() == 1 ? "" : "s") +" found for Article-ID " + articleId // + "."); } return ret; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.imageCache; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.utils.Utils; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class ForegroundService extends Service implements ICacheEndListener { private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class }; private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class, Notification.class }; private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class }; private NotificationManager mNM; private Method mSetForeground; private Method mStartForeground; private Method mStopForeground; private Object[] mSetForegroundArgs = new Object[1]; private Object[] mStartForegroundArgs = new Object[2]; private Object[] mStopForegroundArgs = new Object[1]; public static final String ACTION_LOAD_IMAGES = "load_images"; public static final String ACTION_LOAD_ARTICLES = "load_articles"; private ImageCacher imageCacher; private static ForegroundService instance = null; private static ICacheEndListener parent; public static boolean isInstanceCreated() { return instance != null; } private boolean imageCache = false; public static void loadImagesToo() { if (instance != null) instance.imageCache = true; } public static void registerCallback(ICacheEndListener parentGUI) { parent = parentGUI; } void invokeMethod(Method method, Object[] args) { try { method.invoke(this, mStartForegroundArgs); } catch (InvocationTargetException e) { // Should not happen. Log.e(Utils.TAG, "Unable to invoke method", e); } catch (IllegalAccessException e) { // Should not happen. Log.e(Utils.TAG, "Unable to invoke method", e); } } /** * This is a wrapper around the new startForeground method, using the older * APIs if it is not available. */ void startForegroundCompat(int id, Notification notification) { // If we have the new startForeground API, then use it. if (mStartForeground != null) { mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; invokeMethod(mStartForeground, mStartForegroundArgs); return; } // Fall back on the old API. mSetForegroundArgs[0] = Boolean.TRUE; invokeMethod(mSetForeground, mSetForegroundArgs); mNM.notify(id, notification); } /** * This is a wrapper around the new stopForeground method, using the older * APIs if it is not available. */ void stopForegroundCompat(int id) { // If we have the new stopForeground API, then use it. if (mStopForeground != null) { mStopForegroundArgs[0] = Boolean.TRUE; try { mStopForeground.invoke(this, mStopForegroundArgs); } catch (InvocationTargetException e) { // Should not happen. Log.e(Utils.TAG, "Unable to invoke stopForeground", e); } catch (IllegalAccessException e) { // Should not happen. Log.e(Utils.TAG, "Unable to invoke stopForeground", e); } return; } // Fall back on the old API. Note to cancel BEFORE changing the // foreground state, since we could be killed at that point. mNM.cancel(id); mSetForegroundArgs[0] = Boolean.FALSE; invokeMethod(mSetForeground, mSetForegroundArgs); } @Override public void onCreate() { instance = this; mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); } catch (NoSuchMethodException e) { // Running on an older platform. mStartForeground = mStopForeground = null; return; } try { mSetForeground = getClass().getMethod("setForeground", mSetForegroundSignature); } catch (NoSuchMethodException e) { throw new IllegalStateException("OS doesn't have Service.startForeground OR Service.setForeground!"); } } @Override public void onDestroy() { finishService(); } /** * Cleans up all running notifications, notifies waiting activities and clears the instance of the service. */ public void finishService() { if (instance != null) { // Remove the notification stopForegroundCompat(R.string.Cache_service_started); // Call all activities Controller.getInstance().notifyActivities(); // Reset Instance instance = null; } } // This is the old onStart method that will be called on the pre-2.0 // platform. On 2.0 or later we override onStartCommand() so this // method will not be called. @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } void handleCommand(Intent intent) { // Fail-safe if (intent == null || intent.getAction() == null) return; int icon = R.drawable.notification_icon; CharSequence title = ""; CharSequence ticker = getText(R.string.Cache_service_started); CharSequence text = getText(R.string.Cache_service_text); if (ACTION_LOAD_IMAGES.equals(intent.getAction())) { imageCacher = new ImageCacher(this, this, false); imageCacher.execute(); title = getText(R.string.Cache_service_imagecache); } else if (ACTION_LOAD_ARTICLES.equals(intent.getAction())) { imageCacher = new ImageCacher(this, this, true); imageCacher.execute(); title = getText(R.string.Cache_service_articlecache); } // Display notification Notification notification = new Notification(icon, ticker, System.currentTimeMillis()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0); notification.setLatestEventInfo(this, title, text, pendingIntent); startForegroundCompat(R.string.Cache_service_started, notification); } @Override public void onCacheEnd() { // Start a new cacher if images have been requested if (imageCache) { imageCache = false; imageCacher = new ImageCacher(this, this, false); imageCacher.execute(); } else { finishService(); this.stopSelf(); } } @Override public void onCacheProgress(int taskCount, int progress) { if (parent != null) parent.onCacheProgress(taskCount, progress); } @Override public IBinder onBind(Intent intent) { return null; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.imageCache; import org.ttrssreader.utils.FileUtils; import android.os.AsyncTask; public class DownloadImageTask extends AsyncTask<String, Void, Long> { private ImageCache imageCache; private long maxFileSize; public boolean allOK = true; public DownloadImageTask(ImageCache cache, long maxFileSize) { this.imageCache = cache; this.maxFileSize = maxFileSize; } @Override protected Long doInBackground(String... params) { long downloaded = 0; for (String url : params) { long size = FileUtils.downloadToFile(url, imageCache.getCacheFile(url), maxFileSize); if (size == -1) { allOK = false; // Error } else { downloaded += size; } } return downloaded; } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler * Modified 2010 by Nils Braden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.imageCache; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import org.ttrssreader.controllers.Controller; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.AbstractCache; import org.ttrssreader.utils.Utils; import android.graphics.Bitmap; import android.os.Environment; import android.util.Log; /** * Implements a cache capable of caching image files. It exposes helper methods to immediately * access binary image data as {@link Bitmap} objects. * * @author Matthias Kaeppler * @author Nils Braden (modified some stuff) */ public class ImageCache extends AbstractCache<String, byte[]> { public ImageCache(int initialCapacity) { super("ImageCache", initialCapacity, 1); } /** * Enable caching to the phone's SD card. * * @param context * the current context * @return */ public boolean enableDiskCache() { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // Use configured output directory diskCacheDir = Controller.getInstance().cacheFolder(); File folder = new File(diskCacheDir); if (!folder.exists()) { if (!folder.mkdirs()) { // Folder could not be created, fallback to internal directory on sdcard // Path: /sdcard/Android/data/org.ttrssreader/cache/ diskCacheDir = Constants.CACHE_FOLDER_DEFAULT; folder = new File(diskCacheDir); } } if (!folder.exists()) folder.mkdirs(); isDiskCacheEnabled = folder.exists(); // Create .nomedia File in Cache-Folder so android doesn't generate thumbnails File nomediaFile = new File(diskCacheDir + File.separator + ".nomedia"); if (!nomediaFile.exists()) { try { nomediaFile.createNewFile(); } catch (IOException e) { } } } if (!isDiskCacheEnabled) Log.e(Utils.TAG, "Failed creating disk cache directory " + diskCacheDir); return isDiskCacheEnabled; } public void fillMemoryCacheFromDisk() { byte[] b = new byte[] {}; File folder = new File(diskCacheDir); File[] files = folder.listFiles(); if (files == null) return; for (File file : files) { cache.put(file.getName(), b); } } public boolean containsKey(String key) { if (cache.containsKey(getFileNameForKey(key))) return true; return (isDiskCacheEnabled && getCacheFile((String) key).exists()); } @Override public String getFileNameForKey(String imageUrl) { return imageUrl.replaceAll("[:;#~%$\"!<>|+*\\()^/,%?&=]", "+").replaceAll("[+]+", "+"); } public File getCacheFile(String key) { File f = new File(diskCacheDir); if (!f.exists()) f.mkdirs(); return new File(diskCacheDir + "/" + getFileNameForKey(key)); } @Override protected byte[] readValueFromDisk(File file) throws IOException { return null; } @Override protected void writeValueToDisk(BufferedOutputStream ostream, byte[] value) throws IOException { } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.interfaces; public interface IUpdateEndListener { public void onUpdateEnd(); public void onUpdateProgress(); }
Java
package org.ttrssreader.gui.interfaces; import org.ttrssreader.model.pojos.Article; public interface TextInputAlertCallback { public void onPublishNoteResult(Article a, String note); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.interfaces; public interface IItemSelectedListener { enum TYPE { CATEGORY, FEED, FEEDHEADLINE, NONE } public void itemSelected(TYPE type, int selectedIndex, int oldIndex); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.interfaces; import org.ttrssreader.model.MainAdapter; public interface IConfigurable { public void setAdapter(MainAdapter adapter); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.interfaces; public interface ICacheEndListener { public void onCacheEnd(); public void onCacheProgress(int taskCount, int progress); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. Braden. * Copyright (C) 2010 F. Bechstein. * 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.gui; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.NotInitializedException; import org.ttrssreader.gui.fragments.FeedHeadlineListFragment; import org.ttrssreader.gui.fragments.FeedListFragment; import org.ttrssreader.model.CategoryAdapter; import org.ttrssreader.model.MainAdapter; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.TopExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; public class CategoryActivity extends MenuActivity { private static final int DIALOG_WELCOME = 1; private static final int DIALOG_UPDATE = 2; private static final int DIALOG_CRASH = 3; private static final int SELECTED_VIRTUAL_CATEGORY = 1; private static final int SELECTED_CATEGORY = 2; private static final int SELECTED_LABEL = 3; private static final int SELECT_ARTICLES = MenuActivity.MARK_GROUP + 54; private String applicationName = null; public boolean cacherStarted = false; private CategoryAdapter adapter = null; // Remember to explicitly check every access to adapter for it beeing null! private CategoryUpdater categoryUpdater = null; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); // Log.d(Utils.TAG, "onCreate - CategoryActivity"); setContentView(R.layout.categorylist); // Register our own ExceptionHander Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this)); // Delete DB if requested Controller.getInstance().setDeleteDBScheduled(Controller.getInstance().isDeleteDBOnStartup()); if (!Utils.checkFirstRun(this)) { // Check for new installation showDialog(DIALOG_WELCOME); } else if (!Utils.checkNewVersion(this)) { // Check for update showDialog(DIALOG_UPDATE); } else if (!Utils.checkCrashReport(this)) { // Check for crash-reports showDialog(DIALOG_CRASH); } else if (!Utils.checkConfig()) {// Check if we have a server specified openConnectionErrorDialog((String) getText(R.string.CategoryActivity_NoServer)); } // Start caching if requested if (Controller.getInstance().cacheImagesOnStartup()) { boolean startCache = true; if (Controller.getInstance().cacheImagesOnlyWifi()) { // Check if Wifi is connected, if not don't start the ImageCache ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mWifi.isConnected()) { Log.i(Utils.TAG, "Preference Start ImageCache only on WIFI set, doing nothing..."); startCache = false; } } // Indicate that the cacher started anyway so the refresh is supressed if the ImageCache is configured but // only for Wifi. cacherStarted = true; if (startCache) { Log.i(Utils.TAG, "Starting ImageCache..."); doCache(false); // images } } } @Override protected void onResume() { super.onResume(); refreshAndUpdate(); } private void closeCursor() { if (adapter != null) adapter.closeCursor(); } @Override protected void onPause() { // First call super.onXXX, then do own clean-up. It actually makes a difference but I got no idea why. super.onPause(); closeCursor(); } @Override protected void onStop() { super.onStop(); closeCursor(); } @Override protected void onDestroy() { super.onDestroy(); closeCursor(); } @Override protected void doRefresh() { if (applicationName == null) applicationName = getResources().getString(R.string.ApplicationName); int unreadCount = DBHelper.getInstance().getUnreadCount(Data.VCAT_ALL, true); setTitle(MainAdapter.formatTitle(applicationName, unreadCount)); if (adapter != null) { adapter.makeQuery(true); adapter.notifyDataSetChanged(); } try { if (Controller.getInstance().getConnector().hasLastError()) openConnectionErrorDialog(Controller.getInstance().getConnector().pullLastError()); } catch (NotInitializedException e) { } if (categoryUpdater == null && !isCacherRunning()) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); } } @Override protected void doUpdate() { // Only update if no categoryUpdater already running if (categoryUpdater != null) { if (categoryUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { categoryUpdater = null; } else { return; } } if (!isCacherRunning() && !cacherStarted) { setProgressBarIndeterminateVisibility(true); setProgressBarVisibility(true); categoryUpdater = new CategoryUpdater(); categoryUpdater.execute(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(MARK_GROUP, SELECT_ARTICLES, Menu.NONE, R.string.Commons_SelectArticles); } @Override public boolean onContextItemSelected(MenuItem item) { Log.d(Utils.TAG, "CategoryActivity: onContextItemSelected called"); AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (adapter == null) return false; int id = adapter.getId(cmi.position); switch (item.getItemId()) { case MARK_READ: if (id < -10) new Updater(this, new ReadStateUpdater(id, 42)).execute(); new Updater(this, new ReadStateUpdater(id)).execute(); return true; case SELECT_ARTICLES: if (id < 0) return false; // Do nothing for Virtual Category or Labels Intent i = new Intent(context, FeedHeadlineActivity.class); i.putExtra(FeedHeadlineActivity.FEED_ID, FeedHeadlineActivity.FEED_NO_ID); i.putExtra(FeedHeadlineActivity.FEED_CAT_ID, id); i.putExtra(FeedHeadlineActivity.FEED_TITLE, adapter.getTitle(cmi.position)); i.putExtra(FeedHeadlineActivity.FEED_SELECT_ARTICLES, true); startActivity(i); } return false; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { Log.d(Utils.TAG, "CategoryActivity: onOptionsItemSelected called"); boolean ret = super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.Menu_Refresh: Data.getInstance().resetTime(-1, true, false, false); cacherStarted = false; doUpdate(); return true; case R.id.Menu_MarkAllRead: if (adapter != null) { new Updater(this, new ReadStateUpdater(adapter.getCategories())).execute(); return true; } else { return false; } } if (ret) { refreshAndUpdate(); } return true; } public class CategoryUpdater extends AsyncTask<Void, Integer, Void> { private int taskCount = 0; private static final int DEFAULT_TASK_COUNT = 4; @Override protected Void doInBackground(Void... params) { boolean onlyUnreadArticles = Controller.getInstance().onlyUnread(); Set<Feed> labels = DBHelper.getInstance().getFeeds(-2); taskCount = DEFAULT_TASK_COUNT + labels.size() + 1; // 1 for the caching of all articles int progress = 0; publishProgress(++progress); // Move progress forward Data.getInstance().updateCounters(false); // Cache articles for all categories publishProgress(++progress); Data.getInstance().cacheArticles(false); // Refresh articles for all labels for (Feed f : labels) { if (f.unread == 0 && onlyUnreadArticles) continue; publishProgress(++progress); // Move progress forward Data.getInstance().updateArticles(f.id, onlyUnreadArticles, false, false); } publishProgress(++progress); // Move progress forward to 100% // This stuff will be done in background without UI-notification, but the progress-calls will be done anyway // to ensure the UI is refreshed properly. ProgressBar is rendered invisible with the call to // publishProgress(taskCount). Data.getInstance().updateVirtualCategories(); publishProgress(++progress); Data.getInstance().updateCategories(false); publishProgress(taskCount); Data.getInstance().updateFeeds(Data.VCAT_ALL, false); return null; } @Override protected void onProgressUpdate(Integer... values) { if (values[0] == taskCount) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); doRefresh(); return; } setProgress((10000 / (taskCount + 1)) * values[0]); doRefresh(); } } @Override protected final Dialog onCreateDialog(final int id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setCancelable(true); final Context context = this; switch (id) { case DIALOG_WELCOME: builder.setTitle(getResources().getString(R.string.Welcome_Title)); builder.setMessage(getResources().getString(R.string.Welcome_Message)); builder.setNeutralButton((String) getText(R.string.Preferences_Btn), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { Intent i = new Intent(context, PreferencesActivity.class); startActivity(i); d.dismiss(); } }); break; case DIALOG_UPDATE: builder.setTitle(getResources().getString(R.string.Changelog_Title)); final String[] changes = getResources().getStringArray(R.array.updates); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < changes.length; i++) { sb.append("\n\n"); sb.append(changes[i]); if (sb.length() > 4000) // Don't include all messages, nobody reads the old stuff anyway break; } builder.setMessage(sb.toString().trim()); builder.setPositiveButton(android.R.string.ok, null); builder.setNeutralButton((String) getText(R.string.CategoryActivity_Donate), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString( R.string.DonateUrl)))); d.dismiss(); } }); break; case DIALOG_CRASH: builder.setTitle(getResources().getString(R.string.ErrorActivity_Title)); builder.setMessage(getResources().getString(R.string.Check_Crash)); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { sendReport(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { deleteFile(TopExceptionHandler.FILE); d.dismiss(); } }); break; } return builder.create(); } public void sendReport() { String line = ""; StringBuilder sb = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(openFileInput(TopExceptionHandler.FILE))); while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (FileNotFoundException fnfe) { // ... } catch (IOException ioe) { // ... } Intent sendIntent = new Intent(Intent.ACTION_SEND); String subject = "Error report"; String mail = getResources().getString(R.string.About_mail); String body = "Please mail this to " + mail + ": " + "\n\n" + sb.toString() + "\n\n"; sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { mail }); sendIntent.putExtra(Intent.EXTRA_TEXT, body); sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); sendIntent.setType("message/rfc822"); startActivity(Intent.createChooser(sendIntent, "Title:")); deleteFile(TopExceptionHandler.FILE); } @Override public void setAdapter(MainAdapter adapter) { if (adapter instanceof CategoryAdapter) this.adapter = (CategoryAdapter) adapter; } @Override public void itemSelected(TYPE type, int selectedIndex, int oldIndex) { // Log.d(Utils.TAG, this.getClass().getName() + " - itemSelected called. Type: " + type); if (adapter == null) { Log.d(Utils.TAG, "Adapter shouldn't be null here..."); return; } // Who is calling? switch (type) { case CATEGORY: Log.d(Utils.TAG, "CATEGORY selected. Index: " + selectedIndex); break; case FEED: Log.d(Utils.TAG, "FEED selected. Index: " + selectedIndex); break; case FEEDHEADLINE: Log.d(Utils.TAG, "FEEDHEADLINE selected. Index: " + selectedIndex); break; } // Decide what kind of item was selected int selectedId = adapter.getId(selectedIndex); final int selection; if (selectedId < 0 && selectedId >= -4) { selection = SELECTED_VIRTUAL_CATEGORY; } else if (selectedId < -10) { selection = SELECTED_LABEL; } else { selection = SELECTED_CATEGORY; } // Find out if we are using a wide screen ListFragment secondPane = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.details); if (secondPane != null && secondPane.isInLayout()) { Log.d(Utils.TAG, "Filling right pane... (" + selectedIndex + " " + oldIndex + ")"); // Set the list item as checked // getListView().setItemChecked(selectedIndex, true); // Is the current selected ondex the same as the clicked? If so, there is no need to update // if (details != null && selectedIndex == oldIndex) // return; FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); FeedHeadlineListFragment feedHeadlineFragment = null; FeedListFragment feedFragment = null; switch (selection) { case SELECTED_VIRTUAL_CATEGORY: feedHeadlineFragment = FeedHeadlineListFragment.newInstance(selectedId, adapter.getTitle(selectedIndex), 0, false); ft.replace(R.id.feed_headline_list, feedHeadlineFragment); break; case SELECTED_LABEL: feedHeadlineFragment = FeedHeadlineListFragment.newInstance(selectedId, adapter.getTitle(selectedIndex), -2, false); ft.replace(R.id.feed_headline_list, feedHeadlineFragment); break; case SELECTED_CATEGORY: feedFragment = FeedListFragment.newInstance(selectedId, adapter.getTitle(selectedIndex)); ft.replace(R.id.feed_list, feedFragment); break; } // Replace the old fragment with the new one // Use a fade animation. This makes it clear that this is not a new "layer" // above the current, but a replacement ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } else { // This is not a tablet - start a new activity Intent i = null; switch (selection) { case SELECTED_VIRTUAL_CATEGORY: i = new Intent(context, FeedHeadlineActivity.class); i.putExtra(FeedHeadlineActivity.FEED_ID, selectedId); i.putExtra(FeedHeadlineActivity.FEED_TITLE, adapter.getTitle(selectedIndex)); break; case SELECTED_LABEL: i = new Intent(context, FeedHeadlineActivity.class); i.putExtra(FeedHeadlineActivity.FEED_ID, selectedId); i.putExtra(FeedHeadlineActivity.FEED_CAT_ID, -2); i.putExtra(FeedHeadlineActivity.FEED_TITLE, adapter.getTitle(selectedIndex)); break; case SELECTED_CATEGORY: i = new Intent(context, FeedActivity.class); i.putExtra(FeedActivity.FEED_CAT_ID, selectedId); i.putExtra(FeedActivity.FEED_CAT_TITLE, adapter.getTitle(selectedIndex)); break; } if (i != null) startActivity(i); } } }
Java
/* * ttrss-reader-fork for Android * Copyright (C) 2010 N. 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.gui; import org.ttrssreader.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ErrorActivity extends Activity { public static final int ACTIVITY_SHOW_ERROR = 42; public static final int ACTIVITY_EXIT = 40; public static final String ERROR_MESSAGE = "ERROR_MESSAGE"; private String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.error); Bundle extras = getIntent().getExtras(); if (extras != null) { message = extras.getString(ERROR_MESSAGE); } else if (savedInstanceState != null) { message = savedInstanceState.getString(ERROR_MESSAGE); } TextView errorText = (TextView) this.findViewById(R.id.ErrorActivity_ErrorMessage); errorText.setText(message); Button prefBtn = (Button) this.findViewById(R.id.Preferences_Btn); prefBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); openPreferences(); } }); Button exitBtn = (Button) this.findViewById(R.id.ErrorActivity_ExitBtn); exitBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { exitButtonPressed(); } }); Button closeBtn = (Button) this.findViewById(R.id.ErrorActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { closeButtonPressed(); } }); } private void exitButtonPressed() { setResult(ACTIVITY_EXIT); finish(); } private void closeButtonPressed() { setResult(ACTIVITY_SHOW_ERROR); finish(); } private void openPreferences() { startActivity(new Intent(this, PreferencesActivity.class)); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.gui.interfaces.IConfigurable; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IUpdateEndListener; import org.ttrssreader.imageCache.ForegroundService; import org.ttrssreader.model.updaters.StateSynchronisationUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.Utils; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; /** * This class pulls common functionality from the three subclasses (CategoryActivity, FeedListActivity and * FeedHeadlineListActivity). */ public abstract class MenuActivity extends FragmentActivity implements IUpdateEndListener, ICacheEndListener, IConfigurable, IItemSelectedListener { protected Updater updater; protected Context context = null; protected boolean isTablet = false; protected static final int MARK_GROUP = 42; protected static final int MARK_READ = MARK_GROUP + 1; protected static final int MARK_STAR = MARK_GROUP + 2; protected static final int MARK_PUBLISH = MARK_GROUP + 3; protected static final int MARK_PUBLISH_NOTE = MARK_GROUP + 4; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); context = getApplicationContext(); // Initialize Singletons for Config, Data-Access and DB Controller.getInstance().checkAndInitializeController(this, getWindowManager().getDefaultDisplay()); DBHelper.getInstance().checkAndInitializeDB(this); Data.getInstance().checkAndInitializeData(this); // Register this instance to be notified when the ImageCache finished. Controller.getInstance().registerActivity(this); // This is a tablet if this view exists View details = findViewById(R.id.details); isTablet = details != null && details.getVisibility() == View.VISIBLE; } @Override protected void onPause() { super.onPause(); Controller.getInstance().unregisterActivity(this); } @Override protected void onDestroy() { super.onDestroy(); if (updater != null) { updater.cancel(true); updater = null; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == ErrorActivity.ACTIVITY_SHOW_ERROR) { refreshAndUpdate(); } else if (resultCode == PreferencesActivity.ACTIVITY_SHOW_PREFERENCES) { refreshAndUpdate(); } else if (resultCode == ErrorActivity.ACTIVITY_EXIT) { finish(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.generic, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem offline = menu.findItem(R.id.Menu_WorkOffline); if (Controller.getInstance().workOffline()) { offline.setTitle(getString(R.string.UsageOnlineTitle)); offline.setIcon(R.drawable.ic_menu_play_clip); } else { offline.setTitle(getString(R.string.UsageOfflineTitle)); offline.setIcon(R.drawable.ic_menu_stop); } MenuItem displayUnread = menu.findItem(R.id.Menu_DisplayOnlyUnread); if (Controller.getInstance().onlyUnread()) { displayUnread.setTitle(getString(R.string.Commons_DisplayAll)); } else { displayUnread.setTitle(getString(R.string.Commons_DisplayOnlyUnread)); } return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.Menu_DisplayOnlyUnread: Controller.getInstance().setDisplayOnlyUnread(!Controller.getInstance().onlyUnread()); return true; case R.id.Menu_InvertSort: if (this instanceof FeedHeadlineActivity) { Controller.getInstance() .setInvertSortArticleList(!Controller.getInstance().invertSortArticlelist()); } else { Controller.getInstance().setInvertSortFeedsCats(!Controller.getInstance().invertSortFeedscats()); } return true; case R.id.Menu_WorkOffline: Controller.getInstance().setWorkOffline(!Controller.getInstance().workOffline()); if (!Controller.getInstance().workOffline()) { // Synchronize status of articles with server new Updater(this, new StateSynchronisationUpdater()).execute((Void[]) null); } return true; case R.id.Menu_ShowPreferences: startActivityForResult(new Intent(this, PreferencesActivity.class), PreferencesActivity.ACTIVITY_SHOW_PREFERENCES); return true; case R.id.Menu_About: startActivity(new Intent(this, AboutActivity.class)); return true; // // Removed. See res/menu/generic.xml for more information. // case R.id.Category_Menu_ArticleCache: // doCache(true); // return true; case R.id.Category_Menu_ImageCache: doCache(false); return true; default: return false; } } protected abstract void doRefresh(); /* ############# BEGIN: Update */ protected abstract void doUpdate(); @Override public void onUpdateEnd() { updater = null; doRefresh(); } @Override public void onUpdateProgress() { doRefresh(); } /* ############# END: Update */ /* ############# BEGIN: Cache */ protected void doCache(boolean onlyArticles) { // Register for progress-updates ForegroundService.registerCallback(this); if (isCacherRunning()) { if (!onlyArticles) // Tell cacher to do images too ForegroundService.loadImagesToo(); else // Running and already caching images, no need to do anything return; } // Start new cacher Intent intent; if (onlyArticles) { intent = new Intent(ForegroundService.ACTION_LOAD_ARTICLES); } else { intent = new Intent(ForegroundService.ACTION_LOAD_IMAGES); } intent.setClass(this.getApplicationContext(), ForegroundService.class); setProgressBarVisibility(true); startService(intent); } @Override public void onCacheEnd() { setProgressBarVisibility(false); doRefresh(); } @Override public void onCacheProgress(int taskCount, int progress) { if (taskCount == progress) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); } else { setProgress((10000 / (taskCount + 1)) * progress); } doRefresh(); } protected boolean isCacherRunning() { return ForegroundService.isInstanceCreated(); } /* ############# END: Cache */ protected void openConnectionErrorDialog(String errorMessage) { if (updater != null) { updater.cancel(true); updater = null; } setProgressBarIndeterminateVisibility(false); Intent i = new Intent(this, ErrorActivity.class); i.putExtra(ErrorActivity.ERROR_MESSAGE, errorMessage); startActivityForResult(i, ErrorActivity.ACTIVITY_SHOW_ERROR); // finish(); } protected void refreshAndUpdate() { if (Utils.checkConfig()) { doRefresh(); doUpdate(); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import java.io.File; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.preferences.Constants; import org.ttrssreader.preferences.FileBrowserHelper; import org.ttrssreader.preferences.FileBrowserHelper.FileBrowserFailOverCallback; import org.ttrssreader.utils.Utils; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; public class PreferencesActivity extends PreferenceActivity { public static final int ACTIVITY_SHOW_PREFERENCES = 43; public static final int ACTIVITY_CHOOSE_ATTACHMENT_FOLDER = 1; public static final int ACTIVITY_CHOOSE_CACHE_FOLDER = 2; private static AsyncTask<Void, Void, Void> init; private Context context; private Preference downloadPath; private Preference cachePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); addPreferencesFromResource(R.layout.preferences); setResult(ACTIVITY_SHOW_PREFERENCES); downloadPath = findPreference(Constants.SAVE_ATTACHMENT); downloadPath.setSummary(Controller.getInstance().saveAttachmentPath()); downloadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileBrowserHelper.getInstance().showFileBrowserActivity(PreferencesActivity.this, new File(Controller.getInstance().saveAttachmentPath()), ACTIVITY_CHOOSE_ATTACHMENT_FOLDER, callbackDownloadPath); return true; } FileBrowserFailOverCallback callbackDownloadPath = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { downloadPath.setSummary(path); Controller.getInstance().setSaveAttachmentPath(path); } @Override public void onCancel() { // canceled, do nothing } }; }); cachePath = findPreference(Constants.CACHE_FOLDER); cachePath.setSummary(Controller.getInstance().cacheFolder()); cachePath.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileBrowserHelper.getInstance().showFileBrowserActivity(PreferencesActivity.this, new File(Controller.getInstance().cacheFolder()), ACTIVITY_CHOOSE_CACHE_FOLDER, callbackCachePath); return true; } FileBrowserFailOverCallback callbackCachePath = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { cachePath.setSummary(path); Controller.getInstance().setCacheFolder(path); } @Override public void onCancel() { // canceled, do nothing } }; }); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(Controller.getInstance()); } @Override protected void onPause() { super.onPause(); // Unregister the listener whenever a key changes getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( Controller.getInstance()); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(Controller.getInstance()); } @Override protected void onStop() { super.onStop(); if (init != null) { init.cancel(true); init = null; } if (Utils.checkConfig()) { init = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Controller.checkAndInitializeController(context, (0 != 1)); return null; } }; init.execute(); } } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.preferences, menu); return true; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.Preferences_Menu_Reset: resetPreferences(); return true; case R.id.Preferences_Menu_ResetDatabase: resetDB(); return true; } return false; } private void resetPreferences() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Constants.resetPreferences(prefs); this.finish(); ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName()); startActivity(new Intent().setComponent(comp)); } private void resetDB() { Controller.getInstance().setDeleteDBScheduled(true); DBHelper.getInstance().checkAndInitializeDB(this); this.finish(); ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName()); startActivity(new Intent().setComponent(comp)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String path = null; if (resultCode == RESULT_OK && data != null) { // obtain the filename Uri fileUri = data.getData(); if (fileUri != null) path = fileUri.getPath(); } if (path != null) { switch (requestCode) { case ACTIVITY_CHOOSE_ATTACHMENT_FOLDER: downloadPath.setSummary(path); Controller.getInstance().setSaveAttachmentPath(path); break; case ACTIVITY_CHOOSE_CACHE_FOLDER: cachePath.setSummary(path); Controller.getInstance().setCacheFolder(path); break; } } super.onActivityResult(requestCode, resultCode, data); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. Braden. * Copyright (C) The Developers from K-9 Mail (https://code.google.com/p/k9mail/) * * 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.gui.view; 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.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.DateUtils; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; /** * Copied and modified for my purpose, originally developed for K-9 Mail. Source: * https://github.com/k9mail/k-9/blob/master/src/com/fsck/k9/view/MessageHeader.java * * @author https://code.google.com/p/k9mail/ * */ public class ArticleHeaderView extends LinearLayout { private TextView feedView; private TextView dateView; private TextView timeView; private TextView titleView; private CheckBox starred; private Article article; private Context context; public ArticleHeaderView(Context context, AttributeSet attrs) { super(context, attrs); this.setBackgroundColor(Color.WHITE); this.context = context; } private void initializeLayout() { feedView = (TextView) findViewById(R.id.feed); feedView.setTextColor(Color.BLACK); titleView = (TextView) findViewById(R.id.title); titleView.setTextColor(Color.BLACK); dateView = (TextView) findViewById(R.id.date); dateView.setTextColor(Color.BLACK); timeView = (TextView) findViewById(R.id.time); timeView.setTextColor(Color.BLACK); starred = (CheckBox) findViewById(R.id.starred); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { return; } }); feedView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); starred.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Updater(null, new StarredStateUpdater(article, article.isStarred ? 0 : 1)).execute(); } }); } public void populate(Article article) { this.article = article; this.initializeLayout(); Feed feed = DBHelper.getInstance().getFeed(article.feedId); if (feed != null) { feedView.setText(feed.title); } titleView.setText(article.title); Date updated = article.updated; dateView.setText(DateUtils.getDate(context, updated)); timeView.setText(DateUtils.getTime(context, updated)); starred.setChecked(article.isStarred); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. Braden. * Copyright (C) The Developers from K-9 Mail (https://code.google.com/p/k9mail/) * * 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.gui.view; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.util.TypedValue; import android.webkit.WebView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * Copied and modified for my purpose, originally developed for K-9 Mail. Source: * https://github.com/k9mail/k-9/blob/master/src/com/fsck/k9/view/MessageHeader.java * * @author https://code.google.com/p/k9mail/ * */ public class ArticleView extends RelativeLayout { private RelativeLayout centralView; private WebView webView; private LinearLayout buttonView; private TextView swipeView; public ArticleView(Context context, AttributeSet attrs) { super(context, attrs); this.setBackgroundColor(Color.WHITE); } private void initializeLayout() { centralView = (RelativeLayout) findViewById(R.id.centralView); webView = (WebView) findViewById(R.id.webView); buttonView = (LinearLayout) findViewById(R.id.buttonView); swipeView = (TextView) findViewById(R.id.swipeView); // First check for swipe-option, this overrides the buttons-option if (Controller.getInstance().useSwipe()) { if (Controller.getInstance().leftHanded() && Controller.landscape) { // Try to move swipe-area to left side... // First: Remove the view centralView.removeView(swipeView); // calculate width of the swipe-area in pixels, its the number of pixels of the value 45dip int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 45, getResources() .getDisplayMetrics()); // Create new layout-parameters which align this view left in the parent view LayoutParams params = new LayoutParams(width, LayoutParams.FILL_PARENT); params.addRule(ALIGN_LEFT, webView.getId()); // Add the view again centralView.addView(swipeView, params); // Recalculate values recomputeViewAttributes(swipeView); } swipeView.setVisibility(TextView.INVISIBLE); swipeView.setPadding(16, Controller.padding, 16, Controller.padding); if (Controller.landscape) swipeView.setHeight(Controller.swipeAreaHeight); else swipeView.setWidth(Controller.swipeAreaWidth); // remove Buttons this.removeView(buttonView); } else if (Controller.getInstance().useButtons()) { if (Controller.getInstance().leftHanded() && Controller.landscape) { // Try to move buttons to left side... // First: Remove the view this.removeView(buttonView); // calculate width of the swipe-area in pixels, its the number of pixels of the value 45dip int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 45, getResources() .getDisplayMetrics()); // Create new layout-parameters which align this view left in the parent view LayoutParams params = new LayoutParams(width, LayoutParams.FILL_PARENT); params.addRule(ALIGN_PARENT_LEFT, TRUE); // Add the view again this.addView(buttonView, params); // Recalculate values recomputeViewAttributes(buttonView); // Webview and its container has to be moved to the right side to make room for the buttons. // Not necessary for the swipe area since this is an overlay to the webview. this.removeView(centralView); LayoutParams centralViewParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.addRule(RIGHT_OF, buttonView.getId()); this.addView(centralView, centralViewParams); // Recalculate values recomputeViewAttributes(this); } // Remove Swipe-Area centralView.removeView(swipeView); } else { // Both disabled, remove everything centralView.removeView(swipeView); this.removeView(buttonView); } // Recalculate values recomputeViewAttributes(centralView); } public void populate() { this.initializeLayout(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.view; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.gui.ArticleActivity; import org.ttrssreader.gui.MediaPlayerActivity; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; public class ArticleWebViewClient extends WebViewClient { private Context context; private float originalScale = Float.MAX_VALUE; private ArticleActivity articleActivity; public ArticleWebViewClient(ArticleActivity a) { this.articleActivity = a; } @Override public boolean shouldOverrideUrlLoading(WebView view, final String url) { context = view.getContext(); boolean audioOrVideo = false; for (String s : FileUtils.AUDIO_EXTENSIONS) { if (url.toLowerCase().contains("." + s)) { audioOrVideo = true; break; } } for (String s : FileUtils.VIDEO_EXTENSIONS) { if (url.toLowerCase().contains("." + s)) { audioOrVideo = true; break; } } if (audioOrVideo) { // @formatter:off final CharSequence[] items = { (String) context.getText(R.string.WebViewClientActivity_Display), (String) context.getText(R.string.WebViewClientActivity_Download) }; // @formatter:on AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("What shall we do?"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: Log.i(Utils.TAG, "Displaying file in mediaplayer: " + url); Intent i = new Intent(context, MediaPlayerActivity.class); i.putExtra(MediaPlayerActivity.URL, url); context.startActivity(i); break; case 1: try { new AsyncDownloader().execute(new URL(url)); } catch (MalformedURLException e) { e.printStackTrace(); } break; default: Log.e(Utils.TAG, "Doing nothing, but why is that?? Item: " + item); break; } } }); AlertDialog alert = builder.create(); alert.show(); } else { Uri uri = Uri.parse(url); try { context.startActivity(new Intent(Intent.ACTION_VIEW, uri)); } catch (Exception e) { e.printStackTrace(); } } return true; } // This calls the webview which loads different HTML-Headers for original zoom and other zoom-factors, we got // original zoom with images scaled to match display-width and other factors to display in original width. @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { super.onScaleChanged(view, oldScale, newScale); Log.d(Utils.TAG, String.format("originalScale: %s, oldScale: %s, newScale: %s", originalScale, oldScale, newScale)); if (originalScale == Float.MAX_VALUE) { originalScale = oldScale; articleActivity.onZoomChanged(); // originalScale == newScale); } } private boolean externalStorageState() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } else { return false; } } private class AsyncDownloader extends AsyncTask<URL, Void, Void> { private final static int BUFFER = 1024; protected Void doInBackground(URL... urls) { if (urls.length < 1) { String msg = "No URL given, skipping download..."; Log.w(Utils.TAG, msg); Utils.showFinishedNotification(msg, 0, true, context); return null; } else if (!externalStorageState()) { String msg = "External Storage not available, skipping download..."; Log.w(Utils.TAG, msg); Utils.showFinishedNotification(msg, 0, true, context); return null; } Utils.showRunningNotification(context, false); URL url = urls[0]; long start = System.currentTimeMillis(); // Build name as "download_123801230712", then try to extract a proper name from URL String name = "download_" + System.currentTimeMillis(); if (!url.getFile().equals("")) { String n = url.getFile(); name = n.substring(1).replaceAll("[^A-Za-z0-9_.]", ""); if (name.contains(".") && name.length() > name.indexOf(".") + 4) { // Try to guess the position of the extension.. name = name.substring(0, name.indexOf(".") + 4); } else if (name.length() == 0) { // just to make sure.. name = "download_" + System.currentTimeMillis(); } } // Use configured output directory File folder = new File(Controller.getInstance().saveAttachmentPath()); if (!folder.exists()) { if (!folder.mkdirs()) { // Folder could not be created, fallback to internal directory on sdcard // Path: /sdcard/Android/data/org.ttrssreader/files/ folder = new File(Constants.SAVE_ATTACHMENT_DEFAULT); folder.mkdirs(); } } if (!folder.exists()) folder.mkdirs(); BufferedInputStream in = null; FileOutputStream fos = null; BufferedOutputStream bout = null; int count = -1; File file = null; try { HttpURLConnection c = (HttpURLConnection) url.openConnection(); file = new File(folder, name); if (file.exists()) { count = (int) file.length(); c.setRequestProperty("Range", "bytes=" + file.length() + "-"); // try to resume downloads } c.setRequestMethod("GET"); c.setDoInput(true); c.setDoOutput(true); in = new BufferedInputStream(c.getInputStream()); fos = (count == 0) ? new FileOutputStream(file) : new FileOutputStream(file, true); bout = new BufferedOutputStream(fos, BUFFER); byte[] data = new byte[BUFFER]; int x = 0; while ((x = in.read(data, 0, BUFFER)) >= 0) { bout.write(data, 0, x); count += x; } int time = (int) (System.currentTimeMillis() - start) / 1000; // Show Intent which opens the file Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); if (file != null) intent.setDataAndType(Uri.fromFile(file), FileUtils.getMimeType(file.getName())); Log.i(Utils.TAG, "Finished. Path: " + file.getAbsolutePath() + " Time: " + time + "s Bytes: " + count); Utils.showFinishedNotification(file.getAbsolutePath(), time, false, context, intent); } catch (IOException e) { String msg = "Error while downloading: " + e; Log.e(Utils.TAG, msg); e.printStackTrace(); Utils.showFinishedNotification(msg, 0, true, context); } finally { // Remove "running"-notification Utils.showRunningNotification(context, true); } return null; } } }
Java
package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.model.pojos.Article; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.EditText; public class TextInputAlert { private Article article; private TextInputAlertCallback callback; public TextInputAlert(TextInputAlertCallback callback, Article article) { this.callback = callback; this.article = article; } public void show(Context context) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle(context.getString(R.string.Commons_MarkPublishNote)); final EditText input = new EditText(context); input.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); input.setMinLines(3); input.setMaxLines(10); alert.setView(input); alert.setPositiveButton(context.getString(R.string.Utils_OkayAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); callback.onPublishNoteResult(article, value); } }); alert.setNegativeButton(context.getString(R.string.Utils_CancelAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.NotInitializedException; import org.ttrssreader.gui.fragments.FeedHeadlineListFragment; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.model.MainAdapter; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.Utils; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.MenuItem; import android.widget.AdapterView.AdapterContextMenuInfo; public class FeedActivity extends MenuActivity { public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_CAT_TITLE = "FEED_CAT_TITLE"; // Extras private int categoryId; private String categoryTitle; private FeedAdapter adapter = null; // Remember to explicitly check every access to adapter for it beeing null! private FeedUpdater feedUpdater = null; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); // Log.d(Utils.TAG, "onCreate - FeedActivity"); setContentView(R.layout.feedlist); Bundle extras = getIntent().getExtras(); if (extras != null) { categoryId = extras.getInt(FEED_CAT_ID); categoryTitle = extras.getString(FEED_CAT_TITLE); } else if (instance != null) { categoryId = instance.getInt(FEED_CAT_ID); categoryTitle = instance.getString(FEED_CAT_TITLE); } else { categoryId = -1; categoryTitle = null; } } @Override protected void onResume() { super.onResume(); DBHelper.getInstance().checkAndInitializeDB(this); doRefresh(); doUpdate(); } private void closeCursor() { if (adapter != null) adapter.closeCursor(); } @Override protected void onPause() { // First call super.onXXX, then do own clean-up. It actually makes a difference but I got no idea why. super.onPause(); closeCursor(); } @Override protected void onStop() { super.onStop(); closeCursor(); } @Override protected void onDestroy() { super.onDestroy(); closeCursor(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); outState.putString(FEED_CAT_TITLE, categoryTitle); super.onSaveInstanceState(outState); } @Override protected void doRefresh() { int unreadCount = DBHelper.getInstance().getUnreadCount(categoryId, true); setTitle(MainAdapter.formatTitle(categoryTitle, unreadCount)); if (adapter != null) { adapter.makeQuery(true); adapter.notifyDataSetChanged(); } try { if (Controller.getInstance().getConnector().hasLastError()) openConnectionErrorDialog(Controller.getInstance().getConnector().pullLastError()); } catch (NotInitializedException e) { } if (feedUpdater == null) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); } } @Override protected void doUpdate() { // Only update if no feedUpdater already running if (feedUpdater != null) { if (feedUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { feedUpdater = null; } else { return; } } if (!isCacherRunning()) { setProgressBarIndeterminateVisibility(true); setProgressBarVisibility(false); feedUpdater = new FeedUpdater(); feedUpdater.execute(); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (item.getItemId() == MARK_READ) { new Updater(this, new ReadStateUpdater(adapter.getId(cmi.position), 42)).execute(); return true; } return false; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { boolean ret = super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.Menu_Refresh: Data.getInstance().resetTime(categoryId, false, true, false); doUpdate(); return true; case R.id.Menu_MarkAllRead: new Updater(this, new ReadStateUpdater(categoryId)).execute(); return true; } if (ret) { doRefresh(); } return true; } /** * * * @author n * */ public class FeedUpdater extends AsyncTask<Void, Integer, Void> { private int taskCount = 0; private static final int DEFAULT_TASK_COUNT = 2; @Override protected Void doInBackground(Void... params) { Category c = DBHelper.getInstance().getCategory(categoryId); taskCount = DEFAULT_TASK_COUNT + (c.unread != 0 ? 1 : 0); int progress = 0; publishProgress(++progress); // Move progress forward Data.getInstance().updateFeeds(categoryId, false); publishProgress(++progress); // Move progress forward // Update articles for current category if (c.unread != 0) Data.getInstance().updateArticles(c.id, Controller.getInstance().onlyUnread(), true, false); publishProgress(taskCount); // Move progress forward to 100% return null; } @Override protected void onProgressUpdate(Integer... values) { if (values[0] == taskCount) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); doRefresh(); return; } setProgress((10000 / (taskCount + 1)) * values[0]); doRefresh(); } } @Override public void setAdapter(MainAdapter adapter) { if (adapter instanceof FeedAdapter) this.adapter = (FeedAdapter) adapter; } @Override public void itemSelected(TYPE type, int selectedIndex, int oldIndex) { // Log.d(Utils.TAG, this.getClass().getName() + " - itemSelected called. Type: " + type); if (adapter == null) { Log.d(Utils.TAG, "Adapter shouldn't be null here..."); return; } // Find out if we are using a wide screen ListFragment secondPane = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.details); if (secondPane != null && secondPane.isInLayout()) { Log.d(Utils.TAG, "Filling right pane... (" + selectedIndex + " " + oldIndex + ")"); // Set the list item as checked // getListView().setItemChecked(selectedIndex, true); // Get the fragment instance ListFragment details = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.details); // Is the current selected ondex the same as the clicked? If so, there is no need to update if (details != null && selectedIndex == oldIndex) return; details = FeedHeadlineListFragment.newInstance(adapter.getId(selectedIndex), adapter.getTitle(selectedIndex), categoryId, false); // Replace the old fragment with the new one FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.details, details); // Use a fade animation. This makes it clear that this is not a new "layer" // above the current, but a replacement ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } else { // This is not a tablet - start a new activity Intent i = new Intent(context, FeedHeadlineActivity.class); i.putExtra(FeedHeadlineActivity.FEED_CAT_ID, categoryId); i.putExtra(FeedHeadlineActivity.FEED_ID, adapter.getId(selectedIndex)); i.putExtra(FeedHeadlineActivity.FEED_TITLE, adapter.getTitle(selectedIndex)); if (i != null) startActivity(i); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import org.ttrssreader.R; import android.app.Activity; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class MediaPlayerActivity extends Activity { public static final String URL = "media_url"; private String url; private MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); setContentView(R.layout.media); Bundle extras = getIntent().getExtras(); if (extras != null) { url = extras.getString(URL); } else if (instance != null) { url = instance.getString(URL); } else { url = ""; } VideoView videoView = (VideoView) findViewById(R.id.MediaView); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); Uri video = Uri.parse(url); videoView.setMediaController(mediaController); videoView.setVideoURI(video); videoView.start(); } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null) mediaPlayer.release(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import java.util.Set; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.NotInitializedException; import org.ttrssreader.gui.interfaces.IUpdateEndListener; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.gui.view.ArticleHeaderView; import org.ttrssreader.gui.view.ArticleView; import org.ttrssreader.gui.view.ArticleWebViewClient; import org.ttrssreader.imageCache.ImageCacher; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.updaters.PublishedStateUpdater; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.StateSynchronisationUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Button; import android.widget.TextView; public class ArticleActivity extends Activity implements IUpdateEndListener, TextInputAlertCallback { public static final String ARTICLE_ID = "ARTICLE_ID"; public static final String ARTICLE_FEED_ID = "ARTICLE_FEED_ID"; public static final String ARTICLE_MOVE = "ARTICLE_MOVE"; public static final int ARTICLE_MOVE_NONE = 0; public static final int ARTICLE_MOVE_DEFAULT = ARTICLE_MOVE_NONE; // Extras private int articleId = -1; private int feedId = -1; private int categoryId = -1000; private boolean selectArticlesForCategory = false; private int lastMove = ARTICLE_MOVE_DEFAULT; private ArticleHeaderView headerContainer; private ArticleView mainContainer; private Article article = null; private String content; private boolean linkAutoOpened; private boolean markedRead = false; private WebView webView; private TextView swipeView; private Button buttonNext; private Button buttonPrev; private GestureDetector mGestureDetector; private String baseUrl = null; private FeedHeadlineAdapter parentAdapter = null; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); // Log.d(Utils.TAG, "onCreate - ArticleActivity"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); Controller.getInstance().checkAndInitializeController(this, getWindowManager().getDefaultDisplay()); DBHelper.getInstance().checkAndInitializeDB(this); Data.getInstance().checkAndInitializeData(this); if (Controller.getInstance().displayArticleHeader()) requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.articleitem); headerContainer = (ArticleHeaderView) findViewById(R.id.article_header_container); mainContainer = (ArticleView) findViewById(R.id.article_main_layout); webView = (WebView) findViewById(R.id.webView); buttonPrev = (Button) findViewById(R.id.buttonPrev); buttonNext = (Button) findViewById(R.id.buttonNext); swipeView = (TextView) findViewById(R.id.swipeView); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.setWebViewClient(new ArticleWebViewClient(this)); // TODO: Use this to reposition the zoom-buttons? // final View zoom = webView.getZoomControls(); // zoom.setLayoutParams(params) // Detect gestures mGestureDetector = new GestureDetector(onGestureListener); webView.setOnKeyListener(keyListener); buttonNext.setOnClickListener(onButtonPressedListener); buttonPrev.setOnClickListener(onButtonPressedListener); Bundle extras = getIntent().getExtras(); if (extras != null) { articleId = extras.getInt(ARTICLE_ID); feedId = extras.getInt(ARTICLE_FEED_ID); categoryId = extras.getInt(FeedHeadlineActivity.FEED_CAT_ID); selectArticlesForCategory = extras.getBoolean(FeedHeadlineActivity.FEED_SELECT_ARTICLES); lastMove = extras.getInt(ARTICLE_MOVE); } else if (instance != null) { articleId = instance.getInt(ARTICLE_ID); feedId = instance.getInt(ARTICLE_FEED_ID); categoryId = instance.getInt(FeedHeadlineActivity.FEED_CAT_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineActivity.FEED_SELECT_ARTICLES); lastMove = instance.getInt(ARTICLE_MOVE); } Controller.getInstance().lastOpenedFeed = feedId; Controller.getInstance().lastOpenedArticle = articleId; parentAdapter = new FeedHeadlineAdapter(getApplicationContext(), feedId, categoryId, selectArticlesForCategory); doVibrate(0); // Get article from DB article = DBHelper.getInstance().getArticle(articleId); // Mark as read if necessary, do it here because in doRefresh() it will be done several tiumes even if you set // it to "unread" in the meantime. if (article != null && article.isUnread && Controller.getInstance().automaticMarkRead()) { article.isUnread = false; new Updater(null, new ReadStateUpdater(article, feedId, 0)).execute(); markedRead = true; } } @Override protected void onResume() { super.onResume(); DBHelper.getInstance().checkAndInitializeDB(this); doRefresh(); } private void closeCursor() { if (parentAdapter != null) { parentAdapter.closeCursor(); } } @Override protected void onPause() { // First call super.onXXX, then do own clean-up. It actually makes a difference but I got no idea why. super.onPause(); closeCursor(); } @Override protected void onStop() { // Check again to make sure it didnt get updated and marked as unread again in the background if (!markedRead) { if (article != null && article.isUnread && Controller.getInstance().automaticMarkRead()) new Updater(null, new ReadStateUpdater(article, feedId, 0)).execute(); } super.onStop(); closeCursor(); } @Override protected void onDestroy() { // Check again to make sure it didnt get updated and marked as unread again in the background if (!markedRead) { if (article != null && article.isUnread && Controller.getInstance().automaticMarkRead()) new Updater(null, new ReadStateUpdater(article, feedId, 0)).execute(); } super.onDestroy(); closeCursor(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(ARTICLE_ID, articleId); outState.putInt(ARTICLE_FEED_ID, feedId); outState.putInt(FeedHeadlineActivity.FEED_CAT_ID, categoryId); outState.putBoolean(FeedHeadlineActivity.FEED_SELECT_ARTICLES, selectArticlesForCategory); outState.putInt(ARTICLE_MOVE, lastMove); } private void doRefresh() { setProgressBarIndeterminateVisibility(true); if (Controller.getInstance().workOffline()) { webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY); } else { webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); } try { // Check for errors if (Controller.getInstance().getConnector().hasLastError()) { openConnectionErrorDialog(Controller.getInstance().getConnector().pullLastError()); setProgressBarIndeterminateVisibility(false); return; } // Get article from DB only if necessary if (article == null) article = DBHelper.getInstance().getArticle(articleId); if (article == null || article.content == null) return; // Populate information-bar on top of the webView if enabled if (Controller.getInstance().displayArticleHeader()) { headerContainer.populate(article); } else { headerContainer.setVisibility(View.GONE); } // Initialize mainContainer with buttons or swipe-view mainContainer.populate(); final int contentLength = article.content.length(); // Inject the specific code for attachments, <img> for images, http-link for Videos StringBuilder contentTmp = injectAttachments(getApplicationContext(), new StringBuilder(article.content), article.attachments); // if (article.cachedImages) // Do this anyway, article.cachedImages can be true if some images were fetched and others produced errors contentTmp = injectArticleLink(getApplicationContext(), contentTmp); content = injectCachedImages(contentTmp.toString(), articleId); // Load html from Controller and insert content String text = Controller.htmlHeader.replace("MARKER", content); // TODO: Whole "switch background-color-thing" needs to be refactored. if (Controller.getInstance().darkBackground()) { webView.setBackgroundColor(Color.BLACK); text = "<font color='white'>" + text + "</font>"; setDarkBackground(headerContainer); } // Use if loadDataWithBaseURL, 'cause loadData is buggy (encoding error & don't support "%" in html). baseUrl = StringSupport.getBaseURL(article.url); webView.loadDataWithBaseURL(baseUrl, text, "text/html", "utf-8", "about:blank"); setTitle(article.title); if (!linkAutoOpened && contentLength < 3) { if (Controller.getInstance().openUrlEmptyArticle()) { Log.i(Utils.TAG, "Article-Content is empty, opening URL in browser"); linkAutoOpened = true; openLink(); } } } catch (NotInitializedException e) { } setProgressBarIndeterminateVisibility(false); } /** * Recursively walks all viewGroups and their Views inside the given ViewGroup and sets the background to black and, * in case a TextView is found, the Text-Color to white. * * @param v * the ViewGroup to walk through */ private void setDarkBackground(ViewGroup v) { v.setBackgroundColor(Color.BLACK); for (int i = 0; i < v.getChildCount(); i++) { // View at index 0 seems to be this view itself. View vChild = v.getChildAt(i); if (vChild == null || vChild.getId() == v.getId()) continue; if (vChild instanceof TextView) ((TextView) vChild).setTextColor(Color.WHITE); if (vChild instanceof ViewGroup) setDarkBackground(((ViewGroup) vChild)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.article, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (article == null) return true; MenuItem read = menu.findItem(R.id.Article_Menu_MarkRead); if (article.isUnread) { read.setTitle(getString(R.string.Commons_MarkRead)); } else { read.setTitle(getString(R.string.Commons_MarkUnread)); } MenuItem publish = menu.findItem(R.id.Article_Menu_MarkStar); if (article.isStarred) { publish.setTitle(getString(R.string.Commons_MarkUnstar)); } else { publish.setTitle(getString(R.string.Commons_MarkStar)); } MenuItem star = menu.findItem(R.id.Article_Menu_MarkPublish); if (article.isPublished) { star.setTitle(getString(R.string.Commons_MarkUnpublish)); } else { star.setTitle(getString(R.string.Commons_MarkPublish)); } MenuItem offline = menu.findItem(R.id.Article_Menu_WorkOffline); if (Controller.getInstance().workOffline()) { offline.setTitle(getString(R.string.UsageOnlineTitle)); offline.setIcon(R.drawable.ic_menu_play_clip); } else { offline.setTitle(getString(R.string.UsageOfflineTitle)); offline.setIcon(R.drawable.ic_menu_stop); } return true; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.Article_Menu_MarkRead: new Updater(null, new ReadStateUpdater(article, feedId, article.isUnread ? 0 : 1)).execute(); return true; case R.id.Article_Menu_MarkStar: new Updater(null, new StarredStateUpdater(article, article.isStarred ? 0 : 1)).execute(); return true; case R.id.Article_Menu_MarkPublish: new Updater(null, new PublishedStateUpdater(article, article.isPublished ? 0 : 1)).execute(); return true; case R.id.Article_Menu_MarkPublishNote: new TextInputAlert(this, article).show(this); return true; case R.id.Article_Menu_WorkOffline: Controller.getInstance().setWorkOffline(!Controller.getInstance().workOffline()); if (!Controller.getInstance().workOffline()) { // Synchronize status of articles with server new Updater(this, new StateSynchronisationUpdater()).execute((Void[]) null); } return true; case R.id.Article_Menu_OpenLink: openLink(); return true; case R.id.Article_Menu_ShareLink: String content = (String) getText(R.string.ArticleActivity_ShareSubject); Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); if (article != null) { i.putExtra(Intent.EXTRA_TEXT, content + " " + article.url); i.putExtra(Intent.EXTRA_SUBJECT, article.title); } startActivity(Intent.createChooser(i, (String) getText(R.string.ArticleActivity_ShareTitle))); return true; default: return false; } } /** * Starts a new activity with the url of the current article. This should open a webbrowser in most cases. If the * url contains spaces or newline-characters it is first trim()'ed. */ private void openLink() { if (article == null || article.url == null || article.url.length() == 0) return; String url = article.url; if (article.url.contains(" ") || article.url.contains("\n")) url = url.trim(); try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } catch (ActivityNotFoundException e) { Log.e(Utils.TAG, "Couldn't find a suitable activity for the uri: " + url); } } public void onZoomChanged() { // Load html from Raw-Ressources and insert content String temp = getResources().getString(R.string.INJECT_HTML_HEAD_ZOOM); if (content == null) content = ""; String text = temp.replace("MARKER", content); webView.loadDataWithBaseURL(baseUrl, text, "text/html", "utf-8", "about:blank"); } private void openNextArticle(int direction) { int newIndex = getCurrentIndex() + direction; // Check: No more articles in this direction? if (doVibrate(newIndex)) return; Intent i = new Intent(this, ArticleActivity.class); i.putExtra(ARTICLE_ID, parentAdapter.getId(newIndex)); i.putExtra(ARTICLE_FEED_ID, feedId); i.putExtra(FeedHeadlineActivity.FEED_CAT_ID, categoryId); i.putExtra(FeedHeadlineActivity.FEED_SELECT_ARTICLES, selectArticlesForCategory); i.putExtra(ARTICLE_MOVE, direction); // Store direction so next article can evaluate if we are running into // a "wall" startActivityForResult(i, 0); finish(); } private int getCurrentIndex() { int currentIndex = -2; // -2 so index is still -1 if direction is +1, avoids moving when no move possible int tempIndex = parentAdapter.getIds().indexOf(articleId); if (tempIndex >= 0) currentIndex = tempIndex; return currentIndex; } private boolean doVibrate(int newIndex) { int tempIndex = 0; if (newIndex == 0 && lastMove != 0) { tempIndex = getCurrentIndex() + lastMove; } else { tempIndex = newIndex; } if (tempIndex < 0 || tempIndex >= parentAdapter.getCount()) { if (Controller.getInstance().vibrateOnLastArticle()) ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return true; } return false; } @Override public boolean dispatchTouchEvent(MotionEvent e) { boolean temp = super.dispatchTouchEvent(e); if (Controller.getInstance().useSwipe()) return mGestureDetector.onTouchEvent(e); else return temp; } private OnGestureListener onGestureListener = new OnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (!Controller.getInstance().useSwipe()) return false; float movement = 0; boolean isSwipe = false; int dx = (int) (e2.getX() - e1.getX()); int dy = (int) (e2.getY() - e1.getY()); if (Controller.landscape) { // LANDSCAPE // Don't accept the fling if it's too short as it may conflict with a button push if (Math.abs(dy) > Controller.swipeHeight && Math.abs(velocityY) > Math.abs(velocityX)) isSwipe = true; if (Math.abs(dx) > (int) (Controller.absWidth * 0.30)) return false; // Too much X-Movement (30% of screen-width) // Check if Swipe-Motion is inside the Swipe-Area if (Controller.getInstance().leftHanded()) { // Swipe-Area on LEFT side of the screen int swipeAreaPosition = Controller.swipeAreaWidth; if (e1.getX() > swipeAreaPosition || e2.getX() > swipeAreaPosition) { if (isSwipe) { // Display text for swipe-area swipeView.setVisibility(TextView.VISIBLE); new Handler().postDelayed(timerTask, 1000); } return false; } } else { // Swipe-Area on RIGHT side of the screen int swipeAreaPosition = webView.getWidth() - Controller.swipeAreaWidth; if (e1.getX() < swipeAreaPosition || e2.getX() < swipeAreaPosition) { if (isSwipe) { // Display text for swipe-area swipeView.setVisibility(TextView.VISIBLE); new Handler().postDelayed(timerTask, 1000); } return false; } } if (isSwipe) movement = velocityY; } else { // PORTRAIT int SWIPE_BOTTOM = webView.getHeight() - Controller.swipeAreaHeight; // Don't accept the fling if it's too short as it may conflict with a button push if (Math.abs(dx) > Controller.swipeWidth && Math.abs(velocityX) > Math.abs(velocityY)) isSwipe = true; if (Math.abs(dy) > (int) (Controller.absHeight * 0.2)) return false; // Too much Y-Movement (20% of screen-height) // Check if Swipe-Motion is inside the Swipe-Area if (e1.getY() < SWIPE_BOTTOM || e2.getY() < SWIPE_BOTTOM) { if (isSwipe) { // Display text for swipe-area swipeView.setVisibility(TextView.VISIBLE); new Handler().postDelayed(timerTask, 1000); } return false; } if (isSwipe) movement = velocityX; } if (isSwipe && movement != 0) { if (movement > 0) openNextArticle(-1); else openNextArticle(1); return true; } return false; } // @formatter:off private Runnable timerTask = new Runnable() { public void run() { // Need this to set the text invisible after some time swipeView.setVisibility(TextView.INVISIBLE); } }; @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public void onShowPress(MotionEvent e) { } // @formatter:on }; private OnClickListener onButtonPressedListener = new OnClickListener() { @Override public void onClick(View v) { if (v.equals(buttonNext)) openNextArticle(-1); else if (v.equals(buttonPrev)) openNextArticle(1); } }; public boolean onKeyDown(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { openNextArticle(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { openNextArticle(1); return true; } } return super.onKeyDown(keyCode, event); } public boolean onKeyUp(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) return true; } return super.onKeyUp(keyCode, event); } private OnKeyListener keyListener = new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_N) { openNextArticle(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_B) { openNextArticle(1); return true; } } return false; } }; private void openConnectionErrorDialog(String errorMessage) { Intent i = new Intent(this, ErrorActivity.class); i.putExtra(ErrorActivity.ERROR_MESSAGE, errorMessage); startActivityForResult(i, ErrorActivity.ACTIVITY_SHOW_ERROR); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ErrorActivity.ACTIVITY_SHOW_ERROR) doRefresh(); } private static StringBuilder injectAttachments(Context context, StringBuilder content, Set<String> attachments) { if (content == null) content = new StringBuilder(); for (String url : attachments) { if (url.length() == 0) continue; boolean image = false; for (String s : FileUtils.IMAGE_EXTENSIONS) { if (url.toLowerCase().contains("." + s)) image = true; } boolean audioOrVideo = false; for (String s : FileUtils.AUDIO_EXTENSIONS) { if (url.toLowerCase().contains("." + s)) audioOrVideo = true; } for (String s : FileUtils.VIDEO_EXTENSIONS) { if (url.toLowerCase().contains("." + s)) audioOrVideo = true; } content.append("<br>\n"); if (image) { content.append("<img src=\"").append(url).append("\" /><br>\n"); } else if (audioOrVideo) { content.append("<a href=\"").append(url).append("\">"); content.append((String) context.getText(R.string.ArticleActivity_MediaPlay)).append("</a>"); } else { content.append("<a href=\"").append(url).append("\">"); content.append((String) context.getText(R.string.ArticleActivity_MediaDisplayLink)).append("</a>"); } } return content; } private StringBuilder injectArticleLink(Context context, StringBuilder html) { if (!Controller.getInstance().injectArticleLink()) return html; if (article != null) { if ((article.url != null) && (article.url.length() > 0)) { html.append("<br>\n"); html.append("<a href=\"").append(article.url).append("\" rel=\"alternate\">"); html.append((String) context.getText(R.string.ArticleActivity_ArticleLink)); html.append("</a>"); } } return html; } /** * Injects the local path to every image which could be found in the local cache, replacing the original URLs in the * html. * * @param html * the original html * @return the altered html with the URLs replaced so they point on local files if available */ private static String injectCachedImages(String html, int articleId) { if (html == null || html.length() < 40) // Random. Chosen by fair dice-roll. return html; for (String url : ImageCacher.findAllImageUrls(html, articleId)) { String localUrl = ImageCacher.getCachedImageUrl(url); if (localUrl != null) { html = html.replace(url, localUrl); } } return html; } // @formatter:off @Override public void onUpdateEnd() { /* Not necessary here */ } @Override public void onUpdateProgress() { /* Not necessary here */ } // @formatter:on @Override public void onPublishNoteResult(Article a, String note) { new Updater(null, new PublishedStateUpdater(a, a.isPublished ? 0 : 1, note)).execute(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.fragments; import org.ttrssreader.gui.interfaces.IConfigurable; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.utils.Utils; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.View; import android.widget.ListView; public class FeedListFragment extends ListFragment { private static final TYPE THIS_TYPE = TYPE.FEED; public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_CAT_TITLE = "FEED_CAT_TITLE"; private static final String SELECTED_INDEX = "selectedIndex"; private static final int SELECTED_INDEX_DEFAULT = -1; private int selectedIndex = SELECTED_INDEX_DEFAULT; private int selectedIndexOld = SELECTED_INDEX_DEFAULT; // Extras private int categoryId; private String categoryTitle; private FeedAdapter adapter = null; private ListView listView; public static FeedListFragment newInstance(int id, String title) { // Create a new fragment instance FeedListFragment detail = new FeedListFragment(); detail.categoryId = id; detail.categoryTitle = title; detail.setHasOptionsMenu(true); return detail; } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); listView = getListView(); registerForContextMenu(listView); Bundle extras = getActivity().getIntent().getExtras(); if (extras != null) { categoryId = extras.getInt(FEED_CAT_ID); categoryTitle = extras.getString(FEED_CAT_TITLE); } else if (instance != null) { categoryId = instance.getInt(FEED_CAT_ID); categoryTitle = instance.getString(FEED_CAT_TITLE); selectedIndex = instance.getInt(SELECTED_INDEX, SELECTED_INDEX_DEFAULT); } adapter = new FeedAdapter(getActivity().getApplicationContext(), categoryId); setListAdapter(adapter); // Inject Adapter into activity. Don't know if this is the way to do stuff here... if (getActivity() instanceof IConfigurable) ((IConfigurable) getActivity()).setAdapter(adapter); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); outState.putString(FEED_CAT_TITLE, categoryTitle); super.onSaveInstanceState(outState); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (adapter == null) { Log.d(Utils.TAG, "Adapter shouldn't be null here..."); return; } selectedIndexOld = selectedIndex; selectedIndex = position; // Set selected item if (getActivity() instanceof IItemSelectedListener) ((IItemSelectedListener) getActivity()).itemSelected(THIS_TYPE, selectedIndex, selectedIndexOld); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.fragments; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.gui.interfaces.IConfigurable; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.CategoryAdapter; import org.ttrssreader.utils.Utils; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.View; import android.widget.ListView; public class CategoryListFragment extends ListFragment { private static final TYPE THIS_TYPE = TYPE.CATEGORY; private static final String SELECTED_INDEX = "selectedIndex"; private static final int SELECTED_INDEX_DEFAULT = -1; private int selectedIndex = SELECTED_INDEX_DEFAULT; private int selectedIndexOld = SELECTED_INDEX_DEFAULT; private CategoryAdapter adapter = null; private ListView listView; @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); listView = getListView(); registerForContextMenu(listView); adapter = new CategoryAdapter(getActivity().getApplicationContext()); setListAdapter(adapter); // Read the selected list item after orientation changes and similar if (instance != null) selectedIndex = instance.getInt(SELECTED_INDEX, SELECTED_INDEX_DEFAULT); // Inject Adapter into activity. Don't know if this is the way to do stuff here... if (getActivity() instanceof IConfigurable) ((IConfigurable) getActivity()).setAdapter(adapter); } @Override public void onResume() { super.onResume(); Controller.getInstance().lastOpenedFeed = null; Controller.getInstance().lastOpenedArticle = null; DBHelper.getInstance().checkAndInitializeDB(getActivity().getApplicationContext()); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (adapter == null) { Log.d(Utils.TAG, "Adapter shouldn't be null here..."); return; } selectedIndexOld = selectedIndex; selectedIndex = position; // Set selected item if (getActivity() instanceof IItemSelectedListener) ((IItemSelectedListener) getActivity()).itemSelected(THIS_TYPE, selectedIndex, selectedIndexOld); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; public class ArticleFragment extends Fragment { public static final String ARTICLE_ID = "ARTICLE_ID"; public static final String ARTICLE_FEED_ID = "ARTICLE_FEED_ID"; public static final String ARTICLE_MOVE = "ARTICLE_MOVE"; public static final int ARTICLE_MOVE_NONE = 0; public static final int ARTICLE_MOVE_DEFAULT = ARTICLE_MOVE_NONE; // private int articleId = -1; // private int feedId = -1; // private int categoryId = -1000; // private boolean selectArticlesForCategory = false; // private int lastMove = ARTICLE_MOVE_DEFAULT; // private WebView webview; public static ArticleFragment newInstance(int id, int feedId, int categoryId, boolean selectArticles, int lastMove) { // Create a new fragment instance ArticleFragment detail = new ArticleFragment(); // detail.articleId = id; // detail.feedId = feedId; // detail.categoryId = categoryId; // detail.selectArticlesForCategory = selectArticles; // detail.lastMove = lastMove; detail.setHasOptionsMenu(true); return detail; } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); // Bundle extras = getActivity().getIntent().getExtras(); // if (extras != null) { // articleId = extras.getInt(ARTICLE_ID); // feedId = extras.getInt(ARTICLE_FEED_ID); // categoryId = extras.getInt(FeedHeadlineActivity.FEED_CAT_ID); // selectArticlesForCategory = extras.getBoolean(FeedHeadlineActivity.FEED_SELECT_ARTICLES); // lastMove = extras.getInt(ARTICLE_MOVE); // } else if (instance != null) { // articleId = instance.getInt(ARTICLE_ID); // feedId = instance.getInt(ARTICLE_FEED_ID); // categoryId = instance.getInt(FeedHeadlineActivity.FEED_CAT_ID); // selectArticlesForCategory = instance.getBoolean(FeedHeadlineActivity.FEED_SELECT_ARTICLES); // lastMove = instance.getInt(ARTICLE_MOVE); // } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // outState.putInt(ARTICLE_ID, articleId); // outState.putInt(ARTICLE_FEED_ID, feedId); // outState.putInt(FeedHeadlineActivity.FEED_CAT_ID, categoryId); // outState.putBoolean(FeedHeadlineActivity.FEED_SELECT_ARTICLES, selectArticlesForCategory); // outState.putInt(ARTICLE_MOVE, lastMove); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui.fragments; import org.ttrssreader.gui.interfaces.IConfigurable; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.utils.Utils; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.View; import android.widget.ListView; public class FeedHeadlineListFragment extends ListFragment { private static final TYPE THIS_TYPE = TYPE.FEEDHEADLINE; public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_ID = "ARTICLE_FEED_ID"; public static final String FEED_TITLE = "FEED_TITLE"; public static final String FEED_SELECT_ARTICLES = "FEED_SELECT_ARTICLES"; public static final String FEED_INDEX = "INDEX"; private static final String SELECTED_INDEX = "selectedIndex"; private static final int SELECTED_INDEX_DEFAULT = -1; private int selectedIndex = SELECTED_INDEX_DEFAULT; private int selectedIndexOld = SELECTED_INDEX_DEFAULT; // Extras private int categoryId = -1000; private int feedId = -1000; private String feedTitle = null; private boolean selectArticlesForCategory = false; private FeedHeadlineAdapter adapter = null; private ListView listView; public static FeedHeadlineListFragment newInstance(int id, String title, int categoryId, boolean selectArticles) { // Create a new fragment instance FeedHeadlineListFragment detail = new FeedHeadlineListFragment(); detail.categoryId = categoryId; detail.feedId = id; detail.feedTitle = title; detail.selectArticlesForCategory = selectArticles; detail.setHasOptionsMenu(true); return detail; } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); listView = getListView(); registerForContextMenu(listView); Bundle extras = getActivity().getIntent().getExtras(); if (extras != null) { categoryId = extras.getInt(FEED_CAT_ID); feedId = extras.getInt(FEED_ID); feedTitle = extras.getString(FEED_TITLE); selectArticlesForCategory = extras.getBoolean(FEED_SELECT_ARTICLES); } else if (instance != null) { categoryId = instance.getInt(FEED_CAT_ID); feedId = instance.getInt(FEED_ID); feedTitle = instance.getString(FEED_TITLE); selectArticlesForCategory = instance.getBoolean(FEED_SELECT_ARTICLES); selectedIndex = instance.getInt(SELECTED_INDEX, SELECTED_INDEX_DEFAULT); } adapter = new FeedHeadlineAdapter(getActivity().getApplicationContext(), feedId, categoryId, selectArticlesForCategory); setListAdapter(adapter); // Inject Adapter into activity. Don't know if this is the way to do stuff here... if (getActivity() instanceof IConfigurable) ((IConfigurable) getActivity()).setAdapter(adapter); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); outState.putInt(FEED_ID, feedId); outState.putString(FEED_TITLE, feedTitle); outState.putBoolean(FEED_SELECT_ARTICLES, selectArticlesForCategory); super.onSaveInstanceState(outState); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (adapter == null) { Log.d(Utils.TAG, "Adapter shouldn't be null here..."); return; } selectedIndexOld = selectedIndex; selectedIndex = position; // Set selected item if (getActivity() instanceof IItemSelectedListener) ((IItemSelectedListener) getActivity()).itemSelected(THIS_TYPE, selectedIndex, selectedIndexOld); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.NotInitializedException; import org.ttrssreader.gui.fragments.ArticleFragment; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.model.MainAdapter; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.updaters.PublishedStateUpdater; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.Utils; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Vibrator; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; public class FeedHeadlineActivity extends MenuActivity implements TextInputAlertCallback { public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_ID = "ARTICLE_FEED_ID"; public static final String FEED_TITLE = "FEED_TITLE"; public static final String FEED_SELECT_ARTICLES = "FEED_SELECT_ARTICLES"; public static final String FEED_INDEX = "INDEX"; public static final int FEED_NO_ID = 37846914; public boolean flingDetected = false; // Extras private int categoryId = -1000; private int feedId = -1000; private String feedTitle = null; private boolean selectArticlesForCategory = false; private GestureDetector gestureDetector; private FeedHeadlineAdapter adapter = null; // Remember to explicitly check every access to adapter for it beeing // null! private FeedHeadlineUpdater headlineUpdater = null; private FeedAdapter parentAdapter = null; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); // Log.d(Utils.TAG, "onCreate - FeedHeadlineActivity"); setContentView(R.layout.feedheadlinelist); gestureDetector = new GestureDetector(onGestureListener); Bundle extras = getIntent().getExtras(); if (extras != null) { categoryId = extras.getInt(FEED_CAT_ID); feedId = extras.getInt(FEED_ID); feedTitle = extras.getString(FEED_TITLE); selectArticlesForCategory = extras.getBoolean(FEED_SELECT_ARTICLES); } else if (instance != null) { categoryId = instance.getInt(FEED_CAT_ID); feedId = instance.getInt(FEED_ID); feedTitle = instance.getString(FEED_TITLE); selectArticlesForCategory = instance.getBoolean(FEED_SELECT_ARTICLES); } Controller.getInstance().lastOpenedFeed = feedId; Controller.getInstance().lastOpenedArticle = null; parentAdapter = new FeedAdapter(getApplicationContext(), categoryId); } @Override protected void onResume() { super.onResume(); DBHelper.getInstance().checkAndInitializeDB(this); doRefresh(); doUpdate(); } private void closeCursor() { if (adapter != null) adapter.closeCursor(); if (parentAdapter != null) parentAdapter.closeCursor(); } @Override protected void onPause() { // First call super.onXXX, then do own clean-up. It actually makes a difference but I got no idea why. super.onPause(); closeCursor(); } @Override protected void onStop() { super.onStop(); closeCursor(); } @Override protected void onDestroy() { super.onDestroy(); closeCursor(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); outState.putInt(FEED_ID, feedId); outState.putString(FEED_TITLE, feedTitle); outState.putBoolean(FEED_SELECT_ARTICLES, selectArticlesForCategory); super.onSaveInstanceState(outState); } @Override protected void doRefresh() { int unreadCount = 0; if (selectArticlesForCategory) unreadCount = DBHelper.getInstance().getUnreadCount(categoryId, true); else unreadCount = DBHelper.getInstance().getUnreadCount(feedId, false); setTitle(MainAdapter.formatTitle(feedTitle, unreadCount)); flingDetected = false; // reset fling-status if (adapter != null) { adapter.makeQuery(true); adapter.notifyDataSetChanged(); } try { if (Controller.getInstance().getConnector().hasLastError()) openConnectionErrorDialog(Controller.getInstance().getConnector().pullLastError()); } catch (NotInitializedException e) { } if (headlineUpdater == null) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); } } @Override protected void doUpdate() { // Only update if no headlineUpdater already running if (headlineUpdater != null) { if (headlineUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { headlineUpdater = null; } else { return; } } if (!isCacherRunning()) { setProgressBarIndeterminateVisibility(true); setProgressBarVisibility(false); headlineUpdater = new FeedHeadlineUpdater(); headlineUpdater.execute(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Get selected Article AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Article a = (Article) adapter.getItem(info.position); menu.removeItem(MARK_READ); // Remove "Mark read" from super-class if (a.isUnread) { menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); } else { menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkUnread); } if (a.isStarred) { menu.add(MARK_GROUP, MARK_STAR, Menu.NONE, R.string.Commons_MarkUnstar); } else { menu.add(MARK_GROUP, MARK_STAR, Menu.NONE, R.string.Commons_MarkStar); } if (a.isPublished) { menu.add(MARK_GROUP, MARK_PUBLISH, Menu.NONE, R.string.Commons_MarkUnpublish); } else { menu.add(MARK_GROUP, MARK_PUBLISH, Menu.NONE, R.string.Commons_MarkPublish); menu.add(MARK_GROUP, MARK_PUBLISH_NOTE, Menu.NONE, R.string.Commons_MarkPublishNote); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); Article a = (Article) adapter.getItem(cmi.position); if (a == null) return false; switch (item.getItemId()) { case MARK_READ: new Updater(this, new ReadStateUpdater(a, feedId, a.isUnread ? 0 : 1)).execute(); break; case MARK_STAR: new Updater(this, new StarredStateUpdater(a, a.isStarred ? 0 : 1)).execute(); break; case MARK_PUBLISH: new Updater(this, new PublishedStateUpdater(a, a.isPublished ? 0 : 1)).execute(); break; case MARK_PUBLISH_NOTE: new TextInputAlert(this, a).show(this); break; default: return false; } doRefresh(); return true; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { boolean ret = super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.Menu_Refresh: if (selectArticlesForCategory) { Data.getInstance().resetTime(categoryId, false, true, false); } else { Data.getInstance().resetTime(feedId, false, false, true); } doUpdate(); return true; case R.id.Menu_MarkAllRead: if (selectArticlesForCategory) { new Updater(this, new ReadStateUpdater(categoryId)).execute(); } else { new Updater(this, new ReadStateUpdater(feedId, 42)).execute(); } return true; } if (ret) { doRefresh(); } return true; } private void openNextFeed(int direction) { if (feedId < 0) return; int currentIndex = -2; // -2 so index is still -1 if direction is +1, avoids moving when no move possible int tempIndex = parentAdapter.getIds().indexOf(feedId); if (tempIndex >= 0) currentIndex = tempIndex; int index = currentIndex + direction; // No more feeds in this direction if (index < 0 || index >= parentAdapter.getCount()) { if (Controller.getInstance().vibrateOnLastArticle()) ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return; } int id = parentAdapter.getId(index); String title = parentAdapter.getTitle(index); Intent i = new Intent(this, getClass()); i.putExtra(FEED_ID, id); i.putExtra(FEED_TITLE, title); i.putExtra(FEED_CAT_ID, categoryId); startActivityForResult(i, 0); finish(); } @Override public boolean dispatchTouchEvent(MotionEvent e) { super.dispatchTouchEvent(e); return gestureDetector.onTouchEvent(e); } private OnGestureListener onGestureListener = new OnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { int dx = (int) (e2.getX() - e1.getX()); int dy = (int) (e2.getY() - e1.getY()); if (Math.abs(dy) > (int) (Controller.absHeight * 0.2)) { return false; // Too much Y-Movement (20% of screen-height) } // don't accept the fling if it's too short as it may conflict with a button push if (Math.abs(dx) > Controller.swipeWidth && Math.abs(velocityX) > Math.abs(velocityY)) { flingDetected = true; if (velocityX > 0) { openNextFeed(-1); } else { openNextFeed(1); } return true; } return false; } // @formatter:off @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public void onShowPress(MotionEvent e) { } // @formatter:on }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_N) { openNextFeed(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_B) { openNextFeed(1); return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_N || keyCode == KeyEvent.KEYCODE_B) { return true; } } return super.onKeyUp(keyCode, event); } /** * * * @author n * */ public class FeedHeadlineUpdater extends AsyncTask<Void, Integer, Void> { private int taskCount = 0; private static final int DEFAULT_TASK_COUNT = 2; @Override protected Void doInBackground(Void... params) { taskCount = DEFAULT_TASK_COUNT; int progress = 0; boolean displayUnread = Controller.getInstance().onlyUnread(); if (selectArticlesForCategory) { publishProgress(++progress); // Move progress forward Data.getInstance().updateArticles(categoryId, displayUnread, true, false); } else { publishProgress(++progress); // Move progress forward Data.getInstance().updateArticles(feedId, displayUnread, false, false); } publishProgress(taskCount); // Move progress forward to 100% return null; } @Override protected void onProgressUpdate(Integer... values) { if (values[0] == taskCount) { setProgressBarIndeterminateVisibility(false); setProgressBarVisibility(false); doRefresh(); return; } setProgress((10000 / (taskCount + 1)) * values[0]); doRefresh(); } } @Override public void setAdapter(MainAdapter adapter) { if (adapter instanceof FeedHeadlineAdapter) this.adapter = (FeedHeadlineAdapter) adapter; } @Override public void itemSelected(TYPE type, int selectedIndex, int oldIndex) { // Log.d(Utils.TAG, this.getClass().getName() + " - itemSelected called. Type: " + type); if (adapter == null) { Log.d(Utils.TAG, "Adapter shouldn't be null here..."); return; } // Find out if we are using a wide screen ListFragment secondPane = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.details); if (secondPane != null && secondPane.isInLayout()) { Log.d(Utils.TAG, "Filling right pane... (" + selectedIndex + " " + oldIndex + ")"); // Set the list item as checked // getListView().setItemChecked(selectedIndex, true); // Get the fragment instance ArticleFragment articleView = (ArticleFragment) getSupportFragmentManager().findFragmentById( R.id.articleView); // Is the current selected ondex the same as the clicked? If so, there is no need to update if (articleView != null && selectedIndex == oldIndex) return; articleView = ArticleFragment.newInstance(adapter.getId(selectedIndex), feedId, categoryId, selectArticlesForCategory, ArticleActivity.ARTICLE_MOVE_DEFAULT); // Replace the old fragment with the new one FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.details, articleView); // Use a fade animation. This makes it clear that this is not a new "layer" // above the current, but a replacement ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } else { // This is not a tablet - start a new activity // if (!flingDetected) { // TODO: Think about what to do with the fling-gesture in a three-pane-layout. Intent i = new Intent(context, ArticleActivity.class); i.putExtra(ArticleActivity.ARTICLE_ID, adapter.getId(selectedIndex)); i.putExtra(ArticleActivity.ARTICLE_FEED_ID, feedId); i.putExtra(FeedHeadlineActivity.FEED_CAT_ID, categoryId); i.putExtra(FeedHeadlineActivity.FEED_SELECT_ARTICLES, selectArticlesForCategory); i.putExtra(ArticleActivity.ARTICLE_MOVE, ArticleActivity.ARTICLE_MOVE_DEFAULT); if (i != null) startActivity(i); // } } } public void onPublishNoteResult(Article a, String note) { new Updater(this, new PublishedStateUpdater(a, a.isPublished ? 0 : 1, note)).execute(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.gui; import org.ttrssreader.R; import org.ttrssreader.utils.Utils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.about); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_info); TextView versionText = (TextView) this.findViewById(R.id.AboutActivity_VersionText); versionText.setText(this.getString(R.string.AboutActivity_VersionText) + " " + Utils.getAppVersionName(this)); TextView licenseText = (TextView) this.findViewById(R.id.AboutActivity_LicenseText); licenseText.setText(this.getString(R.string.AboutActivity_LicenseText) + " " + this.getString(R.string.AboutActivity_LicenseTextValue)); TextView urlText = (TextView) this.findViewById(R.id.AboutActivity_UrlText); urlText.setText(this.getString(R.string.AboutActivity_UrlTextValue)); TextView thanksText = (TextView) this.findViewById(R.id.AboutActivity_ThanksText); thanksText.setText(this.getString(R.string.AboutActivity_ThanksTextValue)); Button closeBtn = (Button) this.findViewById(R.id.AboutActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { closeButtonPressed(); } }); Button donateBtn = (Button) this.findViewById(R.id.AboutActivity_DonateBtn); donateBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { donateButtonPressed(); } }); } private void closeButtonPressed() { this.finish(); } private void donateButtonPressed() { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.DonateUrl)))); this.finish(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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) { 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 N. 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 org.ttrssreader.utils.FileUtils; 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 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 USE_KEYSTORE_DEFAULT = false; public static final boolean USE_OF_A_LAZY_SERVER_DEFAULT = false; // Usage public static final String AUTOMATIC_MARK_READ = "UsageAutomaticMarkReadPreference"; public static final String OPEN_URL_EMPTY_ARTICLE = "UsageOpenUrlEmptyArticlePreference"; public static final String USE_VOLUME_KEYS = "UsageUseVolumeKeysPreference"; public static final String VIBRATE_ON_LAST_ARTICLE = "UsageVibrateOnLastArticlePreference"; public static final String WORK_OFFLINE = "UsageWorkOfflinePreference"; // Usage Default Values public static final boolean AUTOMATIC_MARK_READ_DEFAULT = true; public static final boolean OPEN_URL_EMPTY_ARTICLE_DEFAULT = false; public static final boolean USE_VOLUME_KEYS_DEFAULT = false; public static final boolean VIBRATE_ON_LAST_ARTICLE_DEFAULT = true; public static final boolean WORK_OFFLINE_DEFAULT = false; // Display public static final String SHOW_VIRTUAL = "DisplayShowVirtualPreference"; public static final String USE_SWIPE = "DisplayUseSwipePreference"; public static final String USE_BUTTONS = "DisplayUseButtonsPreference"; public static final String LEFT_HANDED = "DisplayLeftHandedPreference"; public static final String ONLY_UNREAD = "DisplayShowUnreadOnlyPreference"; public static final String ARTICLE_LIMIT = "DisplayArticleLimitPreference"; public static final String DISPLAY_ARTICLE_HEADER = "DisplayArticleHeaderPreference"; 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 INJECT_ARTICLE_LINK = "DisplayArticleLinkPreference"; 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 DARK_BACKGROUND = "DisplayDarkBackgroundPreference"; // Display Default Values public static final boolean SHOW_VIRTUAL_DEFAULT = true; public static final boolean USE_SWIPE_DEFAULT = true; public static final boolean USE_BUTTONS_DEFAULT = false; public static final boolean LEFT_HANDED_DEFAULT = false; public static final boolean ONLY_UNREAD_DEFAULT = false; public static final int ARTICLE_LIMIT_DEFAULT = 1000; public static final boolean DISPLAY_ARTICLE_HEADER_DEFAULT = true; 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 INJECT_ARTICLE_LINK_DEFAULT = true; 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 boolean DARK_BACKGROUND_DEFAULT = false; // System public static final String IMAGE_CACHE_SIZE = "StoreImageLimitPreference"; public static final String IMAGE_CACHE_UNREAD = "CacheImagesUnreadArticlesPreference"; public static final String SAVE_ATTACHMENT = "SaveAttachmentPreference"; public static final String CACHE_FOLDER = "CacheFolderPreference"; public static final String VACUUM_DB_SCHEDULED = "VacuumDBScheduledPreference"; public static final String DELETE_DB_SCHEDULED = "DeleteDBScheduledPreference"; public static final String DELETE_DB_ON_STARTUP = "DeleteDBOnStartupPreference"; public static final String SERVER_VERSION = "ServerVersion"; public static final String SERVER_VERSION_LAST_UPDATE = "ServerVersionLastUpdate"; public static final String CACHE_ON_STARTUP = "CacheOnStartupPreference"; public static final String CACHE_IMAGES_ON_STARTUP = "CacheImagesOnStartupPreference"; public static final String CACHE_IMAGES_ONLY_WIFI = "CacheImagesOnlyWifiPreference"; public static final String LOG_SENSITIVE_DATA = "LogSensitiveDataPreference"; // System Default Values public static final int IMAGE_CACHE_SIZE_DEFAULT = 50; public static final boolean IMAGE_CACHE_UNREAD_DEFAULT = true; public static final String SAVE_ATTACHMENT_DEFAULT; public static final String CACHE_FOLDER_DEFAULT; public static final boolean VACUUM_DB_SCHEDULED_DEFAULT = false; public static final boolean DELETE_DB_SCHEDULED_DEFAULT = false; public static final boolean DELETE_DB_ON_STARTUP_DEFAULT = false; public static final int SERVER_VERSION_DEFAULT = -1; public static final long SERVER_VERSION_LAST_UPDATE_DEFAULT = -1; public static final boolean CACHE_ON_STARTUP_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 LOG_SENSITIVE_DATA_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 DATABASE_VERSION = "DatabaseVersion"; public static final String LAST_UPDATE_TIME = "LastUpdateTime"; public static final String LAST_VERSION_RUN = "LastVersionRun"; public static final String LAST_VACUUM_DATE = "lastVacuumDate"; // 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 int DATABASE_VERSION_DEFAULT = 1; public static final long LAST_UPDATE_TIME_DEFAULT = 1; public static final String LAST_VERSION_RUN_DEFAULT = "1"; public static final long LAST_VACUUM_DATE_DEFAULT = 0; /* * 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() + camelCaseString.substring(1); } static String toProperCase(String s) { return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.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.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.utils.Utils; import android.content.Context; import android.net.ConnectivityManager; import android.util.Log; public class Data { public static final int VCAT_UNCAT = 0; public static final int VCAT_STAR = -1; public static final int VCAT_PUB = -2; public static final int VCAT_FRESH = -3; public static final int VCAT_ALL = -4; private static Data instance = null; private Context context; private long countersUpdated = 0; private long articlesCached = 0; private Map<Integer, Long> articlesUpdated = new HashMap<Integer, Long>(); private Map<Integer, Long> feedsUpdated = new HashMap<Integer, Long>(); private long virtCategoriesUpdated = 0; private long categoriesUpdated = 0; private Map<Integer, Long> articlesChanged = new HashMap<Integer, Long>(); private Map<Integer, Long> feedsChanged = new HashMap<Integer, Long>(); private long categoriesChanged = 0; private ConnectivityManager cm; // Singleton private Data() { } public static Data getInstance() { if (instance == null) { synchronized (Data.class) { if (instance == null) instance = new Data(); } } return instance; } public synchronized void checkAndInitializeData(final Context context) { this.context = context; if (context != null) cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } public long getArticlesChanged(int feedId) { if (articlesChanged.get(feedId) == null) return -1; else return articlesChanged.get(feedId); } public long getFeedsChanged(int categoryId) { if (feedsChanged.get(categoryId) == null) return -1; else return feedsChanged.get(categoryId); } public long getCategoriesChanged() { if (categoriesChanged == 0) return -1; else return categoriesChanged; } public void setArticlesChanged(int feedId, long time) { if (articlesChanged.get(feedId) == null || articlesChanged.get(feedId) < time) articlesChanged.put(feedId, time); } public void setFeedsChanged(int categoryId, long time) { if (feedsChanged.get(categoryId) == null || feedsChanged.get(categoryId) < time) feedsChanged.put(categoryId, time); } public void setCategoriesChanged(long time) { if (categoriesChanged < time) categoriesChanged = time; } // *** COUNTERS ********************************************************************* public void resetTime(int id, boolean isCat, boolean isFeed, boolean isArticle) { if (isCat) { // id doesn't matter virtCategoriesUpdated = 0; categoriesUpdated = 0; categoriesChanged = 0; countersUpdated = 0; } if (isFeed) { feedsUpdated.put(id, new Long(0)); // id == categoryId feedsChanged.put(id, new Long(0)); // id == categoryId } if (isArticle) { articlesUpdated.put(id, new Long(0)); // id == feedId articlesChanged.put(id, new Long(0)); // id == feedId } } public void updateCounters(boolean overrideOffline) { if (countersUpdated > System.currentTimeMillis() - Utils.HALF_UPDATE_TIME) { // Update counters more often.. return; } else if (Utils.isConnected(cm) || overrideOffline) { try { if (Controller.getInstance().getConnector().getCounters()) countersUpdated = System.currentTimeMillis(); // Only mark as updated if the call was successful } catch (NotInitializedException e) { } } } // *** ARTICLES ********************************************************************* public void cacheArticles(boolean overrideOffline) { int limit = 500; if (articlesCached > System.currentTimeMillis() - Utils.UPDATE_TIME) { return; } else if (Utils.isConnected(cm) || (overrideOffline && Utils.checkConnected(cm))) { try { int sinceId = DBHelper.getInstance().getSinceId(); int count = Controller.getInstance().getConnector() .getHeadlinesToDatabase(-4, limit, "all_articles", true, sinceId, 0); if (count == limit) { Controller.getInstance().getConnector() .getHeadlinesToDatabase(-4, limit, "all_articles", true, sinceId, 0); // TODO: Think! What do we do when the limit is reached? Set the limit higher or fetch another 500? // What if this is a new installation, shall we bulk-load ALL articles (because this is what happens // if we start fetching the next 500 and so on)? // Just doing it twice for now, 1000 articles offline should be fine for most people. } // Only mark as updated if the first call was successful if (count != -1) { articlesCached = System.currentTimeMillis(); // Store all category-ids and ids of all feeds for this category in db articlesUpdated.put(-4, articlesCached); articlesChanged.put(-4, articlesCached); for (Feed f : DBHelper.getInstance().getFeeds(-3)) { articlesUpdated.put(f.id, articlesCached); articlesChanged.put(f.id, articlesCached); } } } catch (NotInitializedException e) { } } } public void updateArticles(int feedId, boolean displayOnlyUnread, boolean isCat, boolean overrideOffline) { Log.d(Utils.TAG, String.format("feedId: %s, displayOnlyUnread: %s, isCat: %s, overrideOffline: %s", feedId, displayOnlyUnread, isCat, overrideOffline)); // Check if unread-count and actual number of unread articles match, if not do a seperate call with // displayOnlyUnread=true boolean needUnreadUpdate = false; if (!isCat && !displayOnlyUnread) { int unreadCount = DBHelper.getInstance().getUnreadCount(feedId, false); int actualUnread = DBHelper.getInstance().getUnreadArticles(feedId).size(); if (unreadCount > actualUnread) { needUnreadUpdate = true; articlesUpdated.put(feedId, System.currentTimeMillis() - Utils.UPDATE_TIME - 1000); } } Long time = articlesUpdated.get(feedId); if (time == null) time = new Long(0); if (time > System.currentTimeMillis() - Utils.UPDATE_TIME) { return; } else if (Utils.isConnected(cm) || (overrideOffline && Utils.checkConnected(cm))) { if (feedId == VCAT_PUB || feedId == VCAT_STAR) displayOnlyUnread = false; // Display all articles for Starred/Published // Calculate an appropriate upper limit for the number of articles int limit = calculateLimit(feedId, displayOnlyUnread, isCat); try { String viewMode = (displayOnlyUnread ? "unread" : "all_articles"); int count = Controller.getInstance().getConnector() .getHeadlinesToDatabase(feedId, limit, viewMode, isCat); // If necessary and not displaying only unread articles: Refresh unread articles to get them too. if (needUnreadUpdate && !displayOnlyUnread) Controller.getInstance().getConnector().getHeadlinesToDatabase(feedId, limit, "unread", isCat); // Only mark as updated if the first call was successful if (count != -1) { long currentTime = System.currentTimeMillis(); // Store requested feed-/category-id and ids of all feeds in db for this category if a category was // requested articlesUpdated.put(feedId, currentTime); articlesChanged.put(feedId, currentTime); if (isCat) { for (Feed f : DBHelper.getInstance().getFeeds(feedId)) { articlesUpdated.put(f.id, currentTime); articlesChanged.put(f.id, currentTime); } } } } catch (NotInitializedException e) { } } } /* * Calculate an appropriate upper limit for the number of articles */ private int calculateLimit(int feedId, boolean displayOnlyUnread, boolean isCat) { int limit = 50; switch (feedId) { case VCAT_STAR: // Starred case VCAT_PUB: // Published limit = 300; 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 (limit <= 0 && displayOnlyUnread) limit = 50; // No unread articles, fetch some stuff else if (limit <= 0) limit = 100; // No unread, fetch some to make sure we are at least a bit up-to-date else if (limit > 300) limit = 300; // Lots of unread articles, fetch the first 300 if (limit < 300) { if (isCat) limit = limit + 50; // Add some so we have a chance of getting not only the newest and possibly read // articles but also older ones. else limit = limit + 15; // Less on feed, more on category... } return limit; } // *** FEEDS ************************************************************************ public Set<Feed> updateFeeds(int categoryId, boolean overrideOffline) { Long time = feedsUpdated.get(categoryId); if (time == null) time = new Long(0); if (time > System.currentTimeMillis() - Utils.UPDATE_TIME) { return null; } else if (Utils.isConnected(cm) || (overrideOffline && Utils.checkConnected(cm))) { try { Set<Feed> ret = new LinkedHashSet<Feed>(); Set<Feed> feeds = Controller.getInstance().getConnector().getFeeds(); // Only delete feeds if we got new feeds... if (!feeds.isEmpty()) { DBHelper.getInstance().deleteFeeds(); for (Feed f : feeds) { if (categoryId == VCAT_ALL || f.categoryId == categoryId) ret.add(f); } DBHelper.getInstance().insertFeeds(feeds); // Store requested category-id and ids of all received feeds feedsUpdated.put(categoryId, System.currentTimeMillis()); feedsChanged.put(categoryId, System.currentTimeMillis()); for (Feed f : feeds) { feedsUpdated.put(f.categoryId, System.currentTimeMillis()); feedsChanged.put(f.categoryId, System.currentTimeMillis()); } } return ret; } catch (NotInitializedException e) { } } return null; } // *** CATEGORIES ******************************************************************* public Set<Category> updateVirtualCategories() { if (virtCategoriesUpdated > 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); virtCategoriesUpdated = System.currentTimeMillis(); return vCats; } public Set<Category> updateCategories(boolean overrideOffline) { if (categoriesUpdated > System.currentTimeMillis() - Utils.UPDATE_TIME) { return null; } else if (Utils.isConnected(cm) || overrideOffline) { try { Set<Category> categories = Controller.getInstance().getConnector().getCategories(); if (!categories.isEmpty()) { DBHelper.getInstance().deleteCategories(false); DBHelper.getInstance().insertCategories(categories); categoriesUpdated = System.currentTimeMillis(); categoriesChanged = System.currentTimeMillis(); } return categories; } catch (NotInitializedException e) { } } return null; } // *** STATUS ******************************************************************* public void setArticleRead(Set<Integer> ids, int articleState) { boolean erg = false; if (Utils.isConnected(cm)) try { erg = Controller.getInstance().getConnector().setArticleRead(ids, articleState); } catch (NotInitializedException e) { return; } 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)) try { erg = Controller.getInstance().getConnector().setArticleStarred(ids, articleState); } catch (NotInitializedException e) { return; } 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)) try { erg = Controller.getInstance().getConnector().setArticlePublished(ids, articleState); } catch (NotInitializedException e) { return; } // 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); } } public void setRead(int id, boolean isCategory) { boolean erg = false; if (Utils.isConnected(cm)) { try { erg = Controller.getInstance().getConnector().setRead(id, isCategory); } catch (NotInitializedException e) { return; } } if (isCategory || id < 0) { DBHelper.getInstance().markCategoryRead(id); if (!erg) DBHelper.getInstance().markUnsynchronizedStatesCategory(id); } else { DBHelper.getInstance().markFeedRead(id); if (!erg) DBHelper.getInstance().markUnsynchronizedStatesFeed(id); } } public String getPref(String pref) { if (Utils.isConnected(cm)) try { return Controller.getInstance().getConnector().getPref(pref); } catch (NotInitializedException e) { return null; } return null; } public int getVersion() { if (Utils.isConnected(cm)) try { return Controller.getInstance().getConnector().getVersion(); } catch (NotInitializedException e) { return -1; } return -1; } public int getApiLevel() { if (Utils.isConnected(cm)) try { return Controller.getInstance().getConnector().getApiLevel(); } catch (NotInitializedException e) { return -1; } return -1; } public void synchronizeStatus() throws NotInitializedException { if (!Utils.isConnected(cm)) return; 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); } } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.FilenameFilter; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.utils.FileDateComparator; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.util.Log; public class DBHelper { private static DBHelper instance = null; private boolean initialized = false; private boolean vacuumDone = false; private static final ReentrantReadWriteLock dbReadLock = new ReentrantReadWriteLock(); public static final String DATABASE_NAME = "ttrss.db"; public static final String DATABASE_BACKUP_NAME = "_backup_"; public static final int DATABASE_VERSION = 51; 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"; // Careful with locking, we don't dbReadLock // on this // table but instead on TABLE_ARTICLES public static final String TABLE_LABELS = "labels"; public static final String TABLE_MARK = "marked"; 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 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)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, coalesce((SELECT cachedImages FROM " + TABLE_ARTICLES + " WHERE id=?), 0))"; // 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 (?, ?)"; // @formatter:on private Context context; public SQLiteDatabase db; private SQLiteStatement insertCategory; private SQLiteStatement insertFeed; private SQLiteStatement insertArticle; private SQLiteStatement insertLabel; // Singleton private DBHelper() { } public static DBHelper getInstance() { synchronized (DBHelper.class) { if (instance == null) { instance = new DBHelper(); } } return instance; } public synchronized void checkAndInitializeDB(final Context context) { this.context = context; // Check if deleteDB is scheduled or if DeleteOnStartup is set if (Controller.getInstance().isDeleteDBScheduled()) { if (deleteDB()) { initialized = initializeDBHelper(); Controller.getInstance().resetDeleteDBScheduled(); return; // Don't need to check if DB is corrupted, it is NEW! } } // Initialize DB if (!initialized) { initialized = initializeDBHelper(); } else if (db == null || !db.isOpen()) { initialized = initializeDBHelper(); } // Test if DB is accessible, backup and delete if not, else do the vacuuming 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.w(Utils.TAG, "Database was corrupted, creating a new one..."); closeDB(); backupAndRemoveDB(); // Initialize again... initialized = initializeDBHelper(); } finally { if (c != null) c.close(); } // Do VACUUM if necessary and hasn't been done yet if (Controller.getInstance().isVacuumDBScheduled() && !vacuumDone) { Log.i(Utils.TAG, "Doing VACUUM, this can take a while..."); // Reset scheduling-data Controller.getInstance().setVacuumDBScheduled(false); Controller.getInstance().setLastVacuumDate(); // call vacuum vacuum(); } } } private synchronized void backupAndRemoveDB() { // Move DB-File to backup File f = context.getDatabasePath(DATABASE_NAME); f.renameTo(new File(f.getAbsolutePath() + DATABASE_BACKUP_NAME + System.currentTimeMillis())); // Find setReadble method in old api try { Class<?> cls = SharedPreferences.Editor.class; Method m = cls.getMethod("setReadble"); m.invoke(f, true, false); } catch (Exception e1) { } // Check if there are too many old backups FilenameFilter fnf = new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.contains(DATABASE_BACKUP_NAME)) return true; return false; } }; File[] backups = f.getParentFile().listFiles(fnf); if (backups != null && backups.length > 3) { // Sort list of files by last access date List<File> list = Arrays.asList(backups); Collections.sort(list, new FileDateComparator()); for (int i = list.size(); i > 2; i++) { // Delete all except the 2 newest backups list.get(i).delete(); } } } private synchronized boolean initializeDBHelper() { if (context == null) { Log.e(Utils.TAG, "Can't handle internal DB without Context-Object."); return false; } if (db != null) closeDB(); OpenHelper openHelper = new OpenHelper(context); db = openHelper.getWritableDatabase(); db.setLockingEnabled(false); insertCategory = db.compileStatement(INSERT_CATEGORY); insertFeed = db.compileStatement(INSERT_FEED); insertArticle = db.compileStatement(INSERT_ARTICLE); insertLabel = db.compileStatement(INSERT_LABEL); return true; } private boolean deleteDB() { if (context == null) return false; if (db != null) { closeDB(); } Log.w(Utils.TAG, "Deleting Database as requested by preferences."); File f = context.getDatabasePath(DATABASE_NAME); if (f.exists()) return f.delete(); return false; } private void closeDB() { // Close DB, acquire all locks to make sure no other threads have write-access to the DB right now. synchronized (TABLE_ARTICLES) { synchronized (TABLE_FEEDS) { synchronized (TABLE_CATEGORIES) { synchronized (TABLE_MARK) { dbReadLock.writeLock().lock(); db.close(); db = null; dbReadLock.writeLock().unlock(); } } } } } private boolean isDBAvailable() { boolean ret = false; if (db != null && db.isOpen()) { ret = true; } else if (db != null) { OpenHelper openHelper = new OpenHelper(context); db = openHelper.getWritableDatabase(); initialized = db.isOpen(); ret = initialized; } else { Log.i(Utils.TAG, "Controller not initialized, trying to do that now..."); initialized = initializeDBHelper(); ret = initialized; } if (ret) dbReadLock.readLock().lock(); return ret; } private static class OpenHelper extends SQLiteOpenHelper { OpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { // @formatter:off db.execSQL( "CREATE TABLE " + TABLE_CATEGORIES + " (id INTEGER PRIMARY KEY," + " title TEXT," + " unread INTEGER)"); db.execSQL( "CREATE TABLE " + TABLE_FEEDS + " (id INTEGER PRIMARY KEY," + " categoryId INTEGER," + " title TEXT," + " url TEXT," + " unread INTEGER)"); db.execSQL( "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)"); db.execSQL( "CREATE TABLE " + TABLE_ARTICLES2LABELS + " (articleId INTEGER," + " labelId INTEGER, PRIMARY KEY(articleId, labelId))"); db.execSQL("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 } /** * @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(Utils.TAG, String.format("Upgrading database from %s to 40.", oldVersion)); Log.i(Utils.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(Utils.TAG, String.format("Upgrading database from %s to 42.", oldVersion)); Log.i(Utils.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(Utils.TAG, String.format("Upgrading database from %s to 45.", oldVersion)); Log.i(Utils.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(Utils.TAG, String.format("Upgrading database from %s to 46.", oldVersion)); Log.i(Utils.TAG, String.format(" (Executing: %s", sql)); Log.i(Utils.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(Utils.TAG, String.format("Upgrading database from %s to 47.", oldVersion)); Log.i(Utils.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(Utils.TAG, String.format("Upgrading database from %s to 48.", oldVersion)); Log.i(Utils.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(Utils.TAG, String.format("Upgrading database from %s to 49.", oldVersion)); Log.i(Utils.TAG, String.format(" (Executing: %s", sql)); db.execSQL(sql); didUpgrade = true; } if (oldVersion < 50) { Log.i(Utils.TAG, String.format("Upgrading database from %s to 50.", oldVersion)); ContentValues cv = new ContentValues(); 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(Utils.TAG, String.format("Upgrading database from %s to 51.", oldVersion)); Log.i(Utils.TAG, String.format(" (Executing: %s", sql)); Log.i(Utils.TAG, String.format(" (Executing: %s", sql2)); db.execSQL(sql); db.execSQL(sql2); didUpgrade = true; } if (didUpgrade == false) { Log.w(Utils.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); onCreate(db); } } } /** * Used by MainAdapter to directly access the DB and get a cursor for the ListViews. * * @see android.database.sqlite.SQLiteDatabase#rawQuery(String, String[]) */ public Cursor query(String sql, String[] selectionArgs) { return db.rawQuery(sql, selectionArgs); } public Cursor queryArticlesForImageCache(boolean onlyUnreadImages) { // Add where-clause for only unread articles String where = "cachedImages=0"; if (onlyUnreadImages) where += " AND isUnread>0"; return db.query(TABLE_ARTICLES, new String[] { "id", "content", "attachments" }, where, null, null, null, null); } // *******| INSERT |******************************************************************* private void insertCategory(int id, String title, int unread) { if (!isDBAvailable()) return; if (title == null) title = ""; synchronized (TABLE_CATEGORIES) { insertCategory.bindLong(1, id); insertCategory.bindString(2, title); insertCategory.bindLong(3, unread); insertCategory.execute(); } dbReadLock.readLock().unlock(); } public void insertCategories(Set<Category> set) { if (set == null) return; for (Category c : set) { insertCategory(c.id, c.title, c.unread); } } private void insertFeed(int id, int categoryId, String title, String url, int unread) { if (!isDBAvailable()) return; if (title == null) title = ""; if (url == null) url = ""; synchronized (TABLE_FEEDS) { insertFeed.bindLong(1, new Integer(id).longValue()); insertFeed.bindLong(2, new Integer(categoryId).longValue()); insertFeed.bindString(3, title); insertFeed.bindString(4, url); insertFeed.bindLong(5, unread); insertFeed.execute(); } dbReadLock.readLock().unlock(); } private void insertFeed(Feed f) { if (f == null) return; insertFeed(f.id, f.categoryId, f.title, f.url, f.unread); } public void insertFeeds(Set<Feed> set) { if (set == null) return; for (Feed f : set) { insertFeed(f); } } public void insertArticle(int id, int feedId, String title, boolean isUnread, String articleUrl, String articleCommentUrl, Date updateDate, String content, Set<String> attachments, boolean isStarred, boolean isPublished, int label) { if (!isDBAvailable()) return; if (title == null) title = ""; if (content == null) content = ""; if (articleUrl == null) articleUrl = ""; if (articleCommentUrl == null) articleCommentUrl = ""; if (updateDate == null) updateDate = new Date(); if (attachments == null) attachments = new LinkedHashSet<String>(); long retId = -1; synchronized (TABLE_ARTICLES) { insertArticle.bindLong(1, id); insertArticle.bindLong(2, feedId); insertArticle.bindString(3, title); insertArticle.bindLong(4, (isUnread ? 1 : 0)); insertArticle.bindString(5, articleUrl); insertArticle.bindString(6, articleCommentUrl); insertArticle.bindLong(7, updateDate.getTime()); insertArticle.bindString(8, content); insertArticle.bindString(9, parseAttachmentSet(attachments)); insertArticle.bindLong(10, (isStarred ? 1 : 0)); insertArticle.bindLong(11, (isPublished ? 1 : 0)); insertArticle.bindLong(12, id); // ID again for the where-clause retId = insertArticle.executeInsert(); } if (retId > 0) insertLabel(id, label); dbReadLock.readLock().unlock(); } public static Object[] prepareArticleArray(int id, int feedId, String title, boolean isUnread, String articleUrl, String articleCommentUrl, Date updateDate, String content, Set<String> attachments, boolean isStarred, boolean isPublished, int label) { Object[] ret = new Object[11]; ret[0] = id; ret[1] = feedId; ret[2] = (title == null ? "" : title); ret[3] = (isUnread ? 1 : 0); ret[4] = (articleUrl == null ? "" : articleUrl);; ret[5] = (articleCommentUrl == null ? "" : articleCommentUrl);; ret[6] = updateDate.getTime(); ret[7] = (content == null ? "" : content);; ret[8] = parseAttachmentSet(attachments); ret[9] = (isStarred ? 1 : 0); ret[10] = (isPublished ? 1 : 0); return ret; } /** * New method of inserting many articles into the DB at once. Doesn't seem to run faster then the old way so i'll * just leave this code here for future reference and ignore it until it proves to be useful. * * @param input * Object-Array with the fields of an article-object. */ public void bulkInsertArticles(List<Object[]> input) { if (!isDBAvailable()) return; if (input == null || input.isEmpty()) return; StringBuilder stmt = new StringBuilder(); stmt.append("INSERT OR REPLACE INTO " + TABLE_ARTICLES); Object[] entry = input.get(0); stmt.append(" SELECT "); stmt.append(entry[0] + " AS id, "); stmt.append(entry[1] + " AS feedId, "); stmt.append(DatabaseUtils.sqlEscapeString(entry[2] + "") + " AS title, "); stmt.append(entry[3] + " AS isUnread, "); stmt.append("'" + entry[4] + "' AS articleUrl, "); stmt.append("'" + entry[5] + "' AS articleCommentUrl, "); stmt.append(entry[6] + " AS updateDate, "); stmt.append(DatabaseUtils.sqlEscapeString(entry[7] + "") + " AS content, "); stmt.append("'" + entry[8] + "' AS attachments, "); stmt.append(entry[9] + " AS isStarred, "); stmt.append(entry[10] + " AS isPublished, "); stmt.append("coalesce((SELECT cachedImages FROM articles WHERE id=" + entry[0] + "), 0) AS cachedImages UNION"); for (int i = 1; i < input.size(); i++) { entry = input.get(i); stmt.append(" SELECT "); for (int j = 0; j < entry.length; j++) { if (j == 2 || j == 7) { // Escape and enquote Content and Title, they can contain quotes stmt.append(DatabaseUtils.sqlEscapeString(entry[j] + "")); } else if (j == 4 || j == 5 || j == 8) { // Just enquote Text-Fields stmt.append("'" + entry[j] + "'"); } else { // Leave numbers.. stmt.append(entry[j]); } if (j < (entry.length - 1)) stmt.append(", "); if (j == (entry.length - 1)) stmt.append(", coalesce((SELECT cachedImages FROM articles WHERE id=" + entry[0] + "), 0)"); } if (i < input.size() - 1) stmt.append(" UNION "); } // long retId = -1; synchronized (TABLE_ARTICLES) { db.execSQL(stmt.toString()); } // if (retId > 0) // insertLabel(id, label); dbReadLock.readLock().unlock(); } private void insertLabel(int articleId, int label) { if (label < -10) { synchronized (TABLE_ARTICLES) { insertLabel.bindLong(1, articleId); insertLabel.bindLong(2, label); insertLabel.executeInsert(); } } } // *******| UPDATE |******************************************************************* public void markCategoryRead(int categoryId) { if (isDBAvailable()) { updateCategoryUnreadCount(categoryId, 0); for (Feed f : getFeeds(categoryId)) { markFeedRead(f.id); } } dbReadLock.readLock().unlock(); } public void markFeedRead(int feedId) { if (isDBAvailable()) { String[] cols = new String[] { "isStarred", "isPublished", "updateDate" }; Cursor c = db.query(TABLE_ARTICLES, cols, "isUnread>0 AND feedId=" + feedId, null, null, null, null); int countStar = 0; int countPub = 0; int countFresh = 0; int countAll = 0; long ms = System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge(); Date maxAge = new Date(ms); if (c.moveToFirst()) { while (true) { countAll++; if (c.getInt(0) > 0) countStar++; if (c.getInt(1) > 0) countPub++; Date d = new Date(c.getLong(2)); if (d.after(maxAge)) countFresh++; if (!c.move(1)) break; } } c.close(); updateCategoryDeltaUnreadCount(Data.VCAT_STAR, countStar * -1); updateCategoryDeltaUnreadCount(Data.VCAT_PUB, countPub * -1); updateCategoryDeltaUnreadCount(Data.VCAT_FRESH, countFresh * -1); updateCategoryDeltaUnreadCount(Data.VCAT_ALL, countAll * -1); updateFeedUnreadCount(feedId, 0); synchronized (TABLE_ARTICLES) { if (feedId < -10) { markLabelRead(feedId); } else { ContentValues cv = new ContentValues(); cv.put("isUnread", 0); db.update(TABLE_ARTICLES, cv, "isUnread>0 AND feedId=" + feedId, null); } } } dbReadLock.readLock().unlock(); } public void markLabelRead(int labelId) { if (isDBAvailable()) { synchronized (TABLE_ARTICLES) { ContentValues cv = new ContentValues(); cv.put("isUnread", 0); String idList = "SELECT id FROM " + TABLE_ARTICLES + " AS a, " + TABLE_ARTICLES2LABELS + " as l WHERE a.id=l.articleId AND l.labelId=" + labelId; synchronized (TABLE_ARTICLES) { db.update(TABLE_ARTICLES, cv, "isUnread>0 AND id IN(" + idList + ")", null); } } } dbReadLock.readLock().unlock(); } // Marks only the articles as read so the JSONConnector can retrieve new articles and overwrite the old articles public void markFeedOnlyArticlesRead(int feedId, boolean isCat) { if (!isCat && feedId < -10) { markLabelRead(feedId); return; } if (isDBAvailable()) { ContentValues cv = new ContentValues(); cv.put("isUnread", 0); // Mark all articles from feed or category as read, depending on isCat. Just use idList with only one feedId // if it is just a feed, else create a list of feedIds. String idList = ""; if (isCat) idList = "SELECT id FROM " + TABLE_FEEDS + " WHERE categoryId=" + feedId; else idList = feedId + ""; synchronized (TABLE_ARTICLES) { db.update(TABLE_ARTICLES, cv, "isUnread>0 AND feedId IN(" + idList + ")", null); } } dbReadLock.readLock().unlock(); } public void markArticles(Set<Integer> iDlist, String mark, int state) { if (isDBAvailable()) { for (Integer id : iDlist) { markArticle(id, mark, state); } } } public void markArticle(int id, String mark, int state) { if (isDBAvailable()) { synchronized (TABLE_ARTICLES) { String sql = String.format("UPDATE %s SET %s=%s WHERE id=%s", TABLE_ARTICLES, mark, state, id); db.execSQL(sql); } } dbReadLock.readLock().unlock(); } public void markUnsynchronizedStatesCategory(int categoryId) { Set<Integer> ids = new HashSet<Integer>(); for (Feed f : getFeeds(categoryId)) { if (f.unread > 0) { for (Article a : getUnreadArticles(f.id)) { ids.add(a.id); } } } markUnsynchronizedStates(ids, MARK_READ, 0); } public void markUnsynchronizedStatesFeed(int feedId) { Feed f = getFeed(feedId); if (f != null && f.unread > 0) { Set<Integer> ids = new HashSet<Integer>(); for (Article a : getUnreadArticles(f.id)) { ids.add(a.id); } markUnsynchronizedStates(ids, MARK_READ, 0); } } public void markUnsynchronizedStates(Set<Integer> ids, String mark, int state) { if (!isDBAvailable()) return; // 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! // } synchronized (TABLE_MARK) { 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)); } } dbReadLock.readLock().unlock(); } // 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; synchronized (TABLE_MARK) { for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; ContentValues cv = new ContentValues(); cv.put(MARK_NOTE, note); db.update(TABLE_MARK, cv, "id=" + id, null); } } dbReadLock.readLock().unlock(); } public void updateCategoryUnreadCount(int id) { } public void updateCategoryUnreadCount(int id, int count) { if (isDBAvailable() && count >= 0) { ContentValues cv = new ContentValues(); cv.put("unread", count); synchronized (TABLE_CATEGORIES) { db.update(TABLE_CATEGORIES, cv, "id=?", new String[] { id + "" }); } } dbReadLock.readLock().unlock(); } public void updateCategoryDeltaUnreadCount(int id, int delta) { Category c = getCategory(id); int count = c.unread; count += delta; updateCategoryUnreadCount(id, count); } public void updateFeedUnreadCount(int id, int count) { if (isDBAvailable() && count >= 0) { ContentValues cv = new ContentValues(); cv.put("unread", count); synchronized (TABLE_FEEDS) { db.update(TABLE_FEEDS, cv, "id=?", new String[] { id + "" }); } } dbReadLock.readLock().unlock(); } public void updateFeedDeltaUnreadCount(int id, int delta) { Feed f = getFeed(id); int count = f.unread; count += delta; updateFeedUnreadCount(id, count); } public void updateAllArticlesCachedImages(boolean isCachedImages) { if (isDBAvailable()) { ContentValues cv = new ContentValues(); cv.put("cachedImages", isCachedImages); synchronized (TABLE_ARTICLES) { db.update(TABLE_ARTICLES, cv, "cachedImages=0", null); // Only apply if not yet applied } } dbReadLock.readLock().unlock(); } public void updateArticleCachedImages(int id, boolean isCachedImages) { if (isDBAvailable()) { ContentValues cv = new ContentValues(); cv.put("cachedImages", isCachedImages); synchronized (TABLE_ARTICLES) { db.update(TABLE_ARTICLES, cv, "cachedImages=0 & id=" + id, null); // Only apply if not yet applied and // ID matches } } dbReadLock.readLock().unlock(); } public void deleteCategories(boolean withVirtualCategories) { if (isDBAvailable()) { String wherePart = ""; if (!withVirtualCategories) { wherePart = "id > 0"; } synchronized (TABLE_CATEGORIES) { db.delete(TABLE_CATEGORIES, wherePart, null); } } dbReadLock.readLock().unlock(); } public void deleteFeeds() { if (isDBAvailable()) { synchronized (TABLE_FEEDS) { db.delete(TABLE_FEEDS, null, null); } } dbReadLock.readLock().unlock(); } /** * Deletes articles until the configured number of articles is matched. Published and Starred articles are ignored * so the configured limit is not an exact upper limit to the numbe rof articles in the database. */ public void purgeArticlesNumber() { if (isDBAvailable()) { int number = Controller.getInstance().getArticleLimit(); String idList = "SELECT id FROM " + TABLE_ARTICLES + " WHERE isPublished=0 AND isStarred=0 ORDER BY updateDate DESC LIMIT -1 OFFSET " + number; synchronized (TABLE_ARTICLES) { db.delete(TABLE_ARTICLES, "id in(" + idList + ")", null); purgeLabels(); } } dbReadLock.readLock().unlock(); } public void purgePublishedArticles() { if (isDBAvailable()) { synchronized (TABLE_ARTICLES) { db.delete(TABLE_ARTICLES, "isPublished>0", null); purgeLabels(); } } dbReadLock.readLock().unlock(); } public void purgeStarredArticles() { if (isDBAvailable()) { synchronized (TABLE_ARTICLES) { db.delete(TABLE_ARTICLES, "isStarred>0", null); purgeLabels(); } } dbReadLock.readLock().unlock(); } private void purgeLabels() { // @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 synchronized (TABLE_ARTICLES) { db.delete(TABLE_ARTICLES2LABELS, "articleId IN(" + idsArticles + ")", null); db.delete(TABLE_ARTICLES2LABELS, "labelId IN(" + idsFeeds + ")", null); } } public void vacuum() { if (vacuumDone) return; try { long time = System.currentTimeMillis(); db.execSQL("VACUUM"); vacuumDone = true; Log.i(Utils.TAG, "SQLite VACUUM took " + (System.currentTimeMillis() - time) + " ms."); } catch (SQLException e) { Log.e(Utils.TAG, "SQLite VACUUM failed: " + e.getMessage() + " " + e.getCause()); } } // *******| SELECT |******************************************************************* public int getSinceId() { int ret = 0; if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(TABLE_ARTICLES, new String[] {"id"}, null, null, null, null, "id DESC", "1"); if (!c.isAfterLast()) { if (c.isBeforeFirst() && !c.moveToFirst()) return 0; ret = c.getInt(0); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } // Takes about 2 to 6 ms on Motorola Milestone public Article getArticle(int id) { Article ret = null; if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(TABLE_ARTICLES, null, "id=?", new String[] { id + "" }, null, null, null, null); while (!c.isAfterLast()) { ret = handleArticleCursor(c); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public Feed getFeed(int id) { Feed ret = new Feed(); if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(TABLE_FEEDS, null, "id=?", new String[] { id + "" }, null, null, null, null); while (!c.isAfterLast()) { ret = handleFeedCursor(c); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public Category getCategory(int id) { Category ret = new Category(); if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(TABLE_CATEGORIES, null, "id=?", new String[] { id + "" }, null, null, null, null); while (!c.isAfterLast()) { ret = handleCategoryCursor(c); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public Set<Article> getUnreadArticles(int feedId) { Set<Article> ret = new LinkedHashSet<Article>(); if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(TABLE_ARTICLES, null, "feedId=? AND isUnread>0", new String[] { feedId + "" }, null, null, null, null); while (!c.isAfterLast()) { ret.add(handleArticleCursor(c)); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } /** * 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) { Set<Feed> ret = new LinkedHashSet<Feed>(); if (!isDBAvailable()) return ret; Cursor c = null; try { String where = "categoryId=" + categoryId; if (categoryId < 0 && categoryId != -2) { where = null; } c = db.query(TABLE_FEEDS, null, where, null, null, null, "UPPER(title) ASC"); while (!c.isAfterLast()) { ret.add(handleFeedCursor(c)); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public Set<Category> getVirtualCategories() { Set<Category> ret = new LinkedHashSet<Category>(); if (!isDBAvailable()) return ret; Cursor c = db.query(TABLE_CATEGORIES, null, "id<1", null, null, null, "id ASC"); try { while (!c.isAfterLast()) { Category ci = handleCategoryCursor(c); ret.add(ci); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public Set<Category> getCategoriesIncludingUncategorized() { Set<Category> ret = new LinkedHashSet<Category>(); if (!isDBAvailable()) return ret; Cursor c = db.query(TABLE_CATEGORIES, null, "id>=0", null, null, null, "title ASC"); try { while (!c.isAfterLast()) { Category ci = handleCategoryCursor(c); ret.add(ci); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public int getUnreadCount(int id, boolean isCat) { int ret = 0; if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(isCat ? TABLE_CATEGORIES : TABLE_FEEDS, new String[] { "unread" }, "id=?", new String[] { id + "" }, null, null, null, null); if (c.moveToFirst()) { ret = c.getInt(0); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public Map<Integer, String> getMarked(String mark, int status) { Map<Integer, String> ret = new HashMap<Integer, String>(); if (!isDBAvailable()) return ret; Cursor c = null; try { c = db.query(TABLE_MARK, new String[] { "id", MARK_NOTE }, mark + "=" + status, null, null, null, null, null); if (!c.moveToFirst()) return ret; while (!c.isAfterLast()) { ret.put(c.getInt(0), c.getString(1)); c.move(1); } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) c.close(); } dbReadLock.readLock().unlock(); return ret; } public void setMarked(Map<Integer, String> ids, String mark) { if (!isDBAvailable()) return; try { for (String idList : StringSupport.convertListToString(ids.keySet(), 100)) { ContentValues cv = new ContentValues(); 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 for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; ContentValues cv = new ContentValues(); cv.put(MARK_NOTE, note); db.update(TABLE_MARK, cv, "id=" + id, null); } } catch (Exception e) { e.printStackTrace(); } dbReadLock.readLock().unlock(); } // ******************************************* private static Article handleArticleCursor(Cursor c) { if (c.isBeforeFirst() && !c.moveToFirst()) return null; // @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 ); ret.cachedImages = (c.getInt(11) != 0); // @formatter:on return ret; } private static Feed handleFeedCursor(Cursor c) { if (c.isBeforeFirst() && !c.moveToFirst()) return null; // @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) { if (c.isBeforeFirst() && !c.moveToFirst()) return null; // @formatter:off Category ret = new Category( c.getInt(0), // id c.getString(1), // title c.getInt(2)); // unread // @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; } private static String parseAttachmentSet(Set<String> att) { if (att == null) return ""; StringBuilder ret = new StringBuilder(); for (String s : att) { ret.append(s + ";"); } if (att.size() > 0) ret.deleteCharAt(ret.length() - 1); return ret.toString(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.gui.MenuActivity; import org.ttrssreader.imageCache.ImageCache; import org.ttrssreader.net.Connector; import org.ttrssreader.net.JSONConnector; import org.ttrssreader.preferences.Constants; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.DisplayMetrics; 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 { public final static String JSON_END_URL = "api/"; private static final String MARKER_ALIGN = "TEXT_ALIGN_MARKER"; private static final String MARKER_LINK = "LINK_MARKER"; private static final String MARKER_LINK_VISITED = "LINK_VISITED_MARKER"; private boolean initialized = false; private Context context; private Connector ttrssConnector; private ImageCache imageCache; private String imageCacheLock = ""; // Use this to lock access to the cache as workaround for NPE on imageCache private static Controller instance = null; private SharedPreferences prefs = null; 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 useKeystore = null; private String keystorePassword = null; private Boolean lazyServer = null; private Boolean automaticMarkRead = null; private Boolean openUrlEmptyArticle = null; private Boolean useVolumeKeys = null; private Boolean vibrateOnLastArticle = null; private Boolean workOffline = null; private Boolean showVirtual = null; private Boolean useSwipe = null; private Boolean useButtons = null; private Boolean leftHanded = null; private Boolean onlyUnread = null; private Integer articleLimit = null; private Boolean displayArticleHeader = null; private Boolean invertSortArticlelist = null; private Boolean invertSortFeedscats = null; private Boolean alignFlushLeft = null; private Boolean injectArticleLink = null; private Boolean dateTimeSystem = null; private String dateString = null; private String timeString = null; private Boolean darkBackground = null; private Integer imageCacheSize = null; private Boolean imageCacheUnread = null; private String saveAttachment = null; private String cacheFolder = null; private Boolean isVacuumDBScheduled = null; private Boolean isDeleteDBScheduled = null; private Boolean isDeleteDBOnStartup = null; private Boolean cacheImagesOnStartup = null; private Boolean cacheImagesOnlyWifi = null; private Boolean logSensitiveData = null; private Long apiLevelUpdated = null; private Integer apiLevel = null; private Long appVersionCheckTime = null; private Integer appLatestVersion = null; private Long lastUpdateTime = null; private String lastVersionRun = null; private Boolean newInstallation = false; private String freshArticleMaxAge = ""; private Long lastVacuumDate = null; public volatile Integer lastOpenedFeed = null; public volatile Integer lastOpenedArticle = null; // Article-View-Stuff public static String htmlHeader = ""; public static int absHeight = -1; public static int absWidth = -1; public static int swipeAreaHeight = -1; public static int swipeWidth = -1; public static int swipeAreaWidth = -1; public static int swipeHeight = -1; public static int padding = -1; public static boolean landscape = false; // Singleton private Controller() { } public static Controller getInstance() { synchronized (Controller.class) { if (instance == null || instance.prefs == null) { instance = new Controller(); } } return instance; } public synchronized void checkAndInitializeController(final Context context, final Display display) { this.context = context; if (!initialized) { initializeController(display); initialized = true; } } public static synchronized void checkAndInitializeController(final Context context, boolean force_dummy_parameter) { Controller.instance = null; Controller.getInstance().checkAndInitializeController(context, null); } private synchronized void initializeController(final Display display) { prefs = PreferenceManager.getDefaultSharedPreferences(context); // Check for new installation if (!prefs.contains(Constants.URL) && !prefs.contains(Constants.LAST_VERSION_RUN)) { newInstallation = true; } ttrssConnector = new JSONConnector(); // Attempt to initialize some stuff in a background-thread to reduce loading time // TODO: Check if it works.. // Start a login-request separately because this takes some time new Thread(new Runnable() { public void run() { ttrssConnector.sessionAlive(); } }).start(); new Thread(new Runnable() { public void run() { // Only need once we are displaying the feed-list or an article... refreshDisplayMetrics(display); // This is only needed once an article is displayed synchronized (htmlHeader) { // Article-Prefetch-Stuff from Raw-Ressources and System htmlHeader = context.getResources().getString(R.string.INJECT_HTML_HEAD); // Replace alignment-marker with the requested layout, align:left or justified String replaceAlign = ""; if (alignFlushLeft()) { replaceAlign = context.getResources().getString(R.string.ALIGN_LEFT); htmlHeader = htmlHeader.replace(MARKER_ALIGN, replaceAlign); } else { replaceAlign = context.getResources().getString(R.string.ALIGN_JUSTIFY); htmlHeader = htmlHeader.replace(MARKER_ALIGN, replaceAlign); } // Replace color-markers with matching colors for the requested background String replaceLink = ""; String replaceLinkVisited = ""; if (darkBackground()) { replaceLink = context.getResources().getString(R.string.COLOR_LINK_DARK); replaceLinkVisited = context.getResources().getString(R.string.COLOR_LINK_DARK_VISITED); htmlHeader = htmlHeader.replace(MARKER_LINK, replaceLink); htmlHeader = htmlHeader.replace(MARKER_LINK_VISITED, replaceLinkVisited); } else { replaceLink = context.getResources().getString(R.string.COLOR_LINK_LIGHT); replaceLinkVisited = context.getResources().getString(R.string.COLOR_LINK_LIGHT_VISITED); htmlHeader = htmlHeader.replace(MARKER_LINK, replaceLink); htmlHeader = htmlHeader.replace(MARKER_LINK_VISITED, replaceLinkVisited); } } // 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(context); } }).start(); } public static void refreshDisplayMetrics(Display display) { if (display == null) return; DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); absHeight = metrics.heightPixels; absWidth = metrics.widthPixels; // Portrait-Mode swipeAreaHeight = (int) (absHeight * 0.25); // 25% of absolute height swipeWidth = (int) (absWidth * 0.5); // 50% of absolute width // Landscape-Mode swipeAreaWidth = (int) (absWidth * 0.20); // 20% of absolute width swipeHeight = (int) (absHeight * 0.5); // 50% of absolute height // Is this fine for orientation-recognition? display.getOrientation() is deprecated and // display.getRotation() doesn't give information about which layout is used. if (absWidth > absHeight) { landscape = true; padding = (int) ((swipeAreaWidth / 2) - (16 * metrics.density)); // TODO: Why 16??? } else { landscape = false; padding = (int) ((swipeAreaHeight / 2) - (16 * metrics.density)); // TODO: Why 16??? } } // ******* CONNECTION-Options **************************** public URI url() { if (url == null) url = prefs.getString(Constants.URL, Constants.URL_DEFAULT); if (!url.endsWith(JSON_END_URL)) { if (!url.endsWith("/")) { url += "/"; } url += JSON_END_URL; } try { return new URI(url); } catch (URISyntaxException e) { // Return default URL if creating an URI from the configured URL fails... try { return new URI(Constants.URL_DEFAULT); } catch (URISyntaxException e1) { } } return null; // Should never be reached! } public String updateTriggerURI() { String url = prefs.getString(Constants.URL, Constants.URL_DEFAULT); if (!url.endsWith(JSON_END_URL)) { if (!url.endsWith("/")) { url += "/"; } } final String updateSuffix = "backend.php?op=globalUpdateFeeds&daemon=1"; return url + updateSuffix; } public String username() { if (username == null) username = prefs.getString(Constants.USERNAME, Constants.EMPTY); return username; } public String password() { if (password == null) 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 Connector getConnector() throws NotInitializedException { // Initialized inside initializeController(); if (ttrssConnector != null) { return ttrssConnector; } else { throw new NotInitializedException(new NullPointerException()); } } public ImageCache getImageCache(Context context) { synchronized (imageCacheLock) { if (imageCache == null) { imageCache = new ImageCache(2000); if (context == null || !imageCache.enableDiskCache()) { imageCache = null; } } } return imageCache; } public String getKeystorePassword() { if (keystorePassword == null) keystorePassword = prefs.getString(Constants.KEYSTORE_PASSWORD, Constants.EMPTY); return keystorePassword; } // ******* USAGE-Options **************************** public boolean automaticMarkRead() { if (automaticMarkRead == null) automaticMarkRead = prefs.getBoolean(Constants.AUTOMATIC_MARK_READ, Constants.AUTOMATIC_MARK_READ_DEFAULT); return automaticMarkRead; } public void setAutomaticMarkRead(boolean automaticMarkRead) { put(Constants.AUTOMATIC_MARK_READ, automaticMarkRead); this.automaticMarkRead = automaticMarkRead; } public boolean lazyServer() { if (lazyServer == null) lazyServer = prefs.getBoolean(Constants.USE_OF_A_LAZY_SERVER, Constants.USE_OF_A_LAZY_SERVER_DEFAULT); return lazyServer; } 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 vibrateOnLastArticle() { if (vibrateOnLastArticle == null) vibrateOnLastArticle = prefs.getBoolean(Constants.VIBRATE_ON_LAST_ARTICLE, Constants.VIBRATE_ON_LAST_ARTICLE_DEFAULT); return vibrateOnLastArticle; } public void setVibrateOnLastArticle(boolean vibrateOnLastArticle) { put(Constants.VIBRATE_ON_LAST_ARTICLE, vibrateOnLastArticle); this.vibrateOnLastArticle = vibrateOnLastArticle; } 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; } // ******* DISPLAY-Options **************************** 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 boolean useSwipe() { if (useSwipe == null) useSwipe = prefs.getBoolean(Constants.USE_SWIPE, Constants.USE_SWIPE_DEFAULT); return useSwipe; } public void setUseSwipe(boolean useSwipe) { put(Constants.USE_SWIPE, useSwipe); this.useSwipe = useSwipe; } public boolean useButtons() { if (useButtons == null) useButtons = prefs.getBoolean(Constants.USE_BUTTONS, Constants.USE_BUTTONS_DEFAULT); return useButtons; } public void setUseButtons(boolean useButtons) { put(Constants.USE_BUTTONS, useButtons); this.useButtons = useButtons; } public boolean leftHanded() { if (leftHanded == null) leftHanded = prefs.getBoolean(Constants.LEFT_HANDED, Constants.LEFT_HANDED_DEFAULT); return leftHanded; } public void setLeftHanded(boolean leftHanded) { put(Constants.LEFT_HANDED, leftHanded); this.leftHanded = leftHanded; } 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 int getArticleLimit() { if (articleLimit == null) articleLimit = prefs.getInt(Constants.ARTICLE_LIMIT, Constants.ARTICLE_LIMIT_DEFAULT); return articleLimit; } public void setArticleLimit(int articleLimit) { put(Constants.ARTICLE_LIMIT, articleLimit); this.articleLimit = articleLimit; } public boolean displayArticleHeader() { if (displayArticleHeader == null) displayArticleHeader = prefs.getBoolean(Constants.DISPLAY_ARTICLE_HEADER, Constants.DISPLAY_ARTICLE_HEADER_DEFAULT); return displayArticleHeader; } public void setDisplayArticleHeader(boolean displayArticleHeader) { put(Constants.DISPLAY_ARTICLE_HEADER, displayArticleHeader); this.displayArticleHeader = displayArticleHeader; } 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 injectArticleLink() { if (injectArticleLink == null) injectArticleLink = prefs.getBoolean(Constants.INJECT_ARTICLE_LINK, Constants.INJECT_ARTICLE_LINK_DEFAULT); return injectArticleLink; } public void setInjectArticleLink(boolean injectArticleLink) { put(Constants.INJECT_ARTICLE_LINK, injectArticleLink); this.injectArticleLink = injectArticleLink; } 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 boolean darkBackground() { if (darkBackground == null) darkBackground = prefs.getBoolean(Constants.DARK_BACKGROUND, Constants.DARK_BACKGROUND_DEFAULT); return darkBackground; } public void setDarkBackground(boolean darkBackground) { put(Constants.DARK_BACKGROUND, darkBackground); this.darkBackground = darkBackground; } // SYSTEM public int getImageCacheSize() { if (imageCacheSize == null) imageCacheSize = prefs.getInt(Constants.IMAGE_CACHE_SIZE, Constants.IMAGE_CACHE_SIZE_DEFAULT); return imageCacheSize; } public void setImageCacheSize(int imageCacheSize) { put(Constants.IMAGE_CACHE_SIZE, imageCacheSize); this.imageCacheSize = imageCacheSize; } public boolean isImageCacheUnread() { if (imageCacheUnread == null) imageCacheUnread = prefs.getBoolean(Constants.IMAGE_CACHE_UNREAD, Constants.IMAGE_CACHE_UNREAD_DEFAULT); return imageCacheUnread; } public void setImageCacheUnread(boolean imageCacheUnread) { put(Constants.IMAGE_CACHE_UNREAD, imageCacheUnread); this.imageCacheUnread = imageCacheUnread; } 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); return cacheFolder; } public void setCacheFolder(String cacheFolder) { put(Constants.CACHE_FOLDER, cacheFolder); this.cacheFolder = cacheFolder; } public boolean isVacuumDBScheduled() { long time = System.currentTimeMillis(); long thirtyDays = 30 * 24 * 60 * 60 * 1000L; // Note "L" for explicit cast to long if (lastVacuumDate() < (time - thirtyDays)) return true; if (isVacuumDBScheduled == null) isVacuumDBScheduled = prefs .getBoolean(Constants.VACUUM_DB_SCHEDULED, Constants.VACUUM_DB_SCHEDULED_DEFAULT); return isVacuumDBScheduled; } public void setVacuumDBScheduled(boolean isVacuumDBScheduled) { put(Constants.VACUUM_DB_SCHEDULED, isVacuumDBScheduled); this.isVacuumDBScheduled = isVacuumDBScheduled; } public boolean isDeleteDBScheduled() { if (isDeleteDBScheduled == null) isDeleteDBScheduled = prefs .getBoolean(Constants.DELETE_DB_SCHEDULED, Constants.DELETE_DB_SCHEDULED_DEFAULT); return isDeleteDBScheduled; } public void setDeleteDBScheduled(boolean isDeleteDBScheduled) { put(Constants.DELETE_DB_SCHEDULED, isDeleteDBScheduled); this.isDeleteDBScheduled = isDeleteDBScheduled; } // Reset to false if preference to delete on every start is not set public void resetDeleteDBScheduled() { if (!isDeleteDBOnStartup()) { put(Constants.DELETE_DB_SCHEDULED, Constants.DELETE_DB_SCHEDULED_DEFAULT); this.isDeleteDBScheduled = Constants.DELETE_DB_SCHEDULED_DEFAULT; } } public boolean isDeleteDBOnStartup() { if (isDeleteDBOnStartup == null) isDeleteDBOnStartup = prefs.getBoolean(Constants.DELETE_DB_ON_STARTUP, Constants.DELETE_DB_ON_STARTUP_DEFAULT); return isDeleteDBOnStartup; } public void setDeleteDBOnStartup(boolean isDeleteDBOnStartup) { put(Constants.DELETE_DB_ON_STARTUP, isDeleteDBOnStartup); this.isDeleteDBOnStartup = isDeleteDBOnStartup; setDeleteDBScheduled(isDeleteDBOnStartup); } 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 logSensitiveData() { if (logSensitiveData == null) logSensitiveData = prefs.getBoolean(Constants.LOG_SENSITIVE_DATA, Constants.LOG_SENSITIVE_DATA_DEFAULT); return logSensitiveData; } public void setLogSensitiveData(boolean logSensitiveData) { put(Constants.LOG_SENSITIVE_DATA, logSensitiveData); this.logSensitiveData = logSensitiveData; } // ******* INTERNAL Data **************************** public long apiLevelUpdated() { if (apiLevelUpdated == null) apiLevelUpdated = prefs.getLong(Constants.API_LEVEL_UPDATED, Constants.API_LEVEL_UPDATED_DEFAULT); return apiLevelUpdated; } private void setApiLevelUpdated(long apiLevelUpdated) { put(Constants.APP_VERSION_CHECK_TIME, apiLevelUpdated); this.apiLevelUpdated = apiLevelUpdated; } public int apiLevel() { if (apiLevel == null) apiLevel = prefs.getInt(Constants.API_LEVEL, Constants.API_LEVEL_DEFAULT); return apiLevel; } public void setApiLevel(int apiLevel) { put(Constants.API_LEVEL, apiLevel); this.apiLevel = apiLevel; setApiLevelUpdated(System.currentTimeMillis()); } 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 long getLastUpdateTime() { if (lastUpdateTime == null) lastUpdateTime = prefs.getLong(Constants.LAST_UPDATE_TIME, Constants.LAST_UPDATE_TIME_DEFAULT); return lastUpdateTime; } public void setLastUpdateTime(long lastUpdateTime) { put(Constants.LAST_UPDATE_TIME, lastUpdateTime); this.lastUpdateTime = lastUpdateTime; } 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 setLastVacuumDate() { long time = System.currentTimeMillis(); put(Constants.LAST_VACUUM_DATE, time); this.lastVacuumDate = time; } public long lastVacuumDate() { if (lastVacuumDate == null) lastVacuumDate = prefs.getLong(Constants.LAST_VACUUM_DATE, Constants.LAST_VACUUM_DATE_DEFAULT); return lastVacuumDate; } private AsyncTask<Void, Void, Void> task; public long getFreshArticleMaxAge() { int ret = 48 * 60 * 60 * 1000; // Refreshed every two days only if (freshArticleMaxAge == null) { return ret; } else if (freshArticleMaxAge.equals("")) { // Only start task if none existing yet if (task == null) { task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { freshArticleMaxAge = Data.getInstance().getPref("FRESH_ARTICLE_MAX_AGE"); return null; } }; task.execute(); } } try { ret = Integer.parseInt(freshArticleMaxAge) * 60 * 60 * 1000; } catch (Exception e) { return ret; } return ret; } /* * 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; } // ------------------------------ // Call all registered instances of MenuActivity when caching is done private List<MenuActivity> callbacks = new ArrayList<MenuActivity>(); public void notifyActivities() { synchronized (callbacks) { for (MenuActivity m : callbacks) { m.onCacheEnd(); } // Why?? // callbacks = new ArrayList<MenuActivity>(); } } public void registerActivity(MenuActivity activity) { synchronized (callbacks) { callbacks.add(activity); // Reduce size to maximum of 3 activities if (callbacks.size() > 2) { List<MenuActivity> temp = new ArrayList<MenuActivity>(); temp.addAll(callbacks.subList(callbacks.size() - 2, callbacks.size())); callbacks = temp; } } } public void unregisterActivity(MenuActivity activity) { synchronized (callbacks) { callbacks.remove(activity); } } /** * 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) { 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())) { try { Object f = field.get(this); if (!(f instanceof String)) continue; if (key.equals((String) f)) { // reset variable, it will be re-read on next access String fieldName = Constants.constant2Var(field.getName()); Controller.class.getDeclaredField(fieldName).set(this, null); // "Declared" so also private // fields are returned } } catch (Exception e) { e.printStackTrace(); } } } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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; public class NotInitializedException extends Exception { private static final long serialVersionUID = 1L; public NotInitializedException(String msg) { super(msg); } public NotInitializedException(String format, Object... args) { super(String.format(format, args)); } public NotInitializedException(final String message, final Throwable cause) { super(message, cause); } public NotInitializedException(final Throwable cause) { super(cause); } public NotInitializedException(final Throwable cause, final String format, final Object... args) { super(String.format(format, args), cause); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.utils; import org.ttrssreader.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; /* * RotatableTextView, (C) 2010, Radu Motisan radu.motisan@gmail.com, modified by Nils Braden * * Purpose: create a custom textview control, that supports rotation and other customizations */ public class RotatableTextView extends TextView { private int color = Color.WHITE; private int backgroundColor = Color.BLACK; private Typeface typeface = null; private int size = 14; private int angle = 0; private int pivotWidth = 0; private int pivotHeight = 0; private String text = ""; public RotatableTextView(Context context) { super(context); typeface = Typeface.create("arial", Typeface.NORMAL); } public RotatableTextView(Context context, AttributeSet attrs) { super(context, attrs); typeface = Typeface.create("arial", Typeface.NORMAL); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RotatableTextView); text = a.getString(R.styleable.RotatableTextView_text); color = a.getColor(R.styleable.RotatableTextView_textColor, Color.WHITE); size = a.getInt(R.styleable.RotatableTextView_textSize, 14); angle = a.getInt(R.styleable.RotatableTextView_textRotation, 0); backgroundColor = a.getColor(R.styleable.RotatableTextView_backgroundColor, Color.BLACK); a.recycle(); } public RotatableTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); typeface = Typeface.create("arial", Typeface.NORMAL); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RotatableTextView, defStyle, 0); text = a.getString(R.styleable.RotatableTextView_text); color = a.getColor(R.styleable.RotatableTextView_textColor, Color.WHITE); size = a.getInt(R.styleable.RotatableTextView_textSize, 14); angle = a.getInt(R.styleable.RotatableTextView_textRotation, 0); backgroundColor = a.getColor(R.styleable.RotatableTextView_backgroundColor, Color.BLACK); a.recycle(); } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setTypeface(typeface); paint.setStyle(Paint.Style.FILL); paint.setColor(color); paint.setTextSize(size); paint.setTextAlign(Align.CENTER); pivotWidth = this.getWidth() / 2; pivotHeight = this.getHeight() / 2; canvas.rotate(angle, pivotWidth, pivotHeight); canvas.drawColor(backgroundColor); canvas.drawText(text, pivotWidth, pivotHeight, paint); super.onDraw(canvas); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Comparator; import android.util.Log; /** * * @author Nils Braden * */ public class FileUtils { /** * Supported extensions of imagefiles, see http://developer.android.com/guide/appendix/media-formats.html */ public static final String[] IMAGE_EXTENSIONS = { "jpeg", "jpg", "gif", "png", "bmp", "webp" }; public static final String IMAGE_MIME = "image/*"; /** * Supported extensions of audiofiles, see http://developer.android.com/guide/appendix/media-formats.html * I removed the extensions from this list which are also used for video files. It is easier to open these in the * videoplayer and blaming the source instead of trying to figure out mime-types by hand. */ public static final String[] AUDIO_EXTENSIONS = { "mp3", "mid", "midi", "xmf", "mxmf", "ogg", "wav" }; public static final String AUDIO_MIME = "audio/*"; /** * Supported extensions of videofiles, see http://developer.android.com/guide/appendix/media-formats.html */ public static final String[] VIDEO_EXTENSIONS = { "3gp", "mp4", "m4a", "aac", "ts", "webm", "mkv", "mpg", "mpeg", "avi", "flv" }; public static final String VIDEO_MIME = "video/*"; /** * Path on sdcard to store files (DB, Certificates, ...) */ public static final String SDCARD_PATH_FILES = "/Android/data/org.ttrssreader/files/"; /** * Path on sdcard to store cache */ public static final String SDCARD_PATH_CACHE = "/Android/data/org.ttrssreader/cache/"; /** * Downloads a given URL directly to a file, when maxSize bytes are reached the download is stopped and the file is * deleted. * * @param downloadUrl * the URL of the file * @param file * the destination file * @param maxSize * the size in bytes after which to abort the download * @return length of the downloaded file */ public static long downloadToFile(String downloadUrl, File file, long maxSize) { FileOutputStream fos = null; int byteWritten = 0; try { if (file.exists()) file.delete(); URL url = new URL(downloadUrl); URLConnection connection = url.openConnection(); // Check filesize if available from header if (connection.getHeaderField("Content-Length") != null) { long length = Long.parseLong(connection.getHeaderField("Content-Length")); if (length > maxSize) { Log.i(Utils.TAG, String.format( "Not starting download of %s, the size (%s MB) exceeds the maximum filesize of %s MB.", downloadUrl, length / 1048576, maxSize / 1048576)); return -1; } } file.createNewFile(); fos = new FileOutputStream(file); InputStream is = connection.getInputStream(); int size = 1024 * 8; byte[] buf = new byte[size]; int byteRead; while (((byteRead = is.read(buf)) != -1)) { fos.write(buf, 0, byteRead); byteWritten += byteRead; if (byteWritten > maxSize) { Log.w(Utils.TAG, String.format( "Download interrupted, the size of %s bytes exceeds maximum filesize.", byteWritten)); file.delete(); byteWritten = 0; // Set to 0 so the article will not be scheduled for download again. break; } } } catch (Exception e) { Log.i(Utils.TAG, "Download not finished properly. Exception: " + e.getMessage()); byteWritten = -1; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } return byteWritten; } /** * Sums up the size of a folder including all files and subfolders. * * @param folder * the folder * @return the size of the folder */ public static long getFolderSize(File folder) { long size = 0; for (File f : folder.listFiles()) { if (f.isDirectory()) { size += getFolderSize(f); } else { size += f.length(); } } return size; } /** * At the moment this method just returns a generic mime-type for audio, video or image-files, a more specific way * of probing for the type (MIME-Sniffing or exact checks on the extension) are yet to be implemented. * * Implementation-Hint: See * https://code.google.com/p/openintents/source/browse/trunk/filemanager/FileManager/src/org * /openintents/filemanager/FileManagerActivity.java * * @param fileName * @return */ public static String getMimeType(String fileName) { String ret = ""; if (fileName == null || fileName.length() == 0) return ret; for (String ext : IMAGE_EXTENSIONS) { if (fileName.endsWith(ext)) return IMAGE_MIME; } for (String ext : AUDIO_EXTENSIONS) { if (fileName.endsWith(ext)) return AUDIO_MIME; } for (String ext : VIDEO_EXTENSIONS) { if (fileName.endsWith(ext)) return VIDEO_MIME; } return ret; } public class FileDateComparator implements Comparator<File> { @Override public int compare(File f1, File f2) { // Hopefully avoids crashes due to IllegalArgumentExceptions if (f1.equals(f2)) return 0; long size1 = f1.lastModified(); long size2 = f2.lastModified(); if (size1 < size2) { return -1; } else if (size1 > size2) { return 1; } return 0; // equal } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.utils; import java.util.Date; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import android.content.Context; /** * Provides functionality to automatically format date and time values (or both) depending on settings of the app and * the systems configuration. * * @author Nils Braden */ public class DateUtils { /** * Returns the formatted date and time in the format specified by Controller.dateString() and * Controller.timeString() or if settings indicate the systems configuration should be used it returns the date and * time formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the date and time */ public static String getDateTime(Context context, Date date) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return dateFormat.format(date) + " " + timeFormat.format(date); } else { try { String format = Controller.getInstance().dateString() + " " + Controller.getInstance().timeString(); return android.text.format.DateFormat.format(format, date).toString(); } catch (Exception e) { // Retreat to default date-time-format String format = context.getResources().getString(R.string.DisplayDateFormatDefault) + " " + context.getResources().getString(R.string.DisplayTimeFormatDefault); return android.text.format.DateFormat.format(format, date).toString(); } } } /** * Returns the formatted date in the format specified by Controller.dateString() or if settings indicate the systems * configuration should be used it returns the date formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the date */ public static String getDate(Context context, Date date) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); return dateFormat.format(date); } else { try { String format = Controller.getInstance().dateString(); return android.text.format.DateFormat.format(format, date).toString(); } catch (Exception e) { // Retreat to default date-format String format = context.getResources().getString(R.string.DisplayDateFormatDefault); return android.text.format.DateFormat.format(format, date).toString(); } } } /** * Returns the formatted time in the format specified by Controller.timeString() or if settings indicate the systems * configuration should be used it returns the time formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the time */ public static String getTime(Context context, Date time) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return timeFormat.format(time); } else { try { String format = Controller.getInstance().timeString(); return android.text.format.DateFormat.format(format, time).toString(); } catch (Exception e) { // Retreat to default time-format String format = context.getResources().getString(R.string.DisplayTimeFormatDefault); return android.text.format.DateFormat.format(format, time).toString(); } } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.utils; import java.io.File; import java.util.Comparator; /** * Compares two files by their last-modified-date. * * @author Nils Braden * */ public class FileDateComparator implements Comparator<File> { @Override public int compare(File f1, File f2) { // Hopefully avoids crashes due to IllegalArgumentExceptions if (f1.equals(f2)) return 0; long size1 = f1.lastModified(); long size2 = f2.lastModified(); if (size1 < size2) { return -1; } else if (size1 > size2) { return 1; } return 0; // equal } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler * Modified 2010 by Nils Braden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import com.google.common.collect.MapMaker; /** * <p> * A simple 2-level cache consisting of a small and fast in-memory cache (1st level cache) and an (optional) slower but * bigger disk cache (2nd level cache). For disk caching, either the application's cache directory or the SD card can be * used. Please note that in the case of the app cache dir, Android may at any point decide to wipe that entire * directory if it runs low on internal storage. The SD card cache <i>must</i> be managed by the application, e.g. by * calling {@link #wipe} whenever the app quits. * </p> * <p> * When pulling from the cache, it will first attempt to load the data from memory. If that fails, it will try to load * it from disk (assuming disk caching is enabled). If that succeeds, the data will be put in the in-memory cache and * returned (read-through). Otherwise it's a cache miss. * </p> * <p> * Pushes to the cache are always write-through (i.e. the data will be stored both on disk, if disk caching is enabled, * and in memory). * </p> * * @author Matthias Kaeppler * @author Nils Braden (modified some stuff) */ public abstract class AbstractCache<KeyT, ValT> implements Map<KeyT, ValT> { protected boolean isDiskCacheEnabled; protected String diskCacheDir; protected ConcurrentMap<KeyT, ValT> cache; /** * Creates a new cache instance. * * @param name * a human readable identifier for this cache. Note that this value will be used to * derive a directory name if the disk cache is enabled, so don't get too creative * here (camel case names work great) * @param initialCapacity * the initial element size of the cache * @param expirationInMinutes * time in minutes after which elements will be purged from the cache (NOTE: this * only affects the memory cache, the disk cache does currently NOT handle element * TTLs!) * @param maxConcurrentThreads * how many threads you think may at once access the cache; this need not be an exact * number, but it helps in fragmenting the cache properly */ public AbstractCache(String name, int initialCapacity, int maxConcurrentThreads) { MapMaker mapMaker = new MapMaker(); mapMaker.initialCapacity(initialCapacity); // mapMaker.expiration(expirationInMinutes * 60, TimeUnit.SECONDS); mapMaker.concurrencyLevel(maxConcurrentThreads); mapMaker.softValues(); this.cache = mapMaker.makeMap(); } /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. * * @return the full absolute path to the directory where files are cached, if the disk cache is * enabled, otherwise null */ public String getDiskCacheDirectory() { return diskCacheDir; } /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Turns a cache key * into the file name that will be used to persist the value to disk. Subclasses must implement * this. * * @param key * the cache key * @return the file name */ public abstract String getFileNameForKey(KeyT key); /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Restores a value * previously persisted to the disk cache. * * @param file * the file holding the cached value * @return the cached value * @throws IOException */ protected abstract ValT readValueFromDisk(File file) throws IOException; /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Persists a value to * the disk cache. * * @param ostream * the file output stream (buffered). * @param value * the cache value to persist * @throws IOException */ protected abstract void writeValueToDisk(BufferedOutputStream ostream, ValT value) throws IOException; private void cacheToDisk(KeyT key, ValT value) { File file = new File(diskCacheDir + "/" + getFileNameForKey(key)); try { file.createNewFile(); file.deleteOnExit(); BufferedOutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); writeValueToDisk(ostream, value); ostream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private File getFileForKey(KeyT key) { return new File(diskCacheDir + "/" + getFileNameForKey(key)); } /** * Reads a value from the cache by probing the in-memory cache, and if enabled and the in-memory * probe was a miss, the disk cache. * * @param elementKey * the cache key * @return the cached value, or null if element was not cached */ @SuppressWarnings("unchecked") public synchronized ValT get(Object elementKey) { KeyT key = (KeyT) elementKey; ValT value = cache.get(key); if (value != null) { // memory hit return value; } // memory miss, try reading from disk File file = getFileForKey(key); if (file.exists()) { // disk hit try { value = readValueFromDisk(file); } catch (IOException e) { // treat decoding errors as a cache miss e.printStackTrace(); return null; } if (value == null) { return null; } cache.put(key, value); return value; } // cache miss return null; } /** * Writes an element to the cache. NOTE: If disk caching is enabled, this will write through to * the disk, which may introduce a performance penalty. */ public synchronized ValT put(KeyT key, ValT value) { if (isDiskCacheEnabled) { cacheToDisk(key, value); } return cache.put(key, value); } public synchronized void putAll(Map<? extends KeyT, ? extends ValT> t) { throw new UnsupportedOperationException(); } /** * Checks if a value is present in the cache. If the disk cached is enabled, this will also * check whether the value has been persisted to disk. * * @param key * the cache key * @return true if the value is cached in memory or on disk, false otherwise */ @SuppressWarnings("unchecked") public synchronized boolean containsKey(Object key) { return cache.containsKey(key) || (isDiskCacheEnabled && getFileForKey((KeyT) key).exists()); } /** * Checks if the given value is currently hold in memory. */ public synchronized boolean containsValue(Object value) { return cache.containsValue(value); } @SuppressWarnings("unchecked") public synchronized ValT remove(Object key) { ValT value = cache.remove(key); if (isDiskCacheEnabled) { File cachedValue = getFileForKey((KeyT) key); if (cachedValue.exists()) { cachedValue.delete(); } } return value; } public Set<KeyT> keySet() { return cache.keySet(); } public Set<Map.Entry<KeyT, ValT>> entrySet() { return cache.entrySet(); } public synchronized int size() { return cache.size(); } public synchronized boolean isEmpty() { return cache.isEmpty(); } public synchronized void clear() { cache.clear(); if (isDiskCacheEnabled) { File[] cachedFiles = new File(diskCacheDir).listFiles(); if (cachedFiles == null) { return; } for (File f : cachedFiles) { f.delete(); } } } public Collection<ValT> values() { return cache.values(); } }
Java
package org.ttrssreader.utils; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import android.net.Uri; import android.text.TextUtils; // contains code from the Apache Software foundation public class StringSupport { /** * Turns a camel case string into an underscored one, e.g. "HelloWorld" * becomes "hello_world". * * @param camelCaseString * the string to underscore * @return the underscored string */ protected static String underscore(String camelCaseString) { String[] words = splitByCharacterTypeCamelCase(camelCaseString); return TextUtils.join("_", words).toLowerCase(); } /** * <p> * Splits a String by Character type as returned by <code>java.lang.Character.getType(char)</code>. Groups of * contiguous characters of the same type are returned as complete tokens, with the following exception: the * character of type <code>Character.UPPERCASE_LETTER</code>, if any, immediately preceding a token of type * <code>Character.LOWERCASE_LETTER</code> will belong to the following token rather than to the preceding, if any, * <code>Character.UPPERCASE_LETTER</code> token. * * <pre> * StringUtils.splitByCharacterTypeCamelCase(null) = null * StringUtils.splitByCharacterTypeCamelCase("") = [] * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"] * StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"] * StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"] * StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"] * StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"] * </pre> * * @param str * the String to split, may be <code>null</code> * @return an array of parsed Strings, <code>null</code> if null String * input * @since 2.4 */ private static String[] splitByCharacterTypeCamelCase(String str) { return splitByCharacterType(str, true); } /** * <p> * Splits a String by Character type as returned by <code>java.lang.Character.getType(char)</code>. Groups of * contiguous characters of the same type are returned as complete tokens, with the following exception: if * <code>camelCase</code> is <code>true</code>, the character of type <code>Character.UPPERCASE_LETTER</code>, if * any, immediately preceding a token of type <code>Character.LOWERCASE_LETTER</code> will belong to the following * token rather than to the preceding, if any, <code>Character.UPPERCASE_LETTER</code> token. * * @param str * the String to split, may be <code>null</code> * @param camelCase * whether to use so-called "camel-case" for letter types * @return an array of parsed Strings, <code>null</code> if null String * input * @since 2.4 */ private static String[] splitByCharacterType(String str, boolean camelCase) { if (str == null) { return null; } if (str.length() == 0) { return new String[0]; } char[] c = str.toCharArray(); ArrayList<String> list = new ArrayList<String>(); int tokenStart = 0; int currentType = Character.getType(c[tokenStart]); for (int pos = tokenStart + 1; pos < c.length; pos++) { int type = Character.getType(c[pos]); if (type == currentType) { continue; } if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { int newTokenStart = pos - 1; if (newTokenStart != tokenStart) { list.add(new String(c, tokenStart, newTokenStart - tokenStart)); tokenStart = newTokenStart; } } else { list.add(new String(c, tokenStart, pos - tokenStart)); tokenStart = pos; } currentType = type; } list.add(new String(c, tokenStart, c.length - tokenStart)); return (String[]) list.toArray(new String[list.size()]); } /** * Splits the ids into Sets of Strings with 50 ids each if configured in preferences, else only splits on 500 to * avoid extremely large requests. * * @param ids * the set of ids to be split * @param maxCount * the maximum length of each list * @return a set of Strings with comma-separated ids */ public static Set<String> convertListToString(Set<Integer> ids, int maxCount) { Set<String> ret = new HashSet<String>(); Iterator<Integer> it = ids.iterator(); StringBuilder idList = new StringBuilder(); int count = 0; while (it.hasNext()) { Integer next = it.next(); if (next == null) continue; idList.append(next); if (count == maxCount) { ret.add(idList.toString()); idList = new StringBuilder(); count = 0; } else { count++; } if (it.hasNext()) idList.append(","); } String list = idList.toString(); // Should not happen, but happens anyway: Cut of leading and trailing commas if (list.startsWith(",")) list = list.substring(1); if (list.endsWith(",")) list = list.substring(0, list.length() - 1); ret.add(list); return ret; } public static String[] setToArray(Set<String> set) { String[] ret = new String[set.size()]; int i = 0; for (String s : set) { ret[i++] = s; } return ret; } public static String getBaseURL(String url) { Uri uri = Uri.parse(url); if (uri != null) { return uri.getScheme() + "://" + uri.getAuthority(); } return null; } public static String convertStreamToString(InputStream inputStream) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = new BufferedInputStream(inputStream, 1024); byte[] buffer = new byte[1024]; int n = 0; try { while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); } } finally { out.close(); in.close(); } return out.toString("UTF-8"); } }
Java
// @formatter:off /** * <p>Encodes and decodes to and from Base64 notation.</p> * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> * * <p>Example:</p> * * <code>String encoded = Base64.encode( myByteArray );</code> * <br /> * <code>byte[] myByteArray = Base64.decode( encoded );</code> * * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass * several pieces of information to the encoder. In the "higher level" methods such as * encodeBytes( bytes, options ) the options parameter can be used to indicate such * things as first gzipping the bytes before encoding them, not inserting linefeeds, * and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, * Section 2.1, implementations should not add line feeds unless explicitly told * to do so. I've got Base64 set to this behavior now, although earlier versions * broke lines by default.</p> * * <p>The constants defined in Base64 can be OR-ed together to combine options, so you * might make a call like this:</p> * * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> * <p>to compress the data before encoding it and then making the output have newline characters.</p> * <p>Also...</p> * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> * * * * <p> * Change Log: * </p> * <ul> * <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the * value 01111111, which is an invalid base 64 character but should not * throw an ArrayIndexOutOfBoundsException either. Led to discovery of * mishandling (or potential for better handling) of other bad input * characters. You should now get an IOException if you try decoding * something that has bad characters in it.</li> * <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded * string ended in the last column; the buffer was not properly shrunk and * contained an extra (null) byte that made it into the string.</li> * <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size * was wrong for files of size 31, 34, and 37 bytes.</li> * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing * the Base64.OutputStream closed the Base64 encoding (by padding with equals * signs) too soon. Also added an option to suppress the automatic decoding * of gzipped streams. Also added experimental support for specifying a * class loader when using the * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} * method.</li> * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java * footprint with its CharEncoders and so forth. Fixed some javadocs that were * inconsistent. Removed imports and specified things like java.io.IOException * explicitly inline.</li> * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the * final encoded data will be so that the code doesn't have to create two output * arrays: an oversized initial one and then a final, exact-sized one. Big win * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not * using the gzip options which uses a different mechanism with streams and stuff).</li> * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some * similar helper methods to be more efficient with memory by not returning a * String but just a byte array.</li> * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments * and bug fixes queued up and finally executed. Thanks to everyone who sent * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. * Much bad coding was cleaned up including throwing exceptions where necessary * instead of returning null values or something similar. Here are some changes * that may affect you: * <ul> * <li><em>Does not break lines, by default.</em> This is to keep in compliance with * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> * <li><em>Throws exceptions instead of returning null values.</em> Because some operations * (especially those that may permit the GZIP option) use IO streams, there * is a possiblity of an java.io.IOException being thrown. After some discussion and * thought, I've changed the behavior of the methods to throw java.io.IOExceptions * rather than return null if ever there's an error. I think this is more * appropriate, though it will require some changes to your code. Sorry, * it should have been done this way to begin with.</li> * <li><em>Removed all references to System.out, System.err, and the like.</em> * Shame on me. All I can say is sorry they were ever there.</li> * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed * such as when passed arrays are null or offsets are invalid.</li> * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings. * This was especially annoying before for people who were thorough in their * own projects and then had gobs of javadoc warnings on this file.</li> * </ul> * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug * when using very small files (~&lt; 40 bytes).</li> * <li>v2.2 - Added some helper methods for encoding/decoding directly from * one file to the next. Also added a main() method to support command line * encoding/decoding from one file to the next. Also added these Base64 dialects: * <ol> * <li>The default is RFC3548 format.</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates * URL and file name friendly format as described in Section 4 of RFC3548. * http://www.faqs.org/rfcs/rfc3548.html</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates * URL and file name friendly format that preserves lexical ordering as described * in http://www.faqs.org/qa/rfcc-1940.html</li> * </ol> * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> * for contributing the new Base64 dialects. * </li> * * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.</li> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ package org.ttrssreader.utils; public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding in first bit. Value is one. */ public final static int ENCODE = 1; /** Specify decoding in first bit. Value is zero. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed in second bit. Value is two. */ public final static int GZIP = 2; /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */ public final static int DONT_GUNZIP = 4; /** Do break lines when encoding. Value is 8. */ public final static int DO_BREAK_LINES = 8; /** * Encode using Base64-like encoding that is URL- and Filename-safe as described * in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * It is important to note that data encoded this way is <em>not</em> officially valid Base64, * or at the very least should not be called Base64 without also specifying that is * was encoded using the URL- and Filename-safe dialect. */ public final static int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ public final static int ORDERED = 32; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ /** The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] _STANDARD_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] _STANDARD_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ /** * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ private final static byte[] _URL_SAFE_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' }; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ private final static byte[] _URL_SAFE_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ /** * I don't get the point of this technique, but someone requested it, * and it is described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ private final static byte[] _ORDERED_ALPHABET = { (byte)'-', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'_', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ /** * Returns one of the _SOMETHING_ALPHABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getAlphabet( int options ) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet /** * Returns one of the _SOMETHING_DECODABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED and URL_SAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getDecodabet( int options ) { if( (options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } // end getAlphabet /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; } // end encode3to4 /** * <p>Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>.</p> * <p>This is the lowest level of the encoding methods with * all possible parameters.</p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { byte[] ALPHABET = getAlphabet( options ); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> ByteBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); encoded.put(enc4); } // end input remaining } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> CharBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); for( int i = 0; i < 4; i++ ){ encoded.put( (char)(enc4[i] & 0xFF) ); } } // end input remaining } /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @throws java.io.IOException if there is an error * @throws NullPointerException if serializedObject is null * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) throws java.io.IOException { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @return The data in Base64-encoded form * @throws NullPointerException if source array is null * @since 1.4 */ public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * <p>As of v 2.3, if there is an error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes( source, off, len, NO_OPTIONS ); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { byte[] encoded = encodeBytesToBytes( source, off, len, options ); // Return value according to relevant encoding. try { return new String( encoded, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( encoded ); } // end catch } // end encodeBytes /** * Similar to {@link #encodeBytes(byte[])} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source ) { byte[] encoded = null; try { encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); } catch( java.io.IOException ex ) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; } /** * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } // end encodeBytesToBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * <p>This is the lowest level of the decoding methods with * all possible parameters.</p> * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid * or there is not enough room in the array. * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode( byte[] source ) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; } /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @param options Can specify options such as alphabet type to use * @return decoded data * @throws java.io.IOException If bogus characters exist in source data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len, int options ) throws java.io.IOException { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); } // end if if( len == 0 ){ return new byte[0]; }else if( len < 4 ){ throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len ); } // end if byte[] DECODABET = getDecodabet( options ); int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for( i = off; i < off+len; i++ ) { // Loop through source sbiDecode = DECODABET[ source[i]&0xFF ]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = source[i]; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( source[i] == EQUALS_SIGN ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format( "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @throws java.io.IOException If there is a problem * @since 1.4 */ public static byte[] decode( String s ) throws java.io.IOException { return decode( s, NO_OPTIONS ); } /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @param options encode options such as URL_SAFE * @return the decoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if <tt>s</tt> is null * @since 1.4 */ public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 1.5 */ public static Object decodeToObject( String encodedObject ) throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject,NO_OPTIONS,null); } /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * If <tt>loader</tt> is not null, it will be the class loader * used when deserializing. * * @param encodedObject The Base64 data to decode * @param options Various parameters related to decoding * @param loader Optional class loader to use in deserializing classes. * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 2.3.4 */ public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if dataToEncode is null * @since 2.1 */ public static void encodeToFile( byte[] dataToEncode, String filename ) throws java.io.IOException { if( dataToEncode == null ){ throw new NullPointerException( "Data to encode was null." ); } // end iff Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end encodeToFile /** * Convenience method for decoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @throws java.io.IOException if there is an error * @since 2.1 */ public static void decodeToFile( String dataToDecode, String filename ) throws java.io.IOException { Base64.OutputStream bos = null; try{ bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading encoded data * @return decoded byte array * @throws java.io.IOException if there is an error * @since 2.1 */ public static byte[] decodeFromFile( String filename ) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading binary data * @return base64-encoded string * @throws java.io.IOException if there is an error * @since 2.1 */ public static String encodeFromFile( String filename ) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void encodeFileToFile( String infile, String outfile ) throws java.io.IOException { String encoded = Base64.encodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end encodeFileToFile /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void decodeFileToFile( String infile, String outfile ) throws java.io.IOException { byte[] decoded = Base64.decodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( decoded ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end decodeFileToFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters private int options; // Record options used to create the stream. private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.options = options; // Record for later this.breakLines = (options & DO_BREAK_LINES) > 0; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } else { break; // out of for loop } // end else: end of stream } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; // Must be end of stream } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) { break; // Reads a -1 if end of stream } // end if: end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0, options ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ){ return -1; } // end if: got data if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) { position = -1; } // end if: end return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); if( b >= 0 ) { dest[off + i] = (byte) b; } else if( i == 0 ) { return -1; } else { break; // Out of 'for' loop } // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; private int options; // Record for later private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DO_BREAK_LINES) != 0; this.encode = (options & ENCODE) != 0; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; this.options = options; this.decodabet = getDecodabet(options); } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ @Override public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to encode. this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { this.out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to output. int len = Base64.decode4to3( buffer, 0, b4, 0, options ); out.write( b4, 0, len ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ @Override public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws java.io.IOException if there's an error. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position, options ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ @Override public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @throws java.io.IOException if there's an error flushing * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64 //@formatter:on
Java
/* * Copyright (C) 2008 OpenIntents.org * Modified 2010 by Nils Braden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.res.XmlResourceParser; public class MimeTypeParser { public static final String TAG_MIMETYPES = "MimeTypes"; public static final String TAG_TYPE = "type"; public static final String ATTR_EXTENSION = "extension"; public static final String ATTR_MIMETYPE = "mimetype"; private XmlPullParser mXpp; private MimeTypes mMimeTypes; public MimeTypeParser() { } public MimeTypes fromXml(InputStream in) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); mXpp = factory.newPullParser(); mXpp.setInput(new InputStreamReader(in)); return parse(); } public MimeTypes fromXmlResource(XmlResourceParser in) throws XmlPullParserException, IOException { mXpp = in; return parse(); } public MimeTypes parse() throws XmlPullParserException, IOException { mMimeTypes = new MimeTypes(); int eventType = mXpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tag = mXpp.getName(); if (eventType == XmlPullParser.START_TAG) { if (tag.equals(TAG_MIMETYPES)) { } else if (tag.equals(TAG_TYPE)) { addMimeTypeStart(); } } else if (eventType == XmlPullParser.END_TAG) { if (tag.equals(TAG_MIMETYPES)) { } } eventType = mXpp.next(); } return mMimeTypes; } private void addMimeTypeStart() { String extension = mXpp.getAttributeValue(null, ATTR_EXTENSION); String mimetype = mXpp.getAttributeValue(null, ATTR_MIMETYPE); mMimeTypes.put(extension, mimetype); } }
Java
/* * Copyright (C) 2008 OpenIntents.org * Modified 2010 by Nils Braden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ttrssreader.utils; import java.util.HashMap; import java.util.Map; import android.webkit.MimeTypeMap; public class MimeTypes { private Map<String, String> mMimeTypes; public MimeTypes() { mMimeTypes = new HashMap<String, String>(); } public void put(String type, String extension) { // Convert extensions to lower case letters for easier comparison extension = extension.toLowerCase(); mMimeTypes.put(type, extension); } public String getMimeType(String filename) { String extension = MimeTypes.getExtension(filename); // Let's check the official map first. Webkit has a nice extension-to-MIME map. // Be sure to remove the first character from the extension, which is the "." character. if (extension.length() > 0) { String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1)); if (webkitMimeType != null) { // Found one. Let's take it! return webkitMimeType; } } // Convert extensions to lower case letters for easier comparison extension = extension.toLowerCase(); String mimetype = mMimeTypes.get(extension); if (mimetype == null) mimetype = "*/*"; return mimetype; } public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot); } else { // No extension. return ""; } } }
Java
package org.ttrssreader.utils; import java.io.FileOutputStream; import org.ttrssreader.controllers.Controller; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; /** * Saves Exceptions with Stack-Trace to a file in the application-directory so it can be sent to the developer by mail * on the next run of the application. * * @author Jayesh from http://jyro.blogspot.com/2009/09/crash-report-for-android-app.html * */ public class TopExceptionHandler implements Thread.UncaughtExceptionHandler { public static final String FILE = "stack.trace"; private Thread.UncaughtExceptionHandler handler; private Activity app = null; public TopExceptionHandler(Activity app) { this.handler = Thread.getDefaultUncaughtExceptionHandler(); this.app = app; } public void uncaughtException(Thread t, Throwable e) { StackTraceElement[] element = e.getStackTrace(); StringBuilder sb = new StringBuilder(); sb.append(e.toString() + "\n\n"); sb.append("--------- Stacktrace ---------\n"); for (int i = 0; i < element.length; i++) { sb.append(" " + element[i].toString() + "\n"); } sb.append("------------------------------\n\n"); // If the exception was thrown in a background thread inside // AsyncTask, then the actual exception can be found with getCause Throwable cause = e.getCause(); if (cause != null) { sb.append("--------- Cause --------------\n"); sb.append(cause.toString() + "\n\n"); element = cause.getStackTrace(); for (int i = 0; i < element.length; i++) { sb.append(" " + element[i].toString() + "\n"); } sb.append("------------------------------\n\n"); } sb.append("--------- Device -------------\n"); sb.append("Brand: " + Build.BRAND + "\n"); sb.append("Device: " + Build.DEVICE + "\n"); sb.append("Model: " + Build.MODEL + "\n"); sb.append("Id: " + Build.ID + "\n"); sb.append("Product: " + Build.PRODUCT + "\n"); sb.append("------------------------------\n\n"); sb.append("--------- Firmware -----------\n"); sb.append("SDK: " + Build.VERSION.SDK + "\n"); sb.append("Release: " + Build.VERSION.RELEASE + "\n"); sb.append("Incremental: " + Build.VERSION.INCREMENTAL + "\n"); sb.append("------------------------------\n\n"); PackageManager pm = app.getPackageManager(); PackageInfo pi = null; try { pi = pm.getPackageInfo(app.getPackageName(), 0); } catch (Exception ex) { } sb.append("--------- Application --------\n"); sb.append("Version: " + Controller.getInstance().getLastVersionRun() + "\n"); sb.append("Version-Code: " + (pi != null ? pi.versionCode : "null") + "\n"); sb.append("------------------------------\n\n"); try { FileOutputStream trace = app.openFileOutput(FILE, Context.MODE_PRIVATE); trace.write(sb.toString().getBytes()); trace.close(); } catch (Exception ioe) { } handler.uncaughtException(t, e); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.utils; import java.io.FileNotFoundException; import java.net.URI; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.preferences.Constants; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.util.Log; public class Utils { /** * Min supported versions of the Tiny Tiny RSS Server */ public static final int SERVER_VERSION = 150; /** * The TAG for Log-Output */ public static final String TAG = "ttrss"; /** * Vibrate-Time for vibration when end of list is reached */ public static final long SHORT_VIBRATE = 50; /** * The time after which data will be fetched again from the server if asked for the data */ public static final int UPDATE_TIME = 600000; public static final int HALF_UPDATE_TIME = UPDATE_TIME / 2; /** * The Pattern to match image-urls inside HTML img-tags. */ public static final Pattern findImageUrlsPattern = Pattern.compile("<img.+src=\"([^\\\"]*)\".*>", Pattern.CASE_INSENSITIVE); private static final int ID_RUNNING = 4564561; private static final int ID_FINISHED = 7897891; /* * Check if this is the first run of the app, if yes, returns false. */ public static boolean checkFirstRun(Context a) { return !(Controller.getInstance().newInstallation()); } /* * Check if a new version of the app was installed, returns false if this is the case. */ public static boolean checkNewVersion(Context c) { String thisVersion = getAppVersionName(c); String lastVersionRun = Controller.getInstance().getLastVersionRun(); Controller.getInstance().setLastVersionRun(thisVersion); if (thisVersion.equals(lastVersionRun)) { // No new version installed, perhaps a new version exists // Only run task once for every session if (AsyncTask.Status.PENDING.equals(updateVersionTask.getStatus())) updateVersionTask.execute(); return true; } else { return false; } } /* * Check if crashreport-file exists, returns false if it exists. */ public static boolean checkCrashReport(Context c) { // Ignore crashreport if this version isn't the newest from market int latest = Controller.getInstance().appLatestVersion(); int current = getAppVersionCode(c); if (latest > current) return true; // Ignore! try { c.openFileInput(TopExceptionHandler.FILE); return false; } catch (FileNotFoundException e) { return true; } } /* * Checks the config for a user-defined server, returns true if a server has been defined */ public static boolean checkConfig() { URI uri = Controller.getInstance().url(); if (uri == null || uri.toASCIIString().equals(Constants.URL_DEFAULT + Controller.JSON_END_URL)) { return false; } return true; } /** * Retrieves the packaged version-code of the application * * @param c * - The Activity to retrieve the current version * @return the version-string */ public static int getAppVersionCode(Context c) { int result = 0; try { PackageManager manager = c.getPackageManager(); PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0); result = info.versionCode; } catch (NameNotFoundException e) { Log.w(TAG, "Unable to get application version: " + e.getMessage()); result = 0; } return result; } /** * Retrieves the packaged version-name of the application * * @param c * - The Activity to retrieve the current version * @return the version-string */ public static String getAppVersionName(Context c) { String result = ""; try { PackageManager manager = c.getPackageManager(); PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0); result = info.versionName; } catch (NameNotFoundException e) { Log.w(TAG, "Unable to get application version: " + e.getMessage()); result = ""; } return result; } /** * Checks if the option to work offline is set or if the data-connection isn't established, else returns true. If we * are about to connect it waits for maximum one second and then returns the network state without waiting anymore. * * @param cm * @return */ public static boolean isConnected(ConnectivityManager cm) { if (Controller.getInstance().workOffline()) return false; return checkConnected(cm); } /** * Wrapper for Method checkConnected(ConnectivityManager cm, boolean onlyWifi) * * @param cm * @return */ public static boolean checkConnected(ConnectivityManager cm) { return checkConnected(cm, false); } /** * Only checks the connectivity without regard to the preferences * * @param cm * @return */ public static boolean checkConnected(ConnectivityManager cm, boolean onlyWifi) { if (cm == null) return false; NetworkInfo info; if (onlyWifi) { info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } else { info = cm.getActiveNetworkInfo(); } if (info == null) return false; if (info.isConnected()) return true; synchronized (Utils.class) { int wait = 0; while (info.isConnectedOrConnecting() && !info.isConnected()) { try { wait += 100; Utils.class.wait(100); } catch (InterruptedException e) { e.printStackTrace(); } if (wait > 1000) { // Wait a maximum of one second for connection break; } } } return info.isConnected(); } public static void showFinishedNotification(String content, int time, boolean error, Context context) { showFinishedNotification(content, time, error, context, new Intent()); } /** * Shows a notification with the given parameters * * @param content * the string to display * @param time * how long the process took * @param error * set to true if an error occured * @param context * the context */ public static void showFinishedNotification(String content, int time, boolean error, Context context, Intent intent) { int icon; CharSequence title = ""; CharSequence ticker = ""; CharSequence text = content; if (content == null) text = context.getText(R.string.Utils_DownloadFinishedText); if (error) { icon = R.drawable.icon; title = context.getText(R.string.Utils_DownloadErrorTitle); ticker = context.getText(R.string.Utils_DownloadErrorTicker); } else { icon = R.drawable.icon; title = String.format((String) context.getText(R.string.Utils_DownloadFinishedTitle), time); ticker = context.getText(R.string.Utils_DownloadFinishedTicker); } String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotMan = (NotificationManager) context.getSystemService(ns); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); Notification n = new Notification(icon, ticker, System.currentTimeMillis()); n.flags |= Notification.FLAG_AUTO_CANCEL; n.setLatestEventInfo(context, title, text, pendingIntent); mNotMan.notify(ID_FINISHED, n); } public static void showRunningNotification(Context context, boolean finished) { showRunningNotification(context, finished, new Intent()); } /** * Shows a notification indicating that something is running. When called with finished=true it removes the * notification. * * @param context * the context * @param finished * if the notification is to be removed */ public static void showRunningNotification(Context context, boolean finished, Intent intent) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotMan = (NotificationManager) context.getSystemService(ns); // if finished remove notification and return, else display notification if (finished) { mNotMan.cancel(ID_RUNNING); return; } int icon = R.drawable.notification_icon; CharSequence title = context.getText(R.string.Utils_DownloadRunningTitle); CharSequence ticker = context.getText(R.string.Utils_DownloadRunningTicker); CharSequence text = context.getText(R.string.Utils_DownloadRunningText); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); Notification n = new Notification(icon, ticker, System.currentTimeMillis()); n.flags |= Notification.FLAG_AUTO_CANCEL; n.setLatestEventInfo(context, title, text, pendingIntent); mNotMan.notify(ID_RUNNING, n); } /** * Reads a file from my webserver and parses the content. It containts the version code of the latest supported * version. If the version of the installed app is lower then this the feature "Send mail with stacktrace on error" * will be disabled to make sure I only receive "new" Bugreports. */ private static AsyncTask<Void, Void, Void> updateVersionTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } // Check last appVersionCheckDate long last = Controller.getInstance().appVersionCheckTime(); long time = System.currentTimeMillis(); if (time - last > 86400000) { // More then one day // Retrieve remote version int remote = 0; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://nilsbraden.de/android/tt-rss/minSupportedVersion.txt"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity.getContentLength() < 0 || httpEntity.getContentLength() > 100) throw new Exception("Content too long or empty."); String content = EntityUtils.toString(httpEntity); // Only ever read the integer if it matches the regex and is not too long if (content.matches("[0-9]*[\\r\\n]*")) { content = content.replaceAll("[^0-9]*", ""); remote = Integer.parseInt(content); } } catch (Exception e) { Log.e(TAG, "Error while downloading version-information: " + e.getMessage()); } // Store version if (remote > 0) Controller.getInstance().setAppLatestVersion(remote); } // Also fetch the current API-Level from the server. This may be helpful later. last = Controller.getInstance().apiLevelUpdated(); if (time - last > 86400000) { // One day int apiLevel = Data.getInstance().getApiLevel(); Controller.getInstance().setApiLevel(apiLevel); } return null; } }; }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.net; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class FakeSocketFactory implements SocketFactory, LayeredSocketFactory { private SSLContext sslcontext = null; private static SSLContext createEasySSLContext() throws IOException { try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new FakeTrustManager() }, null); return context; } catch (Exception e) { throw new IOException(e.getMessage()); } } private SSLContext getSSLContext() throws IOException { if (this.sslcontext == null) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; } @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; } @Override public Socket createSocket() throws IOException { return getSSLContext().getSocketFactory().createSocket(); } @Override public boolean isSecure(Socket arg0) throws IllegalArgumentException { return true; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.net; import java.util.Map; import java.util.Set; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; public interface Connector { /** * Manually check if this controller is currently connected and the session is alive. Starts a login if not. */ public boolean sessionAlive(); /** * Retrieves a set of maps which map strings to the information, e.g. "id" -> 42, containing the counters for every * category and feed. The retrieved information is directly inserted into the database. * * @return true if the request succeeded. */ public boolean getCounters(); /** * Retrieves all categories. * * @return a list of categories. */ public Set<Category> getCategories(); /** * Retrieves all feeds, mapped to their categories. * * @return a map of all feeds mapped to the categories. */ public Set<Feed> getFeeds(); /** * Retrieves the specified articles and directly stores them in the database. * * @param id * the id of the feed/category * @param limit * the maximum number of articles to be fetched * @param viewMode * indicates wether only unread articles should be included (Possible values: all_articles, unread, * adaptive, marked, updated) * @param isCategory * indicates if we are dealing with a category or a feed * @return the number of fetched articles. */ public int getHeadlinesToDatabase(Integer id, int limit, String viewMode, boolean isCategory); /** * Retrieves the specified articles and directly stores them in the database. * * @param id * the id of the feed/category * @param limit * the maximum number of articles to be fetched * @param viewMode * indicates wether only unread articles should be included (Possible values: all_articles, unread, * adaptive, marked, updated) * @param isCategory * indicates if we are dealing with a category or a feed * @param sinceId * only retrieves articles with an id > sinceId, does nothing if set to zero. * @param skip * the number of articles which should be skipped from the newest article on, allows for pagination. * @return the number of fetched articles. */ public int getHeadlinesToDatabase(Integer id, int limit, String viewMode, boolean isCategory, int sinceId, int skip); /** * Marks the given list of article-Ids as read/unread depending on int articleState. * * @param articlesIds * a list of article-ids. * @param articleState * the new state of the article (0 -> mark as read; 1 -> mark as unread). */ public boolean setArticleRead(Set<Integer> ids, int articleState); /** * Marks the given Article as "starred"/"not starred" depending on int articleState. * * @param ids * a list of article-ids. * @param articleState * the new state of the article (0 -> not starred; 1 -> starred; 2 -> toggle). * @return true if the operation succeeded. */ public boolean setArticleStarred(Set<Integer> ids, int articleState); /** * Marks the given Articles as "published"/"not published" depending on articleState. * * @param ids * a list of article-ids with corresponding notes (may be null). * @param articleState * the new state of the articles (0 -> not published; 1 -> published; 2 -> toggle). * @return true if the operation succeeded. */ public boolean setArticlePublished(Map<Integer, String> ids, int articleState); /** * Marks a feed or a category with all its feeds as read. * * @param id * the feed-id/category-id. * @param isCategory * indicates whether id refers to a feed or a category. * @return true if the operation succeeded. */ public boolean setRead(int id, boolean isCategory); /** * Returns the value for the given preference-name as a string. * * @param pref * the preferences name * @return the value of the preference or null if it ist not set or unknown */ public String getPref(String pref); /** * Returns the version of the server-installation as integer (version-string without dots) * * @return the version */ public int getVersion(); /** * Retrieves the API-Level of the currently used server-installation. * * @return the API-Level of the server-installation */ public int getApiLevel(); /** * Returns true if there was an error. * * @return true if there was an error. */ public boolean hasLastError(); /** * Returns the last error-message and resets the error-state of the connector. * * @return a string with the last error-message. */ public String pullLastError(); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.net; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public class FakeTrustManager implements X509TrustManager { private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return _AcceptedIssuers; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.net; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JSONResult { private JSONArray names; private JSONArray values; // public TTRSSJsonResult(InputStream is) throws JSONException { // this(Utils.convertStreamToString(is)); // } public JSONResult(String input) throws JSONException { JSONObject object = new JSONObject(input); names = object.names(); values = object.toJSONArray(names); } public JSONArray getNames() { return names; } public JSONArray getValues() { return values; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.net; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyStore; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpParams; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.os.Environment; import android.util.Log; /** * Create a HttpClient object based on the user preferences. */ public class HttpClientFactory { private static HttpClientFactory instance; private SchemeRegistry registry; public HttpClientFactory() { boolean trustAllSslCerts = Controller.getInstance().trustAllSsl(); boolean useCustomKeyStore = Controller.getInstance().useKeystore(); registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); SocketFactory socketFactory = null; if (useCustomKeyStore) { String keystorePassword = Controller.getInstance().getKeystorePassword(); socketFactory = newSslSocketFactory(keystorePassword); if (socketFactory == null) { socketFactory = SSLSocketFactory.getSocketFactory(); Log.w(Utils.TAG, "Custom key store could not be read, using default settings."); } } else if (trustAllSslCerts) { socketFactory = new FakeSocketFactory(); } else { socketFactory = SSLSocketFactory.getSocketFactory(); } registry.register(new Scheme("https", socketFactory, 443)); } public DefaultHttpClient getHttpClient(HttpParams httpParams) { DefaultHttpClient httpInstance = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); return httpInstance; } public static HttpClientFactory getInstance() { synchronized (HttpClientFactory.class) { if (instance == null) { instance = new HttpClientFactory(); } } return instance; } /** * Create a socket factory with the custom key store * * @param keystorePassword * the password to unlock the custom keystore * * @return socket factory with custom key store */ private static SSLSocketFactory newSslSocketFactory(String keystorePassword) { try { KeyStore trusted = KeyStore.getInstance("BKS"); File file = new File(Environment.getExternalStorageDirectory() + File.separator + FileUtils.SDCARD_PATH_FILES + "store.bks"); if (!file.exists()) return null; InputStream in = new FileInputStream(file); try { trusted.load(in, keystorePassword.toCharArray()); } finally { in.close(); } return new SSLSocketFactory(trusted); } catch (Exception e) { e.printStackTrace(); } return null; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 N. 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.net; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.net.SocketException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.Base64; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; public class JSONConnector implements Connector { // other units in milliseconds static final int SECOND = 1000; static final int MINUTE = 60 * SECOND; private static String lastError = ""; private static boolean hasLastError = false; private static final String PARAM_OP = "op"; private static final String PARAM_USER = "user"; private static final String PARAM_PW = "password"; private static final String PARAM_CAT_ID = "cat_id"; private static final String PARAM_FEED_ID = "feed_id"; private static final String PARAM_ARTICLE_IDS = "article_ids"; private static final String PARAM_LIMIT = "limit"; private static final String PARAM_VIEWMODE = "view_mode"; private static final String PARAM_SHOW_CONTENT = "show_content"; private static final String PARAM_INC_ATTACHMENTS = "include_attachments"; // include_attachments available since // 1.5.3 but is ignored on older versions private static final String PARAM_SINCE_ID = "since_id"; private static final String PARAM_SKIP = "skip"; private static final String PARAM_MODE = "mode"; private static final String PARAM_FIELD = "field"; // 0-starred, 1-published, 2-unread, 3-article note (since api // level 1) private static final String PARAM_DATA = "data"; // optional data parameter when setting note field private static final String PARAM_IS_CAT = "is_cat"; private static final String PARAM_PREF = "pref_name"; private static final String PARAM_OUTPUT_MODE = "output_mode"; // output_mode (default: flc) - what kind of // information to return (f-feeds, l-labels, // c-categories, t-tags) private static final String VALUE_LOGIN = "login"; private static final String VALUE_GET_CATEGORIES = "getCategories"; private static final String VALUE_GET_FEEDS = "getFeeds"; private static final String VALUE_GET_HEADLINES = "getHeadlines"; private static final String VALUE_UPDATE_ARTICLE = "updateArticle"; private static final String VALUE_CATCHUP = "catchupFeed"; private static final String VALUE_UPDATE_FEED = "updateFeed"; private static final String VALUE_GET_PREF = "getPref"; private static final String VALUE_GET_VERSION = "getVersion"; private static final String VALUE_API_LEVEL = "getApiLevel"; private static final String VALUE_GET_COUNTERS = "getCounters"; private static final String VALUE_OUTPUT_MODE = "flc"; // f - feeds, l - labels, c - categories, t - tags private static final String ERROR = "error"; private static final String ERROR_TEXT = "Error: "; private static final String NOT_LOGGED_IN = "NOT_LOGGED_IN"; private static final String UNKNOWN_METHOD = "UNKNOWN_METHOD"; private static final String NOT_LOGGED_IN_MESSAGE = "Couldn't login to your account, please check your credentials."; private static final String API_DISABLED = "API_DISABLED"; private static final String API_DISABLED_MESSAGE = "Please enable API for the user \"%s\" in the preferences of this user on the Server."; private static final String STATUS = "status"; private static final String SESSION_ID = "session_id"; // session id as an out parameter private static final String SID = "sid"; // session id as an in parameter private static final String ID = "id"; private static final String TITLE = "title"; private static final String UNREAD = "unread"; private static final String CAT_ID = "cat_id"; private static final String FEED_ID = "feed_id"; private static final String UPDATED = "updated"; private static final String CONTENT = "content"; private static final String URL = "link"; private static final String FEED_URL = "feed_url"; private static final String COMMENT_URL = "comments"; private static final String ATTACHMENTS = "attachments"; private static final String CONTENT_URL = "content_url"; private static final String STARRED = "marked"; private static final String PUBLISHED = "published"; private static final String VALUE = "value"; private static final String VERSION = "version"; private static final String LEVEL = "level"; private static final String COUNTER_KIND = "kind"; private static final String COUNTER_CAT = "cat"; private static final String COUNTER_ID = "id"; private static final String COUNTER_COUNTER = "counter"; private static final int MAX_ID_LIST_LENGTH = 100; private String httpUsername; private String httpPassword; private String sessionId; private String loginLock = ""; private CredentialsProvider credProvider = null; private DefaultHttpClient client; public JSONConnector() { refreshHTTPAuth(); this.sessionId = null; } private void refreshHTTPAuth() { if (!Controller.getInstance().useHttpAuth()) return; boolean refreshNeeded = false; if (httpUsername == null || !httpUsername.equals(Controller.getInstance().httpUsername())) refreshNeeded = true; if (httpPassword == null || !httpPassword.equals(Controller.getInstance().httpPassword())) refreshNeeded = true; if (!refreshNeeded) return; // Refresh data httpUsername = Controller.getInstance().httpUsername(); httpPassword = Controller.getInstance().httpPassword(); // Refresh Credentials-Provider if (!httpUsername.equals(Constants.EMPTY) && !httpPassword.equals(Constants.EMPTY)) { credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(httpUsername, httpPassword)); } } private InputStream doRequest(Map<String, String> params, boolean firstCall) { HttpPost post = new HttpPost(); try { if (sessionId != null) { params.put(SID, sessionId); } // check if http-Auth-Settings have changed, reload values if necessary refreshHTTPAuth(); // Set Address post.setURI(Controller.getInstance().url()); post.addHeader("Accept-Encoding", "gzip"); // Add POST data JSONObject json = new JSONObject(params); StringEntity jsonData = new StringEntity(json.toString(), "UTF-8"); jsonData.setContentType("application/json"); post.setEntity(jsonData); // Add timeouts for the connection { HttpParams httpParams = post.getParams(); // Set the timeout until a connection is established. int timeoutConnection = 5 * SECOND; HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) which is the timeout for waiting for data. // use longer timeout when lazyServer-Feature is used int timeoutSocket = (Controller.getInstance().lazyServer()) ? 15 * MINUTE : 8 * SECOND; HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); post.setParams(httpParams); } // LOG-Output if (!Controller.getInstance().logSensitiveData()) { // Filter password and session-id Object paramPw = json.remove(PARAM_PW); Object paramSID = json.remove(SID); Log.i(Utils.TAG, "Request: " + json); json.put(PARAM_PW, paramPw); json.put(SID, paramSID); } else { Log.i(Utils.TAG, "Request: " + json); } if (client == null) client = HttpClientFactory.getInstance().getHttpClient(post.getParams()); else client.setParams(post.getParams()); // Add SSL-Stuff if (credProvider != null) client.setCredentialsProvider(credProvider); } catch (Exception e) { hasLastError = true; lastError = "Error creating HTTP-Connection [ " + e.getMessage() + " ]"; return null; } HttpResponse response = null; try { response = client.execute(post); // Execute the request } catch (ClientProtocolException e) { hasLastError = true; lastError = "ClientProtocolException on client.execute(post) [ " + e.getMessage() + " ]"; return null; } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(Utils.TAG, "SSLPeerUnverifiedException (" + e.getMessage() + ") in doRequest()"); return null; } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(Utils.TAG, "SSLException on client.execute(post) [ " + e.getMessage() + " ]"); } else { hasLastError = true; lastError = "SSLException on client.execute(post) [ " + e.getMessage() + " ]"; } return null; } catch (InterruptedIOException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(Utils.TAG, "InterruptedIOException (" + e.getMessage() + ") in doRequest()"); return null; } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(Utils.TAG, "SocketException (" + e.getMessage() + ") in doRequest()"); return null; } catch (IOException e) { Log.w(Utils.TAG, "IOException (" + e.getMessage() + ") in doRequest()"); return null; } // Try to check for HTTP Status codes int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_UNAUTHORIZED) { hasLastError = true; lastError = "Couldn't connect to server. returned status: \"401 Unauthorized (HTTP/1.0 - RFC 1945)\""; return null; } InputStream instream = null; try { HttpEntity entity = response.getEntity(); if (entity != null) instream = entity.getContent(); // Try to decode gzipped instream, if it is not gzip we stay to normal reading Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) instream = new GZIPInputStream(instream); if (instream == null) { hasLastError = true; lastError = "Couldn't get InputStream in Method doRequest(String url) [instream was null]"; return null; } } catch (Exception e) { if (instream != null) try { instream.close(); } catch (IOException e1) { } hasLastError = true; lastError = "Exception: " + e.getMessage(); return null; } return instream; } private String readResult(Map<String, String> params, boolean login, boolean firstCall) throws IOException { InputStream in = doRequest(params, true); if (in == null) return null; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); String ret = ""; // Check if content contains array or object, array indicates login-response or error, object is content reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_OBJECT)) { JsonObject object = new JsonObject(); reader.beginObject(); while (reader.hasNext()) { object.addProperty(reader.nextName(), reader.nextString()); } reader.endObject(); if (object.get(SESSION_ID) != null) { ret = object.get(SESSION_ID).getAsString(); break; } else if (object.get(STATUS) != null) { ret = object.get(STATUS).getAsString(); break; } else if (object.get(VALUE) != null) { ret = object.get(VALUE).getAsString(); break; } else if (object.get(ERROR) != null) { String message = object.get(ERROR).getAsString(); if (message.contains(NOT_LOGGED_IN)) { sessionId = null; if (login()) return readResult(params, login, false); // Just do the same request again else return null; } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = String.format(API_DISABLED_MESSAGE, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = ERROR_TEXT + message; return null; } } } else { reader.skipValue(); } } reader.close(); if (ret.startsWith("\"")) ret = ret.substring(1, ret.length()); if (ret.endsWith("\"")) ret = ret.substring(0, ret.length() - 1); return ret; } private JsonReader prepareReader(Map<String, String> params) throws IOException { return prepareReader(params, true); } private JsonReader prepareReader(Map<String, String> params, boolean firstCall) throws IOException { InputStream in = doRequest(params, true); if (in == null) return null; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_OBJECT)) { // Handle error JsonObject object = new JsonObject(); reader.beginObject(); while (reader.hasNext()) { object.addProperty(reader.nextName(), reader.nextString()); } reader.endObject(); if (object.get(ERROR) != null) { String message = object.get(ERROR).toString(); if (message.contains(NOT_LOGGED_IN)) { sessionId = null; if (login()) return prepareReader(params, false); // Just do the same request again else return null; } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = String.format(API_DISABLED_MESSAGE, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = ERROR_TEXT + message; } } else if (t.equals(JsonToken.BEGIN_ARRAY)) { return reader; } } else { reader.skipValue(); } } return null; } public boolean sessionAlive() { // Make sure we are logged in if (sessionId == null || lastError.equals(NOT_LOGGED_IN)) if (!login()) return false; if (hasLastError) return false; return true; } /** * Does an API-Call and ignores the result. * * @param params * @return true if the call was successful. */ private boolean doRequestNoAnswer(Map<String, String> params) { if (!sessionAlive()) return false; try { String result = readResult(params, false, true); Log.d(Utils.TAG, "Result: " + result); if ("OK".equals(result)) return true; else return false; } catch (IOException e) { e.printStackTrace(); if (!hasLastError) { hasLastError = true; lastError = ERROR_TEXT + e.getMessage(); } } return false; } /** * Tries to login to the ttrss-server with the base64-encoded password. * * @return true on success, false otherwise */ private boolean login() { long time = System.currentTimeMillis(); // Just login once, check if already logged in after acquiring the lock on mSessionId synchronized (loginLock) { if (sessionId != null && !(lastError.equals(NOT_LOGGED_IN))) return true; // Login done while we were waiting for the lock Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_LOGIN); params.put(PARAM_USER, Controller.getInstance().username()); params.put(PARAM_PW, Base64.encodeBytes(Controller.getInstance().password().getBytes())); // No check with assertLogin here, we are about to login so no need for this. sessionId = null; try { sessionId = readResult(params, true, true); if (sessionId != null) { Log.v(Utils.TAG, "login: " + (System.currentTimeMillis() - time) + "ms"); return true; } } catch (IOException e) { e.printStackTrace(); if (!hasLastError) { hasLastError = true; lastError = ERROR_TEXT + e.getMessage(); } } if (!hasLastError) { // Login didnt succeed, write message hasLastError = true; lastError = NOT_LOGGED_IN_MESSAGE; } return false; } } // ***************** Helper-Methods ************************************************** private void parseCounter(JsonReader reader) { SQLiteDatabase db = DBHelper.getInstance().db; synchronized (DBHelper.TABLE_ARTICLES) { db.beginTransaction(); try { reader.beginArray(); while (reader.hasNext()) { boolean cat = false; int id = Integer.MAX_VALUE; int counter = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(COUNTER_KIND)) { cat = reader.nextString().equals(COUNTER_CAT); } else if (name.equals(COUNTER_ID)) { String value = reader.nextString(); // Check if id is a string, then it would be a global counter if (value.equals("global-unread") || value.equals("subscribed-feeds")) continue; id = Integer.parseInt(value); } else if (name.equals(COUNTER_COUNTER)) { String value = reader.nextString(); // Check if null because of an API-bug if (!value.equals("null")) counter = Integer.parseInt(value); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); ContentValues cv = new ContentValues(); cv.put("unread", counter); if (id == Integer.MAX_VALUE) continue; if (cat && id >= 0) { // Category db.update(DBHelper.TABLE_CATEGORIES, cv, "id=?", new String[] { id + "" }); Data.getInstance().setFeedsChanged(id, System.currentTimeMillis()); } else if (!cat && id < 0 && id >= -4) { // Virtual Category db.update(DBHelper.TABLE_CATEGORIES, cv, "id=?", new String[] { id + "" }); } else if (!cat && id > 0) { // Feed db.update(DBHelper.TABLE_FEEDS, cv, "id=?", new String[] { id + "" }); } else if (!cat && id < -10) { // Label db.update(DBHelper.TABLE_FEEDS, cv, "id=?", new String[] { id + "" }); } } reader.endArray(); db.setTransactionSuccessful(); } catch (IOException e) { e.printStackTrace(); } finally { db.endTransaction(); Data.getInstance().setCategoriesChanged(System.currentTimeMillis()); DBHelper.getInstance().purgeArticlesNumber(); } } } private Set<String> parseAttachments(JsonReader reader) throws IOException { Set<String> ret = new HashSet<String>(); reader.beginArray(); while (reader.hasNext()) { String attId = null; String attUrl = null; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(CONTENT_URL)) { attUrl = reader.nextString(); } else if (name.equals(ID)) { attId = reader.nextString(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); if (attId != null && attUrl != null) ret.add(attUrl); } reader.endArray(); return ret; } private int parseArticleArray(JsonReader reader, int labelId, int catId, boolean isCategory) { long time = System.currentTimeMillis(); int count = 0; SQLiteDatabase db = DBHelper.getInstance().db; synchronized (DBHelper.TABLE_ARTICLES) { db.beginTransaction(); try { // People are complaining about not all articles being marked the right way, so just overwrite all // unread // states and fetch new articles... // Moved this inside the transaction to make sure this only happens if the transaction is successful DBHelper.getInstance().markFeedOnlyArticlesRead(catId, isCategory); // List<Object[]> articleList = new ArrayList<Object[]>(); reader.beginArray(); while (reader.hasNext()) { count++; int id = -1; String title = null; boolean isUnread = false; Date updated = null; int realFeedId = 0; String content = null; String articleUrl = null; String articleCommentUrl = null; Set<String> attachments = null; boolean isStarred = false; boolean isPublished = false; reader.beginObject(); while (reader.hasNext() && reader.peek().equals(JsonToken.NAME)) { // ? String name = reader.nextName(); try { if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(UNREAD)) { isUnread = reader.nextBoolean(); } else if (name.equals(UPDATED)) { updated = new Date(new Long(reader.nextString() + "000").longValue()); } else if (name.equals(FEED_ID)) { realFeedId = reader.nextInt(); } else if (name.equals(CONTENT)) { content = reader.nextString(); } else if (name.equals(URL)) { articleUrl = reader.nextString(); } else if (name.equals(COMMENT_URL)) { articleCommentUrl = reader.nextString(); } else if (name.equals(ATTACHMENTS)) { attachments = parseAttachments(reader); } else if (name.equals(STARRED)) { isStarred = reader.nextBoolean(); } else if (name.equals(PUBLISHED)) { isPublished = reader.nextBoolean(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { Log.w(Utils.TAG, "Result contained illegal value for entry \"" + name + "\"."); reader.skipValue(); continue; } } reader.endObject(); if (id != -1 && title != null) { DBHelper.getInstance().insertArticle(id, realFeedId, title, isUnread, articleUrl, articleCommentUrl, updated, content, attachments, isStarred, isPublished, labelId); // articleList.add(DBHelper.prepareArticleArray(id, realFeedId, title, isUnread, articleUrl, // articleCommentUrl, updated, content, attachments, isStarred, isPublished, labelId)); } // See comment on DBHelper.getInstance().bulkInsertArticles for information about this. // if (articleList.size() > 100) { // DBHelper.getInstance().bulkInsertArticles(articleList); // articleList = new ArrayList<Object[]>(); // } } reader.endArray(); db.setTransactionSuccessful(); } catch (IOException e) { e.printStackTrace(); } finally { db.endTransaction(); if (isCategory) Data.getInstance().setCategoriesChanged(System.currentTimeMillis()); else Data.getInstance().setFeedsChanged(catId, System.currentTimeMillis()); DBHelper.getInstance().purgeArticlesNumber(); } } Log.d(Utils.TAG, "INSERT took " + (System.currentTimeMillis() - time) + "ms"); return count; } // ***************** Retrieve-Data-Methods ************************************************** @Override public boolean getCounters() { boolean ret = true; makeLazyServerWork(); // otherwise the unread counters may be outdated if (!sessionAlive()) return false; long time = System.currentTimeMillis(); Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_COUNTERS); params.put(PARAM_OUTPUT_MODE, VALUE_OUTPUT_MODE); JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return false; parseCounter(reader); } catch (IOException e) { e.printStackTrace(); ret = false; } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.v(Utils.TAG, "getCounters: " + (System.currentTimeMillis() - time) + "ms"); return ret; } @Override public Set<Category> getCategories() { long time = System.currentTimeMillis(); Set<Category> ret = new LinkedHashSet<Category>(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_CATEGORIES); JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int id = -1; String title = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(UNREAD)) { unread = reader.nextInt(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); // Don't handle categories with an id below 1, we already have them in the DB from // Data.updateVirtualCategories() if (id > 0 && title != null) ret.add(new Category(id, title, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.v(Utils.TAG, "getCategories: " + (System.currentTimeMillis() - time) + "ms"); return ret; } private Set<Feed> getFeeds(boolean tolerateWrongUnreadInformation) { long time = System.currentTimeMillis(); Set<Feed> ret = new LinkedHashSet<Feed>();; if (!sessionAlive()) return ret; if (!tolerateWrongUnreadInformation) { makeLazyServerWork(); } Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_FEEDS); params.put(PARAM_CAT_ID, Data.VCAT_ALL + ""); // Hardcoded -4 fetches all feeds. See // http://tt-rss.org/redmine/wiki/tt-rss/JsonApiReference#getFeeds JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int categoryId = -1; int id = 0; String title = null; String feedUrl = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(CAT_ID)) { categoryId = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(FEED_URL)) { feedUrl = reader.nextString(); } else if (name.equals(UNREAD)) { unread = reader.nextInt(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); if (id != -1 || categoryId == -2) // normal feed (>0) or label (-2) if (title != null) // Dont like complicated if-statements.. ret.add(new Feed(id, categoryId, title, feedUrl, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.v(Utils.TAG, "getFeeds: " + (System.currentTimeMillis() - time) + "ms"); return ret; } @Override public Set<Feed> getFeeds() { return getFeeds(false); } private boolean makeLazyServerWork(Integer feedId) { if (Controller.getInstance().lazyServer()) { Map<String, String> taskParams = new HashMap<String, String>(); taskParams.put(PARAM_OP, VALUE_UPDATE_FEED); taskParams.put(PARAM_FEED_ID, feedId + ""); return doRequestNoAnswer(taskParams); } return true; } private long noTaskUntil = 0; final static private long minTaskIntervall = 10 * MINUTE; private boolean makeLazyServerWork() { boolean ret = true; final long time = System.currentTimeMillis(); if (Controller.getInstance().lazyServer() && (noTaskUntil < time)) { noTaskUntil = time + minTaskIntervall; Set<Feed> feedset = getFeeds(true); Iterator<Feed> feeds = feedset.iterator(); while (feeds.hasNext()) { final Feed f = feeds.next(); ret = ret && makeLazyServerWork(f.id); } } return ret; } @Override public int getHeadlinesToDatabase(Integer id, int limit, String viewMode, boolean isCategory) { return getHeadlinesToDatabase(id, limit, viewMode, isCategory, 0, 0); } @Override public int getHeadlinesToDatabase(Integer id, int limit, String viewMode, boolean isCategory, int sinceId, int skip) { long time = System.currentTimeMillis(); int count = 0; if (!sessionAlive()) return -1; makeLazyServerWork(id); Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_HEADLINES); params.put(PARAM_FEED_ID, id + ""); params.put(PARAM_LIMIT, limit + ""); params.put(PARAM_VIEWMODE, viewMode); params.put(PARAM_SHOW_CONTENT, "1"); params.put(PARAM_INC_ATTACHMENTS, "1"); params.put(PARAM_IS_CAT, (isCategory ? "1" : "0")); if (sinceId > 0) params.put(PARAM_SINCE_ID, sinceId + ""); if (skip > 0) params.put(PARAM_SKIP, skip + ""); if (id == Data.VCAT_STAR && !isCategory) // We set isCategory=false for starred/published articles... DBHelper.getInstance().purgeStarredArticles(); if (id == Data.VCAT_PUB && !isCategory) DBHelper.getInstance().purgePublishedArticles(); JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return -1; count = parseArticleArray(reader, (!isCategory && id < -10 ? id : -1), id, isCategory); } catch (IOException e) { e.printStackTrace(); return -1; } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.v(Utils.TAG, "getHeadlinesToDatabase: " + (System.currentTimeMillis() - time) + "ms"); return count; } @Override public boolean setArticleRead(Set<Integer> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "2"); ret = ret && doRequestNoAnswer(params); } return ret; } @Override public boolean setArticleStarred(Set<Integer> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "0"); ret = ret && doRequestNoAnswer(params); } return ret; } @Override public boolean setArticlePublished(Map<Integer, String> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids.keySet(), MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "1"); ret = ret && doRequestNoAnswer(params); // Add a note to the article(s) for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; params.put(PARAM_FIELD, "3"); // Field 3 is the "Add note" field params.put(PARAM_DATA, note); ret = ret && doRequestNoAnswer(params); } } return ret; } @Override public boolean setRead(int id, boolean isCategory) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_CATCHUP); params.put(PARAM_FEED_ID, id + ""); params.put(PARAM_IS_CAT, (isCategory ? "1" : "0")); return doRequestNoAnswer(params); } @Override public String getPref(String pref) { if (!sessionAlive()) return null; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_PREF); params.put(PARAM_PREF, pref); try { String ret = readResult(params, false, true); return ret; } catch (IOException e) { e.printStackTrace(); } return null; } @Override public int getVersion() { int ret = -1; if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_VERSION); String response = ""; JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { try { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals(VERSION)) { response = reader.nextString(); } else { reader.skipValue(); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } } // Replace dots, parse integer ret = Integer.parseInt(response.replace(".", "")); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } @Override public int getApiLevel() { int ret = -1; if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_API_LEVEL); String response = ""; JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { try { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals(LEVEL)) { response = reader.nextString(); } else { reader.skipValue(); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } } if (response.contains(UNKNOWN_METHOD)) { ret = 0; // Assume Api-Level 0 } else { ret = Integer.parseInt(response); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } @Override public boolean hasLastError() { return hasLastError; } @Override public String pullLastError() { String ret = new String(lastError); lastError = ""; hasLastError = false; return ret; } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import com.google.gwt.core.client.JavaScriptObject; /** * Global JavaScript function for JSON callbacks from non-RPC invocations. * <p> * To setup a callback declare one in your remote service interface: * * <pre> * public interface MyActions extends RemoteJsonService { * CallbackHandle&lt;MyResult&gt; forMyResult(AsyncCallback&lt;MyResult&gt; ac); * } * </pre> * <p> * Then in your application code create the callback handle and obtain its * function name. Pass the function name to the remote service, so the remote * service can execute: * * <pre> * $functionName($result) * </pre> * <p> * where <code>$functionName</code> came from {@link #getFunctionName()} (you * may need to prefix <code>"parent."</code> if invoking within an iframe) and * <code>$result</code> is the native JSON encoding of the <code>MyResult</code> * object type. * <p> * When the callback is complete it will be automatically unregistered from the * window and your {@link AsyncCallback}'s <code>onSuccess</code> will be called * with the deserialized <code>MyResult</code> instance. * <p> * Each CallbackHandle uses a unique function name, permitting the application * to use multiple concurrent callbacks. Handles which are canceled before the * response is received will never be invoked. */ public class CallbackHandle<R> { private static int callbackId; static { nativeInit(); } private static int nextFunction() { return ++callbackId; } private final ResultDeserializer<R> deserializer; private final AsyncCallback<R> callback; private int functionId; /** * Create a new callback instance. * <p> * Typically this should be done by a factory function inside of a * RemoteJsonService interface. * * @param ser parses the JSON result once received back. * @param ac the application callback function to supply the result to. Only * <code>onSuccess</code> will be invoked. */ public CallbackHandle(final ResultDeserializer<R> ser, final AsyncCallback<R> ac) { deserializer = ser; callback = ac; } /** * Install this handle into the browser window and generate a unique name. * <p> * Does nothing if the callback has already been installed. * <p> * This method pins this callback object and the application supplied * {@link AsyncCallback} into the global browser memory, so it exists when the * JSON service returns with its result data. If the JSON service never * returns, the callback (and anything it reaches) may leak. Applications can * use {@link #cancel()} to explicitly remove this handle. */ public void install() { if (functionId == 0) { functionId = nextFunction(); nativeInstall(functionId, this); } } /** * Obtain the unique function name for this JSON callback. * <p> * Applications must call {@link #install()} first to ensure the function name * has been generated and installed into the window. The function name is only * valid until either {@link #cancel()} is called or the remote service has * returned the call. * * @return name of the function the JSON service should call with the * resulting data. */ public String getFunctionName() { assert functionId > 0; return "__gwtjsonrpc_callbackhandle[" + functionId + "]"; } /** * Delete this function from the browser so it can't be called. * <p> * Does nothing if the callback has already been canceled. * <p> * This method deletes the function, permitting <code>this</code> and the * application callback to be garbage collected. Automatically invoked when a * result is received. */ public void cancel() { if (functionId > 0) { nativeDelete(functionId); functionId = 0; } } final void onResult(final JavaScriptObject rpcResult) { cancel(); JsonUtil.invoke(deserializer, callback, rpcResult); } private static final native void nativeInit() /*-{ $wnd.__gwtjsonrpc_callbackhandle = new Array(); }-*/; private static final native void nativeDelete(int funid) /*-{ delete $wnd.__gwtjsonrpc_callbackhandle[funid]; }-*/; private static final native void nativeInstall(int funid, CallbackHandle<?> imp) /*-{ $wnd.__gwtjsonrpc_callbackhandle[funid] = function(r) { imp.@org.rapla.rest.gwtjsonrpc.client.CallbackHandle::onResult(Lcom/google/gwt/core/client/JavaScriptObject;)({result:r}); }; }-*/; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; import org.rapla.rest.gwtjsonrpc.client.event.BaseRpcEvent; import org.rapla.rest.gwtjsonrpc.client.event.RpcCompleteEvent; import org.rapla.rest.gwtjsonrpc.client.event.RpcCompleteHandler; import org.rapla.rest.gwtjsonrpc.client.event.RpcStartEvent; import org.rapla.rest.gwtjsonrpc.client.event.RpcStartHandler; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.rpc.InvocationException; import com.google.gwt.user.client.rpc.ServiceDefTarget; /** Client side utility functions. */ public class JsonUtil { private static final HandlerManager globalHandlers = new HandlerManager(null); /** * Bind a RemoteJsonService proxy to its server URL. * * @param <T> type of the service interface. * @param imp the service instance, returned by <code>GWT.create</code>. * @param path the path of the service, relative to the GWT module. * @return always <code>imp</code>. * @see com.google.gwt.user.client.rpc.RemoteServiceRelativePath */ public static <T> T bind(final T imp, final String path) { assert GWT.isClient(); assert imp instanceof ServiceDefTarget; final String base = GWT.getModuleBaseURL(); ((ServiceDefTarget) imp).setServiceEntryPoint(base + path); return imp; } /** Register a handler for RPC start events. */ public static HandlerRegistration addRpcStartHandler(RpcStartHandler h) { return globalHandlers.addHandler(RpcStartEvent.getType(), h); } /** Register a handler for RPC completion events. */ public static HandlerRegistration addRpcCompleteHandler(RpcCompleteHandler h) { return globalHandlers.addHandler(RpcCompleteEvent.getType(), h); } public static void fireEvent(BaseRpcEvent<?> event) { globalHandlers.fireEvent(event); } public static <T> void invoke(final ResultDeserializer<T> resultDeserializer, final AsyncCallback<T> callback, final JavaScriptObject rpcResult) { final T result; try { result = resultDeserializer.fromResult(rpcResult); } catch (RuntimeException e) { callback.onFailure(new InvocationException("Invalid JSON Response", e)); return; } callback.onSuccess(result); } private JsonUtil() { } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; import com.google.gwt.json.client.JSONValue; /** * Exception given to * {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback#onFailure(Throwable)}. * <p> * This exception is used if the remote JSON server has returned a well-formed * JSON error response. */ public class RemoteJsonException extends Exception { private static final long serialVersionUID = 1L; private int code; private JSONValue data; /** * Construct a new exception representing a well formed JSON error response. * * @param message A String value that provides a short description of the * error * @param code A number that indicates the actual error that occurred * @param data A JSON value instance that carries custom and * application-specific error information */ public RemoteJsonException(final String message, int code, JSONValue data) { super(message); this.code = code; this.data = data; } /** * Creates a new RemoteJsonException with code 999 and no data. * * @param message A String value that provides a short description of the * error */ public RemoteJsonException(final String message) { this(message, 999, null); } /** * Gets the error code. * <p> * Note that the JSON-RPC 1.1 draf does not define error codes yet. * * @return A number that indicates the actual error that occurred. */ public int getCode() { return code; } /** * Same as getData. * * @return the error data, or <code>null</code> if none was specified * @see #getData */ public JSONValue getError() { return data; } /** * Gets the extra error information supplied by the service. * * @return the error data, or <code>null</code> if none was specified */ public JSONValue getData() { return data; } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import com.google.gwt.core.client.GWT; /** Simple callback to ignore a return value. */ public class VoidCallback implements AsyncCallback<VoidResult> { public static final VoidCallback INSTANCE = new VoidCallback(); protected VoidCallback() { } @Override public void onSuccess(final VoidResult result) { } @Override public void onFailure(final Throwable caught) { GWT.log("Error in VoidCallback", caught); } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client; /** * Indicates the remote JSON server is not available. * <p> * Usually supplied to {@link org.rapla.rest.gwtjsonrpc.common.AsyncCallback#onFailure(Throwable)} when the * remote host isn't answering, such as if the HTTP server is restarting and has * temporarily stopped accepting new connections. */ @SuppressWarnings("serial") public class ServerUnavailableException extends Exception { public static final String MESSAGE = "Server Unavailable"; public ServerUnavailableException() { super(MESSAGE); } }
Java
package org.rapla.rest.gwtjsonrpc.client.impl; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import org.rapla.rest.gwtjsonrpc.common.FutureResult; public class FutureResultImpl<T> implements FutureResult<T> { JsonCall call; public T get() throws Exception { throw new UnsupportedOperationException(); } public T get(long wait) throws Exception { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public void get(AsyncCallback<T> callback) { call.send(callback); } public void setCall( JsonCall call) { this.call = call; } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl; import com.google.gwt.core.client.JavaScriptObject; /** * Base class for the {@link PrimitiveArrayResultDeserializer} and generated * object array result deserializers. */ public abstract class ArrayResultDeserializer { protected static native JavaScriptObject getResult( JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; protected static native int getResultSize(JavaScriptObject responseObject) /*-{ return responseObject.result.length; }-*/; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl; import org.rapla.rest.gwtjsonrpc.client.ServerUnavailableException; import org.rapla.rest.gwtjsonrpc.client.event.RpcCompleteEvent; import org.rapla.rest.gwtjsonrpc.client.event.RpcStartEvent; import org.rapla.rest.gwtjsonrpc.common.AsyncCallback; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; public abstract class JsonCall<T> implements RequestCallback { protected static final JavaScriptObject jsonParser; static { jsonParser = selectJsonParser(); } /** * Select the most efficient available JSON parser. * * If we have a native JSON parser, present in modern browsers (FF 3.5 and * IE8, at time of writing), it is returned. If no native parser is found, a * parser function using <code>eval</code> is returned. * * This is done dynamically, not with a GWT user.agent check, because FF3.5 * does not have a specific user.agent associated with it. Introducing a new * property for the presence of an ES3.1 parser is not worth it, since the * check is only done once anyway, and will result in significantly longer * compile times. * * As GWT will undoubtedly introduce support for the native JSON parser in the * {@link com.google.gwt.json.client.JSONParser JSONParser} class, this code * should be reevaluated to possibly use the GWT parser reference. * * @return a javascript function with the fastest available JSON parser * @see "http://wiki.ecmascript.org/doku.php?id=es3.1:json_support" */ private static native JavaScriptObject selectJsonParser() /*-{ if ($wnd.JSON && typeof $wnd.JSON.parse === 'function') return $wnd.JSON.parse; else return function(expr) { return eval('(' + expr + ')'); }; }-*/; protected final AbstractJsonProxy proxy; protected final String methodName; protected final String requestParams; protected final ResultDeserializer<T> resultDeserializer; protected int attempts; protected AsyncCallback<T> callback; private String token; protected JsonCall(final AbstractJsonProxy abstractJsonProxy, final String methodName, final String requestParams, final ResultDeserializer<T> resultDeserializer) { this.proxy = abstractJsonProxy; this.methodName = methodName; this.requestParams = requestParams; this.resultDeserializer = resultDeserializer; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public AbstractJsonProxy getProxy() { return proxy; } public String getMethodName() { return methodName; } protected abstract void send(); public void send(AsyncCallback<T> callback) { this.callback = callback; send(); } protected void send(RequestBuilder rb) { try { if ( token != null) { rb.setHeader("Authorization", "Bearer " + token); } attempts++; rb.send(); } catch (RequestException e) { callback.onFailure(e); return; } if (attempts == 1) { RpcStartEvent.fire(this); } } @Override public void onError(final Request request, final Throwable exception) { RpcCompleteEvent.fire(this); if (exception.getClass() == RuntimeException.class && exception.getMessage().contains("XmlHttpRequest.status")) { // GWT's XMLHTTPRequest class gives us RuntimeException when the // status code is unreadable from the browser. This occurs when // the connection has failed, e.g. the host is down. // callback.onFailure(new ServerUnavailableException()); } else { callback.onFailure(exception); } } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.rpc.InvocationException; import com.google.gwt.user.client.rpc.RpcRequestBuilder; import com.google.gwt.user.client.rpc.ServiceDefTarget; /** * Base class for generated RemoteJsonService implementations. * <p> * At runtime <code>GWT.create(Foo.class)</code> returns a subclass of this * class, implementing the Foo and {@link ServiceDefTarget} interfaces. */ public abstract class AbstractJsonProxy implements ServiceDefTarget { /** URL of the service implementation. */ String url; private String token; @Override public String getServiceEntryPoint() { return url; } @Override public void setServiceEntryPoint(final String address) { url = address; } @Override public String getSerializationPolicyName() { return "jsonrpc"; } @Override public void setRpcRequestBuilder(RpcRequestBuilder builder) { if (builder != null) throw new UnsupportedOperationException( "A RemoteJsonService does not use the RpcRequestBuilder, so this method is unsupported."); /** * From the gwt docs: * * Calling this method with a null value will reset any custom behavior to * the default implementation. * * If builder == null, we just ignore this invocation. */ } protected <T> void doInvoke(final String methodName, final String reqData, final ResultDeserializer<T> ser, final FutureResultImpl<T> cb) throws InvocationException { if (url == null) { throw new NoServiceEntryPointSpecifiedException(); } JsonCall<T> newJsonCall = newJsonCall(this, methodName, reqData, ser); cb.setCall( newJsonCall); if ( token != null ) { newJsonCall.setToken( token ); } } protected abstract <T> JsonCall<T> newJsonCall(AbstractJsonProxy proxy, final String methodName, final String reqData, final ResultDeserializer<T> ser); protected static native JavaScriptObject hostPageCacheGetOnce(String name) /*-{ var r = $wnd[name];$wnd[name] = null;return r ? {result: r} : null; }-*/; protected static native JavaScriptObject hostPageCacheGetMany(String name) /*-{ return $wnd[name] ? {result : $wnd[name]} : null; }-*/; public void setAuthThoken(String token) { this.token = token; } }
Java
// Copyright 2009 Gert Scholten // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.v2_0; import org.rapla.rest.gwtjsonrpc.client.JsonUtil; import org.rapla.rest.gwtjsonrpc.client.RemoteJsonException; import org.rapla.rest.gwtjsonrpc.client.event.RpcCompleteEvent; import org.rapla.rest.gwtjsonrpc.client.impl.AbstractJsonProxy; import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import org.rapla.rest.gwtjsonrpc.common.JsonConstants; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.Response; import com.google.gwt.json.client.JSONObject; import com.google.gwt.user.client.rpc.InvocationException; import com.google.gwt.user.client.rpc.StatusCodeException; /** Base JsonCall implementation for JsonRPC version 2.0 */ abstract class JsonCall20<T> extends JsonCall<T> { protected static int lastRequestId = 0; protected int requestId; JsonCall20(AbstractJsonProxy abstractJsonProxy, String methodName, String requestParams, ResultDeserializer<T> resultDeserializer) { super(abstractJsonProxy, methodName, requestParams, resultDeserializer); } @Override public void onResponseReceived(final Request req, final Response rsp) { final int sc = rsp.getStatusCode(); if (isJsonBody(rsp)) { final RpcResult r; try { r = parse(jsonParser, rsp.getText()); } catch (RuntimeException e) { RpcCompleteEvent.fire(this); callback.onFailure(new InvocationException("Bad JSON response: " + e)); return; } if (r.error() != null) { // TODO: define status code for the invalid XSRF msg for 2.0 (-32099 ?) final String errmsg = r.error().message(); if (JsonConstants.ERROR_INVALID_XSRF.equals(errmsg)) { if (attempts < 2) { // The XSRF cookie was invalidated (or didn't exist) and the // service demands we have one in place to make calls to it. // A new token was returned to us, so start the request over. // send(); } else { RpcCompleteEvent.fire(this); callback.onFailure(new InvocationException(errmsg)); } } else { RpcCompleteEvent.fire(this); callback.onFailure(new RemoteJsonException(errmsg, r.error().code(), new JSONObject(r.error()).get("data"))); } return; } if (sc == Response.SC_OK) { RpcCompleteEvent.fire(this); JsonUtil.invoke(resultDeserializer, callback, r); return; } } if (sc == Response.SC_OK) { RpcCompleteEvent.fire(this); callback.onFailure(new InvocationException("No JSON response")); } else { RpcCompleteEvent.fire(this); callback.onFailure(new StatusCodeException(sc, rsp.getStatusText())); } } protected static boolean isJsonBody(final Response rsp) { String type = rsp.getHeader("Content-Type"); if (type == null) { return false; } int semi = type.indexOf(';'); if (semi >= 0) { type = type.substring(0, semi).trim(); } return JsonConstants.JSONRPC20_ACCEPT_CTS.contains(type); } /** * Call a JSON parser javascript function to parse an encoded JSON string. * * @param parser a javascript function * @param json encoded JSON text * @return the parsed data * @see #jsonParser */ private static final native RpcResult parse(JavaScriptObject parserFunction, String json) /*-{ return parserFunction(json); }-*/; private static class RpcResult extends JavaScriptObject { protected RpcResult() { } final native RpcError error()/*-{ return this.error; }-*/; final native String xsrfKey()/*-{ return this.xsrfKey; }-*/; } private static class RpcError extends JavaScriptObject { protected RpcError() { } final native String message()/*-{ return this.message; }-*/; final native int code()/*-{ return this.code; }-*/; } }
Java
// Copyright 2009 Gert Scholten // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.v2_0; import org.rapla.rest.gwtjsonrpc.client.impl.AbstractJsonProxy; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import org.rapla.rest.gwtjsonrpc.common.JsonConstants; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.URL; /** JsonCall implementation for JsonRPC version 2.0 over HTTP POST */ public class JsonCall20HttpGet<T> extends JsonCall20<T> { private String encodedRequestParams; public JsonCall20HttpGet(AbstractJsonProxy abstractJsonProxy, String methodName, String requestParams, ResultDeserializer<T> resultDeserializer) { super(abstractJsonProxy, methodName, requestParams, resultDeserializer); encodedRequestParams = URL.encodeQueryString(encodeBase64(requestParams)); } @Override protected void send() { requestId = ++lastRequestId; final StringBuilder url = new StringBuilder(proxy.getServiceEntryPoint()); url.append("?jsonrpc=2.0&method=").append(methodName); url.append("&params=").append(encodedRequestParams); url.append("&id=").append(requestId); final RequestBuilder rb; rb = new RequestBuilder(RequestBuilder.GET, url.toString()); rb.setHeader("Content-Type", JsonConstants.JSONRPC20_REQ_CT); rb.setHeader("Accept", JsonConstants.JSONRPC20_ACCEPT_CTS); rb.setCallback(this); send(rb); } /** * Javascript base64 encoding implementation from. * * @see http://ecmanaut.googlecode.com/svn/trunk/lib/base64.js */ private static native String encodeBase64(String data) /*-{ var out = "", c1, c2, c3, e1, e2, e3, e4; for (var i = 0; i < data.length; ) { c1 = data.charCodeAt(i++); c2 = data.charCodeAt(i++); c3 = data.charCodeAt(i++); e1 = c1 >> 2; e2 = ((c1 & 3) << 4) + (c2 >> 4); e3 = ((c2 & 15) << 2) + (c3 >> 6); e4 = c3 & 63; if (isNaN(c2)) e3 = e4 = 64; else if (isNaN(c3)) e4 = 64; out += tab.charAt(e1) + tab.charAt(e2) + tab.charAt(e3) + tab.charAt(e4); } return out; }-*/; }
Java
// Copyright 2009 Gert Scholten // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.v2_0; import org.rapla.rest.gwtjsonrpc.client.impl.AbstractJsonProxy; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import org.rapla.rest.gwtjsonrpc.common.JsonConstants; import com.google.gwt.http.client.RequestBuilder; /** JsonCall implementation for JsonRPC version 2.0 over HTTP POST */ public class JsonCall20HttpPost<T> extends JsonCall20<T> { public JsonCall20HttpPost(AbstractJsonProxy abstractJsonProxy, String methodName, String requestParams, ResultDeserializer<T> resultDeserializer) { super(abstractJsonProxy, methodName, requestParams, resultDeserializer); } @Override protected void send() { requestId = ++lastRequestId; final StringBuilder body = new StringBuilder(); body.append("{\"jsonrpc\":\"2.0\",\"method\":\""); body.append(methodName); body.append("\",\"params\":"); body.append(requestParams); body.append(",\"id\":").append(requestId); body.append("}"); final RequestBuilder rb; rb = new RequestBuilder(RequestBuilder.POST, proxy.getServiceEntryPoint()); rb.setHeader("Content-Type", JsonConstants.JSONRPC20_REQ_CT); rb.setHeader("Accept", JsonConstants.JSONRPC20_ACCEPT_CTS); rb.setCallback(this); rb.setRequestData(body.toString()); send(rb); } }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsonUtils; public class PrimitiveArraySerializer { public static final PrimitiveArraySerializer INSTANCE = new PrimitiveArraySerializer(); private void printJsonWithToString(final StringBuilder sb, final Object[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i] != null ? o[i].toString() : JsonSerializer.JS_NULL); } sb.append(']'); } // Serialisation of Boxed Primitives public void printJson(final StringBuilder sb, final Boolean[] o) { printJsonWithToString(sb, o); } public void printJson(final StringBuilder sb, final Byte[] o) { printJsonWithToString(sb, o); } public void printJson(final StringBuilder sb, final Character[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } if (o[i] != null) { sb.append(JsonUtils.escapeValue(String.valueOf(o[i]))); } else sb.append(JsonSerializer.JS_NULL); } sb.append(']'); } public void printJson(final StringBuilder sb, final Double[] o) { printJsonWithToString(sb, o); } public void printJson(final StringBuilder sb, final Float[] o) { printJsonWithToString(sb, o); } public void printJson(final StringBuilder sb, final Integer[] o) { printJsonWithToString(sb, o); } public void printJson(final StringBuilder sb, final Short[] o) { printJsonWithToString(sb, o); } // Serialisation of Primitives public void printJson(final StringBuilder sb, final boolean[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } public void printJson(final StringBuilder sb, final byte[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } public void printJson(final StringBuilder sb, final char[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } public void printJson(final StringBuilder sb, final double[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } public void printJson(final StringBuilder sb, final float[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } public void printJson(final StringBuilder sb, final int[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } public void printJson(final StringBuilder sb, final short[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } sb.append(o[i]); } sb.append(']'); } // DeSerialisation native getters private static final native boolean getBoolean(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; private static final native byte getByte(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; private static final native String getString(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; private static final native double getDouble(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; private static final native float getFloat(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; private static final native int getInteger(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; private static final native short getShort(JavaScriptObject jso, int pos) /*-{ return jso[pos]; }-*/; // DeSerialisation of boxed primitive arrays public void fromJson(final JavaScriptObject jso, final Boolean[] r) { for (int i = 0; i < r.length; i++) { r[i] = getBoolean(jso, i); } } public void fromJson(final JavaScriptObject jso, final Byte[] r) { for (int i = 0; i < r.length; i++) { r[i] = getByte(jso, i); } } public void fromJson(final JavaScriptObject jso, final Character[] r) { for (int i = 0; i < r.length; i++) { r[i] = JsonSerializer.toChar(getString(jso, i)); } } public void fromJson(final JavaScriptObject jso, final Double[] r) { for (int i = 0; i < r.length; i++) { r[i] = getDouble(jso, i); } } public void fromJson(final JavaScriptObject jso, final Float[] r) { for (int i = 0; i < r.length; i++) { r[i] = getFloat(jso, i); } } public void fromJson(final JavaScriptObject jso, final Integer[] r) { for (int i = 0; i < r.length; i++) { r[i] = getInteger(jso, i); } } public void fromJson(final JavaScriptObject jso, final Short[] r) { for (int i = 0; i < r.length; i++) { r[i] = getShort(jso, i); } } // DeSerialisation of primitive arrays public void fromJson(final JavaScriptObject jso, final boolean[] r) { for (int i = 0; i < r.length; i++) { r[i] = getBoolean(jso, i); } } public void fromJson(final JavaScriptObject jso, final byte[] r) { for (int i = 0; i < r.length; i++) { r[i] = getByte(jso, i); } } public void fromJson(final JavaScriptObject jso, final char[] r) { for (int i = 0; i < r.length; i++) { r[i] = JsonSerializer.toChar(getString(jso, i)); } } public void fromJson(final JavaScriptObject jso, final double[] r) { for (int i = 0; i < r.length; i++) { r[i] = getDouble(jso, i); } } public void fromJson(final JavaScriptObject jso, final float[] r) { for (int i = 0; i < r.length; i++) { r[i] = getFloat(jso, i); } } public void fromJson(final JavaScriptObject jso, final int[] r) { for (int i = 0; i < r.length; i++) { r[i] = getInteger(jso, i); } } public void fromJson(final JavaScriptObject jso, final short[] r) { for (int i = 0; i < r.length; i++) { r[i] = getShort(jso, i); } } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsonUtils; /** * Serialization for a {@link java.util.Map} using only String keys. * <p> * The JSON representation is a JSON object, the map keys become the property * names of the JSON object and the map values are the property values. * <p> * When deserialized from JSON the Map implementation is always a * {@link HashMap}. When serializing to JSON any Map is permitted. */ public class StringMapSerializer<V> extends JsonSerializer<java.util.Map<String, V>> implements ResultDeserializer<java.util.Map<String, V>> { private final JsonSerializer<V> valueSerializer; public StringMapSerializer(final JsonSerializer<V> v) { valueSerializer = v; } @Override public void printJson(final StringBuilder sb, final java.util.Map<String, V> o) { sb.append('{'); boolean first = true; for (final Map.Entry<String, V> e : o.entrySet()) { if (first) { first = false; } else { sb.append(','); } sb.append(JsonUtils.escapeValue(e.getKey())); sb.append(':'); encode(sb, valueSerializer, e.getValue()); } sb.append('}'); } private static <T> void encode(final StringBuilder sb, final JsonSerializer<T> serializer, final T item) { if (item != null) { serializer.printJson(sb, item); } else { sb.append(JS_NULL); } } @Override public java.util.Map<String, V> fromJson(final Object o) { if (o == null) { return null; } final JavaScriptObject jso = (JavaScriptObject) o; final Map<String, V> r = new LinkedHashMap<String, V>(); copy(r, jso); return r; } @Override public java.util.Map<String, V> fromResult(final JavaScriptObject response) { final JavaScriptObject result = ObjectSerializer.objectResult(response); return result == null ? null : fromJson(result); } private native void copy(Map<String, V> r, JavaScriptObject jsObject) /*-{ for (var key in jsObject) { this.@org.rapla.rest.gwtjsonrpc.client.impl.ser.StringMapSerializer::copyOne(Ljava/util/Map;Ljava/lang/String;Ljava/lang/Object;)(r, key, jsObject[key]); } }-*/; void copyOne(final Map<String, V> r, final String k, final Object o) { r.put(k, valueSerializer.fromJson(o)); } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import com.google.gwt.core.client.JavaScriptObject; import java.util.ArrayList; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; /** * Serialization for a {@link java.util.List}. * <p> * When deserialized from JSON the List implementation is always an * {@link ArrayList}. When serializing to JSON any List is permitted. */ public class ListSerializer<T> extends JsonSerializer<java.util.List<T>> implements ResultDeserializer<java.util.List<T>> { private final JsonSerializer<T> serializer; public ListSerializer(final JsonSerializer<T> s) { serializer = s; } @Override public void printJson(final StringBuilder sb, final java.util.List<T> o) { sb.append('['); boolean first = true; for (final T item : o) { if (first) { first = false; } else { sb.append(','); } if (item != null) { serializer.printJson(sb, item); } else { sb.append(JS_NULL); } } sb.append(']'); } @Override public java.util.List<T> fromJson(final Object o) { if (o == null) { return null; } final JavaScriptObject jso = (JavaScriptObject) o; final int n = size(jso); final ArrayList<T> r = new ArrayList<T>(n); for (int i = 0; i < n; i++) { r.add(serializer.fromJson(get(jso, i))); } return r; } @Override public java.util.List<T> fromResult(final JavaScriptObject response) { final JavaScriptObject result = ObjectSerializer.objectResult(response); return result == null ? null : fromJson(result); } private static final native int size(JavaScriptObject o)/*-{ return o.length; }-*/; private static final native Object get(JavaScriptObject o, int i)/*-{ return o[i]; }-*/; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import com.google.gwt.core.client.JavaScriptObject; import java.util.HashSet; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; /** * Serialization for a {@link java.util.Set}. * <p> * When deserialized from JSON the Set implementation is always a * {@link HashSet}. When serializing to JSON any Set is permitted. */ public class SetSerializer<T> extends JsonSerializer<java.util.Set<T>> implements ResultDeserializer<java.util.Set<T>> { private final JsonSerializer<T> serializer; public SetSerializer(final JsonSerializer<T> s) { serializer = s; } @Override public void printJson(final StringBuilder sb, final java.util.Set<T> o) { sb.append('['); boolean first = true; for (final T item : o) { if (first) { first = false; } else { sb.append(','); } if (item != null) { serializer.printJson(sb, item); } else { sb.append(JS_NULL); } } sb.append(']'); } @Override public java.util.Set<T> fromJson(final Object o) { if (o == null) { return null; } final JavaScriptObject jso = (JavaScriptObject) o; final int n = size(jso); final HashSet<T> r = new HashSet<T>(n); for (int i = 0; i < n; i++) { r.add(serializer.fromJson(get(jso, i))); } return r; } @Override public java.util.Set<T> fromResult(final JavaScriptObject response) { final JavaScriptObject result = ObjectSerializer.objectResult(response); return result == null ? null : fromJson(result); } private static final native int size(JavaScriptObject o)/*-{ return o.length; }-*/; private static final native Object get(JavaScriptObject o, int i)/*-{ return o[i]; }-*/; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; /** Base serializer for Enum types. */ public abstract class EnumSerializer<T extends Enum<?>> extends JsonSerializer<T> { @Override public void printJson(final StringBuilder sb, final T o) { sb.append('"'); sb.append(o.name()); sb.append('"'); } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import java.util.Date; import org.rapla.components.util.ParseDateException; import org.rapla.components.util.SerializableDateTimeFormat; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; /** Default serialization for a {@link java.util.Date}. */ public final class JavaUtilDate_JsonSerializer extends JsonSerializer<java.util.Date> implements ResultDeserializer<java.util.Date> { public static final JavaUtilDate_JsonSerializer INSTANCE = new JavaUtilDate_JsonSerializer(); @Override public java.util.Date fromJson(final Object o) { if (o != null) { Date date; try { date = SerializableDateTimeFormat.INSTANCE.parseTimestamp((String)o); } catch (ParseDateException e) { throw new IllegalArgumentException("Invalid date format: " + o); } return date; } return null; } @Override public void printJson(final StringBuilder sb, final java.util.Date o) { sb.append('"'); String string = SerializableDateTimeFormat.INSTANCE.formatTimestamp( o); sb.append(string); sb.append('"'); } @Override public Date fromResult(JavaScriptObject responseObject) { return fromJson(PrimitiveResultDeserializers.stringResult(responseObject)); } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; /** * Serialization for a {@link java.util.Map} using any Object key. * <p> * The JSON format is an array with even length, alternating key and value * elements. For example: <code>[k1, v1, k2, v2, k3, v3, ...]</code>. The keys * and values may be any Object type. * <p> * When deserialized from JSON the Map implementation is always a * {@link HashMap}. When serializing to JSON any Map is permitted. */ public class ObjectMapSerializer<K, V> extends JsonSerializer<java.util.Map<K, V>> implements ResultDeserializer<java.util.Map<K, V>> { private final JsonSerializer<K> keySerializer; private final JsonSerializer<V> valueSerializer; public ObjectMapSerializer(final JsonSerializer<K> k, final JsonSerializer<V> v) { keySerializer = k; valueSerializer = v; } @Override public void printJson(final StringBuilder sb, final java.util.Map<K, V> o) { sb.append('['); boolean first = true; for (final Map.Entry<K, V> e : o.entrySet()) { if (first) { first = false; } else { sb.append(','); } encode(sb, keySerializer, e.getKey()); sb.append(','); encode(sb, valueSerializer, e.getValue()); } sb.append(']'); } private static <T> void encode(final StringBuilder sb, final JsonSerializer<T> serializer, final T item) { if (item != null) { serializer.printJson(sb, item); } else { sb.append(JS_NULL); } } @Override public java.util.Map<K, V> fromJson(final Object o) { if (o == null) { return null; } final JavaScriptObject jso = (JavaScriptObject) o; final int n = size(jso); final HashMap<K, V> r = new LinkedHashMap<K, V>(); for (int i = 0; i < n;) { final K k = keySerializer.fromJson(get(jso, i++)); final V v = valueSerializer.fromJson(get(jso, i++)); r.put(k, v); } return r; } @Override public java.util.Map<K, V> fromResult(final JavaScriptObject response) { final JavaScriptObject result = ObjectSerializer.objectResult(response); return result == null ? null : fromJson(result); } private static final native int size(JavaScriptObject o)/*-{ return o.length; }-*/; private static final native Object get(JavaScriptObject o, int i)/*-{ return o[i]; }-*/; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; /** Base class for generated JsonSerializer implementations. */ public abstract class ObjectSerializer<T extends Object> extends JsonSerializer<T> implements ResultDeserializer<T> { @Override public void printJson(final StringBuilder sb, final Object o) { sb.append("{"); printJsonImpl(0, sb, o); sb.append("}"); } protected abstract int printJsonImpl(int field, StringBuilder sb, Object o); @Override public T fromResult(JavaScriptObject responseObject) { final JavaScriptObject result = objectResult(responseObject); return result == null ? null : fromJson(result); } static native JavaScriptObject objectResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import org.rapla.rest.gwtjsonrpc.common.VoidResult; import com.google.gwt.core.client.JavaScriptObject; public class VoidResult_JsonSerializer extends JsonSerializer<VoidResult> implements ResultDeserializer<VoidResult> { public static final VoidResult_JsonSerializer INSTANCE = new VoidResult_JsonSerializer(); private VoidResult_JsonSerializer() { } @Override public void printJson(final StringBuilder sb, final VoidResult o) { sb.append("{}"); } @Override public VoidResult fromJson(final Object o) { return VoidResult.INSTANCE; } @Override public VoidResult fromResult(JavaScriptObject responseObject) { return VoidResult.INSTANCE; } }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsonUtils; /** Default serialization for a String. */ public final class JavaLangString_JsonSerializer extends JsonSerializer<java.lang.String> implements ResultDeserializer<java.lang.String> { public static final JavaLangString_JsonSerializer INSTANCE = new JavaLangString_JsonSerializer(); @Override public java.lang.String fromJson(final Object o) { return (String) o; } @Override public void printJson(final StringBuilder sb, final java.lang.String o) { sb.append(JsonUtils.escapeValue(o)); } @Override public String fromResult(JavaScriptObject responseObject) { return PrimitiveResultDeserializers.stringResult(responseObject); } }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; public class PrimitiveResultDeserializers { static native boolean booleanResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; static native byte byteResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; static native String stringResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; static char charResult(JavaScriptObject responseObject) { return JsonSerializer.toChar(stringResult(responseObject)); } static native double doubleResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; static native float floatResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; static native int intResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; static native short shortResult(JavaScriptObject responseObject) /*-{ return responseObject.result; }-*/; public static final ResultDeserializer<Boolean> BOOLEAN_INSTANCE = new ResultDeserializer<Boolean>() { @Override public Boolean fromResult(JavaScriptObject responseObject) { return booleanResult(responseObject); } }; public static final ResultDeserializer<Byte> BYTE_INSTANCE = new ResultDeserializer<Byte>() { @Override public Byte fromResult(JavaScriptObject responseObject) { return byteResult(responseObject); } }; public static final ResultDeserializer<Character> CHARACTER_INSTANCE = new ResultDeserializer<Character>() { @Override public Character fromResult(JavaScriptObject responseObject) { return charResult(responseObject); } }; public static final ResultDeserializer<Double> DOUBLE_INSTANCE = new ResultDeserializer<Double>() { @Override public Double fromResult(JavaScriptObject responseObject) { return doubleResult(responseObject); } }; public static final ResultDeserializer<Float> FLOAT_INSTANCE = new ResultDeserializer<Float>() { @Override public Float fromResult(JavaScriptObject responseObject) { return floatResult(responseObject); } }; public static final ResultDeserializer<Integer> INTEGER_INSTANCE = new ResultDeserializer<Integer>() { @Override public Integer fromResult(JavaScriptObject responseObject) { return intResult(responseObject); } }; public static final ResultDeserializer<Short> SHORT_INSTANCE = new ResultDeserializer<Short>() { @Override public Short fromResult(JavaScriptObject responseObject) { return shortResult(responseObject); } }; }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.ArrayResultDeserializer; import org.rapla.rest.gwtjsonrpc.client.impl.ResultDeserializer; import com.google.gwt.core.client.JavaScriptObject; public class PrimitiveArrayResultDeserializers extends ArrayResultDeserializer { public static ResultDeserializer<Boolean[]> BOOLEAN_INSTANCE = new ResultDeserializer<Boolean[]>() { @Override public Boolean[] fromResult(JavaScriptObject responseObject) { final Boolean[] tmp = new Boolean[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; public static ResultDeserializer<Byte[]> BYTE_INSTANCE = new ResultDeserializer<Byte[]>() { @Override public Byte[] fromResult(JavaScriptObject responseObject) { final Byte[] tmp = new Byte[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; public static ResultDeserializer<Character[]> CHARACTER_INSTANCE = new ResultDeserializer<Character[]>() { @Override public Character[] fromResult(JavaScriptObject responseObject) { final Character[] tmp = new Character[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; public static ResultDeserializer<Double[]> DOUBLE_INSTANCE = new ResultDeserializer<Double[]>() { @Override public Double[] fromResult(JavaScriptObject responseObject) { final Double[] tmp = new Double[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; public static ResultDeserializer<Float[]> FLOAT_INSTANCE = new ResultDeserializer<Float[]>() { @Override public Float[] fromResult(JavaScriptObject responseObject) { final Float[] tmp = new Float[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; public static ResultDeserializer<Integer[]> INTEGER_INSTANCE = new ResultDeserializer<Integer[]>() { @Override public Integer[] fromResult(JavaScriptObject responseObject) { final Integer[] tmp = new Integer[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; public static ResultDeserializer<Short[]> SHORT_INSTANCE = new ResultDeserializer<Short[]>() { @Override public Short[] fromResult(JavaScriptObject responseObject) { final Short[] tmp = new Short[getResultSize(responseObject)]; PrimitiveArraySerializer.INSTANCE.fromJson(getResult(responseObject), tmp); return tmp; } }; }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl.ser; import org.rapla.rest.gwtjsonrpc.client.impl.JsonSerializer; import com.google.gwt.core.client.JavaScriptObject; /** * Default serialization for any Object[] sort of type. * <p> * Primitive array types (like <code>int[]</code>) are not supported. */ public class ObjectArraySerializer<T> { private final JsonSerializer<T> serializer; public ObjectArraySerializer(final JsonSerializer<T> s) { serializer = s; } public void printJson(final StringBuilder sb, final T[] o) { sb.append('['); for (int i = 0, n = o.length; i < n; i++) { if (i > 0) { sb.append(','); } final T v = o[i]; if (v != null) { serializer.printJson(sb, v); } else { sb.append(JsonSerializer.JS_NULL); } } sb.append(']'); } public void fromJson(final JavaScriptObject jso, final T[] r) { for (int i = 0; i < r.length; i++) { r[i] = serializer.fromJson(get(jso, i)); } } public static native int size(JavaScriptObject o)/*-{ return o.length; }-*/; private static final native Object get(JavaScriptObject o, int i)/*-{ return o[i]; }-*/; }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl; import com.google.gwt.core.client.JavaScriptObject; /** * Inteface class for deserializers of results from JSON RPC calls. Since * primitive and array results need to be handled specially, not all results can * be deserialized using the standard object serializers. * * @param <T> the result type of an RPC call. */ public interface ResultDeserializer<T> { public T fromResult(JavaScriptObject responseObject); }
Java
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.impl; import com.google.gwt.core.client.JsonUtils; /** * Converter between JSON and Java object representations. * <p> * Implementors must provide bidirectional conversion, typically using the GWT * JavaScriptObject and native JavaScript magic to read the JSON data structure. * <p> * Most implementations are generated automatically at compile-time by the * <code>RemoteJsonServiceProxyGenerator</code>. * * @param <T> type of Java class this type works on. */ public abstract class JsonSerializer<T> { /** Magic constant in JSON to mean the same as Java null. */ public static final String JS_NULL = "null"; /** * Convert a Java object to JSON text. * <p> * Implementations should recursively call any nested object or collection at * the appropriate time to append the nested item's JSON text. * * @param sb the output string buffer the JSON text should be appended onto * the end of. * @param o the Java instance being converted. Never null. */ public abstract void printJson(StringBuilder sb, T o); /** * Convert from JSON (stored as a JavaScriptObject) into a new Java instance. * * @param o the JSON object instance; typically this should be downcast to * JavaScriptObject. May be null, in which case null should be returned * instead of an instance. * @return null if <code>o</code> was null; otherwise the new object instance * with the data copied over form the JSON representation. */ public abstract T fromJson(Object o); /** * Utility function to convert a String to safe JSON text. * <p> * For example, if <code>val = "b\nb"</code> this method returns the value * <code>"\"b\\nb\""</code>. * <p> * Typically called by {@link #printJson(StringBuilder, Object)}, or through * {@link JavaLangString_JsonSerializer}. * * @param val string text requiring escaping support. Must not be null. * @return a JSON literal text value, surrounded with double quotes. * @deprecated Use {@link JsonUtils#escapeValue(String)} */ @Deprecated public static final String escapeString(String val) { return JsonUtils.escapeValue(val); } /** * Escape a single character, without double quotes surrounding it. * * @deprecated implementation depends on private method hack. Do not use. */ @Deprecated public static final String escapeChar(final char c) { return escapeCharImpl(String.valueOf(c)); } @Deprecated private static final native String escapeCharImpl(String c) /*-{ return @com.google.gwt.core.client.JsonUtils::escapeChar(Ljava/lang/String;)(c); }-*/; /** Return the first character of a string, or '\0' if the string is empty. */ public static final char toChar(final String val) { return val.length() > 0 ? val.charAt(0) : '\0'; } }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.user.client.rpc.ServiceDefTarget; /** Common event for {@link RpcStartEvent}, {@link RpcCompleteEvent}. */ public abstract class BaseRpcEvent<T extends EventHandler> extends GwtEvent<T> { JsonCall<?> call; /** @return the service instance the remote call occurred on. */ public Object getService() { assertLive(); return call.getProxy(); } /** @return the service instance the remote call occurred on. */ public ServiceDefTarget getServiceDefTarget() { assertLive(); return call.getProxy(); } /** @return the method name being invoked on the service. */ public String getMethodName() { assertLive(); return call.getMethodName(); } }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import com.google.gwt.event.shared.EventHandler; /** Handler to receive notifications on RPC beginning. */ public interface RpcStartHandler extends EventHandler { /** Invoked when an RPC call starts. */ public void onRpcStart(RpcStartEvent event); }
Java
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.rapla.rest.gwtjsonrpc.client.event; import org.rapla.rest.gwtjsonrpc.client.JsonUtil; import org.rapla.rest.gwtjsonrpc.client.impl.JsonCall; /** Event received by {@link RpcCompleteHandler} */ public class RpcCompleteEvent extends BaseRpcEvent<RpcCompleteHandler> { private static Type<RpcCompleteHandler> TYPE = null; private static RpcCompleteEvent INSTANCE = null; /** * Fires a RpcCompleteEvent. * <p> * For internal use only. * * @param eventData */ @SuppressWarnings("rawtypes") public static void fire(Object eventData) { assert eventData instanceof JsonCall : "For internal use only"; if (TYPE != null) { // If we have a TYPE, we have an INSTANCE. INSTANCE.call = (JsonCall) eventData; JsonUtil.fireEvent(INSTANCE); } } /** * Gets the type associated with this event. * * @return returns the event type */ public static Type<RpcCompleteHandler> getType() { if (TYPE == null) { TYPE = new Type<RpcCompleteHandler>(); INSTANCE = new RpcCompleteEvent(); } return TYPE; } private RpcCompleteEvent() { // Do nothing } @Override public Type<RpcCompleteHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(final RpcCompleteHandler handler) { handler.onRpcComplete(this); } @Override protected void kill() { super.kill(); call = null; } }
Java