code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.Calendar;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Represents a torrent on a server daemon.
*
* @author erickok
*
*/
public final class Torrent implements Parcelable, Comparable<Torrent> {
final private long id;
final private String hash;
final private String name;
private TorrentStatus statusCode;
final private String locationDir;
final private int rateDownload;
final private int rateUpload;
final private int peersGettingFromUs;
final private int peersSendingToUs;
final private int peersConnected;
final private int peersKnown;
final private int eta;
final private long downloadedEver;
final private long uploadedEver;
final private long totalSize;
final private float partDone;
final private float available;
private String label;
final private Date dateAdded;
final private Date dateDone;
final private String error;
//public long getID() { return id; }
//public String getHash() { return hash; }
public String getName() { return name; }
public TorrentStatus getStatusCode() { return statusCode; }
public String getLocationDir() { return locationDir; }
public int getRateDownload() { return rateDownload; }
public int getRateUpload() { return rateUpload; }
public int getPeersGettingFromUs() { return peersGettingFromUs; }
public int getPeersSendingToUs() { return peersSendingToUs; }
public int getPeersConnected() { return peersConnected; }
public int getPeersKnown() { return peersKnown; }
public int getEta() { return eta; }
public long getDownloadedEver() { return downloadedEver; }
public long getUploadedEver() { return uploadedEver; }
public long getTotalSize() { return totalSize; }
public float getPartDone() { return partDone; }
public float getAvailability() { return available; }
public String getLabelName() { return label; }
public Date getDateAdded() { return dateAdded; }
public Date getDateDone() { return dateDone; }
public String getError() { return error; }
private Torrent(Parcel in) {
this.id = in.readLong();
this.hash = in.readString();
this.name = in.readString();
this.statusCode = TorrentStatus.getStatus(in.readInt());
this.locationDir = in.readString();
this.rateDownload = in.readInt();
this.rateUpload = in.readInt();
this.peersGettingFromUs = in.readInt();
this.peersSendingToUs = in.readInt();
this.peersConnected = in.readInt();
this.peersKnown = in.readInt();
this.eta = in.readInt();
this.downloadedEver = in.readLong();
this.uploadedEver = in.readLong();
this.totalSize = in.readLong();
this.partDone = in.readFloat();
this.available = in.readFloat();
this.label = in.readString();
long lDateAdded = in.readLong();
this.dateAdded = (lDateAdded == -1)? null: new Date(lDateAdded);
long lDateDone = in.readLong();
this.dateDone = (lDateDone == -1)? null: new Date(lDateDone);
this.error = in.readString();
}
public Torrent(long id, String hash, String name, TorrentStatus statusCode, String locationDir, int rateDownload, int rateUpload,
int peersGettingFromUs, int peersSendingToUs, int peersConnected, int peersKnown, int eta,
long downloadedEver, long uploadedEver, long totalSize, float partDone, float available, String label,
Date dateAdded, Date realDateDone, String error) {
this.id = id;
this.hash = hash;
this.name = name;
this.statusCode = statusCode;
this.locationDir = locationDir;
this.rateDownload = rateDownload;
this.rateUpload = rateUpload;
this.peersGettingFromUs = peersGettingFromUs;
this.peersSendingToUs = peersSendingToUs;
this.peersConnected = peersConnected;
this.peersKnown = peersKnown;
this.eta = eta;
this.downloadedEver = downloadedEver;
this.uploadedEver = uploadedEver;
this.totalSize = totalSize;
this.partDone = partDone;
this.available = available;
this.label = label;
this.dateAdded = dateAdded;
if (realDateDone != null) {
this.dateDone = realDateDone;
} else {
if (eta == -1 || eta == -2) {
this.dateDone = new Date(Long.MAX_VALUE);
} else {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, eta);
this.dateDone = cal.getTime();
}
}
this.error = error;
}
/**
* Returns the torrent-specific ID, which is the torrent's hash or (if not available) the long number
* @return The torrent's (session-transient) unique ID
*/
public String getUniqueID() {
if (this.hash == null) {
return "" + this.id;
} else {
return this.hash;
}
}
/**
* Gives the upload/download seed ratio.
* @return The ratio in range [0,r]
*/
public double getRatio() {
return ((double)uploadedEver) / ((double)downloadedEver);
}
/**
* Gives the percentage of the download that is completed
* @return The downloaded percentage in range [0,1]
*/
public float getDownloadedPercentage() {
return partDone;
}
/**
* Indicates if the torrent can be paused at this moment
* @return If it can be paused
*/
public boolean canPause() {
// Can pause when it is downloading or seeding
return statusCode == TorrentStatus.Downloading || statusCode == TorrentStatus.Seeding;
}
/**
* Indicates whether the torrent can be resumed
* @return If it can be resumed
*/
public boolean canResume() {
// Can resume when it is paused
return statusCode == TorrentStatus.Paused;
}
/**
* Indicates if the torrent can be started at this moment
* @return If it can be started
*/
public boolean canStart() {
// Can start when it is queued
return statusCode == TorrentStatus.Queued;
}
/**
* Indicates whether the torrent can be stopped
* @return If it can be stopped
*/
public boolean canStop() {
// Can stop when it is downloading or seeding or paused
return statusCode == TorrentStatus.Downloading || statusCode == TorrentStatus.Seeding || statusCode == TorrentStatus.Paused;
}
public void mimicResume() {
if (getDownloadedPercentage() >= 1) {
statusCode = TorrentStatus.Seeding;
} else {
statusCode = TorrentStatus.Downloading;
}
}
public void mimicPause() {
statusCode = TorrentStatus.Paused;
}
public void mimicStart() {
if (getDownloadedPercentage() >= 1) {
statusCode = TorrentStatus.Seeding;
} else {
statusCode = TorrentStatus.Downloading;
}
}
public void mimicStop() {
statusCode = TorrentStatus.Queued;
}
public void mimicNewLabel(String newLabel) {
label = newLabel;
}
@Override
public String toString() {
// (HASH_OR_ID) NAME
return "(" + ((hash != null)? hash: String.valueOf(id)) + ") " + name;
}
@Override
public int compareTo(Torrent another) {
// Compare torrent objects on their name (used for sorting only!)
return name.compareTo(another.getName());
}
public static final Parcelable.Creator<Torrent> CREATOR = new Parcelable.Creator<Torrent>() {
public Torrent createFromParcel(Parcel in) {
return new Torrent(in);
}
public Torrent[] newArray(int size) {
return new Torrent[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(hash);
dest.writeString(name);
dest.writeInt(statusCode.getCode());
dest.writeString(locationDir);
dest.writeInt(rateDownload);
dest.writeInt(rateUpload);
dest.writeInt(peersGettingFromUs);
dest.writeInt(peersSendingToUs);
dest.writeInt(peersConnected);
dest.writeInt(peersKnown);
dest.writeInt(eta);
dest.writeLong(downloadedEver);
dest.writeLong(uploadedEver);
dest.writeLong(totalSize);
dest.writeFloat(partDone);
dest.writeFloat(available);
dest.writeString(label);
dest.writeLong((dateAdded == null)? -1: dateAdded.getTime());
dest.writeLong((dateDone == null)? -1: dateDone.getTime());
dest.writeString(error);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.Comparator;
/**
* Implements a comparator for Torrent objects, which can for example be used to sort torrent on several
* different properties, which can be found in the TorrentsSortBy enum
*
* @author erickok
*
*/
public class TorrentsComparator implements Comparator<Torrent> {
TorrentsSortBy sortBy;
boolean reversed;
/**
* Instantiate a torrents comparator. The daemon object is used to check support for comparing
* on the set properties. If the daemon does not support the property, ascending Alphanumeric
* sorting will be used even if sorting is requested on the unsupported property.
* @param daemon The loaded server daemon, which exposes what features and properties it supports
* @param sortBy The requested sorting property (Alphanumeric is used for unsupported properties that are requested)
* @param reversed If the sorting should be in reverse order
*/
public TorrentsComparator(IDaemonAdapter daemon, TorrentsSortBy sortBy, boolean reversed) {
this.sortBy = sortBy;
this.reversed = reversed;
switch (sortBy) {
case DateAdded:
if (daemon != null && !Daemon.supportsDateAdded(daemon.getType())) {
// Reset the sorting to simple Alphanumeric
this.sortBy = TorrentsSortBy.Alphanumeric;
this.reversed = false;
}
break;
}
}
@Override
public int compare(Torrent tor1, Torrent tor2) {
if (!reversed) {
switch (sortBy) {
case Status:
return tor1.getStatusCode().compareStatusCodeTo(tor2.getStatusCode());
case DateAdded:
return tor1.getDateAdded().compareTo(tor2.getDateAdded());
case DateDone:
return tor1.getDateDone().compareTo(tor2.getDateDone());
case UploadSpeed:
return new Integer(tor1.getRateUpload()).compareTo(new Integer(tor2.getRateUpload()));
case Ratio:
return new Double(tor1.getRatio()).compareTo(new Double(tor2.getRatio()));
default:
return tor1.getName().toLowerCase().compareTo(tor2.getName().toLowerCase());
}
} else {
switch (sortBy) {
case Status:
return 0 - tor1.getStatusCode().compareStatusCodeTo(tor2.getStatusCode());
case DateAdded:
return 0 - tor1.getDateAdded().compareTo(tor2.getDateAdded());
case DateDone:
return 0 - tor1.getDateDone().compareTo(tor2.getDateDone());
case UploadSpeed:
return 0 - (new Integer(tor1.getRateUpload()).compareTo(new Integer(tor2.getRateUpload())));
case Ratio:
return 0 - new Double(tor1.getRatio()).compareTo(new Double(tor2.getRatio()));
default:
return 0 - tor1.getName().toLowerCase().compareTo(tor2.getName().toLowerCase());
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
/**
* An exception thrown when an error occurs inside a server daemon adapter.
* The error message is from a resource string ID, since this can be
* translated. An alternative message is given to use as logging output not
* visible to the user.
*
* @author erickok
*
*/
public class DaemonException extends Exception {
private static final long serialVersionUID = 1L;
private ExceptionType internalException;
public enum ExceptionType {
MethodUnsupported,
ConnectionError,
UnexpectedResponse,
ParsingFailed,
AuthenticationFailure,
NotConnected,
FileAccessError;
}
public DaemonException(ExceptionType internalException, String message) {
super(message);
this.internalException = internalException;
}
public ExceptionType getType() {
return internalException;
}
@Override
public String toString() {
return internalException.toString() + " exception: " + getMessage();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.Qbittorrent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetFilePriorityTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
import com.android.internalcopy.http.multipart.FilePart;
import com.android.internalcopy.http.multipart.MultipartEntity;
import com.android.internalcopy.http.multipart.Part;
/**
* The daemon adapter for the qBittorrent torrent client.
*
* @author erickok
*
*/
public class QbittorrentAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "qBittorrent daemon";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
private int version = -1;
public QbittorrentAdapter(DaemonSettings settings) {
this.settings = settings;
}
private void ensureVersion() throws DaemonException {
if (version > 0)
return;
// We still need to retrieve the version number from the server
// Do this by getting the web interface about page and trying to parse the version number
// Format is something like 'qBittorrent v2.9.7 (Web UI)'
String about = makeRequest("/about.html");
String aboutStartText = "qBittorrent v";
String aboutEndText = " (Web UI)";
int aboutStart = about.indexOf(aboutStartText);
int aboutEnd = about.indexOf(aboutEndText);
try {
if (aboutStart >= 0 && aboutEnd > aboutStart) {
// String found: now parse a version like 2.9.7 as a number like 20907 (allowing 10 places for each .)
String[] parts = about.substring(aboutStart + aboutStartText.length(), aboutEnd).split("\\.");
if (parts.length > 0) {
version = Integer.parseInt(parts[0]) * 100 * 100;
if (parts.length > 1) {
version += Integer.parseInt(parts[1]) * 100;
if (parts.length > 2) {
// For the last part only read until a non-numeric character is read
// For example version 3.0.0-alpha5 is read as version code 30000
String numbers = "";
for (char c : parts[2].toCharArray()) {
if (Character.isDigit(c))
// Still a number; add it to the numbers string
numbers += Character.toString(c);
else {
// No longer reading numbers; stop reading
break;
}
}
version += Integer.parseInt(numbers);
return;
}
}
}
}
} catch (NumberFormatException e) {
}
// Unable to establish version number; assume an old version by setting it to version 1
version = 10000;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
ensureVersion();
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
JSONArray result = new JSONArray(makeRequest(version >= 30000? "/json/torrents": "/json/events"));
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonTorrents(result),null);
case GetTorrentDetails:
// Request tracker and error details for a specific teacher
String mhash = ((GetTorrentDetailsTask)task).getTargetTorrent().getUniqueID();
JSONArray messages = new JSONArray(makeRequest("/json/propertiesTrackers/" + mhash));
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, parseJsonTorrentDetails(messages));
case GetFileList:
// Request files listing for a specific torrent
String fhash = ((GetFileListTask)task).getTargetTorrent().getUniqueID();
JSONArray files = new JSONArray(makeRequest("/json/propertiesFiles/" + fhash));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFiles(files));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask)task).getFile();
makeUploadRequest("/command/upload", ufile);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", url));
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
// Request to add a magnet link by URL
String magnet = ((AddByMagnetUrlTask)task).getUrl();
makeRequest("/command/download", new BasicNameValuePair("urls", magnet));
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeRequest((removeTask.includingData()? "/command/deletePerm": "/command/delete"), new BasicNameValuePair("hashes", removeTask.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeRequest("/command/pause", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
makeRequest("/command/pauseall");
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRequest("/command/resume", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeRequest("/command/resumeall");
return new DaemonTaskSuccessResult(task);
case SetFilePriorities:
// Update the priorities to a set of files
SetFilePriorityTask setPrio = (SetFilePriorityTask) task;
String newPrio = "0";
if (setPrio.getNewPriority() == Priority.Low) {
newPrio = "1";
} else if (setPrio.getNewPriority() == Priority.Normal) {
newPrio = "2";
} else if (setPrio.getNewPriority() == Priority.High) {
newPrio = "7";
}
// We have to make a separate request per file, it seems
for (TorrentFile file : setPrio.getForFiles()) {
makeRequest("/command/setFilePrio", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()), new BasicNameValuePair("id", file.getKey()), new BasicNameValuePair("priority", newPrio));
}
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// TODO: This doesn't seem to work yet
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
int dl = (ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue());
int ul = (ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue());
// First get the preferences
JSONObject prefs = new JSONObject(makeRequest("/json/preferences"));
prefs.put("dl_limit", dl);
prefs.put("up_limit", ul);
makeRequest("/command/setPreferences", new BasicNameValuePair("json", URLEncoder.encode(prefs.toString(), HTTP.UTF_8)));
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (UnsupportedEncodingException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
}
}
private String makeRequest(String path, NameValuePair... params) throws DaemonException {
try {
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (NameValuePair param : params) {
nvps.add(param);
}
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
return makeWebRequest(path, httppost);
} catch (UnsupportedEncodingException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private String makeUploadRequest(String path, String file) throws DaemonException {
try {
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
File upload = new File(URI.create(file));
Part[] parts = { new FilePart("torrentfile", upload) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
return makeWebRequest(path, httppost);
} catch (FileNotFoundException e) {
throw new DaemonException(ExceptionType.FileAccessError, e.toString());
}
}
private String makeWebRequest(String path, HttpPost httppost) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
// Execute
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read JSON response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
//TLog.d(LOG_NAME, "Success: " + (result.length() > 300? result.substring(0, 300) + "... (" + result.length() + " chars)": result));
// Return raw result
return result;
}
DLog.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all qBittorrent requests.
* @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
/*httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
for (Header header : request.getAllHeaders()) {
TLog.d(LOG_NAME, "Request: " + header.getName() + ": " + header.getValue());
}
}
});*/
}
/**
* Build the URL of the web UI request from the user settings
* @return The URL to request
*/
private String buildWebUIUrl(String path) {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + path;
}
private TorrentDetails parseJsonTorrentDetails(JSONArray messages) throws JSONException {
ArrayList<String> trackers = new ArrayList<String>();
ArrayList<String> errors = new ArrayList<String>();
// Parse response
if (messages.length() > 0) {
for (int i = 0; i < messages.length(); i++) {
JSONObject tor = messages.getJSONObject(i);
trackers.add(tor.getString("url"));
String msg = tor.getString("msg");
if (msg != null && !msg.equals(""))
errors.add(msg);
}
}
// Return the list
return new TorrentDetails(trackers, errors);
}
private ArrayList<Torrent> parseJsonTorrents(JSONArray response) throws JSONException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
for (int i = 0; i < response.length(); i++) {
JSONObject tor = response.getJSONObject(i);
int leechers = parseLeech(tor.getString("num_leechs"));
int seeders = parseSeeds(tor.getString("num_seeds"));
int known = parseKnown(tor.getString("num_leechs"), tor.getString("num_seeds"));
long size = parseSize(tor.getString("size"));
double ratio = parseRatio(tor.getString("ratio"));
double progress = tor.getDouble("progress");
int dlspeed = parseSpeed(tor.getString("dlspeed"));
// Add the parsed torrent to the list
torrents.add(new Torrent(
(long)i,
tor.getString("hash"),
tor.getString("name"),
parseStatus(tor.getString("state")),
null,
dlspeed,
parseSpeed(tor.getString("upspeed")),
leechers,
leechers + seeders,
known,
known,
(int) ((size - (size * progress)) / dlspeed),
(long)(size * progress),
(long)(size * ratio),
size,
(float)progress,
0f,
null,
null, // Only available in /json/propertiesGeneral on a per-torrent basis, unfortunately
null,
null));
}
// Return the list
return torrents;
}
private double parseRatio(String string) {
// Ratio is given in "1.5" string format
try {
return Double.parseDouble(string);
} catch (Exception e) {
return 0D;
}
}
private long parseSize(String string) {
// See https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation
if (string.equals("Unknown"))
return -1;
// Sizes are given in "703.3 MiB"-like string format
// Returns size in B-based long
String[] parts = string.split(" ");
if (parts[1].equals("TiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L * 1024L * 1024L * 1024L);
} else if (parts[1].equals("GiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L * 1024L * 1024L);
} else if (parts[1].equals("MiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L * 1024L);
} else if (parts[1].equals("KiB")) {
return (long) (Double.parseDouble(parts[0]) * 1024L);
}
return (long) (Double.parseDouble(parts[0]));
}
private int parseKnown(String leechs, String seeds) {
// Peers are given in the "num_leechs":"91 (449)","num_seeds":"6 (27)" strings
// Or sometimes just "num_leechs":"91","num_seeds":"6" strings
// Peers known are in the last () bit of the leechers and seeders
int leechers = 0;
if (leechs.indexOf("(") < 0) {
leechers = Integer.parseInt(leechs);
} else {
leechers = Integer.parseInt(leechs.substring(leechs.indexOf("(") + 1, leechs.indexOf(")")));
}
int seeders = 0;
if (seeds.indexOf("(") < 0) {
seeders = Integer.parseInt(seeds);
} else {
seeders = Integer.parseInt(seeds.substring(seeds.indexOf("(") + 1, seeds.indexOf(")")));
}
return leechers + seeders;
}
private int parseSeeds(String seeds) {
// Seeds are in the first part of the "num_seeds":"6 (27)" string
// In some situations it it just a "6" string
if (seeds.indexOf(" ") < 0) {
return Integer.parseInt(seeds);
}
return Integer.parseInt(seeds.substring(0, seeds.indexOf(" ")));
}
private int parseLeech(String leechs) {
// Leechers are in the first part of the "num_leechs":"91 (449)" string
// In some situations it it just a "0" string
if (leechs.indexOf(" ") < 0) {
return Integer.parseInt(leechs);
}
return Integer.parseInt(leechs.substring(0, leechs.indexOf(" ")));
}
private int parseSpeed(String speed) {
// See https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation
if (speed.equals("Unknown"))
return -1;
// Speeds are in "21.9 KiB/s"-like string format
// Returns speed in B/s-based integer
String[] parts = speed.split(" ");
if (parts[1].equals("GiB/s")) {
return (int) (Double.parseDouble(parts[0]) * 1024 * 1024 * 1024);
} else if (parts[1].equals("MiB/s")) {
return (int) (Double.parseDouble(parts[0]) * 1024 * 1024);
} else if (parts[1].equals("KiB/s")) {
return (int) (Double.parseDouble(parts[0]) * 1024);
}
return (int) (Double.parseDouble(parts[0]));
}
private TorrentStatus parseStatus(String state) {
// Status is given as a descriptive string
if (state.equals("downloading")) {
return TorrentStatus.Downloading;
} else if (state.equals("uploading")) {
return TorrentStatus.Seeding;
} else if (state.equals("pausedDL")) {
return TorrentStatus.Paused;
} else if (state.equals("pausedUL")) {
return TorrentStatus.Paused;
} else if (state.equals("stalledUP")) {
return TorrentStatus.Seeding;
} else if (state.equals("stalledDL")) {
return TorrentStatus.Downloading;
} else if (state.equals("checkingUP")) {
return TorrentStatus.Checking;
} else if (state.equals("checkingDL")) {
return TorrentStatus.Checking;
} else if (state.equals("queuedDL")) {
return TorrentStatus.Queued;
} else if (state.equals("queuedUL")) {
return TorrentStatus.Queued;
}
return TorrentStatus.Unknown;
}
private ArrayList<TorrentFile> parseJsonFiles(JSONArray response) throws JSONException {
// Parse response
ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
for (int i = 0; i < response.length(); i++) {
JSONObject file = response.getJSONObject(i);
long size = parseSize(file.getString("size"));
torrentfiles.add(new TorrentFile(
"" + i,
file.getString("name"),
null,
null,
size,
(long) (size * file.getDouble("progress")),
parsePriority(file.getInt("priority"))));
}
// Return the list
return torrentfiles;
}
private Priority parsePriority(int priority) {
// Priority is an integer
// Actually 1 = Normal, 2 = High, 7 = Maximum, but adjust this to Transdroid values
if (priority == 0) {
return Priority.Off;
} else if (priority == 1) {
return Priority.Low;
} else if (priority == 2) {
return Priority.Normal;
}
return Priority.High;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum TorrentStatus {
Waiting (1),
Checking (2),
Downloading (4),
Seeding (8),
Paused (16),
Queued (32),
Error (64),
Unknown (0);
private int code;
private static final Map<Integer,TorrentStatus> lookup = new HashMap<Integer,TorrentStatus>();
static {
for(TorrentStatus s : EnumSet.allOf(TorrentStatus.class))
lookup.put(s.getCode(), s);
}
TorrentStatus(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static TorrentStatus getStatus(int code) {
return lookup.get(code);
}
public int compareStatusCodeTo(TorrentStatus another) {
return new Integer(this.getCode()).compareTo(new Integer(another.getCode()));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum DaemonMethod {
Retrieve (0),
AddByUrl (1),
AddByMagnetUrl (2),
AddByFile (3),
Remove (4),
Pause (5),
PauseAll (6),
Resume (7),
ResumeAll (8),
Stop (9),
StopAll (10),
Start (11),
StartAll (12),
GetFileList (13),
SetFilePriorities (14),
SetTransferRates (15),
SetLabel(16),
SetDownloadLocation (17),
GetTorrentDetails (18),
SetTrackers (19),
SetAlternativeMode (20),
GetStats (21);
private int code;
private static final Map<Integer,DaemonMethod> lookup = new HashMap<Integer,DaemonMethod>();
static {
for(DaemonMethod s : EnumSet.allOf(DaemonMethod.class))
lookup.put(s.getCode(), s);
}
DaemonMethod(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static DaemonMethod getStatus(int code) {
return lookup.get(code);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import android.os.Bundle;
public class StartAllTask extends DaemonTask {
protected StartAllTask(IDaemonAdapter adapter, Bundle data) {
super(adapter, DaemonMethod.StartAll, null, data);
}
public static StartAllTask create(IDaemonAdapter adapter, boolean forceStart) {
Bundle data = new Bundle();
data.putBoolean("FORCED", forceStart);
return new StartAllTask(adapter, data);
}
public boolean includingData() {
return extras.getBoolean("FORCED");
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
/**
* The result of a successfully executed task on the daemon.
*
* @author erickok
*
*/
public class DaemonTaskSuccessResult extends DaemonTaskResult {
public DaemonTaskSuccessResult(DaemonTask executedTask) {
super(executedTask, true);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import android.os.Bundle;
public class SetTransferRatesTask extends DaemonTask {
protected SetTransferRatesTask(IDaemonAdapter adapter, Bundle data) {
super(adapter, DaemonMethod.SetTransferRates, null, data);
}
public static SetTransferRatesTask create(IDaemonAdapter adapter, Integer uploadRate, Integer downloadRate) {
Bundle data = new Bundle();
data.putInt("UPLOAD_RATE", (uploadRate == null? -1: uploadRate.intValue()));
data.putInt("DOWNLOAD_RATE", (downloadRate == null? -1: downloadRate.intValue()));
return new SetTransferRatesTask(adapter, data);
}
public Integer getUploadRate() {
int uploadRate = extras.getInt("UPLOAD_RATE");
return (uploadRate == -1? null: new Integer(uploadRate));
}
public Integer getDownloadRate() {
int downloadRate = extras.getInt("DOWNLOAD_RATE");
return (downloadRate == -1? null: new Integer(downloadRate));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import android.os.Bundle;
public class AddByMagnetUrlTask extends DaemonTask {
protected AddByMagnetUrlTask(IDaemonAdapter adapter, Bundle data) {
super(adapter, DaemonMethod.AddByMagnetUrl, null, data);
}
public static AddByMagnetUrlTask create(IDaemonAdapter adapter, String url) {
Bundle data = new Bundle();
data.putString("URL", url);
return new AddByMagnetUrlTask(adapter, data);
}
public String getUrl() {
return extras.getString("URL");
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonException;
/**
*
* The result daemon task that failed. Use getException() to see what went wrong.
*
* @author erickok
*
*/
public class DaemonTaskFailureResult extends DaemonTaskResult {
private DaemonException e;
public DaemonTaskFailureResult(DaemonTask executedTask, DaemonException e) {
super(executedTask, false);
this.e = e;
}
/**
* Return the exception that occurred during the task execution.
* @return A daemon exception object with string res ID or fixed string message
*/
public DaemonException getException() {
return e;
}
@Override
public String toString() {
return "Failure on " + executedTask.toString() + ": " + getException().toString();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
public class ResumeTask extends DaemonTask {
protected ResumeTask(IDaemonAdapter adapter, Torrent targetTorrent) {
super(adapter, DaemonMethod.Resume, targetTorrent, null);
}
public static ResumeTask create(IDaemonAdapter adapter, Torrent targetTorrent) {
return new ResumeTask(adapter, targetTorrent);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import android.os.Bundle;
public class SetLabelTask extends DaemonTask {
protected SetLabelTask(IDaemonAdapter adapter, Torrent targetTorrent, Bundle data) {
super(adapter, DaemonMethod.SetLabel, targetTorrent, data);
}
public static SetLabelTask create(IDaemonAdapter adapter, Torrent targetTorrent, String newLabel) {
Bundle data = new Bundle();
data.putString("NEW_LABEL", newLabel);
return new SetLabelTask(adapter, targetTorrent, data);
}
public String getNewLabel() {
return extras.getString("NEW_LABEL");
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
public class PauseTask extends DaemonTask {
protected PauseTask(IDaemonAdapter adapter, Torrent targetTorrent) {
super(adapter, DaemonMethod.Pause, targetTorrent, null);
}
public static PauseTask create(IDaemonAdapter adapter, Torrent targetTorrent) {
return new PauseTask(adapter, targetTorrent);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
public class GetTorrentDetailsTask extends DaemonTask {
protected GetTorrentDetailsTask(IDaemonAdapter adapter, Torrent targetTorrent) {
super(adapter, DaemonMethod.GetTorrentDetails, targetTorrent, null);
}
public static GetTorrentDetailsTask create(IDaemonAdapter adapter, Torrent targetTorrent) {
return new GetTorrentDetailsTask(adapter, targetTorrent);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
public class ResumeAllTask extends DaemonTask {
protected ResumeAllTask(IDaemonAdapter adapter) {
super(adapter, DaemonMethod.ResumeAll, null, null);
}
public static ResumeAllTask create(IDaemonAdapter adapter) {
return new ResumeAllTask(adapter);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import android.os.Bundle;
public class SetAlternativeModeTask extends DaemonTask {
protected SetAlternativeModeTask(IDaemonAdapter adapter, Bundle data) {
super(adapter, DaemonMethod.SetAlternativeMode, null, data);
}
public static SetAlternativeModeTask create(IDaemonAdapter adapter, boolean isAlternativeModeEnabled) {
Bundle data = new Bundle();
data.putBoolean("ALT_MODE", isAlternativeModeEnabled);
return new SetAlternativeModeTask(adapter, data);
}
public boolean isAlternativeModeEnabled() {
return extras.getBoolean("ALT_MODE");
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.Torrent;
/**
* The result of a task that was executed on the daemon. This is always either a success or failure and hence
* only these in-line classes are publicly used.
*
* @author erickok
*
*/
public class DaemonTaskResult {
protected DaemonTask executedTask;
protected boolean success;
/**
* Protected constructor. This class must be used only via the DaemonTaskSuccessResult or DaemonTaskFailureResult.
*/
protected DaemonTaskResult(DaemonTask executedTask, boolean wasSuccessful) {
this.executedTask = executedTask;
this.success = wasSuccessful;
}
/**
* Returns the original task that we were executing on the daemon, so all extra data is also available.
* @return The task as it was originally queued
*/
public DaemonTask getTask() {
return executedTask;
}
/**
* Returns the original method that we were executing on the daemon.
* @return The method type of the executed task
*/
public DaemonMethod getMethod() {
return executedTask.getMethod();
}
/**
* The torrent to that was the target of the executed task.
* @return The targeted torrent object, or null if it was torrent-independent
*/
public Torrent getTargetTorrent() {
return executedTask.getTargetTorrent();
}
/**
* Whether the task executed successfully.
* @return True if the task executed as expected, false if some error occurred
*/
public boolean wasSuccessful() {
return success;
}
@Override
public String toString() {
return (success? "Success on ": "Failure on ") + executedTask.toString();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import java.util.List;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.Label;
/**
* The result of a successfully executed RetrieveTask on the daemon.
*
* @author erickok
*
*/
public class RetrieveTaskSuccessResult extends DaemonTaskSuccessResult {
private List<Torrent> torrents;
private List<Label> labels;
public RetrieveTaskSuccessResult(RetrieveTask executedTask, List<Torrent> torrents, List<Label> labels) {
super(executedTask);
this.torrents = torrents;
this.labels = labels;
}
public List<Torrent> getTorrents() {
return torrents;
}
public List<Label> getLabels() {
return labels;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import android.os.Bundle;
public class AddByUrlTask extends DaemonTask {
protected AddByUrlTask(IDaemonAdapter adapter, Bundle data) {
super(adapter, DaemonMethod.AddByUrl, null, data);
}
public static AddByUrlTask create(IDaemonAdapter adapter, String url, String title) {
Bundle data = new Bundle();
data.putString("URL", url);
data.putString("TITLE", title);
return new AddByUrlTask(adapter, data);
}
public String getUrl() {
return extras.getString("URL");
}
public String getTitle() {
return extras.getString("TITLE");
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.TorrentDetails;
/**
* The result of a successfully executed GetTorrentDetailsTask on the daemon.
*
* @author erickok
*
*/
public class GetTorrentDetailsTaskSuccessResult extends DaemonTaskSuccessResult {
private TorrentDetails details;
public GetTorrentDetailsTaskSuccessResult(GetTorrentDetailsTask executedTask, TorrentDetails details) {
super(executedTask);
this.details = details;
}
public TorrentDetails getTorrentDetails() {
return details;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import android.os.Bundle;
public class SetTrackersTask extends DaemonTask {
protected SetTrackersTask(IDaemonAdapter adapter, Torrent targetTorrent, Bundle data) {
super(adapter, DaemonMethod.SetTrackers, targetTorrent, data);
}
public static SetTrackersTask create(IDaemonAdapter adapter, Torrent targetTorrent, List<String> list) {
Bundle data = new Bundle();
data.putStringArrayList("NEW_TRACKERS_LSIT", new ArrayList<String>(list));
return new SetTrackersTask(adapter, targetTorrent, data);
}
public ArrayList<String> getNewTrackers() {
return extras.getStringArrayList("NEW_TRACKERS_LSIT");
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import android.os.Bundle;
public class StartTask extends DaemonTask {
protected StartTask(IDaemonAdapter adapter, Torrent targetTorrent, Bundle data) {
super(adapter, DaemonMethod.Start, targetTorrent, data);
}
public static StartTask create(IDaemonAdapter adapter, Torrent targetTorrent, boolean forceStart) {
Bundle data = new Bundle();
data.putBoolean("FORCED", forceStart);
return new StartTask(adapter, targetTorrent, data);
}
public boolean isForced() {
return extras.getBoolean("FORCED");
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
public class StopAllTask extends DaemonTask {
protected StopAllTask(IDaemonAdapter adapter) {
super(adapter, DaemonMethod.StopAll, null, null);
}
public static StopAllTask create(IDaemonAdapter adapter) {
return new StopAllTask(adapter);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
public class RetrieveTask extends DaemonTask {
protected RetrieveTask(IDaemonAdapter adapter) {
super(adapter, DaemonMethod.Retrieve, null, null);
}
public static RetrieveTask create(IDaemonAdapter adapter) {
return new RetrieveTask(adapter);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
/**
* The result of a successfully executed RetrieveTask on the daemon.
*
* @author erickok
*
*/
public class GetStatsTaskSuccessResult extends DaemonTaskSuccessResult {
private final boolean alternativeModeEnabled;
private final long downloadDirFreeSpaceBytes;
public GetStatsTaskSuccessResult(GetStatsTask executedTask, boolean alternativeModeEnabled, long downloadDirFreeSpaceBytes) {
super(executedTask);
this.alternativeModeEnabled = alternativeModeEnabled;
this.downloadDirFreeSpaceBytes = downloadDirFreeSpaceBytes;
}
public boolean isAlternativeModeEnabled() {
return alternativeModeEnabled;
}
public long getDownloadDirFreeSpaceBytes() {
return downloadDirFreeSpaceBytes;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import java.util.List;
import org.transdroid.daemon.TorrentFile;
/**
* The result of a successfully executed GetFileListTask on the daemon.
*
* @author erickok
*
*/
public class GetFileListTaskSuccessResult extends DaemonTaskSuccessResult {
private List<TorrentFile> files;
public GetFileListTaskSuccessResult(GetFileListTask executedTask, List<TorrentFile> files) {
super(executedTask);
this.files = files;
}
public List<TorrentFile> getFiles() {
return files;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import android.os.Bundle;
public class RemoveTask extends DaemonTask {
protected RemoveTask(IDaemonAdapter adapter, Torrent targetTorrent, Bundle data) {
super(adapter, DaemonMethod.Remove, targetTorrent, data);
}
public static RemoveTask create(IDaemonAdapter adapter, Torrent targetTorrent, boolean includingData) {
Bundle data = new Bundle();
data.putBoolean("WITH_DATA", includingData);
return new RemoveTask(adapter, targetTorrent, data);
}
public boolean includingData() {
return extras.getBoolean("WITH_DATA");
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
public class GetFileListTask extends DaemonTask {
protected GetFileListTask(IDaemonAdapter adapter, Torrent targetTorrent) {
super(adapter, DaemonMethod.GetFileList, targetTorrent, null);
}
public static GetFileListTask create(IDaemonAdapter adapter, Torrent targetTorrent) {
return new GetFileListTask(adapter, targetTorrent);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
public class PauseAllTask extends DaemonTask {
protected PauseAllTask(IDaemonAdapter adapter) {
super(adapter, DaemonMethod.PauseAll, null, null);
}
public static PauseAllTask create(IDaemonAdapter adapter) {
return new PauseAllTask(adapter);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import android.os.Bundle;
public class AddByFileTask extends DaemonTask {
protected AddByFileTask(IDaemonAdapter adapter, Bundle data) {
super(adapter, DaemonMethod.AddByFile, null, data);
}
public static AddByFileTask create(IDaemonAdapter adapter, String file) {
Bundle data = new Bundle();
data.putString("FILE", file);
return new AddByFileTask(adapter, data);
}
public String getFile() {
return extras.getString("FILE");
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import android.os.Bundle;
public class SetDownloadLocationTask extends DaemonTask {
protected SetDownloadLocationTask(IDaemonAdapter adapter, Torrent targetTorrent, Bundle data) {
super(adapter, DaemonMethod.SetDownloadLocation, targetTorrent, data);
}
public static SetDownloadLocationTask create(IDaemonAdapter adapter, Torrent targetTorrent, String newLocation) {
Bundle data = new Bundle();
data.putString("LOCATION", newLocation);
return new SetDownloadLocationTask(adapter, targetTorrent, data);
}
public String getNewLocation() {
return extras.getString("LOCATION");
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import java.util.ArrayList;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentFile;
import android.os.Bundle;
public class SetFilePriorityTask extends DaemonTask {
protected SetFilePriorityTask(IDaemonAdapter adapter, Torrent targetTorrent, Bundle data) {
super(adapter, DaemonMethod.SetFilePriorities, targetTorrent, data);
}
public static SetFilePriorityTask create(IDaemonAdapter adapter, Torrent targetTorrent, Priority newPriority, ArrayList<TorrentFile> forFiles) {
Bundle data = new Bundle();
data.putInt("NEW_PRIORITY", newPriority.getCode());
data.putParcelableArrayList("FOR_FILES", forFiles);
return new SetFilePriorityTask(adapter, targetTorrent, data);
}
public static SetFilePriorityTask create(IDaemonAdapter adapter, Torrent targetTorrent, Priority newPriority, TorrentFile forFile) {
ArrayList<TorrentFile> forFiles = new ArrayList<TorrentFile>();
forFiles.add(forFile);
return create(adapter, targetTorrent, newPriority, forFiles);
}
public Priority getNewPriority() {
return Priority.getPriority(extras.getInt("NEW_PRIORITY"));
}
public ArrayList<TorrentFile> getForFiles() {
return extras.getParcelableArrayList("FOR_FILES");
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
public class StopTask extends DaemonTask {
protected StopTask(IDaemonAdapter adapter, Torrent targetTorrent) {
super(adapter, DaemonMethod.Stop, targetTorrent, null);
}
public static StopTask create(IDaemonAdapter adapter, Torrent targetTorrent) {
return new StopTask(adapter, targetTorrent);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
public class GetStatsTask extends DaemonTask {
protected GetStatsTask(IDaemonAdapter adapter) {
super(adapter, DaemonMethod.GetStats, null, null);
}
public static GetStatsTask create(IDaemonAdapter adapter) {
return new GetStatsTask(adapter);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.task;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A daemon task represents some action that needs to be performed
* on the server daemon. It has no capabilities on itself; these are
* marshaled to the daemon adapter. Therefore all needed info (the
* parameters) needs to be added to the extras bundle.
*
* To help create these tasks and there data, each possible daemon
* method is created using a task-specific separate class with a
* create() method.
*
* This class is Parcelable so it can be persisted in between an
* Activity breakdown and recreation.
*
* @author erickok
*
*/
public class DaemonTask implements Parcelable {
protected IDaemonAdapter adapter;
protected final DaemonMethod method;
protected final Torrent targetTorrent;
protected final Bundle extras;
private DaemonTask(Parcel in) {
this.method = DaemonMethod.getStatus(in.readInt());
this.targetTorrent = in.readParcelable(Torrent.class.getClassLoader());
this.extras = in.readBundle();
}
protected DaemonTask(IDaemonAdapter adapter, DaemonMethod method, Torrent targetTorrent, Bundle extras) {
this.adapter = adapter;
this.method = method;
this.targetTorrent = targetTorrent;
if (extras == null) {
this.extras = new Bundle();
} else {
this.extras = extras;
}
}
/**
* Execute the task on the appropriate daemon adapter
*/
public DaemonTaskResult execute() {
return adapter.executeTask(this);
}
public DaemonMethod getMethod() {
return method;
}
public Daemon getAdapterType() {
return this.adapter.getType();
}
public Torrent getTargetTorrent() {
return targetTorrent;
}
public Bundle getExtras() {
return extras;
}
public static final Parcelable.Creator<DaemonTask> CREATOR = new Parcelable.Creator<DaemonTask>() {
public DaemonTask createFromParcel(Parcel in) {
return new DaemonTask(in);
}
public DaemonTask[] newArray(int size) {
return new DaemonTask[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(method.getCode());
dest.writeParcelable(targetTorrent, 0);
dest.writeBundle(extras);
}
/**
* Returns a readable description of this task in the form 'MethodName on AdapterName with TorrentName and AllExtras'
*/
public String toString() {
return method.toString() + (adapter == null? "": " on " + adapter.getType()) + (targetTorrent != null || extras != null? " with ": "") + (targetTorrent == null? "": targetTorrent.toString() + (targetTorrent != null && extras != null? " and ": "")) + (extras == null? "": extras.toString());
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.Bitflu;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetStatsTask;
import org.transdroid.daemon.task.GetStatsTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.daemon.util.DLog;
/**
* An adapter that allows for easy access to uTorrent torrent data. Communication
* is handled via authenticated JSON-RPC HTTP GET requests and responses.
*
* @author adrianulrich
*
*/
// TODO: TransferRates support
public class BitfluAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "Bitflu daemon";
private static final String JSON_ROOT = "Bitflu";
private static final String RPC_TORRENT_LIST = "torrentList";
private static final String RPC_PAUSE_TORRENT = "pause/";
private static final String RPC_RESUME_TORRENT = "resume/";
private static final String RPC_CANCEL_TORRENT = "cancel/";
private static final String RPC_REMOVE_TORRENT = "wipe/";
private static final String RPC_TORRENT_FILES = "showfiles-ext/";
private static final String RPC_START_DOWNLOAD = "startdownload/";
private String webuiroot = "";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
/**
* Initialises an adapter that provides operations to the Bitflu web interface
*/
public BitfluAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
JSONObject result = makeBitfluRequest(RPC_TORRENT_LIST);
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result.getJSONArray(JSON_ROOT)),null);
case GetStats:
return new GetStatsTaskSuccessResult((GetStatsTask) task, false, -1);
case Pause:
makeBitfluRequest(RPC_PAUSE_TORRENT + task.getTargetTorrent().getUniqueID());
return new DaemonTaskSuccessResult(task);
case Resume:
makeBitfluRequest(RPC_RESUME_TORRENT + task.getTargetTorrent().getUniqueID());
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
String removeUriBase = RPC_CANCEL_TORRENT;
if(removeTask.includingData()) {
removeUriBase = RPC_REMOVE_TORRENT;
}
DLog.d(LOG_NAME, "*** CALLING "+removeUriBase);
makeBitfluRequest(removeUriBase + task.getTargetTorrent().getUniqueID());
return new DaemonTaskSuccessResult(task);
case GetFileList:
JSONObject jfiles = makeBitfluRequest(RPC_TORRENT_FILES + task.getTargetTorrent().getUniqueID());
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonShowFilesTorrent(jfiles.getJSONArray(JSON_ROOT)));
case AddByUrl:
String url = URLEncoder.encode(((AddByUrlTask)task).getUrl(), "UTF-8");
makeBitfluRequest(RPC_START_DOWNLOAD + url);
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
String magnet = URLEncoder.encode(((AddByMagnetUrlTask)task).getUrl(), "UTF-8");
makeBitfluRequest(RPC_START_DOWNLOAD + magnet);
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (UnsupportedEncodingException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, e.toString()));
}
}
private JSONObject makeBitfluRequest(String addToUrl) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
//TLog.d(LOG_NAME, "Request to: "+ buildWebUIUrl() + addToUrl);
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + addToUrl);
HttpResponse response = httpclient.execute(httpget);
// Read JSON response
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
int httpstatus = response.getStatusLine().getStatusCode();
if(httpstatus != 200) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Invalid reply from server, http status code: " + httpstatus);
}
if(result.equals("")) { // Empty responses are ok: add fake json content
result = "empty_response";
}
JSONObject json = new JSONObject("{ \""+JSON_ROOT+"\" : "+ result +"}");
instream.close();
return json;
} catch (DaemonException e) {
throw e;
} catch (JSONException e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONArray results) throws JSONException {
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
if (results != null) {
for (int i = 0; i < results.length(); i++) {
JSONObject tor = results.getJSONObject(i);
long done_bytes = tor.getLong("done_bytes");
long total_bytes = tor.getLong("total_bytes");
float percent = ((float)done_bytes/((float)total_bytes+1));
torrents.add(new Torrent(i,
tor.getString("key"),
tor.getString("name"),
convertBitfluStatus(tor),
"/" + settings.getOS().getPathSeperator(),
tor.getInt("speed_download"),
tor.getInt("speed_upload"),
0, // 'uploading to'
tor.getInt("active_clients"),
tor.getInt("clients"),
tor.getInt("clients"),
tor.getInt("eta"),
done_bytes,
tor.getLong("uploaded_bytes"),
total_bytes,
percent, // Percentage to [0..1]
0f, // Not available
null, // label
null, // Not available
null, // Not available
null)); // Not available
}
}
// Return the list
return torrents;
}
private ArrayList<TorrentFile> parseJsonShowFilesTorrent(JSONArray response) throws JSONException {
ArrayList<TorrentFile> files = new ArrayList<TorrentFile>();
if(response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject finfo = response.getJSONObject(i);
long done_bytes = finfo.getLong("done") * finfo.getLong("chunksize");
long file_size = finfo.getLong("size");
if( done_bytes > file_size) { /* Shared chunk */
done_bytes = file_size;
}
files.add(new TorrentFile(
"" + i,
finfo.getString("name"),
finfo.getString("path"),
null, // hmm.. can we have something without file:// ?!
file_size,
done_bytes,
Priority.Normal
));
}
}
return files;
}
private TorrentStatus convertBitfluStatus(JSONObject obj) throws JSONException {
if( obj.getInt("paused") != 0 ) {
return TorrentStatus.Paused;
}
else if (obj.getLong("done_bytes") == obj.getLong("total_bytes")) {
return TorrentStatus.Seeding;
}
return TorrentStatus.Downloading;
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all HTTP requests.
* @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise() throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
if(settings != null) {
webuiroot = settings.getFolder();
}
}
/**
* Build the URL of the Transmission web UI from the user settings.
* @return The URL of the RPC API
*/
private String buildWebUIUrl() {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + webuiroot + "/";
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
/**
* A class that contains all the settings for a server daemon to connect.
*
* @author erickok
*
*/
public final class DaemonSettings {
private static final String DEFAULT_NAME = "Default";
final private String name;
final private Daemon type;
final private String address;
final private int port;
final private boolean ssl;
final private boolean sslTrustAll;
final private String sslTrustKey;
final private String folder;
final private boolean useAuthentication;
final private String username;
final private String password;
final private String extraPass;
final private OS os;
final private String downloadDir;
final private String ftpUrl;
final private String ftpPassword;
final private int timeout;
final private boolean alarmOnFinishedDownload;
final private boolean alarmOnNewTorrent;
final private String idString;
final private boolean isAutoGenerated;
protected DaemonSettings() {
this(null, null, null, 0, false, false, null, null, false, null, null, null,
null, null, null, null, 0, false, false, null, false);
}
/**
* Creates a daemon settings instance, providing full connection details
* @param name A name used to identify this server to the user
* @param type The server daemon type
* @param address The server domain name or IP address
* @param port The port on which the server daemon is running
* @param sslTrustKey The specific key that will be accepted.
* @param folder The server (SCGI) folder
* @param useAuthentication Whether to use basic authentication
* @param username The user name to provide during authentication
* @param password The password to provide during authentication
* @param extraPass The Deluge web interface password
* @param downloadDir The default download directory (which may also be used as base directory for file paths)
* @param ftpUrl The partial URL to connect to when requesting FTP-style transfers
* @param timeout The number of seconds to wait before timing out a connection attempt
* @param idString The (numeric) identifier for this server settings (used as postfix on stored preferenced)
* @param isAutoGenerated Whether this setting was generated rather than manually inputed by the user
*/
public DaemonSettings(String name, Daemon type, String address, int port, boolean ssl,
boolean sslTrustAll, String sslTrustKey, String folder, boolean useAuthentication,
String username, String password, String extraPass, OS os, String downloadDir, String ftpUrl, String ftpPassword, int timeout,
boolean alarmOnFinishedDownload, boolean alarmOnNewTorrent, String idString, boolean isAutoGenerated)
{
this.name = name;
this.type = type;
this.address = address;
this.port = port;
this.ssl = ssl;
this.sslTrustAll = sslTrustAll;
this.sslTrustKey = sslTrustKey;
this.folder = folder;
this.useAuthentication = useAuthentication;
this.username = username;
this.password = password;
this.extraPass = extraPass;
this.os = os;
this.downloadDir = downloadDir;
this.ftpUrl = ftpUrl;
this.ftpPassword = ftpPassword;
this.timeout = timeout;
this.alarmOnFinishedDownload = alarmOnFinishedDownload;
this.alarmOnNewTorrent = alarmOnNewTorrent;
this.idString = idString;
this.isAutoGenerated = isAutoGenerated;
}
public String getName() {
return (name == null || name.equals("")? DEFAULT_NAME: name);
}
public Daemon getType() {
return type;
}
public String getAddress() {
return address;
}
public int getPort() {
return port;
}
public boolean getSsl() {
return ssl;
}
public boolean getSslTrustAll() {
return sslTrustAll;
}
public String getSslTrustKey() {
return sslTrustKey;
}
public String getFolder() {
return folder;
}
public boolean shouldUseAuthentication() {
return useAuthentication;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getExtraPassword() {
return extraPass;
}
public OS getOS() {
return os;
}
public String getDownloadDir() {
return downloadDir;
}
public String getFtpUrl() {
return ftpUrl;
}
public String getFtpPassword() {
return ftpPassword;
}
public int getTimeoutInMilliseconds() {
return timeout * 1000;
}
public boolean shouldAlarmOnFinishedDownload() {
return alarmOnFinishedDownload;
}
public boolean shouldAlarmOnNewTorrent() {
return alarmOnNewTorrent;
}
public String getIdString() {
return idString;
}
public boolean isAutoGenerated() {
return isAutoGenerated;
}
/**
* Builds a text that can be used by a human reader to identify this daemon settings
* @return A concatenation of username, address, port and folder, where applicable
*/
public String getHumanReadableIdentifier() {
if (isAutoGenerated) {
// Hide the 'implementation details'; just give the username and server
return (this.shouldUseAuthentication() && this.getUsername() != null && this.getUsername() != "" ? this
.getUsername() + "@" : "") + getAddress();
}
return (this.ssl ? "https://" : "http://")
+ (this.shouldUseAuthentication() && this.getUsername() != null && this.getUsername() != "" ? this
.getUsername() + "@" : "") + getAddress() + ":" + getPort()
+ (Daemon.supportsCustomFolder(getType()) && getFolder() != null ? getFolder() : "");
}
@Override
public String toString() {
return getHumanReadableIdentifier();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskResult;
/**
* The required methods that a server daemon adapter should implement, to
* support all client operations.
*
* @author erickok
*
*/
public interface IDaemonAdapter {
public DaemonTaskResult executeTask(DaemonTask task);
public Daemon getType();
public DaemonSettings getSettings();
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.BuffaloNas;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
import com.android.internalcopy.http.multipart.FilePart;
import com.android.internalcopy.http.multipart.MultipartEntity;
import com.android.internalcopy.http.multipart.Part;
/**
* The daemon adapter for the Buffalo NAS' integrated torrent client.
*
* @author erickok
*
*/
public class BuffaloNasAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "qBittorrent daemon";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
public BuffaloNasAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
JSONObject result = new JSONObject(makeRequest("/api/torrents-get"));
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonTorrents(result),null);
case GetFileList:
// Request files listing for a specific torrent
String fhash = ((GetFileListTask)task).getTargetTorrent().getUniqueID();
JSONObject files = new JSONObject(makeRequest("/api/torrent-get-files", new BasicNameValuePair("hash", fhash)));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseJsonFiles(files, fhash));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask)task).getFile();
makeUploadRequest("/api/torrent-add?start=yes", ufile);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeRequest("/api/torrent-add", new BasicNameValuePair("url", url), new BasicNameValuePair("start", "yes"));
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeRequest("/api/torrent-remove", new BasicNameValuePair("hash", removeTask.getTargetTorrent().getUniqueID()),
new BasicNameValuePair("delete-torrent", "yes"), new BasicNameValuePair("delete-data", (removeTask.includingData()? "yes": "no")));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeRequest("/api/torrent-stop", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRequest("/api/torrent-start", new BasicNameValuePair("hash", task.getTargetTorrent().getUniqueID()));
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
String dl = Integer.toString((ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue() * 1024));
String ul = Integer.toString((ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue() * 1024));
makeRequest("/api/app-settings-set", new BasicNameValuePair("auto_bandwidth_management", "0"), new BasicNameValuePair("max_dl_rate", dl), new BasicNameValuePair("max_ul_rate", ul), new BasicNameValuePair("max_ul_rate_seed", ul));
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
}
}
private String makeRequest(String url, NameValuePair... params) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
}
// Add the parameters to the query string
boolean first = true;
for (NameValuePair param : params) {
if (first) {
url += "?";
first = false;
} else {
url += "&";
}
url += param.getName() + "=" + param.getValue();
}
// Make the request
HttpResponse response = httpclient.execute(new HttpGet(buildWebUIUrl(url)));
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read JSON response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
// Return raw result
return result;
}
DLog.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (UnsupportedEncodingException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private boolean makeUploadRequest(String path, String file) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
}
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
File upload = new File(URI.create(file));
Part[] parts = { new FilePart("fileEl", upload) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
// Make the request
HttpResponse response = httpclient.execute(httppost);
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} catch (FileNotFoundException e) {
throw new DaemonException(ExceptionType.FileAccessError, e.toString());
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all Buffalo NAS requests.
* @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise(int connectionTimeout) throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
}
/**
* Build the URL of the http request from the user settings
* @return The URL to request
*/
private String buildWebUIUrl(String path) {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + path;
}
private ArrayList<Torrent> parseJsonTorrents(JSONObject response) throws JSONException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
JSONArray all = response.getJSONArray("torrents");
for (int i = 0; i < all.length(); i++) {
JSONObject tor = all.getJSONObject(i);
int leechers = tor.getInt("peers_connected");
int seeders = tor.getInt("seeds_connected");
int known = tor.getInt("peers_total") + tor.getInt("seeds_total");
long size = tor.getLong("size");
long sizeDone = tor.getLong("done");
long sizeUp = tor.getLong("payload_upload");
int rateUp = tor.getInt("dl_rate");
int rateDown = tor.getInt("ul_rate");
// Add the parsed torrent to the list
torrents.add(new Torrent(
(long)i,
tor.getString("hash"),
tor.getString("caption"),
parseStatus(tor.getString("state"), tor.getInt("stopped")),
null,
rateDown,
rateUp,
leechers,
leechers + seeders,
known,
known,
(rateDown == 0? -1: (int) ((size - sizeDone) / rateDown)),
sizeDone,
sizeUp,
size,
(float)sizeDone / size,
(float)tor.getDouble("distributed_copies") / 10,
null,
null,
null,
null));
}
// Return the list
return torrents;
}
private TorrentStatus parseStatus(String state, int stopped) {
// Status is given as a descriptive string and an indication if the torrent was stopped/paused
if (state.equals("downloading")) {
if (stopped == 1) {
return TorrentStatus.Paused;
} else {
return TorrentStatus.Downloading;
}
} else if (state.equals("seeding")) {
if (stopped == 1) {
return TorrentStatus.Paused;
} else {
return TorrentStatus.Seeding;
}
}
return TorrentStatus.Unknown;
}
private ArrayList<TorrentFile> parseJsonFiles(JSONObject response, String hash) throws JSONException {
// Parse response
ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
JSONArray all = response.getJSONObject("torrents").getJSONArray(hash);
for (int i = 0; i < all.length(); i++) {
JSONObject file = all.getJSONObject(i);
long size = file.getLong("size");
long sizeDone = file.getLong("done");
torrentfiles.add(new TorrentFile(
"" + file.getInt("id"),
file.getString("name"),
file.getString("name"),
settings.getDownloadDir() + file.getString("name"),
size,
sizeDone,
Priority.Normal));
}
// Return the list
return torrentfiles;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.util.DLog;
public class TaskQueue implements Runnable {
private static final String LOG_NAME = "Queue";
private List<DaemonTask> queue;
private Thread worker;
private IDaemonCallback callback;
private boolean paused;;
public TaskQueue(IDaemonCallback callback) {
queue = Collections.synchronizedList(new LinkedList<DaemonTask>());
paused = true;
this.callback = callback;
worker = new Thread(this);
worker.start();
}
/**
* Enqueue a single new task to later perform.
* @param task The task to add to the queue
*/
public synchronized void enqueue(DaemonTask task) {
queue.add(task);
notifyAll();
}
/**
* Queues an old set of tasks again in the queue. This for example can be
* used to restore on old queue after an Activity was destroyed and
* is restored again.
* @param tasks A list of daemon tasks to queue
*/
public synchronized void requeue(List<DaemonTask> tasks) {
queue.addAll(tasks);
notifyAll();
}
/**
* Removes all remaining tasks from the queue. Existing operations are still
* continued and their results posted back.
*/
public synchronized void clear() {
queue.clear();
notifyAll();
}
/**
* Removes all remaining tasks from the queue that are of some specific type.
* Other remaining tasks will still be executed and running operations are
* still continued and their results posted back.
* @param class1
*/
public synchronized void clear(DaemonMethod ofType) {
Iterator<DaemonTask> task = queue.iterator();
while (task.hasNext()) {
if (task.next().getMethod() == ofType) {
task.remove();
}
}
notifyAll();
}
/**
* Returns a copy of the queue with all remaining tasks. This can be used
* to save them on an Activity destroy and restore them later using
* requeue().
* @return A list containing all remaining tasks
*/
public Queue<DaemonTask> getRemainingTasks() {
return new LinkedList<DaemonTask>(queue);
}
/**
* Request the task perfoming thread to stop all activity
*/
public synchronized void requestStop() {
paused = true;
}
/**
* Request
*/
public synchronized void start() {
paused = false;
notify();
}
@Override
public void run() {
while (true) {
if (this.paused) {
// We are going to pause
DLog.d(LOG_NAME, "Task queue pausing");
}
synchronized (this) {
while (this.paused || queue.isEmpty()) {
try {
// We are going to run again if wait() succeeded (on notify())
wait();
DLog.d(LOG_NAME, "Task queue resuming");
} catch (Exception e) {
}
}
}
processTask();
if (queue.isEmpty()) {
callback.onQueueEmpty();
// We are going to pause
DLog.d(LOG_NAME, "Task queue pausing (queue empty)");
}
}
}
private void processTask() {
// Get the task to execute
DaemonTask task = queue.remove(0);
if (task == null) {
return;
}
if (callback.isAttached())
callback.onQueuedTaskStarted(task);
// Ask the daemon adapter to perform the task (which does it synchronously)
DLog.d(LOG_NAME, "Starting task: " + task.toString());
DaemonTaskResult result = task.execute();
if (callback.isAttached())
callback.onQueuedTaskFinished(task);
// Return the result (to the UI thread)
DLog.d(LOG_NAME, "Task result: " + (result == null? "null": result.toString()));
if (result != null && !this.paused && callback.isAttached()) {
if (result.wasSuccessful()) {
callback.onTaskSuccess((DaemonTaskSuccessResult) result);
} else {
callback.onTaskFailure((DaemonTaskFailureResult) result);
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.HashMap;
import java.util.Map;
import org.transdroid.daemon.util.FileSizeConverter;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Represents a single file contained in a torrent.
*
* @author erickok
*
*/
public final class TorrentFile implements Parcelable, Comparable<TorrentFile> {
private final String key;
private final String name;
private final String relativePath;
private final String fullPath;
private final long totalSize;
private final long downloaded;
private Priority priority;
public TorrentFile(String key, String name, String relativePath, String fullPath, long size, long done, Priority priority) {
this.key = key;
this.name = name;
this.relativePath = relativePath;
this.fullPath = fullPath;
this.totalSize = size;
this.downloaded = done;
this.priority = priority;
}
private TorrentFile(Parcel in) {
this.key = in.readString();
this.name = in.readString();
this.relativePath = in.readString();
this.fullPath = in.readString();
this.totalSize = in.readLong();
this.downloaded = in.readLong();
this.priority = Priority.getPriority(in.readInt());
}
public String getKey() {
return this.key;
}
public String getName() {
return this.name;
}
public String getRelativePath() {
return this.relativePath;
}
public String getFullPath() {
return this.fullPath;
}
public long getTotalSize() {
return this.totalSize;
}
public long getDownloaded() {
return this.downloaded;
}
public Priority getPriority() {
return priority;
}
public float getPartDone() {
return (float)downloaded / (float)totalSize;
}
/**
* Returns a text showing the percentage that is already downloaded of this file
* @return A string indicating the progress, e.g. '85%'
*/
public String getProgressText() {
return String.format("%.1f", getPartDone() * 100) + "%";
}
/**
* Returns a text showing the downloaded and total sizes of this file
* @return A string with the sizes, e.g. '125.3 of 251.2 MB'
*/
public String getDownloadedAndTotalSizeText() {
return FileSizeConverter.getSize(getDownloaded()) + " / " + FileSizeConverter.getSize(getTotalSize());
}
/**
* Returns if the download for this file is complete
* @return True if the downloaded size equals the total size, i.e. if it is completed
*/
public boolean isComplete() {
return getDownloaded() == getTotalSize();
}
/**
* Returns the full path of this file as it should be located on the remote server
* @return The full path, as String
*/
public String getFullPathUri() {
return "file://" + getFullPath();
}
/**
* Try to infer the mime type of this file
* @return The mime type of this file, or null if it could not be inferred
*/
public String getMimeType() {
// TODO: Test if this still works
if (getFullPath() != null && getFullPath().contains(".")) {
final String ext = getFullPath().substring(getFullPath().lastIndexOf('.') + 1);
if (mimeTypes.containsKey(ext)) {
// One of the known extensions: return logical mime type
return mimeTypes.get(ext);
}
}
// Unknown/none/unregistered extension: return null
return null;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(TorrentFile another) {
// Compare file objects on their name (used for sorting only!)
return name.compareTo(another.getName());
}
private static final Map<String, String> mimeTypes = fillMimeTypes();
private static Map<String, String> fillMimeTypes() {
// Full mime type support list is in http://code.google.com/p/android-vlc-remote/source/browse/trunk/AndroidManifest.xml
// We use a selection of the most popular/obvious ones
HashMap<String, String> types = new HashMap<String, String>();
// Application
types.put("m4a", "application/x-extension-m4a");
types.put("flac", "application/x-flac");
types.put("mkv", "application/x-matroska");
types.put("ogg", "application/x-ogg");
// Audio
types.put("m3u", "audio/mpegurl");
types.put("mp3", "audio/mpeg");
types.put("mpa", "audio/mpeg");
types.put("mpc", "audio/x-musepack");
types.put("wav", "audio/x-wav");
types.put("wma", "audio/x-ms-wma");
// Video
types.put("3gp", "video/3gpp");
types.put("avi", "video/x-avi");
types.put("flv", "video/x-flv");
types.put("mov", "video/quicktime");
types.put("mp4", "video/mp4");
types.put("mpg", "video/mpeg");
types.put("mpeg", "video/mpeg");
types.put("vob", "video/mpeg");
types.put("wmv", "video/x-ms-wmv");
return types;
}
public static final Parcelable.Creator<TorrentFile> CREATOR = new Parcelable.Creator<TorrentFile>() {
public TorrentFile createFromParcel(Parcel in) {
return new TorrentFile(in);
}
public TorrentFile[] newArray(int size) {
return new TorrentFile[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(key);
dest.writeString(name);
dest.writeString(relativePath);
dest.writeString(fullPath);
dest.writeLong(downloaded);
dest.writeLong(totalSize);
dest.writeInt(priority.getCode());
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* Transdroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Transdroid 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.
*
* You should have received a copy of the GNU General Public License
* along with Transdroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import org.transdroid.daemon.Deluge.DelugeAdapter;
import org.transdroid.daemon.DLinkRouterBT.DLinkRouterBTAdapter;
import org.transdroid.daemon.Ktorrent.KtorrentAdapter;
import org.transdroid.daemon.Qbittorrent.QbittorrentAdapter;
import org.transdroid.daemon.Rtorrent.RtorrentAdapter;
import org.transdroid.daemon.Synology.SynologyAdapter;
import org.transdroid.daemon.Tfb4rt.Tfb4rtAdapter;
import org.transdroid.daemon.Transmission.TransmissionAdapter;
import org.transdroid.daemon.Utorrent.UtorrentAdapter;
import org.transdroid.daemon.Vuze.VuzeAdapter;
import org.transdroid.daemon.Bitflu.BitfluAdapter;
import org.transdroid.daemon.BuffaloNas.BuffaloNasAdapter;
import org.transdroid.daemon.BitComet.BitCometAdapter;
/**
* Factory for new instances of server daemons, based on user settings.
*
* @author erickok
*
*/
public enum Daemon {
Bitflu {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new BitfluAdapter(settings);
}
},
BitTorrent {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new UtorrentAdapter(settings);
}
},
BuffaloNas {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new BuffaloNasAdapter(settings);
}
},
Deluge {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new DelugeAdapter(settings);
}
},
DLinkRouterBT {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new DLinkRouterBTAdapter(settings);
}
},
KTorrent {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new KtorrentAdapter(settings);
}
},
qBittorrent {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new QbittorrentAdapter(settings);
}
},
rTorrent {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new RtorrentAdapter(settings);
}
},
Tfb4rt {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new Tfb4rtAdapter(settings);
}
},
Synology {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new SynologyAdapter(settings);
}
},
Transmission {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new TransmissionAdapter(settings);
}
},
uTorrent {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new UtorrentAdapter(settings);
}
},
Vuze {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new VuzeAdapter(settings);
}
},
BitComet {
public IDaemonAdapter createAdapter(DaemonSettings settings) {
return new BitCometAdapter(settings);
}
};
public abstract IDaemonAdapter createAdapter(DaemonSettings settings);
/**
* Returns the daemon enum type based on the code used in the user preferences.
* @param daemonCode The 'daemon_<name>' type code
* @return The corresponding daemon enum value, or null if it was an empty or invalid code
*/
public static Daemon fromCode(String daemonCode) {
if (daemonCode == null) {
return null;
}
if (daemonCode.equals("daemon_bitflu")) {
return Bitflu;
}
if (daemonCode.equals("daemon_bittorrent")) {
return BitTorrent;
}
if (daemonCode.equals("daemon_buffalonas")) {
return BuffaloNas;
}
if (daemonCode.equals("daemon_deluge")) {
return Deluge;
}
if (daemonCode.equals("daemon_dlinkrouterbt")) {
return DLinkRouterBT;
}
if (daemonCode.equals("daemon_ktorrent")) {
return KTorrent;
}
if (daemonCode.equals("daemon_qbittorrent")) {
return qBittorrent;
}
if (daemonCode.equals("daemon_rtorrent")) {
return rTorrent;
}
if (daemonCode.equals("daemon_tfb4rt")) {
return Tfb4rt;
}
if (daemonCode.equals("daemon_transmission")) {
return Transmission;
}
if (daemonCode.equals("daemon_synology")) {
return Synology;
}
if (daemonCode.equals("daemon_utorrent")) {
return uTorrent;
}
if (daemonCode.equals("daemon_vuze")) {
return Vuze;
}
if (daemonCode.equals("daemon_bitcomet")) {
return BitComet;
}
return null;
}
public static int getDefaultPortNumber(Daemon type, boolean ssl) {
if (type == null) {
return 8080; // Only happens when the daemon type isn't even set yet
}
switch (type) {
case BitTorrent:
case uTorrent:
case KTorrent:
case qBittorrent:
case BuffaloNas:
return 8080;
case DLinkRouterBT:
case rTorrent:
case Tfb4rt:
case BitComet:
if (ssl) {
return 443;
} else {
return 80;
}
case Deluge:
return 8112;
case Synology:
return 5000;
case Transmission:
return 9091;
case Bitflu:
return 4081;
case Vuze:
return 6884;
}
return 8080;
}
public static boolean supportsStats(Daemon type) {
return type == Transmission || type == Bitflu;
}
public static boolean supportsAvailability(Daemon type) {
return type == uTorrent || type == BitTorrent || type == DLinkRouterBT || type == Transmission || type == Vuze || type == BuffaloNas;
}
public static boolean supportsFileListing(Daemon type) {
return type == Synology || type == Transmission || type == uTorrent || type == BitTorrent || type == KTorrent || type == Deluge || type == rTorrent || type == Vuze || type == DLinkRouterBT || type == Bitflu || type == qBittorrent || type == BuffaloNas || type == BitComet;
}
public static boolean supportsFineDetails(Daemon type) {
return type == uTorrent || type == BitTorrent || type == Daemon.Transmission || type == Deluge || type == rTorrent || type == qBittorrent;
}
public static boolean needsManualPathSpecified(Daemon type) {
return type == uTorrent || type == BitTorrent || type == KTorrent || type == BuffaloNas;
}
public static boolean supportsFilePaths(Daemon type) {
return type == uTorrent || type == BitTorrent || type == Vuze || type == Deluge || type == Transmission || type == rTorrent || type == KTorrent || type == BuffaloNas;
}
public static boolean supportsStoppingStarting(Daemon type) {
return type == uTorrent || type == rTorrent || type == BitTorrent || type == BitComet;
}
public static boolean supportsForcedStarting(Daemon type) {
return type == uTorrent || type == BitTorrent;
}
public static boolean supportsCustomFolder(Daemon type) {
return type == rTorrent || type == Tfb4rt || type == Bitflu || type == Deluge || type == Transmission;
}
public static boolean supportsSetTransferRates(Daemon type) {
return type == Deluge || type == Transmission || type == uTorrent || type == BitTorrent || type == Deluge || type == rTorrent || type == Vuze || type == BuffaloNas || type == BitComet;
}
public static boolean supportsAddByFile(Daemon type) {
// Supported by every client except Bitflu
return type != Bitflu;
}
public static boolean supportsAddByMagnetUrl(Daemon type) {
return type == uTorrent || type == BitTorrent || type == Transmission || type == Synology || type == Deluge || type == Bitflu || type == KTorrent || type == rTorrent || type == qBittorrent || type == BitComet;
}
public static boolean supportsRemoveWithData(Daemon type) {
return type == uTorrent || type == Vuze || type == Transmission || type == Deluge || type == BitTorrent || type == Tfb4rt || type == DLinkRouterBT || type == Bitflu || type == qBittorrent || type == BuffaloNas || type == BitComet || type == rTorrent;
}
public static boolean supportsFilePrioritySetting(Daemon type) {
return type == BitTorrent || type == uTorrent || type == Transmission || type == KTorrent || type == rTorrent || type == Vuze || type == Deluge || type == qBittorrent;
}
public static boolean supportsDateAdded(Daemon type) {
return type == Vuze || type == Transmission || type == rTorrent || type == Bitflu || type == BitComet;
}
public static boolean supportsLabels(Daemon type) {
return type == uTorrent || type == BitTorrent || type == Deluge || type == BitComet || type == rTorrent; // || type == Vuze
}
public static boolean supportsSetLabel(Daemon type) {
return type == uTorrent || type == BitTorrent || type == rTorrent;
}
public static boolean supportsSetDownloadLocation(Daemon type) {
return type == Transmission || type == Deluge;
}
public static boolean supportsSetAlternativeMode(Daemon type) {
return type == Transmission;
}
public static boolean supportsSetTrackers(Daemon type) {
return type == uTorrent || type == BitTorrent || type == Deluge;
}
public static boolean supportsExtraPassword(Daemon type) {
return type == Deluge;
}
public static boolean supportsUsernameForHttp(Daemon type) {
return type == Deluge;
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.openjpa.lib.util;
/**
* Base 16 encoder.
*
* @author Marc Prud'hommeaux
* @nojavadoc
*/
public class Base16Encoder {
private final static char[] HEX = new char[]{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* Convert bytes to a base16 string.
*/
public static String encode(byte[] byteArray) {
StringBuffer hexBuffer = new StringBuffer(byteArray.length * 2);
for (int i = 0; i < byteArray.length; i++)
for (int j = 1; j >= 0; j--)
hexBuffer.append(HEX[(byteArray[i] >> (j * 4)) & 0xF]);
return hexBuffer.toString();
}
/**
* Convert a base16 string into a byte array.
*/
public static byte[] decode(String s) {
int len = s.length();
byte[] r = new byte[len / 2];
for (int i = 0; i < r.length; i++) {
int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1);
if (digit1 >= '0' && digit1 <= '9')
digit1 -= '0';
else if (digit1 >= 'A' && digit1 <= 'F')
digit1 -= 'A' - 10;
if (digit2 >= '0' && digit2 <= '9')
digit2 -= '0';
else if (digit2 >= 'A' && digit2 <= 'F')
digit2 -= 'A' - 10;
r[i] = (byte) ((digit1 << 4) + digit2);
}
return r;
}
}
| Java |
package org.base64.android;
/**
* <p>Encodes and decodes to and from Base64 notation. Released as Public Domain software.</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.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 (~< 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.3
*/
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;
/** 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 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <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 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <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 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <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.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
// Note that the optional GZIPping is handled by Base64.OutputStream.
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
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{ 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 ){
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 ){
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 sbiCrop = 0; // Low seven bits (ASCII) of input
byte sbiDecode = 0; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ]; // Special value
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN ) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException( String.format(
"Bad Base64 input character '%c' in array position %d", source[i], i ) );
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode( String s ) throws java.io.IOException {
return decode( s, NO_OPTIONS );
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if <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)
if( bytes != null && bytes.length >= 4 ) {
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 ) {
// 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 {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
ois = new java.io.ObjectInputStream( bais );
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),40) ]; // Need max() for math on small files (v2.2.1)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Reads <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 ) {
super.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to encode.
out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
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 ) {
super.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 the stream (and the enclosing streams).
* @throws java.io.IOException
* @since 2.3
*/
@Override
public void flush() throws java.io.IOException {
flushBase64();
super.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
flush();
// 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
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/Part.java,v 1.16 2005/01/14 21:16:40 olegk Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.util.EncodingUtils;
/**
* Abstract class for one Part of a multipart post object.
*
* @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
* @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
* @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
*
* @since 2.0
*/
public abstract class Part {
/**
* The boundary
* @deprecated use {@link org.apache.http.client.methods.multipart#MULTIPART_BOUNDARY}
*/
protected static final String BOUNDARY = "----------------314159265358979323846";
/**
* The boundary as a byte array.
* @deprecated
*/
protected static final byte[] BOUNDARY_BYTES = EncodingUtils.getAsciiBytes(BOUNDARY);
/**
* The default boundary to be used if {@link #setPartBoundary(byte[])} has not
* been called.
*/
private static final byte[] DEFAULT_BOUNDARY_BYTES = BOUNDARY_BYTES;
/** Carriage return/linefeed */
protected static final String CRLF = "\r\n";
/** Carriage return/linefeed as a byte array */
protected static final byte[] CRLF_BYTES = EncodingUtils.getAsciiBytes(CRLF);
/** Content dispostion characters */
protected static final String QUOTE = "\"";
/** Content dispostion as a byte array */
protected static final byte[] QUOTE_BYTES =
EncodingUtils.getAsciiBytes(QUOTE);
/** Extra characters */
protected static final String EXTRA = "--";
/** Extra characters as a byte array */
protected static final byte[] EXTRA_BYTES =
EncodingUtils.getAsciiBytes(EXTRA);
/** Content dispostion characters */
protected static final String CONTENT_DISPOSITION = "Content-Disposition: form-data; name=";
/** Content dispostion as a byte array */
protected static final byte[] CONTENT_DISPOSITION_BYTES =
EncodingUtils.getAsciiBytes(CONTENT_DISPOSITION);
/** Content type header */
protected static final String CONTENT_TYPE = "Content-Type: ";
/** Content type header as a byte array */
protected static final byte[] CONTENT_TYPE_BYTES =
EncodingUtils.getAsciiBytes(CONTENT_TYPE);
/** Content charset */
protected static final String CHARSET = "; charset=";
/** Content charset as a byte array */
protected static final byte[] CHARSET_BYTES =
EncodingUtils.getAsciiBytes(CHARSET);
/** Content type header */
protected static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: ";
/** Content type header as a byte array */
protected static final byte[] CONTENT_TRANSFER_ENCODING_BYTES =
EncodingUtils.getAsciiBytes(CONTENT_TRANSFER_ENCODING);
/**
* Return the boundary string.
* @return the boundary string
* @deprecated uses a constant string. Rather use {@link #getPartBoundary}
*/
public static String getBoundary() {
return BOUNDARY;
}
/**
* The ASCII bytes to use as the multipart boundary.
*/
private byte[] boundaryBytes;
/**
* Return the name of this part.
* @return The name.
*/
public abstract String getName();
/**
* Returns the content type of this part.
* @return the content type, or <code>null</code> to exclude the content type header
*/
public abstract String getContentType();
/**
* Return the character encoding of this part.
* @return the character encoding, or <code>null</code> to exclude the character
* encoding header
*/
public abstract String getCharSet();
/**
* Return the transfer encoding of this part.
* @return the transfer encoding, or <code>null</code> to exclude the transfer encoding header
*/
public abstract String getTransferEncoding();
/**
* Gets the part boundary to be used.
* @return the part boundary as an array of bytes.
*
* @since 3.0
*/
protected byte[] getPartBoundary() {
if (boundaryBytes == null) {
// custom boundary bytes have not been set, use the default.
return DEFAULT_BOUNDARY_BYTES;
} else {
return boundaryBytes;
}
}
/**
* Sets the part boundary. Only meant to be used by
* {@link Part#sendParts(OutputStream, Part[], byte[])}
* and {@link Part#getLengthOfParts(Part[], byte[])}
* @param boundaryBytes An array of ASCII bytes.
* @since 3.0
*/
void setPartBoundary(byte[] boundaryBytes) {
this.boundaryBytes = boundaryBytes;
}
/**
* Tests if this part can be sent more than once.
* @return <code>true</code> if {@link #sendData(OutputStream)} can be successfully called
* more than once.
* @since 3.0
*/
public boolean isRepeatable() {
return true;
}
/**
* Write the start to the specified output stream
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected void sendStart(OutputStream out) throws IOException {
out.write(EXTRA_BYTES);
out.write(getPartBoundary());
out.write(CRLF_BYTES);
}
/**
* Write the content disposition header to the specified output stream
*
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected void sendDispositionHeader(OutputStream out) throws IOException {
out.write(CONTENT_DISPOSITION_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtils.getAsciiBytes(getName()));
out.write(QUOTE_BYTES);
}
/**
* Write the content type header to the specified output stream
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected void sendContentTypeHeader(OutputStream out) throws IOException {
String contentType = getContentType();
if (contentType != null) {
out.write(CRLF_BYTES);
out.write(CONTENT_TYPE_BYTES);
out.write(EncodingUtils.getAsciiBytes(contentType));
String charSet = getCharSet();
if (charSet != null) {
out.write(CHARSET_BYTES);
out.write(EncodingUtils.getAsciiBytes(charSet));
}
}
}
/**
* Write the content transfer encoding header to the specified
* output stream
*
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
String transferEncoding = getTransferEncoding();
if (transferEncoding != null) {
out.write(CRLF_BYTES);
out.write(CONTENT_TRANSFER_ENCODING_BYTES);
out.write(EncodingUtils.getAsciiBytes(transferEncoding));
}
}
/**
* Write the end of the header to the output stream
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected void sendEndOfHeader(OutputStream out) throws IOException {
out.write(CRLF_BYTES);
out.write(CRLF_BYTES);
}
/**
* Write the data to the specified output stream
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected abstract void sendData(OutputStream out) throws IOException;
/**
* Return the length of the main content
*
* @return long The length.
* @throws IOException If an IO problem occurs
*/
protected abstract long lengthOfData() throws IOException;
/**
* Write the end data to the output stream.
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
protected void sendEnd(OutputStream out) throws IOException {
out.write(CRLF_BYTES);
}
/**
* Write all the data to the output stream.
* If you override this method make sure to override
* #length() as well
*
* @param out The output stream
* @throws IOException If an IO problem occurs.
*/
public void send(OutputStream out) throws IOException {
sendStart(out);
sendDispositionHeader(out);
sendContentTypeHeader(out);
sendTransferEncodingHeader(out);
sendEndOfHeader(out);
sendData(out);
sendEnd(out);
}
/**
* Return the full length of all the data.
* If you override this method make sure to override
* #send(OutputStream) as well
*
* @return long The length.
* @throws IOException If an IO problem occurs
*/
public long length() throws IOException {
if (lengthOfData() < 0) {
return -1;
}
ByteArrayOutputStream overhead = new ByteArrayOutputStream();
sendStart(overhead);
sendDispositionHeader(overhead);
sendContentTypeHeader(overhead);
sendTransferEncodingHeader(overhead);
sendEndOfHeader(overhead);
sendEnd(overhead);
return overhead.size() + lengthOfData();
}
/**
* Return a string representation of this object.
* @return A string representation of this object.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.getName();
}
/**
* Write all parts and the last boundary to the specified output stream.
*
* @param out The stream to write to.
* @param parts The parts to write.
*
* @throws IOException If an I/O error occurs while writing the parts.
*/
public static void sendParts(OutputStream out, final Part[] parts)
throws IOException {
sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
}
/**
* Write all parts and the last boundary to the specified output stream.
*
* @param out The stream to write to.
* @param parts The parts to write.
* @param partBoundary The ASCII bytes to use as the part boundary.
*
* @throws IOException If an I/O error occurs while writing the parts.
*
* @since 3.0
*/
public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
throws IOException {
if (parts == null) {
throw new IllegalArgumentException("Parts may not be null");
}
if (partBoundary == null || partBoundary.length == 0) {
throw new IllegalArgumentException("partBoundary may not be empty");
}
for (int i = 0; i < parts.length; i++) {
// set the part boundary before the part is sent
parts[i].setPartBoundary(partBoundary);
parts[i].send(out);
}
out.write(EXTRA_BYTES);
out.write(partBoundary);
out.write(EXTRA_BYTES);
out.write(CRLF_BYTES);
}
/**
* Return the total sum of all parts and that of the last boundary
*
* @param parts The parts.
* @return The total length
*
* @throws IOException If an I/O error occurs while writing the parts.
*/
public static long getLengthOfParts(Part[] parts)
throws IOException {
return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
}
/**
* Gets the length of the multipart message including the given parts.
*
* @param parts The parts.
* @param partBoundary The ASCII bytes to use as the part boundary.
* @return The total length
*
* @throws IOException If an I/O error occurs while writing the parts.
*
* @since 3.0
*/
public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
if (parts == null) {
throw new IllegalArgumentException("Parts may not be null");
}
long total = 0;
for (int i = 0; i < parts.length; i++) {
// set the part boundary before we calculate the part's length
parts[i].setPartBoundary(partBoundary);
long l = parts[i].length();
if (l < 0) {
return -1;
}
total += l;
}
total += EXTRA_BYTES.length;
total += partBoundary.length;
total += EXTRA_BYTES.length;
total += CRLF_BYTES.length;
return total;
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePart.java,v 1.19 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.util.EncodingUtils;
/**
* This class implements a part of a Multipart post object that
* consists of a file.
*
* @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
* @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
* @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
* @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
* @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
*
* @since 2.0
*
*/
public class FilePart extends PartBase {
/** Default content encoding of file attachments. */
public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
/** Default charset of file attachments. */
public static final String DEFAULT_CHARSET = "ISO-8859-1";
/** Default transfer encoding of file attachments. */
public static final String DEFAULT_TRANSFER_ENCODING = "binary";
/** Attachment's file name */
protected static final String FILE_NAME = "; filename=";
/** Attachment's file name as a byte array */
private static final byte[] FILE_NAME_BYTES =
EncodingUtils.getAsciiBytes(FILE_NAME);
/** Source of the file part. */
private PartSource source;
/**
* FilePart Constructor.
*
* @param name the name for this part
* @param partSource the source for this part
* @param contentType the content type for this part, if <code>null</code> the
* {@link #DEFAULT_CONTENT_TYPE default} is used
* @param charset the charset encoding for this part, if <code>null</code> the
* {@link #DEFAULT_CHARSET default} is used
*/
public FilePart(String name, PartSource partSource, String contentType, String charset) {
super(
name,
contentType == null ? DEFAULT_CONTENT_TYPE : contentType,
charset == null ? "ISO-8859-1" : charset,
DEFAULT_TRANSFER_ENCODING
);
if (partSource == null) {
throw new IllegalArgumentException("Source may not be null");
}
this.source = partSource;
}
/**
* FilePart Constructor.
*
* @param name the name for this part
* @param partSource the source for this part
*/
public FilePart(String name, PartSource partSource) {
this(name, partSource, null, null);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param file the file to post
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public FilePart(String name, File file)
throws FileNotFoundException {
this(name, new FilePartSource(file), null, null);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param file the file to post
* @param contentType the content type for this part, if <code>null</code> the
* {@link #DEFAULT_CONTENT_TYPE default} is used
* @param charset the charset encoding for this part, if <code>null</code> the
* {@link #DEFAULT_CHARSET default} is used
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public FilePart(String name, File file, String contentType, String charset)
throws FileNotFoundException {
this(name, new FilePartSource(file), contentType, charset);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param fileName the file name
* @param file the file to post
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public FilePart(String name, String fileName, File file)
throws FileNotFoundException {
this(name, new FilePartSource(fileName, file), null, null);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param fileName the file name
* @param file the file to post
* @param contentType the content type for this part, if <code>null</code> the
* {@link #DEFAULT_CONTENT_TYPE default} is used
* @param charset the charset encoding for this part, if <code>null</code> the
* {@link #DEFAULT_CHARSET default} is used
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public FilePart(String name, String fileName, File file, String contentType, String charset)
throws FileNotFoundException {
this(name, new FilePartSource(fileName, file), contentType, charset);
}
/**
* Write the disposition header to the output stream
* @param out The output stream
* @throws IOException If an IO problem occurs
* @see Part#sendDispositionHeader(OutputStream)
*/
@Override
protected void sendDispositionHeader(OutputStream out)
throws IOException {
super.sendDispositionHeader(out);
String filename = this.source.getFileName();
if (filename != null) {
out.write(FILE_NAME_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtils.getAsciiBytes(filename));
out.write(QUOTE_BYTES);
}
}
/**
* Write the data in "source" to the specified stream.
* @param out The output stream.
* @throws IOException if an IO problem occurs.
* @see Part#sendData(OutputStream)
*/
@Override
protected void sendData(OutputStream out) throws IOException {
if (lengthOfData() == 0) {
// this file contains no data, so there is nothing to send.
// we don't want to create a zero length buffer as this will
// cause an infinite loop when reading.
return;
}
byte[] tmp = new byte[4096];
InputStream instream = source.createInputStream();
try {
int len;
while ((len = instream.read(tmp)) >= 0) {
out.write(tmp, 0, len);
}
} finally {
// we're done with the stream, close it
instream.close();
}
}
/**
* Returns the source of the file part.
*
* @return The source.
*/
protected PartSource getSource() {
return this.source;
}
/**
* Return the length of the data.
* @return The length.
* @see Part#lengthOfData()
*/
@Override
protected long lengthOfData() {
return source.getLength();
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartBase.java,v 1.5 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
/**
* Provides setters and getters for the basic Part properties.
*
* @author Michael Becke
*/
public abstract class PartBase extends Part {
/** Name of the file part. */
private String name;
/** Content type of the file part. */
private String contentType;
/** Content encoding of the file part. */
private String charSet;
/** The transfer encoding. */
private String transferEncoding;
/**
* Constructor.
*
* @param name The name of the part
* @param contentType The content type, or <code>null</code>
* @param charSet The character encoding, or <code>null</code>
* @param transferEncoding The transfer encoding, or <code>null</code>
*/
public PartBase(String name, String contentType, String charSet, String transferEncoding) {
if (name == null) {
throw new IllegalArgumentException("Name must not be null");
}
this.name = name;
this.contentType = contentType;
this.charSet = charSet;
this.transferEncoding = transferEncoding;
}
/**
* Returns the name.
* @return The name.
* @see Part#getName()
*/
@Override
public String getName() {
return this.name;
}
/**
* Returns the content type of this part.
* @return String The name.
*/
@Override
public String getContentType() {
return this.contentType;
}
/**
* Return the character encoding of this part.
* @return String The name.
*/
@Override
public String getCharSet() {
return this.charSet;
}
/**
* Returns the transfer encoding of this part.
* @return String The name.
*/
@Override
public String getTransferEncoding() {
return transferEncoding;
}
/**
* Sets the character encoding.
*
* @param charSet the character encoding, or <code>null</code> to exclude the character
* encoding header
*/
public void setCharSet(String charSet) {
this.charSet = charSet;
}
/**
* Sets the content type.
*
* @param contentType the content type, or <code>null</code> to exclude the content type header
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* Sets the part name.
*
* @param name
*/
public void setName(String name) {
if (name == null) {
throw new IllegalArgumentException("Name must not be null");
}
this.name = name;
}
/**
* Sets the transfer encoding.
*
* @param transferEncoding the transfer encoding, or <code>null</code> to exclude the
* transfer encoding header
*/
public void setTransferEncoding(String transferEncoding) {
this.transferEncoding = transferEncoding;
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePart.java,v 1.19 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.util.EncodingUtils;
/**
* This class implements a part of a Multipart post object that
* consists of a file.
*
* @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
* @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
* @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
* @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
* @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
*
* @since 2.0
*
*/
public class BitCometFilePart extends PartBase {
/** Default content encoding of file attachments. */
public static final String DEFAULT_CONTENT_TYPE = "application/x-bittorrent";
/** Attachment's file name */
protected static final String FILE_NAME = "; filename=";
/** Attachment's file name as a byte array */
private static final byte[] FILE_NAME_BYTES =
EncodingUtils.getAsciiBytes(FILE_NAME);
/** Source of the file part. */
private PartSource source;
/**
* FilePart Constructor.
*
* @param name the name for this part
* @param partSource the source for this part
* @param contentType the content type for this part, if <code>null</code> the
* {@link #DEFAULT_CONTENT_TYPE default} is used
* @param charset the charset encoding for this part, if <code>null</code> the
* {@link #DEFAULT_CHARSET default} is used
*/
public BitCometFilePart(String name, PartSource partSource, String contentType, String charset) {
super(
name,
contentType == null ? DEFAULT_CONTENT_TYPE : contentType,
charset == null ? "ISO-8859-1" : charset,
null
);
if (partSource == null) {
throw new IllegalArgumentException("Source may not be null");
}
this.source = partSource;
}
/**
* FilePart Constructor.
*
* @param name the name for this part
* @param partSource the source for this part
*/
public BitCometFilePart(String name, PartSource partSource) {
this(name, partSource, null, null);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param file the file to post
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public BitCometFilePart(String name, File file)
throws FileNotFoundException {
this(name, new FilePartSource(file), null, null);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param file the file to post
* @param contentType the content type for this part, if <code>null</code> the
* {@link #DEFAULT_CONTENT_TYPE default} is used
* @param charset the charset encoding for this part, if <code>null</code> the
* {@link #DEFAULT_CHARSET default} is used
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public BitCometFilePart(String name, File file, String contentType, String charset)
throws FileNotFoundException {
this(name, new FilePartSource(file), contentType, charset);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param fileName the file name
* @param file the file to post
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public BitCometFilePart(String name, String fileName, File file)
throws FileNotFoundException {
this(name, new FilePartSource(fileName, file), null, null);
}
/**
* FilePart Constructor.
*
* @param name the name of the file part
* @param fileName the file name
* @param file the file to post
* @param contentType the content type for this part, if <code>null</code> the
* {@link #DEFAULT_CONTENT_TYPE default} is used
* @param charset the charset encoding for this part, if <code>null</code> the
* {@link #DEFAULT_CHARSET default} is used
*
* @throws FileNotFoundException if the <i>file</i> is not a normal
* file or if it is not readable.
*/
public BitCometFilePart(String name, String fileName, File file, String contentType, String charset)
throws FileNotFoundException {
this(name, new FilePartSource(fileName, file), contentType, charset);
}
/**
* Write the disposition header to the output stream
* @param out The output stream
* @throws IOException If an IO problem occurs
* @see Part#sendDispositionHeader(OutputStream)
*/
@Override
protected void sendDispositionHeader(OutputStream out)
throws IOException {
super.sendDispositionHeader(out);
String filename = this.source.getFileName();
if (filename != null) {
out.write(FILE_NAME_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtils.getAsciiBytes(filename));
out.write(QUOTE_BYTES);
}
}
/**
* Write the data in "source" to the specified stream.
* @param out The output stream.
* @throws IOException if an IO problem occurs.
* @see Part#sendData(OutputStream)
*/
@Override
protected void sendData(OutputStream out) throws IOException {
if (lengthOfData() == 0) {
// this file contains no data, so there is nothing to send.
// we don't want to create a zero length buffer as this will
// cause an infinite loop when reading.
return;
}
byte[] tmp = new byte[4096];
InputStream instream = source.createInputStream();
try {
int len;
while ((len = instream.read(tmp)) >= 0) {
out.write(tmp, 0, len);
}
} finally {
// we're done with the stream, close it
instream.close();
}
}
/**
* Returns the source of the file part.
*
* @return The source.
*/
protected PartSource getSource() {
return this.source;
}
/**
* Return the length of the data.
* @return The length.
* @see Part#lengthOfData()
*/
@Override
protected long lengthOfData() {
return source.getLength();
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartSource.java,v 1.6 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.IOException;
import java.io.InputStream;
/**
* An interface for providing access to data when posting MultiPart messages.
*
* @see FilePart
*
* @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
*
* @since 2.0
*/
public interface PartSource {
/**
* Gets the number of bytes contained in this source.
*
* @return a value >= 0
*/
long getLength();
/**
* Gets the name of the file this source represents.
*
* @return the fileName used for posting a MultiPart file part
*/
String getFileName();
/**
* Gets a new InputStream for reading this source. This method can be
* called more than once and should therefore return a new stream every
* time.
*
* @return a new InputStream
*
* @throws IOException if an error occurs when creating the InputStream
*/
InputStream createInputStream() throws IOException;
}
| Java |
package com.android.internalcopy.http.multipart;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.util.EncodingUtils;
public class Utf8StringPart extends PartBase {
/** Contents of this StringPart. */
private byte[] content;
/** The String value of this part. */
private String value;
public Utf8StringPart(String name, String value) {
super(name, null, null, null);
this.value = value;
}
/**
* Gets the content in bytes. Bytes are lazily created to allow the charset to be changed
* after the part is created.
*
* @return the content in bytes
*/
private byte[] getContent() {
if (content == null) {
content = EncodingUtils.getBytes(value, "utf-8");
}
return content;
}
@Override
protected void sendData(OutputStream out) throws IOException {
out.write(getContent());
}
@Override
protected long lengthOfData() throws IOException {
return getContent().length;
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/ByteArrayPartSource.java,v 1.7 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* A PartSource that reads from a byte array. This class should be used when
* the data to post is already loaded into memory.
*
* @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
*
* @since 2.0
*/
public class ByteArrayPartSource implements PartSource {
/** Name of the source file. */
private String fileName;
/** Byte array of the source file. */
private byte[] bytes;
/**
* Constructor for ByteArrayPartSource.
*
* @param fileName the name of the file these bytes represent
* @param bytes the content of this part
*/
public ByteArrayPartSource(String fileName, byte[] bytes) {
this.fileName = fileName;
this.bytes = bytes;
}
/**
* @see PartSource#getLength()
*/
public long getLength() {
return bytes.length;
}
/**
* @see PartSource#getFileName()
*/
public String getFileName() {
return fileName;
}
/**
* @see PartSource#createInputStream()
*/
public InputStream createInputStream() {
return new ByteArrayInputStream(bytes);
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.java,v 1.1 2004/10/06 03:39:59 mbecke Exp $
* $Revision: 502647 $
* $Date: 2007-02-02 17:22:54 +0100 (Fri, 02 Feb 2007) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import org.apache.http.Header;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;
/**
* Implements a request entity suitable for an HTTP multipart POST method.
* <p>
* The HTTP multipart POST method is defined in section 3.3 of
* <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
* <blockquote>
* The media-type multipart/form-data follows the rules of all multipart
* MIME data streams as outlined in RFC 1521. The multipart/form-data contains
* a series of parts. Each part is expected to contain a content-disposition
* header where the value is "form-data" and a name attribute specifies
* the field name within the form, e.g., 'content-disposition: form-data;
* name="xxxxx"', where xxxxx is the field name corresponding to that field.
* Field names originally in non-ASCII character sets may be encoded using
* the method outlined in RFC 1522.
* </blockquote>
* </p>
* <p>This entity is designed to be used in conjunction with the
* {@link org.apache.http.HttpRequest} to provide
* multipart posts. Example usage:</p>
* <pre>
* File f = new File("/path/fileToUpload.txt");
* HttpRequest request = new HttpRequest("http://host/some_path");
* Part[] parts = {
* new StringPart("param_name", "value"),
* new FilePart(f.getName(), f)
* };
* filePost.setEntity(
* new MultipartRequestEntity(parts, filePost.getParams())
* );
* HttpClient client = new HttpClient();
* int status = client.executeMethod(filePost);
* </pre>
*
* @since 3.0
*/
public class MultipartEntity extends AbstractHttpEntity {
/** The Content-Type for multipart/form-data. */
private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data";
/**
* Sets the value to use as the multipart boundary.
* <p>
* This parameter expects a value if type {@link String}.
* </p>
*/
public static final String MULTIPART_BOUNDARY = "http.method.multipart.boundary";
/**
* The pool of ASCII chars to be used for generating a multipart boundary.
*/
private static byte[] MULTIPART_CHARS = EncodingUtils.getAsciiBytes(
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
/**
* Generates a random multipart boundary string.
*/
private static byte[] generateMultipartBoundary() {
Random rand = new Random();
byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40
for (int i = 0; i < bytes.length; i++) {
bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
}
return bytes;
}
/** The MIME parts as set by the constructor */
protected Part[] parts;
private byte[] multipartBoundary;
private HttpParams params;
private boolean contentConsumed = false;
/**
* Creates a new multipart entity containing the given parts.
* @param parts The parts to include.
* @param params The params of the HttpMethod using this entity.
*/
public MultipartEntity(Part[] parts, HttpParams params) {
if (parts == null) {
throw new IllegalArgumentException("parts cannot be null");
}
if (params == null) {
throw new IllegalArgumentException("params cannot be null");
}
this.parts = parts;
this.params = params;
}
public MultipartEntity(Part[] parts) {
setContentType(MULTIPART_FORM_CONTENT_TYPE);
if (parts == null) {
throw new IllegalArgumentException("parts cannot be null");
}
this.parts = parts;
this.params = null;
}
/**
* Returns the MIME boundary string that is used to demarcate boundaries of
* this part. The first call to this method will implicitly create a new
* boundary string. To create a boundary string first the
* HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise
* a random one is generated.
*
* @return The boundary string of this entity in ASCII encoding.
*/
protected byte[] getMultipartBoundary() {
if (multipartBoundary == null) {
String temp = null;
if (params != null) {
temp = (String) params.getParameter(MULTIPART_BOUNDARY);
}
if (temp != null) {
multipartBoundary = EncodingUtils.getAsciiBytes(temp);
} else {
multipartBoundary = generateMultipartBoundary();
}
}
return multipartBoundary;
}
/**
* Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
*/
public boolean isRepeatable() {
for (int i = 0; i < parts.length; i++) {
if (!parts[i].isRepeatable()) {
return false;
}
}
return true;
}
/* (non-Javadoc)
*/
public void writeTo(OutputStream out) throws IOException {
Part.sendParts(out, parts, getMultipartBoundary());
}
/* (non-Javadoc)
* @see org.apache.commons.http.AbstractHttpEntity.#getContentType()
*/
@Override
public Header getContentType() {
StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
buffer.append("; boundary=");
buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());
}
/* (non-Javadoc)
*/
public long getContentLength() {
try {
return Part.getLengthOfParts(parts, getMultipartBoundary());
} catch (Exception e) {
return 0;
}
}
public InputStream getContent() throws IOException, IllegalStateException {
if(!isRepeatable() && this.contentConsumed ) {
throw new IllegalStateException("Content has been consumed");
}
this.contentConsumed = true;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Part.sendParts(baos, this.parts, this.multipartBoundary);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return bais;
}
public boolean isStreaming() {
return false;
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePartSource.java,v 1.10 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* A PartSource that reads from a File.
*
* @author <a href="mailto:becke@u.washington.edu">Michael Becke</a>
* @author <a href="mailto:mdiggory@latte.harvard.edu">Mark Diggory</a>
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
*
* @since 2.0
*/
public class FilePartSource implements PartSource {
/** File part file. */
private File file = null;
/** File part file name. */
private String fileName = null;
/**
* Constructor for FilePartSource.
*
* @param file the FilePart source File.
*
* @throws FileNotFoundException if the file does not exist or
* cannot be read
*/
public FilePartSource(File file) throws FileNotFoundException {
this.file = file;
if (file != null) {
if (!file.isFile()) {
throw new FileNotFoundException("File is not a normal file.");
}
if (!file.canRead()) {
throw new FileNotFoundException("File is not readable.");
}
this.fileName = file.getName();
}
}
/**
* Constructor for FilePartSource.
*
* @param fileName the file name of the FilePart
* @param file the source File for the FilePart
*
* @throws FileNotFoundException if the file does not exist or
* cannot be read
*/
public FilePartSource(String fileName, File file)
throws FileNotFoundException {
this(file);
if (fileName != null) {
this.fileName = fileName;
}
}
/**
* Return the length of the file
* @return the length of the file.
* @see PartSource#getLength()
*/
public long getLength() {
if (this.file != null) {
return this.file.length();
} else {
return 0;
}
}
/**
* Return the current filename
* @return the filename.
* @see PartSource#getFileName()
*/
public String getFileName() {
return (fileName == null) ? "noname" : fileName;
}
/**
* Return a new {@link FileInputStream} for the current filename.
* @return the new input stream.
* @throws IOException If an IO problem occurs.
* @see PartSource#createInputStream()
*/
public InputStream createInputStream() throws IOException {
if (this.file != null) {
return new FileInputStream(this.file);
} else {
return new ByteArrayInputStream(new byte[] {});
}
}
}
| Java |
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/StringPart.java,v 1.11 2004/04/18 23:51:37 jsdever Exp $
* $Revision: 480424 $
* $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package com.android.internalcopy.http.multipart;
import java.io.OutputStream;
import java.io.IOException;
import org.apache.http.util.EncodingUtils;
/**
* Simple string parameter for a multipart post
*
* @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
* @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
*
* @since 2.0
*/
public class StringPart extends PartBase {
/** Default content encoding of string parameters. */
public static final String DEFAULT_CONTENT_TYPE = "text/plain";
/** Default charset of string parameters*/
public static final String DEFAULT_CHARSET = "US-ASCII";
/** Default transfer encoding of string parameters*/
public static final String DEFAULT_TRANSFER_ENCODING = "8bit";
/** Contents of this StringPart. */
private byte[] content;
/** The String value of this part. */
private String value;
/**
* Constructor.
*
* @param name The name of the part
* @param value the string to post
* @param charset the charset to be used to encode the string, if <code>null</code>
* the {@link #DEFAULT_CHARSET default} is used
*/
public StringPart(String name, String value, String charset) {
super(
name,
DEFAULT_CONTENT_TYPE,
charset == null ? DEFAULT_CHARSET : charset,
DEFAULT_TRANSFER_ENCODING
);
if (value == null) {
throw new IllegalArgumentException("Value may not be null");
}
if (value.indexOf(0) != -1) {
// See RFC 2048, 2.8. "8bit Data"
throw new IllegalArgumentException("NULs may not be present in string parts");
}
this.value = value;
}
/**
* Constructor.
*
* @param name The name of the part
* @param value the string to post
*/
public StringPart(String name, String value) {
this(name, value, null);
}
/**
* Gets the content in bytes. Bytes are lazily created to allow the charset to be changed
* after the part is created.
*
* @return the content in bytes
*/
private byte[] getContent() {
if (content == null) {
content = EncodingUtils.getBytes(value, getCharSet());
}
return content;
}
/**
* Writes the data to the given OutputStream.
* @param out the OutputStream to write to
* @throws IOException if there is a write error
*/
@Override
protected void sendData(OutputStream out) throws IOException {
out.write(getContent());
}
/**
* Return the length of the data.
* @return The length of the data.
* @see Part#lengthOfData()
*/
@Override
protected long lengthOfData() {
return getContent().length;
}
/* (non-Javadoc)
* @see org.apache.commons.httpclient.methods.multipart.BasePart#setCharSet(java.lang.String)
*/
@Override
public void setCharSet(String charSet) {
super.setCharSet(charSet);
this.content = null;
}
}
| Java |
/*
* Copyright 2013 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 com.google.android.gcm.demo.app;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
String SENDER_ID = "Your-Sender-ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Demo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
Context context;
String regid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
@Override
protected void onResume() {
super.onResume();
// Check device for Play Services APK.
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Stores the registration ID and the app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGcmPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Gets the current registration ID for application on GCM service, if there is one.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
// Send an upstream message.
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGcmPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
| Java |
/*
* Copyright 2013 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 com.google.android.gcm.demo.app;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* This {@code WakefulBroadcastReceiver} takes care of creating and managing a
* partial wake lock for your app. It passes off the work of processing the GCM
* message to an {@code IntentService}, while ensuring that the device does not
* go back to sleep in the transition. The {@code IntentService} calls
* {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to
* release the wake lock.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| Java |
/*
* Copyright (C) 2013 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 com.google.android.gcm.demo.app;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {@code IntentService} does the actual handling of the GCM message.
* {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {@code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.server;
import java.io.IOException;
/**
* Exception thrown when GCM returned an error due to an invalid request.
* <p>
* This is equivalent to GCM posts that return an HTTP error different of 200.
*/
public final class InvalidRequestException extends IOException {
private final int status;
private final String description;
public InvalidRequestException(int status) {
this(status, null);
}
public InvalidRequestException(int status, String description) {
super(getMessage(status, description));
this.status = status;
this.description = description;
}
private static String getMessage(int status, String description) {
StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status);
if (description != null) {
base.append("(").append(description).append(")");
}
return base.toString();
}
/**
* Gets the HTTP Status Code.
*/
public int getHttpStatusCode() {
return status;
}
/**
* Gets the error description.
*/
public String getDescription() {
return description;
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.server;
import java.io.Serializable;
/**
* Result of a GCM message request that returned HTTP status code 200.
*
* <p>
* If the message is successfully created, the {@link #getMessageId()} returns
* the message id and {@link #getErrorCodeName()} returns {@literal null};
* otherwise, {@link #getMessageId()} returns {@literal null} and
* {@link #getErrorCodeName()} returns the code of the error.
*
* <p>
* There are cases when a request is accept and the message successfully
* created, but GCM has a canonical registration id for that device. In this
* case, the server should update the registration id to avoid rejected requests
* in the future.
*
* <p>
* In a nutshell, the workflow to handle a result is:
* <pre>
* - Call {@link #getMessageId()}:
* - {@literal null} means error, call {@link #getErrorCodeName()}
* - non-{@literal null} means the message was created:
* - Call {@link #getCanonicalRegistrationId()}
* - if it returns {@literal null}, do nothing.
* - otherwise, update the server datastore with the new id.
* </pre>
*/
public final class Result implements Serializable {
private final String messageId;
private final String canonicalRegistrationId;
private final String errorCode;
public static final class Builder {
// optional parameters
private String messageId;
private String canonicalRegistrationId;
private String errorCode;
public Builder canonicalRegistrationId(String value) {
canonicalRegistrationId = value;
return this;
}
public Builder messageId(String value) {
messageId = value;
return this;
}
public Builder errorCode(String value) {
errorCode = value;
return this;
}
public Result build() {
return new Result(this);
}
}
private Result(Builder builder) {
canonicalRegistrationId = builder.canonicalRegistrationId;
messageId = builder.messageId;
errorCode = builder.errorCode;
}
/**
* Gets the message id, if any.
*/
public String getMessageId() {
return messageId;
}
/**
* Gets the canonical registration id, if any.
*/
public String getCanonicalRegistrationId() {
return canonicalRegistrationId;
}
/**
* Gets the error code, if any.
*/
public String getErrorCodeName() {
return errorCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (messageId != null) {
builder.append(" messageId=").append(messageId);
}
if (canonicalRegistrationId != null) {
builder.append(" canonicalRegistrationId=")
.append(canonicalRegistrationId);
}
if (errorCode != null) {
builder.append(" errorCode=").append(errorCode);
}
return builder.append(" ]").toString();
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.server;
import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS;
import static com.google.android.gcm.server.Constants.JSON_ERROR;
import static com.google.android.gcm.server.Constants.JSON_FAILURE;
import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID;
import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID;
import static com.google.android.gcm.server.Constants.JSON_PAYLOAD;
import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS;
import static com.google.android.gcm.server.Constants.JSON_RESULTS;
import static com.google.android.gcm.server.Constants.JSON_SUCCESS;
import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY;
import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE;
import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN;
import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX;
import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID;
import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME;
import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE;
import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID;
import static com.google.android.gcm.server.Constants.TOKEN_ERROR;
import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID;
import com.google.android.gcm.server.Result.Builder;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper class to send messages to the GCM service using an API Key.
*/
public class Sender {
protected static final String UTF8 = "UTF-8";
/**
* Initial delay before first retry, without jitter.
*/
protected static final int BACKOFF_INITIAL_DELAY = 1000;
/**
* Maximum delay before a retry.
*/
protected static final int MAX_BACKOFF_DELAY = 1024000;
protected final Random random = new Random();
protected static final Logger logger =
Logger.getLogger(Sender.class.getName());
private final String key;
/**
* Default constructor.
*
* @param key API key obtained through the Google API Console.
*/
public Sender(String key) {
this.key = nonNull(key);
}
/**
* Sends a message to one device, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent, including the device's registration id.
* @param registrationId device where the message will be sent.
* @param retries number of retries in case of service unavailability errors.
*
* @return result of the request (see its javadoc for more details).
*
* @throws IllegalArgumentException if registrationId is {@literal null}.
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IOException if message could not be sent.
*/
public Result send(Message message, String registrationId, int retries)
throws IOException {
int attempt = 0;
Result result = null;
int backoff = BACKOFF_INITIAL_DELAY;
boolean tryAgain;
do {
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + registrationId);
}
result = sendNoRetry(message, registrationId);
tryAgain = result == null && attempt <= retries;
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (result == null) {
throw new IOException("Could not send message after " + attempt +
" attempts");
}
return result;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, String, int)} for more info.
*
* @return result of the post, or {@literal null} if the GCM service was
* unavailable or any network exception caused the request to fail.
*
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IllegalArgumentException if registrationId is {@literal null}.
*/
public Result sendNoRetry(Message message, String registrationId)
throws IOException {
StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
Boolean delayWhileIdle = message.isDelayWhileIdle();
if (delayWhileIdle != null) {
addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
}
Boolean dryRun = message.isDryRun();
if (dryRun != null) {
addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
}
String collapseKey = message.getCollapseKey();
if (collapseKey != null) {
addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
}
String restrictedPackageName = message.getRestrictedPackageName();
if (restrictedPackageName != null) {
addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
}
Integer timeToLive = message.getTimeToLive();
if (timeToLive != null) {
addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
}
for (Entry<String, String> entry : message.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
logger.warning("Ignoring payload entry thas has null: " + entry);
} else {
key = PARAM_PAYLOAD_PREFIX + key;
addParameter(body, key, URLEncoder.encode(value, UTF8));
}
}
String requestBody = body.toString();
logger.finest("Request body: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
if (status / 100 == 5) {
logger.fine("GCM service is unavailable (status " + status + ")");
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("Plain post error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
} else {
try {
responseBody = getAndClose(conn.getInputStream());
} catch (IOException e) {
logger.log(Level.WARNING, "Exception reading response: ", e);
// return null so it can retry
return null;
}
}
String[] lines = responseBody.split("\n");
if (lines.length == 0 || lines[0].equals("")) {
throw new IOException("Received empty response from GCM service.");
}
String firstLine = lines[0];
String[] responseParts = split(firstLine);
String token = responseParts[0];
String value = responseParts[1];
if (token.equals(TOKEN_MESSAGE_ID)) {
Builder builder = new Result.Builder().messageId(value);
// check for canonical registration id
if (lines.length > 1) {
String secondLine = lines[1];
responseParts = split(secondLine);
token = responseParts[0];
value = responseParts[1];
if (token.equals(TOKEN_CANONICAL_REG_ID)) {
builder.canonicalRegistrationId(value);
} else {
logger.warning("Invalid response from GCM: " + responseBody);
}
}
Result result = builder.build();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Message created succesfully (" + result + ")");
}
return result;
} else if (token.equals(TOKEN_ERROR)) {
return new Result.Builder().errorCode(value).build();
} else {
throw new IOException("Invalid response from GCM: " + responseBody);
}
}
/**
* Sends a message to many devices, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent.
* @param regIds registration id of the devices that will receive
* the message.
* @param retries number of retries in case of service unavailability errors.
*
* @return combined result of all requests made.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
* @throws IOException if message could not be sent.
*/
public MulticastResult send(Message message, List<String> regIds, int retries)
throws IOException {
int attempt = 0;
MulticastResult multicastResult;
int backoff = BACKOFF_INITIAL_DELAY;
// Map of results by registration id, it will be updated after each attempt
// to send the messages
Map<String, Result> results = new HashMap<String, Result>();
List<String> unsentRegIds = new ArrayList<String>(regIds);
boolean tryAgain;
List<Long> multicastIds = new ArrayList<Long>();
do {
multicastResult = null;
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + unsentRegIds);
}
try {
multicastResult = sendNoRetry(message, unsentRegIds);
} catch(IOException e) {
// no need for WARNING since exception might be already logged
logger.log(Level.FINEST, "IOException on attempt " + attempt, e);
}
if (multicastResult != null) {
long multicastId = multicastResult.getMulticastId();
logger.fine("multicast_id on attempt # " + attempt + ": " +
multicastId);
multicastIds.add(multicastId);
unsentRegIds = updateStatus(unsentRegIds, results, multicastResult);
tryAgain = !unsentRegIds.isEmpty() && attempt <= retries;
} else {
tryAgain = attempt <= retries;
}
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (multicastIds.isEmpty()) {
// all JSON posts failed due to GCM unavailability
throw new IOException("Could not post JSON requests to GCM after "
+ attempt + " attempts");
}
// calculate summary
int success = 0, failure = 0 , canonicalIds = 0;
for (Result result : results.values()) {
if (result.getMessageId() != null) {
success++;
if (result.getCanonicalRegistrationId() != null) {
canonicalIds++;
}
} else {
failure++;
}
}
// build a new object with the overall result
long multicastId = multicastIds.remove(0);
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId).retryMulticastIds(multicastIds);
// add results, in the same order as the input
for (String regId : regIds) {
Result result = results.get(regId);
builder.addResult(result);
}
return builder.build();
}
/**
* Updates the status of the messages sent to devices and the list of devices
* that should be retried.
*
* @param unsentRegIds list of devices that are still pending an update.
* @param allResults map of status that will be updated.
* @param multicastResult result of the last multicast sent.
*
* @return updated version of devices that should be retried.
*/
private List<String> updateStatus(List<String> unsentRegIds,
Map<String, Result> allResults, MulticastResult multicastResult) {
List<Result> results = multicastResult.getResults();
if (results.size() != unsentRegIds.size()) {
// should never happen, unless there is a flaw in the algorithm
throw new RuntimeException("Internal error: sizes do not match. " +
"currentResults: " + results + "; unsentRegIds: " + unsentRegIds);
}
List<String> newUnsentRegIds = new ArrayList<String>();
for (int i = 0; i < unsentRegIds.size(); i++) {
String regId = unsentRegIds.get(i);
Result result = results.get(i);
allResults.put(regId, result);
String error = result.getErrorCodeName();
if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE)
|| error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) {
newUnsentRegIds.add(regId);
}
}
return newUnsentRegIds;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, List, int)} for more info.
*
* @return multicast results if the message was sent successfully,
* {@literal null} if it failed but could be retried.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 status.
* @throws IOException if there was a JSON parsing error
*/
public MulticastResult sendNoRetry(Message message,
List<String> registrationIds) throws IOException {
if (nonNull(registrationIds).isEmpty()) {
throw new IllegalArgumentException("registrationIds cannot be empty");
}
Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE,
message.isDelayWhileIdle());
setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
Map<String, String> payload = message.getData();
if (!payload.isEmpty()) {
jsonRequest.put(JSON_PAYLOAD, payload);
}
String requestBody = JSONValue.toJSONString(jsonRequest);
logger.finest("JSON request: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("JSON error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
}
try {
responseBody = getAndClose(conn.getInputStream());
} catch(IOException e) {
logger.log(Level.WARNING, "IOException reading response", e);
return null;
}
logger.finest("JSON response: " + responseBody);
JSONParser parser = new JSONParser();
JSONObject jsonResponse;
try {
jsonResponse = (JSONObject) parser.parse(responseBody);
int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId);
@SuppressWarnings("unchecked")
List<Map<String, Object>> results =
(List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
if (results != null) {
for (Map<String, Object> jsonResult : results) {
String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
String canonicalRegId =
(String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
String error = (String) jsonResult.get(JSON_ERROR);
Result result = new Result.Builder()
.messageId(messageId)
.canonicalRegistrationId(canonicalRegId)
.errorCode(error)
.build();
builder.addResult(result);
}
}
MulticastResult multicastResult = builder.build();
return multicastResult;
} catch (ParseException e) {
throw newIoException(responseBody, e);
} catch (CustomParserException e) {
throw newIoException(responseBody, e);
}
}
private IOException newIoException(String responseBody, Exception e) {
// log exception, as IOException constructor that takes a message and cause
// is only available on Java 6
String msg = "Error parsing JSON response (" + responseBody + ")";
logger.log(Level.WARNING, msg, e);
return new IOException(msg + ":" + e);
}
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore error
logger.log(Level.FINEST, "IOException closing stream", e);
}
}
}
/**
* Sets a JSON field, but only if the value is not {@literal null}.
*/
private void setJsonField(Map<Object, Object> json, String field,
Object value) {
if (value != null) {
json.put(field, value);
}
}
private Number getNumber(Map<?, ?> json, String field) {
Object value = json.get(field);
if (value == null) {
throw new CustomParserException("Missing field: " + field);
}
if (!(value instanceof Number)) {
throw new CustomParserException("Field " + field +
" does not contain a number: " + value);
}
return (Number) value;
}
class CustomParserException extends RuntimeException {
CustomParserException(String message) {
super(message);
}
}
private String[] split(String line) throws IOException {
String[] split = line.split("=", 2);
if (split.length != 2) {
throw new IOException("Received invalid response line from GCM: " + line);
}
return split;
}
/**
* Make an HTTP post to a given URL.
*
* @return HTTP response.
*/
protected HttpURLConnection post(String url, String body)
throws IOException {
return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body);
}
/**
* Makes an HTTP POST request to a given endpoint.
*
* <p>
* <strong>Note: </strong> the returned connected should not be disconnected,
* otherwise it would kill persistent connections made using Keep-Alive.
*
* @param url endpoint to post the request.
* @param contentType type of request.
* @param body body of the request.
*
* @return the underlying connection.
*
* @throws IOException propagated from underlying methods.
*/
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
if (url == null || body == null) {
throw new IllegalArgumentException("arguments cannot be null");
}
if (!url.startsWith("https://")) {
logger.warning("URL does not use https: " + url);
}
logger.fine("Sending POST to " + url);
logger.finest("POST body: " + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
try {
out.write(bytes);
} finally {
close(out);
}
return conn;
}
/**
* Creates a map with just one key-value pair.
*/
protected static final Map<String, String> newKeyValues(String key,
String value) {
Map<String, String> keyValues = new HashMap<String, String>(1);
keyValues.put(nonNull(key), nonNull(value));
return keyValues;
}
/**
* Creates a {@link StringBuilder} to be used as the body of an HTTP POST.
*
* @param name initial parameter for the POST.
* @param value initial value for that parameter.
* @return StringBuilder to be used an HTTP POST body.
*/
protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Adds a new parameter to the HTTP POST body.
*
* @param body HTTP POST body.
* @param name parameter's name.
* @param value parameter's value.
*/
protected static void addParameter(StringBuilder body, String name,
String value) {
nonNull(body).append('&')
.append(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Gets an {@link HttpURLConnection} given an URL.
*/
protected HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
return conn;
}
/**
* Convenience method to convert an InputStream to a String.
* <p>
* If the stream ends in a newline character, it will be stripped.
* <p>
* If the stream is {@literal null}, returns an empty string.
*/
protected static String getString(InputStream stream) throws IOException {
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
// strip last newline
content.setLength(content.length() - 1);
}
return content.toString();
}
private static String getAndClose(InputStream stream) throws IOException {
try {
return getString(stream);
} finally {
if (stream != null) {
close(stream);
}
}
}
static <T> T nonNull(T argument) {
if (argument == null) {
throw new IllegalArgumentException("argument cannot be null");
}
return argument;
}
void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.server;
/**
* Constants used on GCM service communication.
*/
public final class Constants {
/**
* Endpoint for sending messages.
*/
public static final String GCM_SEND_ENDPOINT =
"https://android.googleapis.com/gcm/send";
/**
* HTTP parameter for registration id.
*/
public static final String PARAM_REGISTRATION_ID = "registration_id";
/**
* HTTP parameter for collapse key.
*/
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
/**
* HTTP parameter for delaying the message delivery if the device is idle.
*/
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
/**
* HTTP parameter for telling gcm to validate the message without actually sending it.
*/
public static final String PARAM_DRY_RUN = "dry_run";
/**
* HTTP parameter for package name that can be used to restrict message delivery by matching
* against the package name used to generate the registration id.
*/
public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name";
/**
* Prefix to HTTP parameter used to pass key-values in the message payload.
*/
public static final String PARAM_PAYLOAD_PREFIX = "data.";
/**
* Prefix to HTTP parameter used to set the message time-to-live.
*/
public static final String PARAM_TIME_TO_LIVE = "time_to_live";
/**
* Too many messages sent by the sender. Retry after a while.
*/
public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded";
/**
* Too many messages sent by the sender to a specific device.
* Retry after a while.
*/
public static final String ERROR_DEVICE_QUOTA_EXCEEDED =
"DeviceQuotaExceeded";
/**
* Missing registration_id.
* Sender should always add the registration_id to the request.
*/
public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration";
/**
* Bad registration_id. Sender should remove this registration_id.
*/
public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration";
/**
* The sender_id contained in the registration_id does not match the
* sender_id used to register with the GCM servers.
*/
public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId";
/**
* The user has uninstalled the application or turned off notifications.
* Sender should stop sending messages to this device and delete the
* registration_id. The client needs to re-register with the GCM servers to
* receive notifications again.
*/
public static final String ERROR_NOT_REGISTERED = "NotRegistered";
/**
* The payload of the message is too big, see the limitations.
* Reduce the size of the message.
*/
public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig";
/**
* Collapse key is required. Include collapse key in the request.
*/
public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey";
/**
* A particular message could not be sent because the GCM servers were not
* available. Used only on JSON requests, as in plain text requests
* unavailability is indicated by a 503 response.
*/
public static final String ERROR_UNAVAILABLE = "Unavailable";
/**
* A particular message could not be sent because the GCM servers encountered
* an error. Used only on JSON requests, as in plain text requests internal
* errors are indicated by a 500 response.
*/
public static final String ERROR_INTERNAL_SERVER_ERROR =
"InternalServerError";
/**
* Time to Live value passed is less than zero or more than maximum.
*/
public static final String ERROR_INVALID_TTL= "InvalidTtl";
/**
* Token returned by GCM when a message was successfully sent.
*/
public static final String TOKEN_MESSAGE_ID = "id";
/**
* Token returned by GCM when the requested registration id has a canonical
* value.
*/
public static final String TOKEN_CANONICAL_REG_ID = "registration_id";
/**
* Token returned by GCM when there was an error sending a message.
*/
public static final String TOKEN_ERROR = "Error";
/**
* JSON-only field representing the registration ids.
*/
public static final String JSON_REGISTRATION_IDS = "registration_ids";
/**
* JSON-only field representing the payload data.
*/
public static final String JSON_PAYLOAD = "data";
/**
* JSON-only field representing the number of successful messages.
*/
public static final String JSON_SUCCESS = "success";
/**
* JSON-only field representing the number of failed messages.
*/
public static final String JSON_FAILURE = "failure";
/**
* JSON-only field representing the number of messages with a canonical
* registration id.
*/
public static final String JSON_CANONICAL_IDS = "canonical_ids";
/**
* JSON-only field representing the id of the multicast request.
*/
public static final String JSON_MULTICAST_ID = "multicast_id";
/**
* JSON-only field representing the result of each individual request.
*/
public static final String JSON_RESULTS = "results";
/**
* JSON-only field representing the error field of an individual request.
*/
public static final String JSON_ERROR = "error";
/**
* JSON-only field sent by GCM when a message was successfully sent.
*/
public static final String JSON_MESSAGE_ID = "message_id";
private Constants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.server;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* GCM message.
*
* <p>
* Instances of this class are immutable and should be created using a
* {@link Builder}. Examples:
*
* <strong>Simplest message:</strong>
* <pre><code>
* Message message = new Message.Builder().build();
* </pre></code>
*
* <strong>Message with optional attributes:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .build();
* </pre></code>
*
* <strong>Message with optional attributes and payload data:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .addData("key1", "value1")
* .addData("key2", "value2")
* .build();
* </pre></code>
*/
public final class Message implements Serializable {
private final String collapseKey;
private final Boolean delayWhileIdle;
private final Integer timeToLive;
private final Map<String, String> data;
private final Boolean dryRun;
private final String restrictedPackageName;
public static final class Builder {
private final Map<String, String> data;
// optional parameters
private String collapseKey;
private Boolean delayWhileIdle;
private Integer timeToLive;
private Boolean dryRun;
private String restrictedPackageName;
public Builder() {
this.data = new LinkedHashMap<String, String>();
}
/**
* Sets the collapseKey property.
*/
public Builder collapseKey(String value) {
collapseKey = value;
return this;
}
/**
* Sets the delayWhileIdle property (default value is {@literal false}).
*/
public Builder delayWhileIdle(boolean value) {
delayWhileIdle = value;
return this;
}
/**
* Sets the time to live, in seconds.
*/
public Builder timeToLive(int value) {
timeToLive = value;
return this;
}
/**
* Adds a key/value pair to the payload data.
*/
public Builder addData(String key, String value) {
data.put(key, value);
return this;
}
/**
* Sets the dryRun property (default value is {@literal false}).
*/
public Builder dryRun(boolean value) {
dryRun = value;
return this;
}
/**
* Sets the restrictedPackageName property.
*/
public Builder restrictedPackageName(String value) {
restrictedPackageName = value;
return this;
}
public Message build() {
return new Message(this);
}
}
private Message(Builder builder) {
collapseKey = builder.collapseKey;
delayWhileIdle = builder.delayWhileIdle;
data = Collections.unmodifiableMap(builder.data);
timeToLive = builder.timeToLive;
dryRun = builder.dryRun;
restrictedPackageName = builder.restrictedPackageName;
}
/**
* Gets the collapse key.
*/
public String getCollapseKey() {
return collapseKey;
}
/**
* Gets the delayWhileIdle flag.
*/
public Boolean isDelayWhileIdle() {
return delayWhileIdle;
}
/**
* Gets the time to live (in seconds).
*/
public Integer getTimeToLive() {
return timeToLive;
}
/**
* Gets the dryRun flag.
*/
public Boolean isDryRun() {
return dryRun;
}
/**
* Gets the restricted package name.
*/
public String getRestrictedPackageName() {
return restrictedPackageName;
}
/**
* Gets the payload data, which is immutable.
*/
public Map<String, String> getData() {
return data;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Message(");
if (collapseKey != null) {
builder.append("collapseKey=").append(collapseKey).append(", ");
}
if (timeToLive != null) {
builder.append("timeToLive=").append(timeToLive).append(", ");
}
if (delayWhileIdle != null) {
builder.append("delayWhileIdle=").append(delayWhileIdle).append(", ");
}
if (dryRun != null) {
builder.append("dryRun=").append(dryRun).append(", ");
}
if (restrictedPackageName != null) {
builder.append("restrictedPackageName=").append(restrictedPackageName).append(", ");
}
if (!data.isEmpty()) {
builder.append("data: {");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(",");
}
builder.delete(builder.length() - 1, builder.length());
builder.append("}");
}
if (builder.charAt(builder.length() - 1) == ' ') {
builder.delete(builder.length() - 2, builder.length());
}
builder.append(")");
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.server;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result of a GCM multicast message request .
*/
public final class MulticastResult implements Serializable {
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
private final List<Result> results;
private final List<Long> retryMulticastIds;
public static final class Builder {
private final List<Result> results = new ArrayList<Result>();
// required parameters
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
// optional parameters
private List<Long> retryMulticastIds;
public Builder(int success, int failure, int canonicalIds,
long multicastId) {
this.success = success;
this.failure = failure;
this.canonicalIds = canonicalIds;
this.multicastId = multicastId;
}
public Builder addResult(Result result) {
results.add(result);
return this;
}
public Builder retryMulticastIds(List<Long> retryMulticastIds) {
this.retryMulticastIds = retryMulticastIds;
return this;
}
public MulticastResult build() {
return new MulticastResult(this);
}
}
private MulticastResult(Builder builder) {
success = builder.success;
failure = builder.failure;
canonicalIds = builder.canonicalIds;
multicastId = builder.multicastId;
results = Collections.unmodifiableList(builder.results);
List<Long> tmpList = builder.retryMulticastIds;
if (tmpList == null) {
tmpList = Collections.emptyList();
}
retryMulticastIds = Collections.unmodifiableList(tmpList);
}
/**
* Gets the multicast id.
*/
public long getMulticastId() {
return multicastId;
}
/**
* Gets the number of successful messages.
*/
public int getSuccess() {
return success;
}
/**
* Gets the total number of messages sent, regardless of the status.
*/
public int getTotal() {
return success + failure;
}
/**
* Gets the number of failed messages.
*/
public int getFailure() {
return failure;
}
/**
* Gets the number of successful messages that also returned a canonical
* registration id.
*/
public int getCanonicalIds() {
return canonicalIds;
}
/**
* Gets the results of each individual message, which is immutable.
*/
public List<Result> getResults() {
return results;
}
/**
* Gets additional ids if more than one multicast message was sent.
*/
public List<Long> getRetryMulticastIds() {
return retryMulticastIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MulticastResult(")
.append("multicast_id=").append(multicastId).append(",")
.append("total=").append(getTotal()).append(",")
.append("success=").append(success).append(",")
.append("failure=").append(failure).append(",")
.append("canonical_ids=").append(canonicalIds).append(",");
if (!results.isEmpty()) {
builder.append("results: " + results);
}
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm;
import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE;
import static com.google.android.gcm.GCMConstants.EXTRA_ERROR;
import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID;
import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE;
import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED;
import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK;
import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Skeleton for application-specific {@link IntentService}s responsible for
* handling communication from Google Cloud Messaging service.
* <p>
* The abstract methods in this class are called from its worker thread, and
* hence should run in a limited amount of time. If they execute long
* operations, they should spawn new threads, otherwise the worker thread will
* be blocked.
* <p>
* Subclasses must provide a public no-arg constructor.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public abstract class GCMBaseIntentService extends IntentService {
/**
* Old TAG used for logging. Marked as deprecated since it should have
* been private at first place.
*/
@Deprecated
public static final String TAG = "GCMBaseIntentService";
private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService",
"[" + getClass().getName() + "]: ");
// wakelock
private static final String WAKELOCK_KEY = "GCM_LIB";
private static PowerManager.WakeLock sWakeLock;
// Java lock used to synchronize access to sWakelock
private static final Object LOCK = GCMBaseIntentService.class;
private final String[] mSenderIds;
// instance counter
private static int sCounter = 0;
private static final Random sRandom = new Random();
private static final int MAX_BACKOFF_MS =
(int) TimeUnit.SECONDS.toMillis(3600); // 1 hour
/**
* Constructor that does not set a sender id, useful when the sender id
* is context-specific.
* <p>
* When using this constructor, the subclass <strong>must</strong>
* override {@link #getSenderIds(Context)}, otherwise methods such as
* {@link #onHandleIntent(Intent)} will throw an
* {@link IllegalStateException} on runtime.
*/
protected GCMBaseIntentService() {
this(getName("DynamicSenderIds"), null);
}
/**
* Constructor used when the sender id(s) is fixed.
*/
protected GCMBaseIntentService(String... senderIds) {
this(getName(senderIds), senderIds);
}
private GCMBaseIntentService(String name, String[] senderIds) {
super(name); // name is used as base name for threads, etc.
mSenderIds = senderIds;
mLogger.log(Log.VERBOSE, "Intent service name: %s", name);
}
private static String getName(String senderId) {
String name = "GCMIntentService-" + senderId + "-" + (++sCounter);
return name;
}
private static String getName(String[] senderIds) {
String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds);
return getName(flatSenderIds);
}
/**
* Gets the sender ids.
*
* <p>By default, it returns the sender ids passed in the constructor, but
* it could be overridden to provide a dynamic sender id.
*
* @throws IllegalStateException if sender id was not set on constructor.
*/
protected String[] getSenderIds(Context context) {
if (mSenderIds == null) {
throw new IllegalStateException("sender id not set on constructor");
}
return mSenderIds;
}
/**
* Called when a cloud message has been received.
*
* @param context application's context.
* @param intent intent containing the message payload as extras.
*/
protected abstract void onMessage(Context context, Intent intent);
/**
* Called when the GCM server tells pending messages have been deleted
* because the device was idle.
*
* @param context application's context.
* @param total total number of collapsed messages
*/
protected void onDeletedMessages(Context context, int total) {
}
/**
* Called on a registration error that could be retried.
*
* <p>By default, it does nothing and returns {@literal true}, but could be
* overridden to change that behavior and/or display the error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*
* @return if {@literal true}, failed operation will be retried (using
* exponential backoff).
*/
protected boolean onRecoverableError(Context context, String errorId) {
return true;
}
/**
* Called on registration or unregistration error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*/
protected abstract void onError(Context context, String errorId);
/**
* Called after a device has been registered.
*
* @param context application's context.
* @param registrationId the registration id returned by the GCM service.
*/
protected abstract void onRegistered(Context context,
String registrationId);
/**
* Called after a device has been unregistered.
*
* @param registrationId the registration id that was previously registered.
* @param context application's context.
*/
protected abstract void onUnregistered(Context context,
String registrationId);
@Override
public final void onHandleIntent(Intent intent) {
try {
Context context = getApplicationContext();
String action = intent.getAction();
if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) {
GCMRegistrar.setRetryBroadcastReceiver(context);
handleRegistration(context, intent);
} else if (action.equals(INTENT_FROM_GCM_MESSAGE)) {
// checks for special messages
String messageType =
intent.getStringExtra(EXTRA_SPECIAL_MESSAGE);
if (messageType != null) {
if (messageType.equals(VALUE_DELETED_MESSAGES)) {
String sTotal =
intent.getStringExtra(EXTRA_TOTAL_DELETED);
if (sTotal != null) {
try {
int total = Integer.parseInt(sTotal);
mLogger.log(Log.VERBOSE,
"Received notification for %d deleted"
+ "messages", total);
onDeletedMessages(context, total);
} catch (NumberFormatException e) {
mLogger.log(Log.ERROR, "GCM returned invalid "
+ "number of deleted messages (%d)",
sTotal);
}
}
} else {
// application is not using the latest GCM library
mLogger.log(Log.ERROR,
"Received unknown special message: %s",
messageType);
}
} else {
onMessage(context, intent);
}
} else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) {
String packageOnIntent = intent.getPackage();
if (packageOnIntent == null || !packageOnIntent.equals(
getApplicationContext().getPackageName())) {
mLogger.log(Log.ERROR,
"Ignoring retry intent from another package (%s)",
packageOnIntent);
return;
}
// retry last call
if (GCMRegistrar.isRegistered(context)) {
GCMRegistrar.internalUnregister(context);
} else {
String[] senderIds = getSenderIds(context);
GCMRegistrar.internalRegister(context, senderIds);
}
}
} finally {
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If onMessage() needs to spawn a thread or do something else,
// it should use its own lock.
synchronized (LOCK) {
// sanity check for null as this is a public method
if (sWakeLock != null) {
sWakeLock.release();
} else {
// should never happen during normal workflow
mLogger.log(Log.ERROR, "Wakelock reference is null");
}
}
}
}
/**
* Called from the broadcast receiver.
* <p>
* Will process the received intent, call handleMessage(), registered(),
* etc. in background threads, with a wake lock, while keeping the service
* alive.
*/
static void runIntentInService(Context context, Intent intent,
String className) {
synchronized (LOCK) {
if (sWakeLock == null) {
// This is called from BroadcastReceiver, there is no init.
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WAKELOCK_KEY);
}
}
sWakeLock.acquire();
intent.setClassName(context, className);
context.startService(intent);
}
private void handleRegistration(final Context context, Intent intent) {
GCMRegistrar.cancelAppPendingIntent();
String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
String error = intent.getStringExtra(EXTRA_ERROR);
String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, "
+ "error = %s, unregistered = %s",
registrationId, error, unregistered);
// registration succeeded
if (registrationId != null) {
GCMRegistrar.resetBackoff(context);
GCMRegistrar.setRegistrationId(context, registrationId);
onRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null) {
// Remember we are unregistered
GCMRegistrar.resetBackoff(context);
String oldRegistrationId =
GCMRegistrar.clearRegistrationId(context);
onUnregistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
// Registration failed
if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
boolean retry = onRecoverableError(context, error);
if (retry) {
int backoffTimeMs = GCMRegistrar.getBackoff(context);
int nextAttempt = backoffTimeMs / 2 +
sRandom.nextInt(backoffTimeMs);
mLogger.log(Log.DEBUG,
"Scheduling registration retry, backoff = %d (%d)",
nextAttempt, backoffTimeMs);
Intent retryIntent =
new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
retryIntent.setPackage(context.getPackageName());
PendingIntent retryPendingIntent = PendingIntent
.getBroadcast(context, 0, retryIntent, 0);
AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + nextAttempt,
retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MAX_BACKOFF_MS) {
GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
}
} else {
mLogger.log(Log.VERBOSE, "Not retrying failed operation");
}
} else {
// Unrecoverable error, notify app
onError(context, error);
}
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities for device registration.
* <p>
* <strong>Note:</strong> this class uses a private {@link SharedPreferences}
* object to keep track of the registration token.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMRegistrar {
/**
* Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)}
* flag until it is considered expired.
*/
// NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8
public static final long DEFAULT_ON_SERVER_LIFESPAN_MS =
1000 * 3600 * 24 * 7;
private static final String TAG = "GCMRegistrar";
private static final String BACKOFF_MS = "backoff_ms";
private static final String GSF_PACKAGE = "com.google.android.gsf";
private static final String PREFERENCES = "com.google.android.gcm";
private static final int DEFAULT_BACKOFF_MS = 3000;
private static final String PROPERTY_REG_ID = "regId";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String PROPERTY_ON_SERVER = "onServer";
private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
"onServerExpirationTime";
private static final String PROPERTY_ON_SERVER_LIFESPAN =
"onServerLifeSpan";
/**
* {@link GCMBroadcastReceiver} instance used to handle the retry intent.
*
* <p>
* This instance cannot be the same as the one defined in the manifest
* because it needs a different permission.
*/
// guarded by GCMRegistrar.class
private static GCMBroadcastReceiver sRetryReceiver;
// guarded by GCMRegistrar.class
private static Context sRetryReceiverContext;
// guarded by GCMRegistrar.class
private static String sRetryReceiverClassName;
// guarded by GCMRegistrar.class
private static PendingIntent sAppPendingIntent;
/**
* Checks if the device has the proper dependencies installed.
* <p>
* This method should be called when the application starts to verify that
* the device supports GCM.
*
* @param context application context.
* @throws UnsupportedOperationException if the device does not support GCM.
*/
public static void checkDevice(Context context) {
int version = Build.VERSION.SDK_INT;
if (version < 8) {
throw new UnsupportedOperationException("Device must be at least " +
"API Level 8 (instead of " + version + ")");
}
PackageManager packageManager = context.getPackageManager();
try {
packageManager.getPackageInfo(GSF_PACKAGE, 0);
} catch (NameNotFoundException e) {
throw new UnsupportedOperationException(
"Device does not have package " + GSF_PACKAGE);
}
}
/**
* Checks that the application manifest is properly configured.
* <p>
* A proper configuration means:
* <ol>
* <li>It creates a custom permission called
* {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
* <li>It defines at least one {@link BroadcastReceiver} with category
* {@code PACKAGE_NAME}.
* <li>The {@link BroadcastReceiver}(s) uses the
* {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS}
* permission.
* <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents
* ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* and
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
* </ol>
* ...where {@code PACKAGE_NAME} is the application package.
* <p>
* This method should be used during development time to verify that the
* manifest is properly set up, but it doesn't need to be called once the
* application is deployed to the users' devices.
*
* @param context application context.
* @throws IllegalStateException if any of the conditions above is not met.
*/
public static void checkManifest(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
String permissionName = packageName + ".permission.C2D_MESSAGE";
// check permission
try {
packageManager.getPermissionInfo(permissionName,
PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Application does not define permission " + permissionName);
}
// check receivers
PackageInfo receiversInfo;
try {
receiversInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Could not get receivers for package " + packageName);
}
ActivityInfo[] receivers = receiversInfo.receivers;
if (receivers == null || receivers.length == 0) {
throw new IllegalStateException("No receiver for package " +
packageName);
}
log(context, Log.VERBOSE, "number of receivers for %s: %d",
packageName, receivers.length);
Set<String> allowedReceivers = new HashSet<String>();
for (ActivityInfo receiver : receivers) {
if (GCMConstants.PERMISSION_GCM_INTENTS.equals(
receiver.permission)) {
allowedReceivers.add(receiver.name);
}
}
if (allowedReceivers.isEmpty()) {
throw new IllegalStateException("No receiver allowed to receive " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void checkReceiver(Context context,
Set<String> allowedReceivers, String action) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
Intent intent = new Intent(action);
intent.setPackage(packageName);
List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent,
PackageManager.GET_INTENT_FILTERS);
if (receivers.isEmpty()) {
throw new IllegalStateException("No receivers for action " +
action);
}
log(context, Log.VERBOSE, "Found %d receivers for action %s",
receivers.size(), action);
// make sure receivers match
for (ResolveInfo receiver : receivers) {
String name = receiver.activityInfo.name;
if (!allowedReceivers.contains(name)) {
throw new IllegalStateException("Receiver " + name +
" is not set with permission " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
}
}
/**
* Initiate messaging registration for the current application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with
* either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or
* {@link GCMConstants#EXTRA_ERROR}.
*
* @param context application context.
* @param senderIds Google Project ID of the accounts authorized to send
* messages to this application.
* @throws IllegalStateException if device does not have all GCM
* dependencies installed.
*/
public static void register(Context context, String... senderIds) {
GCMRegistrar.resetBackoff(context);
internalRegister(context, senderIds);
}
static void internalRegister(Context context, String... senderIds) {
String flatSenderIds = getFlatSenderIds(senderIds);
log(context, Log.VERBOSE, "Registering app for senders %s",
flatSenderIds);
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
context.startService(intent);
}
/**
* Unregister the application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an
* {@link GCMConstants#EXTRA_UNREGISTERED} extra.
*/
public static void unregister(Context context) {
GCMRegistrar.resetBackoff(context);
internalUnregister(context);
}
static void internalUnregister(Context context) {
log(context, Log.VERBOSE, "Unregistering app");
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
context.startService(intent);
}
static String getFlatSenderIds(String... senderIds) {
if (senderIds == null || senderIds.length == 0) {
throw new IllegalArgumentException("No senderIds");
}
StringBuilder builder = new StringBuilder(senderIds[0]);
for (int i = 1; i < senderIds.length; i++) {
builder.append(',').append(senderIds[i]);
}
return builder.toString();
}
/**
* Clear internal resources.
*
* <p>
* This method should be called by the main activity's {@code onDestroy()}
* method.
*/
public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
log(context, Log.VERBOSE, "Unregistering retry receiver");
sRetryReceiverContext.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
sRetryReceiverContext = null;
}
}
static synchronized void cancelAppPendingIntent() {
if (sAppPendingIntent != null) {
sAppPendingIntent.cancel();
sAppPendingIntent = null;
}
}
private synchronized static void setPackageNameExtra(Context context,
Intent intent) {
if (sAppPendingIntent == null) {
log(context, Log.VERBOSE,
"Creating pending intent to get package name");
sAppPendingIntent = PendingIntent.getBroadcast(context, 0,
new Intent(), 0);
}
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
sAppPendingIntent);
}
/**
* Lazy initializes the {@link GCMBroadcastReceiver} instance.
*/
static synchronized void setRetryBroadcastReceiver(Context context) {
if (sRetryReceiver == null) {
if (sRetryReceiverClassName == null) {
// should never happen
log(context, Log.ERROR,
"internal error: retry receiver class not set yet");
sRetryReceiver = new GCMBroadcastReceiver();
} else {
Class<?> clazz;
try {
clazz = Class.forName(sRetryReceiverClassName);
sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
} catch (Exception e) {
log(context, Log.ERROR, "Could not create instance of %s. "
+ "Using %s directly.", sRetryReceiverClassName,
GCMBroadcastReceiver.class.getName());
sRetryReceiver = new GCMBroadcastReceiver();
}
}
String category = context.getPackageName();
IntentFilter filter = new IntentFilter(
GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.addCategory(category);
log(context, Log.VERBOSE, "Registering retry receiver");
sRetryReceiverContext = context;
sRetryReceiverContext.registerReceiver(sRetryReceiver, filter);
}
}
/**
* Sets the name of the retry receiver class.
*/
static synchronized void setRetryReceiverClassName(Context context,
String className) {
log(context, Log.VERBOSE,
"Setting the name of retry receiver class to %s", className);
sRetryReceiverClassName = className;
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
log(context, Log.VERBOSE, "App version changed from %d to %d;"
+ "resetting registration id", oldVersion, newVersion);
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
/**
* Checks whether the application was successfully registered on GCM
* service.
*/
public static boolean isRegistered(Context context) {
return getRegistrationId(context).length() > 0;
}
/**
* Clears the registration id in the persistence store.
*
* <p>As a side-effect, it also expires the registeredOnServer property.
*
* @param context application's context.
* @return old registration id.
*/
static String clearRegistrationId(Context context) {
setRegisteredOnServer(context, null, 0);
return setRegistrationId(context, "");
}
/**
* Sets the registration id in the persistence store.
*
* @param context application's context.
* @param regId registration id
*/
static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
}
/**
* Sets whether the device was successfully registered in the server side.
*/
public static void setRegisteredOnServer(Context context, boolean flag) {
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
setRegisteredOnServer(context, flag, expirationTime);
}
private static void setRegisteredOnServer(Context context, Boolean flag,
long expirationTime) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
if (flag != null) {
editor.putBoolean(PROPERTY_ON_SERVER, flag);
log(context, Log.VERBOSE,
"Setting registeredOnServer flag as %b until %s",
flag, new Timestamp(expirationTime));
} else {
log(context, Log.VERBOSE,
"Setting registeredOnServer expiration to %s",
new Timestamp(expirationTime));
}
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side,
* as set by {@link #setRegisteredOnServer(Context, boolean)}.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, this flag has an expiration date, which
* is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed
* by {@link #setRegisterOnServerLifespan(Context, long)}).
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false);
log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered);
if (isRegistered) {
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
if (System.currentTimeMillis() > expirationTime) {
log(context, Log.VERBOSE, "flag expired on: %s",
new Timestamp(expirationTime));
return false;
}
}
return isRegistered;
}
/**
* Gets how long (in milliseconds) the {@link #isRegistered(Context)}
* property is valid.
*
* @return value set by {@link #setRegisteredOnServer(Context, boolean)} or
* {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set.
*/
public static long getRegisterOnServerLifespan(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN,
DEFAULT_ON_SERVER_LIFESPAN_MS);
return lifespan;
}
/**
* Sets how long (in milliseconds) the {@link #isRegistered(Context)}
* flag is valid.
*/
public static void setRegisterOnServerLifespan(Context context,
long lifespan) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan);
editor.commit();
}
/**
* Gets the application version.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
}
/**
* Resets the backoff counter.
* <p>
* This method should be called after a GCM call succeeds.
*
* @param context application's context.
*/
static void resetBackoff(Context context) {
log(context, Log.VERBOSE, "Resetting backoff");
setBackoff(context, DEFAULT_BACKOFF_MS);
}
/**
* Gets the current backoff counter.
*
* @param context application's context.
* @return current backoff counter, in milliseconds.
*/
static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
/**
* Sets the backoff counter.
* <p>
* This method should be called after a GCM call fails, passing an
* exponential value.
*
* @param context application's context.
* @param backoff new backoff counter, in milliseconds.
*/
static void setBackoff(Context context, int backoff) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putInt(BACKOFF_MS, backoff);
editor.commit();
}
private static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
/**
* Logs a message on logcat.
*
* @param context application's context.
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
private static void log(Context context, int priority, String template,
Object... args) {
if (Log.isLoggable(TAG, priority)) {
String message = String.format(template, args);
Log.println(priority, TAG, "[" + context.getPackageName() + "]: "
+ message);
}
}
private GCMRegistrar() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm;
/**
* Constants used by the GCM library.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMConstants {
/**
* Intent sent to GCM to register the application.
*/
public static final String INTENT_TO_GCM_REGISTRATION =
"com.google.android.c2dm.intent.REGISTER";
/**
* Intent sent to GCM to unregister the application.
*/
public static final String INTENT_TO_GCM_UNREGISTRATION =
"com.google.android.c2dm.intent.UNREGISTER";
/**
* Intent sent by GCM indicating with the result of a registration request.
*/
public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK =
"com.google.android.c2dm.intent.REGISTRATION";
/**
* Intent used by the GCM library to indicate that the registration call
* should be retried.
*/
public static final String INTENT_FROM_GCM_LIBRARY_RETRY =
"com.google.android.gcm.intent.RETRY";
/**
* Intent sent by GCM containing a message.
*/
public static final String INTENT_FROM_GCM_MESSAGE =
"com.google.android.c2dm.intent.RECEIVE";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to indicate which senders (Google API project ids) can send messages to
* the application.
*/
public static final String EXTRA_SENDER = "sender";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to get the application info.
*/
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate that the application has been unregistered.
*/
public static final String EXTRA_UNREGISTERED = "unregistered";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate an error when the registration fails.
* See constants starting with ERROR_ for possible values.
*/
public static final String EXTRA_ERROR = "error";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate the registration id when the registration succeeds.
*/
public static final String EXTRA_REGISTRATION_ID = "registration_id";
/**
* Type of message present in the
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* intent.
* This extra is only set for special messages sent from GCM, not for
* messages originated from the application.
*/
public static final String EXTRA_SPECIAL_MESSAGE = "message_type";
/**
* Special message indicating the server deleted the pending messages.
*/
public static final String VALUE_DELETED_MESSAGES = "deleted_messages";
/**
* Number of messages deleted by the server because the device was idle.
* Present only on messages of special type
* {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES}
*/
public static final String EXTRA_TOTAL_DELETED = "total_deleted";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* to indicate which sender (Google API project id) sent the message.
*/
public static final String EXTRA_FROM = "from";
/**
* Permission necessary to receive GCM intents.
*/
public static final String PERMISSION_GCM_INTENTS =
"com.google.android.c2dm.permission.SEND";
/**
* @see GCMBroadcastReceiver
*/
public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME =
".GCMIntentService";
/**
* The device can't read the response, or there was a 500/503 from the
* server that can be retried later. The application should use exponential
* back off and retry.
*/
public static final String ERROR_SERVICE_NOT_AVAILABLE =
"SERVICE_NOT_AVAILABLE";
/**
* There is no Google account on the phone. The application should ask the
* user to open the account manager and add a Google account.
*/
public static final String ERROR_ACCOUNT_MISSING =
"ACCOUNT_MISSING";
/**
* Bad password. The application should ask the user to enter his/her
* password, and let user retry manually later. Fix on the device side.
*/
public static final String ERROR_AUTHENTICATION_FAILED =
"AUTHENTICATION_FAILED";
/**
* The request sent by the phone does not contain the expected parameters.
* This phone doesn't currently support GCM.
*/
public static final String ERROR_INVALID_PARAMETERS =
"INVALID_PARAMETERS";
/**
* The sender account is not recognized. Fix on the device side.
*/
public static final String ERROR_INVALID_SENDER =
"INVALID_SENDER";
/**
* Incorrect phone registration with Google. This phone doesn't currently
* support GCM.
*/
public static final String ERROR_PHONE_REGISTRATION_ERROR =
"PHONE_REGISTRATION_ERROR";
private GCMConstants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm;
import android.util.Log;
/**
* Custom logger.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
class GCMLogger {
private final String mTag;
// can't use class name on TAG since size is limited to 23 chars
private final String mLogPrefix;
GCMLogger(String tag, String logPrefix) {
mTag = tag;
mLogPrefix = logPrefix;
}
/**
* Logs a message on logcat.
*
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
protected void log(int priority, String template, Object... args) {
if (Log.isLoggable(mTag, priority)) {
String message = String.format(template, args);
Log.println(priority, mTag, mLogPrefix + message);
}
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm;
import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* {@link BroadcastReceiver} that receives GCM messages and delivers them to
* an application-specific {@link GCMBaseIntentService} subclass.
* <p>
* By default, the {@link GCMBaseIntentService} class belongs to the application
* main package and is named
* {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class,
* the {@link #getGCMIntentServiceClassName(Context)} must be overridden.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static boolean mReceiverSet = false;
private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver",
"[" + getClass().getName() + "]: ");
@Override
public final void onReceive(Context context, Intent intent) {
mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction());
// do a one-time check if app is using a custom GCMBroadcastReceiver
if (!mReceiverSet) {
mReceiverSet = true;
GCMRegistrar.setRetryReceiverClassName(context,
getClass().getName());
}
String className = getGCMIntentServiceClassName(context);
mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className);
// Delegates to the application-specific intent service.
GCMBaseIntentService.runIntentInService(context, intent, className);
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
/**
* Gets the class name of the intent service that will handle GCM messages.
*/
protected String getGCMIntentServiceClassName(Context context) {
return getDefaultIntentServiceClassName(context);
}
/**
* Gets the default class name of the intent service that will handle GCM
* messages.
*/
static final String getDefaultIntentServiceClassName(Context context) {
String className = context.getPackageName() +
DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gcm;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
private static final int MULTICAST_SIZE = 1000;
private Sender sender;
private static final Executor threadPool = Executors.newFixedThreadPool(5);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String registrationId = devices.get(0);
Message message = new Message.Builder().build();
Result result = sender.send(message, registrationId, 5);
status = "Sent message to one device: " + result;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == MULTICAST_SIZE || counter == total) {
asyncSend(partialDevices);
partialDevices.clear();
tasks++;
}
}
status = "Asynchronously sending " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
private void asyncSend(List<String> partialDevices) {
// make a copy
final List<String> devices = new ArrayList<String>(partialDevices);
threadPool.execute(new Runnable() {
public void run() {
Message message = new Message.Builder().build();
MulticastResult multicastResult;
try {
multicastResult = sender.send(message, devices, 5);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error posting messages", e);
return;
}
List<Result> results = multicastResult.getResults();
// analyze the results
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logger.fine("Succesfully sent message to device: " + regId +
"; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.info("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
logger.info("Unregistered device: " + regId);
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to " + regId + ": " + error);
}
}
}
}});
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is thread-safe but not persistent (it will lost the data when the
* app is restarted) - it is meant just as an example.
*/
public final class Datastore {
private static final List<String> regIds = new ArrayList<String>();
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
synchronized (regIds) {
regIds.add(regId);
}
}
/**
* Unregisters a device.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
synchronized (regIds) {
regIds.remove(regId);
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
synchronized (regIds) {
regIds.remove(oldId);
regIds.add(newId);
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
synchronized (regIds) {
return new ArrayList<String>(regIds);
}
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from a
* {@value #PATH} file located in the classpath (typically under
* {@code WEB-INF/classes}).
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String PATH = "/api.key";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
logger.info("Reading " + PATH + " from resources (probably from " +
"WEB-INF/classes");
String key = getKey();
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key);
}
/**
* Gets the access key.
*/
protected String getKey() {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(PATH);
if (stream == null) {
throw new IllegalStateException("Could not find file " + PATH +
" on web resources)");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
String key = reader.readLine();
return key;
} catch (IOException e) {
throw new RuntimeException("Could not read file " + PATH, e);
} finally {
try {
reader.close();
} catch (IOException e) {
logger.log(Level.WARNING, "Exception closing " + PATH, e);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty()) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import com.google.android.gcm.GCMRegistrar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
/*
* Typically, an application registers automatically, so options
* below are disabled. Uncomment them if you want to manually
* register or unregister the device (you will also need to
* uncomment the equivalent options on options_menu.xml).
*/
/*
case R.id.options_register:
GCMRegistrar.register(this, SENDER_ID);
return true;
case R.id.options_unregister:
GCMRegistrar.unregister(this);
return true;
*/
case R.id.options_clear:
mDisplay.setText(null);
return true;
case R.id.options_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
} | Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.app;
import android.content.Context;
import android.content.Intent;
/**
* Helper class providing methods and constants common to other classes in the
* app.
*/
public final class CommonUtilities {
/**
* Base URL of the Demo Server (such as http://my_host:8080/gcm-demo)
*/
static final String SERVER_URL = null;
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = null;
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
/**
* Intent used to display a message in the screen.
*/
static final String DISPLAY_MESSAGE_ACTION =
"com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered,
registrationId));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message. Extras: " + intent.getExtras());
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
Queue queue = QueueFactory.getQueue("gcm");
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String device = devices.get(0);
queue.add(withUrl("/send").param(
SendMessageServlet.PARAMETER_DEVICE, device));
status = "Single message queued for registration id " + device;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
String multicastKey = Datastore.createMulticast(partialDevices);
logger.fine("Queuing " + partialSize + " devices on multicast " +
multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/send")
.param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey)
.method(Method.POST);
queue.add(taskOptions);
partialDevices.clear();
tasks++;
}
}
status = "Queued tasks to send " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that sends a message to a device.
* <p>
* This servlet is invoked by AppEngine's Push Queue mechanism.
*/
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount";
private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName";
private static final int MAX_RETRY = 3;
static final String PARAMETER_DEVICE = "device";
static final String PARAMETER_MULTICAST = "multicastKey";
private Sender sender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp) {
resp.setStatus(200);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getHeader(HEADER_QUEUE_NAME) == null) {
throw new IOException("Missing header " + HEADER_QUEUE_NAME);
}
String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT);
logger.fine("retry count: " + retryCountHeader);
if (retryCountHeader != null) {
int retryCount = Integer.parseInt(retryCountHeader);
if (retryCount > MAX_RETRY) {
logger.severe("Too many retries, dropping task");
taskDone(resp);
return;
}
}
String regId = req.getParameter(PARAMETER_DEVICE);
if (regId != null) {
sendSingleMessage(regId, resp);
return;
}
String multicastKey = req.getParameter(PARAMETER_MULTICAST);
if (multicastKey != null) {
sendMulticastMessage(multicastKey, resp);
return;
}
logger.severe("Invalid request!");
taskDone(resp);
return;
}
private Message createMessage() {
Message message = new Message.Builder().build();
return message;
}
private void sendSingleMessage(String regId, HttpServletResponse resp) {
logger.info("Sending message to device " + regId);
Message message = createMessage();
Result result;
try {
result = sender.sendNoRetry(message, regId);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
taskDone(resp);
return;
}
if (result == null) {
retryTask(resp);
return;
}
if (result.getMessageId() != null) {
logger.info("Succesfully sent message to device " + regId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.finest("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to device " + regId
+ ": " + error);
}
}
}
private void sendMulticastMessage(String multicastKey,
HttpServletResponse resp) {
// Recover registration ids from datastore
List<String> regIds = Datastore.getMulticast(multicastKey);
Message message = createMessage();
MulticastResult multicastResult;
try {
multicastResult = sender.sendNoRetry(message, regIds);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
multicastDone(resp, multicastKey);
return;
}
boolean allDone = true;
// check if any registration id must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = regIds.get(i);
Datastore.updateRegistration(regId, canonicalRegId);
}
}
}
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retriableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = regIds.get(i);
logger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
}
if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retriableRegIds.add(regId);
}
}
}
if (!retriableRegIds.isEmpty()) {
// update task
Datastore.updateMulticast(multicastKey, retriableRegIds);
allDone = false;
retryTask(resp);
}
}
if (allDone) {
multicastDone(resp, multicastKey);
} else {
retryTask(resp);
}
}
private void multicastDone(HttpServletResponse resp, String encodedKey) {
Datastore.deleteMulticast(encodedKey);
taskDone(resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is neither persistent (it will lost the data when the app is
* restarted) nor thread safe.
*/
public final class Datastore {
static final int MULTICAST_SIZE = 1000;
private static final String DEVICE_TYPE = "Device";
private static final String DEVICE_REG_ID_PROPERTY = "regId";
private static final String MULTICAST_TYPE = "Multicast";
private static final String MULTICAST_REG_IDS_PROPERTY = "regIds";
private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder
.withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE);
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private static final DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*
* @param regId device's registration id.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity != null) {
logger.fine(regId + " is already registered; ignoring.");
return;
}
entity = new Entity(DEVICE_TYPE);
entity.setProperty(DEVICE_REG_ID_PROPERTY, regId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Unregisters a device.
*
* @param regId device's registration id.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity == null) {
logger.warning("Device " + regId + " already unregistered");
} else {
Key key = entity.getKey();
datastore.delete(key);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(oldId);
if (entity == null) {
logger.warning("No device for registration id " + oldId);
return;
}
entity.setProperty(DEVICE_REG_ID_PROPERTY, newId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
List<String> devices;
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE);
Iterable<Entity> entities =
datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS);
devices = new ArrayList<String>();
for (Entity entity : entities) {
String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY);
devices.add(device);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return devices;
}
/**
* Gets the number of total devices.
*/
public static int getTotalDevices() {
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE).setKeysOnly();
List<Entity> allKeys =
datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS);
int total = allKeys.size();
logger.fine("Total number of devices: " + total);
txn.commit();
return total;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
private static Entity findDeviceByRegId(String regId) {
Query query = new Query(DEVICE_TYPE)
.addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId);
PreparedQuery preparedQuery = datastore.prepare(query);
List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS);
Entity entity = null;
if (!entities.isEmpty()) {
entity = entities.get(0);
}
int size = entities.size();
if (size > 0) {
logger.severe(
"Found " + size + " entities for regId " + regId + ": " + entities);
}
return entity;
}
/**
* Creates a persistent record with the devices to be notified using a
* multicast message.
*
* @param devices registration ids of the devices.
* @return encoded key for the persistent record.
*/
public static String createMulticast(List<String> devices) {
logger.info("Storing multicast for " + devices.size() + " devices");
String encodedKey;
Transaction txn = datastore.beginTransaction();
try {
Entity entity = new Entity(MULTICAST_TYPE);
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
Key key = entity.getKey();
encodedKey = KeyFactory.keyToString(key);
logger.fine("multicast key: " + encodedKey);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return encodedKey;
}
/**
* Gets a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static List<String> getMulticast(String encodedKey) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
entity = datastore.get(key);
@SuppressWarnings("unchecked")
List<String> devices =
(List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY);
txn.commit();
return devices;
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return Collections.emptyList();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
* @param devices new list of registration ids of the devices.
*/
public static void updateMulticast(String encodedKey, List<String> devices) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return;
}
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Deletes a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static void deleteMulticast(String encodedKey) {
Transaction txn = datastore.beginTransaction();
try {
Key key = KeyFactory.stringToKey(encodedKey);
datastore.delete(key);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from the App Engine datastore.
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String ENTITY_KIND = "Settings";
private static final String ENTITY_KEY = "MyKey";
private static final String ACCESS_KEY_FIELD = "ApiKey";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
Entity entity;
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
entity = new Entity(key);
// NOTE: it's not possible to change entities in the local server, so
// it will be necessary to hardcode the API key below if you are running
// it locally.
entity.setProperty(ACCESS_KEY_FIELD,
"replace_this_text_by_your_Simple_API_Access_key");
datastore.put(entity);
logger.severe("Created fake key. Please go to App Engine admin "
+ "console, change its value to your API Key (the entity "
+ "type is '" + ENTITY_KIND + "' and its field to be changed is '"
+ ACCESS_KEY_FIELD + "'), then restart the server!");
}
String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 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 com.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
int total = Datastore.getTotalDevices();
if (total == 0) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + total + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
package cx.hell.android.pdfview;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cx.hell.android.lib.pagesview.FindResult;
import cx.hell.android.lib.pagesview.PagesView;
import cx.hell.android.lib.pdf.PDF;
// #ifdef pro
// import java.util.Stack;
// import java.util.Map;
// import android.content.DialogInterface.OnDismissListener;
// import android.view.ViewGroup.LayoutParams;
// import android.widget.ScrollView;
// import android.text.method.ScrollingMovementMethod;
// import cx.hell.android.lib.pdf.PDF.Outline;
// import cx.hell.android.lib.view.TreeView;
// #endif
/**
* Document display activity.
*/
@SuppressWarnings("unused")
public class OpenFileActivity extends Activity implements SensorEventListener {
private final static String TAG = "cx.hell.android.pdfview";
private final static int[] zoomAnimations = {
R.anim.zoom_disappear, R.anim.zoom_almost_disappear, R.anim.zoom
};
private final static int[] pageNumberAnimations = {
R.anim.page_disappear, R.anim.page_almost_disappear, R.anim.page,
R.anim.page_show_always
};
private PDF pdf = null;
private PagesView pagesView = null;
// #ifdef pro
//
// /**
// * Complete top-level view (layout) of text reflow.
// * Hidden (with Visibility.GONE) when not in text reflow mode.
// */
// private View textReflowView = null;
//
// /**
// * View that contains scrollable view(s) visible in text reflow mode.
// */
// private ScrollView textReflowScrollView = null;
//
// /**
// * TextView visible in text reflow mode, contains text extracted from PDF file.
// */
// private TextView textReflowTextView = null;
//
// #endif
private PDFPagesProvider pdfPagesProvider = null;
private Actions actions = null;
private Handler zoomHandler = null;
private Handler pageHandler = null;
private Runnable zoomRunnable = null;
private Runnable pageRunnable = null;
private MenuItem aboutMenuItem = null;
private MenuItem gotoPageMenuItem = null;
private MenuItem rotateLeftMenuItem = null;
private MenuItem rotateRightMenuItem = null;
private MenuItem findTextMenuItem = null;
private MenuItem clearFindTextMenuItem = null;
private MenuItem chooseFileMenuItem = null;
private MenuItem optionsMenuItem = null;
// #ifdef pro
// private MenuItem tableOfContentsMenuItem = null;
// private MenuItem textReflowMenuItem = null;
// #endif
private EditText pageNumberInputField = null;
private EditText findTextInputField = null;
private LinearLayout findButtonsLayout = null;
private Button findPrevButton = null;
private Button findNextButton = null;
private Button findHideButton = null;
private RelativeLayout activityLayout = null;
private boolean eink = false;
// currently opened file path
private String filePath = "/";
private String findText = null;
private Integer currentFindResultPage = null;
private Integer currentFindResultNumber = null;
// zoom buttons, layout and fade animation
private ImageButton zoomDownButton;
private ImageButton zoomWidthButton;
private ImageButton zoomUpButton;
private Animation zoomAnim;
private LinearLayout zoomLayout;
// page number display
private TextView pageNumberTextView;
private Animation pageNumberAnim;
private int box = 2;
public boolean showZoomOnScroll = false;
private int fadeStartOffset = 7000;
private int colorMode = Options.COLOR_MODE_NORMAL;
private SensorManager sensorManager;
private static final int ZOOM_COLOR_NORMAL = 0;
private static final int ZOOM_COLOR_RED = 1;
private static final int ZOOM_COLOR_GREEN = 2;
private static final int[] zoomUpId = {
R.drawable.btn_zoom_up, R.drawable.red_btn_zoom_up, R.drawable.green_btn_zoom_up
};
private static final int[] zoomDownId = {
R.drawable.btn_zoom_down, R.drawable.red_btn_zoom_down, R.drawable.green_btn_zoom_down
};
private static final int[] zoomWidthId = {
R.drawable.btn_zoom_width, R.drawable.red_btn_zoom_width, R.drawable.green_btn_zoom_width
};
private float[] gravity = { 0f, -9.81f, 0f};
private long gravityAge = 0;
private int prevOrientation;
private boolean history = true;
// #ifdef pro
// /**
// * If true, then current activity is in text reflow mode.
// */
// private boolean textReflowMode = false;
// #endif
/**
* Called when the activity is first created.
* TODO: initialize dialog fast, then move file loading to other thread
* TODO: add progress bar for file load
* TODO: add progress icon for file rendering
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Options.setOrientation(this);
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this);
this.box = Integer.parseInt(options.getString(Options.PREF_BOX, "2"));
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Get display metrics
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
// use a relative layout to stack the views
activityLayout = new RelativeLayout(this);
// the PDF view
this.pagesView = new PagesView(this);
activityLayout.addView(pagesView);
startPDF(options);
if (!this.pdf.isValid()) {
finish();
}
// #ifdef pro
// /* TODO: move to separate method */
// LinearLayout textReflowLayout = new LinearLayout(this);
// this.textReflowView = textReflowLayout;
// textReflowLayout.setOrientation(LinearLayout.VERTICAL);
//
// this.textReflowScrollView = new ScrollView(this);
// this.textReflowScrollView.setFillViewport(true);
//
// this.textReflowTextView = new TextView(this);
//
// LinearLayout textReflowButtonsLayout = new LinearLayout(this);
// textReflowButtonsLayout.setGravity(Gravity.CENTER);
// textReflowButtonsLayout.setOrientation(LinearLayout.HORIZONTAL);
// Button textReflowPrevPageButton = new Button(this);
// textReflowPrevPageButton.setText("Prev");
// textReflowPrevPageButton.setOnClickListener(new OnClickListener() {
// public void onClick(View v) {
// OpenFileActivity.this.nextPage(-1);
// }
// });
// Button textReflowNextPageButton = new Button(this);
// textReflowNextPageButton.setText("Next");
// textReflowNextPageButton.setOnClickListener(new OnClickListener() {
// public void onClick(View v) {
// OpenFileActivity.this.nextPage(1);
// }
// });
// textReflowButtonsLayout.addView(textReflowPrevPageButton);
// textReflowButtonsLayout.addView(textReflowNextPageButton);
//
// this.textReflowScrollView.addView(this.textReflowTextView);
// LinearLayout.LayoutParams textReflowScrollViewLayoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1);
// textReflowLayout.addView(this.textReflowScrollView, textReflowScrollViewLayoutParams);
// textReflowLayout.addView(textReflowButtonsLayout, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 0));
//
// activityLayout.addView(this.textReflowView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
// this.textReflowView.setVisibility(View.GONE);
// AndroidReflections.setScrollbarFadingEnabled(this.textReflowView, true);
// #endif
// the find buttons
this.findButtonsLayout = new LinearLayout(this);
this.findButtonsLayout.setOrientation(LinearLayout.HORIZONTAL);
this.findButtonsLayout.setVisibility(View.GONE);
this.findButtonsLayout.setGravity(Gravity.CENTER);
this.findPrevButton = new Button(this);
this.findPrevButton.setText("Prev");
this.findButtonsLayout.addView(this.findPrevButton);
this.findNextButton = new Button(this);
this.findNextButton.setText("Next");
this.findButtonsLayout.addView(this.findNextButton);
this.findHideButton = new Button(this);
this.findHideButton.setText("Hide");
this.findButtonsLayout.addView(this.findHideButton);
this.setFindButtonHandlers();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
activityLayout.addView(this.findButtonsLayout, lp);
this.pageNumberTextView = new TextView(this);
this.pageNumberTextView.setTextSize(8f*metrics.density);
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
activityLayout.addView(this.pageNumberTextView, lp);
// display this
this.setContentView(activityLayout);
// go to last viewed page
// gotoLastPage();
// send keyboard events to this view
pagesView.setFocusable(true);
pagesView.setFocusableInTouchMode(true);
this.zoomHandler = new Handler();
this.pageHandler = new Handler();
this.zoomRunnable = new Runnable() {
public void run() {
fadeZoom();
}
};
this.pageRunnable = new Runnable() {
public void run() {
fadePage();
}
};
}
/**
* Save the current page before exiting
*/
@Override
protected void onPause() {
super.onPause();
saveLastPage();
if (sensorManager != null) {
sensorManager.unregisterListener(this);
sensorManager = null;
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putInt(Options.PREF_PREV_ORIENTATION, prevOrientation);
Log.v(TAG, "prevOrientation saved: "+prevOrientation);
edit.commit();
}
}
@Override
protected void onResume() {
super.onResume();
sensorManager = null;
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this);
if (Options.setOrientation(this)) {
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
if (sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() > 0) {
gravity[0] = 0f;
gravity[1] = -9.81f;
gravity[2] = 0f;
gravityAge = 0;
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
this.prevOrientation = options.getInt(Options.PREF_PREV_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(this.prevOrientation);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
history = options.getBoolean(Options.PREF_HISTORY, true);
boolean eink = options.getBoolean(Options.PREF_EINK, false);
this.pagesView.setEink(eink);
if (eink)
this.setTheme(android.R.style.Theme_Light);
this.pagesView.setNook2(options.getBoolean(Options.PREF_NOOK2, false));
if (options.getBoolean(Options.PREF_KEEP_ON, false))
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
actions = new Actions(options);
this.pagesView.setActions(actions);
setZoomLayout(options);
this.pagesView.setZoomLayout(zoomLayout);
this.showZoomOnScroll = options.getBoolean(Options.PREF_SHOW_ZOOM_ON_SCROLL, false);
this.pagesView.setSideMargins(
Integer.parseInt(options.getString(Options.PREF_SIDE_MARGINS, "0")));
this.pagesView.setTopMargin(
Integer.parseInt(options.getString(Options.PREF_TOP_MARGIN, "0")));
this.pagesView.setDoubleTap(Integer.parseInt(options.getString(Options.PREF_DOUBLE_TAP,
""+Options.DOUBLE_TAP_ZOOM_IN_OUT)));
int newBox = Integer.parseInt(options.getString(Options.PREF_BOX, "2"));
if (this.box != newBox) {
saveLastPage();
this.box = newBox;
startPDF(options);
this.pagesView.goToBookmark();
}
this.colorMode = Options.getColorMode(options);
this.eink = options.getBoolean(Options.PREF_EINK, false);
this.pageNumberTextView.setBackgroundColor(Options.getBackColor(colorMode));
this.pageNumberTextView.setTextColor(Options.getForeColor(colorMode));
this.pdfPagesProvider.setGray(Options.isGray(this.colorMode));
this.pdfPagesProvider.setExtraCache(1024*1024*Options.getIntFromString(options, Options.PREF_EXTRA_CACHE, 0));
this.pdfPagesProvider.setOmitImages(options.getBoolean(Options.PREF_OMIT_IMAGES, false));
this.pagesView.setColorMode(this.colorMode);
this.pdfPagesProvider.setRenderAhead(options.getBoolean(Options.PREF_RENDER_AHEAD, true));
this.pagesView.setVerticalScrollLock(options.getBoolean(Options.PREF_VERTICAL_SCROLL_LOCK, false));
this.pagesView.invalidate();
int zoomAnimNumber = Integer.parseInt(options.getString(Options.PREF_ZOOM_ANIMATION, "2"));
if (zoomAnimNumber == Options.ZOOM_BUTTONS_DISABLED)
zoomAnim = null;
else
zoomAnim = AnimationUtils.loadAnimation(this,
zoomAnimations[zoomAnimNumber]);
int pageNumberAnimNumber = Integer.parseInt(options.getString(Options.PREF_PAGE_ANIMATION, "3"));
if (pageNumberAnimNumber == Options.PAGE_NUMBER_DISABLED)
pageNumberAnim = null;
else
pageNumberAnim = AnimationUtils.loadAnimation(this,
pageNumberAnimations[pageNumberAnimNumber]);
fadeStartOffset = 1000 * Integer.parseInt(options.getString(Options.PREF_FADE_SPEED, "7"));
if (options.getBoolean(Options.PREF_FULLSCREEN, false))
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
else
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.pageNumberTextView.setVisibility(pageNumberAnim == null ? View.GONE : View.VISIBLE);
// #ifdef pro
// this.zoomLayout.setVisibility((zoomAnim == null || this.textReflowMode) ? View.GONE : View.VISIBLE);
// #endif
// #ifdef lite
this.zoomLayout.setVisibility(zoomAnim == null ? View.GONE : View.VISIBLE);
// #endif
showAnimated(true);
}
/**
* Set handlers on findNextButton and findHideButton.
*/
private void setFindButtonHandlers() {
this.findPrevButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OpenFileActivity.this.findPrev();
}
});
this.findNextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OpenFileActivity.this.findNext();
}
});
this.findHideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OpenFileActivity.this.findHide();
}
});
}
/**
* Set handlers on zoom level buttons
*/
private void setZoomButtonHandlers() {
this.zoomDownButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
pagesView.doAction(actions.getAction(Actions.LONG_ZOOM_IN));
return true;
}
});
this.zoomDownButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pagesView.doAction(actions.getAction(Actions.ZOOM_IN));
}
});
this.zoomWidthButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pagesView.zoomWidth();
}
});
this.zoomWidthButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
pagesView.zoomFit();
return true;
}
});
this.zoomUpButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pagesView.doAction(actions.getAction(Actions.ZOOM_OUT));
}
});
this.zoomUpButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
pagesView.doAction(actions.getAction(Actions.LONG_ZOOM_OUT));
return true;
}
});
}
private void startPDF(SharedPreferences options) {
this.pdf = this.getPDF();
if (!this.pdf.isValid()) {
Log.v(TAG, "Invalid PDF");
if (this.pdf.isInvalidPassword()) {
Toast.makeText(this, "This file needs a password", 4000).show();
}
else {
Toast.makeText(this, "Invalid PDF file", 4000).show();
}
return;
}
this.colorMode = Options.getColorMode(options);
this.pdfPagesProvider = new PDFPagesProvider(this, pdf,
Options.isGray(this.colorMode),
options.getBoolean(Options.PREF_OMIT_IMAGES, false),
options.getBoolean(Options.PREF_RENDER_AHEAD, true));
pagesView.setPagesProvider(pdfPagesProvider);
Bookmark b = new Bookmark(this.getApplicationContext()).open();
pagesView.setStartBookmark(b, filePath);
b.close();
}
/**
* Return PDF instance wrapping file referenced by Intent.
* Currently reads all bytes to memory, in future local files
* should be passed to native code and remote ones should
* be downloaded to local tmp dir.
* @return PDF instance
*/
private PDF getPDF() {
final Intent intent = getIntent();
Uri uri = intent.getData();
filePath = uri.getPath();
if (uri.getScheme().equals("file")) {
if (history) {
Recent recent = new Recent(this);
recent.add(0, filePath);
recent.commit();
}
return new PDF(new File(filePath), this.box);
} else if (uri.getScheme().equals("content")) {
ContentResolver cr = this.getContentResolver();
FileDescriptor fileDescriptor;
try {
fileDescriptor = cr.openFileDescriptor(uri, "r").getFileDescriptor();
} catch (FileNotFoundException e) {
throw new RuntimeException(e); // TODO: handle errors
}
return new PDF(fileDescriptor, this.box);
} else {
throw new RuntimeException("don't know how to get filename from " + uri);
}
}
// #ifdef pro
// /**
// * Handle keys.
// * Handles back key by switching off text reflow mode if enabled.
// * @param keyCode key pressed
// * @param event key press event
// */
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if (keyCode == KeyEvent.KEYCODE_BACK) {
// if (this.textReflowMode) {
// this.setTextReflowMode(false);
// return true; /* meaning we've handled event */
// }
// }
// return super.onKeyDown(keyCode, event);
// }
// #endif
/**
* Handle menu.
* @param menuItem selected menu item
* @return true if menu item was handled
*/
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem == this.aboutMenuItem) {
Intent intent = new Intent();
intent.setClass(this, AboutPDFViewActivity.class);
this.startActivity(intent);
return true;
} else if (menuItem == this.gotoPageMenuItem) {
this.showGotoPageDialog();
} else if (menuItem == this.rotateLeftMenuItem) {
this.pagesView.rotate(-1);
} else if (menuItem == this.rotateRightMenuItem) {
this.pagesView.rotate(1);
} else if (menuItem == this.findTextMenuItem) {
this.showFindDialog();
} else if (menuItem == this.clearFindTextMenuItem) {
this.clearFind();
} else if (menuItem == this.chooseFileMenuItem) {
startActivity(new Intent(this, ChooseFileActivity.class));
} else if (menuItem == this.optionsMenuItem) {
startActivity(new Intent(this, Options.class));
// #ifdef pro
// } else if (menuItem == this.tableOfContentsMenuItem) {
// Outline outline = this.pdf.getOutline();
// if (outline != null) {
// this.showTableOfContentsDialog(outline);
// } else {
// Toast.makeText(this, "Table of Contents not found", Toast.LENGTH_SHORT).show();
// }
// } else if (menuItem == this.textReflowMenuItem) {
// this.setTextReflowMode(! this.textReflowMode);
//
// #endif
}
return false;
}
private void setOrientation(int orientation) {
if (orientation != this.prevOrientation) {
Log.v(TAG, "setOrientation: "+orientation);
setRequestedOrientation(orientation);
this.prevOrientation = orientation;
}
}
/**
* Intercept touch events to handle the zoom buttons animation
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
showPageNumber(true);
if (showZoomOnScroll) {
showZoom();
}
}
return super.dispatchTouchEvent(event);
};
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
if (action == KeyEvent.ACTION_UP || action == KeyEvent.ACTION_DOWN) {
if (!eink)
showAnimated(false);
}
return super.dispatchKeyEvent(event);
};
public void showZoom() {
// #ifdef pro
// if (this.textReflowMode) {
// zoomLayout.setVisibility(View.GONE);
// return;
// }
// #endif
if (zoomAnim == null) {
zoomLayout.setVisibility(View.GONE);
return;
}
zoomLayout.clearAnimation();
zoomLayout.setVisibility(View.VISIBLE);
zoomHandler.removeCallbacks(zoomRunnable);
zoomHandler.postDelayed(zoomRunnable, fadeStartOffset);
}
private void fadeZoom() {
// #ifdef pro
// if (this.textReflowMode) {
// this.zoomLayout.setVisibility(View.GONE);
// return;
// }
// #endif
if (eink || zoomAnim == null) {
zoomLayout.setVisibility(View.GONE);
}
else {
zoomAnim.setStartOffset(0);
zoomAnim.setFillAfter(true);
zoomLayout.startAnimation(zoomAnim);
}
}
public void showPageNumber(boolean force) {
if (pageNumberAnim == null) {
pageNumberTextView.setVisibility(View.GONE);
return;
}
pageNumberTextView.setVisibility(View.VISIBLE);
String newText = ""+(this.pagesView.getCurrentPage()+1)+"/"+
this.pdfPagesProvider.getPageCount();
if (!force && newText.equals(pageNumberTextView.getText()))
return;
pageNumberTextView.setText(newText);
pageNumberTextView.clearAnimation();
pageHandler.removeCallbacks(pageRunnable);
pageHandler.postDelayed(pageRunnable, fadeStartOffset);
}
private void fadePage() {
if (eink || pageNumberAnim == null) {
pageNumberTextView.setVisibility(View.GONE);
}
else {
pageNumberAnim.setStartOffset(0);
pageNumberAnim.setFillAfter(true);
pageNumberTextView.startAnimation(pageNumberAnim);
}
}
/**
* Show zoom buttons and page number
*/
public void showAnimated(boolean alsoZoom) {
if (alsoZoom)
showZoom();
showPageNumber(true);
}
/**
* Hide the find buttons
*/
private void clearFind() {
this.currentFindResultPage = null;
this.currentFindResultNumber = null;
this.pagesView.setFindMode(false);
this.findButtonsLayout.setVisibility(View.GONE);
}
/**
* Show error message to user.
* @param message message to show
*/
private void errorMessage(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog = builder.setMessage(message).setTitle("Error").create();
dialog.show();
}
/**
* Called from menu when user want to go to specific page.
*/
private void showGotoPageDialog() {
final Dialog d = new Dialog(this);
d.setTitle(R.string.goto_page_dialog_title);
LinearLayout contents = new LinearLayout(this);
contents.setOrientation(LinearLayout.VERTICAL);
TextView label = new TextView(this);
final int pagecount = this.pdfPagesProvider.getPageCount();
label.setText("Page number from " + 1 + " to " + pagecount);
this.pageNumberInputField = new EditText(this);
this.pageNumberInputField.setInputType(InputType.TYPE_CLASS_NUMBER);
this.pageNumberInputField.setText("" + (this.pagesView.getCurrentPage() + 1));
Button goButton = new Button(this);
goButton.setText(R.string.goto_page_go_button);
goButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int pageNumber = -1;
try {
pageNumber = Integer.parseInt(OpenFileActivity.this.pageNumberInputField.getText().toString())-1;
} catch (NumberFormatException e) {
/* ignore */
}
d.dismiss();
if (pageNumber >= 0 && pageNumber < pagecount) {
OpenFileActivity.this.gotoPage(pageNumber);
} else {
OpenFileActivity.this.errorMessage("Invalid page number");
}
}
});
Button page1Button = new Button(this);
page1Button.setText(getResources().getString(R.string.page) +" 1");
page1Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
d.dismiss();
OpenFileActivity.this.gotoPage(0);
}
});
Button lastPageButton = new Button(this);
lastPageButton.setText(getResources().getString(R.string.page) +" "+pagecount);
lastPageButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
d.dismiss();
OpenFileActivity.this.gotoPage(pagecount-1);
}
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = 5;
params.rightMargin = 5;
params.bottomMargin = 2;
params.topMargin = 2;
contents.addView(label, params);
contents.addView(pageNumberInputField, params);
contents.addView(goButton, params);
contents.addView(page1Button, params);
contents.addView(lastPageButton, params);
d.setContentView(contents);
d.show();
}
private void gotoPage(int page) {
Log.i(TAG, "rewind to page " + page);
if (this.pagesView != null) {
this.pagesView.scrollToPage(page);
showAnimated(true);
}
}
/**
* Save the last page in the bookmarks
*/
private void saveLastPage() {
BookmarkEntry entry = this.pagesView.toBookmarkEntry();
Bookmark b = new Bookmark(this.getApplicationContext()).open();
b.setLast(filePath, entry);
b.close();
Log.i(TAG, "last page saved for "+filePath);
}
/**
*
* Create options menu, called by Android system.
* @param menu menu to populate
* @return true meaning that menu was populated
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.gotoPageMenuItem = menu.add(R.string.goto_page);
this.rotateRightMenuItem = menu.add(R.string.rotate_page_left);
this.rotateLeftMenuItem = menu.add(R.string.rotate_page_right);
this.clearFindTextMenuItem = menu.add(R.string.clear_find_text);
this.chooseFileMenuItem = menu.add(R.string.choose_file);
this.optionsMenuItem = menu.add(R.string.options);
/* The following appear on the second page. The find item can safely be kept
* there since it can also be accessed from the search key on most devices.
*/
// #ifdef pro
// this.tableOfContentsMenuItem = menu.add(R.string.table_of_contents);
// this.textReflowMenuItem = menu.add(R.string.text_reflow);
// #endif
this.findTextMenuItem = menu.add(R.string.find_text);
this.aboutMenuItem = menu.add(R.string.about);
return true;
}
/**
* Prepare menu contents.
* Hide or show "Clear find results" menu item depending on whether
* we're in find mode.
* @param menu menu that should be prepared
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
this.clearFindTextMenuItem.setVisible(this.pagesView.getFindMode());
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i(TAG, "onConfigurationChanged(" + newConfig + ")");
}
/**
* Show find dialog.
* Very pretty UI code ;)
*/
public void showFindDialog() {
Log.d(TAG, "find dialog...");
final Dialog dialog = new Dialog(this);
dialog.setTitle(R.string.find_dialog_title);
LinearLayout contents = new LinearLayout(this);
contents.setOrientation(LinearLayout.VERTICAL);
this.findTextInputField = new EditText(this);
this.findTextInputField.setWidth(this.pagesView.getWidth() * 80 / 100);
Button goButton = new Button(this);
goButton.setText(R.string.find_go_button);
goButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String text = OpenFileActivity.this.findTextInputField.getText().toString();
OpenFileActivity.this.findText(text);
dialog.dismiss();
}
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = 5;
params.rightMargin = 5;
params.bottomMargin = 2;
params.topMargin = 2;
contents.addView(findTextInputField, params);
contents.addView(goButton, params);
dialog.setContentView(contents);
dialog.show();
}
private void setZoomLayout(SharedPreferences options) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int colorMode = Options.getColorMode(options);
int mode = ZOOM_COLOR_NORMAL;
if (colorMode == Options.COLOR_MODE_GREEN_ON_BLACK) {
mode = ZOOM_COLOR_GREEN;
}
else if (colorMode == Options.COLOR_MODE_RED_ON_BLACK) {
mode = ZOOM_COLOR_RED;
}
// the zoom buttons
if (zoomLayout != null) {
activityLayout.removeView(zoomLayout);
}
zoomLayout = new LinearLayout(this);
zoomLayout.setOrientation(LinearLayout.HORIZONTAL);
zoomDownButton = new ImageButton(this);
zoomDownButton.setImageDrawable(getResources().getDrawable(zoomDownId[mode]));
zoomDownButton.setBackgroundColor(Color.TRANSPARENT);
zoomLayout.addView(zoomDownButton, (int)(80 * metrics.density), (int)(50 * metrics.density)); // TODO: remove hardcoded values
zoomWidthButton = new ImageButton(this);
zoomWidthButton.setImageDrawable(getResources().getDrawable(zoomWidthId[mode]));
zoomWidthButton.setBackgroundColor(Color.TRANSPARENT);
zoomLayout.addView(zoomWidthButton, (int)(58 * metrics.density), (int)(50 * metrics.density));
zoomUpButton = new ImageButton(this);
zoomUpButton.setImageDrawable(getResources().getDrawable(zoomUpId[mode]));
zoomUpButton.setBackgroundColor(Color.TRANSPARENT);
zoomLayout.addView(zoomUpButton, (int)(80 * metrics.density), (int)(50 * metrics.density));
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
setZoomButtonHandlers();
activityLayout.addView(zoomLayout,lp);
}
private void findText(String text) {
Log.d(TAG, "findText(" + text + ")");
this.findText = text;
this.find(true);
}
/**
* Called when user presses "next" button in find panel.
*/
private void findNext() {
this.find(true);
}
/**
* Called when user presses "prev" button in find panel.
*/
private void findPrev() {
this.find(false);
}
/**
* Called when user presses hide button in find panel.
*/
private void findHide() {
if (this.pagesView != null) this.pagesView.setFindMode(false);
this.currentFindResultNumber = null;
this.currentFindResultPage = null;
this.findButtonsLayout.setVisibility(View.GONE);
}
/**
* Helper class that handles search progress, search cancelling etc.
*/
static class Finder implements Runnable, DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
private OpenFileActivity parent = null;
private boolean forward;
private AlertDialog dialog = null;
private String text;
private int startingPage;
private int pageCount;
private boolean cancelled = false;
/**
* Constructor for finder.
* @param parent parent activity
*/
public Finder(OpenFileActivity parent, boolean forward) {
this.parent = parent;
this.forward = forward;
this.text = parent.findText;
this.pageCount = parent.pagesView.getPageCount();
if (parent.currentFindResultPage != null) {
if (forward) {
this.startingPage = (parent.currentFindResultPage + 1) % pageCount;
} else {
this.startingPage = (parent.currentFindResultPage - 1 + pageCount) % pageCount;
}
} else {
this.startingPage = parent.pagesView.getCurrentPage();
}
}
public void setDialog(AlertDialog dialog) {
this.dialog = dialog;
}
public void run() {
int page = -1;
this.createDialog();
this.showDialog();
for(int i = 0; i < this.pageCount; ++i) {
if (this.cancelled) {
this.dismissDialog();
return;
}
page = (startingPage + pageCount + (this.forward ? i : -i)) % this.pageCount;
Log.d(TAG, "searching on " + page);
this.updateDialog(page);
List<FindResult> findResults = this.findOnPage(page);
if (findResults != null && !findResults.isEmpty()) {
Log.d(TAG, "found something at page " + page + ": " + findResults.size() + " results");
this.dismissDialog();
this.showFindResults(findResults, page);
return;
}
}
/* TODO: show "nothing found" message */
this.dismissDialog();
}
/**
* Called by finder thread to get find results for given page.
* Routed to PDF instance.
* If result is not empty, then finder loop breaks, current find position
* is saved and find results are displayed.
* @param page page to search on
* @return results
*/
private List<FindResult> findOnPage(int page) {
if (this.text == null) throw new IllegalStateException("text cannot be null");
return this.parent.pdf.find(this.text, page);
}
private void createDialog() {
this.parent.runOnUiThread(new Runnable() {
public void run() {
String title = Finder.this.parent.getString(R.string.searching_for).replace("%1$s", Finder.this.text);
String message = Finder.this.parent.getString(R.string.page_of).replace("%1$d", String.valueOf(Finder.this.startingPage)).replace("%2$d", String.valueOf(pageCount));
AlertDialog.Builder builder = new AlertDialog.Builder(Finder.this.parent);
AlertDialog dialog = builder
.setTitle(title)
.setMessage(message)
.setCancelable(true)
.setNegativeButton(R.string.cancel, Finder.this)
.create();
dialog.setOnCancelListener(Finder.this);
Finder.this.dialog = dialog;
}
});
}
public void updateDialog(final int page) {
this.parent.runOnUiThread(new Runnable() {
public void run() {
String message = Finder.this.parent.getString(R.string.page_of).replace("%1$d", String.valueOf(page)).replace("%2$d", String.valueOf(pageCount));
Finder.this.dialog.setMessage(message);
}
});
}
public void showDialog() {
this.parent.runOnUiThread(new Runnable() {
public void run() {
Finder.this.dialog.show();
}
});
}
public void dismissDialog() {
final AlertDialog dialog = this.dialog;
this.parent.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
public void onCancel(DialogInterface dialog) {
Log.d(TAG, "onCancel(" + dialog + ")");
this.cancelled = true;
}
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "onClick(" + dialog + ")");
this.cancelled = true;
}
private void showFindResults(final List<FindResult> findResults, final int page) {
this.parent.runOnUiThread(new Runnable() {
public void run() {
int fn = Finder.this.forward ? 0 : findResults.size()-1;
Finder.this.parent.currentFindResultPage = page;
Finder.this.parent.currentFindResultNumber = fn;
Finder.this.parent.pagesView.setFindResults(findResults);
Finder.this.parent.pagesView.setFindMode(true);
Finder.this.parent.pagesView.scrollToFindResult(fn);
Finder.this.parent.findButtonsLayout.setVisibility(View.VISIBLE);
Finder.this.parent.pagesView.invalidate();
}
});
}
};
/**
* GUI for finding text.
* Used both on initial search and for "next" and "prev" searches.
* Displays dialog, handles cancel button, hides dialog as soon as
* something is found.
* @param
*/
private void find(boolean forward) {
if (this.currentFindResultPage != null) {
/* searching again */
int nextResultNum = forward ? this.currentFindResultNumber + 1 : this.currentFindResultNumber - 1;
if (nextResultNum >= 0 && nextResultNum < this.pagesView.getFindResults().size()) {
/* no need to really find - just focus on given result and exit */
this.currentFindResultNumber = nextResultNum;
this.pagesView.scrollToFindResult(nextResultNum);
this.pagesView.invalidate();
return;
}
}
/* finder handles next/prev and initial search by itself */
Finder finder = new Finder(this, forward);
Thread finderThread = new Thread(finder);
finderThread.start();
}
// #ifdef pro
// /**
// * Build and display dialog containing table of contents.
// * @param outline root of TOC tree
// */
// private void showTableOfContentsDialog(Outline outline) {
// if (outline == null) throw new IllegalArgumentException("nothing to show");
// final Dialog dialog = new Dialog(this);
// dialog.setTitle(R.string.toc_dialog_title);
// LinearLayout contents = new LinearLayout(this);
// contents.setOrientation(LinearLayout.VERTICAL);
// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// params.leftMargin = 5;
// params.rightMargin = 5;
// params.bottomMargin = 2;
// params.topMargin = 2;
// final TreeView tocTree = new TreeView(this);
// tocTree.setCacheColorHint(0);
// tocTree.setTree(outline);
// DocumentOptions documentOptions = new DocumentOptions(this.getApplicationContext());
// try {
// String openNodesString = documentOptions.getValue(this.filePath, "toc_open_nodes");
// if (openNodesString != null) {
// String[] openNodes = documentOptions.getValue(this.filePath, "toc_open_nodes").split(",");
// for(String openNode: openNodes) {
// long nodeId = -1;
// try {
// nodeId = Long.parseLong(openNode);
// } catch (NumberFormatException e) {
// Log.w(TAG, "failed to parse " + openNode + " as long: " + e);
// continue;
// }
// tocTree.open(nodeId);
// }
// }
// } finally {
// documentOptions.close();
// }
// tocTree.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Log.d(TAG, "onItemClick(" + parent + ", " + view + ", " + position + ", " + id);
// TreeView treeView = (TreeView)parent;
// TreeView.TreeNode treeNode = treeView.getTreeNodeAtPosition(position);
// Outline outline = (Outline) treeNode;
// int pageNumber = outline.page;
// OpenFileActivity.this.gotoPage(pageNumber);
// dialog.dismiss();
// }
// });
// contents.addView(tocTree, params);
// dialog.setContentView(contents);
// dialog.setOnDismissListener(new OnDismissListener() {
// public void onDismiss(DialogInterface dialog) {
// /* save state */
// Log.d(TAG, "saving TOC tree state");
// Map<Long,Boolean> state = tocTree.getState();
// String openNodes = "";
// for(long key: state.keySet()) {
// if (state.get(key)) {
// if (openNodes.length() > 0) openNodes += ",";
// openNodes += key;
// }
// }
// DocumentOptions documentOptions = new DocumentOptions(OpenFileActivity.this.getApplicationContext());
// try {
// documentOptions.setValue(filePath, "toc_open_nodes", openNodes);
// } finally {
// documentOptions.close();
// }
// }
// });
// dialog.show();
// }
//
//
// /**
// * Quick and dirty way to reduce tree to two lists for TOC dialog.
// */
// private void outlineToArrayList(List<String> list, List<Integer> pages, Outline outline, int level) {
// final class Pair {
// public Pair(int level, Outline outline) {
// this.level = level;
// this.outline = outline;
// }
// public int level;
// public Outline outline;
// };
//
// Stack<Pair> stack = new Stack<Pair>();
// stack.push(new Pair(0, outline));
//
// Log.d(TAG, "converting table of contents...");
//
// while(! stack.empty()) {
// Pair p = stack.pop();
// //Log.d(TAG, "got " + p.outline.title + " / " + p.outline.page + " from stack");
// //Log.d(TAG, " down points to: " + ((p.outline.down != null) ? p.outline.down.title : null));
// //Log.d(TAG, " next points to: " + ((p.outline.next != null) ? p.outline.next.title : null));
// String s = "";
// for(int i = 0; i < p.level; ++i) s += " ";
// s += p.outline.title;
// list.add(s);
// pages.add(p.outline.page);
// if (p.outline.next != null) {
// stack.push(new Pair(p.level, p.outline.next));
// }
// if (p.outline.down != null) {
// stack.push(new Pair(p.level + 1, p.outline.down));
// }
// }
//
// /*
// if (outline == null) return;
// String s = "";
// for(int i = 0; i < level; ++i) s += " ";
// s += outline.title;
// list.add(s);
// pages.add(outline.page);
// if (outline.down != null) this.outlineToArrayList(list, pages, outline.down, level+1);
// if (outline.next != null) this.outlineToArrayList(list, pages, outline.next, level);
// */
// }
// #endif
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
gravity[0] = 0.8f * gravity[0] + 0.2f * event.values[0];
gravity[1] = 0.8f * gravity[1] + 0.2f * event.values[1];
gravity[2] = 0.8f * gravity[2] + 0.2f * event.values[2];
float sq0 = gravity[0]*gravity[0];
float sq1 = gravity[1]*gravity[1];
float sq2 = gravity[2]*gravity[2];
gravityAge++;
if (gravityAge < 4) {
// ignore initial hiccups
return;
}
if (sq1 > 3 * (sq0 + sq2)) {
if (gravity[1] > 4)
setOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else if (gravity[1] < -4 && Integer.parseInt(Build.VERSION.SDK) >= 9)
setOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
else if (sq0 > 3 * (sq1 + sq2)) {
if (gravity[0] > 4)
setOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else if (gravity[0] < -4 && Integer.parseInt(Build.VERSION.SDK) >= 9)
setOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
}
// #ifdef pro
// /**
// * Switch text reflow mode and set this.textReflowMode by hiding and showing relevant interface elements.
// * @param mode if true ten show text reflow view, otherwise hide text reflow view
// */
// private void setTextReflowMode(boolean mode) {
// if (mode) {
// Log.d(TAG, "text reflow");
// int page = this.pagesView.getCurrentPage();
// String text = this.pdf.getText(page);
// if (text == null) text = "";
// text = text.trim();
// Log.d(TAG, "text of page " + page + " is: " + text);
// this.textReflowTextView.setText(text);
// this.textReflowScrollView.scrollTo(0,0);
// this.textReflowMenuItem.setTitle("Close Text Reflow");
// this.pagesView.setVisibility(View.GONE);
// this.zoomLayout.clearAnimation();
// this.zoomHandler.removeCallbacks(zoomRunnable);
// this.zoomLayout.setVisibility(View.GONE);
// this.textReflowView.setVisibility(View.VISIBLE);
// this.textReflowMode = true;
// } else {
// this.textReflowMenuItem.setTitle("Text Reflow");
// this.textReflowView.setVisibility(View.GONE);
// this.pagesView.setVisibility(View.VISIBLE);
// this.textReflowMode = false;
// this.showZoom();
// }
// }
//
// /**
// * Change to next or prev page.
// * Called from text reflow mode buttons.
// * @param offset if 1 then go to next page, if -1 then go to prev page, otherwise raise IllegalArgumentException
// */
// private void nextPage(int offset) {
// if (offset == 1) {
// this.pagesView.doAction(Actions.ACTION_FULL_PAGE_DOWN);
// } else if (offset == -1) {
// this.pagesView.doAction(Actions.ACTION_FULL_PAGE_UP);
// } else {
// throw new IllegalArgumentException("invalid offset: " + offset);
// }
// if (this.textReflowMode) {
// int page = this.pagesView.getCurrentPage();
// String text = this.pdf.getText(page);
// if (text == null) text = "";
// text = text.trim();
// this.textReflowTextView.setText(text);
// this.textReflowScrollView.scrollTo(0,0);
// }
// }
// #endif
}
| Java |
package cx.hell.android.pdfview;
import java.io.File;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
public class Recent extends ArrayList<String> {
/**
* Default serial version identifier because base class is serializable.
*/
private static final long serialVersionUID = 1L;
private final static int MAX_RECENT=5; /* must be at least 1 */
private final String PREF_TAG = "Recent";
private final String RECENT_PREFIX = "Recent.";
private final String RECENT_COUNT = "count";
private Context context;
public Recent(Context context) {
super();
this.context = context;
SharedPreferences pref = this.context.getSharedPreferences(PREF_TAG, 0);
int count = pref.getInt(RECENT_COUNT, 0);
for(int i=0; i<count; i++) {
String fileName = pref.getString(RECENT_PREFIX + i, "");
File file = new File(fileName);
if (file.exists()) {
add(fileName);
}
}
}
private void write() {
SharedPreferences.Editor edit =
this.context.getSharedPreferences(PREF_TAG, 0).edit();
edit.putInt(RECENT_COUNT, size());
for(int i=0; i<size(); i++) {
edit.putString(RECENT_PREFIX + i, get(i));
}
edit.commit();
}
void commit() {
for(int i=size()-1; i>=0; i--) {
for(int j=0; j<i; j++) {
if (get(i).equals(get(j))) {
remove(i);
break;
}
}
}
for(int i=size()-1; i>=MAX_RECENT; i--) {
remove(i);
}
write();
}
}
| Java |
package cx.hell.android.pdfview;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
public class Options extends PreferenceActivity implements OnSharedPreferenceChangeListener {
private final static String TAG = "cx.hell.android.pdfview";
public final static String PREF_TAG = "Options";
public final static String PREF_ZOOM_ANIMATION = "zoomAnimation";
public final static String PREF_DIRS_FIRST = "dirsFirst";
public final static String PREF_SHOW_EXTENSION = "showExtension";
public final static String PREF_ORIENTATION = "orientation";
public final static String PREF_FULLSCREEN = "fullscreen";
public final static String PREF_PAGE_ANIMATION = "pageAnimation";
public final static String PREF_FADE_SPEED = "fadeSpeed";
public final static String PREF_RENDER_AHEAD = "renderAhead";
public final static String PREF_COLOR_MODE = "colorMode";
public final static String PREF_OMIT_IMAGES = "omitImages";
public final static String PREF_VERTICAL_SCROLL_LOCK = "verticalScrollLock";
public final static String PREF_BOX = "boxType";
public final static String PREF_SIDE_MARGINS = "sideMargins2"; // sideMargins was boolean
public final static String PREF_TOP_MARGIN = "topMargin";
public final static String PREF_EXTRA_CACHE = "extraCache";
public final static String PREF_DOUBLE_TAP = "doubleTap";
public final static String PREF_VOLUME_PAIR = "volumePair";
public final static String PREF_ZOOM_PAIR = "zoomPair";
public final static String PREF_LONG_ZOOM_PAIR = "longZoomPair";
public final static String PREF_UP_DOWN_PAIR = "upDownPair";
public final static String PREF_LEFT_RIGHT_PAIR = "leftRightPair";
public final static String PREF_RIGHT_UP_DOWN_PAIR = "rightUpDownPair";
public final static String PREF_EINK = "eink";
public final static String PREF_NOOK2 = "nook2";
public final static String PREF_KEEP_ON = "keepOn";
public final static String PREF_SHOW_ZOOM_ON_SCROLL = "showZoomOnScroll";
public final static String PREF_HISTORY = "history";
public final static String PREF_TOP_BOTTOM_TAP_PAIR = "topBottomTapPair";
public final static String PREF_PREV_ORIENTATION = "prevOrientation";
public final static int PAGE_NUMBER_DISABLED = 100;
public final static int ZOOM_BUTTONS_DISABLED = 100;
public final static int DOUBLE_TAP_NONE = 0;
public final static int DOUBLE_TAP_ZOOM = 1;
public final static int DOUBLE_TAP_ZOOM_IN_OUT = 2;
public final static int PAIR_NONE = 0;
public final static int PAIR_SCREEN = 1;
public final static int PAIR_PAGE = 2;
public final static int PAIR_ZOOM_1020 = 3;
public final static int PAIR_ZOOM_1050 = 4;
public final static int PAIR_ZOOM_1100 = 5;
public final static int PAIR_ZOOM_1200 = 6;
public final static int PAIR_ZOOM_1414 = 7;
public final static int PAIR_ZOOM_2000 = 8;
public final static int PAIR_PAGE_TOP = 9;
public final static int PAIR_SCREEN_REV = 10;
public final static int PAIR_PAGE_REV = 11;
public final static int PAIR_PAGE_TOP_REV = 12;
public final static int COLOR_MODE_NORMAL = 0;
public final static int COLOR_MODE_INVERT = 1;
public final static int COLOR_MODE_GRAY = 2;
public final static int COLOR_MODE_INVERT_GRAY = 3;
public final static int COLOR_MODE_BLACK_ON_YELLOWISH = 4;
public final static int COLOR_MODE_GREEN_ON_BLACK = 5;
public final static int COLOR_MODE_RED_ON_BLACK = 6;
private final static int[] foreColors = {
Color.BLACK, Color.WHITE, Color.BLACK, Color.WHITE,
Color.BLACK, Color.GREEN, Color.RED };
private final static int[] backColors = {
Color.WHITE, Color.BLACK, Color.WHITE, Color.BLACK,
Color.rgb(239, 219, 189),
Color.BLACK, Color.BLACK };
private static final float[][] colorMatrices = {
null, /* COLOR_MODE_NORMAL */
{-1.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_INVERT */
0.0f, -1.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, -1.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 0.0f, 255.0f},
{0.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_GRAY */
0.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_INVERT_GRAY */
0.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, -1.0f, 255.0f},
{0.0f, 0.0f, 0.0f, 0.0f, 239.0f, /* COLOR_MODE_BLACK_ON_YELLOWISH */
0.0f, 0.0f, 0.0f, 0.0f, 219.0f,
0.0f, 0.0f, 0.0f, 0.0f, 189.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 0.0f, 0f, /* COLOR_MODE_GREEN_ON_BLACK */
0.0f, 0.0f, 0.0f, 0.0f, 255.0f,
0.0f, 0.0f, 0.0f, 0.0f, 0f,
0.0f, 0.0f, 0.0f, -1.0f, 255.0f},
{0.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_RED_ON_BLACK */
0.0f, 0.0f, 0.0f, 0.0f, 0f,
0.0f, 0.0f, 0.0f, 0.0f, 0f,
0.0f, 0.0f, 0.0f, -1.0f, 255.0f}
};
private Resources resources;
private static final String[] summaryKeys = { PREF_ZOOM_ANIMATION, PREF_ORIENTATION, PREF_PAGE_ANIMATION,
PREF_FADE_SPEED, PREF_COLOR_MODE, PREF_BOX, PREF_SIDE_MARGINS, PREF_TOP_MARGIN,
PREF_EXTRA_CACHE, PREF_DOUBLE_TAP, PREF_VOLUME_PAIR, PREF_ZOOM_PAIR,
PREF_LONG_ZOOM_PAIR, PREF_UP_DOWN_PAIR, PREF_LEFT_RIGHT_PAIR, PREF_RIGHT_UP_DOWN_PAIR,
PREF_TOP_BOTTOM_TAP_PAIR };
private static final int[] summaryEntryValues = { R.array.zoom_animations, R.array.orientations, R.array.page_animations,
R.array.fade_speeds, R.array.color_modes, R.array.boxes, R.array.margins, R.array.margins,
R.array.extra_caches, R.array.double_tap_actions, R.array.action_pairs, R.array.action_pairs,
R.array.action_pairs, R.array.action_pairs, R.array.action_pairs, R.array.action_pairs, R.array.action_pairs };
private static final int[] summaryEntries = { R.array.zoom_animation_labels, R.array.orientation_labels, R.array.page_animation_labels,
R.array.fade_speed_labels, R.array.color_mode_labels, R.array.box_labels, R.array.margin_labels, R.array.margin_labels,
R.array.extra_cache_labels, R.array.double_tap_action_labels, R.array.action_pair_labels, R.array.action_pair_labels,
R.array.action_pair_labels, R.array.action_pair_labels, R.array.action_pair_labels, R.array.action_pair_labels, R.array.action_pair_labels };
private static final int[] summaryDefaults = { R.string.default_zoom_animation, R.string.default_orientation, R.string.default_page_animation,
R.string.default_fade_speed, R.string.default_color_mode, R.string.default_box, R.string.default_side_margin, R.string.default_top_margin,
R.string.default_extra_cache, R.string.default_double_tap_action, R.string.default_volume_pair, R.string.default_zoom_pair,
R.string.default_long_zoom_pair, R.string.default_up_down_pair, R.string.default_left_right_pair, R.string.default_right_up_down_pair, R.string.default_top_bottom_tap_pair };
public String getString(SharedPreferences options, String key) {
return getString(this.resources, options, key);
}
public static String getString(Resources resources, SharedPreferences options, String key) {
for (int i=0; i<summaryKeys.length; i++)
if (summaryKeys[i].equals(key))
return options.getString(key, resources.getString(summaryDefaults[i]));
return options.getString(key, "");
}
public void setSummaries() {
for (int i=0; i<summaryKeys.length; i++) {
setSummary(i);
}
}
public void setSummary(String key) {
for (int i=0; i<summaryKeys.length; i++) {
if (summaryKeys[i].equals(key)) {
setSummary(i);
return;
}
}
}
public void setSummary(int i) {
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this);
Preference pref = findPreference(summaryKeys[i]);
String value = options.getString(summaryKeys[i], resources.getString(summaryDefaults[i]));
String[] valueArray = resources.getStringArray(summaryEntryValues[i]);
String[] entryArray = resources.getStringArray(summaryEntries[i]);
for (int j=0; j<valueArray.length; j++)
if (valueArray[j].equals(value)) {
pref.setSummary(entryArray[j]);
return;
}
}
public static int getIntFromString(SharedPreferences pref, String option, int def) {
return Integer.parseInt(pref.getString(option, ""+def));
}
public static float[] getColorModeMatrix(int colorMode) {
return colorMatrices[colorMode];
}
public static boolean isGray(int colorMode) {
return COLOR_MODE_GRAY <= colorMode;
}
public static int getForeColor(int colorMode) {
return foreColors[colorMode];
}
public static int getBackColor(int colorMode) {
return backColors[colorMode];
}
public static int getColorMode(SharedPreferences pref) {
return getIntFromString(pref, PREF_COLOR_MODE, 0);
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.resources = getResources();
addPreferencesFromResource(R.xml.options);
}
@Override
public void onResume() {
super.onResume();
setOrientation(this);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
setSummaries();
}
/* returns true when the calling app is responsible for monitoring */
public static boolean setOrientation(Activity activity) {
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(activity);
int orientation = Integer.parseInt(options.getString(PREF_ORIENTATION, "0"));
switch(orientation) {
case 0:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
break;
case 1:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 2:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case 3:
int prev = options.getInt(Options.PREF_PREV_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Log.v(TAG, "restoring orientation: "+prev);
activity.setRequestedOrientation(prev);
return true;
default:
break;
}
return false;
}
public void onSharedPreferenceChanged(SharedPreferences options, String key) {
setSummary(key);
}
}
| Java |
package cx.hell.android.pdfview;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
/**
* Displays "About..." info.
*/
public class AboutPDFViewActivity extends Activity {
/**
* Load about html document and display it via WebView.
* @param state saved instance state
*/
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
this.setContentView(R.layout.about);
WebView v = (WebView)this.findViewById(R.id.webview_about);
android.content.res.Resources resources = this.getResources();
InputStream aboutHtmlInputStream = new BufferedInputStream(resources.openRawResource(R.raw.about));
String aboutHtml = null;
try {
aboutHtml = StreamUtils.readStringFully(aboutHtmlInputStream);
aboutHtmlInputStream.close();
aboutHtmlInputStream = null;
resources = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
v.loadData(
aboutHtml,
"text/html",
"utf-8"
);
}
}
| Java |
package cx.hell.android.pdfview;
// #ifdef pro
// import java.lang.reflect.InvocationTargetException;
// import java.lang.reflect.Method;
//
// import android.util.Log;
// import android.view.View;
// #endif
/**
* Find newer methods using reflection and call them if found.
*/
final public class AndroidReflections {
// #ifdef pro
// private final static String TAG = "cx.hell.android.pdfview";
//
// public static void setScrollbarFadingEnabled(View view, boolean fadeScrollbars) {
// Class<View> viewClass = View.class;
// Method sfeMethod = null;
// try {
// sfeMethod = viewClass.getMethod("setScrollbarFadingEnabled", boolean.class);
// } catch (NoSuchMethodException e) {
// // nwm
// Log.d(TAG, "View.setScrollbarFadingEnabled not found");
// return;
// }
// try {
// sfeMethod.invoke(view, fadeScrollbars);
// } catch (InvocationTargetException e) {
// /* should not throw anything according to Android Reference */
// /* TODO: ui error handling */
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// /* TODO: wat do? */
// Log.w(TAG, "View.setScrollbarFadingEnabled exists, but is not visible: " + e);
// }
// }
// #endif
}
| Java |
package cx.hell.android.pdfview;
import java.io.IOException;
import java.io.InputStream;
import android.util.Log;
import android.widget.ProgressBar;
public class StreamUtils {
public static byte[] readBytesFully(InputStream i) throws IOException {
return StreamUtils.readBytesFully(i, 0, null);
}
public static byte[] readBytesFully(InputStream i, int max, ProgressBar progressBar) throws IOException {
byte buf[] = new byte[4096];
int totalReadBytes = 0;
while(true) {
int readBytes = 0;
readBytes = i.read(buf, totalReadBytes, buf.length-totalReadBytes);
if (readBytes < 0) {
// end of stream
break;
}
totalReadBytes += readBytes;
if (progressBar != null) progressBar.setProgress(totalReadBytes);
if (max > 0 && totalReadBytes > max) {
throw new IOException("Remote file is too big");
}
if (totalReadBytes == buf.length) {
// grow buf
Log.d("cx.hell.android.pdfview", "readBytesFully: growing buffer from " + buf.length + " to " + (buf.length*2));
byte newbuf[] = new byte[buf.length*2];
System.arraycopy(buf, 0, newbuf, 0, totalReadBytes);
buf = newbuf;
}
}
byte result[] = new byte[totalReadBytes];
System.arraycopy(buf, 0, result, 0, totalReadBytes);
return result;
}
public static String readStringFully(InputStream i) throws IOException {
byte[] b = StreamUtils.readBytesFully(i);
return new String(b, "utf-8");
}
}
| Java |
package cx.hell.android.pdfview;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* Minimalistic file browser.
*/
public class ChooseFileActivity extends Activity implements OnItemClickListener {
/**
* Logging tag.
*/
private final static String TAG = "cx.hell.android.pdfview";
private final static String PREF_TAG = "ChooseFileActivity";
private final static String PREF_HOME = "Home";
private final static int[] recentIds = {
R.id.recent1, R.id.recent2, R.id.recent3, R.id.recent4, R.id.recent5
};
private String currentPath;
private TextView pathTextView = null;
private ListView filesListView = null;
private FileFilter fileFilter = null;
private ArrayAdapter<FileListEntry> fileListAdapter = null;
private ArrayList<FileListEntry> fileList = null;
private Recent recent = null;
private MenuItem aboutMenuItem = null;
private MenuItem setAsHomeMenuItem = null;
private MenuItem optionsMenuItem = null;
private MenuItem deleteContextMenuItem = null;
private MenuItem removeContextMenuItem = null;
private MenuItem setAsHomeContextMenuItem = null;
private Boolean dirsFirst = true;
private Boolean showExtension = false;
private Boolean history = true;
private Boolean light = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (light)
this.setTheme(android.R.style.Theme_Light);
currentPath = getHome();
this.fileFilter = new FileFilter() {
public boolean accept(File f) {
return (f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"));
}
};
this.setContentView(R.layout.filechooser);
this.pathTextView = (TextView) this.findViewById(R.id.path);
this.filesListView = (ListView) this.findViewById(R.id.files);
final Activity activity = this;
this.fileList = new ArrayList<FileListEntry>();
this.fileListAdapter = new ArrayAdapter<FileListEntry>(this,
R.layout.onelinewithicon, fileList) {
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
v = View.inflate(activity, R.layout.onelinewithicon, null);
}
else {
v = convertView;
}
FileListEntry entry = fileList.get(position);
v.findViewById(R.id.home).setVisibility(
entry.getType() == FileListEntry.HOME ? View.VISIBLE:View.GONE );
v.findViewById(R.id.upfolder).setVisibility(
entry.isUpFolder() ? View.VISIBLE:View.GONE );
v.findViewById(R.id.folder).setVisibility(
(entry.getType() == FileListEntry.NORMAL &&
entry.isDirectory() &&
! entry.isUpFolder()) ? View.VISIBLE:View.GONE );
int r = entry.getRecentNumber();
for (int i=0; i < recentIds.length; i++) {
v.findViewById(recentIds[i]).setVisibility(
i == r ? View.VISIBLE : View.GONE);
}
TextView tv = (TextView)v.findViewById(R.id.text);
tv.setText(entry.getLabel());
tv.setTypeface(tv.getTypeface(),
entry.getType() == FileListEntry.RECENT ? Typeface.ITALIC :
Typeface.NORMAL);
return v;
}
};
this.filesListView.setAdapter(this.fileListAdapter);
this.filesListView.setOnItemClickListener(this);
registerForContextMenu(this.filesListView);
}
/**
* Reset list view and list adapter to reflect change to currentPath.
*/
private void update() {
this.pathTextView.setText(this.currentPath);
this.fileListAdapter.clear();
FileListEntry entry;
if (history && isHome(currentPath)) {
recent = new Recent(this);
for (int i = 0; i < recent.size() && i < recentIds.length; i++) {
File file = new File(recent.get(i));
entry = new FileListEntry(FileListEntry.RECENT, i, file, showExtension);
this.fileList.add(entry);
}
}
else {
recent = null;
}
entry = new FileListEntry(FileListEntry.HOME,
getResources().getString(R.string.go_home));
this.fileListAdapter.add(entry);
if (!this.currentPath.equals("/")) {
File upFolder = new File(this.currentPath).getParentFile();
entry = new FileListEntry(FileListEntry.NORMAL,
-1, upFolder, "..");
this.fileListAdapter.add(entry);
}
File files[] = new File(this.currentPath).listFiles(this.fileFilter);
if (files != null) {
try {
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
if (f1 == null) throw new RuntimeException("f1 is null inside sort");
if (f2 == null) throw new RuntimeException("f2 is null inside sort");
try {
if (dirsFirst && f1.isDirectory() != f2.isDirectory()) {
if (f1.isDirectory())
return -1;
else
return 1;
}
return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase());
} catch (NullPointerException e) {
throw new RuntimeException("failed to compare " + f1 + " and " + f2, e);
}
}
});
} catch (NullPointerException e) {
throw new RuntimeException("failed to sort file list " + files + " for path " + this.currentPath, e);
}
for (File file:files) {
entry = new FileListEntry(FileListEntry.NORMAL, -1, file, showExtension);
this.fileListAdapter.add(entry);
}
}
this.filesListView.setSelection(0);
}
public void pdfView(File f) {
Log.i(TAG, "post intent to open file " + f);
Intent intent = new Intent();
intent.setDataAndType(Uri.fromFile(f), "application/pdf");
intent.setClass(this, OpenFileActivity.class);
intent.setAction("android.intent.action.VIEW");
this.startActivity(intent);
}
private String getHome() {
String defaultHome = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = getSharedPreferences(PREF_TAG, 0).getString(PREF_HOME,
defaultHome);
if (path.length()>1 && path.endsWith("/")) {
path = path.substring(0,path.length()-2);
}
File pathFile = new File(path);
if (pathFile.exists() && pathFile.isDirectory())
return path;
else
return defaultHome;
}
@SuppressWarnings("rawtypes")
public void onItemClick(AdapterView parent, View v, int position, long id) {
FileListEntry clickedEntry = this.fileList.get(position);
File clickedFile;
if (clickedEntry.getType() == FileListEntry.HOME) {
clickedFile = new File(getHome());
}
else {
clickedFile = clickedEntry.getFile();
}
if (!clickedFile.exists())
return;
if (clickedFile.isDirectory()) {
this.currentPath = clickedFile.getAbsolutePath();
this.update();
} else {
pdfView(clickedFile);
}
}
public void setAsHome() {
SharedPreferences.Editor edit = getSharedPreferences(PREF_TAG, 0).edit();
edit.putString(PREF_HOME, currentPath);
edit.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem == this.aboutMenuItem) {
Intent intent = new Intent();
intent.setClass(this, AboutPDFViewActivity.class);
this.startActivity(intent);
return true;
}
else if (menuItem == this.setAsHomeMenuItem) {
setAsHome();
return true;
}
else if (menuItem == this.optionsMenuItem){
startActivity(new Intent(this, Options.class));
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.setAsHomeMenuItem = menu.add(R.string.set_as_home);
this.optionsMenuItem = menu.add(R.string.options);
this.aboutMenuItem = menu.add("About");
return true;
}
@Override
public void onResume() {
super.onResume();
Options.setOrientation(this); /* TODO: Handle Harder-to-change orientation */
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this);
dirsFirst = options.getBoolean(Options.PREF_DIRS_FIRST, true);
showExtension = options.getBoolean(Options.PREF_SHOW_EXTENSION, false);
history = options.getBoolean(Options.PREF_HISTORY, true);
this.update();
}
@Override
public boolean onContextItemSelected(MenuItem item) {
int position =
((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position;
if (item == deleteContextMenuItem) {
FileListEntry entry = this.fileList.get(position);
if (entry.getType() == FileListEntry.NORMAL &&
! entry.isDirectory()) {
entry.getFile().delete();
update();
}
return true;
}
else if (item == removeContextMenuItem) {
FileListEntry entry = this.fileList.get(position);
if (entry.getType() == FileListEntry.RECENT) {
recent.remove(entry.getRecentNumber());
recent.commit();
update();
}
}
else if (item == setAsHomeContextMenuItem) {
setAsHome();
}
return false;
}
private boolean isHome(String path) {
File pathFile = new File(path);
File homeFile = new File(getHome());
try {
return pathFile.getCanonicalPath().equals(homeFile.getCanonicalPath());
} catch (IOException e) {
return false;
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v == this.filesListView) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
if (info.position < 0)
return;
FileListEntry entry = this.fileList.get(info.position);
if (entry.getType() == FileListEntry.HOME) {
setAsHomeContextMenuItem = menu.add(R.string.set_as_home);
}
else if (entry.getType() == FileListEntry.RECENT) {
removeContextMenuItem = menu.add(R.string.remove_from_recent);
}
else if (! entry.isDirectory()) {
deleteContextMenuItem = menu.add(R.string.delete);
}
}
}
}
| Java |
package cx.hell.android.pdfview;
import android.graphics.Bitmap;
public class BitmapCacheValue {
public Bitmap bitmap;
/* public long millisAdded; */
public long millisAccessed;
public long priority;
public BitmapCacheValue(Bitmap bitmap, long millisAdded, long priority) {
this.bitmap = bitmap;
/* this.millisAdded = millisAdded; */
this.millisAccessed = millisAdded;
this.priority = priority;
}
}
| Java |
package cx.hell.android.pdfview;
/**
* High level user-visible application exception.
*/
public class ApplicationException extends Exception {
private static final long serialVersionUID = 3168318522532680977L;
public ApplicationException(String message) {
super(message);
}
}
| Java |
package cx.hell.android.pdfview;
// #ifdef pro
//
// import java.text.SimpleDateFormat;
// import java.util.ArrayList;
// import java.util.Collections;
// import java.util.Date;
// import java.util.HashMap;
// import java.util.Iterator;
// import java.util.List;
// import java.util.Map;
//
// import android.content.Context;
// import android.database.Cursor;
// import android.database.sqlite.SQLiteDatabase;
// import android.database.sqlite.SQLiteStatement;
// import android.util.Log;
//
// /**
// * Similar to Preferences/Options, but uses document (file) id as part of the key.
// * Implemented as database.
// * Keys can expire.
// * Each instance of this class represents a connection to database.
// */
// public class DocumentOptions {
//
// private final static String TAG = "cx.hell.android.pdfview";
//
// private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
// /**
// * Database holds at most this many documents.
// */
// private final static int MAX_ENTRIES = 1024;
//
// /**
// * Database deletes entries older than MAX_AGE_SEC seconds.
// */
// private final static long MAX_AGE_SEC = 3600 * 24 * 30 * 6; // 6 months
//
// /**
// * Map of sql statements used to create database objects.
// */
// private final static Map<String,List<String>> CREATE_TABLE_SQL;
// static {
// Map<String,List<String>> m = new HashMap<String,List<String>>();
// ArrayList<String> l = new ArrayList<String>();
// l.add("create table document_options (\n" +
// "o_id integer, o_created timestamp not null default current_timestamp,\n" +
// "o_modified timestamp not null default current_timestamp,\n" +
// "o_doc varchar(4096) not null, o_key varchar(4096) not null, o_value varchar(4096)\n" +
// ")");
// l.add("create unique index document_options_i on document_options (o_doc, o_key)");
// m.put("document_options", l);
// CREATE_TABLE_SQL = Collections.unmodifiableMap(m);
// }
//
// private final static String UPSERT_VALUE_SQL = "insert or replace into document_options\n" +
// "(o_doc, o_key, o_modified, o_created, o_value)\n" +
// "values (?, ?, current_timestamp, (select o_created from document_options where o_doc = ? and o_key = ?), ?)";
//
// /**
// * Database access.
// */
// private SQLiteDatabase sqliteDatabase = null;
//
// /**
// * Compiled statement for value update (upsert) that uses insert or replace.
// */
// private SQLiteStatement upsertValueStatement = null;
//
// /**
// * Create new database access instance.
// */
// public DocumentOptions(Context context) {
// this.sqliteDatabase = context.openOrCreateDatabase("document_options", Context.MODE_PRIVATE, null);
// this.setupDatabase();
// this.upsertValueStatement = this.sqliteDatabase.compileStatement(UPSERT_VALUE_SQL);
// }
//
// /**
// * Format date as String.
// */
// private String formatDate(Date date) {
// return DocumentOptions.dateFormat.format(date);
// }
//
// /**
// * Check if table exists.
// * @param tableName table name
// * @return true if table tableName exists
// */
// private boolean tableExists(String tableName) {
// int cnt = -1;
// Cursor curs = null;
// try {
// curs = this.sqliteDatabase.query("sqlite_master", new String[]{"name"}, "name = ?", new String[]{tableName}, null, null, null);
// cnt = curs.getCount();
// } finally {
// if (curs != null) curs.close();
// }
//
// return cnt == 1;
// }
//
// /**
// * Create table by executing create table sql statements from CREATE_TABLE_SQL.
// * @param tableName table name
// */
// private void createTable(String tableName) {
// Log.d(TAG, "creating table " + tableName);
// List<String> table_sql_statements = DocumentOptions.CREATE_TABLE_SQL.get(tableName);
// Iterator<String> i = table_sql_statements.iterator();
// while(i.hasNext()) {
// String sql = i.next();
// Log.d(TAG, "executing sql \"" + sql + "\"");
// this.sqliteDatabase.execSQL(sql);
// }
// }
//
// /**
// * Create or upgrade database schema.
// */
// private synchronized void setupDatabase() {
// if (!this.tableExists("document_options")) {
// this.createTable("document_options");
// }
// }
//
// /**
// * Save value.
// */
// public void setValue(String documentId, String key, String value) {
// this.upsertValueStatement.clearBindings();
// /* o_doc, o_key, o_doc, o_key, o_value */
// this.upsertValueStatement.bindString(1, documentId);
// this.upsertValueStatement.bindString(2, key);
// this.upsertValueStatement.bindString(3, documentId);
// this.upsertValueStatement.bindString(4, key);
// this.upsertValueStatement.bindString(5, value);
// this.upsertValueStatement.execute();
// }
//
// public void setValues(String documentId, Map<String,String> values) {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Get all preferences for given document.
// */
// public Map<String, String> getValues(String documentId) {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Get one document preference value for given documentId and given key.
// */
// public String getValue(String documentId, String key) {
// Cursor c = this.sqliteDatabase.query("document_options", new String[]{"o_value"}, "o_doc = ? and o_key = ?", new String[]{documentId, key}, null, null, null);
// try {
// int cnt = c.getCount();
// if (cnt == 0) return null;
// c.moveToFirst();
// String value = c.getString(0);
// return value;
// } finally {
// c.close();
// }
// }
//
// /**
// * Close underlying database.
// */
// public void close() {
// if (this.upsertValueStatement != null) {
// this.upsertValueStatement.close();
// this.upsertValueStatement = null;
// }
// if (this.sqliteDatabase != null) {
// this.sqliteDatabase.close();
// this.sqliteDatabase = null;
// }
// }
// }
//
// #endif | Java |
package cx.hell.android.pdfview;
import android.content.SharedPreferences;
import android.view.KeyEvent;
public class Actions {
public int zoom;
public int longZoom;
public int upDown;
public int volume;
public int leftRight;
public int rightUpDown;
public int topBottomTap;
public static final int ZOOM_IN = 1000000;
public static final int ZOOM_OUT = 1000001;
public static final int LONG_ZOOM_IN = 1000002;
public static final int LONG_ZOOM_OUT = 1000003;
public static final int TOP_TAP = 1000004;
public static final int BOTTOM_TAP = 1000005;
public final static int ACTION_NONE = 0;
public final static int ACTION_SCREEN_DOWN = 1;
public final static int ACTION_SCREEN_UP = 2;
public final static int ACTION_FULL_PAGE_DOWN = 3;
public final static int ACTION_FULL_PAGE_UP = 4;
public final static int ACTION_PREV_PAGE = 5;
public final static int ACTION_NEXT_PAGE = 6;
public final static int ACTION_ZOOM_IN_1020 = 7;
public final static int ACTION_ZOOM_IN_1050 = 8;
public final static int ACTION_ZOOM_IN_1100 = 9;
public final static int ACTION_ZOOM_IN_1200 = 10;
public final static int ACTION_ZOOM_IN_1414 = 11;
public final static int ACTION_ZOOM_IN_2000 = 12;
public final static int ACTION_ZOOM_OUT_1020 = 13;
public final static int ACTION_ZOOM_OUT_1050 = 14;
public final static int ACTION_ZOOM_OUT_1100 = 15;
public final static int ACTION_ZOOM_OUT_1200 = 16;
public final static int ACTION_ZOOM_OUT_1414 = 17;
public final static int ACTION_ZOOM_OUT_2000 = 18;
public Actions(SharedPreferences pref) {
this.zoom = Integer.parseInt(pref.getString(Options.PREF_ZOOM_PAIR, ""+Options.PAIR_ZOOM_1414));
this.longZoom = Integer.parseInt(pref.getString(Options.PREF_LONG_ZOOM_PAIR, ""+Options.PAIR_ZOOM_2000));
this.upDown = Integer.parseInt(pref.getString(Options.PREF_UP_DOWN_PAIR, ""+Options.PAIR_SCREEN));
this.volume = Integer.parseInt(pref.getString(Options.PREF_VOLUME_PAIR, ""+Options.PAIR_SCREEN));
this.leftRight = Integer.parseInt(pref.getString(Options.PREF_UP_DOWN_PAIR, ""+Options.PAIR_PAGE));
this.rightUpDown = Integer.parseInt(pref.getString(Options.PREF_RIGHT_UP_DOWN_PAIR, ""+Options.PAIR_SCREEN));
this.topBottomTap = Integer.parseInt(pref.getString(Options.PREF_TOP_BOTTOM_TAP_PAIR, ""+Options.PAIR_NONE));
}
public static float getZoomValue(int action) {
switch(action) {
case ACTION_ZOOM_IN_1020:
return 1f/1.02f;
case ACTION_ZOOM_IN_1050:
return 1f/1.05f;
case ACTION_ZOOM_IN_1100:
return 1f/1.1f;
case ACTION_ZOOM_IN_1200:
return 1f/1.2f;
case ACTION_ZOOM_IN_1414:
return 1f/1.414f;
case ACTION_ZOOM_IN_2000:
return 1f/1.414f;
case ACTION_ZOOM_OUT_1020:
return 1.02f;
case ACTION_ZOOM_OUT_1050:
return 1.05f;
case ACTION_ZOOM_OUT_1100:
return 1.1f;
case ACTION_ZOOM_OUT_1200:
return 1.2f;
case ACTION_ZOOM_OUT_1414:
return 1.414f;
case ACTION_ZOOM_OUT_2000:
return 1.414f;
default:
return -1f;
}
}
public static int getAction(int pairAction, int item) {
switch(pairAction) {
case Options.PAIR_SCREEN:
return item == 0 ? ACTION_SCREEN_UP : ACTION_SCREEN_DOWN;
case Options.PAIR_PAGE:
return item == 0 ? ACTION_FULL_PAGE_UP : ACTION_FULL_PAGE_DOWN;
case Options.PAIR_PAGE_TOP:
return item == 0 ? ACTION_PREV_PAGE : ACTION_NEXT_PAGE;
case Options.PAIR_SCREEN_REV:
return item == 1 ? ACTION_SCREEN_UP : ACTION_SCREEN_DOWN;
case Options.PAIR_PAGE_REV:
return item == 1 ? ACTION_FULL_PAGE_UP : ACTION_FULL_PAGE_DOWN;
case Options.PAIR_PAGE_TOP_REV:
return item == 1 ? ACTION_PREV_PAGE : ACTION_NEXT_PAGE;
case Options.PAIR_ZOOM_1020:
return item == 0 ? ACTION_ZOOM_OUT_1020 : ACTION_ZOOM_IN_1020;
case Options.PAIR_ZOOM_1050:
return item == 0 ? ACTION_ZOOM_OUT_1050 : ACTION_ZOOM_IN_1050;
case Options.PAIR_ZOOM_1100:
return item == 0 ? ACTION_ZOOM_OUT_1100 : ACTION_ZOOM_IN_1100;
case Options.PAIR_ZOOM_1200:
return item == 0 ? ACTION_ZOOM_OUT_1200 : ACTION_ZOOM_IN_1200;
case Options.PAIR_ZOOM_1414:
return item == 0 ? ACTION_ZOOM_OUT_1414 : ACTION_ZOOM_IN_1414;
case Options.PAIR_ZOOM_2000:
return item == 0 ? ACTION_ZOOM_OUT_2000 : ACTION_ZOOM_IN_2000;
default:
return ACTION_NONE;
}
}
public int getAction(int key) {
switch(key) {
case TOP_TAP:
return getAction(this.topBottomTap, 0);
case BOTTOM_TAP:
return getAction(this.topBottomTap, 1);
case ZOOM_OUT:
return getAction(this.zoom, 0);
case ZOOM_IN:
return getAction(this.zoom, 1);
case LONG_ZOOM_OUT:
return getAction(this.longZoom, 0);
case LONG_ZOOM_IN:
return getAction(this.longZoom, 1);
case 94:
return getAction(this.rightUpDown, 0);
case 95:
return getAction(this.rightUpDown, 1);
case KeyEvent.KEYCODE_VOLUME_UP:
return getAction(this.volume, 0);
case KeyEvent.KEYCODE_VOLUME_DOWN:
return getAction(this.volume, 1);
case 92:
case KeyEvent.KEYCODE_DPAD_UP:
return getAction(this.upDown, 0);
case 93:
case KeyEvent.KEYCODE_DPAD_DOWN:
return getAction(this.upDown, 1);
case KeyEvent.KEYCODE_DPAD_LEFT:
return getAction(this.leftRight, 0);
case KeyEvent.KEYCODE_DPAD_RIGHT:
return getAction(this.leftRight, 1);
default:
return ACTION_NONE;
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.