Example usage for org.apache.cordova CallbackContext getCallbackId

List of usage examples for org.apache.cordova CallbackContext getCallbackId

Introduction

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

Prototype

public String getCallbackId() 

Source Link

Usage

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 {//from   w  w w  . j  a  v  a  2s .c om

        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.ayogo.cordova.notification.NotificationPlugin.java

License:Apache License

@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callback) {

    if (action.equals("requestPermission")) {
        callback.sendPluginResult(new PluginResult(PluginResult.Status.OK, "granted"));
        return true;
    }//from  w w w .j  av a2s  . co  m

    if (action.equals("showNotification")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    String title = args.getString(0);
                    JSONObject options = args.getJSONObject(1);

                    if (options.optString("tag", null) == null) {
                        options.put("tag", callback.getCallbackId());
                    }

                    LOG.v(TAG, "Schedule Notification: " + title);

                    mgr.scheduleNotification(title, options);

                    callback.sendPluginResult(new PluginResult(PluginResult.Status.OK));
                } catch (JSONException ex) {
                    callback.sendPluginResult(
                            new PluginResult(PluginResult.Status.ERROR, "Missing or invalid title or options"));
                }
            }
        });
        return true;
    }

    if (action.equals("closeNotification")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    String tag = args.getString(0);

                    LOG.v(TAG, "cancel Notification: " + tag);

                    mgr.cancelNotification(tag);

                    callback.sendPluginResult(new PluginResult(PluginResult.Status.OK));
                } catch (JSONException ex) {
                    callback.sendPluginResult(
                            new PluginResult(PluginResult.Status.ERROR, "Missing or invalid title or options"));
                }
            }
        });
        return true;
    }

    if (action.equals("getNotifications")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                LOG.v(TAG, "Get Notifications");

                JSONArray notifications = mgr.getNotifications();

                // Android doesn't require permission to send push notifications
                callback.sendPluginResult(new PluginResult(PluginResult.Status.OK, notifications));
            }
        });
        return true;
    }

    LOG.i(TAG, "Tried to call " + action + " with " + args.toString());

    callback.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
    return false;
}

From source file:com.cloudant.sync.cordova.CloudantSyncPlugin.java

License:Open Source License

private void resolveConflictsForDocument(final String documentStoreName, final String documentId,
        final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/* w  w w.j a  va 2 s .  c o  m*/
        public void run() {
            try {
                DocumentStore ds = getDocumentStore(documentStoreName);

                ConflictResolverWrapper conflictResolver = new ConflictResolverWrapper(callbackContext);

                // Store the conflictResolver in a map indexed by a unique ID that can be passed around
                // to retrieve the conflictResolver from other callbacks. The callbackId is unique
                // to each invocation of this method so we'll use that.
                resolverMap.put(callbackContext.getCallbackId(), conflictResolver);
                ds.database().resolveConflicts(documentId, conflictResolver);
                PluginResult r = new PluginResult(PluginResult.Status.OK);
                callbackContext.sendPluginResult(r);

            } catch (Exception e) {
                callbackContext.error(e.getMessage());
            }
        }
    });
}

From source file:com.commontime.plugin.LocationManager.java

License:Apache License

private void registerDelegateCallbackId(JSONObject arguments, final CallbackContext callbackContext) {

    _handleCallSafely(callbackContext, new ILocationManagerCommand() {

        @Override//w w w.j  a v  a 2  s  .  c o  m
        public PluginResult run() {
            debugLog("Registering delegate callback ID: " + callbackContext.getCallbackId());
            //delegateCallbackId = callbackContext.getCallbackId();

            createMonitorCallbacks(callbackContext);
            createRangingCallbacks(callbackContext);
            createManagerCallbacks(callbackContext);

            PluginResult result = new PluginResult(PluginResult.Status.OK);
            result.setKeepCallback(true);
            return result;
        }
    });

}

From source file:com.dtworkshop.inappcrossbrowser.WebViewBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @return              A PluginResult object with a status and message.
 *//*  w ww  .  ja va  2  s . c om*/
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");
                    /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
                     * Previously the Config class had a static method, isUrlWhitelisted(). That
                     * responsibility has been moved to the plugins, with an aggregating method in
                     * PluginManager.
                     */
                    Boolean shouldAllowNavigation = null;
                    if (url.startsWith("javascript:")) {
                        shouldAllowNavigation = true;
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
                            shouldAllowNavigation = (Boolean) iuw.invoke(null, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method gpm = webView.getClass().getMethod("getPluginManager");
                            PluginManager pm = (PluginManager) gpm.invoke(webView);
                            Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
                            shouldAllowNavigation = (Boolean) san.invoke(pm, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    // load in webview
                    if (Boolean.TRUE.equals(shouldAllowNavigation)) {
                        Log.d(LOG_TAG, "loading in webview");
                        webView.loadUrl(url);
                    }
                    //Load the dialer
                    else 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());
                        }
                    }
                    // load in InAppBrowser
                    else {
                        Log.d(LOG_TAG, "loading in InAppBrowser");
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    Log.d(LOG_TAG, "in system");
                    result = openExternal(url);
                }
                // perso a3d HORIZONTAL
                else if (BLANKH.equals(target)) {
                    Log.d(LOG_TAG, "in blank horizontal");
                    result = showWebPage(url, features);
                }
                // BLANK - or anything else
                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;
}

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 {//w  ww  . j av a2s  .  c  o  m
        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.glasgowtiger.inappbrowser.InAppBrowser.java

License:Apache License

/**
 * 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.
 *//*from w  w w.  ja v a 2s  .c  o m*/
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");
                    /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
                     * Previously the Config class had a static method, isUrlWhitelisted(). That
                     * responsibility has been moved to the plugins, with an aggregating method in
                     * PluginManager.
                     */
                    Boolean shouldAllowNavigation = null;
                    if (url.startsWith("javascript:")) {
                        shouldAllowNavigation = true;
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
                            shouldAllowNavigation = (Boolean) iuw.invoke(null, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method gpm = webView.getClass().getMethod("getPluginManager");
                            PluginManager pm = (PluginManager) gpm.invoke(webView);
                            Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
                            shouldAllowNavigation = (Boolean) san.invoke(pm, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    // load in webview
                    if (Boolean.TRUE.equals(shouldAllowNavigation)) {
                        Log.d(LOG_TAG, "loading in webview");
                        webView.loadUrl(url);
                    }
                    //Load the dialer
                    else 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());
                        }
                    }
                    // load in InAppBrowser
                    else {
                        Log.d(LOG_TAG, "loading in InAppBrowser");
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    Log.d(LOG_TAG, "in system");
                    result = openExternal(url);
                }
                // BLANK - or anything else
                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;
}

From source file:com.ibm.mqtt.android.cordova.plugin.MqttPlugin.java

License:Open Source License

@Override
/**//from   w  w w . j a  v  a 2 s . c om
 * This method takes the data passed through from javascript via "cordova.exec" and
 * makes appropriate method calls to the service.
 * Most calls will respond by broadcasting intents which our callbacklistener handles
 * 
 * This is a large method, but falls naturally into sections based on the action being
 * processed, so it doesn't seem necessary to split it into multiple methods.
 * 
 * @param action the action to be performed (see MqttServiceConstants)
 * @param args the parameters specified by the javascript code
 * @param callbackId 
 *       the callbackId which can be used to invoke to the success/failure callbacks
 *       provide to the cordova.execute call
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    traceDebug(TAG, "execute(" + action + ",{" + args + "}," + callbackContext.getCallbackId() + ")",
            callbackContext);
    try {
        if (action.equals(MqttServiceConstants.START_SERVICE_ACTION)) {
            if (mqttService != null) {
                traceDebug(TAG, "execute - service already started", callbackContext);
                return true;
            }
            serviceIntent = new Intent(context, MqttService.class);
            serviceIntent.putExtra(MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN,
                    callbackContext.getCallbackId());
            ComponentName serviceComponentName = context.startService(serviceIntent);

            if (serviceComponentName == null) {
                traceError(TAG, "execute() - could not start " + MqttService.class, callbackContext);
                return false;
            }

            if (context.bindService(serviceIntent, serviceConnection, 0)) {
                // we return Status.NO_RESULT and setKeepCallback(true)
                // so that the callbackListener can use this callbackId
                // when it receives a connected event
                PluginResult result = new PluginResult(Status.NO_RESULT);
                result.setKeepCallback(true);

                callbackContext.sendPluginResult(result);
                return true;
            }
            return false;
        }

        if (action.equals(MqttServiceConstants.SET_TRACE_CALLBACK)) {
            // This is a trifle inelegant
            traceCallbackId = callbackContext.getCallbackId();
            if (mqttService != null) {
                mqttService.setTraceCallbackId(callbackContext.getCallbackId());
            }
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SET_TRACE_ENABLED)) {
            traceEnabled = true;
            if (mqttService != null) {
                mqttService.setTraceEnabled(traceEnabled);
            }
            PluginResult result = new PluginResult(Status.OK);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SET_TRACE_DISABLED)) {
            traceEnabled = false;
            if (mqttService != null) {
                mqttService.setTraceEnabled(traceEnabled);
            }
            PluginResult result = new PluginResult(Status.OK);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (mqttService == null) {
            return false;
        }

        if (action.equals(MqttServiceConstants.STOP_SERVICE_ACTION)) {
            Intent serviceIntent = new Intent(context, MqttService.class);
            context.stopService(serviceIntent);
            mqttService = null;
            return true;
        }

        if (action.equals(MqttServiceConstants.GET_CLIENT_ACTION)) {
            // This is a simple operation and we do it synchronously
            String clientHandle;
            try {
                String host = args.getString(0);
                int port = args.getInt(1);
                String clientId = args.getString(2);
                clientHandle = mqttService.getClient(host, port, clientId);

                // Set up somewhere to hold callbacks for this client
                callbackMap.put(clientHandle, new HashMap<String, String>());
            } catch (JSONException e) {
                traceException(TAG, "execute()", e, callbackContext);
                return false;
            }
            // We return a clientHandle to the javascript client,
            // which it can use to identify the client on subsequent calls
            return true;
        }

        // All remaining actions have a clientHandle as their first arg
        String clientHandle = args.getString(0);

        if (action.equals(MqttServiceConstants.CONNECT_ACTION)) {
            int timeout = args.getInt(1);
            boolean cleanSession = args.getBoolean(2);
            String userName = args.optString(3);
            String passWord = args.optString(4);
            int keepAliveInterval = args.getInt(5);
            JSONObject jsMsg = args.optJSONObject(6);
            MessagingMessage willMessage = (jsMsg == null) ? null : messageFromJSON(jsMsg, callbackContext);
            boolean useSSL = args.getBoolean(7);
            Properties sslProperties = null;
            JSONObject jsSslProperties = args.getJSONObject(8);
            if (jsSslProperties.length() != 0) {
                sslProperties = new Properties();
                Iterator<?> sslPropertyIterator = jsSslProperties.keys();
                while (sslPropertyIterator.hasNext()) {
                    String propertyName = (String) sslPropertyIterator.next();
                    String propertyValue = jsSslProperties.getString(propertyName);
                    sslProperties.put("com.ibm.ssl." + propertyName, propertyValue);
                }
            }
            String invocationContext = args.optString(9);
            mqttService.connect(clientHandle, timeout, cleanSession, userName, passWord, keepAliveInterval,
                    willMessage, useSSL, sslProperties, invocationContext, callbackContext.getCallbackId());
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.DISCONNECT_ACTION)) {
            String invocationContext = args.optString(1);
            mqttService.disconnect(clientHandle, invocationContext, callbackContext.getCallbackId());
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SEND_ACTION)) {
            JSONObject jsMsg = args.getJSONObject(1);
            MessagingMessage msg = messageFromJSON(jsMsg, callbackContext);
            String invocationContext = args.optString(2);
            mqttService.send(clientHandle, msg, invocationContext, callbackContext.getCallbackId());
            // we return Status.NO_RESULT and setKeepCallback(true)
            // so that the callbackListener can use this callbackId
            // at an appropriate time - what time that is depends on
            // the qos value specified.
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SUBSCRIBE_ACTION)) {
            String topicFilter = args.getString(1);
            int qos = args.getInt(2);
            String invocationContext = args.optString(3);
            mqttService.subscribe(clientHandle, topicFilter, qos, invocationContext,
                    callbackContext.getCallbackId());
            // we return Status.NO_RESULT and setKeepCallback(true)
            // so that the callbackListener can use this callbackId
            // when it receives an event from the subscribe operation
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.UNSUBSCRIBE_ACTION)) {
            String topicFilter = args.getString(1);
            String invocationContext = args.optString(2);
            mqttService.unsubscribe(clientHandle, topicFilter, invocationContext,
                    callbackContext.getCallbackId());
            // we return Status.NO_RESULT and setKeepCallback(true)
            // so that the callbackListener can use this callbackId
            // when it receives an event from the unsubscribe operation
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.ACKNOWLEDGE_RECEIPT_ACTION)) {
            // This is a synchronous operation
            String id = args.getString(1);
            return mqttService.acknowledgeMessageArrival(clientHandle, id);
        }

        // The remaining actions are used to register callbacks for
        // "unsolicited" events
        if (action.equals(MqttServiceConstants.SET_ON_CONNECTIONLOST_CALLBACK)) {
            return setCallback(clientHandle, MqttServiceConstants.ON_CONNECTION_LOST_ACTION, callbackContext);
        }
        if (action.equals(MqttServiceConstants.SET_ON_MESSAGE_DELIVERED_CALLBACK)) {
            return setCallback(clientHandle, MqttServiceConstants.MESSAGE_DELIVERED_ACTION, callbackContext);
        }
        if (action.equals(MqttServiceConstants.SET_ON_MESSAGE_ARRIVED_CALLBACK)) {
            boolean setCallbackResult = setCallback(clientHandle, MqttServiceConstants.MESSAGE_ARRIVED_ACTION,
                    callbackContext);
            return setCallbackResult;
        }

    } catch (JSONException e) {
        return false;
    } catch (IllegalArgumentException e) {
        return false;
    }

    return false;
}

From source file:com.ibm.mqtt.android.cordova.plugin.MqttPlugin.java

License:Open Source License

private boolean setCallback(String clientHandle, String action, CallbackContext callbackContext) {
    Map<String /* action */, String /* callbackId */> clientCallbacks = callbackMap.get(clientHandle);
    if (clientCallbacks == null) {
        return false;
    }/*from w w  w.  ja va2 s.co  m*/
    clientCallbacks.put(action, callbackContext.getCallbackId());
    PluginResult result = new PluginResult(Status.NO_RESULT);
    result.setKeepCallback(true); // keep it around

    callbackContext.sendPluginResult(result);
    return true;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments, wrapped with some Cordova helpers.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return/*from   www.ja va  2  s  . co  m*/
 * @throws JSONException
 */
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 Options features = parseFeature(args.optString(2));
        customSchema = features.customSchema;

        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
                     * Previously the Config class had a static method, isUrlWhitelisted(). That
                     * responsibility has been moved to the plugins, with an aggregating method in
                     * PluginManager.
                     */
                    Boolean shouldAllowNavigation = null;
                    if (url.startsWith("javascript:")) {
                        shouldAllowNavigation = true;
                    }
                    if (shouldAllowNavigation == null) {
                        shouldAllowNavigation = new Whitelist().isUrlWhiteListed(url);
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method gpm = webView.getClass().getMethod("getPluginManager");
                            PluginManager pm = (PluginManager) gpm.invoke(webView);
                            Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
                            shouldAllowNavigation = (Boolean) san.invoke(pm, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    // load in webview
                    if (Boolean.TRUE.equals(shouldAllowNavigation)) {
                        webView.loadUrl(url);
                    }
                    //Load the dialer
                    else if (url.startsWith(WebView.SCHEME_TEL)) {
                        try {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse(url));
                            cordova.getActivity().startActivity(intent);
                        } catch (android.content.ActivityNotFoundException e) {
                            emitError(ERR_CRITICAL, String.format("Error dialing %s: %s", url, e.toString()));
                        }
                    }
                    // load in ThemeableBrowser
                    else {
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    result = openExternal(url);
                }
                // BLANK - or anything else
                else {
                    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 if (action.equals("reload")) {
        if (inAppWebView != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    inAppWebView.reload();
                }
            });
        }
    } else {
        return false;
    }
    return true;
}