Example usage for org.json JSONObject optBoolean

List of usage examples for org.json JSONObject optBoolean

Introduction

In this page you can find the example usage for org.json JSONObject optBoolean.

Prototype

public boolean optBoolean(String key, boolean defaultValue) 

Source Link

Document

Get an optional boolean associated with a key.

Usage

From source file:com.hichinaschool.flashcards.libanki.Sched.java

/**
 * Sibling spacing//  www.  j  a  va2 s .co  m
 * ********************
 */

private void _burySiblings(Card card) {
    LinkedList<Long> toBury = new LinkedList<Long>();
    JSONObject nconf = _newConf(card);
    boolean buryNew = nconf.optBoolean("bury", true);
    JSONObject rconf = _revConf(card);
    boolean buryRev = rconf.optBoolean("bury", true);
    // loop through and remove from queues
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase()
                .rawQuery(String.format(Locale.US,
                        "select id, queue from cards where nid=%d and id!=%d "
                                + "and (queue=0 or (queue=2 and due<=%d))",
                        new Object[] { card.getNid(), card.getId(), mToday }), null);
        while (cur.moveToNext()) {
            long cid = cur.getLong(0);
            int queue = cur.getInt(1);
            if (queue == 2) {
                if (buryRev) {
                    toBury.add(cid);
                }
                // if bury disabled, we still discard to give same-day spacing
                mRevQueue.remove(cid);
            } else {
                // if bury is disabled, we still discard to give same-day spacing
                if (buryNew) {
                    toBury.add(cid);
                    mNewQueue.remove(cid);
                }
            }
        }
    } finally {
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }
    // then bury
    mCol.getDb().execute("update cards set queue=-2,mod=?,usn=? where id in " + Utils.ids2str(toBury),
            new Object[] { Utils.now(), mCol.usn() });
}

From source file:org.cloudsky.cordovaPlugins.BarcodeminCDV.java

/**
 * Starts an intent to scan and decode a barcode.
 *///from  ww  w . ja v  a 2s.c  o m
public void scan(final JSONArray args) {

    final CordovaPlugin that = this;

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

            Intent intentScan = new Intent(SCAN_INTENT);
            intentScan.addCategory(Intent.CATEGORY_DEFAULT);

            // add config as intent extras
            if (args.length() > 0) {

                JSONObject obj;
                JSONArray names;
                String key;
                Object value;

                for (int i = 0; i < args.length(); i++) {

                    try {
                        obj = args.getJSONObject(i);
                    } catch (JSONException e) {
                        Log.i("CordovaLog", e.getLocalizedMessage());
                        continue;
                    }

                    names = obj.names();
                    for (int j = 0; j < names.length(); j++) {
                        try {
                            key = names.getString(j);
                            value = obj.get(key);

                            if (value instanceof Integer) {
                                intentScan.putExtra(key, (Integer) value);
                            } else if (value instanceof String) {
                                intentScan.putExtra(key, (String) value);
                            }

                        } catch (JSONException e) {
                            Log.i("CordovaLog", e.getLocalizedMessage());
                        }
                    }

                    intentScan.putExtra(Intents.Scan.CAMERA_ID,
                            obj.optBoolean(PREFER_FRONTCAMERA, false) ? 1 : 0);
                    intentScan.putExtra(Intents.Scan.SHOW_FLIP_CAMERA_BUTTON,
                            obj.optBoolean(SHOW_FLIP_CAMERA_BUTTON, false));
                    if (obj.has(FORMATS)) {
                        intentScan.putExtra(Intents.Scan.FORMATS, obj.optString(FORMATS));
                    }
                    if (obj.has(PROMPT)) {
                        intentScan.putExtra(Intents.Scan.PROMPT_MESSAGE, obj.optString(PROMPT));
                    }
                    //if (obj.has(ORIENTATION)) {
                    //intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, obj.optString(ORIENTATION));
                    intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, "false");
                    //}
                }

            }

            // avoid calling other phonegap apps
            intentScan.setPackage(that.cordova.getActivity().getApplicationContext().getPackageName());

            that.cordova.startActivityForResult(that, intentScan, REQUEST_CODE);
        }
    });
}

From source file:com.mllrsohn.videodialog.VideoDialogPlugin.java

private void playVideo(JSONObject params, final CallbackContext callbackContext) throws JSONException {

    loopVideo = params.optBoolean("loop", true);
    path = params.optString("url");

    uri = Uri.parse(path);/*from www.j  ava  2 s .c o  m*/

    if (path.contains(ASSETS)) {
        try {
            String filepath = path.replace(ASSETS, "");
            String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());
            File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);

            if (!fp.exists()) {
                this.copy(filepath, filename);
            }
            uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);
        } catch (IOException e) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
        }

    }

    // Create dialog in new thread
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {

            // Set Basic Dialog
            dialog = new Dialog((Context) cordova.getActivity(), android.R.style.Theme_NoTitleBar_Fullscreen);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);

            // Layout View
            RelativeLayout main = new RelativeLayout((Context) cordova.getActivity());
            main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

            // Video View
            mVideoView = new VideoView((Context) cordova.getActivity());
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            mVideoView.setLayoutParams(lp);

            mVideoView.setVideoPath(uri.toString());
            mVideoView.start();
            main.addView(mVideoView);

            dialog.setContentView(main);
            dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
            dialog.show();

            // Close on touch
            mVideoView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "stopped"));
                    dialog.dismiss();
                    return true;
                }
            });

            // Set Looping
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(loopVideo);
                }
            });

            // On Completion
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaplayer) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Done"));
                    dialog.dismiss();
                }
            });

        }
    });
}

From source file:com.tassadar.multirommgr.installfragment.UbuntuManifest.java

public boolean downloadAndParse(Device dev) {
    ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
    try {//w ww. j  a  v a  2s  .  c om
        final String url = dev.getUbuntuBaseUrl() + CHANNELS_PATH;
        if (!Utils.downloadFile(url, out, null, true) || out.size() == 0)
            return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        Object rawObject = new JSONTokener(out.toString()).nextValue();
        if (!(rawObject instanceof JSONObject)) {
            Log.e(TAG, "Malformed manifest format!");
            return false;
        }

        JSONObject o = (JSONObject) rawObject;
        SharedPreferences pref = MgrApp.getPreferences();

        Iterator itr = o.keys();
        while (itr.hasNext()) {
            String name = (String) itr.next();
            JSONObject c = o.getJSONObject(name);

            // Skip hidden channels
            if (c.optBoolean("hidden", false) && !pref.getBoolean(SettingsFragment.UTOUCH_SHOW_HIDDEN, false)) {
                continue;
            }

            addChannel(name, c);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    // Remove channels without the device we're currently running on and load images
    Iterator<Map.Entry<String, TreeMap<String, UbuntuChannel>>> f_itr = m_flavours.entrySet().iterator();
    while (f_itr.hasNext()) {
        Map<String, UbuntuChannel> channelMap = f_itr.next().getValue();
        Iterator<Map.Entry<String, UbuntuChannel>> c_itr = channelMap.entrySet().iterator();
        while (c_itr.hasNext()) {
            UbuntuChannel c = c_itr.next().getValue();

            // Devices like deb or tilapia won't be in
            // Ubuntu Touch manifests, yet the versions
            // for flo/grouper work fine - select those.
            String dev_name = dev.getName();
            if (!c.hasDevice(dev_name)) {
                dev_name = dev.getBaseVariantName();

                if (!c.hasDevice(dev_name)) {
                    c_itr.remove();
                    continue;
                }
            }

            try {
                if (!c.loadDeviceImages(dev_name, dev))
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            // Remove channels with no images for our device
            if (!c.hasImages()) {
                c_itr.remove();
                continue;
            }

            Log.d(TAG, "Got channel: " + c.getDisplayName());
        }

        if (channelMap.isEmpty())
            f_itr.remove();
    }
    return true;
}

From source file:org.eclipse.orion.internal.server.servlets.file.ServletFileStoreHandler.java

/**
 * Copies any defined fields in the provided JSON object into the destination file info.
 * @param source The JSON object to copy fields from
 * @param destination The file info to copy fields to
 *//*from  www . j a v a2 s .co  m*/
public static void copyJSONToFileInfo(JSONObject source, FileInfo destination) {
    destination.setName(source.optString(ProtocolConstants.KEY_NAME, destination.getName()));
    destination.setLastModified(
            source.optLong(ProtocolConstants.KEY_LAST_MODIFIED, destination.getLastModified()));
    destination.setDirectory(source.optBoolean(ProtocolConstants.KEY_DIRECTORY, destination.isDirectory()));

    JSONObject attributes = source.optJSONObject(ProtocolConstants.KEY_ATTRIBUTES);
    if (attributes != null) {
        for (int i = 0; i < ATTRIBUTE_KEYS.length; i++) {
            //undefined means the client does not want to change the value, so can't interpret as false
            if (!attributes.isNull(ATTRIBUTE_KEYS[i]))
                destination.setAttribute(ATTRIBUTE_BITS[i], attributes.optBoolean(ATTRIBUTE_KEYS[i]));
        }
    }
}

From source file:org.godotengine.godot.FireBase.java

private void initFireBase(final String data) {
    Utils.d("Data From File: " + data);

    JSONObject config = null;
    mFirebaseApp = FirebaseApp.initializeApp(activity);

    if (data.length() <= 0) {
        Utils.d("FireBase initialized.");
        return;/*w  w  w . j a  va2s. c o m*/
    }

    try {
        config = new JSONObject(data);
        firebaseConfig = config;
    } catch (JSONException e) {
        Utils.d("JSON Parse error: " + e.toString());
    }

    //Analytics++
    if (config.optBoolean("Analytics", true)) {
        Utils.d("Initializing Firebase Analytics.");
        Analytics.getInstance(activity).init(mFirebaseApp);
    }
    //Analytics--

    //AdMob++
    if (config.optBoolean("AdMob", false)) {
        Utils.d("Initializing Firebase AdMob.");
        AdMob.getInstance(activity).init(mFirebaseApp);
    }
    //AdMob--

    //Auth++
    if (config.optBoolean("Authentication", false)) {
        Utils.d("Initializing Firebase Authentication.");
        Auth.getInstance(activity).init(mFirebaseApp);
        Auth.getInstance(activity).configure(config.optString("AuthConf"));
    }
    //Auth--

    //Notification++
    if (config.optBoolean("Notification", false)) {
        Utils.d("Initializing Firebase Notification.");
        Notification.getInstance(activity).init(mFirebaseApp);
    }
    //Notification--

    //Invites++
    if (config.optBoolean("Invites", false)) {
        Utils.d("Initializing Firebase Invites.");
        Invites.getInstance(activity).init(mFirebaseApp);
    }
    //Invites--

    //RemoteConfig++
    if (config.optBoolean("RemoteConfig", false)) {
        Utils.d("Initializing Firebase RemoteConfig.");
        RemoteConfig.getInstance(activity).init(mFirebaseApp);
    }
    //RemoteConfig--

    //Storage++
    if (config.optBoolean("Storage", false)) {
        if (!config.optBoolean("Authentication", false)) {
            Utils.d("Firebase Storage needs Authentication.");
        }

        Utils.d("Initializing Firebase Storage.");
        Storage.getInstance(activity).init(mFirebaseApp);
    }
    //Storage--

    Utils.d("FireBase initialized.");
}

From source file:org.apache.cordova.navigationmenu.NavigationMenu.java

/**
 * Called when a message is sent to plugin.
 *
 * @param id            The message id/* ww  w.  ja  v  a 2 s  .  co  m*/
 * @param data          The message data
 * @return              Object to stop propagation or null
 */
public Object onMessage(String id, Object data) {
    if (id.equals("onCreateOptionsMenu")) {
        this.menuinitialized = true;
        Menu menu = (Menu) data;
        Object[] items = this.items.values().toArray();
        for (Object jsonObject : items) {
            JSONObject menuItem = (JSONObject) jsonObject;
            appendItem(menu, menuItem);
        }

        this.webView.sendJavascript("console.log('onCreateOptionsMenu');");
        return null;
    } else if (id.equals("onPrepareOptionsMenu")) {
        Menu menu = (Menu) data;
        for (int i = 0; i < menu.size(); i++) {
            MenuItem menuItem = menu.getItem(i);
            int itemId = menuItem.getItemId();
            JSONObject itemDescription = this.items.get(itemId);
            boolean enabled = itemDescription.optBoolean("enabled", true);
            enableMenuItem(menuItem.setEnabled(enabled), enabled);
        }
    } else if (id.equals("onOptionsItemSelected")) {
        MenuItem menuItem = (MenuItem) data;
        int itemId = menuItem.getItemId();
        this.webView.sendJavascript("menu.optionItemClick && menu.optionItemClick(" + itemId + ");");
    }

    return null;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitBranchTest.java

@Test
public void testListBranches() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    JSONObject clone = clone(clonePath);
    String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

    branch(branchesLocation, "a");
    branch(branchesLocation, "z");

    JSONObject branches = listBranches(branchesLocation);
    JSONArray branchesArray = branches.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(3, branchesArray.length());

    // validate branch metadata
    JSONObject branch = branchesArray.getJSONObject(1);
    assertEquals(Constants.MASTER, branch.getString(ProtocolConstants.KEY_NAME));
    assertBranchUri(branch.getString(ProtocolConstants.KEY_LOCATION));
    assertTrue(branch.optBoolean(GitConstants.KEY_BRANCH_CURRENT, false));
    branch = branchesArray.getJSONObject(0);
    assertEquals("z", branch.getString(ProtocolConstants.KEY_NAME));
    // assert properly sorted, new first
    long lastTime = Long.MAX_VALUE;
    for (int i = 0; i < branchesArray.length(); i++) {
        long t = branchesArray.getJSONObject(i).getLong(ProtocolConstants.KEY_LOCAL_TIMESTAMP);
        assertTrue(t <= lastTime);/*www. java  2s.  c  o  m*/
        lastTime = t;
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitBranchTest.java

@Test
public void testAddRemoveBranch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    JSONObject clone = clone(clonePath);
    String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

    String[] branchNames = { "dev", "change/1/1", "working@bug1" };
    for (String branchName : branchNames) {
        // create branch
        WebResponse response = branch(branchesLocation, branchName);
        String branchLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);

        // check details
        WebRequest request = getGetRequest(branchLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        JSONObject branches = listBranches(branchesLocation);
        JSONArray branchesArray = branches.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(2, branchesArray.length());
        JSONObject branch0 = branchesArray.getJSONObject(0);
        JSONObject branch1 = branchesArray.getJSONObject(1);
        if (branch0.optBoolean(GitConstants.KEY_BRANCH_CURRENT, false))
            assertFalse(branch1.optBoolean(GitConstants.KEY_BRANCH_CURRENT, false));
        else/* ww  w.  j a  v a  2s .  com*/
            assertTrue(branch1.optBoolean(GitConstants.KEY_BRANCH_CURRENT, false));

        // remove branch
        request = getDeleteGitBranchRequest(branchLocation);
        response = webConversation.getResponse(request);
        assertTrue(HttpURLConnection.HTTP_OK == response.getResponseCode()
                || HttpURLConnection.HTTP_ACCEPTED == response.getResponseCode());

        // list branches again, make sure it's gone
        request = getGetRequest(branchesLocation);
        response = webConversation.getResponse(request);
        ServerStatus status = waitForTask(response);
        assertTrue(status.toString(), status.isOK());
        branches = status.getJsonData();
        branchesArray = branches.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(1, branchesArray.length());
        JSONObject branch = branchesArray.getJSONObject(0);
        assertTrue(branch.optBoolean(GitConstants.KEY_BRANCH_CURRENT, false));
    }
}

From source file:com.extjs.JSBuilder2.java

private static void createTargetsWithFileIncludes() {
    try {//from ww  w  .  j  a  va 2  s .  co m
        int len = pkgs.length();

        /* loop over packages for fileIncludes */
        for (int i = 0; i < len; i++) {
            /* Build pkg and include file deps */
            JSONObject pkg = pkgs.getJSONObject(i);

            /* if we don't include dependencies, it must be fileIncludes */
            if (!pkg.optBoolean("includeDeps", false)) {
                String targFileName = pkg.getString("file");
                if (targFileName.contains(".js")) {
                    targFileName = FileHelper.insertFileSuffix(pkg.getString("file"), debugSuffix);
                }

                if (verbose) {
                    System.out.format("Building the '%s' package as '%s'%n", pkg.getString("name"),
                            targFileName);
                }

                /* create file and write out header */
                File targetFile = new File(deployDir.getCanonicalPath() + File.separatorChar + targFileName);
                outputFiles.add(targetFile);
                targetFile.getParentFile().mkdirs();
                FileHelper.writeStringToFile("", targetFile, false);

                /* get necessary file includes for this specific package */
                JSONArray fileIncludes = pkg.getJSONArray("fileIncludes");
                int fileIncludesLen = fileIncludes.length();
                if (verbose) {
                    System.out.format("- There are %d file include(s).%n", fileIncludesLen);
                }

                /* loop over file includes */
                for (int j = 0; j < fileIncludesLen; j++) {
                    /* open each file, read into string and append to target */
                    JSONObject fileCfg = fileIncludes.getJSONObject(j);

                    String subFileName = projectHome + File.separatorChar + fileCfg.getString("path")
                            + fileCfg.getString("text");
                    if (verbose) {
                        System.out.format("- - %s%s%n", fileCfg.getString("path"), fileCfg.getString("text"));
                    }

                    File subFile = new File(subFileName);
                    String tempString = FileHelper.readFileToString(subFile);
                    FileHelper.writeStringToFile(tempString, targetFile, true);
                }
            }
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
        System.err.println("Failed to create targets with fileIncludes.");
    }
}