List of usage examples for org.json JSONObject get
public Object get(String key) throws JSONException
From source file:org.jabsorb.ng.serializer.impl.DictionarySerializer.java
@Override public Object unmarshall(final SerializerState state, final Class<?> clazz, final Object o) throws UnmarshallException { final JSONObject jso = (JSONObject) o; String java_class; // Hint check try {//from ww w .j a va 2 s . co m java_class = jso.getString("javaClass"); } catch (final JSONException e) { throw new UnmarshallException("Could not read javaClass", e); } if (java_class == null) { throw new UnmarshallException("no type hint"); } // Create the dictionary Hashtable<Object, Object> dictionary; if (java_class.equals("java.util.Dictionary") || java_class.equals("java.util.Hashtable")) { dictionary = new Hashtable<Object, Object>(); } else if (java_class.equals("java.util.Properties")) { dictionary = new Properties(); } else { throw new UnmarshallException("not a Dictionary"); } // Parse the JSON map JSONObject jsonmap; try { jsonmap = jso.getJSONObject("map"); } catch (final JSONException e) { throw new UnmarshallException("map missing", e); } if (jsonmap == null) { throw new UnmarshallException("map missing"); } state.setSerialized(o, dictionary); final Iterator<?> i = jsonmap.keys(); String key = null; try { while (i.hasNext()) { key = (String) i.next(); dictionary.put(key, ser.unmarshall(state, null, jsonmap.get(key))); } } catch (final UnmarshallException e) { throw new UnmarshallException("key " + key + " " + e.getMessage(), e); } catch (final JSONException e) { throw new UnmarshallException("key " + key + " " + e.getMessage(), e); } return dictionary; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitRevertTest.java
@Test public void testRevert() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "first line\nsec. line\nthird line\n"); addFile(testTxt);// www . j av a 2 s. c o m commitFile(testTxt, "lines in test.txt", false); JSONArray commitsArray = log(gitHeadUri); assertEquals(2, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toRevert = commit.getString(ProtocolConstants.KEY_NAME); // REVERT JSONObject revert = revert(gitHeadUri, toRevert); assertEquals("OK", revert.getString(GitConstants.KEY_RESULT)); // new revert commit is present commitsArray = log(gitHeadUri); assertEquals(3, commitsArray.length()); commit = commitsArray.getJSONObject(0); String revertMessage = commit.optString(GitConstants.KEY_COMMIT_MESSAGE); assertEquals(true, revertMessage != null); assertEquals(true, revertMessage.startsWith("Revert \"lines in test.txt\"")); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitRevertTest.java
@Test public void testRevertFailure() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "first line\nsec. line\nthird line\n"); addFile(testTxt);/*from w ww . j av a2 s . c om*/ commitFile(testTxt, "lines in test.txt", false); JSONArray commitsArray = log(gitHeadUri); assertEquals(2, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toRevert = commit.getString(ProtocolConstants.KEY_NAME); modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n"); addFile(testTxt); // REVERT JSONObject revert = revert(gitHeadUri, toRevert); assertEquals("FAILURE", revert.getString(GitConstants.KEY_RESULT)); // there's no new revert commit commitsArray = log(gitHeadUri); assertEquals(2, commitsArray.length()); commit = commitsArray.getJSONObject(0); String revertMessage = commit.optString(GitConstants.KEY_COMMIT_MESSAGE); assertEquals(true, revertMessage != null); assertEquals(false, revertMessage.startsWith("Revert \"lines in test.txt\"")); } }
From source file:io.spring.initializr.web.project.MainControllerIntegrationTests.java
private static void assertStandardErrorBody(String body, String message) { assertNotNull("error body must be available", body); JSONObject model = new JSONObject(body); assertEquals(message, model.get("message")); }
From source file:org.wso2.carbon.connector.integration.test.flickr.FlickrConnectoreIntegrationTest.java
/** * Positive test case for addTags method with mandatory parameters. */// w w w . j a va 2 s.c o m @Test(priority = 1, groups = { "wso2.esb" }, description = "flickr {addTags} integration test with mandatory parameters") public void testFlickrAddTagsWithMandatoryParameters() throws Exception { String jsonRequestFilePath = pathToRequestsDirectory + "flickr_addTags.txt"; String methodName = "flickr_addTags"; String rawString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath); rawString = rawString.replace("dummyvalue", flickrConnectorProperties.getProperty("photoId")); rawString = rawString.replace("tagName", flickrConnectorProperties.getProperty("tagName") + System.currentTimeMillis()); final String jsonString = addCredentials(rawString); final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml"; proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath))); try { JSONObject responseConnector = ConnectorIntegrationUtil.sendRequest("POST", getProxyServiceURL(methodName), jsonString); String httpMethod = "GET"; String parameters = "format=json&nojsoncallback=1&method=flickr.photos.getInfo&api_key=" + flickrConnectorProperties.getProperty("consumerKey") + "&photo_id=" + flickrConnectorProperties.getProperty("photoId"); JSONObject responseDirect = ConnectorIntegrationUtil.sendRestRequest(false, httpMethod, parameters, flickrConnectorProperties); addTagMethodTagId = ((JSONObject) responseConnector.getJSONObject("tags").getJSONArray("tag").get(0)) .getString("full_tag_id"); Assert.assertTrue(responseDirect.toString().contains(addTagMethodTagId)); } finally { proxyAdmin.deleteProxy(methodName); } }
From source file:net.idlesoft.android.apps.github.activities.SingleActivityItem.java
private void loadActivityItemBox() { final TextView date = (TextView) findViewById(R.id.tv_activity_item_date); final ImageView gravatar = (ImageView) findViewById(R.id.iv_activity_item_gravatar); final ImageView icon = (ImageView) findViewById(R.id.iv_activity_item_icon); final TextView title_tv = (TextView) findViewById(R.id.tv_activity_item_title); try {// w w w.j a va 2 s . co m final JSONObject entry = mJson; final JSONObject payload = entry.getJSONObject("payload"); String end; final SimpleDateFormat dateFormat = new SimpleDateFormat(Hubroid.GITHUB_ISSUES_TIME_FORMAT); final Date item_time = dateFormat.parse(entry.getString("created_at")); final Date current_time = dateFormat.parse(dateFormat.format(new Date())); final long ms = current_time.getTime() - item_time.getTime(); final long sec = ms / 1000; final long min = sec / 60; final long hour = min / 60; final long day = hour / 24; if (day > 0) { if (day == 1) { end = " day ago"; } else { end = " days ago"; } date.setText(day + end); } else if (hour > 0) { if (hour == 1) { end = " hour ago"; } else { end = " hours ago"; } date.setText(hour + end); } else if (min > 0) { if (min == 1) { end = " minute ago"; } else { end = " minutes ago"; } date.setText(min + end); } else { if (sec == 1) { end = " second ago"; } else { end = " seconds ago"; } date.setText(sec + end); } final String actor = entry.getString("actor"); final String eventType = entry.getString("type"); String title = actor + " did something..."; gravatar.setImageBitmap(GravatarCache.getDipGravatar(GravatarCache.getGravatarID(actor), 30.0f, getResources().getDisplayMetrics().density)); if (eventType.contains("PushEvent")) { icon.setImageResource(R.drawable.push); title = actor + " pushed to " + payload.getString("ref").split("/")[2] + " at " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("WatchEvent")) { final String action = payload.getString("action"); if (action.equalsIgnoreCase("started")) { icon.setImageResource(R.drawable.watch_started); } else { icon.setImageResource(R.drawable.watch_stopped); } title = actor + " " + action + " watching " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("GistEvent")) { final String action = payload.getString("action"); icon.setImageResource(R.drawable.gist); title = actor + " " + action + "d " + payload.getString("name"); } else if (eventType.contains("ForkEvent")) { icon.setImageResource(R.drawable.fork); title = actor + " forked " + entry.getJSONObject("repository").getString("name") + "/" + entry.getJSONObject("repository").getString("owner"); } else if (eventType.contains("CommitCommentEvent")) { icon.setImageResource(R.drawable.comment); title = actor + " commented on " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("ForkApplyEvent")) { icon.setImageResource(R.drawable.merge); title = actor + " applied fork commits to " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("FollowEvent")) { icon.setImageResource(R.drawable.follow); title = actor + " started following " + payload.getJSONObject("target").getString("login"); } else if (eventType.contains("CreateEvent")) { icon.setImageResource(R.drawable.create); if (payload.getString("object").contains("repository")) { title = actor + " created repository " + payload.getString("name"); } else if (payload.getString("object").contains("branch")) { title = actor + " created branch " + payload.getString("object_name") + " at " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (payload.getString("object").contains("tag")) { title = actor + " created tag " + payload.getString("object_name") + " at " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } } else if (eventType.contains("IssuesEvent")) { if (payload.getString("action").equalsIgnoreCase("opened")) { icon.setImageResource(R.drawable.issues_open); } else { icon.setImageResource(R.drawable.issues_closed); } title = actor + " " + payload.getString("action") + " issue " + payload.getInt("number") + " on " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("DeleteEvent")) { icon.setImageResource(R.drawable.delete); if (payload.getString("object").contains("repository")) { title = actor + " deleted repository " + payload.getString("name"); } else if (payload.getString("object").contains("branch")) { title = actor + " deleted branch " + payload.getString("object_name") + " at " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (payload.getString("object").contains("tag")) { title = actor + " deleted tag " + payload.getString("object_name") + " at " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } } else if (eventType.contains("WikiEvent")) { icon.setImageResource(R.drawable.wiki); title = actor + " " + payload.getString("action") + " a page in the " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name") + " wiki"; } else if (eventType.contains("DownloadEvent")) { icon.setImageResource(R.drawable.download); title = actor + " uploaded a file to " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("PublicEvent")) { icon.setImageResource(R.drawable.opensource); title = actor + " open sourced " + entry.getJSONObject("repository").getString("name"); } else if (eventType.contains("PullRequestEvent")) { final int number = (payload.get("pull_request") instanceof JSONObject) ? payload.getJSONObject("pull_request").getInt("number") : payload.getInt("number"); if (payload.getString("action").equalsIgnoreCase("opened")) { icon.setImageResource(R.drawable.issues_open); title = actor + " opened pull request " + number + " on " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } else if (payload.getString("action").equalsIgnoreCase("closed")) { icon.setImageResource(R.drawable.issues_closed); title = actor + " closed pull request " + number + " on " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } } else if (eventType.contains("MemberEvent")) { icon.setImageResource(R.drawable.follow); title = actor + " added " + payload.getString("member") + " to " + entry.getJSONObject("repository").getString("owner") + "/" + entry.getJSONObject("repository").getString("name"); } title_tv.setText(title); gravatar.setOnClickListener(new OnClickListener() { public void onClick(final View v) { final Intent i = new Intent(SingleActivityItem.this, Profile.class); i.putExtra("username", actor); startActivity(i); } }); } catch (final JSONException e) { e.printStackTrace(); } catch (final ParseException e) { e.printStackTrace(); } }
From source file:net.dv8tion.jda.core.handle.PresenceUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { //Do a pre-check to see if this is for a Guild, and if it is, if the guild is currently locked. if (content.has("guild_id")) { final long guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; }//from w w w . ja va 2s . co m JSONObject jsonUser = content.getJSONObject("user"); final long userId = jsonUser.getLong("id"); UserImpl user = (UserImpl) api.getUserMap().get(userId); //If we do know about the user, lets update the user's specific info. // Afterwards, we will see if we already have them cached in the specific guild // or Relation. If not, we'll cache the OnlineStatus and Game for later handling // unless OnlineStatus is OFFLINE, in which case we probably received this event // due to a User leaving a guild or no longer being a relation. if (user != null) { if (jsonUser.has("username")) { String name = jsonUser.getString("username"); String discriminator = jsonUser.get("discriminator").toString(); String avatarId = jsonUser.isNull("avatar") ? null : jsonUser.getString("avatar"); if (!user.getName().equals(name)) { String oldUsername = user.getName(); String oldDiscriminator = user.getDiscriminator(); user.setName(name); user.setDiscriminator(discriminator); api.getEventManager().handle( new UserNameUpdateEvent(api, responseNumber, user, oldUsername, oldDiscriminator)); } String oldAvatar = user.getAvatarId(); if (!(avatarId == null && oldAvatar == null) && !Objects.equals(avatarId, oldAvatar)) { String oldAvatarId = user.getAvatarId(); user.setAvatarId(avatarId); api.getEventManager().handle(new UserAvatarUpdateEvent(api, responseNumber, user, oldAvatarId)); } } //Now that we've update the User's info, lets see if we need to set the specific Presence information. // This is stored in the Member or Relation objects. String gameName = null; String gameUrl = null; Game.GameType type = null; if (!content.isNull("game") && !content.getJSONObject("game").isNull("name")) { gameName = content.getJSONObject("game").get("name").toString(); gameUrl = (content.getJSONObject("game").isNull("url") ? null : content.getJSONObject("game").get("url").toString()); try { type = content.getJSONObject("game").isNull("type") ? Game.GameType.DEFAULT : Game.GameType.fromKey( Integer.parseInt(content.getJSONObject("game").get("type").toString())); } catch (NumberFormatException ex) { type = Game.GameType.DEFAULT; } } Game nextGame = (gameName == null ? null : new GameImpl(gameName, gameUrl, type)); OnlineStatus status = OnlineStatus.fromKey(content.getString("status")); //If we are in a Guild, then we will use Member. // If we aren't we'll be dealing with the Relation system. if (content.has("guild_id")) { GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id")); MemberImpl member = (MemberImpl) guild.getMember(user); //If the Member is null, then User isn't in the Guild. //This is either because this PRESENCE_UPDATE was received before the GUILD_MEMBER_ADD event // or because a Member recently left and this PRESENCE_UPDATE came after the GUILD_MEMBER_REMOVE event. //If it is because a Member recently left, then the status should be OFFLINE. As such, we will ignore // the event if this is the case. If the status isn't OFFLINE, we will cache and use it when the // Member object is setup during GUILD_MEMBER_ADD if (member == null) { //Cache the presence and return to finish up. if (status != OnlineStatus.OFFLINE) { guild.getCachedPresenceMap().put(userId, content); return null; } } else { //The member is already cached, so modify the presence values and fire events as needed. if (!member.getOnlineStatus().equals(status)) { OnlineStatus oldStatus = member.getOnlineStatus(); member.setOnlineStatus(status); api.getEventManager().handle( new UserOnlineStatusUpdateEvent(api, responseNumber, user, guild, oldStatus)); } if (member.getGame() == null ? nextGame != null : !member.getGame().equals(nextGame)) { Game oldGame = member.getGame(); member.setGame(nextGame); api.getEventManager() .handle(new UserGameUpdateEvent(api, responseNumber, user, guild, oldGame)); } } } else { //In this case, this PRESENCE_UPDATE is for a Relation. } } else { //In this case, we don't have the User cached, which means that we can't update the User's information. // This is most likely because this PRESENCE_UPDATE came before the GUILD_MEMBER_ADD that would have added // this User to our User cache. Or, it could have come after a GUILD_MEMBER_REMOVE that caused the User // to be removed from JDA's central User cache because there were no more connected Guilds. If this is // the case, then the OnlineStatus will be OFFLINE and we can ignore this event. //Either way, we don't have the User cached so we need to cache the Presence information if // the OnlineStatus is not OFFLINE. //If the OnlineStatus is OFFLINE, ignore the event and return. OnlineStatus status = OnlineStatus.fromKey(content.getString("status")); if (status == OnlineStatus.OFFLINE) return null; //If this was for a Guild, cache it in the Guild for later use in GUILD_MEMBER_ADD if (content.has("guild_id")) { GuildImpl guild = (GuildImpl) api.getGuildById(content.getLong("guild_id")); guild.getCachedPresenceMap().put(userId, content); } else { //cache in relationship stuff } } return null; }
From source file:pt.webdetails.cdb.query.AbstractQuery.java
@Override public void fromJSON(JSONObject json) { String _id, _key, _group, _name; HashMap<String, Object> _properties = new HashMap<String, Object>(); try {/*from ww w . j av a 2s . c o m*/ /* Load everything into temporary variables */ _id = json.getString("guid"); _key = json.getString("@rid"); _group = json.getString("group"); _name = json.getString("name"); JSONObject props = json.getJSONObject("definition"); for (String key : JSONObject.getNames(props)) { _properties.put(key, props.get(key)); } /* Seems like we managed to safely load everything, so it's * now safe to copy all the values over to the object */ id = _id; key = _key; group = _group; name = _name; properties = _properties; } catch (JSONException jse) { logger.error("Error while reading values from JSON", jse); } }
From source file:pt.webdetails.cdb.query.AbstractQuery.java
@Override public void load(String key) { PersistenceEngine eng = PersistenceEngine.getInstance(); try {//from w w w .j ava 2 s .com Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); JSONObject response = eng.query("select * from Query where @rid = :id", params); JSONObject query = (JSONObject) ((JSONArray) response.get("object")).get(0); fromJSON(query); } catch (Exception e) { logger.error(e); } }
From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java
public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException { super(_randoms, PacketType.PUSH_DATA); _raw.order(ByteOrder.LITTLE_ENDIAN); if (_raw.remaining() < 8) { throw new MalformedPacketException("too short"); }/*w w w .j a va 2 s . c o m*/ gatewayEui = new byte[8]; _raw.get(gatewayEui); byte[] json = new byte[_raw.remaining()]; _raw.get(json); JSONObject jo; try { jo = new JSONObject(new String(json)); } catch (JSONException ex) { throw new MalformedPacketException("malformed json"); } stats = new ArrayList<>(); rxpks = new ArrayList<>(); if (jo.has("rxpk")) { if (!jo.get("rxpk").getClass().equals(JSONArray.class)) { throw new MalformedPacketException("malformed json (rxpk)"); } JSONArray rxpk = jo.getJSONArray("rxpk"); for (int i = 0; i < rxpk.length(); i++) { rxpks.add(new Rxpk(rxpk.getJSONObject(i))); } } if (jo.has("stat")) { if (!jo.get("stat").getClass().equals(JSONArray.class)) { throw new MalformedPacketException("malformed json (stat)"); } JSONArray stat = jo.getJSONArray("stat"); for (int i = 0; i < stat.length(); i++) { stats.add(new Stat(stat.getJSONObject(i))); } } }