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:edu.umass.cs.gigapaxos.paxospackets.FailureDetectionPacket.java

public FailureDetectionPacket(JSONObject json, Stringifiable<NodeIDType> unstringer) throws JSONException {
    super(json);/* w w  w .  ja v  a 2 s  .c  o  m*/
    this.senderNodeID = unstringer.valueOf(json.getString(Keys.SNDR.toString()));
    this.responderNodeID = unstringer.valueOf(json.getString(Keys.RCVR.toString()));
    assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.FAILURE_DETECT);
    this.packetType = PaxosPacket.getPaxosPacketType(json);
    this.status = json.getBoolean(Keys.MODE.toString());
    this.saddr = MessageNIOTransport.getSenderAddress(json);
}

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

@Override
protected Long handleInternally(JSONObject content) {
    final long guildId = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(guildId))
        return guildId;

    GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent));
        return null;
    }/*from w w  w. j  a v  a2 s .c om*/

    JSONArray array = content.getJSONArray("emojis");
    TLongObjectMap<Emote> emoteMap = guild.getEmoteMap();
    List<Emote> oldEmotes = new ArrayList<>(emoteMap.valueCollection()); //snapshot of emote cache
    List<Emote> newEmotes = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
        JSONObject current = array.getJSONObject(i);
        final long emoteId = current.getLong("id");
        EmoteImpl emote = (EmoteImpl) emoteMap.get(emoteId);
        EmoteImpl oldEmote = null;

        if (emote == null) {
            emote = new EmoteImpl(emoteId, guild);
            newEmotes.add(emote);
        } else {
            // emote is in our cache which is why we don't want to remove it in cleanup later
            oldEmotes.remove(emote);
            oldEmote = emote.clone();
        }

        emote.setName(current.getString("name")).setManaged(current.getBoolean("managed"));
        //update roles
        JSONArray roles = current.getJSONArray("roles");
        Set<Role> newRoles = emote.getRoleSet();
        Set<Role> oldRoles = new HashSet<>(newRoles); //snapshot of cached roles
        for (int j = 0; j < roles.length(); j++) {
            Role role = guild.getRoleById(roles.getString(j));
            newRoles.add(role);
            oldRoles.remove(role);
        }

        //cleanup old cached roles that were not found in the JSONArray
        for (Role r : oldRoles) {
            // newRoles directly writes to the set contained in the emote
            newRoles.remove(r);
        }

        // finally, update the emote
        emoteMap.put(emote.getIdLong(), emote);
        // check for updated fields and fire events
        handleReplace(oldEmote, emote);
    }
    //cleanup old emotes that don't exist anymore
    for (Emote e : oldEmotes) {
        emoteMap.remove(e.getIdLong());
        api.getEventManager().handle(new EmoteRemovedEvent(api, responseNumber, e));
    }

    for (Emote e : newEmotes) {
        api.getEventManager().handle(new EmoteAddedEvent(api, responseNumber, e));
    }

    return null;
}

From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java

public Txpk(JSONObject _json) throws MalformedPacketException {

    /**// ww  w  .j a  v a  2s.c  o m
     * imme
     */
    if (!_json.has("imme")) {
        imme = false;
    } else {
        imme = _json.getBoolean("imme");
    }

    /**
     * tmst
     */
    if (!_json.has("tmst")) {
        tmst = Integer.MAX_VALUE;
    } else {
        tmst = _json.getInt("tmst");
    }

    /**
     * time
     */
    if (!_json.has("time")) {
        time = null;
    } else {
        time = _json.getString("time");
    }

    /**
     * rfch
     */
    if (!_json.has("rfch")) {
        throw new MalformedPacketException("missing rfch");
    } else {
        rfch = _json.getInt("rfch");
    }

    /**
     * freq
     */
    if (!_json.has("freq")) {
        throw new MalformedPacketException("missing freq");
    } else {
        freq = _json.getDouble("stat");
    }

    /**
     * powe
     */
    if (!_json.has("powe")) {
        throw new MalformedPacketException("missing powe");
    } else {
        powe = _json.getInt("powe");
    }

    /**
     * modu
     */
    if (!_json.has("modu")) {
        throw new MalformedPacketException("missing modu");
    } else {
        modu = Modulation.parse(_json.getString("modu"));
    }

    /**
     * datr
     */
    if (!_json.has("datr")) {
        throw new MalformedPacketException("missing datr");
    } else {
        switch (modu) {
        case FSK:
            datr = _json.getInt("datr");
            break;
        case LORA:
            datr = _json.getString("datr");
            break;
        }
    }

    /**
     * codr
     */
    if (!_json.has("codr")) {
        if (modu.equals(Modulation.FSK)) {
            codr = null;
        } else {
            throw new MalformedPacketException("missing codr");
        }
    } else {
        codr = _json.getString("codr");
    }

    /**
     * fdev
     */
    if (!_json.has("fdev")) {
        if (modu.equals(Modulation.LORA)) {
            fdev = Integer.MAX_VALUE;
        } else {
            throw new MalformedPacketException("missing fdev");
        }
    } else {
        fdev = _json.getInt("fdev");
    }

    /**
     * ipol
     */
    if (!_json.has("ipol")) {
        if (modu.equals(Modulation.FSK)) {
            ipol = false;
        } else {
            throw new MalformedPacketException("missing ipol");
        }
    } else {
        ipol = _json.getBoolean("ipol");
    }

    /**
     * prea
     */
    if (!_json.has("prea")) {
        throw new MalformedPacketException("missing prea");
    } else {
        prea = _json.getInt("prea");
    }

    /**
     * size
     */
    if (!_json.has("size")) {
        throw new MalformedPacketException("missing size");
    } else {
        size = _json.getInt("size");
    }

    /**
     * data
     */
    if (!_json.has("data")) {
        throw new MalformedPacketException("missing data");
    } else {
        byte[] raw;

        try {
            raw = Base64.getDecoder().decode(_json.getString("data"));
        } catch (IllegalArgumentException ex) {
            throw new MalformedPacketException("malformed data");
        }

        data = new PhyPayload(ByteBuffer.wrap(raw));
    }

    /**
     * ncrc
     */
    if (!_json.has("ncrc")) {
        ncrc = false;
    } else {
        ncrc = _json.getBoolean("ncrc");
    }
}

From source file:org.everit.json.schema.TestSuiteTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }//w  w w  .j  ava 2s.  c  o  m
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:com.nginious.http.application.Http11SerializerTestCase.java

private void testResponse(String body) throws Exception {
    JSONObject bean = new JSONObject(body);
    assertTrue(bean.has("testBean1"));
    bean = bean.getJSONObject("testBean1");

    assertEquals(true, bean.getBoolean("first"));
    assertEquals(1.1d, bean.getDouble("second"));
    assertEquals(1.2f, (float) bean.getDouble("third"));
    assertEquals(2, bean.getInt("fourth"));
    assertEquals(5L, bean.getLong("fifth"));
    assertEquals((short) 3, (short) bean.getInt("sixth"));
    assertEquals("Seven", bean.getString("seventh"));
    assertTrue(bean.has("eight"));
    assertTrue(bean.has("ninth"));
}

From source file:com.nextgis.maplib.display.TMSRenderer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    mAntiAlias = jsonObject.getBoolean(JSON_TMSRENDERER_ANTIALIAS);
    mFilterBitmap = jsonObject.getBoolean(JSON_TMSRENDERER_FILTERBMP);
    mDither = jsonObject.getBoolean(JSON_TMSRENDERER_DITHER);
    mContrast = (float) jsonObject.getDouble(JSON_TMSRENDERER_CONTRAST);
    mBrightness = (float) jsonObject.getDouble(JSON_TMSRENDERER_BRIGHTNESS);
    mForceToGrayScale = jsonObject.getBoolean(JSON_TMSRENDERER_GRAYSCALE);

    mRasterPaint.setAntiAlias(mAntiAlias);
    mRasterPaint.setFilterBitmap(mFilterBitmap);
    mRasterPaint.setDither(mDither);/*from   w ww  .  java 2  s.  c o m*/

    setContrastBrightness(mContrast, mBrightness, mForceToGrayScale);
}

From source file:com.nextgis.maplib.map.VectorLayer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY);
    mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY);
    if (jsonObject.has(JSON_RENDERERPROPS_KEY)) {
        setDefaultRenderer();/*w  w w.j  a v  a  2 s.c om*/

        if (null != mRenderer && mRenderer instanceof IJSONStore) {
            IJSONStore jsonStore = (IJSONStore) mRenderer;
            jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY));
        }
    }

    if (mIsInitialized) {
        mExtents = new GeoEnvelope();

        //load vector cache
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(false);
        String[] columns = new String[] { "_ID", "GEOM" };
        Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            mVectorCacheItems = new ArrayList<>();
            do {
                try {
                    GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1));
                    int nId = cursor.getInt(0);
                    mExtents.merge(geoGeometry.getEnvelope());
                    mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());
        }
    }
}

From source file:com.nginious.http.websocket.WebSocketTestCase.java

public void testDeserializableBeans() throws Exception {
    WebSocketTestConnection wsConn = null;

    try {/* w ww  .j  a  v a2 s  .  c  om*/
        wsConn = handshake("wsdeserialize");

        byte[] mask = generateRandomBytes(4);
        String str = "{ \"testBean1\": { \"first\": \"true\" } }";
        byte len = (byte) (0x80 + str.length());
        byte[] payload = generateMaskedString(str, mask);
        byte[] header = { (byte) 0x81, len, mask[0], mask[1], mask[2], mask[3] };

        byte[] frame = new byte[header.length + payload.length];
        System.arraycopy(header, 0, frame, 0, header.length);
        System.arraycopy(payload, 0, frame, header.length, payload.length);
        wsConn.write(frame);

        // Check response frame
        byte[] respFrame = wsConn.readFrame();
        assertNotNull(respFrame);

        byte flags = respFrame[0];
        assertTrue((flags & 0x80) > 0); // Check for final frame flag set
        assertTrue("i=" + str.length() + ", flags=" + flags, (flags & 0x0F) == 0x01); // Check for opcode text message
        len = respFrame[1];

        String respStr = new String(respFrame, 2, len);
        JSONObject testBean = new JSONObject(respStr);
        assertTrue(testBean.has("testBean1"));
        JSONObject testBean2 = testBean.getJSONObject("testBean1");
        assertNotNull(testBean2);
        assertTrue(testBean2.getBoolean("first"));
    } finally {
        if (wsConn != null) {
            wsConn.close();
        }
    }
}

From source file:com.nginious.http.websocket.WebSocketTestCase.java

public void testSerializableBeans() throws Exception {
    WebSocketTestConnection wsConn = null;

    try {// www . j  av  a  2s  . c om
        wsConn = handshake("wsserialize");

        byte[] mask = generateRandomBytes(4);
        String str = "{ \"testBean1\": { \"first\": \"true\" } }";
        byte len = (byte) (0x80 + str.length());
        byte[] payload = generateMaskedString(str, mask);
        byte[] header = { (byte) 0x81, len, mask[0], mask[1], mask[2], mask[3] };

        byte[] frame = new byte[header.length + payload.length];
        System.arraycopy(header, 0, frame, 0, header.length);
        System.arraycopy(payload, 0, frame, header.length, payload.length);
        wsConn.write(frame);

        // Check response frame
        byte[] respFrame = wsConn.readFrame();
        assertNotNull(respFrame);

        byte flags = respFrame[0];
        assertTrue((flags & 0x80) > 0); // Check for final frame flag set
        assertTrue("i=" + str.length() + ", flags=" + flags, (flags & 0x0F) == 0x01); // Check for opcode text message
        len = respFrame[1];

        String respStr = new String(respFrame, 2, len);
        JSONObject testBean = new JSONObject(respStr);
        assertTrue(testBean.has("testBean1"));
        JSONObject testBean2 = testBean.getJSONObject("testBean1");
        assertNotNull(testBean2);
        assertTrue(testBean2.getBoolean("first"));
    } finally {
        if (wsConn != null) {
            wsConn.close();
        }
    }
}

From source file:com.markupartist.sthlmtraveling.provider.planner.JourneyQuery.java

public static JourneyQuery fromJson(JSONObject jsonObject) throws JSONException {
    JourneyQuery journeyQuery = new JourneyQuery.Builder().origin(jsonObject.getJSONObject("origin"))
            .destination(jsonObject.getJSONObject("destination"))
            .transportModes(jsonObject.has("transportModes") ? jsonObject.getJSONArray("transportModes") : null)
            .create();//from w  w w  . java2s. co  m

    if (jsonObject.has("isTimeDeparture")) {
        journeyQuery.isTimeDeparture = jsonObject.getBoolean("isTimeDeparture");
    }
    if (jsonObject.has("alternativeStops")) {
        journeyQuery.alternativeStops = jsonObject.getBoolean("alternativeStops");
    }
    if (jsonObject.has("via")) {
        JSONObject jsonVia = jsonObject.getJSONObject("via");
        Location via = new Location();
        via.name = jsonVia.getString("name");
        journeyQuery.via = via;
    }

    return journeyQuery;
}