Skip to content

Instantly share code, notes, and snippets.

@danpe
Created September 6, 2015 01:54
Show Gist options
  • Save danpe/9b1fcda5119156c851d7 to your computer and use it in GitHub Desktop.
Save danpe/9b1fcda5119156c851d7 to your computer and use it in GitHub Desktop.
Efficient Presistent CookieStore for Android
/**
* Copyright 2015 Dan Peleg - https://github.com/danpe
* Based on http://codereview.stackexchange.com/q/61494/6732
*
* 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.
*/
import android.os.Parcel;
import android.os.Parcelable;
import java.net.HttpCookie;
public class HttpCookieParcelable implements Parcelable {
private HttpCookie cookie;
public HttpCookieParcelable(HttpCookie cookie) {
this.cookie = cookie;
}
public HttpCookieParcelable(Parcel source) {
String name = source.readString();
String value = source.readString();
cookie = new HttpCookie(name, value);
cookie.setComment(source.readString());
cookie.setCommentURL(source.readString());
cookie.setDiscard(source.readByte() != 0);
cookie.setDomain(source.readString());
cookie.setMaxAge(source.readLong());
cookie.setPath(source.readString());
cookie.setPortlist(source.readString());
cookie.setSecure(source.readByte() != 0);
cookie.setVersion(source.readInt());
}
public HttpCookie getCookie() {
return cookie;
}
public void setCookie(HttpCookie cookie) {
this.cookie = cookie;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(cookie.getName());
dest.writeString(cookie.getValue());
dest.writeString(cookie.getComment());
dest.writeString(cookie.getCommentURL());
dest.writeByte((byte) (cookie.getDiscard() ? 1 : 0));
dest.writeString(cookie.getDomain());
dest.writeLong(cookie.getMaxAge());
dest.writeString(cookie.getPath());
dest.writeString(cookie.getPortlist());
dest.writeByte((byte) (cookie.getSecure() ? 1 : 0));
dest.writeInt(cookie.getVersion());
}
public static final Parcelable.Creator<HttpCookieParcelable> CREATOR =
new Parcelable.Creator<HttpCookieParcelable>() {
@Override
public HttpCookieParcelable[] newArray(int size) {
return new HttpCookieParcelable[size];
}
@Override
public HttpCookieParcelable createFromParcel(Parcel source) {
return new HttpCookieParcelable(source);
}
};
}
/**
* Copyright 2013 Omar Miatello - omar.miatello@justonetouch.it
* Based on http://stackoverflow.com/a/18000094/1228545
*
* 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.
*/
import android.os.Parcel;
import android.os.Parcelable;
/**
* How to use<a></>
* - Make a simple object (POJO)
* - Create a parcelable in ONE CLICK! http://devk.it/proj/parcelabler/
* - Convert to pojo <-> byte[]
*
* Example
* MyParcelable happy = new MyParcelable();
* byte[] toByte = ParcelableUtil.marshall(happy);
* // Save to DB? Send via socket?
* // ...
* // Restore from DB?
* byte[] fromByte = cursor.getBlob(c);
* MyParcelable happy = ParcelableUtil.unmarshall(fromByte, MyParcelable.CREATOR);
*/
public class ParcelableUtil {
public static byte[] marshall(Parcelable parceable) {
Parcel parcel = Parcel.obtain();
parceable.writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle(); // not sure if needed or a good idea
return bytes;
}
public static <T extends Parcelable> T unmarshall(byte[] bytes, Parcelable.Creator<T> creator) {
Parcel parcel = unmarshall(bytes);
return creator.createFromParcel(parcel);
}
public static Parcel unmarshall(byte[] bytes) {
Parcel parcel = Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0); // this is extremely important!
return parcel;
}
}
/**
* Copyright 2015 Dan Peleg - https://github.com/danpe
* Based on http://codereview.stackexchange.com/q/61494/6732
*
* 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.
*/
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.utils.ParcelableUtil;
import java.io.ByteArrayInputStream;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by danpeleg on 9/5/15.
*/
public class PersistentCookieStore implements CookieStore
{
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "CookiesPrefsFile";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final HashMap<String, ConcurrentHashMap<String, HttpCookie>> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public PersistentCookieStore(Context context)
{
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<>();
// Load any previously stored cookies into the store
Map<String, ?> prefsMap = cookiePrefs.getAll();
for(Map.Entry<String, ?> entry : prefsMap.entrySet())
{
if ((entry.getValue()) != null && !((String)entry.getValue()).startsWith(COOKIE_NAME_PREFIX))
{
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames)
{
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null)
{
HttpCookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null)
{
if(!cookies.containsKey(entry.getKey()))
cookies.put(entry.getKey(), new ConcurrentHashMap<String, HttpCookie>());
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
}
@Override
public void add(URI uri, HttpCookie cookie) {
String name = getCookieToken(uri, cookie);
// Save cookie into local store, or remove if expired
if (!cookie.hasExpired()) {
if(!cookies.containsKey(uri.getHost()))
cookies.put(uri.getHost(), new ConcurrentHashMap<String, HttpCookie>());
cookies.get(uri.getHost()).put(name, cookie);
} else {
if(cookies.containsKey(uri.toString()))
cookies.get(uri.getHost()).remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new HttpCookieParcelable(cookie)));
prefsWriter.commit();
}
protected String getCookieToken(URI uri, HttpCookie cookie) {
return cookie.getName() + cookie.getDomain();
}
@Override
public List<HttpCookie> get(URI uri) {
ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
if(cookies.containsKey(uri.getHost()))
ret.addAll(cookies.get(uri.getHost()).values());
return ret;
}
@Override
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.commit();
cookies.clear();
return true;
}
@Override
public boolean remove(URI uri, HttpCookie cookie) {
String name = getCookieToken(uri, cookie);
if(cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name)) {
cookies.get(uri.getHost()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if(cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
prefsWriter.commit();
return true;
} else {
return false;
}
}
@Override
public List<HttpCookie> getCookies() {
ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
@Override
public List<URI> getURIs() {
ArrayList<URI> ret = new ArrayList<URI>();
for (String key : cookies.keySet())
try {
ret.add(new URI(key));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return ret;
}
/**
* Serializes Cookie object into String
*
* @param cookie cookie to be encoded, can be null
* @return cookie encoded as String
*/
protected String encodeCookie(HttpCookieParcelable cookie)
{
if (cookie == null)
return null;
return byteArrayToHexString(ParcelableUtil.marshall(cookie));
}
/**
* Returns cookie decoded from cookie string
*
* @param cookieString string of cookie as returned from http request
* @return decoded cookie or null if exception occured
*/
protected HttpCookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
bytes);
HttpCookieParcelable cookieParcel = ParcelableUtil.unmarshall(bytes, HttpCookieParcelable.CREATOR);
HttpCookie cookie = cookieParcel.getCookie();
return cookie;
}
/**
* Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any
* large Base64 libraries. Can be overridden if you like!
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* Converts hex values from strings to byte array
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment