List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:edu.stanford.junction.api.activity.ActivityScript.java
public void addRolePlatform(String role, String platform, JSONObject platformSpec) { try {// ww w. j a v a 2 s. c o m if (roleSpecs == null) roleSpecs = new JSONObject(); if (!roleSpecs.has(role)) { roleSpecs.put(role, new JSONObject()); } JSONObject jsonRole = roleSpecs.getJSONObject(role); if (!jsonRole.has("platforms")) { jsonRole.put("platforms", new JSONObject()); } JSONObject jsonPlatforms = jsonRole.getJSONObject("platforms"); jsonPlatforms.put(platform, platformSpec); mJSON = null; // reset } catch (Exception e) { e.printStackTrace(); } }
From source file:edu.stanford.junction.api.activity.ActivityScript.java
public void addRoleHint(String role, String hint) { try {//from w w w .j a va 2 s . c o m if (roleSpecs == null) roleSpecs = new JSONObject(); if (!roleSpecs.has(role)) { roleSpecs.put(role, new JSONObject()); } JSONObject jsonRole = roleSpecs.getJSONObject(role); if (!jsonRole.has("hints")) { jsonRole.put("hints", new JSONArray()); } JSONArray jsonHints = jsonRole.getJSONArray("hints"); jsonHints.put(hint); mJSON = null; // reset } catch (Exception e) { e.printStackTrace(); } }
From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java
private void loadFromJSON(File json) { try {//from w w w. j a va2s . c o m String s = readFile(json); if (s.trim().length() != 0) { JSONObject jsonO = new JSONObject(s); if (jsonO.has("title")) { jTextField3.setText(jsonO.getString("title")); } if (jsonO.has("id")) { jTextField5.setText(jsonO.getString("id")); jTextField2.setText("/usr/palm/applications/" + jTextField5.getText() + "/"); jTextField2.setCaretPosition(0); } if (jsonO.has("version")) { jTextField6.setText(jsonO.getString("version").replaceAll("-", ".").replaceAll("_", ".")); } if (jsonO.has("vendor")) { jTextField7.setText(jsonO.getString("vendor")); } } } catch (Exception e) { } }
From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java
public void readFromControlFile(File control) { try {//from w w w . j a v a2 s . c o m BufferedReader input = new BufferedReader(new FileReader(control)); String line = input.readLine(); while (line != null) { line = line.trim(); if (line.length() > 0 && line.indexOf(":") != line.length() - 1) { if (line.startsWith("Package")) { jTextField5.setText(line.substring(line.indexOf(":") + 2)); } else if (line.startsWith("Description")) { jTextField3.setText(line.substring(line.indexOf(":") + 2)); } else if (line.startsWith("Version")) { jTextField6.setText( line.substring(line.indexOf(":") + 2).replaceAll("-", ".").replaceAll("_", ".")); } else if (line.startsWith("Architecture")) { setArch(line.substring(line.indexOf(":") + 2)); } else if (line.startsWith("Maintainer")) { jTextField7.setText(line.substring(line.indexOf(":") + 2)); } else if (line.startsWith("Depends")) { String[] tokens = line.substring(line.indexOf(":") + 2).split(","); for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].trim(); if (!depends.contains(tokens[i])) { depends.add(tokens[i]); } } jList2.setListData(depends.toArray()); } else if (line.startsWith("Source")) { JSONObject src = new JSONObject(line.substring(line.indexOf(":") + 2)); if (src.has("Icon")) { jTextField4.setText(src.getString("Icon")); } if (src.has("Screenshots")) { JSONArray ss = src.getJSONArray("Screenshots"); for (int i = 0; i < ss.length(); i++) { if (!ssURLs.contains(ss.getString(i))) { ssURLs.add(ss.getString(i)); } } jList1.setListData(ssURLs.toArray()); } if (src.has("FullDescription")) { jTextArea2.setText(src.getString("FullDescription").replaceAll("<br>", "\n")); } if (src.has("Homepage")) { jTextField9.setText(src.getString("Homepage")); } if (src.has("Type")) { setType(src.getString("Type")); } if (src.has("Category")) { jTextField12.setText(src.getString("Category")); } if (src.has("License")) { jTextField11.setText(src.getString("License")); } if (src.has("Location")) { jTextField10.setText(src.getString("Location")); } if (src.has("PostInstallFlags")) { setFlag(jComboBox2, src.getString("PostInstallFlags")); } if (src.has("PostUpdateFlags")) { setFlag(jComboBox3, src.getString("PostUpdateFlags")); } if (src.has("PostRemoveFlags")) { setFlag(jComboBox4, src.getString("PostRemoveFlags")); } } } line = input.readLine(); } } catch (Exception e) { } }
From source file:org.dasein.cloud.joyent.JoyentException.java
static public ExceptionItems parseException(int code, String json) { ExceptionItems items = new ExceptionItems(); items.code = code;//from w ww. java2 s .com items.type = CloudErrorType.GENERAL; items.message = "unknown"; items.details = "The cloud provided an error code without explanation"; if (json != null) { try { JSONObject ob = new JSONObject(json); if (ob.has("message")) { items.details = ob.getString("message"); } else { items.details = "[" + code + "] " + items.message; } if (ob.has("code")) { items.message = ob.getString("code"); if (items.message == null) { items.message = "unknown"; } else { items.message = items.message.trim(); } } else { items.message = "unknown"; } String t = items.message.toLowerCase().trim(); if (t.equals("notauthorized") || t.equals("invalidcredentials")) { items.type = CloudErrorType.AUTHENTICATION; } else if (t.equals("requestthrottled")) { items.type = CloudErrorType.CAPACITY; } else if (t.equals("requesttoolarge") || t.equals("badrequest") || t.equals("invalidargument") || t.equals("invalidheader") || t.equals("invalidversion") || t.equals("missingparameter")) { items.type = CloudErrorType.COMMUNICATION; } else if (t.equals("resourcenotfound")) { return null; } } catch (JSONException e) { SmartDataCenter.getLogger(JoyentException.class, "std") .warn("parseException(): Invalid JSON in cloud response: " + json); items.details = json; } } return items; }
From source file:com.mifos.mifosxdroid.dialogfragments.loanaccountdisbursement.LoanAccountDisbursement.java
@Override public void showLoanTemplate(ResponseBody result) { final ArrayList<PaymentTypeOptions> paymentOption = new ArrayList<PaymentTypeOptions>(); final ArrayList<String> paymentNames = new ArrayList<String>(); BufferedReader reader = null; StringBuilder sb = new StringBuilder(); String line;/*from w w w .j a va 2 s . c o m*/ try { reader = new BufferedReader(new InputStreamReader(result.byteStream())); while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject obj = new JSONObject(sb.toString()); if (obj.has("paymentTypeOptions")) { JSONArray paymentOptions = obj.getJSONArray("paymentTypeOptions"); for (int i = 0; i < paymentOptions.length(); i++) { JSONObject paymentObject = paymentOptions.getJSONObject(i); PaymentTypeOptions payment = new PaymentTypeOptions(); payment.setId(paymentObject.optInt("id")); payment.setName(paymentObject.optString("name")); paymentOption.add(payment); paymentNames.add(paymentObject.optString("name")); paymentNameIdHashMap.put(payment.getName(), payment.getId()); } } String stringResult = sb.toString(); } catch (Exception e) { Log.e(LOG_TAG, "", e); } ArrayAdapter<String> paymentAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, paymentNames); paymentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp_payment_type.setAdapter(paymentAdapter); sp_payment_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { paymentTypeId = paymentNameIdHashMap.get(paymentNames.get(i)); Log.d("paymentId " + paymentNames.get(i), String.valueOf(paymentTypeId)); if (paymentTypeId != -1) { } else { Toast.makeText(getActivity(), getString(R.string.error_select_payment), Toast.LENGTH_SHORT) .show(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }
From source file:com.tapfortap.phonegap.TapForTapPhoneGapPlugin.java
private void setAdOptions(JSONObject options) throws JSONException { adView.setLayoutParams(getLayoutParamsForOptions(options)); if (options.has("gender")) { String gender = options.getString("gender"); if (gender.equals("male")) TapForTap.setGender(TapForTap.Gender.MALE); else if (gender.equals("female")) TapForTap.setGender(TapForTap.Gender.FEMALE); else/*from ww w . j ava2s . c o m*/ TapForTap.setGender(TapForTap.Gender.NONE); } if (options.has("age")) { TapForTap.setAge(options.getInt("age")); } if (options.has("location")) { JSONObject locationObject = options.getJSONObject("location"); Location location = new Location("user"); location.setLatitude(locationObject.getDouble("latitude")); location.setLongitude(locationObject.getDouble("longitude")); TapForTap.setLocation(location); } }
From source file:fi.harism.lucidchat.api.ChatConnection.java
/** * Handle server event messages.//from w w w. j av a 2 s . c o m */ private void handleEvent(String message) { try { // We receive always JSON messages. JSONObject json = new JSONObject(message); // Get event type from JSON. String event = json.optString("event"); // Handle session_created event. if (event.equals("session_created")) { // Here we expect that server sends user_auth only when new // session is created. In case where old session was continues // user_auth ought not to be present. if (!json.has("user_auth")) { // Notify server about connection. mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Session resumed userId=" + mUserId + " sessionId=" + mSessionId)); mObserver.onConnect(mUserId, mUserAuth, mSessionId); } else { // New session was created. mUserId = json.getString("user_id"); mUserAuth = json.getString("user_auth"); mSessionId = json.getString("session_id"); mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Session created userId=" + mUserId + " sessionId=" + mSessionId)); mObserver.onConnect(mUserId, mUserAuth, mSessionId); // If autojoin is enabled send join message. if (mAutojoin) { sendJoinChannel(NINCHAT_LOUNGE); } } } // Handle user_updated and user_found events. if (event.equals("user_updated") || event.equals("user_found")) { String userId = json.getString("user_id"); // If update was sent for ourself. if (userId.equals(mUserId)) { // We do nothing on updates sent to self at the moment. } else { // Notify observer about user updated event. JSONObject userAttrs = json.getJSONObject("user_attrs"); String name = userAttrs.optString("name"); String realName = userAttrs.optString("realname"); boolean connected = userAttrs.optBoolean("connected"); mObserver.onUserUpdated(new User(userId, name, realName, connected)); } } // Handle channel_updated event. if (event.equals("channel_updated")) { String channelId = json.getString("channel_id"); JSONObject channelAttrs = json.getJSONObject("channel_attrs"); String name = channelAttrs.optString("name"); String topic = channelAttrs.optString("topic"); mObserver.onChannelUpdated(new Channel(channelId, name, topic)); } // Handle search_results event. if (event.equals("search_results")) { mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Search results event")); Vector<Channel> channelList = new Vector<Channel>(); // Parse channels from search results. JSONObject channels = json.optJSONObject("channels"); if (channels != null) { JSONArray names = channels.names(); for (int i = 0; i < names.length(); ++i) { String channelId = names.getString(i); JSONObject channelAttrs = channels.getJSONObject(channelId).getJSONObject("channel_attrs"); String name = channelAttrs.optString("name"); String topic = channelAttrs.optString("topic"); channelList.add(new Channel(channelId, name, topic)); } } // Parse users from search results. Vector<User> userList = new Vector<User>(); JSONObject users = json.optJSONObject("users"); if (users != null) { JSONArray names = users.names(); for (int i = 0; i < names.length(); ++i) { String userId = names.getString(i); if (!userId.equals(mUserId)) { JSONObject user = users.getJSONObject(userId); String name = user.optString("name"); String realName = user.optString("realname"); boolean connected = user.optBoolean("connected"); userList.add(new User(userId, name, realName, connected)); } } } mObserver.onSearchResults(channelList, userList); } // Handle channel_joined event. if (event.equals("channel_joined")) { mObserver.onServerMessage(new Message(Message.TYPE_LOG, "Channel joined event")); String channelId = json.getString("channel_id"); Vector<User> userList = new Vector<User>(); JSONObject channelMembers = json.getJSONObject("channel_members"); JSONArray names = channelMembers.names(); for (int i = 0; i < names.length(); ++i) { String userId = names.getString(i); JSONObject userAttrs = channelMembers.getJSONObject(userId).getJSONObject("user_attrs"); if (!userId.equals(mUserId)) { String name = userAttrs.optString("name"); String realName = userAttrs.optString("realname"); boolean connected = userAttrs.optBoolean("connected"); userList.add(new User(userId, name, realName, connected)); } } JSONObject channelAttrs = json.getJSONObject("channel_attrs"); String name = channelAttrs.getString("name"); String topic = channelAttrs.getString("topic"); mObserver.onChannelJoined(new Channel(channelId, name, topic), userList); } // Message receiving happens with 2 callbacks. First // message_received is sent from server and then an empty JSON with // message only. if (event.equals("message_received")) { // Check message_type. We handle only text messages. if (json.optString("message_type").equals("ninchat.com/text")) { mMessage = json; } if (json.optString("message_type").equals("ninchat.com/info")) { mMessage = json; } } // Second part of text message receiving. if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/text") && json.has("text")) { // Message time is in seconds after epoch. long messageTime = mMessage.getLong("message_time") * 1000; String messageUserName = mMessage.getString("message_user_name"); String channelId = mMessage.optString("channel_id"); String userId = mMessage.optString("user_id"); String text = json.getString("text"); mMessage = null; // If channel_id exists notify observer about channel message. if (channelId.length() > 0) { mObserver.onChannelMessage(channelId, new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text)); } // If user_id exists notify observer about private message. if (userId.length() > 0) { User user = new User(userId, messageUserName, "", true); mObserver.onUserMessage(user, new Message(Message.TYPE_CONVERSATION, messageTime, messageUserName, text)); } } if (mMessage != null && mMessage.optString("message_type").equals("ninchat.com/info") && json.has("info")) { String info = json.getString("info"); if (info.equals("join")) { String channelId = mMessage.getString("channel_id"); String userId = json.getString("user_id"); String userName = json.getString("user_name"); mObserver.onInfoJoin(channelId, userId, userName); } if (info.equals("part")) { String channelId = mMessage.getString("channel_id"); String userId = json.getString("user_id"); String userName = json.getString("user_name"); mObserver.onInfoPart(channelId, userId, userName); } mMessage = null; } // Handle channel_parted event. if (event.equals("channel_parted")) { String channelId = json.getString("channel_id"); mObserver.onChannelParted(channelId); } // Handle channel_member_joined. if (event.equals("channel_member_joined")) { String channelId = json.getString("channel_id"); String userId = json.getString("user_id"); JSONObject userAttrs = json.getJSONObject("user_attrs"); String name = userAttrs.getString("name"); String realname = userAttrs.optString("realname"); boolean connected = userAttrs.optBoolean("connected"); mObserver.onUserJoin(channelId, new User(userId, name, realname, connected)); } // Handle channel_member_parted. if (event.equals("channel_member_parted")) { String channelId = json.getString("channel_id"); String userId = json.getString("user_id"); mObserver.onUserPart(channelId, userId); } // Handle second phase of delete_user. if (event.equals("user_deleted")) { mWSC.disconnect(); } } catch (JSONException ex) { ex.printStackTrace(); } }
From source file:com.appdevper.mediaplayer.app.CastPlayback.java
private void updateMetadata() { try {//from w w w. ja va 2 s .co m MediaInfo mediaInfo = mCastManager.getRemoteMediaInformation(); if (mediaInfo == null) { return; } JSONObject customData = mediaInfo.getCustomData(); if (customData != null && customData.has(ITEM_ID)) { String remoteMediaId = customData.getString(ITEM_ID); if (!TextUtils.equals(mCurrentMediaId, remoteMediaId)) { mCurrentMediaId = remoteMediaId; if (mCallback != null) { mCallback.onMetadataChanged(remoteMediaId); } mCurrentPosition = getCurrentStreamPosition(); } } } catch (TransientNetworkDisconnectionException | NoConnectionException | JSONException e) { LogHelper.e(TAG, e, "Exception processing update metadata"); } }
From source file:ai.susi.mind.SusiThought.java
/** * create a clone of a json object as a SusiThought object * @param json the 'other' thought, probably an exported and re-imported thought *///from w ww . j a va 2s . co m public SusiThought(JSONObject json) { this(); if (json.has(this.metadata_name)) this.put(this.metadata_name, json.getJSONObject(this.metadata_name)); if (json.has(this.data_name)) this.setData(json.getJSONArray(this.data_name)); if (json.has("actions")) this.put("actions", json.getJSONArray("actions")); }