Example usage for org.apache.cordova PluginResult setKeepCallback

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

Introduction

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

Prototype

public void setKeepCallback(boolean b) 

Source Link

Usage

From source file:com.bsafe.sensors.motion.BSMotionSensorsPlugin.java

License:Apache License

private void win() {
    // Success return object
    PluginResult result = new PluginResult(PluginResult.Status.OK, this.getAccelerationJSON());
    result.setKeepCallback(true);
    callbackContext.sendPluginResult(result);
}

From source file:com.ca.mas.cordova.connecta.MASConnectaPlugin.java

License:Open Source License

/**
 * Register the listener for incoming messages
 *///  w  w  w  .jav a  2 s.c  o m
private void registerReceiver(final JSONArray args, final CallbackContext callbackContext) {
    _messageReceiverCallback = callbackContext;
    if (!isListenerRegistered) {
        try {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectaConsts.MAS_CONNECTA_BROADCAST_MESSAGE_ARRIVED);
            LocalBroadcastManager.getInstance(this.cordova.getActivity())
                    .registerReceiver(new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context context, Intent intent) {
                            if (!intent.getAction()
                                    .equals(ConnectaConsts.MAS_CONNECTA_BROADCAST_MESSAGE_ARRIVED)) {
                                return;
                            }
                            try {
                                MASMessage message = MASMessage.newInstance(intent);
                                try {
                                    final String senderId = message.getSenderId();
                                    final String contentType = message.getContentType();
                                    if (contentType.startsWith("image")) {
                                        byte[] msg = message.getPayload();
                                        if (MAS.DEBUG) {
                                            Log.w(TAG, "message receiver got image from " + senderId
                                                    + ", image length " + msg.length);
                                        }
                                    } else {
                                        byte[] msg = message.getPayload();
                                        String m = new String(msg);
                                        if (MAS.DEBUG) {
                                            Log.w(TAG, "message receiver got text message from " + senderId
                                                    + ", " + m);
                                        }
                                    }
                                } catch (Exception ignore) {

                                }
                                JSONObject obj = new JSONObject(
                                        message.createJSONStringFromMASMessage(context));
                                String payload = obj.getString("Payload");
                                byte[] payloadBytes = decodeBase64IncomingMessage(payload);
                                payload = new String(payloadBytes);
                                obj.put("Payload", payload);
                                PluginResult result = new PluginResult(PluginResult.Status.OK, obj);
                                result.setKeepCallback(true);
                                _messageReceiverCallback.sendPluginResult(result);
                            } catch (Exception jce) {
                                Log.e(TAG, "message parse exception: " + jce);
                                JSONObject obj = getError(new MASCordovaException("Invalid Message received"));
                                PluginResult result = new PluginResult(PluginResult.Status.ERROR, obj);
                                result.setKeepCallback(true);
                                _messageReceiverCallback.sendPluginResult(result);
                            }
                        }
                    }, intentFilter);
            isListenerRegistered = true;
            PluginResult result = new PluginResult(PluginResult.Status.OK, true);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        } catch (Exception ex) {
            isListenerRegistered = false;
            Log.e(TAG, "initMessageReceiver exception: " + ex);
            callbackContext.error("Unable to initialize:" + ex.getMessage());
        }
    }
}

From source file:com.cem.echo.Echo.java

protected boolean getCertificateList(CallbackContext callbackContext) {
    System.out.println("-----getcertlist: entrance deneme");

    List<String> certs = new ArrayList<String>();

    try {/*  www  . ja v  a  2 s.c  om*/
        /*            InputStream lisansStream = cordova.getActivity().getResources().openRawResource(cordova.getActivity().getResources().getIdentifier("lisans", "raw", cordova.getActivity().getPackageName()));
                    LicenseUtil.setLicenseXml(lisansStream);
                    lisansStream.close();*/

        Resources activityRes = cordova.getActivity().getResources();
        int lisansid = activityRes.getIdentifier("lisans", "raw", cordova.getActivity().getPackageName());
        InputStream lisansStream = activityRes.openRawResource(lisansid);
        LicenseUtil.setLicenseXml(lisansStream);
        lisansStream.close();

        System.out.println("-----getcertlist: lisans aldik");

        mTerminalHandler = new SCDTerminalHandler(cordova.getActivity());

        mAPDUSmartCard = new APDUSmartCard(mTerminalHandler);
        mAPDUSmartCard.setDisableSecureMessaging(true);

        CardTerminal[] terminalList = mAPDUSmartCard.getTerminalList();

        CardTerminal cardTerminal = terminalList[0];

        //System.out.println("hehehe " + terminalList[0]);

        mAPDUSmartCard.openSession(cardTerminal);
        String readerName = cardTerminal.getName();
        List<byte[]> signCertValueList = mAPDUSmartCard.getSignatureCertificates();

        certificateList = new ArrayList<ECertificate>();

        for (byte[] signCertValue : signCertValueList) {
            ECertificate signCert = new ECertificate(signCertValue);
            //Sadece nitelikli sertifikalar ekiliyor.
            //Kanuni geerlilii olmayan sertifikalarla imza atlmak istenirse bu kontrol kaldrlabilir.
            //  if(signCert.isQualifiedCertificate()){
            certificateList.add(signCert);
            System.out.println("Sertifika Sahibi :" + signCert.getSubject().getCommonNameAttribute());
            certs.add(signCert.getSubject().getCommonNameAttribute());
            //}
        }
    } catch (Exception e) {
        e.printStackTrace();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        //callbackContext.error("Sertifikalar alrken bir hata olutu.");
        return false;
    }

    String[] res = new String[certs.size()];
    certs.toArray(res);

    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, new JSONArray(certs));
    pluginResult.setKeepCallback(true);
    callbackContext.sendPluginResult(pluginResult);
    //callbackContext.success(new JSONArray(certs));
    return true;
}

From source file:com.cem.echo.Echo.java

protected boolean sign(int _certIndex, String _password, String _sourceFilePath, String _destFilePath,
        CallbackContext _callbackContext) {
    final int certIndex = _certIndex;
    final String password = _password;
    final String sourceFilePath = _sourceFilePath.replaceAll("file://", "");
    final String destFilePath = _destFilePath.replaceAll("file://", "");

    final CallbackContext callbackContext = _callbackContext;

    System.out.println("-----sign: entrance: " + certIndex + " " + password + " " + sourceFilePath);
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            try {

                mAPDUSmartCard.login(password);

                ECertificate signCert = certificateList.get(certIndex);

                BaseSigner signer = mAPDUSmartCard.getSigner(signCert.asX509Certificate(),
                        Algorithms.SIGNATURE_RSA_SHA1);
                BaseSignedData bsd = new BaseSignedData();

                System.out.println("--------------LOGIN BASARILI------------");

                /*File tempFile = new File("cem1.txt");
                System.out.println("---temp file: " + tempFile.getAbsolutePath());
                        /*from www. j  a v a  2  s .  c om*/
                CordovaResourceApi resourceApi = webView.getResourceApi();
                Uri sourceUri = resourceApi.remapUri(Uri.fromFile(new File("cem2.txt")));
                System.out.println("---source uri: " + sourceUri);
                        
                tempFile = resourceApi.mapUriToFile(Uri.parse(sourceFilePath));
                System.out.println("sourcefilepath....");
                if(tempFile != null) {
                System.out.println(tempFile.getAbsolutePath());
                } else {
                System.out.println("null file");
                }
                        
                System.out.println("sourceuri...");
                tempFile = resourceApi.mapUriToFile(sourceUri);
                if(tempFile != null) {
                System.out.println(tempFile.getAbsolutePath());
                } else {
                System.out.println("null file");
                }*/

                ISignable content = new SignableFile(new File(sourceFilePath));
                bsd.addContent(content);
                //Since SigningTime attribute is optional,add it to optional attributes list
                List<IAttribute> optionalAttributes = new ArrayList<IAttribute>();
                optionalAttributes.add(new SigningTimeAttr(Calendar.getInstance()));
                HashMap<String, Object> params = new HashMap<String, Object>();

                params.put(EParameters.P_VALIDATE_CERTIFICATE_BEFORE_SIGNING, false);
                bsd.addSigner(ESignatureType.TYPE_BES, signCert, signer, optionalAttributes, params);
                byte[] signedDocument = bsd.getEncoded();
                System.out.println("mzalama ilemi tamamland. Dosyaya yazlacak. Imzali Veri ="
                        + (signedDocument.toString()));

                AsnIO.dosyayaz(signedDocument, destFilePath);

                mAPDUSmartCard.logout();
                mAPDUSmartCard.closeSession();
            } catch (Exception e) {
                e.printStackTrace();
                PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
                //callbackContext.error("mzalama srasnda bir hata olutu. Ltfen ifrenizi kontrol edip tekrar deneyiniz.");
                //return false;
            }

            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
            //callbackContext.success();
            //return true;
        }
    });

    return true;

}

From source file:com.clevertap.cordova.CleverTapPlugin.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    Log.d(LOG_TAG, "handling action " + action);

    boolean haveError = false;
    String errorMsg = "unhandled CleverTapPlugin action";

    PluginResult result = null;

    if (!checkCleverTapInitialized()) {
        result = new PluginResult(PluginResult.Status.ERROR, "CleverTap API not initialized");
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }//www. j  ava 2  s  .  c o  m

    // not required for Android here but handle as its in the JS interface
    else if (action.equals("registerPush")) {
        result = new PluginResult(PluginResult.Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    // not required for Android here but handle as its in the JS interface
    else if (action.equals("setPushTokenAsString")) {
        result = new PluginResult(PluginResult.Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    else if (action.equals("setDebugLevel")) {
        int level = (args.length() == 1 ? args.getInt(0) : -1);
        if (level >= 0) {
            CleverTapAPI.setDebugLevel(level);
            result = new PluginResult(PluginResult.Status.NO_RESULT);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
            return true;
        }

    }

    else if (action.equals("enablePersonalization")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                cleverTap.enablePersonalization();
                PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;

    }

    else if (action.equals("recordEventWithName")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.event.push(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("recordEventWithNameAndProps")) {
        String eventName = null;
        JSONObject jsonProps;
        HashMap<String, Object> _props = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                eventName = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "eventName cannot be null";
            }
            if (!args.isNull(1)) {
                jsonProps = args.getJSONObject(1);
                try {
                    _props = toMap(jsonProps);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing event properties";
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _eventName = eventName;
            final HashMap<String, Object> props = _props;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.event.push(_eventName, props);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("recordChargedEventWithDetailsAndItems")) {
        JSONObject jsonDetails;
        JSONArray jsonItems;
        HashMap<String, Object> _details = null;
        ArrayList<HashMap<String, Object>> _items = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                jsonDetails = args.getJSONObject(0);
                try {
                    _details = toMap(jsonDetails);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
            if (!args.isNull(1)) {
                jsonItems = args.getJSONArray(1);
                try {
                    _items = toArrayListOfStringObjectMaps(jsonItems);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final HashMap<String, Object> details = _details;
            final ArrayList<HashMap<String, Object>> items = _items;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        cleverTap.event.push(CleverTapAPI.CHARGED_EVENT, details, items);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    } catch (InvalidEventNameException e) {
                        PluginResult _result = new PluginResult(PluginResult.Status.ERROR,
                                e.getLocalizedMessage());
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                }
            });
            return true;
        }
    }

    else if (action.equals("eventGetFirstTime")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    double first = cleverTap.event.getFirstTime(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, (float) first);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetLastTime")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    double lastTime = cleverTap.event.getLastTime(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, (float) lastTime);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetOccurrences")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    int num = cleverTap.event.getCount(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, num);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetDetails")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    EventDetail details = cleverTap.event.getDetails(eventName);
                    try {
                        JSONObject jsonDetails = CleverTapPlugin.eventDetailsToJSON(details);
                        PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    } catch (JSONException e) {
                        PluginResult _result = new PluginResult(PluginResult.Status.ERROR,
                                e.getLocalizedMessage());
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("getEventHistory")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                Map<String, EventDetail> history = cleverTap.event.getHistory();
                try {
                    JSONObject jsonDetails = CleverTapPlugin.eventHistoryToJSON(history);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                } catch (JSONException e) {
                    PluginResult _result = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            }
        });
        return true;
    }

    else if (action.equals("setLocation")) {
        Double lat = null;
        Double lon = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                lat = args.getDouble(0);
            } else {
                haveError = true;
                errorMsg = "lat cannot be null";
            }
            if (!args.isNull(1)) {
                lon = args.getDouble(1);
            } else {
                haveError = true;
                errorMsg = "lon cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final Location location = new Location("CleverTapPlugin");
            location.setLatitude(lat);
            location.setLongitude(lon);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.updateLocation(location);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileSet")) {
        JSONObject jsonProfile = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonProfile = args.getJSONObject(0);
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final JSONObject _jsonProfile = jsonProfile;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        HashMap<String, Object> profile = toMap(_jsonProfile);
                        String dob = (String) profile.get("DOB");
                        if (dob != null) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
                            try {
                                Date date = format.parse(dob);
                                profile.put("DOB", date);
                            } catch (ParseException e) {
                                profile.remove("DOB");
                                Log.d(LOG_TAG, "invalid DOB format in profileSet");
                            }
                        }

                        cleverTap.profile.push(profile);

                    } catch (Exception e) {
                        Log.d(LOG_TAG, "Error setting profile " + e.getLocalizedMessage());
                    }

                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });

            return true;
        }
    }

    else if (action.equals("profileSetGraphUser")) {
        JSONObject jsonGraphUser = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonGraphUser = args.getJSONObject(0);
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final JSONObject _jsonGraphUser = jsonGraphUser;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.pushFacebookUser(_jsonGraphUser);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileSetGooglePlusUser")) {
        JSONObject jsonGooglePlusUser;
        HashMap<String, Object> _profile = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonGooglePlusUser = args.getJSONObject(0);
                try {
                    _profile = toMapFromGooglePlusUser(jsonGooglePlusUser);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final HashMap<String, Object> profile = _profile;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.push(profile);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileGetProperty")) {
        final String propertyName = (args.length() == 1 ? args.getString(0) : null);
        if (propertyName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult _result;
                    Object prop = cleverTap.profile.getProperty(propertyName);

                    if (prop instanceof JSONArray) {
                        JSONArray _prop = (JSONArray) prop;
                        _result = new PluginResult(PluginResult.Status.OK, _prop);

                    } else {
                        String _prop;
                        if (prop != null) {
                            _prop = prop.toString();
                        } else {
                            _prop = null;
                        }
                        _result = new PluginResult(PluginResult.Status.OK, _prop);
                    }

                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "propertyName cannot be null";
        }
    }

    else if (action.equals("profileGetCleverTapID")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String CleverTapID = cleverTap.getCleverTapID();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, CleverTapID);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("profileRemoveValueForKey")) {
        final String key = (args.length() == 1 ? args.getString(0) : null);
        if (key != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.removeValueForKey(key);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "property key cannot be null";
        }
    }

    else if (action.equals("profileSetMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.setMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    }

    else if (action.equals("profileAddMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.addMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    } else if (action.equals("profileRemoveMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.removeMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    }

    else if (action.equals("profileAddMultiValue")) {
        String key = null;
        String value = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                value = args.getString(1);
            } else {
                haveError = true;
                errorMsg = "value cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final String _value = value;

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.addMultiValueForKey(_key, _value);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileRemoveMultiValue")) {
        String key = null;
        String value = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                value = args.getString(1);
            } else {
                haveError = true;
                errorMsg = "value cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final String _value = value;

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.removeMultiValueForKey(_key, _value);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("sessionGetTimeElapsed")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int time = cleverTap.session.getTimeElapsed();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, time);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetTotalVisits")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int count = cleverTap.session.getTotalVisits();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, count);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetScreenCount")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int count = cleverTap.session.getScreenCount();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, count);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetPreviousVisitTime")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int time = cleverTap.session.getPreviousVisitTime();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, time);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetUTMDetails")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                UTMDetail details = cleverTap.session.getUTMDetails();
                try {
                    JSONObject jsonDetails = CleverTapPlugin.utmDetailsToJSON(details);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                } catch (JSONException e) {
                    PluginResult _result = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            }
        });
        return true;
    }

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

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

License:Open Source License

/**
 * Creates a new Replicator//from  w w  w  . j a v  a  2 s.  c  o  m
 * @param documentStoreName - The name of the DocumentStore
 * @param remoteURI - The remote database URI
 * @param type - The type of replication to be performed
 * @param token - The unique token id of the Replicator
 * @param callbackContext - The javascript callback to execute when complete or errored
 */
private void createReplicator(final String documentStoreName, final String remoteURI, final String type,
        final Integer token, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {
            try {
                DocumentStore ds = getDocumentStore(documentStoreName);

                if (remoteURI == null || type == null || token == null) {
                    throw new Exception("Replicator uri, type, and token must not be null");
                }

                URI uri;
                try {
                    uri = new URI(remoteURI);
                } catch (URISyntaxException e) {
                    throw new Exception("Invalid uri: " + remoteURI);
                }

                Replicator replicator;
                final SyncPluginInterceptor interceptor = new SyncPluginInterceptor(callbackContext);
                if (type.equals("push")) {
                    replicator = ReplicatorBuilder.push().to(uri).from(ds)
                            .addRequestInterceptors((HttpConnectionRequestInterceptor) interceptor)
                            .addResponseInterceptors((HttpConnectionResponseInterceptor) interceptor).build();
                } else if (type.equals("pull")) {
                    replicator = ReplicatorBuilder.pull().from(uri).to(ds)
                            .addRequestInterceptors((HttpConnectionRequestInterceptor) interceptor)
                            .addResponseInterceptors((HttpConnectionResponseInterceptor) interceptor).build();
                } else {
                    throw new Exception("Replicator 'type' must be either 'push' or 'pull'. Received: " + type);
                }

                if (replicator == null) {
                    throw new Exception("Failed to create " + type + " Replicator. Builder returned null");
                }

                replicator.getEventBus().register(new SyncPluginListener(callbackContext));

                replicators.put(token, replicator);
                interceptors.put(token, interceptor);

                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);

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

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

public void canUseTwitterSystemAccount(final CallbackContext callbackContext) {

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;

            Account[] twitterAccounts = accountManager.getAccountsByType("com.twitter.android.auth.login");

            // Twitter doesn't allow to get user's tokens from native account which signed by custom app
            // therefore the method returns false

            //pluginResult = new PluginResult(PluginResult.Status.OK, (twitterAccounts.length > 0));

            pluginResult = new PluginResult(PluginResult.Status.OK, false);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }/*  www.  j a  v  a  2  s. c o  m*/
    });
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

public void getTwitterSystemAccounts(final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;
            JSONObject json = new JSONObject();
            JSONArray accounts = new JSONArray();

            Account[] twitterAccounts = accountManager.getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        JSONObject account = new JSONObject();

                        account.put("userName", twitterAccounts[i].name);

                        accounts.put(account);

                        json.put("accounts", accounts);
                    }//from   ww  w.  j  a  v  a  2s  .c o m

                    pluginResult = new PluginResult(PluginResult.Status.OK, json);
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
            }

            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }
    });
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

public void getTwitterSystemAccount(final String networkUserName, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;
            final JSONObject json = new JSONObject();
            final JSONObject account = new JSONObject();

            final Account[] twitterAccounts = accountManager
                    .getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        if (twitterAccounts[i].name.equals(networkUserName)) {
                            account.put("userName", twitterAccounts[i].name);

                            final Account twitterAccount = twitterAccounts[i];

                            accountManager.getAuthToken(twitterAccount, "com.twitter.android.oauth.token", null,
                                    false, new AccountManagerCallback<Bundle>() {
                                        @Override
                                        public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
                                            try {
                                                Bundle bundle = accountManagerFuture.getResult();

                                                if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                                    Intent intent = bundle
                                                            .getParcelable(AccountManager.KEY_INTENT);

                                                    //clear the new task flag just in case, since a result is expected
                                                    int flags = intent.getFlags();
                                                    flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                    intent.setFlags(flags);

                                                    requestedTwitterAccountName = networkUserName;

                                                    cordova.getActivity().startActivityForResult(intent,
                                                            TWITTER_OAUTH_REQUEST);
                                                } else {
                                                    account.put("oauth_token",
                                                            bundle.getString(AccountManager.KEY_AUTHTOKEN));

                                                    accountManager.getAuthToken(twitterAccount,
                                                            "com.twitter.android.oauth.token.secret", null,
                                                            false, new AccountManagerCallback<Bundle>() {
                                                                @Override
                                                                public void run(
                                                                        AccountManagerFuture<Bundle> accountManagerFuture) {
                                                                    try {
                                                                        Bundle bundle = accountManagerFuture
                                                                                .getResult();

                                                                        if (bundle.containsKey(
                                                                                AccountManager.KEY_INTENT)) {
                                                                            Intent intent = bundle
                                                                                    .getParcelable(
                                                                                            AccountManager.KEY_INTENT);

                                                                            //clear the new task flag just in case, since a result is expected
                                                                            int flags = intent.getFlags();
                                                                            flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                                            intent.setFlags(flags);

                                                                            requestedTwitterAccountName = networkUserName;

                                                                            cordova.getActivity()
                                                                                    .startActivityForResult(
                                                                                            intent,
                                                                                            TWITTER_OAUTH_REQUEST);
                                                                        } else {
                                                                            account.put("oauth_token_secret",
                                                                                    bundle.getString(
                                                                                            AccountManager.KEY_AUTHTOKEN));

                                                                            json.put("data", account);

                                                                            Log.v(TAG, "Account data: "
                                                                                    + json.toString());

                                                                            PluginResult pluginResult = new PluginResult(
                                                                                    PluginResult.Status.OK,
                                                                                    json);
                                                                            pluginResult.setKeepCallback(true);
                                                                            callbackContext.sendPluginResult(
                                                                                    pluginResult);
                                                                        }

                                                                    } catch (Exception e) {
                                                                        PluginResult pluginResult = new PluginResult(
                                                                                PluginResult.Status.ERROR,
                                                                                e.getLocalizedMessage());
                                                                        pluginResult.setKeepCallback(true);
                                                                        callbackContext
                                                                                .sendPluginResult(pluginResult);
                                                                    }
                                                                }
                                                            }, null);
                                                }

                                            } catch (Exception e) {
                                                PluginResult pluginResult = new PluginResult(
                                                        PluginResult.Status.ERROR, e.getLocalizedMessage());
                                                pluginResult.setKeepCallback(true);
                                                callbackContext.sendPluginResult(pluginResult);
                                            }
                                        }
                                    }, null);
                        }/*from w  w w .ja  v a 2 s  .c o m*/
                    }
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        }
    });
}

From source file:com.commontime.cordova.audio.AudioHandler.java

License:Apache License

void sendEventMessage(String action, JSONObject actionData) {
    JSONObject message = new JSONObject();
    try {/*from w  w w  .  j a va 2  s .c  o  m*/
        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);
    }
}