List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java
/** * Start the listeners for zeroconf services *//*from w ww.j a v a2 s .c o m*/ public void doStateNone() { if (wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) { Cursor c = messagesProviderHelper.publicMessages(); while (c.isAfterLast() == false) { String message_hash = c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH)); boolean result = checkHash(message_hash); if (!result) { try { JSONObject message = new JSONObject(); message.put("message_title", c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_TITLE))); message.put("message_content", c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_CONTENT))); message.put("message_hash", c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH))); message.put("message_type", c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_TYPE))); message.put("message_time", c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_TIME))); message.put("message_received_time", c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_RECEIVED_TIME))); message.put("message_priority", c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_PRIORITY))); String attachment_path = c .getString(c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_PATH)); //String serializedMessage = message.toString(); // First, get our nonce consumer = new CommonsHttpOAuthConsumer(key, secret); consumer.setTokenWithSecret(token, token_secret); HttpPost nonce_request = new HttpPost(NEXUS_NONCE_URL); consumer.sign(nonce_request); HttpClient client = new DefaultHttpClient(); String response = client.execute(nonce_request, new BasicResponseHandler()); JSONObject object = new JSONObject(response); String nonce = object.getString("nonce"); // Then, take our nonce and key and put them in the message message.put("message_nonce", nonce); message.put("message_key", key); // Setup our multipart entity MultipartEntity entity = new MultipartEntity(); // Deal with file attachment if (!attachment_path.equals("")) { File file = new File(attachment_path); ContentBody cbFile = new FileBody(file); entity.addPart("message_attachment", cbFile); // add the original filename to the message message.put("message_attachment_original_filename", c.getString( c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_ORIGINAL_FILENAME))); } String serializedMessage = message.toString(); ContentBody messageBody = new StringBody(serializedMessage); entity.addPart("message", messageBody); HttpPost message_request = new HttpPost(NEXUS_MESSAGE_URL); message_request.setEntity(entity); client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); response = client.execute(message_request, new BasicResponseHandler()); object = new JSONObject(response); boolean message_result = object.getBoolean("result"); if (message_result) { ContentValues values = new ContentValues(); values.put(MessagesProviderHelper.KEY_MESSAGE_HASH, message_hash); values.put(MessagesProviderHelper.KEY_UPLOADED, 1); int res = messagesProviderHelper .setPublic(c.getLong(c.getColumnIndex(MessagesProviderHelper.KEY_ID)), values); if (res == 0) { log.debug("Message with hash " + message_hash + " not found; this should never happen!"); } } } catch (OAuthMessageSignerException e) { log.debug("OAuthMessageSignerException: " + e); } catch (OAuthExpectationFailedException e) { log.debug("OAuthExpectationFailedException: " + e); } catch (OAuthCommunicationException e) { log.debug("OAuthCommunicationException: " + e); } catch (JSONException e) { log.debug("JSON Error: " + e); } catch (IOException e) { log.debug("IOException: " + e); } } c.moveToNext(); } c.close(); } setServiceState(STATE_SERVICE_WAIT); }
From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java
/** * Check the hash using the API//from w w w. j a v a 2s. c o m */ private boolean checkHash(String message_hash) { boolean result = true; try { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(HASH_REQUEST_URL + message_hash + ".json"); String response = client.execute(request, new BasicResponseHandler()); JSONObject object = new JSONObject(response); result = object.getBoolean("result"); } catch (JSONException e) { log.debug("JSON Error: " + e); } catch (IOException e) { log.debug("IOException: " + e); } return result; }
From source file:net.dv8tion.jda.core.handle.ChannelUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { ChannelType type = ChannelType.fromId(content.getInt("type")); if (type == ChannelType.GROUP) { handleGroup(content);//from ww w.j a va2 s . com return null; } List<IPermissionHolder> changed = new ArrayList<>(); List<IPermissionHolder> contained = new ArrayList<>(); final long channelId = content.getLong("id"); final int position = content.getInt("position"); final String name = content.getString("name"); final boolean nsfw = !content.isNull("nsfw") && content.getBoolean("nsfw"); JSONArray permOverwrites = content.getJSONArray("permission_overwrites"); switch (type) { case TEXT: { String topic = content.isNull("topic") ? null : content.getString("topic"); TextChannelImpl textChannel = (TextChannelImpl) api.getTextChannelMap().get(channelId); if (textChannel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug( "CHANNEL_UPDATE attempted to update a TextChannel that does not exist. JSON: " + content); return null; } //If any properties changed, update the values and fire the proper events. final String oldName = textChannel.getName(); final String oldTopic = textChannel.getTopic(); final int oldPosition = textChannel.getPositionRaw(); final boolean oldNsfw = textChannel.isNSFW(); if (!Objects.equals(oldName, name)) { textChannel.setName(name); api.getEventManager() .handle(new TextChannelUpdateNameEvent(api, responseNumber, textChannel, oldName)); } if (!Objects.equals(oldTopic, topic)) { textChannel.setTopic(topic); api.getEventManager() .handle(new TextChannelUpdateTopicEvent(api, responseNumber, textChannel, oldTopic)); } if (oldPosition != position) { textChannel.setRawPosition(position); api.getEventManager() .handle(new TextChannelUpdatePositionEvent(api, responseNumber, textChannel, oldPosition)); } if (oldNsfw != nsfw) { textChannel.setNSFW(nsfw); api.getEventManager() .handle(new TextChannelUpdateNSFWEvent(api, responseNumber, textChannel, nsfw)); } applyPermissions(textChannel, content, permOverwrites, contained, changed); //If this update modified permissions in any way. if (!changed.isEmpty()) { api.getEventManager() .handle(new TextChannelUpdatePermissionsEvent(api, responseNumber, textChannel, changed)); } break; //Finish the TextChannelUpdate case } case VOICE: { VoiceChannelImpl voiceChannel = (VoiceChannelImpl) api.getVoiceChannelMap().get(channelId); int userLimit = content.getInt("user_limit"); int bitrate = content.getInt("bitrate"); if (voiceChannel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent)); EventCache.LOG.debug( "CHANNEL_UPDATE attempted to update a VoiceChannel that does not exist. JSON: " + content); return null; } //If any properties changed, update the values and fire the proper events. final String oldName = voiceChannel.getName(); final int oldPosition = voiceChannel.getPositionRaw(); final int oldLimit = voiceChannel.getUserLimit(); final int oldBitrate = voiceChannel.getBitrate(); if (!Objects.equals(oldName, name)) { voiceChannel.setName(name); api.getEventManager() .handle(new VoiceChannelUpdateNameEvent(api, responseNumber, voiceChannel, oldName)); } if (oldPosition != position) { voiceChannel.setRawPosition(position); api.getEventManager().handle( new VoiceChannelUpdatePositionEvent(api, responseNumber, voiceChannel, oldPosition)); } if (oldLimit != userLimit) { voiceChannel.setUserLimit(userLimit); api.getEventManager() .handle(new VoiceChannelUpdateUserLimitEvent(api, responseNumber, voiceChannel, oldLimit)); } if (oldBitrate != bitrate) { voiceChannel.setBitrate(bitrate); api.getEventManager() .handle(new VoiceChannelUpdateBitrateEvent(api, responseNumber, voiceChannel, oldBitrate)); } applyPermissions(voiceChannel, content, permOverwrites, contained, changed); //If this update modified permissions in any way. if (!changed.isEmpty()) { api.getEventManager() .handle(new VoiceChannelUpdatePermissionsEvent(api, responseNumber, voiceChannel, changed)); } break; //Finish the VoiceChannelUpdate case } default: throw new IllegalArgumentException( "CHANNEL_UPDATE provided an unrecognized channel type JSON: " + content); } return null; }
From source file:org.b3log.solo.SoloServletListener.java
/** * Loads preference.//from www. j a v a 2 s . c om * * <p> * Loads preference from repository, loads skins from skin directory then * sets it into preference if the skins changed. Puts preference into * cache and persists it to repository finally. * </p> * * <p> * <b>Note</b>: Do NOT use method * {@linkplain org.b3log.solo.util.Preferences#getPreference()} * to load it, caused by the method may retrieve it from cache. * </p> */ private void loadPreference() { Stopwatchs.start("Load Preference"); LOGGER.info("Loading preference...."); final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance(); JSONObject preference; try { preference = preferenceRepository.get(Preference.PREFERENCE); if (null == preference) { LOGGER.log(Level.WARNING, "Can't not init default skin, please init B3log Solo first"); return; } Skins.loadSkins(preference); final boolean pageCacheEnabled = preference.getBoolean(Preference.PAGE_CACHE_ENABLED); Templates.enableCache(pageCacheEnabled); } catch (final Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new IllegalStateException(e); } Stopwatchs.end(); }
From source file:ded.model.Inheritance.java
public Inheritance(JSONObject o, ArrayList<Entity> integerToEntity) throws JSONException { this.parent = Entity.fromJSONRef(integerToEntity, o.getLong("parentRef")); this.open = o.getBoolean("open"); this.pt = AWTJSONUtil.pointFromJSON(o.getJSONObject("pt")); }
From source file:org.apache.cordova.contacts.ContactAccessorSdk5.java
/** * This method takes the fields required and search options in order to produce an * array of contacts that matches the criteria provided. * @param fields an array of items to be used as search criteria * @param options that can be applied to contact searching * @return an array of contacts// ww w .ja va2 s .c om */ @Override public JSONArray search(JSONArray fields, JSONObject options) { // Get the find options String searchTerm = ""; int limit = Integer.MAX_VALUE; boolean multiple = true; if (options != null) { searchTerm = options.optString("filter"); if (searchTerm.length() == 0) { searchTerm = "%"; } else { searchTerm = "%" + searchTerm + "%"; } try { multiple = options.getBoolean("multiple"); if (!multiple) { limit = 1; } } catch (JSONException e) { // Multiple was not specified so we assume the default is true. } } else { searchTerm = "%"; } //Log.d(LOG_TAG, "Search Term = " + searchTerm); //Log.d(LOG_TAG, "Field Length = " + fields.length()); //Log.d(LOG_TAG, "Fields = " + fields.toString()); // Loop through the fields the user provided to see what data should be returned. HashMap<String, Boolean> populate = buildPopulationSet(options); // Build the ugly where clause and where arguments for one big query. WhereOptions whereOptions = buildWhereClause(fields, searchTerm); // Get all the id's where the search term matches the fields passed in. Cursor idCursor = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Data.CONTACT_ID }, whereOptions.getWhere(), whereOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC"); // Create a set of unique ids Set<String> contactIds = new HashSet<String>(); int idColumn = -1; while (idCursor.moveToNext()) { if (idColumn < 0) { idColumn = idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID); } contactIds.add(idCursor.getString(idColumn)); } idCursor.close(); // Build a query that only looks at ids WhereOptions idOptions = buildIdClause(contactIds, searchTerm); // Determine which columns we should be fetching. HashSet<String> columnsToFetch = new HashSet<String>(); columnsToFetch.add(ContactsContract.Data.CONTACT_ID); columnsToFetch.add(ContactsContract.Data.RAW_CONTACT_ID); columnsToFetch.add(ContactsContract.Data.MIMETYPE); if (isRequired("displayName", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME); } if (isRequired("name", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.PREFIX); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.SUFFIX); } if (isRequired("phoneNumbers", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Phone._ID); columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.NUMBER); columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.TYPE); } if (isRequired("emails", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Email._ID); columnsToFetch.add(ContactsContract.CommonDataKinds.Email.DATA); columnsToFetch.add(ContactsContract.CommonDataKinds.Email.TYPE); } if (isRequired("addresses", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal._ID); columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.STREET); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.CITY); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.REGION); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE); columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY); } if (isRequired("organizations", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Organization._ID); columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE); columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.DEPARTMENT); columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.COMPANY); columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TITLE); } if (isRequired("ims", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Im._ID); columnsToFetch.add(ContactsContract.CommonDataKinds.Im.DATA); columnsToFetch.add(ContactsContract.CommonDataKinds.Im.TYPE); } if (isRequired("note", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Note.NOTE); } if (isRequired("nickname", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Nickname.NAME); } if (isRequired("urls", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Website._ID); columnsToFetch.add(ContactsContract.CommonDataKinds.Website.URL); columnsToFetch.add(ContactsContract.CommonDataKinds.Website.TYPE); } if (isRequired("birthday", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Event.START_DATE); columnsToFetch.add(ContactsContract.CommonDataKinds.Event.TYPE); } if (isRequired("photos", populate)) { columnsToFetch.add(ContactsContract.CommonDataKinds.Photo._ID); } // Do the id query Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI, columnsToFetch.toArray(new String[] {}), idOptions.getWhere(), idOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC"); JSONArray contacts = populateContactArray(limit, populate, c); return contacts; }
From source file:com.github.dfa.diaspora_android.data.PodAspect.java
public PodAspect(JSONObject json) throws JSONException { if (json.has("id")) { id = json.getLong("id"); }/* www . jav a 2s . com*/ if (json.has("name")) { name = json.getString("name"); } if (json.has("selected")) { selected = json.getBoolean("selected"); } }
From source file:de.fahrgemeinschaft.util.ReoccuringWeekDaysView.java
public void setDays(JSONObject details) { this.details = details; try {//w ww . j a va 2s.c om reoccuring = false; JSONObject days = details.getJSONObject(FahrgemeinschaftConnector.REOCCUR); for (int i = 0; i < 7; i++) { boolean selected = days.getBoolean(FahrgemeinschaftConnector.DAYS[i]); getChildAt(i).setSelected(selected); if (selected) reoccuring = true; } } catch (Exception e) { clear(); } }
From source file:com.marketcloud.marketcloud.Json.java
/** * Retrieves the "status" field in a JSONObject. * * @param jsonObject the JSONObject that will be parsed * @return a boolean containing the status of the JSONObject * @throws JSONException usually thrown if the "status" field does not exist */// w ww. j ava 2 s . c om @SuppressWarnings("unused") public boolean getStatus(JSONObject jsonObject) throws JSONException { return jsonObject.getBoolean("status"); }
From source file:edu.rit.csh.androidwebnews.HttpsConnector.java
/** * Creates the threads with all of their sub-threads * * @param obj - the JSONObject of the top level thread to use * @return Thread - the newly created thread with all of its sub-threads *///from w ww . j ava 2 s .co m private PostThread createThread(JSONObject obj, int depthLevel) { JSONObject post; try { post = new JSONObject(obj.getString("post")); PostThread thread = new PostThread(post.getString("date"), post.getInt("number"), post.getString("subject"), post.getString("author_name"), post.getString("author_email"), post.getString("newsgroup"), post.getBoolean("starred"), post.getString("unread_class"), post.getString("personal_class"), post.getString("sticky_until")); thread.setDepth(depthLevel); if (obj.getJSONArray("children") != null) { for (int i = 0; i < obj.getJSONArray("children").length(); i++) { PostThread child = createThread(obj.getJSONArray("children").getJSONObject(i), depthLevel + 1); child.setParent(thread); thread.addChild(child); } } return thread; } catch (JSONException ignored) { } return null; }