use of org.apache.cordova.PluginResult in project jpHolo by teusink.
the class FileTransfer method download.
/**
* Downloads a file form a given URL and saves it to the specified directory.
*
* @param source URL of the server to receive the file
* @param target Full path of the file on the file system
*/
private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(LOG_TAG, "download " + source + " to " + target);
final CordovaResourceApi resourceApi = webView.getResourceApi();
final boolean trustEveryone = args.optBoolean(2);
final String objectId = args.getString(3);
final JSONObject headers = args.optJSONObject(4);
final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));
// Accept a path or a URI for the source.
Uri tmpTarget = Uri.parse(target);
final Uri targetUri = resourceApi.remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));
int uriType = CordovaResourceApi.getUriType(sourceUri);
final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
return;
}
// TODO: refactor to also allow resources & content:
if (!isLocalTransfer && !Config.isUrlWhiteListed(source)) {
Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
return;
}
final RequestContext context = new RequestContext(source, target, callbackContext);
synchronized (activeRequests) {
activeRequests.put(objectId, context);
}
cordova.getThreadPool().execute(new Runnable() {
public void run() {
if (context.aborted) {
return;
}
HttpURLConnection connection = null;
HostnameVerifier oldHostnameVerifier = null;
SSLSocketFactory oldSocketFactory = null;
File file = null;
PluginResult result = null;
TrackingInputStream inputStream = null;
boolean cached = false;
OutputStream outputStream = null;
try {
OpenForReadResult readResult = null;
file = resourceApi.mapUriToFile(targetUri);
context.targetFile = file;
Log.d(LOG_TAG, "Download file:" + sourceUri);
FileProgressResult progress = new FileProgressResult();
if (isLocalTransfer) {
readResult = resourceApi.openForRead(sourceUri);
if (readResult.length != -1) {
progress.setLengthComputable(true);
progress.setTotal(readResult.length);
}
inputStream = new SimpleTrackingInputStream(readResult.inputStream);
} else {
// connect to server
// Open a HTTP connection to the URL based on protocol
connection = resourceApi.createHttpConnection(sourceUri);
if (useHttps && trustEveryone) {
// Setup the HTTPS connection class to trust everyone
HttpsURLConnection https = (HttpsURLConnection) connection;
oldSocketFactory = trustAllHosts(https);
// Save the current hostnameVerifier
oldHostnameVerifier = https.getHostnameVerifier();
// Setup the connection not to verify hostnames
https.setHostnameVerifier(DO_NOT_VERIFY);
}
connection.setRequestMethod("GET");
// TODO: Make OkHttp use this CookieManager by default.
String cookie = CookieManager.getInstance().getCookie(sourceUri.toString());
if (cookie != null) {
connection.setRequestProperty("cookie", cookie);
}
// This must be explicitly set for gzip progress tracking to work.
connection.setRequestProperty("Accept-Encoding", "gzip");
// Handle the other headers
if (headers != null) {
addHeadersToRequest(connection, headers);
}
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
cached = true;
connection.disconnect();
Log.d(LOG_TAG, "Resource not modified: " + source);
JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null);
result = new PluginResult(PluginResult.Status.ERROR, error);
} else {
if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
// the encoding -- identity or gzip
if (connection.getContentLength() != -1) {
progress.setLengthComputable(true);
progress.setTotal(connection.getContentLength());
}
}
inputStream = getInputStream(connection);
}
}
if (!cached) {
try {
synchronized (context) {
if (context.aborted) {
return;
}
context.connection = connection;
}
// write bytes to file
byte[] buffer = new byte[MAX_BUFFER_SIZE];
int bytesRead = 0;
outputStream = resourceApi.openOutputStream(targetUri);
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
// Send a progress event.
progress.setLoaded(inputStream.getTotalRawBytesRead());
PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
progressResult.setKeepCallback(true);
context.sendPluginResult(progressResult);
}
} finally {
synchronized (context) {
context.connection = null;
}
safeClose(inputStream);
safeClose(outputStream);
}
Log.d(LOG_TAG, "Saved file: " + target);
// create FileEntry object
Class webViewClass = webView.getClass();
PluginManager pm = null;
try {
Method gpm = webViewClass.getMethod("getPluginManager");
pm = (PluginManager) gpm.invoke(webView);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
if (pm == null) {
try {
Field pmf = webViewClass.getField("pluginManager");
pm = (PluginManager) pmf.get(webView);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
file = resourceApi.mapUriToFile(targetUri);
context.targetFile = file;
FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
if (filePlugin != null) {
JSONObject fileEntry = filePlugin.getEntryForFile(file);
if (fileEntry != null) {
result = new PluginResult(PluginResult.Status.OK, fileEntry);
} else {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null);
Log.e(LOG_TAG, "File plugin cannot represent download path");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
}
} else {
Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file");
result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file");
}
}
} catch (FileNotFoundException e) {
JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
Log.e(LOG_TAG, error.toString(), e);
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (IOException e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
Log.e(LOG_TAG, error.toString(), e);
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} catch (Throwable e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
Log.e(LOG_TAG, error.toString(), e);
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} finally {
synchronized (activeRequests) {
activeRequests.remove(objectId);
}
if (connection != null) {
// Revert back to the proper verifier and socket factories
if (trustEveryone && useHttps) {
HttpsURLConnection https = (HttpsURLConnection) connection;
https.setHostnameVerifier(oldHostnameVerifier);
https.setSSLSocketFactory(oldSocketFactory);
}
}
if (result == null) {
result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null));
}
// Remove incomplete download.
if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
file.delete();
}
context.sendPluginResult(result);
}
}
});
}
use of org.apache.cordova.PluginResult in project cordova-androidwear by tgardner.
the class AndroidWearPlugin method keepCallback.
private void keepCallback(final CallbackContext callbackContext, JSONObject message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
use of org.apache.cordova.PluginResult in project jpHolo by teusink.
the class CameraLauncher method execute.
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
if (action.equals("takePicture")) {
int srcType = CAMERA;
int destType = FILE_URI;
this.saveToPhotoAlbum = false;
this.targetHeight = 0;
this.targetWidth = 0;
this.encodingType = JPEG;
this.mediaType = PICTURE;
this.mQuality = 80;
this.mQuality = args.getInt(0);
destType = args.getInt(1);
srcType = args.getInt(2);
this.targetWidth = args.getInt(3);
this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5);
this.mediaType = args.getInt(6);
this.allowEdit = args.getBoolean(7);
this.correctOrientation = args.getBoolean(8);
this.saveToPhotoAlbum = args.getBoolean(9);
// make it -1 so later comparisons succeed
if (this.targetWidth < 1) {
this.targetWidth = -1;
}
if (this.targetHeight < 1) {
this.targetHeight = -1;
}
try {
if (srcType == CAMERA) {
this.takePicture(destType, encodingType);
} else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
this.getImage(srcType, destType, encodingType);
}
} catch (IllegalArgumentException e) {
callbackContext.error("Illegal Argument Exception");
PluginResult r = new PluginResult(PluginResult.Status.ERROR);
callbackContext.sendPluginResult(r);
return true;
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
return true;
}
return false;
}
use of org.apache.cordova.PluginResult in project jpHolo by teusink.
the class InAppBrowser method execute.
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, Boolean> features = parseFeature(args.optString(2));
Log.d(LOG_TAG, "target = " + target);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
Log.d(LOG_TAG, "in self");
// load in webview
if (url.startsWith("file://") || url.startsWith("javascript:") || Config.isUrlWhiteListed(url)) {
Log.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
} else //Load the dialer
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Log.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else // load in InAppBrowser
{
Log.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
} else // SYSTEM
if (SYSTEM.equals(target)) {
Log.d(LOG_TAG, "in system");
result = openExternal(url);
} else // BLANK - or anything else
{
Log.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
});
} else if (action.equals("close")) {
closeDialog();
} else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
} else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
} else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
} else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
} else if (action.equals("show")) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.show();
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
} else {
return false;
}
return true;
}
use of org.apache.cordova.PluginResult in project jpHolo by teusink.
the class AudioHandler method execute.
/**
* Executes the request and returns PluginResult.
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
CordovaResourceApi resourceApi = webView.getResourceApi();
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
if (action.equals("startRecordingAudio")) {
String target = args.getString(1);
String fileUriStr;
try {
Uri targetUri = resourceApi.remapUri(Uri.parse(target));
fileUriStr = targetUri.toString();
} catch (IllegalArgumentException e) {
fileUriStr = target;
}
this.startRecordingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));
} else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0));
} else if (action.equals("startPlayingAudio")) {
String target = args.getString(1);
String fileUriStr;
try {
Uri targetUri = resourceApi.remapUri(Uri.parse(target));
fileUriStr = targetUri.toString();
} catch (IllegalArgumentException e) {
fileUriStr = target;
}
this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));
} else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1));
} else if (action.equals("pausePlayingAudio")) {
this.pausePlayingAudio(args.getString(0));
} else if (action.equals("stopPlayingAudio")) {
this.stopPlayingAudio(args.getString(0));
} else if (action.equals("setVolume")) {
try {
this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
} catch (NumberFormatException nfe) {
//no-op
}
} else if (action.equals("getCurrentPositionAudio")) {
float f = this.getCurrentPositionAudio(args.getString(0));
callbackContext.sendPluginResult(new PluginResult(status, f));
return true;
} else if (action.equals("getDurationAudio")) {
float f = this.getDurationAudio(args.getString(0), args.getString(1));
callbackContext.sendPluginResult(new PluginResult(status, f));
return true;
} else if (action.equals("create")) {
String id = args.getString(0);
String src = FileHelper.stripFileProtocol(args.getString(1));
AudioPlayer audio = new AudioPlayer(this, id, src);
this.players.put(id, audio);
} else if (action.equals("release")) {
boolean b = this.release(args.getString(0));
callbackContext.sendPluginResult(new PluginResult(status, b));
return true;
} else {
// Unrecognized action.
return false;
}
callbackContext.sendPluginResult(new PluginResult(status, result));
return true;
}
Aggregations