Created
January 2, 2012 21:30
-
-
Save jophde/1552203 to your computer and use it in GitHub Desktop.
Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.roqbot.client; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URLEncoder; | |
import java.util.List; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.message.BasicNameValuePair; | |
import org.apache.http.protocol.HTTP; | |
import org.apache.http.util.EntityUtils; | |
import org.apache.http.client.entity.UrlEncodedFormEntity; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.client.methods.HttpUriRequest; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import android.widget.Toast; | |
import org.json.JSONArray; | |
public enum Server { | |
ARTIST_DETAILS(Method.GET, "artist.details", false), | |
ARTIST_LIST(Method.GET, "artist.list", false), | |
FAVORITE_ADD(Method.POST,"favorite.add", true), | |
FAVORITE_ADD_MULTI(Method.POST, "favorite.add_multi", true), | |
FAVORITE_FACEBOOK(Method.POST,"favorite.facebook", true), | |
FAVORITE_LASTFM(Method.POST, "favorite.lastfm", true), | |
FAVORITE_PANDORA(Method.POST, "favorite.pandora", true), | |
FAVORITE_LIST(Method.POST, "favorite.list", true), | |
FAVORITE_REMOVE(Method.POST,"favorite.remove", true), | |
MUSIC_CATALOGS(Method.GET, "music.catalogs", false), | |
PLAYLIST_LIST(Method.GET, "playlist.list", true); | |
private enum Method { GET, POST } | |
private static final String URL_API = "http://roqbot.com/api/mobile_v2"; | |
private final Method method; | |
private final String a; | |
private final boolean bUser; | |
private Server(Method method, String a, boolean bUser) { | |
assert method != null; | |
assert (a!= null & a.length() > 0); | |
this.method = method; | |
this.a = a; | |
this.bUser = bUser; | |
} | |
private boolean clearCache; | |
private int cacheDuration; | |
private String cacheKey = ""; | |
public Server clear() { | |
clearCache = true; | |
return this; | |
} | |
public Server cache(int seconds) { | |
this.cacheDuration = seconds; | |
return this; | |
} | |
public JSONObject request(List<NameValuePair> params) { | |
if (params == null) throw new NullPointerException("params is null."); | |
return prepare(params); | |
} | |
private JSONObject prepare(List<NameValuePair> params) { | |
assert params != null; | |
params.add(new BasicNameValuePair("a", a)); | |
if (bUser) { | |
try { | |
JSONObject userProfile = new JSONObject(Roqbot.prefs.getString("userProfile", "")); | |
String sKey = userProfile.getString("sKey"); | |
params.add(new BasicNameValuePair("user_key", sKey)); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
if (cacheDuration > 0) { | |
for (NameValuePair param : params) { | |
cacheKey += param.getName() + "=" + param.getValue() + "&"; | |
} | |
try { | |
cacheKey = URLEncoder.encode(cacheKey, HTTP.UTF_8); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
} | |
if (clearCache) { | |
File cacheFile = new File(Roqbot.context.getCacheDir(), cacheKey); | |
cacheFile.delete(); | |
clearCache = false; | |
} | |
switch (method) { | |
case GET: | |
String url = URL_API + "?"; | |
int size = params.size(); | |
for (NameValuePair param: params) { | |
if (size > 1) { | |
url += param.getName() + "=" + param.getValue() + "&"; | |
} | |
else { | |
url += param.getName() + "=" + param.getValue(); | |
} | |
size--; | |
} | |
try { | |
URLEncoder.encode(url, HTTP.UTF_8); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
return execute(new HttpGet(url)); | |
case POST: | |
HttpPost post = new HttpPost(URL_API); | |
try { | |
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
return execute(post); | |
default: | |
return null; | |
} | |
} | |
// Returns null unless a JSONObject can be built from the returned entity. | |
private JSONObject execute(HttpUriRequest request) { | |
assert request != null; | |
// Check if data is in cache; return that data if it exists and isn't expired | |
JSONObject json = retrieve(); | |
if (json != null) | |
return json; | |
try { | |
request.addHeader("User-Agent", Roqbot.prefs.getString("userAgent", "")); | |
DefaultHttpClient client = new DefaultHttpClient(); | |
HttpResponse response = client.execute(request); | |
json = new JSONObject(EntityUtils.toString(response.getEntity())); | |
} catch(Exception e) { | |
e.printStackTrace(); | |
} | |
if (json != null) | |
if (json.has("aData") && cacheDuration > 0) | |
cache(json); | |
else if (json.has("aErrors")) { | |
// showErrors(json); | |
json = null; | |
} | |
return json; | |
} | |
// Save returned JSONObject to cache | |
private void cache(JSONObject json) { | |
assert json != null; | |
assert json.has("aErrors"); | |
try { | |
File cacheDir = Roqbot.context.getCacheDir(); | |
File cacheFile = new File(cacheDir, cacheKey); | |
if (!cacheFile.isFile()) | |
cacheFile.createNewFile(); | |
FileOutputStream outputStream = new FileOutputStream(cacheFile); | |
long iCurrentTime = System.currentTimeMillis() / 1000; | |
int iExpires = (int) iCurrentTime + cacheDuration; | |
json.put("iExpires", iExpires); | |
OutputStreamWriter osw = new OutputStreamWriter(outputStream); | |
osw.write(json.toString()); | |
osw.flush(); | |
osw.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
// Get saved JSONObject from cache if its not expired | |
private JSONObject retrieve() { | |
JSONObject json = null; | |
try { | |
File cacheDir = Roqbot.context.getCacheDir(); | |
File cacheFile = new File(cacheDir, cacheKey); | |
if (cacheFile.isFile()) { | |
FileInputStream inputStream = new FileInputStream(cacheFile); | |
StringBuilder sb = new StringBuilder(); | |
String line = ""; | |
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); | |
while ((line = reader.readLine()) != null) { | |
sb.append(line); | |
} | |
String stringContents = sb.toString(); | |
inputStream.close(); | |
JSONObject cachedJson = new JSONObject(stringContents); | |
Integer iExpires = cachedJson.getInt("iExpires"); | |
long iCurrentTime = System.currentTimeMillis() / 1000; | |
if (iCurrentTime > iExpires) | |
cacheFile.delete(); | |
else | |
json = cachedJson; | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return json; | |
} | |
private void showErrors(JSONObject json) { | |
assert json != null; | |
assert json.has("aErrors"); | |
JSONArray aErrors = json.optJSONArray("aErrors"); | |
String message = ""; | |
for (int i = 0; i < aErrors.length(); i++) { | |
message = message + "\n- " + aErrors.optJSONObject(i).optString("sText"); | |
} | |
Toast.makeText(Roqbot.context, message, Toast.LENGTH_LONG).show(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment