List of usage examples for org.json JSONObject optBoolean
public boolean optBoolean(String key)
From source file:com.dbmojo.DBMojoServer.java
private static DBMojoServer getMojoServerFromConfig(String[] args) { DBMojoServer server = null;/* w w w . j ava 2 s . com*/ try { String configFilePath = null; String json = null; JSONObject jObj = null; parseJson: { //If a command line argument is passed then assume it is the config file. //Otherwise use the default location if (args.length > 0) { configFilePath = args[0]; } else { configFilePath = DBMojoServer.defaultConfigPath; } try { json = Util.fileToString(configFilePath); } catch (Exception fileEx) { throw new Exception( "the specified config file, '" + configFilePath + "', could not be found and/or read"); } if (json == null || json.equals("")) { throw new Exception("the specified config file, '" + configFilePath + "', is empty"); } try { jObj = new JSONObject(json); } catch (Exception je) { throw new Exception( "the specified config file, '" + configFilePath + "', does not contain valid JSON"); } } //Load basic config data short serverPort = (short) jObj.optInt("serverPort"); boolean useGzip = jObj.optBoolean("useGzip"); short maxConcReq = (short) jObj.optInt("maxConcurrentRequests"); String accessLogPath = jObj.optString("accessLogPath"); String errorLogPath = jObj.optString("errorLogPath"); String debugLogPath = jObj.optString("debugLogPath"); checkMaxConcurrentReqeusts: { if (maxConcReq <= 0) { throw new Exception("please set the max concurrent requests to " + "a resonable number"); } } checkServerPort: { //Make sure serverPort was specified if (serverPort <= 0) { throw new Exception("the server port was not specified"); } //Make sure serverPort is not in use ServerSocket tSocket = null; try { tSocket = new ServerSocket(serverPort); } catch (Exception se) { tSocket = null; throw new Exception("the server port specified is already in use"); } finally { if (tSocket != null) { tSocket.close(); } tSocket = null; } } startLogs: { if (!accessLogPath.equals("")) { //Make sure accessLogPath exists Util.pathExists(accessLogPath, true); //Start logging AccessLog.start(accessLogPath); } if (!errorLogPath.equals("")) { //Make sure errorLogPath exists Util.pathExists(errorLogPath, true); //Start logging ErrorLog.start(errorLogPath); } if (!debugLogPath.equals("")) { //Make sure debugLogPath exists Util.pathExists(debugLogPath, true); //Start logging DebugLog.start(debugLogPath); } } ConcurrentHashMap<String, ConnectionPool> dbPools = new ConcurrentHashMap<String, ConnectionPool>(); loadDbAlaises: { ClassLoader classLoader = ClassLoader.getSystemClassLoader(); final JSONArray dbAliases = jObj.getJSONArray("dbAliases"); for (int i = 0; i < dbAliases.length(); i++) { final JSONObject tObj = dbAliases.getJSONObject(i); final String tAlias = tObj.getString("alias"); final String tDriver = tObj.getString("driver"); final String tDsn = tObj.getString("dsn"); final String tUsername = tObj.getString("username"); final String tPassword = tObj.getString("password"); int tMaxConnections = tObj.getInt("maxConnections"); //Seconds int tExpirationTime = tObj.getInt("expirationTime") * 1000; //Seconds int tConnectTimeout = tObj.getInt("connectTimeout"); //Make sure each alias is named if (tAlias.equals("")) { throw new Exception("alias #" + i + " is missing a name"); } //Attempt to load each JDBC driver to ensure they are on the class path try { Class aClass = classLoader.loadClass(tDriver); } catch (ClassNotFoundException cnf) { throw new Exception("JDBC Driver '" + tDriver + "' is not on the class path"); } //Make sure each alias has a JDBC connection string if (tDsn.equals("")) { throw new Exception("JDBC URL, 'dsn', is missing for alias '" + tAlias + "'"); } //Attempt to create a JDBC Connection ConnectionPool tPool; try { tPool = new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, 1, 1, 1, tAlias); tPool.checkOut(false); } catch (Exception e) { throw new Exception( "JDBC Connection cannot be established " + "for database '" + tAlias + "'"); } finally { tPool = null; } //If the max connections option is not set for this alias //then set it to 25 if (tMaxConnections <= 0) { tMaxConnections = 25; System.out.println("DBMojoServer: Warning, 'maxConnections' " + "not set for alias '" + tAlias + "' using 25"); } //If the connection expiration time is not set for this alias then //set it to 30 seconds if (tExpirationTime <= 0) { tExpirationTime = 30; System.out.println("DBMojoServer: Warning, 'expirationTime' not " + "set for alias '" + tAlias + "' using 30 seconds"); } //If the connection timeout is not set for this alias then //set it to 10 seconds if (tConnectTimeout <= 0) { tConnectTimeout = 10; System.out.println("DBMojoServer Warning, 'connectTimeout' not " + "set for alias '" + tAlias + "' using 10 seconds"); } //Make sure another alias with the same name is not already //defined in the config if (dbPools.containsKey(tAlias)) { throw new Exception( "the alias '" + tAlias + "' is already defined in " + " the provided config file"); } //Everything is nicely set! Lets add a connection pool to the //dbPool Hashtable keyed by this alias name dbPools.put(tAlias, new JDBCConnectionPool(tDriver, tDsn, tUsername, tPassword, tMaxConnections, tExpirationTime, tConnectTimeout, tAlias)); } } loadClusters: { final JSONArray tClusters = jObj.optJSONArray("clusters"); if (tClusters != null) { for (int c = 0; c < tClusters.length(); c++) { final JSONObject tObj = tClusters.getJSONObject(c); final String tAlias = tObj.getString("alias"); final String tWriteTo = tObj.getString("writeTo"); if (dbPools.containsKey(tAlias)) { throw new Exception("the alias '" + tAlias + "' is already defined."); } if (!dbPools.containsKey(tWriteTo)) { throw new Exception( "the alias '" + tWriteTo + "' is not present in the valid dbAliases. " + "This alias cannot be used for a cluster."); } //Add the dbAlias to the cluster writeTo list ConnectionPool writeTo = dbPools.get(tWriteTo); final JSONArray tReadFrom = tObj.getJSONArray("readFrom"); ArrayList<ConnectionPool> readFromList = new ArrayList<ConnectionPool>(); for (int r = 0; r < tReadFrom.length(); r++) { final String tRead = tReadFrom.getString(r); if (!dbPools.containsKey(tRead)) { throw new Exception( "the alias '" + tRead + "' is not present in the valid dbAliases. " + "This alias cannot be used for a cluster."); } //Add the dbAlias to the cluster readFrom list readFromList.add(dbPools.get(tRead)); } dbPools.put(tAlias, new JDBCClusteredConnectionPool(tAlias, writeTo, readFromList)); } } } server = new DBMojoServer(useGzip, serverPort, maxConcReq, dbPools); } catch (Exception jsonEx) { System.out.println("DBMojoServer: Config error, " + jsonEx); System.exit(-1); } return server; }
From source file:org.catnut.fragment.TweetFragment.java
private void loadTweet() { // load tweet from local... String query = CatnutUtils.buildQuery( new String[] { Status.uid, Status.columnText, Status.bmiddle_pic, Status.original_pic, Status.comments_count, Status.reposts_count, Status.attitudes_count, Status.source, Status.favorited, Status.retweeted_status, Status.pic_urls, "s." + Status.created_at, User.screen_name, User.avatar_large, User.remark, User.verified }, "s._id=" + mId, Status.TABLE + " as s", "inner join " + User.TABLE + " as u on s.uid=u._id", null, null);/* w w w.j a v a 2 s. c o m*/ new AsyncQueryHandler(getActivity().getContentResolver()) { @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (cursor.moveToNext()) { Picasso.with(getActivity()).load(cursor.getString(cursor.getColumnIndex(User.avatar_large))) .placeholder(R.drawable.error).error(R.drawable.error).into(mAvatar); final long uid = cursor.getLong(cursor.getColumnIndex(Status.uid)); final String screenName = cursor.getString(cursor.getColumnIndex(User.screen_name)); mAvatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ProfileActivity.class); intent.putExtra(Constants.ID, uid); intent.putExtra(User.screen_name, screenName); startActivity(intent); } }); String remark = cursor.getString(cursor.getColumnIndex(User.remark)); mRemark.setText(TextUtils.isEmpty(remark) ? screenName : remark); mScreenName.setText(getString(R.string.mention_text, screenName)); mPlainText = cursor.getString(cursor.getColumnIndex(Status.columnText)); mText.setText(mPlainText); CatnutUtils.vividTweet(mText, mImageSpan); CatnutUtils.setTypeface(mText, mTypeface); mText.setLineSpacing(0, mLineSpacing); int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count)); mReplayCount.setText(CatnutUtils.approximate(replyCount)); int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count)); mReteetCount.setText(CatnutUtils.approximate(retweetCount)); int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count)); mFavoriteCount.setText(CatnutUtils.approximate(favoriteCount)); String source = cursor.getString(cursor.getColumnIndex(Status.source)); mSource.setText(Html.fromHtml(source).toString()); mCreateAt.setText(DateUtils.getRelativeTimeSpanString( DateTime.getTimeMills(cursor.getString(cursor.getColumnIndex(Status.created_at))))); if (CatnutUtils.getBoolean(cursor, User.verified)) { mTweetLayout.findViewById(R.id.verified).setVisibility(View.VISIBLE); } String thumb = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic)); String url = cursor.getString(cursor.getColumnIndex(Status.original_pic)); loadThumbs(thumb, url, mThumbs, CatnutUtils.optPics(cursor.getString(cursor.getColumnIndex(Status.pic_urls))), mPicsOverflow); // retweet final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status)); if (!TextUtils.isEmpty(jsonString)) { View retweet = mRetweetLayout.inflate(); try { JSONObject json = new JSONObject(jsonString); JSONObject user = json.optJSONObject(User.SINGLE); String _remark = user.optString(User.remark); if (TextUtils.isEmpty(_remark)) { _remark = user.optString(User.screen_name); } CatnutUtils.setText(retweet, R.id.retweet_nick, getString(R.string.mention_text, _remark)); long mills = DateTime.getTimeMills(json.optString(Status.created_at)); CatnutUtils.setText(retweet, R.id.retweet_create_at, DateUtils.getRelativeTimeSpanString(mills)); TweetTextView retweetText = (TweetTextView) CatnutUtils.setText(retweet, R.id.retweet_text, json.optString(Status.text)); CatnutUtils.vividTweet(retweetText, mImageSpan); CatnutUtils.setTypeface(retweetText, mTypeface); retweetText.setLineSpacing(0, mLineSpacing); retweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), TweetActivity.class); intent.putExtra(Constants.JSON, jsonString); startActivity(intent); } }); retweet.findViewById(R.id.verified) .setVisibility(user.optBoolean(User.verified) ? View.VISIBLE : View.GONE); if (json.has(Status.thumbnail_pic)) { loadThumbs(json.optString(Status.bmiddle_pic), json.optString(Status.bmiddle_pic), (ImageView) retweet.findViewById(R.id.thumbs), json.optJSONArray(Status.pic_urls), retweet.findViewById(R.id.pics_overflow)); } } catch (JSONException e) { Log.e(TAG, "convert text to string error!", e); retweet.setVisibility(View.GONE); } } // shareAndFavorite&favorite shareAndFavorite(CatnutUtils.getBoolean(cursor, Status.favorited), mPlainText); } cursor.close(); } }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, query, null, null); }
From source file:org.catnut.fragment.TweetFragment.java
private void loadRetweet() { JSONObject user = mJson.optJSONObject(User.SINGLE); Picasso.with(getActivity()).load(user == null ? Constants.NULL : user.optString(User.avatar_large)) .placeholder(R.drawable.error).error(R.drawable.error).into(mAvatar); final long uid = mJson.optLong(Status.uid); final String screenName = user == null ? getString(R.string.unknown_user) : user.optString(User.screen_name); mAvatar.setOnClickListener(new View.OnClickListener() { @Override/*from w w w . j a v a 2 s . c o m*/ public void onClick(View v) { Intent intent = new Intent(getActivity(), ProfileActivity.class); intent.putExtra(Constants.ID, uid); intent.putExtra(User.screen_name, screenName); startActivity(intent); } }); String remark = user.optString(User.remark); mRemark.setText(TextUtils.isEmpty(remark) ? screenName : remark); mScreenName.setText(getString(R.string.mention_text, screenName)); mPlainText = mJson.optString(Status.text); mText.setText(mPlainText); CatnutUtils.vividTweet(mText, mImageSpan); CatnutUtils.setTypeface(mText, mTypeface); mText.setLineSpacing(0, mLineSpacing); int replyCount = mJson.optInt(Status.comments_count); mReplayCount.setText(CatnutUtils.approximate(replyCount)); int retweetCount = mJson.optInt(Status.reposts_count); mReteetCount.setText(CatnutUtils.approximate(retweetCount)); int favoriteCount = mJson.optInt(Status.attitudes_count); mFavoriteCount.setText(CatnutUtils.approximate(favoriteCount)); String source = mJson.optString(Status.source); mSource.setText(Html.fromHtml(source).toString()); mCreateAt.setText( DateUtils.getRelativeTimeSpanString(DateTime.getTimeMills(mJson.optString(Status.created_at)))); if (user.optBoolean(User.verified)) { mTweetLayout.findViewById(R.id.verified).setVisibility(View.VISIBLE); } loadThumbs(mJson.optString(Status.bmiddle_pic), mJson.optString(Status.original_pic), mThumbs, mJson.optJSONArray(Status.pic_urls), mPicsOverflow); shareAndFavorite(mJson.optBoolean(Status.favorited), mJson.optString(Status.text)); if (!mJson.has(Status.retweeted_status)) { //todo: ????? } }
From source file:edu.umass.cs.gigapaxos.paxospackets.PreparePacket.java
public PreparePacket(JSONObject json) throws JSONException { super(json);/*from w ww. j a va 2s . com*/ assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.PREPARE); this.packetType = PaxosPacket.getPaxosPacketType(json); this.ballot = new Ballot(json.getString(PaxosPacket.NodeIDKeys.B.toString())); this.firstUndecidedSlot = json.getInt(PaxosPacket.Keys.PREP_MIN.toString()); this.recovery = json.optBoolean(PaxosPacket.Keys.RCVRY.toString()); }
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.DeleteObj.java
@Override public void afterDbInsertion(Context context, DbObj obj) { Uri feedUri = obj.getContainingFeed().getUri(); DBHelper dbh = DBHelper.getGlobal(context); try {/*from w w w . j a v a 2 s . c om*/ JSONObject json = obj.getJson(); long[] hashes; if (json.optJSONArray(HASHES) != null) { JSONArray jsonHashes = json.optJSONArray(HASHES); hashes = new long[jsonHashes.length()]; for (int i = 0; i < jsonHashes.length(); i++) { hashes[i] = jsonHashes.optLong(i); } } else if (json.has(HASH)) { hashes = new long[] { json.optLong(HASH) }; } else { Log.d(TAG, "DeleteObj with no hashes!"); return; } Log.d(TAG, "marking or deleting " + hashes.length); dbh.markOrDeleteFeedObjs(feedUri, hashes, (json.has(FORCE) && json.optBoolean(FORCE))); } finally { dbh.close(); } }
From source file:de.luhmer.owncloudnewsreader.reader.owncloud.InsertItemIntoDatabase.java
private static RssItem parseItem(JSONObject e) throws JSONException { Date pubDate = new Date(e.optLong("pubDate") * 1000); String content = e.optString("body"); content = content.replaceAll("<img[^>]*feedsportal.com.*>", ""); content = content.replaceAll("<img[^>]*statisches.auslieferung.commindo-media-ressourcen.de.*>", ""); content = content.replaceAll("<img[^>]*auslieferung.commindo-media-ressourcen.de.*>", ""); content = content.replaceAll("<img[^>]*rss.buysellads.com.*>", ""); String url = e.optString("url"); String guid = e.optString("guid"); String enclosureLink = e.optString("enclosureLink"); String enclosureMime = e.optString("enclosureMime"); if (enclosureLink.trim().equals("") && guid.startsWith("http://gdata.youtube.com/feeds/api/")) { enclosureLink = url;/* w ww.j a v a 2s . com*/ enclosureMime = "youtube"; } RssItem rssItem = new RssItem(); rssItem.setId(e.getLong("id")); rssItem.setFeedId(e.optLong("feedId")); rssItem.setLink(url); rssItem.setTitle(e.optString("title")); rssItem.setGuid(guid); rssItem.setGuidHash(e.optString("guidHash")); rssItem.setBody(content); rssItem.setAuthor(e.optString("author")); rssItem.setLastModified(new Date(e.optLong("lastModified"))); rssItem.setEnclosureLink(enclosureLink); rssItem.setEnclosureMime(enclosureMime); rssItem.setRead(!e.optBoolean("unread")); rssItem.setRead_temp(rssItem.getRead()); rssItem.setStarred(e.optBoolean("starred")); rssItem.setStarred_temp(rssItem.getStarred()); rssItem.setPubDate(pubDate); return rssItem; /* new RssItem(0, e.optString("id"), e.optString("title"), url, content, !e.optBoolean("unread"), null, e.optString("feedId"), null, date, e.optBoolean("starred"), guid, e.optString("guidHash"), e.optString("lastModified"), e.optString("author"), enclosureLink, enclosureMime); */ }
From source file:org.uiautomation.ios.context.BaseWebInspector.java
public void checkForJSErrors(JSONObject response) throws JSONException { if (response.optBoolean("wasThrown")) { JSONObject details = response.getJSONObject("result"); String desc = details.optString("description"); throw new WebDriverException("JS error :" + desc); }/* w w w. j a va2 s. c om*/ }
From source file:org.uiautomation.ios.context.BaseWebInspector.java
public List<Cookie> getCookies() { List<Cookie> res = new ArrayList<Cookie>(); JSONObject o = sendCommand(Page.getCookies()); JSONArray cookies = o.optJSONArray("cookies"); if (cookies != null) { for (int i = 0; i < cookies.length(); i++) { JSONObject cookie = cookies.optJSONObject(i); String name = cookie.optString("name"); String value = cookie.optString("value"); String domain = cookie.optString("domain"); String path = cookie.optString("path"); Date expiry = new Date(cookie.optLong("expires")); boolean isSecure = cookie.optBoolean("secure"); Cookie c = new Cookie(name, value, domain, path, expiry, isSecure); res.add(c);//from w w w . j a v a2s.c om } return res; } else { // TODO } return null; }
From source file:com.facebook.internal.GraphUtil.java
/** * Determines if the open graph object is for posting * @param object The open graph object to check * @return True if the open graph object was created for posting *//*w w w. j a va2 s. c o m*/ public static boolean isOpenGraphObjectForPost(JSONObject object) { return object != null ? object.optBoolean(NativeProtocol.OPEN_GRAPH_CREATE_OBJECT_KEY) : false; }
From source file:com.partypoker.poker.engagement.reach.activity.EngagementPollActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { /* Init layout */ super.onCreate(savedInstanceState); /* If no content, nothing to do, super class already called finish */ if (mContent == null) return;/*from w ww. j a v a2s .c o m*/ /* Render questions */ LinearLayout questionsLayout = getView("questions"); JSONArray questions = mContent.getQuestions(); LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); try { for (int i = 0; i < questions.length(); i++) { /* Get question */ JSONObject question = questions.getJSONObject(i); /* Inflate question layout */ LinearLayout questionLayout = (LinearLayout) layoutInflater .inflate(getLayoutId("engagement_poll_question"), null); /* Set question's title */ TextView questionTitle = (TextView) questionLayout.findViewById(getId("question_title")); questionTitle.setText(question.getString("title")); /* Set choices */ RadioGroup choicesView = (RadioGroup) questionLayout.findViewById(getId("choices")); choicesView.setTag(question); JSONArray choices = question.getJSONArray("choices"); int choiceViewId = 0; for (int j = 0; j < choices.length(); j++) { /* Get choice */ JSONObject choice = choices.getJSONObject(j); /* Inflate choice layout */ RadioButton choiceView = (RadioButton) layoutInflater .inflate(getLayoutId("engagement_poll_choice"), null); /* Each choice is a radio button */ choiceView.setId(choiceViewId++); choiceView.setTag(choice.getString("id")); choiceView.setText(choice.getString("title")); choiceView.setChecked(choice.optBoolean("isDefault")); choicesView.addView(choiceView); } /* Add to parent layouts */ questionsLayout.addView(questionLayout); /* Watch state */ mRadioGroups.add(choicesView); choicesView.setOnCheckedChangeListener(mRadioGroupListener); } } catch (JSONException jsone) { /* Drop on parsing error */ mContent.dropContent(this); finish(); return; } /* Disable action if a choice is not selected */ updateActionState(); }