diff --git a/.gitignore b/.gitignore
index ffbcc03..7406194 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,15 @@
*/bin/
*/gen/
+# gradle
+Fontify/.gradle/*
+SparkCore/.gradle/*
+
+# IntelliJ/AndroidStudio
+*.iml
+.idea/*
+
+
# Local configuration file (sdk path, etc)
*/local.properties
@@ -24,6 +33,9 @@ SparkCore/res/values/local_build.xml
# COMMENTED OUT: we want these.
#.classpath
#.project
-
*/.metadata/
*/.settings/
+
+# Resources
+SparkCore/assets/*
+SparkCore/libs/smartconfiglib.jar
diff --git a/Fontify/AndroidManifest.xml b/Fontify/AndroidManifest.xml
index 7163c1b..0b3f576 100644
--- a/Fontify/AndroidManifest.xml
+++ b/Fontify/AndroidManifest.xml
@@ -1,13 +1,13 @@
+ package="com.danh32.fontify"
+ android:versionCode="1"
+ android:versionName="1.0">
+ android:minSdkVersion="14"
+ android:targetSdkVersion="22"/>
-
+
\ No newline at end of file
diff --git a/Fontify/build.gradle b/Fontify/build.gradle
new file mode 100644
index 0000000..07cfcf3
--- /dev/null
+++ b/Fontify/build.gradle
@@ -0,0 +1,35 @@
+buildscript {
+ repositories {
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:1.1.0'
+ }
+}
+
+
+apply plugin: 'com.android.library'
+android {
+ compileSdkVersion 21
+ buildToolsVersion '22.0.0'
+
+ defaultConfig {
+ minSdkVersion 14
+ targetSdkVersion 22
+ versionCode 1
+ versionName "1.0"
+ }
+
+ lintOptions {
+ abortOnError false
+ }
+
+ sourceSets {
+ main {
+ manifest.srcFile 'AndroidManifest.xml'
+ java.srcDirs = ['src']
+ resources.srcDirs = ['src']
+ res.srcDirs = ['res']
+ }
+ }
+}
\ No newline at end of file
diff --git a/Fontify/gradle.properties b/Fontify/gradle.properties
new file mode 100644
index 0000000..1d3591c
--- /dev/null
+++ b/Fontify/gradle.properties
@@ -0,0 +1,18 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
\ No newline at end of file
diff --git a/Fontify/project.properties b/Fontify/project.properties
index 91d2b02..362a0a3 100644
--- a/Fontify/project.properties
+++ b/Fontify/project.properties
@@ -11,5 +11,5 @@
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
-target=android-19
+target=android-22
android.library=true
diff --git a/SparkCore/AndroidManifest.xml b/SparkCore/AndroidManifest.xml
index e8adb59..bcb8215 100644
--- a/SparkCore/AndroidManifest.xml
+++ b/SparkCore/AndroidManifest.xml
@@ -1,82 +1,82 @@
+ package="io.spark.core.android"
+ android:versionCode="4"
+ android:versionName="0.1.2">
+ android:minSdkVersion="14"
+ android:targetSdkVersion="22"/>
-
-
-
-
-
+
+
+
+
+
+ android:name="io.spark.core.android.app.SparkCoreApp"
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/Theme.CustomTypefaceGradientActionBar">
+ android:name="io.spark.core.android.ui.SignUpActivity"
+ android:screenOrientation="portrait"
+ android:theme="@style/Theme.NoActionBar"
+ android:windowSoftInputMode="stateHidden|adjustResize">
-
+
-
+
+ android:name="io.spark.core.android.ui.LoginActivity"
+ android:screenOrientation="portrait"
+ android:theme="@style/Theme.NoActionBar"
+ android:windowSoftInputMode="stateHidden|adjustResize"/>
+ android:name="io.spark.core.android.ui.smartconfig.SmartConfigActivity"
+ android:screenOrientation="portrait"
+ android:theme="@style/Theme.CustomTypefaceGradientActionBar.Overlay"
+ android:windowSoftInputMode="stateHidden|adjustResize">
+ android:name="android.support.PARENT_ACTIVITY"
+ android:value="io.spark.core.android.ui.corelist.CoreListActivity"/>
+ android:name="io.spark.core.android.ui.smartconfig.NamingActivity"
+ android:screenOrientation="portrait"
+ android:theme="@style/Theme.CustomTypefaceGradientActionBar.Overlay"
+ android:windowSoftInputMode="stateHidden|adjustResize">
+ android:name="android.support.PARENT_ACTIVITY"
+ android:value=".SmartConfigActivity"/>
+ android:name="io.spark.core.android.ui.smartconfig.NoCoresFoundActivity"
+ android:screenOrientation="portrait"
+ android:theme="@style/Theme.CustomTypefaceGradientActionBar.Overlay"
+ android:windowSoftInputMode="stateHidden|adjustResize">
+ android:name="android.support.PARENT_ACTIVITY"
+ android:value=".SmartConfigActivity"/>
+ android:name="io.spark.core.android.ui.corelist.CoreListActivity"
+ android:launchMode="singleTop"
+ android:theme="@style/Theme.CustomTypefaceGradientActionBar.Overlay.NoUp"/>
+ android:name="io.spark.core.android.cloud.requestservice.SimpleSparkApiService"
+ android:exported="false"/>
+ android:name="io.spark.core.android.smartconfig.SmartConfigService"
+ android:exported="false"/>
\ No newline at end of file
diff --git a/SparkCore/build.gradle b/SparkCore/build.gradle
new file mode 100644
index 0000000..2a5ebb1
--- /dev/null
+++ b/SparkCore/build.gradle
@@ -0,0 +1,56 @@
+buildscript {
+ repositories {
+ jcenter()
+ mavenCentral()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:1.1.0'
+ }
+}
+
+apply plugin: 'com.android.application'
+
+repositories {
+ mavenCentral()
+}
+
+
+android {
+ compileSdkVersion 22
+ buildToolsVersion '22.0.0'
+
+ defaultConfig {
+ minSdkVersion 14
+ targetSdkVersion 22
+ versionCode 1
+ versionName "0.1.2"
+ }
+
+ lintOptions {
+ abortOnError false
+ }
+
+ sourceSets {
+ main {
+ manifest.srcFile 'AndroidManifest.xml'
+ java.srcDirs = ['src']
+ resources.srcDirs = ['src']
+ res.srcDirs = ['res']
+ assets.srcDirs = ['assets']
+ }
+ }
+}
+
+dependencies {
+ compile project(':Fontify')
+
+// compile fileTree(dir: 'libs', include: '*.jar')
+
+ compile files('libs/smartconfiglib.jar')
+ compile 'com.android.support:support-v4:22.0.+'
+ compile 'org.apache.commons:commons-lang3:3.0'
+ compile 'com.google.code.gson:gson:2.3.1'
+ compile 'com.google.guava:guava:18.0'
+ compile 'com.squareup.okhttp:okhttp:2.3.0'
+ compile 'com.squareup.okhttp:okhttp-urlconnection:2.3.0'
+}
\ No newline at end of file
diff --git a/SparkCore/gradle.properties b/SparkCore/gradle.properties
new file mode 100644
index 0000000..1d3591c
--- /dev/null
+++ b/SparkCore/gradle.properties
@@ -0,0 +1,18 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
\ No newline at end of file
diff --git a/SparkCore/project.properties b/SparkCore/project.properties
index fbd5841..00cf62b 100644
--- a/SparkCore/project.properties
+++ b/SparkCore/project.properties
@@ -11,5 +11,4 @@
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
-target=android-19
-android.library.reference.1=../Fontify
+target=android-22
diff --git a/SparkCore/res/values/themes.xml b/SparkCore/res/values/themes.xml
index cab7ed0..08f92a9 100644
--- a/SparkCore/res/values/themes.xml
+++ b/SparkCore/res/values/themes.xml
@@ -29,7 +29,6 @@
- @android:color/transparent
- @null
- @null
- - false
- true
- true
@@ -39,5 +38,5 @@
- @android:anim/fade_out
-->
-
+
\ No newline at end of file
diff --git a/SparkCore/src/io/spark/core/android/cloud/login/TokenTool.java b/SparkCore/src/io/spark/core/android/cloud/login/TokenTool.java
index 950c19e..c869722 100644
--- a/SparkCore/src/io/spark/core/android/cloud/login/TokenTool.java
+++ b/SparkCore/src/io/spark/core/android/cloud/login/TokenTool.java
@@ -1,7 +1,7 @@
package io.spark.core.android.cloud.login;
-import io.spark.core.android.app.AppConfig;
-import io.spark.core.android.cloud.ApiUrlHelper;
+import org.apache.http.protocol.HTTP;
+import org.solemnsilence.util.TLog;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -14,112 +14,112 @@
import java.net.HttpURLConnection;
import java.net.URL;
-import org.apache.http.protocol.HTTP;
-import org.solemnsilence.util.TLog;
-
import android.net.Uri;
import android.util.Base64;
import com.google.gson.Gson;
import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.OkUrlFactory;
+import io.spark.core.android.app.AppConfig;
+import io.spark.core.android.cloud.ApiUrlHelper;
public class TokenTool {
- private static final TLog log = new TLog(TokenTool.class);
-
- private static final String[] PATH_SEGMENTS = new String[] { "oauth", "token" };
-
-
- private final Gson gson;
- private final OkHttpClient okHttpclient;
-
- public TokenTool(Gson gson, OkHttpClient okHttpclient) {
- this.gson = gson;
- this.okHttpclient = okHttpclient;
- }
-
-
- public TokenResponse requestToken(TokenRequest tokenRequest) {
- // URL url = ApiUrlHelper.buildUrlNoVersion(PATH);
- Uri.Builder uriBuilder = ApiUrlHelper.getBaseUriBuilder();
- for (String pathSegment : PATH_SEGMENTS) {
- uriBuilder.appendPath(pathSegment);
- }
- URL url = ApiUrlHelper.convertToURL(uriBuilder);
- HttpURLConnection urlConnection = null;
- try {
- urlConnection = okHttpclient.open(url);
- return requestTokenPrivate(urlConnection, tokenRequest);
-
- } catch (Exception e) {
- log.e("Error when logging in");
- return null;
-
- } finally {
- if (urlConnection != null) {
- urlConnection.disconnect();
- }
- }
- }
-
- private TokenResponse requestTokenPrivate(HttpURLConnection urlConnection,
- TokenRequest tokenRequest) {
-
- TokenResponse response = new TokenResponse();
- int responseCode = -1;
-
- urlConnection.setDoOutput(true);
- urlConnection.setConnectTimeout(5000);
- urlConnection.setReadTimeout(15000);
- urlConnection.setRequestProperty("Authorization", getBasicAuthString());
-
- try {
- OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
- out.write(tokenRequest.asFormEncodedData().getBytes(HTTP.UTF_8));
- out.close();
-
- responseCode = urlConnection.getResponseCode();
-
- InputStream in = new BufferedInputStream(urlConnection.getInputStream());
- String responseStr = readStream(in);
- in.close();
- if (responseStr == null) {
- log.e("Error logging in, response was null. HTTP response: " + responseCode);
- return null;
- } else {
- response = gson.fromJson(responseStr, TokenResponse.class);
- }
- } catch (IOException e) {
- log.e("Error requesting token");
- }
-
- response.setStatusCode(responseCode);
- return response;
- }
-
- private String getBasicAuthString() {
- try {
- byte[] asBytes = AppConfig.getSparkTokenCreationCredentials().getBytes(HTTP.UTF_8);
- return "Basic " + Base64.encodeToString(asBytes, Base64.NO_WRAP);
- } catch (UnsupportedEncodingException e) {
- log.e("Error encoding String as UTF-8 bytes: ", e);
- return "";
- }
- }
-
- static String readStream(InputStream in) throws IOException {
- StringBuilder strBuilder = new StringBuilder();
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- for (String line = reader.readLine(); line != null; line = reader.readLine()) {
- strBuilder.append(line).append("\n");
- }
- return strBuilder.toString();
-
- } finally {
- in.close();
- }
- }
+ private static final TLog log = new TLog(TokenTool.class);
+
+ private static final String[] PATH_SEGMENTS = new String[] { "oauth", "token" };
+
+
+ private final Gson gson;
+ private final OkHttpClient okHttpclient;
+
+ public TokenTool(Gson gson, OkHttpClient okHttpclient) {
+ this.gson = gson;
+ this.okHttpclient = okHttpclient;
+ }
+
+
+ public TokenResponse requestToken(TokenRequest tokenRequest) {
+ // URL url = ApiUrlHelper.buildUrlNoVersion(PATH);
+ Uri.Builder uriBuilder = ApiUrlHelper.getBaseUriBuilder();
+ for (String pathSegment : PATH_SEGMENTS) {
+ uriBuilder.appendPath(pathSegment);
+ }
+ URL url = ApiUrlHelper.convertToURL(uriBuilder);
+ HttpURLConnection urlConnection = null;
+ try {
+ urlConnection = new OkUrlFactory(okHttpclient).open(url);
+ return requestTokenPrivate(urlConnection, tokenRequest);
+
+ } catch (Exception e) {
+ log.e("Error when logging in");
+ return null;
+
+ } finally {
+ if (urlConnection != null) {
+ urlConnection.disconnect();
+ }
+ }
+ }
+
+ private TokenResponse requestTokenPrivate(HttpURLConnection urlConnection,
+ TokenRequest tokenRequest) {
+
+ TokenResponse response = new TokenResponse();
+ int responseCode = -1;
+
+ urlConnection.setDoOutput(true);
+ urlConnection.setConnectTimeout(5000);
+ urlConnection.setReadTimeout(15000);
+ urlConnection.setRequestProperty("Authorization", getBasicAuthString());
+
+ try {
+ OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
+ out.write(tokenRequest.asFormEncodedData().getBytes(HTTP.UTF_8));
+ out.close();
+
+ responseCode = urlConnection.getResponseCode();
+
+ InputStream in = new BufferedInputStream(urlConnection.getInputStream());
+ String responseStr = readStream(in);
+ in.close();
+ if (responseStr == null) {
+ log.e("Error logging in, response was null. HTTP response: " + responseCode);
+ return null;
+ } else {
+ response = gson.fromJson(responseStr, TokenResponse.class);
+ }
+ } catch (IOException e) {
+ log.e("Error requesting token");
+ }
+
+ response.setStatusCode(responseCode);
+ return response;
+ }
+
+ private String getBasicAuthString() {
+ try {
+ byte[] asBytes = AppConfig.getSparkTokenCreationCredentials().getBytes(HTTP.UTF_8);
+ return "Basic " + Base64.encodeToString(asBytes, Base64.NO_WRAP);
+ } catch (UnsupportedEncodingException e) {
+ log.e("Error encoding String as UTF-8 bytes: ", e);
+ return "";
+ }
+ }
+
+ static String readStream(InputStream in) throws IOException {
+ StringBuilder strBuilder = new StringBuilder();
+ try {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ for (String line = reader.readLine(); line != null; line = reader.readLine()) {
+ strBuilder.append(line).append("\n");
+ }
+ return strBuilder.toString();
+
+ } finally {
+ in.close();
+ }
+ }
}
diff --git a/SparkCore/src/io/spark/core/android/cloud/requestservice/SimpleSparkApiService.java b/SparkCore/src/io/spark/core/android/cloud/requestservice/SimpleSparkApiService.java
index 8088863..aeec429 100644
--- a/SparkCore/src/io/spark/core/android/cloud/requestservice/SimpleSparkApiService.java
+++ b/SparkCore/src/io/spark/core/android/cloud/requestservice/SimpleSparkApiService.java
@@ -1,17 +1,10 @@
package io.spark.core.android.cloud.requestservice;
-import static org.solemnsilence.util.Py.list;
-import static org.solemnsilence.util.Py.truthy;
-import io.spark.core.android.R;
-import io.spark.core.android.app.AppConfig;
-import io.spark.core.android.cloud.ApiFacade;
-import io.spark.core.android.cloud.ApiFacade.ApiResponseReceiver;
-import io.spark.core.android.cloud.ApiUrlHelper;
-import io.spark.core.android.cloud.WebHelpers;
-import io.spark.core.android.cloud.login.TokenRequest;
-import io.spark.core.android.cloud.login.TokenResponse;
-import io.spark.core.android.cloud.login.TokenTool;
-import io.spark.core.android.storage.Prefs;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.utils.URLEncodedUtils;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.protocol.HTTP;
+import org.solemnsilence.util.TLog;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -21,12 +14,6 @@
import java.net.URL;
import java.util.List;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.utils.URLEncodedUtils;
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.http.protocol.HTTP;
-import org.solemnsilence.util.TLog;
-
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
@@ -36,463 +23,476 @@
import com.google.gson.Gson;
import com.squareup.okhttp.OkHttpClient;
+import com.squareup.okhttp.OkUrlFactory;
+import io.spark.core.android.R;
+import io.spark.core.android.app.AppConfig;
+import io.spark.core.android.cloud.ApiFacade;
+import io.spark.core.android.cloud.ApiFacade.ApiResponseReceiver;
+import io.spark.core.android.cloud.ApiUrlHelper;
+import io.spark.core.android.cloud.WebHelpers;
+import io.spark.core.android.cloud.login.TokenRequest;
+import io.spark.core.android.cloud.login.TokenResponse;
+import io.spark.core.android.cloud.login.TokenTool;
+import io.spark.core.android.storage.Prefs;
+
+import static org.solemnsilence.util.Py.list;
+import static org.solemnsilence.util.Py.truthy;
/**
* IntentService which performs the actual HTTP calls to talk to the Spark
* Cloud.
- *
+ *
* You probably only need to poke around in here to look at the post/put/get
* methods, or if you're debugging.
- *
+ *
*/
public class SimpleSparkApiService extends ClearableIntentService {
- /**
- * Key to retrieve the API response from the Bundle for the ResultReceiver
- */
- public static final String EXTRA_API_RESPONSE_JSON = "EXTRA_API_RESPONSE_JSON";
-
- public static final String EXTRA_RESULT_CODE = "EXTRA_RESULT_CODE";
- public static final String EXTRA_ERROR_MSG = "EXTRA_ERROR_MSG";
-
- /**
- * The status code returned when a request could not be made, i.e.: an
- * IOException was raised because a socket couldn't be opened, etc.
- */
- public static final int REQUEST_FAILURE_CODE = -1;
-
-
- /**
- * Perform a POST request with the given args -- see {@link ApiFacade} for
- * examples.
- *
- * @param ctx
- * any Context
- * @param resourcePathSegments
- * the URL path as a String array (not including version string).
- * e.g.: if your path was
- * "/v1/devices/0123456789abcdef01234567/myFunction", you'd use:
- * new String[] { "devices", "0123456789abcdef01234567",
- * "myFunction" }
- * @param formEncodingBodyData
- * the data to post, as key-value pairs to be encoded as form
- * data.
- * @param resultReceiver
- * Optional; specifies the ResultReceiver instance to use for
- * receiving the result. Using a subclass of
- * {@link ApiResponseReceiver} here is recommended for
- * simplicity.
- * @param broadcastName
- * Optional; specifies the "action" string for a broadcast to be
- * sent via {@link LocalBroadcastManager}. See
- * {@link #processResponse(Response, Intent)} for more info.
- */
- public static void post(Context ctx, String[] resourcePathSegments,
- Bundle formEncodingBodyData, ResultReceiver resultReceiver, String broadcastName) {
- ctx.startService(
- buildRestRequestIntent(ctx, resourcePathSegments, formEncodingBodyData,
- resultReceiver, broadcastName)
- .setAction(ACTION_POST));
- }
-
- /**
- * Perform a PUT request with the given args -- see {@link ApiFacade} for
- * examples
- *
- * @param ctx
- * any Context
- * @param resourcePathSegments
- * the URL path as a String array (not including version string).
- * e.g.: if your path was
- * "/v1/devices/0123456789abcdef01234567/myFunction", you'd use:
- * new String[] { "devices", "0123456789abcdef01234567",
- * "myFunction" }
- * @param params
- * the data to PUT, as key-value pairs in a Bundle
- * @param resultReceiver
- * Optional; specifies the ResultReceiver instance to use for
- * receiving the result. Using a subclass of
- * {@link ApiResponseReceiver} here is recommended for
- * simplicity.
- * @param broadcastName
- * Optional; specifies the "action" string for a broadcast to be
- * sent via {@link LocalBroadcastManager}. See
- * {@link #processResponse(Response, Intent)} for more info.
- */
- public static void put(Context ctx, String[] resourcePathSegments, Bundle params,
- ResultReceiver resultReceiver, String broadcastName) {
- ctx.startService(
- // null post data
- buildRestRequestIntent(ctx, resourcePathSegments, params, resultReceiver,
- broadcastName)
- .setAction(ACTION_PUT));
- }
-
- /**
- * Perform a GET request -- see {@link ApiFacade} for examples
- *
- * @param ctx
- * any Context
- * @param resourcePathSegments
- * the URL path as a String array (not including version string).
- * e.g.: if your path was
- * "/v1/devices/0123456789abcdef01234567/myFunction", you'd use:
- * new String[] { "devices", "0123456789abcdef01234567",
- * "myFunction" }
- * @param params
- * the URL params, as key-value pairs in a Bundle
- * @param resultReceiver
- * Optional; specifies the ResultReceiver instance to use for
- * receiving the result. Using a subclass of
- * {@link ApiResponseReceiver} here is recommended for
- * simplicity.
- * @param broadcastName
- * Optional; specifies the "action" string for a broadcast to be
- * sent via {@link LocalBroadcastManager}. See
- * {@link #processResponse(Response, Intent)} for more info.
- */
- public static void get(Context ctx, String[] resourcePathSegments, Bundle params,
- ResultReceiver resultReceiver, String broadcastName) {
- ctx.startService(
- buildRestRequestIntent(ctx, resourcePathSegments, params, resultReceiver,
- broadcastName)
- .setAction(ACTION_GET));
- }
-
-
- // Logging in is handled a little differently, since it requires a number of
- // different behaviors
- public static void logIn(Context ctx, String username, String password) {
- Intent intent = new Intent(ctx, SimpleSparkApiService.class)
- .putExtra("username", username)
- .putExtra("password", password)
- .setAction(ACTION_LOG_IN);
- ctx.startService(intent);
- }
-
-
-
- private static Intent buildRestRequestIntent(Context ctx, String[] resourcePathSegments,
- Bundle params, ResultReceiver resultReceiver, String broadcastAction) {
-
- Intent intent = new Intent(ctx, SimpleSparkApiService.class)
- .putExtra(EXTRA_RESOURCE_PATH_SEGMENTS, resourcePathSegments);
-
- if (params != null) {
- intent.putExtra(EXTRA_REQUEST_QUERY_PARAMS, params);
- }
-
- if (resultReceiver != null) {
- intent.putExtra(EXTRA_RESULT_RECEIVER, resultReceiver);
- }
-
- if (broadcastAction != null) {
- intent.putExtra(EXTRA_BROADCAST_ACTION, broadcastAction);
- }
-
- return intent;
- }
-
-
- private static final String NS = SimpleSparkApiService.class.getCanonicalName() + ".";
- private static final String ACTION_GET = NS + "ACTION_GET";
- private static final String ACTION_POST = NS + "ACTION_POST";
- private static final String ACTION_PUT = NS + "ACTION_PUT";
-
- private static final String ACTION_LOG_IN = NS + "ACTION_LOG_IN";
-
- private static final String EXTRA_RESOURCE_PATH_SEGMENTS = NS + "EXTRA_RESOURCE_PATH_SEGMENTS";
- private static final String EXTRA_REQUEST_QUERY_PARAMS = NS + "EXTRA_REQUEST_QUERY_PARAMS";
- private static final String EXTRA_RESULT_RECEIVER = NS + "EXTRA_RESULT_RECEIVER";
- private static final String EXTRA_BROADCAST_ACTION = NS + "EXTRA_BROADCAST_ACTION";
-
- Gson gson;
- Prefs prefs;
- OkHttpClient okHttpClient;
- LocalBroadcastManager localBroadcastManager;
- // IntentServices are always single-threaded, so it's safe to just keep
- // re-using the same output stream for capturing responses
- ByteArrayOutputStream reusableResponseStream = new ByteArrayOutputStream(8192);
- TokenTool tokenTool;
-
- boolean authFailed = false;
- String authToken = null;
-
-
-
- public SimpleSparkApiService() {
- super(SimpleSparkApiService.class.getSimpleName());
- gson = WebHelpers.getGson();
- okHttpClient = WebHelpers.getOkClient();
- tokenTool = new TokenTool(gson, okHttpClient);
- prefs = Prefs.getInstance();
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- localBroadcastManager = LocalBroadcastManager.getInstance(this);
- // Don't redeliver intents, it's not critical for this app, and it's a
- // great way to cause crash loops if something is wrong with your
- // Intents.
- setIntentRedelivery(false);
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- if (ACTION_LOG_IN.equals(intent.getAction())) {
- String username = intent.getStringExtra("username");
- String password = intent.getStringExtra("password");
- logIn(username, password);
- return;
- }
-
- String token = getAuthToken();
- if (!truthy(token)) {
- log.d("Making request without token...");
- }
-
- Bundle extras = intent.getExtras();
- String action = intent.getAction();
- Response response = null;
-
- if (ACTION_GET.equals(action)) {
- URL url = buildGetUrl(extras, token);
- response = get(url);
-
- } else if (ACTION_POST.equals(action)) {
- URL url = buildPostUrl(extras, token);
- String postData = getPostData(extras);
- response = post(url, postData);
-
- } else if (ACTION_PUT.equals(action)) {
- URL url = buildPutUrl(extras);
- Bundle queryParams = extras.getBundle(EXTRA_REQUEST_QUERY_PARAMS);
- queryParams.putString(AppConfig.getApiParamAccessToken(), token);
- String putString = URLEncodedUtils.format(
- bundleParamsToNameValuePairs(queryParams),
- HTTP.UTF_8);
- response = put(url, putString);
-
- } else {
- log.wtf("Received intent with unrecognized action: " + action);
- }
-
- processResponse(response, intent);
- }
-
- // returns the status code of the request
- private int logIn(String username, String password) {
- TokenRequest tokenRequest = new TokenRequest(username, password);
- TokenResponse response = tokenTool.requestToken(tokenRequest);
- log.d("Token response received, status code: " + response.getStatusCode());
-
- Intent bcast = new Intent(ApiFacade.BROADCAST_LOG_IN_FINISHED);
- if (response.getStatusCode() == -1 || response.getStatusCode() >= 300) {
- log.e("Error requesting token: " + response.errorDescription);
- bcast.putExtra(EXTRA_ERROR_MSG, response.errorDescription);
- bcast.putExtra(EXTRA_RESULT_CODE, response.getStatusCode());
-
- } else {
- prefs.saveUsername(username);
- prefs.saveCompletedFirstLogin(true);
- prefs.saveToken(response.accessToken);
- bcast.putExtra(EXTRA_RESULT_CODE, response.getStatusCode());
- authFailed = false;
- }
- localBroadcastManager.sendBroadcast(bcast);
-
- return response.getStatusCode();
- }
-
- void processResponse(Response response, Intent intent) {
- Bundle extras = intent.getExtras();
-
- Bundle resultBundle = new Bundle();
- int resultCode = REQUEST_FAILURE_CODE;
-
- String error = getString(R.string.error_communicating_with_server);
- if (response != null) {
- resultCode = response.responseCode;
- resultBundle.putString(EXTRA_API_RESPONSE_JSON, response.apiResponse);
- resultBundle.putInt(EXTRA_RESULT_CODE, resultCode);
- } else {
- resultBundle.putString(EXTRA_ERROR_MSG, error);
- }
-
- ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);
- if (receiver != null) {
- receiver.send(resultCode, resultBundle);
- }
-
- String bcastAction = extras.getString(EXTRA_BROADCAST_ACTION);
- if (truthy(bcastAction)) {
- Intent responseIntent = new Intent()
- .replaceExtras(resultBundle)
- .setAction(bcastAction);
- localBroadcastManager.sendBroadcast(responseIntent);
- }
- }
-
- Response post(URL url, String stringData) {
- return performRequestWithInputData(url, "POST", stringData);
- }
-
- Response put(URL url, String stringData) {
- return performRequestWithInputData(url, "PUT", stringData);
- }
-
- Response performRequestWithInputData(URL url, String httpMethod, String stringData) {
- HttpURLConnection connection = okHttpClient.open(url);
- OutputStream out = null;
- InputStream in = null;
- int responseCode = -1;
- String responseData = "";
-
- try {
- try {
- connection.setRequestMethod(httpMethod);
- connection.setDoOutput(true);
-
- out = connection.getOutputStream();
- out.write(stringData.getBytes(HTTP.UTF_8));
- out.close();
-
- responseCode = connection.getResponseCode();
-
- in = connection.getInputStream();
- responseData = readAsUtf8String(in);
-
- } finally {
- // Clean up.
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- }
- } catch (IOException e) {
- log.e("Error trying to make " + connection.getRequestMethod() + " request");
- }
-
- return new Response(responseCode, responseData);
- }
-
- Response get(URL url) {
- HttpURLConnection connection = okHttpClient.open(url);
- InputStream in = null;
- int responseCode = -1;
- String responseData = "";
- // Java I/O throws *exception*al parties!
- try {
- try {
- responseCode = connection.getResponseCode();
- in = connection.getInputStream();
- responseData = readAsUtf8String(in);
- } finally {
- if (in != null) {
- in.close();
- }
- }
- } catch (IOException e) {
- log.e("Error trying to make GET request");
- }
-
- return new Response(responseCode, responseData);
- }
-
- URL buildGetUrl(Bundle intentExtras, String token) {
- Uri.Builder uriBuilder = ApiUrlHelper.buildUri(token,
- intentExtras.getStringArray(EXTRA_RESOURCE_PATH_SEGMENTS));
- Bundle queryParams = intentExtras.getBundle(EXTRA_REQUEST_QUERY_PARAMS);
- if (queryParams != null) {
- for (NameValuePair param : bundleParamsToNameValuePairs(queryParams)) {
- uriBuilder.appendQueryParameter(param.getName(), param.getValue());
- }
- }
-
- return ApiUrlHelper.convertToURL(uriBuilder);
- }
-
- URL buildPutUrl(Bundle intentExtras) {
- Uri.Builder uriBuilder = ApiUrlHelper.buildUri(null,
- intentExtras.getStringArray(EXTRA_RESOURCE_PATH_SEGMENTS));
- return ApiUrlHelper.convertToURL(uriBuilder);
- }
-
- URL buildPostUrl(Bundle intentExtras, String token) {
- Uri.Builder uriBuilder = ApiUrlHelper.buildUri(token,
- intentExtras.getStringArray(EXTRA_RESOURCE_PATH_SEGMENTS));
- return ApiUrlHelper.convertToURL(uriBuilder);
- }
-
-
- List bundleParamsToNameValuePairs(Bundle params) {
- List paramList = list();
- for (String key : params.keySet()) {
- Object value = params.get(key);
- if (value != null) {
- paramList.add(new BasicNameValuePair(key, value.toString()));
- }
- }
- return paramList;
- }
-
- String getPostData(Bundle intentExtras) {
- String postString = "";
-
- Bundle queryParams = intentExtras.getBundle(EXTRA_REQUEST_QUERY_PARAMS);
-
- if (queryParams != null) {
- String putString = URLEncodedUtils.format(
- bundleParamsToNameValuePairs(queryParams),
- HTTP.UTF_8);
- postString = putString;
- }
-
- return postString;
- }
-
- String readAsUtf8String(InputStream in) throws IOException {
- reusableResponseStream.reset();
- byte[] buffer = new byte[1024];
- for (int count; (count = in.read(buffer)) != -1;) {
- reusableResponseStream.write(buffer, 0, count);
- }
- return reusableResponseStream.toString(HTTP.UTF_8);
- }
-
-
- String getAuthToken() {
- if (!truthy(authToken)) {
- authToken = prefs.getToken();
- }
- return authToken;
- }
-
-
- private static class Response {
-
- public final int responseCode;
- public final String apiResponse;
-
- public Response(int responseCode, String apiResponse) {
- this.responseCode = responseCode;
- this.apiResponse = apiResponse;
- }
-
- @Override
- public String toString() {
- return "RequestResult [resultCode=" + responseCode + ", apiResponse=" + apiResponse
- + "]";
- }
-
- }
-
-
- private static final TLog log = new TLog(SimpleSparkApiService.class);
+ /**
+ * Key to retrieve the API response from the Bundle for the ResultReceiver
+ */
+ public static final String EXTRA_API_RESPONSE_JSON = "EXTRA_API_RESPONSE_JSON";
+
+ public static final String EXTRA_RESULT_CODE = "EXTRA_RESULT_CODE";
+ public static final String EXTRA_ERROR_MSG = "EXTRA_ERROR_MSG";
+
+ /**
+ * The status code returned when a request could not be made, i.e.: an
+ * IOException was raised because a socket couldn't be opened, etc.
+ */
+ public static final int REQUEST_FAILURE_CODE = -1;
+
+
+ /**
+ * Perform a POST request with the given args -- see {@link ApiFacade} for
+ * examples.
+ *
+ * @param ctx
+ * any Context
+ * @param resourcePathSegments
+ * the URL path as a String array (not including version string).
+ * e.g.: if your path was
+ * "/v1/devices/0123456789abcdef01234567/myFunction", you'd use:
+ * new String[] { "devices", "0123456789abcdef01234567",
+ * "myFunction" }
+ * @param formEncodingBodyData
+ * the data to post, as key-value pairs to be encoded as form
+ * data.
+ * @param resultReceiver
+ * Optional; specifies the ResultReceiver instance to use for
+ * receiving the result. Using a subclass of
+ * {@link ApiResponseReceiver} here is recommended for
+ * simplicity.
+ * @param broadcastName
+ * Optional; specifies the "action" string for a broadcast to be
+ * sent via {@link LocalBroadcastManager}. See
+ * {@link #processResponse(Response, Intent)} for more info.
+ */
+ public static void post(Context ctx, String[] resourcePathSegments,
+ Bundle formEncodingBodyData, ResultReceiver resultReceiver, String broadcastName) {
+ ctx.startService(
+ buildRestRequestIntent(ctx, resourcePathSegments, formEncodingBodyData,
+ resultReceiver, broadcastName)
+ .setAction(ACTION_POST));
+ }
+
+ /**
+ * Perform a PUT request with the given args -- see {@link ApiFacade} for
+ * examples
+ *
+ * @param ctx
+ * any Context
+ * @param resourcePathSegments
+ * the URL path as a String array (not including version string).
+ * e.g.: if your path was
+ * "/v1/devices/0123456789abcdef01234567/myFunction", you'd use:
+ * new String[] { "devices", "0123456789abcdef01234567",
+ * "myFunction" }
+ * @param params
+ * the data to PUT, as key-value pairs in a Bundle
+ * @param resultReceiver
+ * Optional; specifies the ResultReceiver instance to use for
+ * receiving the result. Using a subclass of
+ * {@link ApiResponseReceiver} here is recommended for
+ * simplicity.
+ * @param broadcastName
+ * Optional; specifies the "action" string for a broadcast to be
+ * sent via {@link LocalBroadcastManager}. See
+ * {@link #processResponse(Response, Intent)} for more info.
+ */
+ public static void put(Context ctx, String[] resourcePathSegments, Bundle params,
+ ResultReceiver resultReceiver, String broadcastName) {
+ ctx.startService(
+ // null post data
+ buildRestRequestIntent(ctx, resourcePathSegments, params, resultReceiver,
+ broadcastName)
+ .setAction(ACTION_PUT));
+ }
+
+ /**
+ * Perform a GET request -- see {@link ApiFacade} for examples
+ *
+ * @param ctx
+ * any Context
+ * @param resourcePathSegments
+ * the URL path as a String array (not including version string).
+ * e.g.: if your path was
+ * "/v1/devices/0123456789abcdef01234567/myFunction", you'd use:
+ * new String[] { "devices", "0123456789abcdef01234567",
+ * "myFunction" }
+ * @param params
+ * the URL params, as key-value pairs in a Bundle
+ * @param resultReceiver
+ * Optional; specifies the ResultReceiver instance to use for
+ * receiving the result. Using a subclass of
+ * {@link ApiResponseReceiver} here is recommended for
+ * simplicity.
+ * @param broadcastName
+ * Optional; specifies the "action" string for a broadcast to be
+ * sent via {@link LocalBroadcastManager}. See
+ * {@link #processResponse(Response, Intent)} for more info.
+ */
+ public static void get(Context ctx, String[] resourcePathSegments, Bundle params,
+ ResultReceiver resultReceiver, String broadcastName) {
+ ctx.startService(
+ buildRestRequestIntent(ctx, resourcePathSegments, params, resultReceiver,
+ broadcastName)
+ .setAction(ACTION_GET));
+ }
+
+
+ // Logging in is handled a little differently, since it requires a number of
+ // different behaviors
+ public static void logIn(Context ctx, String username, String password) {
+ Intent intent = new Intent(ctx, SimpleSparkApiService.class)
+ .putExtra("username", username)
+ .putExtra("password", password)
+ .setAction(ACTION_LOG_IN);
+ ctx.startService(intent);
+ }
+
+
+ private static Intent buildRestRequestIntent(Context ctx, String[] resourcePathSegments,
+ Bundle params, ResultReceiver resultReceiver, String
+ broadcastAction) {
+
+ Intent intent = new Intent(ctx, SimpleSparkApiService.class)
+ .putExtra(EXTRA_RESOURCE_PATH_SEGMENTS, resourcePathSegments);
+
+ if (params != null) {
+ intent.putExtra(EXTRA_REQUEST_QUERY_PARAMS, params);
+ }
+
+ if (resultReceiver != null) {
+ intent.putExtra(EXTRA_RESULT_RECEIVER, resultReceiver);
+ }
+
+ if (broadcastAction != null) {
+ intent.putExtra(EXTRA_BROADCAST_ACTION, broadcastAction);
+ }
+
+ return intent;
+ }
+
+
+ private static final String NS = SimpleSparkApiService.class.getCanonicalName() + ".";
+ private static final String ACTION_GET = NS + "ACTION_GET";
+ private static final String ACTION_POST = NS + "ACTION_POST";
+ private static final String ACTION_PUT = NS + "ACTION_PUT";
+
+ private static final String ACTION_LOG_IN = NS + "ACTION_LOG_IN";
+
+ private static final String EXTRA_RESOURCE_PATH_SEGMENTS = NS + "EXTRA_RESOURCE_PATH_SEGMENTS";
+ private static final String EXTRA_REQUEST_QUERY_PARAMS = NS + "EXTRA_REQUEST_QUERY_PARAMS";
+ private static final String EXTRA_RESULT_RECEIVER = NS + "EXTRA_RESULT_RECEIVER";
+ private static final String EXTRA_BROADCAST_ACTION = NS + "EXTRA_BROADCAST_ACTION";
+
+ Gson gson;
+ Prefs prefs;
+ OkHttpClient okHttpClient;
+ LocalBroadcastManager localBroadcastManager;
+ // IntentServices are always single-threaded, so it's safe to just keep
+ // re-using the same output stream for capturing responses
+ ByteArrayOutputStream reusableResponseStream = new ByteArrayOutputStream(8192);
+ TokenTool tokenTool;
+
+ boolean authFailed = false;
+ String authToken = null;
+
+
+ public SimpleSparkApiService() {
+ super(SimpleSparkApiService.class.getSimpleName());
+ gson = WebHelpers.getGson();
+ okHttpClient = WebHelpers.getOkClient();
+ tokenTool = new TokenTool(gson, okHttpClient);
+ prefs = Prefs.getInstance();
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ localBroadcastManager = LocalBroadcastManager.getInstance(this);
+ // Don't redeliver intents, it's not critical for this app, and it's a
+ // great way to cause crash loops if something is wrong with your
+ // Intents.
+ setIntentRedelivery(false);
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ if (ACTION_LOG_IN.equals(intent.getAction())) {
+ String username = intent.getStringExtra("username");
+ String password = intent.getStringExtra("password");
+ logIn(username, password);
+ return;
+ }
+
+ String token = getAuthToken();
+ if (!truthy(token)) {
+ log.d("Making request without token...");
+ }
+
+ Bundle extras = intent.getExtras();
+ String action = intent.getAction();
+ Response response = null;
+
+ if (ACTION_GET.equals(action)) {
+ URL url = buildGetUrl(extras, token);
+ response = get(url);
+
+ } else if (ACTION_POST.equals(action)) {
+ URL url = buildPostUrl(extras, token);
+ String postData = getPostData(extras);
+ response = post(url, postData);
+
+ } else if (ACTION_PUT.equals(action)) {
+ URL url = buildPutUrl(extras);
+ Bundle queryParams = extras.getBundle(EXTRA_REQUEST_QUERY_PARAMS);
+ queryParams.putString(AppConfig.getApiParamAccessToken(), token);
+ String putString = URLEncodedUtils.format(
+ bundleParamsToNameValuePairs(queryParams),
+ HTTP.UTF_8);
+ response = put(url, putString);
+
+ } else {
+ log.wtf("Received intent with unrecognized action: " + action);
+ }
+
+ processResponse(response, intent);
+ }
+
+ // returns the status code of the request
+ private int logIn(String username, String password) {
+ TokenRequest tokenRequest = new TokenRequest(username, password);
+ TokenResponse response = tokenTool.requestToken(tokenRequest);
+ log.d("Token response received, status code: " + response.getStatusCode());
+
+ Intent bcast = new Intent(ApiFacade.BROADCAST_LOG_IN_FINISHED);
+ if (response.getStatusCode() == -1 || response.getStatusCode() >= 300) {
+ log.e("Error requesting token: " + response.errorDescription);
+ bcast.putExtra(EXTRA_ERROR_MSG, response.errorDescription);
+ bcast.putExtra(EXTRA_RESULT_CODE, response.getStatusCode());
+
+ } else {
+ prefs.saveUsername(username);
+ prefs.saveCompletedFirstLogin(true);
+ prefs.saveToken(response.accessToken);
+ bcast.putExtra(EXTRA_RESULT_CODE, response.getStatusCode());
+ authFailed = false;
+ }
+ localBroadcastManager.sendBroadcast(bcast);
+
+ return response.getStatusCode();
+ }
+
+ void processResponse(Response response, Intent intent) {
+ Bundle extras = intent.getExtras();
+
+ Bundle resultBundle = new Bundle();
+ int resultCode = REQUEST_FAILURE_CODE;
+
+ String error = getString(R.string.error_communicating_with_server);
+ if (response != null) {
+ resultCode = response.responseCode;
+ resultBundle.putString(EXTRA_API_RESPONSE_JSON, response.apiResponse);
+ resultBundle.putInt(EXTRA_RESULT_CODE, resultCode);
+ } else {
+ resultBundle.putString(EXTRA_ERROR_MSG, error);
+ }
+
+ ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);
+ if (receiver != null) {
+ receiver.send(resultCode, resultBundle);
+ }
+
+ String bcastAction = extras.getString(EXTRA_BROADCAST_ACTION);
+ if (truthy(bcastAction)) {
+ Intent responseIntent = new Intent()
+ .replaceExtras(resultBundle)
+ .setAction(bcastAction);
+ localBroadcastManager.sendBroadcast(responseIntent);
+ }
+ }
+
+ Response post(URL url, String stringData) {
+ return performRequestWithInputData(url, "POST", stringData);
+ }
+
+ Response put(URL url, String stringData) {
+ return performRequestWithInputData(url, "PUT", stringData);
+ }
+
+ Response performRequestWithInputData(URL url, String httpMethod, String stringData) {
+ HttpURLConnection connection = new OkUrlFactory(okHttpClient).open(url);
+ OutputStream out = null;
+ InputStream in = null;
+ int responseCode = -1;
+ String responseData = "";
+
+ try {
+ try {
+ connection.setRequestMethod(httpMethod);
+ connection.setDoOutput(true);
+
+ out = connection.getOutputStream();
+ out.write(stringData.getBytes(HTTP.UTF_8));
+ out.close();
+
+ responseCode = connection.getResponseCode();
+
+ in = connection.getInputStream();
+ responseData = readAsUtf8String(in);
+
+ } finally {
+ // Clean up.
+ if (out != null) {
+ out.close();
+ }
+ if (in != null) {
+ in.close();
+ }
+ }
+ } catch (IOException e) {
+ log.e("Error trying to make " + connection.getRequestMethod() + " request");
+ }
+
+ return new Response(responseCode, responseData);
+ }
+
+ Response get(URL url) {
+ HttpURLConnection connection = new OkUrlFactory(okHttpClient).open(url);
+ InputStream in = null;
+ int responseCode = -1;
+ String responseData = "";
+ // Java I/O throws *exception*al parties!
+ try {
+ try {
+ responseCode = connection.getResponseCode();
+ in = connection.getInputStream();
+ responseData = readAsUtf8String(in);
+ } finally {
+ if (in != null) {
+ in.close();
+ }
+ }
+ } catch (IOException e) {
+ log.e("Error trying to make GET request");
+ }
+
+ return new Response(responseCode, responseData);
+ }
+
+ URL buildGetUrl(Bundle intentExtras, String token) {
+ Uri.Builder uriBuilder = ApiUrlHelper.buildUri(token,
+ intentExtras.getStringArray(EXTRA_RESOURCE_PATH_SEGMENTS));
+ Bundle queryParams = intentExtras.getBundle(EXTRA_REQUEST_QUERY_PARAMS);
+ if (queryParams != null) {
+ for (NameValuePair param : bundleParamsToNameValuePairs(queryParams)) {
+ uriBuilder.appendQueryParameter(param.getName(), param.getValue());
+ }
+ }
+
+ return ApiUrlHelper.convertToURL(uriBuilder);
+ }
+
+ URL buildPutUrl(Bundle intentExtras) {
+ Uri.Builder uriBuilder = ApiUrlHelper.buildUri(null,
+ intentExtras.getStringArray(EXTRA_RESOURCE_PATH_SEGMENTS));
+ return ApiUrlHelper.convertToURL(uriBuilder);
+ }
+
+ URL buildPostUrl(Bundle intentExtras, String token) {
+ Uri.Builder uriBuilder = ApiUrlHelper.buildUri(token,
+ intentExtras.getStringArray(EXTRA_RESOURCE_PATH_SEGMENTS));
+ return ApiUrlHelper.convertToURL(uriBuilder);
+ }
+
+
+ List bundleParamsToNameValuePairs(Bundle params) {
+ List paramList = list();
+ for (String key : params.keySet()) {
+ Object value = params.get(key);
+ if (value != null) {
+ paramList.add(new BasicNameValuePair(key, value.toString()));
+ }
+ }
+ return paramList;
+ }
+
+ String getPostData(Bundle intentExtras) {
+ String postString = "";
+
+ Bundle queryParams = intentExtras.getBundle(EXTRA_REQUEST_QUERY_PARAMS);
+
+ if (queryParams != null) {
+ String putString = URLEncodedUtils.format(
+ bundleParamsToNameValuePairs(queryParams),
+ HTTP.UTF_8);
+ postString = putString;
+ }
+
+ return postString;
+ }
+
+ String readAsUtf8String(InputStream in) throws IOException {
+ reusableResponseStream.reset();
+ byte[] buffer = new byte[1024];
+ for (int count; (count = in.read(buffer)) != -1; ) {
+ reusableResponseStream.write(buffer, 0, count);
+ }
+ return reusableResponseStream.toString(HTTP.UTF_8);
+ }
+
+
+ String getAuthToken() {
+ if (!truthy(authToken)) {
+ authToken = prefs.getToken();
+ }
+ return authToken;
+ }
+
+
+ private static class Response {
+
+ public final int responseCode;
+ public final String apiResponse;
+
+ public Response(int responseCode, String apiResponse) {
+ this.responseCode = responseCode;
+ this.apiResponse = apiResponse;
+ }
+
+ @Override
+ public String toString() {
+ return "RequestResult [resultCode=" + responseCode + ", apiResponse=" + apiResponse
+ + "]";
+ }
+
+ }
+
+
+ private static final TLog log = new TLog(SimpleSparkApiService.class);
}
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..e69de29
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..1d3591c
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,18 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..8c0fb64
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..0c71e76
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Wed Apr 10 15:27:10 PDT 2013
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+ [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..d346f35
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1 @@
+include ':Fontify', ':SparkCore'