List of usage examples for org.apache.cordova PluginResult setKeepCallback
public void setKeepCallback(boolean b)
From source file:com.filetransfer.baidu.bcs.FileTransferBCS.java
License:Apache License
/** * 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 *///ww w. j a va 2 s . c om 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) { 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); FileProgressBCSResult progress = new FileProgressBCSResult(); 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")) { // Only trust content-length header if we understand // 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); } } }); }
From source file:com.firerunner.cordova.TTS.java
License:BSD License
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackContext = callbackContext; try {//from ww w. ja v a 2s .com if (action.equals("speak")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.speak(text, TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message", "TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("interrupt")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); //map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackId); mTts.speak(text, TextToSpeech.QUEUE_FLUSH, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message", "TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("stop")) { if (isReady()) { mTts.stop(); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message", "TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("silence")) { if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.playSilence(args.getLong(0), TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message", "TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("speed")) { if (isReady()) { float speed = (float) (args.optLong(0, 100)) / (float) 100.0; mTts.setSpeechRate(speed); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message", "TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("pitch")) { if (isReady()) { float pitch = (float) (args.optLong(0, 100)) / (float) 100.0; mTts.setPitch(pitch); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message", "TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("startup")) { this.startupCallbackContext = callbackContext; if (mTts == null) { state = TTS.INITIALIZING; mTts = new TextToSpeech(cordova.getActivity().getApplicationContext(), this); PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING); pluginResult.setKeepCallback(true); // do not send this as onInit is more reliable: domaemon // startupCallbackContext.sendPluginResult(pluginResult); } else { PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING); pluginResult.setKeepCallback(true); startupCallbackContext.sendPluginResult(pluginResult); } } else if (action.equals("shutdown")) { if (mTts != null) { mTts.shutdown(); mTts = null; } callbackContext.sendPluginResult(new PluginResult(status, result)); } else if (action.equals("getLanguage")) { if (mTts != null) { result = mTts.getLanguage().toString(); callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("isLanguageAvailable")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.isLanguageAvailable(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("setLanguage")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.setLanguage(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } return true; } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }
From source file:com.firerunner.cordova.TTS.java
License:BSD License
/** * Called when the TTS service is initialized. * * @param status/*from www . j a v a 2 s . c om*/ */ public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { state = TTS.STARTED; //Voice v = mTts.getVoice(); //v. PluginResult result = new PluginResult(PluginResult.Status.OK, TTS.STARTED); result.setKeepCallback(false); //this.success(result, this.startupCallbackId); this.startupCallbackContext.sendPluginResult(result); mTts.setOnUtteranceCompletedListener(this); // Putting this code in hear as a place holder. When everything moves to API level 15 or greater // we'll switch over to this way of trackign progress. // mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() { // // @Override // public void onDone(String utteranceId) { // Log.d(LOG_TAG, "got completed utterance"); // PluginResult result = new PluginResult(PluginResult.Status.OK); // result.setKeepCallback(false); // callbackContext.sendPluginResult(result); // } // // @Override // public void onError(String utteranceId) { // Log.d(LOG_TAG, "got utterance error"); // PluginResult result = new PluginResult(PluginResult.Status.ERROR); // result.setKeepCallback(false); // callbackContext.sendPluginResult(result); // } // // @Override // public void onStart(String utteranceId) { // Log.d(LOG_TAG, "started talking"); // } // // }); } else if (status == TextToSpeech.ERROR) { state = TTS.STOPPED; PluginResult result = new PluginResult(PluginResult.Status.ERROR, TTS.STOPPED); result.setKeepCallback(false); this.startupCallbackContext.sendPluginResult(result); } }
From source file:com.firerunner.cordova.TTS.java
License:BSD License
/** * Once the utterance has completely been played call the speak's success callback *//* w w w . j a v a 2s . co m*/ public void onUtteranceCompleted(String utteranceId) { PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); this.callbackContext.sendPluginResult(result); }
From source file:com.foxit.cordova.plugin.FoxitPdf.java
private void openDocument(String inputPath, byte[] password, String outPath, CallbackContext callbackContext) { Intent intent = new Intent(this.cordova.getActivity(), ReaderActivity.class); Bundle bundle = new Bundle(); bundle.putString("path", inputPath); bundle.putByteArray("password", password); bundle.putString("filePathSaveTo", TextUtils.isEmpty(outPath) ? "" : outPath); intent.putExtras(bundle);//w w w . ja v a2 s. c o m this.cordova.startActivityForResult(this, intent, result_flag); // this.cordova.setActivityResultCallback(this); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "Succeed open this file"); pluginResult.setKeepCallback(true); this.callbackContext.sendPluginResult(pluginResult); }
From source file:com.foxit.cordova.plugin.FoxitPdf.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK && requestCode == result_flag) { String returnedData = intent.getStringExtra("key"); try {//from w ww . jav a 2 s . c o m JSONObject obj = new JSONObject(); obj.put("type", RDK_DOCSAVED_EVENT); obj.put("info", returnedData); if (callbackContext != null) { PluginResult result = new PluginResult(PluginResult.Status.OK, obj); result.setKeepCallback(true); callbackContext.sendPluginResult(result); // if (!true) { // callbackContext = null; // } } } catch (JSONException ex) { // Log.e("JSONException", "URI passed in has caused a JSON error."); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } } }
From source file:com.foxit.cordova.plugin.FoxitPdf.java
public static void onDocOpened(int errCode) { if (callbackContext != null) { try {// w w w. j a va 2 s.c om JSONObject obj = new JSONObject(); obj.put("type", RDK_DOCOPENED_EVENT); obj.put("errorCode", errCode); PluginResult.Status status; if (errCode == 0) { status = PluginResult.Status.OK; } else { status = PluginResult.Status.ERROR; } PluginResult result = new PluginResult(status, obj); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (JSONException e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } } }
From source file:com.foxit.cordova.plugin.FoxitPdf.java
public static void onDocWillSave() { try {//from w w w . java2 s . c om if (callbackContext != null) { JSONObject obj = new JSONObject(); obj.put("type", RDK_DOCWILLSAVE_EVENT); PluginResult result = new PluginResult(PluginResult.Status.OK, obj); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } } catch (JSONException ex) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } }
From source file:com.foxit.cordova.plugin.FoxitPdf.java
private boolean getFormInfo(CallbackContext callbackContext) { if (ReaderActivity.pdfViewCtrl == null || ReaderActivity.pdfViewCtrl.getDoc() == null) { callbackContext.error("Please open document first."); return false; }//from ww w . j a v a 2 s. c om PDFDoc pdfDoc = ReaderActivity.pdfViewCtrl.getDoc(); try { if (!pdfDoc.hasForm()) { callbackContext.error("The current document does not have interactive form."); return false; } Form form = new Form(pdfDoc); int alignment = form.getAlignment(); boolean needConstructAppearances = form.needConstructAppearances(); JSONObject obj = new JSONObject(); obj.put("alignment", alignment); obj.put("needConstructAppearances", needConstructAppearances); DefaultAppearance da = form.getDefaultAppearance(); JSONObject defaultApObj = new JSONObject(); defaultApObj.put("flags", da.getFlags()); defaultApObj.put("textColor", da.getText_color()); defaultApObj.put("textSize", da.getText_size()); obj.put("defaultAppearance", defaultApObj); PluginResult result = new PluginResult(PluginResult.Status.OK, obj); result.setKeepCallback(true); callbackContext.sendPluginResult(result); return true; } catch (PDFException e) { callbackContext.error(e.getMessage() + ", Error code = " + e.getLastError()); } catch (JSONException e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }
From source file:com.foxit.cordova.plugin.FoxitPdf.java
private boolean getAllFormFields(CallbackContext callbackContext) { if (ReaderActivity.pdfViewCtrl == null || ReaderActivity.pdfViewCtrl.getDoc() == null) { callbackContext.error("Please open document first."); return false; }/*from w w w . j a v a2 s.c o m*/ PDFDoc pdfDoc = ReaderActivity.pdfViewCtrl.getDoc(); try { if (!pdfDoc.hasForm()) { callbackContext.error("The current document does not have interactive form."); return false; } Form form = new Form(pdfDoc); int fieldCount = form.getFieldCount(null); if (fieldCount == 0) { callbackContext.error("The current document does not have form fields."); return false; } JSONArray infos = new JSONArray(); for (int i = 0; i < fieldCount; i++) { Field field = form.getField(i, null); int type = field.getType(); JSONObject obj = new JSONObject(); obj.put("fieldIndex", i); obj.put("fieldType", type); obj.put("fieldFlag", field.getFlags()); obj.put("name", field.getName()); obj.put("defValue", field.getDefaultValue()); obj.put("value", field.getValue()); obj.put("alignment", field.getAlignment()); obj.put("alternateName", field.getAlternateName()); obj.put("mappingName", field.getMappingName()); obj.put("maxLength", field.getMaxLength()); obj.put("topVisibleIndex", field.getTopVisibleIndex()); DefaultAppearance da = field.getDefaultAppearance(); JSONObject defaultApObj = new JSONObject(); defaultApObj.put("flags", da.getFlags()); defaultApObj.put("textColor", da.getText_color()); defaultApObj.put("textSize", da.getText_size()); obj.put("defaultAppearance", defaultApObj); if (type == Field.e_TypeComboBox || type == Field.e_TypeListBox) { ChoiceOptionArray options = field.getOptions(); long optionCount = options.getSize(); if (optionCount > 0) { JSONArray optArray = new JSONArray(); for (int j = 0; j < optionCount; j++) { JSONObject optObj = new JSONObject(); ChoiceOption option = options.getAt(j); optObj.put("optionValue", option.getOption_value()); optObj.put("optionLabel", option.getOption_label()); optObj.put("selected", option.getDefault_selected()); optObj.put("defaultSelected", option.getSelected()); optArray.put(optObj); } obj.put("choiceOptions", optArray); } } infos.put(obj); } PluginResult result = new PluginResult(PluginResult.Status.OK, infos); result.setKeepCallback(true); callbackContext.sendPluginResult(result); return true; } catch (PDFException e) { callbackContext.error(e.getMessage() + ", Error code = " + e.getLastError()); } catch (JSONException e) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }