aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/network/Network.java
diff options
context:
space:
mode:
Diffstat (limited to 'main/src/cgeo/geocaching/network/Network.java')
-rw-r--r--main/src/cgeo/geocaching/network/Network.java83
1 files changed, 46 insertions, 37 deletions
diff --git a/main/src/cgeo/geocaching/network/Network.java b/main/src/cgeo/geocaching/network/Network.java
index a49b302..7eb6f61 100644
--- a/main/src/cgeo/geocaching/network/Network.java
+++ b/main/src/cgeo/geocaching/network/Network.java
@@ -1,7 +1,9 @@
package cgeo.geocaching.network;
+import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.settings.Settings;
+import cgeo.geocaching.utils.JsonUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.TextUtils;
@@ -26,11 +28,12 @@ import ch.boye.httpclientandroidlib.params.CoreConnectionPNames;
import ch.boye.httpclientandroidlib.params.CoreProtocolPNames;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.util.EntityUtils;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.Nullable;
-import org.json.JSONException;
-import org.json.JSONObject;
import android.content.Context;
import android.net.ConnectivityManager;
@@ -43,6 +46,7 @@ import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
+import java.util.regex.Pattern;
public abstract class Network {
@@ -51,25 +55,25 @@ public abstract class Network {
/** Native user agent, taken from a Android 2.2 Nexus **/
private final static String NATIVE_USER_AGENT = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
- private static final String PATTERN_PASSWORD = "(?<=[\\?&])[Pp]ass(w(or)?d)?=[^&#$]+";
+ private static final Pattern PATTERN_PASSWORD = Pattern.compile("(?<=[\\?&])[Pp]ass(w(or)?d)?=[^&#$]+");
- private final static HttpParams clientParams = new BasicHttpParams();
+ private final static HttpParams CLIENT_PARAMS = new BasicHttpParams();
static {
- clientParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, CharEncoding.UTF_8);
- clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
- clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);
- clientParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
+ CLIENT_PARAMS.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, CharEncoding.UTF_8);
+ CLIENT_PARAMS.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
+ CLIENT_PARAMS.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
+ CLIENT_PARAMS.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
private static String hidePassword(final String message) {
- return message.replaceAll(PATTERN_PASSWORD, "password=***");
+ return PATTERN_PASSWORD.matcher(message).replaceAll("password=***");
}
private static HttpClient getHttpClient() {
final DefaultHttpClient client = new DefaultHttpClient();
client.setCookieStore(Cookies.cookieStore);
- client.setParams(clientParams);
+ client.setParams(CLIENT_PARAMS);
client.setRedirectStrategy(new LaxRedirectStrategy());
return new DecompressingHttpClient(client);
}
@@ -91,7 +95,7 @@ public abstract class Network {
*
* @param uri the URI to request
* @param params the parameters to add to the POST request
- * @params headers the headers to add to the request
+ * @param headers the headers to add to the request
* @return the HTTP response, or null in case of an encoding error params
*/
@Nullable
@@ -107,14 +111,14 @@ public abstract class Network {
* @return the HTTP response, or null in case of an encoding error params
*/
@Nullable
- public static HttpResponse postJsonRequest(final String uri, final JSONObject json) {
- HttpPost request = new HttpPost(uri);
+ public static HttpResponse postJsonRequest(final String uri, final ObjectNode json) {
+ final HttpPost request = new HttpPost(uri);
request.addHeader("Content-Type", "application/json; charset=utf-8");
if (json != null) {
try {
request.setEntity(new StringEntity(json.toString(), CharEncoding.UTF_8));
- } catch (UnsupportedEncodingException e) {
- Log.e("postJsonRequest:JSON Entity: UnsupportedEncodingException");
+ } catch (final UnsupportedEncodingException e) {
+ Log.e("postJsonRequest:JSON Entity: UnsupportedEncodingException", e);
return null;
}
}
@@ -170,7 +174,7 @@ public abstract class Network {
@Nullable
private static HttpResponse request(final String method, final String uri,
@Nullable final Parameters params, @Nullable final Parameters headers, @Nullable final File cacheFile) {
- HttpRequestBase request;
+ final HttpRequestBase request;
if (method.equals("GET")) {
final String fullUri = params == null ? uri : Uri.parse(uri).buildUpon().encodedQuery(params.toString()).build().toString();
request = new HttpGet(fullUri);
@@ -221,6 +225,10 @@ public abstract class Network {
*/
@Nullable
private static HttpResponse doLogRequest(final HttpRequestBase request) {
+ if (!isNetworkConnected()) {
+ return null;
+ }
+
final String reqLogStr = request.getMethod() + " " + hidePassword(request.getURI().toString());
Log.d(reqLogStr);
@@ -228,7 +236,7 @@ public abstract class Network {
final long before = System.currentTimeMillis();
try {
final HttpResponse response = client.execute(request);
- int status = response.getStatusLine().getStatusCode();
+ final int status = response.getStatusLine().getStatusCode();
if (status == 200) {
Log.d(status + formatTimeSpan(before) + reqLogStr);
} else {
@@ -344,14 +352,14 @@ public abstract class Network {
* @return a JSON object if the request was successful and the body could be decoded, <code>null</code> otherwise
*/
@Nullable
- public static JSONObject requestJSON(final String uri, @Nullable final Parameters params) {
+ public static ObjectNode requestJSON(final String uri, @Nullable final Parameters params) {
final HttpResponse response = request("GET", uri, params, new Parameters("Accept", "application/json, text/javascript, */*; q=0.01"), null);
final String responseData = getResponseData(response, false);
if (responseData != null) {
try {
- return new JSONObject(responseData);
- } catch (final JSONException e) {
- Log.w("Network.requestJSON", e);
+ return (ObjectNode) JsonUtils.reader.readTree(responseData);
+ } catch (final IOException e) {
+ Log.w("requestJSON", e);
}
}
@@ -369,7 +377,7 @@ public abstract class Network {
if (!isSuccess(response)) {
return null;
}
- assert(response != null);
+ assert response != null;
final HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
@@ -383,11 +391,11 @@ public abstract class Network {
}
@Nullable
- private static String getResponseDataNoError(final HttpResponse response, boolean replaceWhitespace) {
+ private static String getResponseDataNoError(final HttpResponse response, final boolean replaceWhitespace) {
try {
- String data = EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8);
+ final String data = EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8);
return replaceWhitespace ? TextUtils.replaceWhitespace(data) : data;
- } catch (Exception e) {
+ } catch (final Exception e) {
Log.e("getResponseData", e);
return null;
}
@@ -420,7 +428,7 @@ public abstract class Network {
* @return the body if the response comes from a successful HTTP request, <code>null</code> otherwise
*/
@Nullable
- public static String getResponseData(@Nullable final HttpResponse response, boolean replaceWhitespace) {
+ public static String getResponseData(@Nullable final HttpResponse response, final boolean replaceWhitespace) {
if (!isSuccess(response)) {
return null;
}
@@ -429,7 +437,7 @@ public abstract class Network {
}
@Nullable
- public static String rfc3986URLEncode(String text) {
+ public static String rfc3986URLEncode(final String text) {
final String encoded = encode(text);
return encoded != null ? StringUtils.replace(encoded.replace("+", "%20"), "%7E", "~") : null;
}
@@ -438,7 +446,7 @@ public abstract class Network {
public static String decode(final String text) {
try {
return URLDecoder.decode(text, CharEncoding.UTF_8);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
Log.e("Network.decode", e);
}
return null;
@@ -448,25 +456,26 @@ public abstract class Network {
public static String encode(final String text) {
try {
return URLEncoder.encode(text, CharEncoding.UTF_8);
- } catch (UnsupportedEncodingException e) {
+ } catch (final UnsupportedEncodingException e) {
Log.e("Network.encode", e);
}
return null;
}
+ private static ConnectivityManager connectivityManager = null;
+
/**
* Checks if the device has network connection.
*
- * @param context
- * context of the application, cannot be null
- *
* @return <code>true</code> if the device is connected to the network.
*/
- public static boolean isNetworkConnected(Context context) {
- ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetwork = conMan.getActiveNetworkInfo();
-
- return activeNetwork != null && activeNetwork.isConnected();
+ public static boolean isNetworkConnected() {
+ if (connectivityManager == null) {
+ // Concurrent assignment would not hurt
+ connectivityManager = (ConnectivityManager) CgeoApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+ }
+ final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
+ return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}