Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java

/**
 * Positive test case for listDiscussionTopics method with optional parameters.
 *//*from   w  w w .j a  v a2  s.  c om*/
@Test(groups = { "wso2.esb" }, dependsOnMethods = {
        "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {listDiscussionTopics} integration test with optional parameters.")
public void testListDiscussionTopicsWithOptionalParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listDiscussionTopics");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listDiscussionTopics_optional.json");

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/"
            + connectorProperties.getProperty("courseId")
            + "/discussion_topics?order_by=position&scope=unlocked";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    JSONArray esbResponseArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(apiResponseArray.length(), esbResponseArray.length());

    if (apiResponseArray.length() > 0) {
        JSONObject esbFirstResult = esbResponseArray.getJSONObject(0);
        JSONObject apiFirstResult = apiResponseArray.getJSONObject(0);

        Assert.assertEquals(apiFirstResult.getString("id"), esbFirstResult.getString("id"));
        Assert.assertEquals(apiFirstResult.getString("title"), esbFirstResult.getString("title"));
        Assert.assertEquals(apiFirstResult.getString("message"), esbFirstResult.getString("message"));
    }

}

From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java

/**
 * Test createEntry method with Mandatory Parameters.
 *///w w w .j  a v a2s .com
@Test(groups = { "wso2.esb" }, dependsOnMethods = {
        "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {createEntry} integration test with Mandatory parameters.")
public void testCreateEntryWithMandatoryParameters() throws IOException, JSONException {

    headersMap.put("Action", "urn:createEntry");

    final String requestString = proxyUrl + "?courseId=" + connectorProperties.getProperty("courseId")
            + "&topicId=" + connectorProperties.getProperty("topicId") + "&apiUrl="
            + connectorProperties.getProperty("apiUrl") + "&accessToken="
            + connectorProperties.getProperty("accessToken");

    MultipartFormdataProcessor multipartProcessor = new MultipartFormdataProcessor(requestString, headersMap);
    File file = new File(pathToResourcesDirectory + connectorProperties.getProperty("attachmentFileName"));
    multipartProcessor.addFileToRequest("attachment", file,
            URLConnection.guessContentTypeFromName(file.getName()));
    multipartProcessor.addFormDataToRequest("message", connectorProperties.getProperty("entryMessage"));

    RestResponse<JSONObject> esbRestResponse = multipartProcessor.processForJsonResponse();
    String entryId = esbRestResponse.getBody().getString("id");
    String userId = esbRestResponse.getBody().getString("user_id");

    connectorProperties.put("entryId", entryId);

    final String apiUrl = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/"
            + connectorProperties.getProperty("courseId") + "/discussion_topics/"
            + connectorProperties.getProperty("topicId") + "/entry_list?ids[]=" + entryId;

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap);
    JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output"));
    JSONObject apiFirstElement = apiResponseArray.getJSONObject(0);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Assert.assertEquals(apiFirstElement.getString("created_at").split("T")[0], sdf.format(new Date()));
    Assert.assertEquals(apiFirstElement.getString("user_id"), userId);
}

From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java

/**
 * Test createEntry method with Optional Parameters.
 *//*  w w  w.j a v  a  2s .c om*/
@Test(groups = { "wso2.esb" }, dependsOnMethods = {
        "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {createEntry} integration test with optional parameters.")
public void testCreateEntryWithOptionalParameters() throws IOException, JSONException {

    headersMap.put("Action", "urn:createEntry");

    final String requestString = proxyUrl + "?courseId=" + connectorProperties.getProperty("courseId")
            + "&topicId=" + connectorProperties.getProperty("topicId") + "&apiUrl="
            + connectorProperties.getProperty("apiUrl") + "&accessToken="
            + connectorProperties.getProperty("accessToken");

    MultipartFormdataProcessor multipartProcessor = new MultipartFormdataProcessor(requestString, headersMap);
    File file = new File(pathToResourcesDirectory + connectorProperties.getProperty("attachmentFileName"));
    multipartProcessor.addFileToRequest("attachment", file,
            URLConnection.guessContentTypeFromName(file.getName()));
    multipartProcessor.addFormDataToRequest("message", connectorProperties.getProperty("entryMessage"));

    RestResponse<JSONObject> esbRestResponse = multipartProcessor.processForJsonResponse();

    String entryId = esbRestResponse.getBody().getString("id");

    final String apiUrl = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/"
            + connectorProperties.getProperty("courseId") + "/discussion_topics/"
            + connectorProperties.getProperty("topicId") + "/entry_list?ids[]=" + entryId;

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap);
    JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output"));
    JSONObject apiFirstElement = apiResponseArray.getJSONObject(0);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Assert.assertEquals(connectorProperties.getProperty("entryMessage"), apiFirstElement.getString("message"));
    Assert.assertEquals(connectorProperties.getProperty("attachmentFileName"),
            apiFirstElement.getJSONObject("attachment").getString("filename"));
    Assert.assertEquals(apiFirstElement.getString("created_at").split("T")[0], sdf.format(new Date()));
}

From source file:cz.autoclient.league_of_legends.LoLVersion.java

@Override
public String getVersion() {
    if (version == null) {
        JSONObject data = getJSONData();
        try {/*from w  w w.ja  v a 2s .  c  o m*/
            version = data.getString("v");
        } catch (JSONException e) {
            System.out.println(e);
            return "error";
        }
        if (version != null) {
            tryClearData();
        }
    }

    return version;
}

From source file:cz.autoclient.league_of_legends.LoLVersion.java

public String getLanguage() {
    if (language == null) {
        JSONObject data = getJSONData();
        try {//www  . j  av a 2  s  .c  o m
            language = data.getString("l");
        } catch (JSONException e) {
            //System.out.println(e);
            return "en_US";
        }
    }
    if (language != null) {
        tryClearData();
    }
    return language;
}

From source file:cz.autoclient.league_of_legends.LoLVersion.java

public static boolean isLatestVersion(String version, Realm realm) {
    if (latestVersion == null) {
        try {//from   w ww . ja  v a2s  . co  m
            JSONObject data = DataLoader
                    .fromURL(new URL("http://ddragon.leagueoflegends.com/realms/" + realm + ".json"));
            latestVersion = data.getString("v");
        } catch (Exception e) {
            //If fail, something is broken so any updates are not possible anyway
            return true;
        }
    }
    return version.equals(latestVersion);
}

From source file:edu.umass.cs.gigapaxos.paxospackets.FailureDetectionPacket.java

public FailureDetectionPacket(JSONObject json, Stringifiable<NodeIDType> unstringer) throws JSONException {
    super(json);//w  ww .j  a  va2  s.co  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.ccghe.emocha.SettingsReqPwd.java

@Override
protected void onResume() {
    super.onResume();

    String url = Preferences.getServerURL(this);

    if (url.length() < Constants.SERVER_URL_MIN_LENGTH) {
        responseText.setText(R.string.settings_serverURL_undefined);
    } else {//from w  ww.java  2  s. c  o  m
        JSONObject response = Server.activatePhone(Preferences.getImei(this));

        try {
            String msg = response.getString("msg");
            responseText.setText(msg);
        } catch (JSONException e) {
            responseText.setText("error");
        }

    }
}

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  va  2 s .  c  o m

    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 {

    /**//  w  w w .j ava2s .  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");
    }
}