WIP: reduce duplicate code & cleanup

This commit is contained in:
Sefa Ilkimen
2019-03-22 02:06:39 +01:00
parent e8e1c4273f
commit ee30160921
15 changed files with 221 additions and 4296 deletions

View File

@@ -56,17 +56,12 @@
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.INTERNET"/>
</config-file>
<!--
<source-file src="src/android/com/github/kevinsawicki/http/HttpRequest.java" target-dir="src/com/github/kevinsawicki/http"/>
<source-file src="src/android/com/github/kevinsawicki/http/OkConnectionFactory.java" target-dir="src/com/github/kevinsawicki/http"/>
<source-file src="src/android/com/github/kevinsawicki/http/TLSSocketFactory.java" target-dir="src/com/github/kevinsawicki/http"/>
-->
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpBase.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpDownload.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpRequest.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpResponse.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/cordovahttp/CordovaHttpUpload.java" target-dir="src/com/silkimen/cordovahttp"/>
<source-file src="src/android/com/silkimen/http/HttpBodyDecoder.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/HttpRequest.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/JsonUtils.java" target-dir="src/com/silkimen/http"/>

File diff suppressed because it is too large Load Diff

View File

@@ -1,61 +0,0 @@
package com.github.kevinsawicki.http;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory(SSLContext context) {
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"});
}
return socket;
}
}

View File

@@ -0,0 +1,171 @@
package com.silkimen.cordovahttp;
import java.io.ByteArrayOutputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
import com.silkimen.http.JsonUtils;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
abstract class CordovaHttpBase implements Runnable {
protected static final String TAG = "Cordova-Plugin-HTTP";
protected String method;
protected String url;
protected String serializer = "none";
protected Object data;
protected JSONObject params;
protected JSONObject headers;
protected int timeout;
protected CallbackContext callbackContext;
public CordovaHttpBase(String method, String url, String serializer, Object data, JSONObject headers, int timeout,
CallbackContext callbackContext) {
this.method = method;
this.url = url;
this.serializer = serializer;
this.data = data;
this.headers = headers;
this.timeout = timeout;
this.callbackContext = callbackContext;
}
public CordovaHttpBase(String method, String url, JSONObject params, JSONObject headers, int timeout,
CallbackContext callbackContext) {
this.method = method;
this.url = url;
this.params = params;
this.headers = headers;
this.timeout = timeout;
this.callbackContext = callbackContext;
}
@Override
public void run() {
CordovaHttpResponse response = new CordovaHttpResponse();
try {
HttpRequest request = this.createRequest();
this.prepareRequest(request);
this.sendBody(request);
this.processResponse(request, response);
} catch (HttpRequestException e) {
if (e.getCause() instanceof SSLHandshakeException) {
response.setStatus(-2);
response.setErrorMessage("SSL handshake failed: " + e.getMessage());
Log.w(TAG, "SSL handshake failed", e);
} else if (e.getCause() instanceof UnknownHostException) {
response.setStatus(-3);
response.setErrorMessage("Host could not be resolved: " + e.getMessage());
Log.w(TAG, "Host could not be resolved", e);
} else if (e.getCause() instanceof SocketTimeoutException) {
response.setStatus(-4);
response.setErrorMessage("Request timed out: " + e.getMessage());
Log.w(TAG, "Request timed out", e);
} else {
response.setStatus(-1);
response.setErrorMessage("There was an error with the request: " + e.getCause().getMessage());
Log.w(TAG, "Generic request error", e);
}
} catch (Exception e) {
response.setStatus(-1);
response.setErrorMessage(e.getMessage());
Log.e(TAG, "An unexpected error occured", e);
}
try {
if (response.hasFailed()) {
this.callbackContext.error(response.toJSON());
} else {
this.callbackContext.success(response.toJSON());
}
} catch (JSONException e) {
Log.e(TAG, "An unexpected error occured while creating HTTP response object", e);
}
}
protected HttpRequest createRequest() throws JSONException {
String processedUrl = HttpRequest.encode(HttpRequest.append(this.url, JsonUtils.getObjectMap(this.params)));
HttpRequest request = new HttpRequest(processedUrl, this.method);
return request;
}
protected void prepareRequest(HttpRequest request) throws JSONException {
request.followRedirects(true /* @TODO */);
request.readTimeout(this.timeout);
request.acceptCharset("UTF-8");
request.uncompress(true);
// setup content type before applying headers, so user can override it
this.setContentType(request);
request.headers(JsonUtils.getStringMap(this.headers));
}
protected void setContentType(HttpRequest request) {
switch (this.serializer) {
case "json":
request.contentType("application/json", "UTF-8");
break;
case "utf8":
request.contentType("text/plain", "UTF-8");
break;
case "urlencoded":
// intentionally left blank, because content type is set in HttpRequest.form()
break;
}
}
protected void sendBody(HttpRequest request) throws Exception {
if (this.data == null) {
return;
}
switch (this.serializer) {
case "json":
request.send(this.data.toString());
break;
case "utf8":
request.send(((JSONObject) this.data).getString("text"));
break;
case "urlencoded":
request.form(JsonUtils.getObjectMap((JSONObject) this.data));
break;
}
}
protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
request.receive(outputStream);
ByteBuffer rawOutput = ByteBuffer.wrap(outputStream.toByteArray());
String decodedBody = HttpBodyDecoder.decodeBody(rawOutput, request.charset());
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
response.setBody(decodedBody);
} else {
response.setErrorMessage(decodedBody);
}
}
}

View File

@@ -1,105 +1,38 @@
package com.silkimen.cordovahttp;
import java.io.File;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
import com.silkimen.http.JsonUtils;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.file.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
class CordovaHttpDownload implements Runnable {
private static final String TAG = "Cordova-Plugin-HTTP";
private String url;
private JSONObject params;
private JSONObject headers;
class CordovaHttpDownload extends CordovaHttpBase {
private String filePath;
private int timeout;
private CallbackContext callbackContext;
public CordovaHttpDownload(String url, JSONObject params, JSONObject headers, String filePath, int timeout,
CallbackContext callbackContext) {
this.url = url;
this.params = params;
this.headers = headers;
super("GET", url, params, headers, timeout, callbackContext);
this.filePath = filePath;
this.timeout = timeout;
this.callbackContext = callbackContext;
}
@Override
public void run() {
CordovaHttpResponse response = new CordovaHttpResponse();
protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
try {
String processedUrl = HttpRequest.encode(HttpRequest.append(this.url, JsonUtils.getObjectMap(this.params)));
if (request.code() >= 200 && request.code() < 300) {
File file = new File(new URI(this.filePath));
JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file);
HttpRequest request = new HttpRequest(processedUrl, "GET")
.followRedirects(true /* @TODO */)
.readTimeout(this.timeout)
.acceptCharset("UTF-8")
.uncompress(true)
.headers(JsonUtils.getStringMap(this.headers));
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
File file = new File(new URI(filePath));
request.receive(file);
response.setFileEntry(FileUtils.getFilePlugin().getEntryForFile(file));
} else {
response.setErrorMessage("There was an error downloading the file");
}
} catch (HttpRequestException e) {
if (e.getCause() instanceof SSLHandshakeException) {
response.setStatus(-2);
response.setErrorMessage("SSL handshake failed: " + e.getMessage());
Log.w(TAG, "SSL handshake failed", e);
} else if (e.getCause() instanceof UnknownHostException) {
response.setStatus(-3);
response.setErrorMessage("Host could not be resolved: " + e.getMessage());
Log.w(TAG, "Host could not be resolved", e);
} else if (e.getCause() instanceof SocketTimeoutException) {
response.setStatus(-4);
response.setErrorMessage("Request timed out: " + e.getMessage());
Log.w(TAG, "Request timed out", e);
} else {
response.setStatus(-1);
response.setErrorMessage("There was an error with the request: " + e.getCause().getMessage());
Log.w(TAG, "Generic request error", e);
}
} catch (Exception e) {
response.setStatus(-1);
response.setErrorMessage(e.getMessage());
Log.e(TAG, "An unexpected error occured", e);
}
try {
if (response.hasFailed()) {
this.callbackContext.error(response.toJSON());
} else {
this.callbackContext.success(response.toJSON());
}
} catch (JSONException e) {
Log.e(TAG, "An unexpected error occured while processing HTTP response", e);
request.receive(file);
response.setFileEntry(fileEntry);
} else {
response.setErrorMessage("There was an error downloading the file");
}
}
}

View File

@@ -0,0 +1,18 @@
package com.silkimen.cordovahttp;
import org.apache.cordova.CallbackContext;
import org.json.JSONObject;
class CordovaHttpOperation extends CordovaHttpBase {
public CordovaHttpOperation(String method, String url, String serializer, Object data, JSONObject headers,
int timeout, CallbackContext callbackContext) {
super(method, url, serializer, data, headers, timeout, callbackContext);
}
public CordovaHttpOperation(String method, String url, JSONObject params, JSONObject headers, int timeout,
CallbackContext callbackContext) {
super(method, url, params, headers, timeout, callbackContext);
}
}

View File

@@ -83,10 +83,10 @@ public class CordovaHttpPlugin extends CordovaPlugin {
JSONObject headers = args.getJSONObject(2);
int timeout = args.getInt(3) * 1000;
CordovaHttpRequest get = new CordovaHttpRequest(method.toUpperCase(), url, params, headers, timeout,
CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, params, headers, timeout,
callbackContext);
cordova.getThreadPool().execute(get);
cordova.getThreadPool().execute(request);
return true;
}
@@ -100,7 +100,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
JSONObject headers = args.getJSONObject(3);
int timeout = args.getInt(4) * 1000;
CordovaHttpRequest request = new CordovaHttpRequest(method.toUpperCase(), url, serializer, data, headers, timeout,
CordovaHttpOperation request = new CordovaHttpOperation(method.toUpperCase(), url, serializer, data, headers, timeout,
callbackContext);
cordova.getThreadPool().execute(request);

View File

@@ -1,156 +0,0 @@
package com.silkimen.cordovahttp;
import java.io.ByteArrayOutputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
import com.silkimen.http.JsonUtils;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class CordovaHttpRequest implements Runnable {
private static final String TAG = "Cordova-Plugin-HTTP";
private String method;
private String url;
private String serializer = "none";
private Object data;
private JSONObject params;
private JSONObject headers;
private int timeout;
private CallbackContext callbackContext;
public CordovaHttpRequest(String method, String url, String serializer, Object data, JSONObject headers,
int timeout, CallbackContext callbackContext) {
this.method = method;
this.url = url;
this.serializer = serializer;
this.data = data;
this.headers = headers;
this.timeout = timeout;
this.callbackContext = callbackContext;
}
public CordovaHttpRequest(String method, String url, JSONObject params, JSONObject headers, int timeout,
CallbackContext callbackContext) {
this.method = method;
this.url = url;
this.params = params;
this.headers = headers;
this.timeout = timeout;
this.callbackContext = callbackContext;
}
@Override
public void run() {
CordovaHttpResponse response = new CordovaHttpResponse();
try {
String processedUrl = HttpRequest.encode(HttpRequest.append(this.url, JsonUtils.getObjectMap(this.params)));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HttpRequest request = new HttpRequest(processedUrl, this.method)
.followRedirects(true /* @TODO */)
.readTimeout(this.timeout)
.acceptCharset("UTF-8")
.uncompress(true);
// setup content type before applying headers, so user can override it
this.setContentType(request)
.headers(JsonUtils.getStringMap(this.headers));
this.sendBody(request)
.receive(outputStream);
ByteBuffer rawOutput = ByteBuffer.wrap(outputStream.toByteArray());
String decodedBody = HttpBodyDecoder.decodeBody(rawOutput, request.charset());
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
response.setBody(decodedBody);
} else {
response.setErrorMessage(decodedBody);
}
} catch (HttpRequestException e) {
if (e.getCause() instanceof SSLHandshakeException) {
response.setStatus(-2);
response.setErrorMessage("SSL handshake failed: " + e.getMessage());
Log.w(TAG, "SSL handshake failed", e);
} else if (e.getCause() instanceof UnknownHostException) {
response.setStatus(-3);
response.setErrorMessage("Host could not be resolved: " + e.getMessage());
Log.w(TAG, "Host could not be resolved", e);
} else if (e.getCause() instanceof SocketTimeoutException) {
response.setStatus(-4);
response.setErrorMessage("Request timed out: " + e.getMessage());
Log.w(TAG, "Request timed out", e);
} else {
response.setStatus(-1);
response.setErrorMessage("There was an error with the request: " + e.getCause().getMessage());
Log.w(TAG, "Generic request error", e);
}
} catch (Exception e) {
response.setStatus(-1);
response.setErrorMessage(e.getMessage());
Log.e(TAG, "An unexpected error occured", e);
}
try {
if (response.hasFailed()) {
this.callbackContext.error(response.toJSON());
} else {
this.callbackContext.success(response.toJSON());
}
} catch (JSONException e) {
Log.e(TAG, "An unexpected error occured while processing HTTP response", e);
}
}
private HttpRequest setContentType(HttpRequest request) {
switch(this.serializer) {
case "json":
return request.contentType("application/json", "UTF-8");
case "utf8":
return request.contentType("text/plain", "UTF-8");
case "urlencoded":
// intentionally left blank, because content type is set in HttpRequest.form()
}
return request;
}
private HttpRequest sendBody(HttpRequest request) throws JSONException {
if (this.data == null) {
return request;
}
switch (this.serializer) {
case "json":
return request.send(this.data.toString());
case "utf8":
return request.send(((JSONObject) this.data).getString("text"));
case "urlencoded":
return request.form(JsonUtils.getObjectMap((JSONObject) this.data));
}
return request;
}
}

View File

@@ -1,128 +1,39 @@
package com.silkimen.cordovahttp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import android.webkit.MimeTypeMap;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
import com.silkimen.http.JsonUtils;
import java.io.File;
import java.net.URI;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.webkit.MimeTypeMap;
import android.util.Log;
class CordovaHttpUpload implements Runnable {
private static final String TAG = "Cordova-Plugin-HTTP";
private String url;
private JSONObject params;
private JSONObject headers;
class CordovaHttpUpload extends CordovaHttpBase {
private String filePath;
private String uploadName;
private int timeout;
private CallbackContext callbackContext;
public CordovaHttpUpload(String url, JSONObject params, JSONObject headers, String filePath, String uploadName,
int timeout, CallbackContext callbackContext) {
this.url = url;
this.params = params;
this.headers = headers;
super("POST", url, params, headers, timeout, callbackContext);
this.filePath = filePath;
this.uploadName = uploadName;
this.timeout = timeout;
this.callbackContext = callbackContext;
}
@Override
public void run() {
CordovaHttpResponse response = new CordovaHttpResponse();
protected void sendBody(HttpRequest request) throws Exception {
int filenameIndex = this.filePath.lastIndexOf('/');
String filename = this.filePath.substring(filenameIndex + 1);
try {
String processedUrl = HttpRequest.encode(HttpRequest.append(this.url, JsonUtils.getObjectMap(this.params)));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int extIndex = this.filePath.lastIndexOf('.');
String ext = this.filePath.substring(extIndex + 1);
HttpRequest request = new HttpRequest(processedUrl, "POST")
.followRedirects(true /* @TODO */)
.readTimeout(this.timeout)
.acceptCharset("UTF-8")
.uncompress(true)
.headers(JsonUtils.getStringMap(this.headers));
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
int filenameIndex = filePath.lastIndexOf('/');
String filename = filePath.substring(filenameIndex + 1);
int extIndex = filePath.lastIndexOf('.');
String ext = filePath.substring(extIndex + 1);
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
request.part(this.uploadName, filename, mimeType, new File(new URI(this.filePath)))
.receive(outputStream);
ByteBuffer rawOutput = ByteBuffer.wrap(outputStream.toByteArray());
String decodedBody = HttpBodyDecoder.decodeBody(rawOutput, request.charset());
response.setStatus(request.code());
response.setUrl(request.url().toString());
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
response.setBody(decodedBody);
} else {
response.setErrorMessage(decodedBody);
}
} catch (HttpRequestException e) {
if (e.getCause() instanceof SSLHandshakeException) {
response.setStatus(-2);
response.setErrorMessage("SSL handshake failed: " + e.getMessage());
Log.w(TAG, "SSL handshake failed", e);
} else if (e.getCause() instanceof UnknownHostException) {
response.setStatus(-3);
response.setErrorMessage("Host could not be resolved: " + e.getMessage());
Log.w(TAG, "Host could not be resolved", e);
} else if (e.getCause() instanceof SocketTimeoutException) {
response.setStatus(-4);
response.setErrorMessage("Request timed out: " + e.getMessage());
Log.w(TAG, "Request timed out", e);
} else {
response.setStatus(-1);
response.setErrorMessage("There was an error with the request: " + e.getCause().getMessage());
Log.w(TAG, "Generic request error", e);
}
} catch (URISyntaxException e) {
response.setStatus(-1);
response.setErrorMessage("An error occured while loading file");
Log.e(TAG, "An error occured while loading file", e);
} catch (Exception e) {
response.setStatus(-1);
response.setErrorMessage(e.getMessage());
Log.e(TAG, "An unexpected error occured", e);
}
try {
if (response.hasFailed()) {
this.callbackContext.error(response.toJSON());
} else {
this.callbackContext.success(response.toJSON());
}
} catch (JSONException e) {
Log.e(TAG, "An unexpected error occured while processing HTTP response", e);
}
request.part(this.uploadName, filename, mimeType, new File(new URI(this.filePath)));
}
}

View File

@@ -1,249 +0,0 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.MalformedInputException;
import javax.net.ssl.SSLHandshakeException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.Iterator;
import android.text.TextUtils;
import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
abstract class CordovaHttp {
protected static final String TAG = "CordovaHTTP";
private static AtomicBoolean disableRedirect = new AtomicBoolean(false);
private String urlString;
private Object params;
private String serializerName;
private JSONObject headers;
private int timeoutInMilliseconds;
private CallbackContext callbackContext;
public CordovaHttp(String urlString, Object params, JSONObject headers, int timeout,
CallbackContext callbackContext) {
this(urlString, params, "default", headers, timeout, callbackContext);
}
public CordovaHttp(String urlString, Object params, String serializerName, JSONObject headers, int timeout,
CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.serializerName = serializerName;
this.headers = headers;
this.timeoutInMilliseconds = timeout;
this.callbackContext = callbackContext;
}
public static void disableRedirect(boolean disable) {
disableRedirect.set(disable);
}
protected String getUrlString() {
return this.urlString;
}
protected Object getParamsObject() {
return this.params;
}
protected String getSerializerName() {
return this.serializerName;
}
protected HashMap<String, Object> getParamsMap() throws JSONException, Exception {
if (this.params instanceof JSONObject) {
return this.getMapFromJSONObject((JSONObject) this.params);
} else {
throw new Exception("unsupported params type, needs to be a JSON object");
}
}
protected JSONObject getHeadersObject() {
return this.headers;
}
protected HashMap<String, String> getHeadersMap() throws JSONException {
return this.getStringMapFromJSONObject(this.headers);
}
protected int getRequestTimeout() {
return this.timeoutInMilliseconds;
}
protected CallbackContext getCallbackContext() {
return this.callbackContext;
}
protected HttpRequest setupRedirect(HttpRequest request) {
if (disableRedirect.get()) {
request.followRedirects(false);
}
return request;
}
protected void setupDataSerializer(HttpRequest request) throws JSONException, Exception {
if ("json".equals(this.getSerializerName())) {
request.contentType(request.CONTENT_TYPE_JSON, request.CHARSET_UTF8);
} else if ("utf8".equals(this.getSerializerName())) {
request.contentType("text/plain", request.CHARSET_UTF8);
}
}
protected void respondWithError(int status, String msg) {
try {
JSONObject response = new JSONObject();
response.put("status", status);
response.put("error", msg);
this.callbackContext.error(response);
} catch (JSONException e) {
this.callbackContext.error(msg);
}
}
protected void respondWithError(String msg) {
this.respondWithError(-1, msg);
}
protected void addResponseHeaders(HttpRequest request, JSONObject response) throws JSONException {
Map<String, List<String>> headers = request.headers();
Map<String, String> filteredHeaders = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
if ((key != null) && (!value.isEmpty())) {
filteredHeaders.put(key.toLowerCase(), TextUtils.join(", ", value));
}
}
response.put("headers", new JSONObject(filteredHeaders));
}
protected HashMap<String, String> getStringMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
Iterator<?> i = object.keys();
while (i.hasNext()) {
String key = (String) i.next();
map.put(key, object.getString(key));
}
return map;
}
protected ArrayList<Object> getListFromJSONArray(JSONArray array) throws JSONException {
ArrayList<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.length(); i++) {
list.add(array.get(i));
}
return list;
}
protected HashMap<String, Object> getMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, Object> map = new HashMap<String, Object>();
Iterator<?> i = object.keys();
while (i.hasNext()) {
String key = (String) i.next();
Object value = object.get(key);
if (value instanceof JSONArray) {
map.put(key, getListFromJSONArray((JSONArray) value));
} else {
map.put(key, object.get(key));
}
}
return map;
}
protected void prepareRequest(HttpRequest request) throws HttpRequestException, JSONException {
this.setupRedirect(request);
request.readTimeout(this.getRequestTimeout());
// request.acceptCharset(ACCEPTED_CHARSETS);
request.headers(this.getHeadersMap());
request.uncompress(true);
}
protected void prepareRequestBody(HttpRequest request) throws JSONException, Exception {
if ("json".equals(this.getSerializerName())) {
request.send(this.getParamsObject().toString());
} else if ("utf8".equals(this.getSerializerName())) {
request.send(this.getParamsMap().get("text").toString());
} else {
request.form(this.getParamsMap());
}
}
protected void returnResponseObject(HttpRequest request) throws HttpRequestException {
try {
JSONObject response = new JSONObject();
int code = request.code();
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
request.receive(outputStream);
ByteBuffer rawOutput = ByteBuffer.wrap(outputStream.toByteArray());
//request.body(rawOutput);
response.put("status", code);
response.put("url", request.url().toString());
this.addResponseHeaders(request, response);
if (code >= 200 && code < 300) {
response.put("data", HttpBodyDecoder.decodeBody(rawOutput, request.charset()));
this.getCallbackContext().success(response);
} else {
response.put("error", HttpBodyDecoder.decodeBody(rawOutput, request.charset()));
this.getCallbackContext().error(response);
}
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (MalformedInputException e) {
this.respondWithError("Could not decode response data due to malformed data");
} catch (CharacterCodingException e) {
this.respondWithError("Could not decode response data due to invalid or unknown charset encoding");
}
}
protected void handleHttpRequestException(HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved: " + e.getMessage());
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out: " + e.getMessage());
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError(-2, "SSL handshake failed: " + e.getMessage());
} else {
this.respondWithError("There was an error with the request: " + e.getMessage());
}
}
}

View File

@@ -1,37 +0,0 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
class CordovaHttpDelete extends CordovaHttp implements Runnable {
public CordovaHttpDelete(String urlString, Object data, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, data, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.delete(this.getUrlString(), this.getParamsMap(), false);
this.prepareRequest(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}

View File

@@ -1,36 +0,0 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
class CordovaHttpHead extends CordovaHttp implements Runnable {
public CordovaHttpHead(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), false);
this.prepareRequest(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}

View File

@@ -1,39 +0,0 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
class CordovaHttpPatch extends CordovaHttp implements Runnable {
public CordovaHttpPatch(String urlString, Object params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, serializerName, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
/* todo */
HttpRequest request = HttpRequest.get(this.getUrlString());
this.setupDataSerializer(request);
this.prepareRequest(request);
this.prepareRequestBody(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}

View File

@@ -1,38 +0,0 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
class CordovaHttpPost extends CordovaHttp implements Runnable {
public CordovaHttpPost(String urlString, Object params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, serializerName, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupDataSerializer(request);
this.prepareRequest(request);
this.prepareRequestBody(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}

View File

@@ -1,38 +0,0 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
class CordovaHttpPut extends CordovaHttp implements Runnable {
public CordovaHttpPut(String urlString, Object data, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, data, serializerName, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.put(this.getUrlString());
this.setupDataSerializer(request);
this.prepareRequest(request);
this.prepareRequestBody(request);
this.returnResponseObject(request);
} catch (HttpRequestException e) {
this.handleHttpRequestException(e);
} catch (Exception e) {
this.respondWithError(e.getMessage());
}
}
}