Skip to content

Commit

Permalink
Replacing platform HTTP client with OkHttp client
Browse files Browse the repository at this point in the history
  • Loading branch information
audaciouscode committed Nov 13, 2016
1 parent 2c88b1c commit 41a9a9b
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 96 deletions.
10 changes: 9 additions & 1 deletion build.gradle
Expand Up @@ -7,7 +7,14 @@ buildscript {
classpath 'com.android.tools.build:gradle:2.2.2'
}
}

repositories {
jcenter()
maven { url "https://oss.sonatype.org/content/groups/public/" }
}

apply plugin: 'com.android.library'

android {
sourceSets {
main {
Expand All @@ -27,9 +34,10 @@ android {

dependencies {
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.squareup.okhttp3:okhttp:3.4.2'
}

useLibrary 'org.apache.http.legacy'
// useLibrary 'org.apache.http.legacy'

defaultConfig {
versionCode 10006
Expand Down
2 changes: 1 addition & 1 deletion src/edu/northwestern/cbits/anthracite/LiberalSSLSocketFactory.java 100644 → 100755
Expand Up @@ -36,7 +36,7 @@ public void checkServerTrusted(X509Certificate[] chain,
}

public X509Certificate[] getAcceptedIssuers() {
return null;
return new X509Certificate[] {};
}
};

Expand Down
198 changes: 104 additions & 94 deletions src/edu/northwestern/cbits/anthracite/Logger.java
Expand Up @@ -5,31 +5,14 @@
import java.io.PrintStream;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.ArrayList;import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Expand All @@ -51,12 +34,26 @@
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Logger
{
private static final String EVENT_TYPE = "event_type";
Expand Down Expand Up @@ -168,6 +165,11 @@ public static Logger getInstance(Context context, String userId)
@SuppressWarnings("unchecked")
public boolean log(String event, Map<String, Object> payload)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this._context);

if (prefs.getBoolean(Logger.DEBUG, Logger.DEBUG_DEFAULT))
Log.e("LOG", "Log event: " + event);

long now = System.currentTimeMillis();

if (payload == null)
Expand All @@ -192,8 +194,6 @@ public boolean log(String event, Map<String, Object> payload)
payload.put("os_version", Build.VERSION.RELEASE);
payload.put("os", "android");

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this._context);

if (prefs.getBoolean(Logger.LOGGER_ENABLED, Logger.LOGGER_ENABLED_DEFAULT))
{
String endpointUri = prefs.getString(Logger.LOGGER_URI, null);
Expand Down Expand Up @@ -338,33 +338,81 @@ public void run()
me._uploading = true;

String endpointUri = prefs.getString(Logger.LOGGER_URI, null);
final String userAgent = prefs.getString(Logger.LOGGER_USER_AGENT, Logger.LOGGER_USER_AGENT_DEFAULT);

if (endpointUri != null)
{
try
{
URI siteUri = new URI(endpointUri);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
OkHttpClient client = null;

SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
final SSLContext sslContext = SSLContext.getInstance("SSL");

if (prefs.getBoolean(Logger.LIBERAL_SSL, Logger.LIBERAL_SSL_DEFAULT))
{
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};

socketFactory = new LiberalSSLSocketFactory(trustStore);
}
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

String userAgent = prefs.getString(Logger.LOGGER_USER_AGENT, Logger.LOGGER_USER_AGENT_DEFAULT);
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

registry.register(new Scheme("https", socketFactory, 443));
OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslSocketFactory);
builder.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.header("User-Agent", userAgent)
.build();
return chain.proceed(requestWithUserAgent);
}
});

builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});

client = builder.build();
} else {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest.newBuilder()
.header("User-Agent", userAgent)
.build();
return chain.proceed(requestWithUserAgent);
}
});

client = new OkHttpClient();
}

String selection = LogContentProvider.APP_EVENT_TRANSMITTED + " = ?";
String[] args =
{ "" + 0 };
String[] args = { "" + 0 };

Cursor c = me._context.getContentResolver().query(LogContentProvider.eventsUri(me._context), null, selection, args, LogContentProvider.APP_EVENT_RECORDED);

Expand All @@ -375,25 +423,14 @@ public void run()

for (int i = 0; i < 250 && c.moveToNext() && failCount < 8; i++)
{
AndroidHttpClient androidClient = null;

try
{
androidClient = AndroidHttpClient.newInstance(userAgent, me._context);

if (prefs.getBoolean(Logger.RAILS_MODE, Logger.RAILS_MODE_DEFAULT))
{
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(androidClient.getParams(), registry);

HttpClient httpClient = new DefaultHttpClient(mgr, androidClient.getParams());
androidClient.close();

String payload = c.getString(c.getColumnIndex(LogContentProvider.APP_EVENT_PAYLOAD));

JSONObject payloadJson = new JSONObject(payload);

HttpPost httpPost = new HttpPost(siteUri);

JSONObject submission = new JSONObject();

Date emitted = new Date((payloadJson.getLong("timestamp") * 1000));
Expand All @@ -411,25 +448,20 @@ public void run()

submission.put("event", event);

StringEntity entity = new StringEntity(submission.toString(2));
entity.setContentType("application/json");

httpPost.setEntity(entity);

httpClient.execute(httpPost);
HttpResponse response = httpClient.execute(httpPost);
Request request = new Request.Builder()
.url(endpointUri)
.post(RequestBody.create(MediaType.parse("application/json"), event.toString(2)))
.build();

HttpEntity httpEntity = response.getEntity();
Response response = client.newCall(request).execute();

String responseContent = EntityUtils.toString(httpEntity);
String responseContent = response.body().string();

if (prefs.getBoolean(Logger.DEBUG, Logger.DEBUG_DEFAULT))
Log.e("LOG", "Log upload result: " + responseContent + " (" + c.getCount() + " remaining)");

JSONObject statusJson = new JSONObject(responseContent);

mgr.shutdown();

if ((statusJson.has("status") && "success".equalsIgnoreCase(statusJson.getString("status"))) || (statusJson.has("result") && "success".equalsIgnoreCase(statusJson.getString("result"))) || (statusJson.has("invalid") && "invalid".equalsIgnoreCase(statusJson.getString("result"))))
{
ContentValues values = new ContentValues();
Expand All @@ -446,26 +478,20 @@ public void run()
}
else
{
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(androidClient.getParams(), registry);

HttpClient httpClient = new DefaultHttpClient(mgr, androidClient.getParams());
androidClient.close();

String payload = c.getString(c.getColumnIndex(LogContentProvider.APP_EVENT_PAYLOAD));

HttpPost httpPost = new HttpPost(siteUri);

List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(Logger.JSON, payload.toString()));
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.US_ASCII);
RequestBody formBody = new FormBody.Builder()
.add(Logger.JSON, payload.toString())
.build();

httpPost.setEntity(entity);
Request request = new Request.Builder()
.url(endpointUri)
.post(formBody)
.build();

HttpResponse response = httpClient.execute(httpPost);
Response response = client.newCall(request).execute();

HttpEntity httpEntity = response.getEntity();

String responseContent = EntityUtils.toString(httpEntity);
String responseContent = response.body().string();

Cursor remaining = me._context.getContentResolver().query(LogContentProvider.eventsUri(me._context), null, selection, args, LogContentProvider.APP_EVENT_RECORDED);

Expand All @@ -476,8 +502,6 @@ public void run()

JSONObject statusJson = new JSONObject(responseContent);

mgr.shutdown();

if ((statusJson.has("status") && "success".equalsIgnoreCase(statusJson.getString("status"))) || (statusJson.has("result") && "success".equalsIgnoreCase(statusJson.getString("result"))))
{
ContentValues values = new ContentValues();
Expand Down Expand Up @@ -516,11 +540,6 @@ public void run()

me.logException(e);
}
finally
{
if (androidClient != null)
androidClient.close();
}
}

c.close();
Expand All @@ -540,26 +559,19 @@ public void run()

try
{
AndroidHttpClient androidClient = AndroidHttpClient.newInstance("Anthracite Event Logger", me._context);
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(androidClient.getParams(), registry);

HttpClient httpClient = new DefaultHttpClient(mgr, androidClient.getParams());
androidClient.close();

JSONObject payloadJson = new JSONObject(payload);

HttpPost httpPost = new HttpPost(uploadUri);
Request request = new Request.Builder()
.url(endpointUri)
.post(RequestBody.create(MediaType.parse("application/json"), payloadJson.toString(2)))
.build();

StringEntity entity = new StringEntity(payloadJson.toString(2));
entity.setContentType("application/json");
Response response = client.newCall(request).execute();

httpPost.setEntity(entity);
String responseContent = response.body().string();

HttpResponse response = httpClient.execute(httpPost);

HttpEntity httpEntity = response.getEntity();

int status = response.getStatusLine().getStatusCode();
int status = response.code();

if (status >= 200 && status < 300)
{
Expand All @@ -574,9 +586,7 @@ public void run()
}

if (prefs.getBoolean(Logger.DEBUG, Logger.DEBUG_DEFAULT))
Log.e("LOG", "Upload transmission result: " + EntityUtils.toString(httpEntity) + " (" + c.getLong(c.getColumnIndex(LogContentProvider.APP_UPLOAD_ID)) + ")");

mgr.shutdown();
Log.e("LOG", "Upload transmission result: " + responseContent + " (" + c.getLong(c.getColumnIndex(LogContentProvider.APP_UPLOAD_ID)) + ")");
}
catch (UnknownHostException | NameNotFoundException e)
{
Expand Down

0 comments on commit 41a9a9b

Please sign in to comment.