private void save(JSONArray args) throws JSONException { final JSONObject contact = args.getJSONObject(0); this.cordova.getThreadPool().execute(new Runnable(){ public void run() { JSONObject res = null; String id = contactAccessor.save(contact); if (id != null) { try { res = contactAccessor.getContactById(id); } catch (JSONException e) { LOG.e(LOG_TAG, "JSON fail.", e); } } if (res != null) { callbackContext.success(res); } else { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, UNKNOWN_ERROR)); } } }); }
/** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Ignore error due to stopLoading(). if (!isCurrentlyLoading) { return; } LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // If this is a "Protocol Not Supported" error, then revert to the previous // page. If there was no previous page, then punt. The application's config // is likely incorrect (start page set to sms: or something like that) if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) { parentEngine.client.clearLoadTimeoutTimer(); if (view.canGoBack()) { view.goBack(); return; } else { super.onReceivedError(view, errorCode, description, failingUrl); } } parentEngine.client.onReceivedError(errorCode, description, failingUrl); }
/** * Convenience method to get a string from a JSON object. Saves a * lot of try/catch writing. * If the property is not found in the object null will be returned. * * @param obj contact object to search * @param property to be looked up * @return The value of the property */ protected String getJsonString(JSONObject obj, String property) { String value = null; try { if (obj != null) { value = obj.getString(property); if (value.equals("null")) { LOG.d(LOG_TAG, property + " is string called 'null'"); value = null; } } } catch (JSONException e) { LOG.d(LOG_TAG, "Could not get = " + e.getMessage()); } return value; }
void sendEventMessage(String action, JSONObject actionData) { JSONObject message = new JSONObject(); try { message.put("action", action); if (actionData != null) { message.put(action, actionData); } } catch (JSONException e) { LOG.e(TAG, "Failed to create event message", e); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, message); pluginResult.setKeepCallback(true); if (messageChannel != null) { messageChannel.sendPluginResult(pluginResult); } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BLUETOOTH) { if (resultCode == Activity.RESULT_OK) { LOG.d(TAG, "User enabled Bluetooth"); if (enableBluetoothCallback != null) { enableBluetoothCallback.success(); } } else { LOG.d(TAG, "User did *NOT* enable Bluetooth"); if (enableBluetoothCallback != null) { enableBluetoothCallback.error("User did not enable Bluetooth"); } } enableBluetoothCallback = null; } }
private JSONObject requestAllPaths() throws JSONException { Context context = cordova.getActivity(); JSONObject ret = new JSONObject(); ret.put("applicationDirectory", "file:///android_asset/"); ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile())); ret.put("dataDirectory", toDirUrl(context.getFilesDir())); ret.put("cacheDirectory", toDirUrl(context.getCacheDir())); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { try { ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile())); ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null))); ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir())); ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory())); } catch(NullPointerException e) { /* If external storage is unavailable, context.getExternal* returns null */ LOG.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage"); } } return ret; }
/** * Requests "dangerous" permissions for the application at runtime. This is a helper method * alternative to cordovaInterface.requestPermissions() that does not require the project to be * built with cordova-android 5.0.0+ * * @param plugin The plugin the permissions are being requested for * @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult() * along with the result of the permissions request * @param permissions The permissions to be requested */ public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) { try { Method requestPermission = CordovaInterface.class.getDeclaredMethod( "requestPermissions", CordovaPlugin.class, int.class, String[].class); // If there is no exception, then this is cordova-android 5.0.0+ requestPermission.invoke(plugin.cordova, plugin, requestCode, permissions); } catch (NoSuchMethodException noSuchMethodException) { // cordova-android version is less than 5.0.0, so permission is implicitly granted LOG.d(LOG_TAG, "No need to request permissions " + Arrays.toString(permissions)); // Notify the plugin that all were granted by using more reflection deliverPermissionResult(plugin, requestCode, permissions); } catch (IllegalAccessException illegalAccessException) { // Should never be caught; this is a public method LOG.e(LOG_TAG, "IllegalAccessException when requesting permissions " + Arrays.toString(permissions), illegalAccessException); } catch(InvocationTargetException invocationTargetException) { // This method does not throw any exceptions, so this should never be caught LOG.e(LOG_TAG, "invocationTargetException when requesting permissions " + Arrays.toString(permissions), invocationTargetException); } }
/** * Create entry in media store for image * * @return uri */ private Uri getUriFromMediaStore() { ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri; try { uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (RuntimeException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (RuntimeException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); return null; } } return uri; }
/** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, AmazonWebStorage.QuotaUpdater quotaUpdater) { LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if (estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(LOG_TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } }
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { LOG.d(TAG, "We are entering execute"); context = callbackContext; if(action.equals("getPermission")) { if(hasPermisssion()) { PluginResult r = new PluginResult(PluginResult.Status.OK); context.sendPluginResult(r); return true; } else { PermissionHelper.requestPermissions(this, 0, permissions); } return true; } return false; }
/** * 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 True if the action was valid, false otherwise. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { if (action.equals("getConnectionInfo")) { this.connectionCallbackContext = callbackContext; NetworkInfo info = sockMan.getActiveNetworkInfo(); String connectionType = ""; try { connectionType = this.getConnectionInfo(info).get("type").toString(); } catch (JSONException e) { LOG.d(LOG_TAG, e.getLocalizedMessage()); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } return false; }
private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) { // Generate the request results int[] requestResults = new int[permissions.length]; Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED); try { Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod( "onRequestPermissionResult", int.class, String[].class, int[].class); onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults); } catch (NoSuchMethodException noSuchMethodException) { // Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it // made it to this point LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException); } catch (IllegalAccessException illegalAccessException) { // Should never be caught; this is a public method LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException); } catch(InvocationTargetException invocationTargetException) { // This method may throw a JSONException. We are just duplicating cordova-android's // exception handling behavior here; all it does is log the exception in CordovaActivity, // print the stacktrace, and ignore it LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException); } }
public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } // https://issues.apache.org/jira/browse/CB-11248 view.clearFocus(); view.requestFocus(); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } }
/** * Write contents of file. * * @param data The contents of the file. * @param offset The position to begin writing the file. * @param isBinary True if the file contents are base64-encoded binary data */ /**/ public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException { try { LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr); Filesystem fs = this.filesystemForURL(inputURL); if (fs == null) { throw new MalformedURLException("No installed handlers for this URL"); } long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); LOG.d("TEST",srcURLstr + ": "+x); return x; } catch (IllegalArgumentException e) { MalformedURLException mue = new MalformedURLException("Unrecognized filesystem URL"); mue.initCause(e); throw mue; } }
/** * Return a Json object for the cordova's callback in case of mpos error * * @param code The code error * @param message The message error */ private void runCallbackError(String code, String message) { try { LOG.w("eliberty.cordova.plugin.payzen", "call error callback runCallbackError"); JSONObject obj = new JSONObject(); obj.put("code", code); obj.put("message", message); synchronized(callbackContext){ callbackContext.error(obj); callbackContext.notify(); } } catch (JSONException jse) { raven.sendException(jse); LOG.w("eliberty.cordova.plugin.payzen", "JSONException : " + jse.getMessage()); } catch (Exception ex) { LOG.w("eliberty.cordova.plugin.payzen", "Exception", ex); raven.sendException(ex); } }
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); LOG.d(TAG, "onCharacteristicWrite " + characteristic); if (writeCallback != null) { if (status == BluetoothGatt.GATT_SUCCESS) { writeCallback.success(); } else { writeCallback.error(status); } writeCallback = null; } commandCompleted(); }
protected HashMap<String, String> getAvailableFileSystems(Activity activity) { Context context = activity.getApplicationContext(); HashMap<String, String> availableFileSystems = new HashMap<String,String>(); availableFileSystems.put("files", context.getFilesDir().getAbsolutePath()); availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath()); availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath()); availableFileSystems.put("root", "/"); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { try { availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath()); availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath()); availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath()); } catch(NullPointerException e) { LOG.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on"); } } return availableFileSystems; }
/** * Stop/Pause recording and save to the file specified when recording started. */ public void stopRecording(boolean stop) { if (this.recorder != null) { try{ if (this.state == STATE.MEDIA_RUNNING) { this.recorder.stop(); } this.recorder.reset(); if (!this.tempFiles.contains(this.tempFile)) { this.tempFiles.add(this.tempFile); } if (stop) { LOG.d(LOG_TAG, "stopping recording"); this.setState(STATE.MEDIA_STOPPED); this.moveFile(this.audioFile); } else { LOG.d(LOG_TAG, "pause recording"); this.setState(STATE.MEDIA_PAUSED); } } catch (Exception e) { e.printStackTrace(); } } }
/** * Return a Json object for the cordova's callback in case of mpos success * @param result The result of Transaction */ private void runCallbackSuccess(Result result) { try { LOG.w("eliberty.cordova.plugin.payzen", "call success callback runCallbackSuccess"); JSONObject obj = new JSONObject(); obj.put("transactionId", result.getTransaction().getTransactionId()); obj.put("transactionUuId", result.getTransaction().getTransactionUuid()); obj.put("status", result.getTransaction().getTransactionStatusLabel().toString()); obj.put("receipt", result.getTransaction().getReceipt()); obj.put("transactionDate", result.getTransaction().getSubmissionDate()); callbackContext.success(obj); } catch (JSONException jse) { raven.sendException(jse); LOG.w("eliberty.cordova.plugin.payzen", "JSONException : " + jse.getMessage()); runCallbackError(Integer.toString(jse.hashCode()), jse.getMessage()); } catch (Exception ex) { LOG.w("eliberty.cordova.plugin.payzen", "Exception", ex); raven.sendException(ex); runCallbackError(Integer.toString(ex.hashCode()), ex.getMessage()); } }
/** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ @Override public void initialize(final CordovaInterface cordova, CordovaWebView webView) { LOG.v(TAG, "StatusBar: initialization"); super.initialize(cordova, webView); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { // Clear flag FLAG_FORCE_NOT_FULLSCREEN which is set initially // by the Cordova. Window window = cordova.getActivity().getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); // Read 'StatusBarBackgroundColor' from config.xml, default is #000000. setStatusBarBackgroundColor(preferences.getString("StatusBarBackgroundColor", "#000000")); // Read 'StatusBarStyle' from config.xml, default is 'lightcontent'. setStatusBarStyle(preferences.getString("StatusBarStyle", "lightcontent")); } }); }
/** * Notify the host application that a page has started loading. * This method is called once for each main frame load so a page with iframes or framesets will call onPageStarted * one time for the main frame. This also means that onPageStarted will not be called when the contents of an * embedded frame changes, i.e. clicking a link whose target is an iframe. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); isCurrentlyLoading = true; LOG.d(TAG, "onPageStarted(" + url + ")"); // Flush stale messages. this.appView.bridge.reset(url); // Broadcast message that page has loaded this.appView.postMessage("onPageStarted", url); // Notify all plugins of the navigation, so they can clean up if necessary. if (this.appView.pluginManager != null) { this.appView.pluginManager.onReset(); } }
public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_STOP_EVENT); obj.put("url", url); sendUpdate(obj, true); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } }