Example usage for org.apache.cordova PluginResult PluginResult

List of usage examples for org.apache.cordova PluginResult PluginResult

Introduction

In this page you can find the example usage for org.apache.cordova PluginResult PluginResult.

Prototype

public PluginResult(Status status, List<PluginResult> multipartMessages) 

Source Link

Usage

From source file:com.acuant.plugin.AcuantMobileSDK.java

@Override
public void onBarcodeTimeOut(Bitmap croppedImage, HashMap<String, Object> imageMetrics, Bitmap originalImage) {
    JSONObject obj = new JSONObject();
    try {//from w  w w.  j  a v a2  s . co  m
        obj.put("id", "barcodeScanTimeOut");

        if (croppedImage != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            croppedImage.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
            obj.put("croppedData", encoded);
        }
        if (originalImage != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            originalImage.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
            obj.put("originalData", encoded);
        }

        if (imageMetrics != null && imageMetrics.get("HAS_GLARE") != null) {
            boolean hasGlare = Boolean.parseBoolean(imageMetrics.get("HAS_GLARE").toString());
            obj.put("HAS_GLARE", hasGlare);
        }
        if (imageMetrics != null && imageMetrics.get("GLARE_GRADE") != null) {
            float glareGrade = Float.parseFloat(imageMetrics.get("GLARE_GRADE").toString());
            obj.put("GLARE_GRADE", glareGrade);
        }

        if (imageMetrics != null && imageMetrics.get("IS_SHARP") != null) {
            boolean isSHarp = Boolean.parseBoolean(imageMetrics.get("IS_SHARP").toString());
            obj.put("IS_SHARP", isSHarp);
        }
        if (imageMetrics != null && imageMetrics.get("SHARPNESS_GRADE") != null) {
            float sharpnessGrade = Float.parseFloat(imageMetrics.get("SHARPNESS_GRADE").toString());
            obj.put("SHARPNESS_GRADE", sharpnessGrade);
        }

        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
        pluginResult.setKeepCallback(true);
        callbackId.sendPluginResult(pluginResult);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.acuant.plugin.AcuantMobileSDK.java

@Override
public void tagReadSucceeded(final AcuantNFCCardDetails cardDetails, final Bitmap face_image,
        final Bitmap sign_image) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/*from   ww w.j  ava 2s  .  com*/
        public void run() {
            try {
                JSONObject obj = new JSONObject();
                obj.put("id", "tagReadSucceeded");
                if (face_image != null) {
                    ByteArrayOutputStream faceImageByteArrayOutputStream = new ByteArrayOutputStream();
                    face_image.compress(Bitmap.CompressFormat.JPEG, 100, faceImageByteArrayOutputStream);
                    byte[] faceImageByte = faceImageByteArrayOutputStream.toByteArray();
                    obj.put("faceImage", Base64.encodeToString(faceImageByte, Base64.DEFAULT));
                }
                if (sign_image != null) {
                    ByteArrayOutputStream faceImageByteArrayOutputStream = new ByteArrayOutputStream();
                    sign_image.compress(Bitmap.CompressFormat.JPEG, 100, faceImageByteArrayOutputStream);
                    byte[] signImageByte = faceImageByteArrayOutputStream.toByteArray();
                    obj.put("signImage", Base64.encodeToString(signImageByte, Base64.DEFAULT));
                }
                JSONObject dataObject = EChipDataWithCard(cardDetails);
                obj.put("EChipData", dataObject);
                PluginResult result = new PluginResult(PluginResult.Status.OK, obj);
                result.setKeepCallback(true);
                callbackId.sendPluginResult(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.acuant.plugin.AcuantMobileSDK.java

@Override
public void tagReadFailed(final String tag_read_error_message) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/*from  w  w  w  .  j  av a2s.  c o m*/
        public void run() {
            try {
                JSONObject obj = new JSONObject();
                obj.put("id", "tagReadFailed");
                obj.put("errorType", ErrorType.AcuantErrorUnknown);
                obj.put("errorMessage", tag_read_error_message);
                PluginResult result = new PluginResult(PluginResult.Status.ERROR, obj);
                result.setKeepCallback(true);
                callbackId.sendPluginResult(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.adobe.phonegap.contentsync.Sync.java

License:Apache License

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("sync")) {
        sync(args, callbackContext);/*from   w  w  w  .  jav a2  s  .  co m*/
        return true;
    } else if (action.equals("download")) {
        final String source = args.getString(0);
        // Production
        String outputDirectory = cordova.getActivity().getCacheDir().getAbsolutePath();
        // Testing
        //String outputDirectory = cordova.getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        String filename = source.substring(source.lastIndexOf("/") + 1, source.length());
        final File target = new File(outputDirectory, filename);
        // @TODO we need these
        final JSONObject headers = new JSONObject();
        final CallbackContext finalContext = callbackContext;
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                if (download(source, target, headers, createProgressEvent("download"), finalContext, false)) {
                    JSONObject retval = new JSONObject();
                    try {
                        retval.put("archiveURL", target.getAbsolutePath());
                    } catch (JSONException e) {
                        // never happens
                    }
                    finalContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, retval));
                }
            }
        });
        return true;
    } else if (action.equals("unzip")) {
        String tempPath = args.getString(0);
        if (tempPath.startsWith("file://")) {
            tempPath = tempPath.substring(7);
        }
        final File source = new File(tempPath);
        final String target = args.getString(1);
        final CallbackContext finalContext = callbackContext;
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                unzipSync(source, target, createProgressEvent("unzip"), finalContext);
                finalContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
            }
        });
        return true;
    } else if (action.equals("cancel")) {
        ProgressEvent progress = activeRequests.get(args.getString(0));
        if (progress != null) {
            progress.setAborted(true);
        }
    }
    return false;
}

From source file:com.adobe.phonegap.contentsync.Sync.java

License:Apache License

private void sync(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    // get args// ww w  .  j  a  v a2  s . c om
    final String src = args.getString(0);
    final String id = args.getString(1);
    final JSONObject headers;
    if (args.optJSONObject(3) != null) {
        headers = args.optJSONObject(3);
    } else {
        headers = new JSONObject();
    }
    final boolean copyCordovaAssets;
    final boolean copyRootApp = args.getBoolean(5);
    final boolean trustEveryone = args.getBoolean(7);
    if (copyRootApp) {
        copyCordovaAssets = true;
    } else {
        copyCordovaAssets = args.getBoolean(4);
    }
    final String manifestFile = args.getString(8);
    Log.d(LOG_TAG, "sync called with id = " + id + " and src = " + src + "!");

    final ProgressEvent progress = createProgressEvent(id);

    /**
     * need to clear cache or Android won't pick up on the replaced
     * content
     */
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            webView.clearCache(true);
        }
    });

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            synchronized (progress) {
                if (progress.isAborted()) {
                    return;
                }
            }

            String outputDirectory = getOutputDirectory(id);

            // Check to see if we should just return the cached version
            String type = args.optString(2, TYPE_REPLACE);
            Log.d(LOG_TAG, "type = " + type);
            File dir = new File(outputDirectory);
            Log.d(LOG_TAG, "dir = " + dir.exists());

            if (type.equals(TYPE_LOCAL) && hasAppBeenUpdated()) {
                savePrefs();

                if ("null".equals(src) && (copyRootApp || copyCordovaAssets)) {
                    if (copyRootApp) {
                        Log.d(LOG_TAG, "doing copy root app");
                        copyRootApp(outputDirectory, manifestFile);
                    }
                    if (copyCordovaAssets) {
                        Log.d(LOG_TAG, "doing copy cordova app");
                        copyCordovaAssets(outputDirectory);
                    }

                } else {
                    type = TYPE_REPLACE;
                }
            }

            if (!dir.exists()) {
                dir.mkdirs();
            }

            if (!type.equals(TYPE_LOCAL)) {
                // download file
                if (download(src, createDownloadFileLocation(id), headers, progress, callbackContext,
                        trustEveryone)) {
                    // update progress with zip file
                    File targetFile = progress.getTargetFile();
                    Log.d(LOG_TAG, "downloaded = " + targetFile.getAbsolutePath());

                    // Backup existing directory
                    File backup = backupExistingDirectory(outputDirectory, type, dir);

                    // @TODO: Do we do this even when type is local?
                    if (copyRootApp) {
                        copyRootApp(outputDirectory, manifestFile);
                    }

                    boolean win = false;
                    if (isZipFile(targetFile)) {
                        win = unzipSync(targetFile, outputDirectory, progress, callbackContext);
                    } else {
                        // copy file to ID
                        win = targetFile.renameTo(new File(outputDirectory));
                        progress.setLoaded(1);
                        progress.setTotal(1);
                        progress.setStatus(STATUS_EXTRACTING);
                        progress.updatePercentage();
                    }

                    // delete temp file
                    targetFile.delete();

                    if (copyCordovaAssets) {
                        copyCordovaAssets(outputDirectory);
                    }

                    if (win) {
                        // success, remove backup
                        removeFolder(backup);
                    } else {
                        // failure, revert backup
                        removeFolder(dir);
                        backup.renameTo(dir);
                    }
                } else {
                    return;
                }
            }

            // complete
            synchronized (activeRequests) {
                activeRequests.remove(id);
            }

            // Send last progress event
            progress.setStatus(STATUS_COMPLETE);
            updateProgress(callbackContext, progress);

            // Send completion message
            try {
                JSONObject result = new JSONObject();
                result.put(PROP_LOCAL_PATH, outputDirectory);

                if (dir.list() != null) {
                    Log.d(LOG_TAG, "size of output dir = " + dir.list().length);
                }
                boolean cached = false;
                if (type.equals(TYPE_LOCAL) && dir.exists() && dir.isDirectory() && dir.list() != null
                        && dir.list().length > 0) {
                    Log.d(LOG_TAG, "we have a dir with some files in it.");
                    cached = true;
                }

                result.put(PROP_CACHED, cached);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
            } catch (JSONException e) {
                // never happens
            }
        }
    });
}

From source file:com.adobe.phonegap.contentsync.Sync.java

License:Apache License

private void updateProgress(CallbackContext callbackContext, ProgressEvent progress) {
    try {//  w w  w  . ja v  a  2 s . c  om
        if (progress.getLoaded() != progress.getTotal() || progress.getStatus() == STATUS_COMPLETE) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }
    } catch (JSONException e) {
        // never happens
    }
}

From source file:com.adobe.plugins.FastCanvasView.java

License:Apache License

public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    Log.i(TAG, "execute: " + action);

    try {/*  w  w  w. j a  va2 s  . co m*/

        if (action.equals("render")) {
            renderCommand = args.getString(0);
            return true;

        } else if (action.equals("setBackgroundColor")) {
            String color = args.getString(0);
            Log.i(TAG, "setBackground: " + color);
            try {
                int red = Integer.valueOf(color.substring(0, 2), 16);
                int green = Integer.valueOf(color.substring(2, 4), 16);
                int blue = Integer.valueOf(color.substring(4, 6), 16);
                FastCanvasJNI.setBackgroundColor(red, green, blue);
            } catch (Exception e) {
                Log.e(TAG, "Invalid background color: " + color, e);
            }

            return true;

        } else if (action.equals("loadTexture")) {
            final Texture texture = new Texture(args.getString(0), args.getInt(1));
            Log.i(TAG, "loadTexture " + texture);
            queue.offer(new Command() {
                @Override
                public void exec() {
                    loadTexture(texture, callbackContext);
                }
            });
            return true;

        } else if (action.equals("unloadTexture")) {
            Log.i(TAG, "unload texture");
            int id = args.getInt(0);
            unloadTexture(id);

            return true;

        } else if (action.equals("setOrtho")) {
            int width = args.getInt(0);
            int height = args.getInt(1);

            Log.i(TAG, "setOrtho: " + width + ", " + height);
            FastCanvasJNI.setOrtho(width, height);

            return true;

        } else if (action.equals("capture")) {
            Log.i(TAG, "capture");

            // set the root path to /mnt/sdcard/
            String file = Environment.getExternalStorageDirectory() + args.getString(4);
            File dir = new File(file).getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs()) {
                callbackContext.sendPluginResult(
                        new PluginResult(PluginResult.Status.ERROR, "Could not create directory"));
                return true;
            }

            int x = args.optInt(0, 0);
            int y = args.optInt(1, 0);
            int width = args.optInt(2, -1);
            int height = args.optInt(3, -1);

            FastCanvasJNI.captureGLLayer(callbackContext.getCallbackId(), x, y, width, height, file);

            return true;

        } else if (action.equals("toDataURL")) {
            Log.i(TAG, "toDataURL");

            String mimeType = args.getString(0);
            int quality = args.getInt(1);
            int width = args.getInt(2);
            int height = args.getInt(3);
            Log.i(TAG, "toDataURL[" + mimeType + "][" + quality + "] = " + width + "x" + height);
            // toDataURL(mimeType, quality);

            byte[] pixels = FastCanvasJNI.captureGLLayerDirect(width, height);
            Log.i(TAG, "toDataURL::pixels = " + pixels + " = " + pixels.length);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Bitmap bmp = BitmapFactory.decodeByteArray(pixels, 0, pixels.length);
            bmp.compress(Bitmap.CompressFormat.JPEG, quality, out);

            String dataURL = "data:" + mimeType + ";base64," + Base64.encodeToString(out.toByteArray(), 0);

            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, dataURL));
            return true;

        } else if (action.equals("isAvailable")) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true));
            return true;

        } else {
            Log.i(TAG, "invalid execute action: " + action);
        }

    } catch (Exception e) {
        Log.e(TAG, "error executing action: " + action + "(" + args + ")", e);
    }

    return false;
}

From source file:com.afreire.plugins.video.VideoPlayer.java

License:BSD License

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {//from  w  w  w .  j ava 2s . co m
        if (action.equals("playVideo")) {
            playVideo(args.getString(0));
        } else {
            status = PluginResult.Status.INVALID_ACTION;
        }
        callbackContext.sendPluginResult(new PluginResult(status, result));
    } catch (JSONException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
    } catch (IOException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
    }
    return true;
}

From source file:com.android.plugins.GyroscopeListener.java

License:Open Source License

/**
 * Executes the request.// w  w  w .j a  v a 2s.com
 *
 * @param action        The action to execute.
 * @param args          The exec() arguments.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              Whether the action was valid.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        this.callbackContext = callbackContext;
        if (this.status != GyroscopeListener.RUNNING) {
            // If not running, then this is an async call, so don't worry about waiting
            // We drop the callback onto our stack, call start, and let start and the sensor callback fire off the callback down the road
            this.start();
        }
    } else if (action.equals("stop")) {
        if (this.status == GyroscopeListener.RUNNING) {
            this.stop();
        }
    } else {
        // Unsupported action
        return false;
    }

    PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT, "");
    result.setKeepCallback(true);
    callbackContext.sendPluginResult(result);
    return true;
}

From source file:com.android.plugins.GyroscopeListener.java

License:Open Source License

private void fail(int code, String message) {
    // Error object
    JSONObject errorObj = new JSONObject();
    try {/*from ww  w. jav  a 2s.co  m*/
        errorObj.put("code", code);
        errorObj.put("message", message);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    PluginResult err = new PluginResult(PluginResult.Status.ERROR, errorObj);
    err.setKeepCallback(true);
    callbackContext.sendPluginResult(err);
}