Example usage for android.util Log DEBUG

List of usage examples for android.util Log DEBUG

Introduction

In this page you can find the example usage for android.util Log DEBUG.

Prototype

int DEBUG

To view the source code for android.util Log DEBUG.

Click Source Link

Document

Priority constant for the println method; use Log.d.

Usage

From source file:com.cloudzilla.fb.FacebookServiceProxy.java

public void showFacebookDialog(final String action, final Bundle params) {
    Log.d(TAG, "showFacebookDialog action=" + action + " params=" + toString(params));

    if (mInstance == null || !mInstance.isOnFacebook()) {
        Log.e(TAG, "You are not on Facebook");
        return;//from w  ww  .j a  v a 2s.c om
    }

    new AsyncTask<Void, Void, JSONObject>() {
        private final IFacebookService facebookService = mFacebookService;

        protected JSONObject doInBackground(Void... nada) {
            JSONObject result = null;

            try {
                JSONObject jsonRequest = new JSONObject();
                jsonRequest.put("method", action);
                for (String key : params.keySet()) {
                    jsonRequest.put(key, params.get(key));
                }
                String resultAsStr = facebookService.ui(jsonRequest.toString());
                if (resultAsStr != null) {
                    result = new JSONObject(resultAsStr);
                }
            } catch (JSONException e) {
                Log.e(TAG, "Exception: ", e);
            } catch (RemoteException e) {
                Log.e(TAG, "Failed to invoke FacebookService", e);
            }

            return result;
        }

        protected void onPostExecute(JSONObject result) {
            Bundle bundle = null;
            if (result != null) {
                try {
                    bundle = toBundle(result);
                } catch (JSONException e) {
                    // Nothing to do. We'll return a Facebook
                    // exception below.
                }

                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Response from Facebook: ");
                    for (String key : bundle.keySet()) {
                        Log.d(TAG, "\t" + key + "=" + bundle.get(key));
                    }
                }
                //                    listener.onComplete(bundle, null);
            } else {
                //                    listener.onComplete(null, new FacebookException());
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(socket, target, port, true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {/*w ww . ja v  a 2  s .  c  o  m*/
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    /*
        if (this.log.isDebugEnabled()) {
          this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
          this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
        }
    */

    prepareSocket(sslsock);

    // Android specific code to enable SNI
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Enabling SNI for " + target);
        }
        try {
            Method method = sslsock.getClass().getMethod("setHostname", String.class);
            method.invoke(sslsock, target);
        } catch (Exception ex) {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "SNI configuration failed", ex);
            }
        }
    }
    // End of Android specific code

    //    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:com.radicaldynamic.groupinform.services.DatabaseService.java

public void setLocalDatabaseInfo(String host, int port) {
    final String tt = t + "setLocalDatabaseInfo(): ";

    if (Collect.Log.DEBUG)
        Log.d(Collect.LOGTAG, tt + "set host and port to " + host + ":" + port);

    mLocalHost = host;/*  w ww .  j  av  a 2  s  . c  o  m*/
    mLocalPort = port;
}

From source file:com.radicaldynamic.groupinform.activities.AccountFolderList.java

public static ArrayList<AccountFolder> loadFolderList() {
    if (Collect.Log.DEBUG)
        Log.d(Collect.LOGTAG, t + "loading folder cache");

    ArrayList<AccountFolder> folders = new ArrayList<AccountFolder>();

    if (!new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.FOLDER_CACHE_FILE).exists()) {
        if (Collect.Log.WARN)
            Log.w(Collect.LOGTAG, t + "folder cache file cannot be read: aborting loadFolderList()");
        return folders;
    }/*from w  w  w  .ja  v  a 2 s.  co m*/

    try {
        FileInputStream fis = new FileInputStream(
                new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.FOLDER_CACHE_FILE));
        InputStreamReader reader = new InputStreamReader(fis);
        BufferedReader buffer = new BufferedReader(reader, 8192);
        StringBuilder sb = new StringBuilder();

        String cur;

        while ((cur = buffer.readLine()) != null) {
            sb.append(cur + "\n");
        }

        buffer.close();
        reader.close();
        fis.close();

        try {
            JSONArray jsonFolders = (JSONArray) new JSONTokener(sb.toString()).nextValue();

            for (int i = 0; i < jsonFolders.length(); i++) {
                JSONObject jsonFolder = jsonFolders.getJSONObject(i);

                AccountFolder folder = new AccountFolder(jsonFolder.getString("id"),
                        jsonFolder.getString("rev"), jsonFolder.getString("owner"),
                        jsonFolder.getString("name"), jsonFolder.getString("description"),
                        jsonFolder.getString("visibility"), jsonFolder.getBoolean("replication"));

                folders.add(folder);

                // Also update the account folder hash since this will be needed by BrowserActivity, among other things
                Collect.getInstance().getInformOnlineState().getAccountFolders().put(folder.getId(), folder);
            }
        } catch (JSONException e) {
            // Parse error (malformed result)
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "failed to parse JSON " + sb.toString());
            e.printStackTrace();
        }
    } catch (Exception e) {
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, t + "unable to read folder cache: " + e.toString());
        e.printStackTrace();
    }

    return folders;
}

From source file:com.cbsb.ftpserv.ProxyConnector.java

/**
 * Connects an outgoing socket to the proxy and authenticates, creating an account
 * if necessary./*from   w w  w .j a  va 2 s. c  o  m*/
 */
private Socket newAuthedSocket(String hostname, int port) {
    if (hostname == null) {
        myLog.i("newAuthedSocket can't connect to null host");
        return null;
    }
    JSONObject json = new JSONObject();
    //String secret = retrieveSecret();
    Socket socket;
    OutputStream out = null;
    InputStream in = null;

    try {
        myLog.d("Opening proxy connection to " + hostname + ":" + port);
        socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
        json.put("android_id", Util.getAndroidId());
        json.put("swiftp_version", Util.getVersion());
        json.put("action", "login");
        out = socket.getOutputStream();
        in = socket.getInputStream();
        int numBytes;

        out.write(json.toString().getBytes(ENCODING));
        myLog.l(Log.DEBUG, "Sent login request");
        // Read and parse the server's response
        byte[] bytes = new byte[IN_BUF_SIZE];
        // Here we assume that the server's response will all be contained in
        // a single read, which may be unsafe for large responses
        numBytes = in.read(bytes);
        if (numBytes == -1) {
            myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
            return null;
        } else if (numBytes == 0) {
            myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
            return null;
        }
        json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
        if (checkAndPrintJsonError(json)) {
            return null;
        }
        myLog.d("newAuthedSocket successful");
        return socket;
    } catch (Exception e) {
        myLog.i("Exception during proxy connection or authentication: " + e);
        return null;
    }
}

From source file:com.mobileglobe.android.customdialer.common.model.AccountTypeManager.java

/**
 * Loads account list and corresponding account types (potentially with data sets). Always
 * called on a background thread./*from ww  w .  j a v  a  2s .c  om*/
 */
protected void loadAccountsInBackground() {
    if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
        Log.d(Constants.PERFORMANCE_TAG, "AccountTypeManager.loadAccountsInBackground start");
    }
    TimingLogger timings = new TimingLogger(TAG, "loadAccountsInBackground");
    final long startTime = SystemClock.currentThreadTimeMillis();
    final long startTimeWall = SystemClock.elapsedRealtime();

    // Account types, keyed off the account type and data set concatenation.
    final Map<AccountTypeWithDataSet, AccountType> accountTypesByTypeAndDataSet = Maps.newHashMap();

    // The same AccountTypes, but keyed off {@link RawContacts#ACCOUNT_TYPE}.  Since there can
    // be multiple account types (with different data sets) for the same type of account, each
    // type string may have multiple AccountType entries.
    final Map<String, List<AccountType>> accountTypesByType = Maps.newHashMap();

    final List<AccountWithDataSet> allAccounts = Lists.newArrayList();
    final List<AccountWithDataSet> contactWritableAccounts = Lists.newArrayList();
    final List<AccountWithDataSet> groupWritableAccounts = Lists.newArrayList();
    final Set<String> extensionPackages = Sets.newHashSet();

    final AccountManager am = mAccountManager;

    final SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
    final AuthenticatorDescription[] auths = am.getAuthenticatorTypes();

    // First process sync adapters to find any that provide contact data.
    for (SyncAdapterType sync : syncs) {
        if (!ContactsContract.AUTHORITY.equals(sync.authority)) {
            // Skip sync adapters that don't provide contact data.
            continue;
        }

        // Look for the formatting details provided by each sync
        // adapter, using the authenticator to find general resources.
        final String type = sync.accountType;
        final AuthenticatorDescription auth = findAuthenticator(auths, type);
        if (auth == null) {
            Log.w(TAG, "No authenticator found for type=" + type + ", ignoring it.");
            continue;
        }

        AccountType accountType;
        if (GoogleAccountType.ACCOUNT_TYPE.equals(type)) {
            accountType = new GoogleAccountType(mContext, auth.packageName);
        } else if (ExchangeAccountType.isExchangeType(type)) {
            accountType = new ExchangeAccountType(mContext, auth.packageName, type);
        } else if (SamsungAccountType.isSamsungAccountType(mContext, type, auth.packageName)) {
            accountType = new SamsungAccountType(mContext, auth.packageName, type);
        } else {
            Log.d(TAG, "Registering external account type=" + type + ", packageName=" + auth.packageName);
            accountType = new ExternalAccountType(mContext, auth.packageName, false);
        }
        if (!accountType.isInitialized()) {
            if (accountType.isEmbedded()) {
                throw new IllegalStateException(
                        "Problem initializing embedded type " + accountType.getClass().getCanonicalName());
            } else {
                // Skip external account types that couldn't be initialized.
                continue;
            }
        }

        accountType.accountType = auth.type;
        accountType.titleRes = auth.labelId;
        accountType.iconRes = auth.iconId;

        addAccountType(accountType, accountTypesByTypeAndDataSet, accountTypesByType);

        // Check to see if the account type knows of any other non-sync-adapter packages
        // that may provide other data sets of contact data.
        extensionPackages.addAll(accountType.getExtensionPackageNames());
    }

    // If any extension packages were specified, process them as well.
    if (!extensionPackages.isEmpty()) {
        Log.d(TAG, "Registering " + extensionPackages.size() + " extension packages");
        for (String extensionPackage : extensionPackages) {
            ExternalAccountType accountType = new ExternalAccountType(mContext, extensionPackage, true);
            if (!accountType.isInitialized()) {
                // Skip external account types that couldn't be initialized.
                continue;
            }
            if (!accountType.hasContactsMetadata()) {
                Log.w(TAG, "Skipping extension package " + extensionPackage + " because"
                        + " it doesn't have the CONTACTS_STRUCTURE metadata");
                continue;
            }
            if (TextUtils.isEmpty(accountType.accountType)) {
                Log.w(TAG, "Skipping extension package " + extensionPackage + " because"
                        + " the CONTACTS_STRUCTURE metadata doesn't have the accountType" + " attribute");
                continue;
            }
            Log.d(TAG, "Registering extension package account type=" + accountType.accountType + ", dataSet="
                    + accountType.dataSet + ", packageName=" + extensionPackage);

            addAccountType(accountType, accountTypesByTypeAndDataSet, accountTypesByType);
        }
    }
    timings.addSplit("Loaded account types");

    Account[] accounts = mAccountManager.getAccounts();
    for (Account account : accounts) {
        boolean syncable = ContentResolver.getIsSyncable(account, ContactsContract.AUTHORITY) > 0;

        if (syncable) {
            List<AccountType> accountTypes = accountTypesByType.get(account.type);
            if (accountTypes != null) {
                // Add an account-with-data-set entry for each account type that is
                // authenticated by this account.
                for (AccountType accountType : accountTypes) {
                    AccountWithDataSet accountWithDataSet = new AccountWithDataSet(account.name, account.type,
                            accountType.dataSet);
                    allAccounts.add(accountWithDataSet);
                    if (accountType.areContactsWritable()) {
                        contactWritableAccounts.add(accountWithDataSet);
                    }
                    if (accountType.isGroupMembershipEditable()) {
                        groupWritableAccounts.add(accountWithDataSet);
                    }
                }
            }
        }
    }

    Collections.sort(allAccounts, ACCOUNT_COMPARATOR);
    Collections.sort(contactWritableAccounts, ACCOUNT_COMPARATOR);
    Collections.sort(groupWritableAccounts, ACCOUNT_COMPARATOR);

    timings.addSplit("Loaded accounts");

    synchronized (this) {
        mAccountTypesWithDataSets = accountTypesByTypeAndDataSet;
        mAccounts = allAccounts;
        mContactWritableAccounts = contactWritableAccounts;
        mGroupWritableAccounts = groupWritableAccounts;
        mInvitableAccountTypes = findAllInvitableAccountTypes(mContext, allAccounts,
                accountTypesByTypeAndDataSet);
    }

    timings.dumpToLog();
    final long endTimeWall = SystemClock.elapsedRealtime();
    final long endTime = SystemClock.currentThreadTimeMillis();

    Log.i(TAG,
            "Loaded meta-data for " + mAccountTypesWithDataSets.size() + " account types, " + mAccounts.size()
                    + " accounts in " + (endTimeWall - startTimeWall) + "ms(wall) " + (endTime - startTime)
                    + "ms(cpu)");

    if (mInitializationLatch != null) {
        mInitializationLatch.countDown();
        mInitializationLatch = null;
    }
    if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
        Log.d(Constants.PERFORMANCE_TAG, "AccountTypeManager.loadAccountsInBackground finish");
    }

    // Check filter validity since filter may become obsolete after account update. It must be
    // done from UI thread.
    mMainThreadHandler.post(mCheckFilterValidityRunnable);
}

From source file:org.swiftp.server.ProxyConnector.java

/**
 * Connects an outgoing socket to the proxy and authenticates, creating an account if
 * necessary.//w  ww  .ja  v  a2 s .co m
 */
private Socket newAuthedSocket(String hostname, int port) {
    if (hostname == null) {
        myLog.i("newAuthedSocket can't connect to null host");
        return null;
    }
    JSONObject json = new JSONObject();
    // String secret = retrieveSecret();
    Socket socket;
    OutputStream out = null;
    InputStream in = null;

    try {
        myLog.d("Opening proxy connection to " + hostname + ":" + port);
        socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
        json.put("android_id", Util.getAndroidId());
        json.put("swiftp_version", Util.getVersion());
        json.put("action", "login");
        out = socket.getOutputStream();
        in = socket.getInputStream();
        int numBytes;

        out.write(json.toString().getBytes(ENCODING));
        myLog.l(Log.DEBUG, "Sent login request");
        // Read and parse the server's response
        byte[] bytes = new byte[IN_BUF_SIZE];
        // Here we assume that the server's response will all be contained in
        // a single read, which may be unsafe for large responses
        numBytes = in.read(bytes);
        if (numBytes == -1) {
            myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
            return null;
        } else if (numBytes == 0) {
            myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
            return null;
        }
        json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
        if (checkAndPrintJsonError(json)) {
            return null;
        }
        myLog.d("newAuthedSocket successful");
        return socket;
    } catch (Exception e) {
        myLog.i("Exception during proxy connection or authentication: " + e);
        return null;
    }
}

From source file:com.samsung.multiwindow.MultiWindow.java

/**
 * Get the MultiWindow enabled applications and activity names
 * // ww  w. ja v  a2 s  .  c  o m
 * @param windowType
 *            The window type freestyle or splitstyle.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * 
 */
private void getMultiWindowApps(final String windowType, final CallbackContext callbackContext)
        throws JSONException {

    if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
        Log.d(TAG, "Inside getMultiWindowApps");
    }
    cordova.getThreadPool().execute(new Runnable() {

        public void run() {

            JSONArray multiWindowApps = new JSONArray();
            Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfos = cordova.getActivity().getPackageManager().queryIntentActivities(
                    intent, PackageManager.GET_RESOLVED_FILTER | PackageManager.GET_META_DATA);

            try {
                // Get the multiwindow enabled applications

                int index = 0;
                for (ResolveInfo r : resolveInfos) {
                    if (r.activityInfo != null && r.activityInfo.applicationInfo.metaData != null) {
                        if (r.activityInfo.applicationInfo.metaData
                                .getBoolean("com.sec.android.support.multiwindow")
                                || r.activityInfo.applicationInfo.metaData
                                        .getBoolean("com.samsung.android.sdk.multiwindow.enable")) {
                            JSONObject appInfo = new JSONObject();
                            boolean bUnSupportedMultiWinodw = false;
                            if (windowType.equalsIgnoreCase("splitstyle")) {
                                if (r.activityInfo.metaData != null) {
                                    String activityWindowStyle = r.activityInfo.metaData
                                            .getString("com.sec.android.multiwindow.activity.STYLE");
                                    if (activityWindowStyle != null) {
                                        ArrayList<String> activityWindowStyles = new ArrayList<String>(
                                                Arrays.asList(activityWindowStyle.split("\\|")));
                                        if (!activityWindowStyles.isEmpty()) {
                                            if (activityWindowStyles.contains("fullscreenOnly")) {
                                                bUnSupportedMultiWinodw = true;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!bUnSupportedMultiWinodw || !windowType.equalsIgnoreCase("splitstyle")) {
                                appInfo.put("packageName", r.activityInfo.applicationInfo.packageName);
                                appInfo.put("activity", r.activityInfo.name);
                                multiWindowApps.put(index++, appInfo);
                            }
                        }
                    }
                }
                callbackContext.success(multiWindowApps);
            } catch (Exception e) {

                callbackContext.error(e.getMessage());
            }

        }
    });
}

From source file:com.radicaldynamic.groupinform.services.DatabaseService.java

synchronized private void connectToLocalServer() throws DbUnavailableException {
    final String tt = t + "connectToLocalServer(): ";

    if (mLocalHost == null || mLocalPort == 0) {
        if (Collect.Log.WARN)
            Log.w(Collect.LOGTAG, tt + "local host information not available; aborting connection");
        mConnectedToLocal = false;/*from   ww  w  . j a v  a  2  s . c o m*/
        return;
    }

    if (Collect.Log.DEBUG)
        Log.d(Collect.LOGTAG, tt + "establishing connection to " + mLocalHost + ":" + mLocalPort);

    try {
        /*
         * Socket timeout of 5 minutes is important, otherwise long-running replications
         * will fail.  It is possible that we will need to extend this in the future if
         * it turns out to be insufficient.
         */
        mLocalHttpClient = new StdHttpClient.Builder().host(mLocalHost).port(mLocalPort)
                .socketTimeout(TIME_FIVE_MINUTES * 1000).build();

        mLocalDbInstance = new StdCouchDbInstance(mLocalHttpClient);
        mLocalDbInstance.getAllDatabases();

        if (mConnectedToLocal == false)
            mConnectedToLocal = true;

        if (Collect.Log.DEBUG)
            Log.d(Collect.LOGTAG, tt + "connection to " + mLocalHost + " successful");
    } catch (Exception e) {
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, tt + e.toString());
        e.printStackTrace();
        mConnectedToLocal = false;
        throw new DbUnavailableException();
    }
}

From source file:com.samsung.spen.SpenPlugin.java

/**
 * /*from   w ww. j a v  a  2 s  .  c o  m*/
 * @param args
 *                 JSON array of options sent from the script.
 * @param surfaceType
 *                int
 * @param callbackContext
 *                CallbackContext
 * @return   options
 *                SpenTrayBarOptions
 * @throws JSONException
 */
private SpenTrayBarOptions createTrayBarOptions(JSONArray args, int surfaceType,
        CallbackContext callbackContext) throws JSONException {
    if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
        Log.d(TAG, "Inside createTrayBarOptions");
    }

    String tempId = args.getString(ID);
    if (tempId != null) {
        tempId = tempId.trim();
        if (tempId.length() > MAX_ID_LENGTH) {
            tempId = tempId.substring(0, MAX_ID_LENGTH);
        }
    }

    final String id = tempId;
    if (id == null || id.equals("") || id.equals("null") || !id.matches("^[ !#-)+-.0-9;=@-Z^-{}~]+$")) {
        SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext);
        return null;
    }

    int sPenFlags = args.optInt(SPEN_FLAGS, Integer.MIN_VALUE);
    if (sPenFlags == Integer.MIN_VALUE || sPenFlags > Utils.MAX_FLAGS_VALUE
            || sPenFlags < Utils.MIN_FLAGS_VALUE) {
        SpenException.sendPluginResult(SpenExceptionType.INVALID_FLAGS, callbackContext);
        return null;
    }

    int returnType = args.optInt(RETURN_TYPE);
    if (returnType != Utils.RETURN_TYPE_IMAGE_DATA && returnType != Utils.RETURN_TYPE_IMAGE_URI
            && returnType != Utils.RETURN_TYPE_TEXT) {

        SpenException.sendPluginResult(SpenExceptionType.INVALID_RETURN_TYPE, callbackContext);
        return null;
    }

    String backgroundColor = args.getString(BACKGROUND_COLOR);

    String imagePath = args.getString(IMAGE_PATH);
    if (imagePath.equals("") || imagePath.equals("null")) {
        imagePath = null;
    } else {
        imagePath = Uri.decode(imagePath);
        String truncatedPath = truncateQueryPart(imagePath);
        File file = new File(truncatedPath);
        if (file.exists()) {
            imagePath = truncatedPath;
        }
    }

    int bgImageScaleType = args.optInt(BACKGROUND_IMAGE_SCALE_TYPE);
    if (bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_CENTER
            && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_FIT
            && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_STRETCH
            && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_TILE) {
        bgImageScaleType = Utils.BACKGROUND_IMAGE_MODE_FIT;
    }

    int imageUriScaleType = args.optInt(IMAGE_URI_SCALE_TYPE);
    if (imageUriScaleType != Utils.IMAGE_URI_MODE_CENTER && imageUriScaleType != Utils.IMAGE_URI_MODE_FIT
            && imageUriScaleType != Utils.IMAGE_URI_MODE_TILE
            && imageUriScaleType != Utils.IMAGE_URI_MODE_STRETCH) {
        imageUriScaleType = Utils.IMAGE_URI_MODE_FIT;
    }

    if (surfaceType == Utils.SURFACE_INLINE) {
        if ((sPenFlags & Utils.FLAG_ADD_PAGE) == Utils.FLAG_ADD_PAGE) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Add Page is not supported in Inline");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_ADD_PAGE;
        }
    } else if (surfaceType == Utils.SURFACE_POPUP) {

        if ((sPenFlags & Utils.FLAG_EDIT) == Utils.FLAG_EDIT) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Edit Page is not supported in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_EDIT;
        }

        if ((sPenFlags & Utils.FLAG_PEN) == Utils.FLAG_PEN) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Pen option is provided by default, is not configurable in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_PEN;

        }

        if ((sPenFlags & Utils.FLAG_ERASER) == Utils.FLAG_ERASER) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Eraser option is provided by default, is not configurable in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_ERASER;

        }

        if ((sPenFlags & Utils.FLAG_UNDO_REDO) == Utils.FLAG_UNDO_REDO) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Undo Redo option is provided by default, is not configurable in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_UNDO_REDO;

        }
    } else {
        SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_TYPE, callbackContext);
        return null;
    }

    if ((sPenFlags & Utils.FLAG_TEXT_RECOGNITION) == Utils.FLAG_TEXT_RECOGNITION
            || (sPenFlags & Utils.FLAG_SHAPE_RECOGNITION) == Utils.FLAG_SHAPE_RECOGNITION) {
        sPenFlags = sPenFlags | Utils.FLAG_SELECTION;
    }

    SpenTrayBarOptions options = new SpenTrayBarOptions(sPenFlags);
    options.setId(id);
    options.setIsfeatureEnabled(mSpenState == SPEN_AND_HAND_SUPPORTED ? true : false);
    options.setColor(backgroundColor);
    options.setBgImageScaleType(bgImageScaleType);
    options.setImageUriScaleType(imageUriScaleType);
    options.setReturnType(returnType);
    options.setSurfaceType(surfaceType);
    options.setImagePath(imagePath);
    options.setDensity(mActivity.getApplicationContext().getResources().getDisplayMetrics().density);

    if (surfaceType == Utils.SURFACE_INLINE) {
        long xRect = 0, yRect = 0, width = 0, height = 0, xBodyRect = 0, yBodyRect = 0;
        if (args.isNull(RECTANGLE_X_VALUE) || args.isNull(RECTANGLE_Y_VALUE) || args.isNull(WIDTH)
                || args.isNull(HEIGHT)) {
            SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext);
            return null;
        } else {
            xRect = args.optLong(RECTANGLE_X_VALUE, Integer.MIN_VALUE);
            yRect = args.optLong(RECTANGLE_Y_VALUE, Integer.MIN_VALUE);
            width = args.optLong(WIDTH, Integer.MIN_VALUE);
            height = args.optLong(HEIGHT, Integer.MIN_VALUE);
            xBodyRect = args.optLong(BODY_RECTANGLE_X_VALUE, Integer.MIN_VALUE);
            yBodyRect = args.optLong(BODY_RECTANGLE_Y_VALUE, Integer.MAX_VALUE);
            if (xRect == Integer.MIN_VALUE || yRect == Integer.MIN_VALUE || width == Integer.MIN_VALUE
                    || height == Integer.MIN_VALUE || xBodyRect == Integer.MIN_VALUE
                    || yBodyRect == Integer.MIN_VALUE || xRect > (long) Integer.MAX_VALUE
                    || yRect > (long) Integer.MAX_VALUE || width > (long) Integer.MAX_VALUE
                    || height > (long) Integer.MAX_VALUE || xBodyRect > (long) Integer.MAX_VALUE
                    || yBodyRect > (long) Integer.MAX_VALUE) {
                SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext);
                return null;
            }
        }
        SurfacePosition surfacePosition = new SurfacePosition(mActivity.getApplicationContext(), (int) width,
                (int) height, (int) xRect - (int) xBodyRect, (int) yRect - (int) yBodyRect);
        if (!surfacePosition.isSurfaceValid(options, mActivity.getApplicationContext())) {
            SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext);
            return null;
        }
        options.setSurfacePosition(surfacePosition);
    } else if (surfaceType == Utils.SURFACE_POPUP) {
        long popupWidth = 0, popupHeight = 0;
        popupWidth = args.optLong(POPUP_WIDTH, Integer.MIN_VALUE);
        popupHeight = args.optLong(POPUP_HEIGHT, Integer.MIN_VALUE);
        SurfacePosition surfacePosition = new SurfacePosition(mActivity.getApplicationContext(),
                (int) popupWidth, (int) popupHeight);
        options.setSurfacePosition(surfacePosition);
    }
    return options;
}