Example usage for org.json JSONObject getBoolean

List of usage examples for org.json JSONObject getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key) throws JSONException 

Source Link

Document

Get the boolean value associated with a key.

Usage

From source file:drusy.ui.panels.WifiStatePanel.java

public void update(final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_WIFI_ID, output,
            "Getting WiFi id", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override/*from  ww  w  .j  ava  2s .  co  m*/
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONArray result = obj.getJSONArray("result");
                JSONObject wifi = result.getJSONObject(0);
                int id = wifi.getInt("id");

                addUsersForWifiId(id, updater);

            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Wi-Fi State (get id)", msg);
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Wi-Fi State (get id)", ex.getMessage());
        }
    });
}

From source file:drusy.ui.panels.WifiStatePanel.java

public void addUsersForWifiId(int id, final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_WIFI_STATIONS.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting WiFi id", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override//from w  w w.ja  va 2  s  . c  o  m
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            clearUsers();
            if (success == true) {
                final JSONArray usersList = obj.getJSONArray("result");

                for (int i = 0; i < usersList.length(); ++i) {
                    JSONObject user = usersList.getJSONObject(i);
                    final String hostname = user.getString("hostname");
                    final long txBytes = user.getLong("tx_rate");
                    final long rxBytes = user.getLong("rx_rate");
                    JSONObject host = user.getJSONObject("host");
                    final String host_type = host.getString("host_type");

                    addUser(host_type, hostname, txBytes, rxBytes);
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Wi-Fi State (get users)", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Wi-Fi State (get users)", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:com.facebook.internal.BundleJSONConverterTest.java

@Test
public void testSimpleValues() throws JSONException {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1st");
    arrayList.add("2nd");
    arrayList.add("third");

    Bundle innerBundle1 = new Bundle();
    innerBundle1.putInt("inner", 1);

    Bundle innerBundle2 = new Bundle();
    innerBundle2.putString("inner", "2");
    innerBundle2.putStringArray("deep list", new String[] { "7", "8" });

    innerBundle1.putBundle("nested bundle", innerBundle2);

    Bundle b = new Bundle();
    b.putBoolean("boolValue", true);
    b.putInt("intValue", 7);
    b.putLong("longValue", 5000000000l);
    b.putDouble("doubleValue", 3.14);
    b.putString("stringValue", "hello world");
    b.putStringArray("stringArrayValue", new String[] { "first", "second" });
    b.putStringArrayList("stringArrayListValue", arrayList);
    b.putBundle("nested", innerBundle1);

    JSONObject json = BundleJSONConverter.convertToJSON(b);
    assertNotNull(json);// w w  w  . j av a  2  s  . c o m

    assertEquals(true, json.getBoolean("boolValue"));
    assertEquals(7, json.getInt("intValue"));
    assertEquals(5000000000l, json.getLong("longValue"));
    assertEquals(3.14, json.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA);
    assertEquals("hello world", json.getString("stringValue"));

    JSONArray jsonArray = json.getJSONArray("stringArrayValue");
    assertEquals(2, jsonArray.length());
    assertEquals("first", jsonArray.getString(0));
    assertEquals("second", jsonArray.getString(1));

    jsonArray = json.getJSONArray("stringArrayListValue");
    assertEquals(3, jsonArray.length());
    assertEquals("1st", jsonArray.getString(0));
    assertEquals("2nd", jsonArray.getString(1));
    assertEquals("third", jsonArray.getString(2));

    JSONObject innerJson = json.getJSONObject("nested");
    assertEquals(1, innerJson.getInt("inner"));
    innerJson = innerJson.getJSONObject("nested bundle");
    assertEquals("2", innerJson.getString("inner"));

    jsonArray = innerJson.getJSONArray("deep list");
    assertEquals(2, jsonArray.length());
    assertEquals("7", jsonArray.getString(0));
    assertEquals("8", jsonArray.getString(1));

    Bundle finalBundle = BundleJSONConverter.convertToBundle(json);
    assertNotNull(finalBundle);

    assertEquals(true, finalBundle.getBoolean("boolValue"));
    assertEquals(7, finalBundle.getInt("intValue"));
    assertEquals(5000000000l, finalBundle.getLong("longValue"));
    assertEquals(3.14, finalBundle.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA);
    assertEquals("hello world", finalBundle.getString("stringValue"));

    List<String> stringList = finalBundle.getStringArrayList("stringArrayValue");
    assertEquals(2, stringList.size());
    assertEquals("first", stringList.get(0));
    assertEquals("second", stringList.get(1));

    stringList = finalBundle.getStringArrayList("stringArrayListValue");
    assertEquals(3, stringList.size());
    assertEquals("1st", stringList.get(0));
    assertEquals("2nd", stringList.get(1));
    assertEquals("third", stringList.get(2));

    Bundle finalInnerBundle = finalBundle.getBundle("nested");
    assertEquals(1, finalInnerBundle.getInt("inner"));
    finalBundle = finalInnerBundle.getBundle("nested bundle");
    assertEquals("2", finalBundle.getString("inner"));

    stringList = finalBundle.getStringArrayList("deep list");
    assertEquals(2, stringList.size());
    assertEquals("7", stringList.get(0));
    assertEquals("8", stringList.get(1));
}

From source file:org.protorabbit.Config.java

static void processURIResources(int type, JSONObject bsjo, ITemplate temp, String baseURI)
        throws JSONException {

    List<ResourceURI> refs = null;
    refs = new ArrayList<ResourceURI>();

    if (bsjo.has("libs")) {

        JSONArray ja = bsjo.getJSONArray("libs");

        for (int j = 0; j < ja.length(); j++) {

            JSONObject so = ja.getJSONObject(j);
            String url = so.getString("url");
            if (url.startsWith("/") || url.startsWith("http")) {
                baseURI = "";
            }/*from w  w w . j  a v a  2 s  . c o  m*/
            ResourceURI ri = new ResourceURI(url, baseURI, type);
            if (so.has("id")) {
                ri.setId(so.getString("id"));
            }
            if (so.has("uaTest")) {
                ri.setUATest(so.getString("uaTest"));
            }
            if (so.has("test")) {
                ri.setTest(so.getString("test"));
            }
            if (so.has("defer")) {
                ri.setDefer(so.getBoolean("defer"));
            }
            if (so.has("combine")) {
                ri.setCombine(so.getBoolean("combine"));
            }
            if (so.has("uniqueURL")) {
                Boolean unique = so.getBoolean("uniqueURL");
                ri.setUniqueURL(unique);
            }
            refs.add(ri);
        }
    }
    Boolean combine = null;
    if (bsjo.has("combineResources")) {
        combine = bsjo.getBoolean("combineResources");
    }
    Boolean lgzip = null;
    if (bsjo.has("gzip")) {
        lgzip = bsjo.getBoolean("gzip");
    }

    if (type == ResourceURI.SCRIPT) {
        temp.setCombineScripts(combine);
        temp.setGzipScripts(lgzip);
        temp.setScripts(refs);
    } else if (type == ResourceURI.LINK) {
        temp.setGzipStyles(lgzip);
        temp.setStyles(refs);
        temp.setCombineStyles(combine);
    }
}

From source file:org.protorabbit.Config.java

@SuppressWarnings("unchecked")
private void registerTemplates(ITemplate temp, JSONObject t, String baseURI) {

    try {/*from   ww  w  .j  a  v a 2  s  .  c o  m*/

        if (t.has("timeout")) {
            long templateTimeout = t.getLong("timeout");
            temp.setTimeout(templateTimeout);
        }

        boolean tgzip = false;

        if (!devMode) {
            tgzip = gzip;
        }

        if (t.has("gzip")) {
            tgzip = t.getBoolean("gzip");
            temp.setGzipStyles(tgzip);
            temp.setGzipScripts(tgzip);
            temp.setGzipTemplate(tgzip);
        }

        if (t.has("uniqueURL")) {
            Boolean unique = t.getBoolean("uniqueURL");
            temp.setUniqueURL(unique);
        }

        // template overrides default combineResources
        if (t.has("combineResources")) {
            boolean combineResources = t.getBoolean("combineResources");
            temp.setCombineResources(combineResources);
            temp.setCombineScripts(combineResources);
            temp.setCombineStyles(combineResources);
        }

        if (t.has("template")) {
            String turi = t.getString("template");
            ResourceURI templateURI = new ResourceURI(turi, baseURI, ResourceURI.TEMPLATE);
            temp.setTemplateURI(templateURI);
        }

        if (t.has("namespace")) {
            temp.setURINamespace(t.getString("namespace"));
        }

        if (t.has("extends")) {
            List<String> ancestors = null;
            String base = t.getString("extends");
            if (base.length() > 0) {
                String[] parentIds = null;
                if (base.indexOf(",") != -1) {
                    parentIds = base.split(",");
                } else {
                    parentIds = new String[1];
                    parentIds[0] = base;
                }
                ancestors = new ArrayList<String>();

                for (int j = 0; j < parentIds.length; j++) {
                    ancestors.add(parentIds[j].trim());
                }
            }

            temp.setAncestors(ancestors);
        }

        if (t.has("overrides")) {

            List<TemplateOverride> overrides = new ArrayList<TemplateOverride>();
            JSONArray joa = t.getJSONArray("overrides");
            for (int z = 0; z < joa.length(); z++) {
                TemplateOverride tor = new TemplateOverride();
                JSONObject toro = joa.getJSONObject(z);
                if (toro.has("test")) {
                    tor.setTest(toro.getString("test"));
                }
                if (toro.has("uaTest")) {
                    tor.setUATest(toro.getString("uaTest"));
                }
                if (toro.has("import")) {
                    tor.setImportURI(toro.getString("import"));
                }
                overrides.add(tor);
            }
            temp.setTemplateOverrides(overrides);
        }

        if (t.has("scripts")) {

            JSONObject bsjo = t.getJSONObject("scripts");

            processURIResources(ResourceURI.SCRIPT, bsjo, temp, baseURI);
        }

        if (t.has("styles")) {
            JSONObject bsjo = t.getJSONObject("styles");

            processURIResources(ResourceURI.LINK, bsjo, temp, baseURI);
        }

        if (t.has("properties")) {

            Map<String, IProperty> properties = null;
            JSONObject po = t.getJSONObject("properties");
            properties = new HashMap<String, IProperty>();

            Iterator<String> jit = po.keys();
            while (jit.hasNext()) {

                String name = jit.next();
                JSONObject so = po.getJSONObject(name);
                int type = IProperty.STRING;
                String value = so.getString("value");

                if (so.has("type")) {

                    String typeString = so.getString("type");

                    if ("string".equals(typeString.toLowerCase())) {
                        type = IProperty.STRING;
                    } else if ("include".equals(typeString.toLowerCase())) {
                        type = IProperty.INCLUDE;
                    }
                }

                IProperty pi = new Property(name, value, type, baseURI, temp.getId());

                if (so.has("timeout")) {
                    long timeout = so.getLong("timeout");
                    pi.setTimeout(timeout);
                }
                if (so.has("id")) {
                    pi.setId(so.getString("id"));
                }
                if (so.has("uaTest")) {
                    pi.setUATest(so.getString("uaTest"));
                }
                if (so.has("test")) {
                    pi.setTest(so.getString("test"));
                }
                if (so.has("defer")) {
                    pi.setDefer(so.getBoolean("defer"));
                }
                if (so.has("deferContent")) {
                    pi.setDeferContent(new StringBuffer(so.getString("deferContent")));
                }
                properties.put(name, pi);
            }
            temp.setProperties(properties);
        }

    } catch (JSONException e) {
        getLogger().log(Level.SEVERE, "Error parsing configuration.", e);
    }

}

From source file:org.wso2.emm.agent.services.PolicyOperationsMapper.java

private Operation buildRestrictionOperation(Operation operation) throws AndroidAgentException {
    operation.setId(INVALID_FLAG);//from www .j ava 2 s .co  m
    try {
        JSONObject payload = new JSONObject(operation.getPayLoad().toString());
        boolean enabled = payload.getBoolean("enabled");
        operation.setEnabled(enabled);
        return operation;
    } catch (JSONException e) {
        throw new AndroidAgentException("Error occurred while parsing payload.", e);
    }
}

From source file:org.wso2.emm.agent.services.PolicyOperationsMapper.java

private Operation buildCameraOperation(Operation operation) throws AndroidAgentException {
    operation.setId(INVALID_FLAG);/* w  ww. ja va 2s.c o m*/
    try {
        JSONObject payload = new JSONObject(operation.getPayLoad().toString());
        boolean enabled = payload.getBoolean("enabled");
        operation.setEnabled(enabled);
        return operation;
    } catch (JSONException e) {
        throw new AndroidAgentException("Error occurred while parsing payload.", e);
    }
}

From source file:org.wso2.emm.agent.services.PolicyOperationsMapper.java

private Operation buildEncryptOperation(Operation operation) throws AndroidAgentException {
    operation.setId(INVALID_FLAG);/*from   w  ww. j  ava  2  s.c  o  m*/
    try {
        JSONObject payload = new JSONObject(operation.getPayLoad().toString());
        boolean encrypt = payload.getBoolean("encrypted");
        operation.setEnabled(encrypt);
        return operation;
    } catch (JSONException e) {
        throw new AndroidAgentException("Error occurred while parsing payload.", e);
    }
}

From source file:net.dv8tion.jda.core.handle.VoiceStateUpdateHandler.java

private void handleGuildVoiceState(JSONObject content) {
    final long userId = content.getLong("user_id");
    final long guildId = content.getLong("guild_id");
    final Long channelId = !content.isNull("channel_id") ? content.getLong("channel_id") : null;
    final String sessionId = !content.isNull("session_id") ? content.getString("session_id") : null;
    boolean selfMuted = content.getBoolean("self_mute");
    boolean selfDeafened = content.getBoolean("self_deaf");
    boolean guildMuted = content.getBoolean("mute");
    boolean guildDeafened = content.getBoolean("deaf");
    boolean suppressed = content.getBoolean("suppress");

    Guild guild = api.getGuildById(guildId);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent));
        EventCache.LOG/*w w  w  . j ava  2  s . com*/
                .debug("Received a VOICE_STATE_UPDATE for a Guild that has yet to be cached. JSON: " + content);
        return;
    }

    VoiceChannelImpl channel = channelId != null ? (VoiceChannelImpl) guild.getVoiceChannelById(channelId)
            : null;
    if (channel == null && channelId != null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug(
                "Received VOICE_STATE_UPDATE for a VoiceChannel that has yet to be cached. JSON: " + content);
        return;
    }

    MemberImpl member = (MemberImpl) guild.getMemberById(userId);
    if (member == null) {
        //Caching of this might not be valid. It is possible that we received this
        // update due to this Member leaving the guild while still connected to a voice channel.
        // In that case, we should not cache this because it could cause problems if they rejoined.
        //However, we can't just ignore it completely because it could be a user that joined off of
        // an invite to a VoiceChannel, so the GUILD_MEMBER_ADD and the VOICE_STATE_UPDATE may have
        // come out of order. Not quite sure what to do. Going to cache for now however.
        //At the worst, this will just cause a few events to fire with bad data if the member rejoins the guild if
        // in fact the issue was that the VOICE_STATE_UPDATE was sent after they had left, however, by caching
        // it we will preserve the integrity of the cache in the event that it was actually a mis-ordering of
        // GUILD_MEMBER_ADD and VOICE_STATE_UPDATE. I'll take some bad-data events over an invalid cache.
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
        EventCache.LOG
                .debug("Received VOICE_STATE_UPDATE for a Member that has yet to be cached. JSON: " + content);
        return;
    }

    GuildVoiceStateImpl vState = (GuildVoiceStateImpl) member.getVoiceState();
    vState.setSessionId(sessionId); //Cant really see a reason for an event for this

    if (!Objects.equals(channel, vState.getChannel())) {
        VoiceChannelImpl oldChannel = (VoiceChannelImpl) vState.getChannel();
        vState.setConnectedChannel(channel);

        if (oldChannel == null) {
            channel.getConnectedMembersMap().put(userId, member);
            api.getEventManager().handle(new GuildVoiceJoinEvent(api, responseNumber, member));
        } else if (channel == null) {
            oldChannel.getConnectedMembersMap().remove(userId);
            api.getEventManager().handle(new GuildVoiceLeaveEvent(api, responseNumber, member, oldChannel));
        } else {
            //If the connect account is the one that is being moved, and this instance of JDA
            // is connected or attempting to connect, them change the channel we expect to be connected to.
            if (guild.getSelfMember().equals(member)) {
                AudioManagerImpl mng = api.getAudioManagerMap().get(guildId);
                if (mng != null && (mng.isConnected() || mng.isAttemptingToConnect()))
                    mng.setConnectedChannel(channel);
            }

            channel.getConnectedMembersMap().put(userId, member);
            oldChannel.getConnectedMembersMap().remove(userId);
            api.getEventManager().handle(new GuildVoiceMoveEvent(api, responseNumber, member, oldChannel));
        }
    }

    boolean wasMute = vState.isMuted();
    boolean wasDeaf = vState.isDeafened();

    if (selfMuted != vState.isSelfMuted()) {
        vState.setSelfMuted(selfMuted);
        api.getEventManager().handle(new GuildVoiceSelfMuteEvent(api, responseNumber, member));
    }
    if (selfDeafened != vState.isSelfDeafened()) {
        vState.setSelfDeafened(selfDeafened);
        api.getEventManager().handle(new GuildVoiceSelfDeafenEvent(api, responseNumber, member));
    }
    if (guildMuted != vState.isGuildMuted()) {
        vState.setGuildMuted(guildMuted);
        api.getEventManager().handle(new GuildVoiceGuildMuteEvent(api, responseNumber, member));
    }
    if (guildDeafened != vState.isGuildDeafened()) {
        vState.setGuildDeafened(guildDeafened);
        api.getEventManager().handle(new GuildVoiceGuildDeafenEvent(api, responseNumber, member));
    }
    if (suppressed != vState.isSuppressed()) {
        vState.setSuppressed(suppressed);
        api.getEventManager().handle(new GuildVoiceSuppressEvent(api, responseNumber, member));
    }
    if (wasMute != vState.isMuted())
        api.getEventManager().handle(new GuildVoiceMuteEvent(api, responseNumber, member));
    if (wasDeaf != vState.isDeafened())
        api.getEventManager().handle(new GuildVoiceDeafenEvent(api, responseNumber, member));
}

From source file:net.dv8tion.jda.core.handle.VoiceStateUpdateHandler.java

private void handleCallVoiceState(JSONObject content) {
    final long userId = content.getLong("user_id");
    final Long channelId = !content.isNull("channel_id") ? content.getLong("channel_id") : null;
    String sessionId = !content.isNull("session_id") ? content.getString("session_id") : null;
    boolean selfMuted = content.getBoolean("self_mute");
    boolean selfDeafened = content.getBoolean("self_deaf");

    //Joining a call
    CallableChannel channel;//from  w  ww  .  jav  a  2s  .  c o  m
    CallVoiceStateImpl vState;
    if (channelId != null) {
        channel = api.asClient().getGroupById(channelId);
        if (channel == null)
            channel = api.getPrivateChannelMap().get(channelId);

        if (channel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "Received a VOICE_STATE_UPDATE for a Group/PrivateChannel that was not yet cached! JSON: "
                            + content);
            return;
        }

        CallImpl call = (CallImpl) channel.getCurrentCall();
        if (call == null) {
            api.getEventCache().cache(EventCache.Type.CALL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG
                    .debug("Received a VOICE_STATE_UPDATE for a Call that is not yet cached. JSON: " + content);
            return;
        }

        CallUser cUser = ((JDAClientImpl) api.asClient()).getCallUserMap().get(userId);
        if (cUser != null && channelId != cUser.getCall().getCallableChannel().getIdLong()) {
            WebSocketClient.LOG.fatal(
                    "Received a VOICE_STATE_UPDATE for a user joining a call, but the user was already in a different call! Big error! JSON: "
                            + content);
            ((CallVoiceStateImpl) cUser.getVoiceState()).setInCall(false);
        }

        cUser = call.getCallUserMap().get(userId);
        if (cUser == null) {
            api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "Received a VOICE_STATE_UPDATE for a user that is not yet a a cached CallUser for the call. (groups only). JSON: "
                            + content);
            return;
        }

        ((JDAClientImpl) api.asClient()).getCallUserMap().put(userId, cUser);
        vState = (CallVoiceStateImpl) cUser.getVoiceState();
        vState.setSessionId(sessionId);
        vState.setInCall(true);

        api.getEventManager().handle(new CallVoiceJoinEvent(api, responseNumber, cUser));
    } else //Leaving a call
    {
        CallUser cUser = ((JDAClientImpl) api.asClient()).getCallUserMap().remove(userId);
        if (cUser == null) {
            api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "Received a VOICE_STATE_UPDATE for a User leaving a Call, but the Call was not yet cached! JSON: "
                            + content);
            return;
        }

        Call call = cUser.getCall();
        channel = call.getCallableChannel();
        vState = (CallVoiceStateImpl) cUser.getVoiceState();
        vState.setSessionId(sessionId);
        vState.setInCall(false);

        api.getEventManager().handle(new CallVoiceLeaveEvent(api, responseNumber, cUser));
    }

    //Now that we're done dealing with the joins and leaves, we can deal with the mute/deaf changes.
    if (selfMuted != vState.isSelfMuted()) {
        vState.setSelfMuted(selfMuted);
        api.getEventManager().handle(new CallVoiceSelfMuteEvent(api, responseNumber, vState.getCallUser()));
    }
    if (selfDeafened != vState.isSelfDeafened()) {
        vState.setSelfDeafened(selfDeafened);
        api.getEventManager().handle(new CallVoiceSelfDeafenEvent(api, responseNumber, vState.getCallUser()));
    }
}