Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

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

Prototype

public int optInt(String key) 

Source Link

Document

Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number.

Usage

From source file:com.vk.sdkweb.api.model.VKApiUserFull.java

public VKApiUserFull parse(JSONObject user) {
    super.parse(user);

    // general/*from  www  .  java 2 s.c  om*/
    last_seen = parseLong(user.optJSONObject(LAST_SEEN), "time");
    bdate = user.optString(BDATE);

    JSONObject city = user.optJSONObject(CITY);
    if (city != null) {
        this.city = new VKApiCity().parse(city);
    }
    JSONObject country = user.optJSONObject(COUNTRY);
    if (country != null) {
        this.country = new VKApiCountry().parse(country);
    }

    // education
    universities = new VKList<VKApiUniversity>(user.optJSONArray(UNIVERSITIES), VKApiUniversity.class);
    schools = new VKList<VKApiSchool>(user.optJSONArray(SCHOOLS), VKApiSchool.class);

    // status
    activity = user.optString(ACTIVITY);

    JSONObject status_audio = user.optJSONObject("status_audio");
    if (status_audio != null)
        this.status_audio = new VKApiAudio().parse(status_audio);

    // personal views
    JSONObject personal = user.optJSONObject(PERSONAL);
    if (personal != null) {
        smoking = personal.optInt("smoking");
        alcohol = personal.optInt("alcohol");
        political = personal.optInt("political");
        life_main = personal.optInt("life_main");
        people_main = personal.optInt("people_main");
        inspired_by = personal.optString("inspired_by");
        religion = personal.optString("religion");
        if (personal.has("langs")) {
            JSONArray langs = personal.optJSONArray("langs");
            if (langs != null) {
                this.langs = new String[langs.length()];
                for (int i = 0; i < langs.length(); i++) {
                    this.langs[i] = langs.optString(i);
                }
            }
        }
    }

    // contacts
    facebook = user.optString("facebook");
    facebook_name = user.optString("facebook_name");
    livejournal = user.optString("livejournal");
    site = user.optString(SITE);
    screen_name = user.optString("screen_name", "id" + id);
    skype = user.optString("skype");
    mobile_phone = user.optString("mobile_phone");
    home_phone = user.optString("home_phone");
    twitter = user.optString("twitter");
    instagram = user.optString("instagram");

    // personal info
    about = user.optString(ABOUT);
    activities = user.optString(ACTIVITIES);
    books = user.optString(BOOKS);
    games = user.optString(GAMES);
    interests = user.optString(INTERESTS);
    movies = user.optString(MOVIES);
    quotes = user.optString(QUOTES);
    tv = user.optString(TV);

    // settings
    nickname = user.optString("nickname", null);
    can_post = parseBoolean(user, CAN_POST);
    can_see_all_posts = parseBoolean(user, CAN_SEE_ALL_POSTS);
    blacklisted_by_me = parseBoolean(user, BLACKLISTED_BY_ME);
    can_write_private_message = parseBoolean(user, CAN_WRITE_PRIVATE_MESSAGE);
    wall_comments = parseBoolean(user, WALL_DEFAULT);
    String deactivated = user.optString("deactivated");
    is_deleted = "deleted".equals(deactivated);
    is_banned = "banned".equals(deactivated);
    wall_default_owner = "owner".equals(user.optString(WALL_DEFAULT));
    verified = parseBoolean(user, VERIFIED);

    // other
    sex = user.optInt(SEX);
    JSONObject counters = user.optJSONObject(COUNTERS);
    if (counters != null)
        this.counters = new Counters(counters);

    relation = user.optInt(RELATION);

    if (user.has(RELATIVES)) {
        if (relatives == null) {
            relatives = new VKList<Relative>();
        }
        relatives.fill(user.optJSONArray(RELATIVES), Relative.class);
    }
    return this;
}

From source file:com.vk.sdkweb.api.model.VKApiUniversity.java

/**
 * Fills a University instance from JSONObject.
 *///from   ww w. j  a  v a2s  . c om
public VKApiUniversity parse(JSONObject from) {
    id = from.optInt("id");
    country_id = from.optInt("country_id");
    city_id = from.optInt("city_id");
    name = from.optString("name");
    faculty = from.optString("faculty");
    faculty_name = from.optString("faculty_name");
    chair = from.optInt("chair");
    chair_name = from.optString("chair_name");
    graduation = from.optInt("graduation");
    education_form = from.optString("education_form");
    education_status = from.optString("education_status");
    return this;
}

From source file:com.dbmojo.DBMojoServer.java

private static DBMojoServer getMojoServerFromConfig(String[] args) {

    DBMojoServer server = null;/*www .j  a v a 2s . c o m*/

    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

protected void refresh() {
    // ???//from  w  w  w. j ava2  s .c  o  m
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, mSelection, Status.TABLE,
                    null, BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = CommentsAPI.show(mId, since_id, 0, size, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.CommentTweetsProcessor(mId),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(Status.total_number);
                                    // ???
                                    mLastTotalCount = 0;
                                    mShowToastTimes = 0;
                                    JSONArray jsonArray = response.optJSONArray(Status.COMMENTS);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, TweetFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

From source file:org.catnut.fragment.TweetFragment.java

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = CommentsAPI.show(mId, 0, max_id, getFetchSize(), 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api, new StatusProcessor.CommentTweetsProcessor(mId),
            new Response.Listener<JSONObject>() {
                @Override//from  ww  w. ja  v  a 2  s  .  c om
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(Status.total_number);
                    mLastTotalCount = mAdapter.getCount();
                    int newSize = response.optJSONArray(Status.COMMENTS).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, TweetFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:org.catnut.fragment.TweetFragment.java

private void toggleFavorite() {
    mRequestQueue.add(/*from ww w  . ja  va 2 s .  c om*/
            new CatnutRequest(getActivity(), mFavorited ? FavoritesAPI.destroy(mId) : FavoritesAPI.create(mId),
                    new StatusProcessor.FavoriteTweetProcessor(), new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Toast.makeText(getActivity(),
                                    mFavorited ? R.string.cancle_favorite_success : R.string.favorite_success,
                                    Toast.LENGTH_SHORT).show();
                            mFavorited = !mFavorited;
                            // ?ui
                            JSONObject status = response.optJSONObject(Status.SINGLE);
                            mReplayCount.setText(CatnutUtils.approximate(status.optInt(Status.comments_count)));
                            mReteetCount.setText(CatnutUtils.approximate(status.optInt(Status.reposts_count)));
                            mFavoriteCount
                                    .setText(CatnutUtils.approximate(status.optInt(Status.attitudes_count)));
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            WeiboAPIError weiboAPIError = WeiboAPIError.fromVolleyError(error);
                            Toast.makeText(getActivity(), weiboAPIError.error, Toast.LENGTH_SHORT).show();
                        }
                    }))
            .setTag(TAG);
}

From source file:com.linkedin.platform.listeners.ApiResponse.java

public static synchronized ApiResponse buildApiResponse(JSONObject apiResponseAsJson) {
    try {//from   w  w w .  j av  a2s.c  o  m
        int statusCode = apiResponseAsJson.optInt(STATUS_CODE);
        String locationHeader = apiResponseAsJson.optString(LOCATION);
        String responseData = apiResponseAsJson.getString(DATA);
        return new ApiResponse(statusCode, responseData, locationHeader);
    } catch (JSONException e) {
        Log.d(TAG, e.getMessage());
    }
    return null;
}

From source file:com.funzio.pure2D.particles.nova.vo.NovaEmitterVO.java

public NovaEmitterVO(final JSONObject json) throws JSONException {
    super(json);/*from w w  w.  jav  a 2  s.c om*/

    name = json.optString("name");

    if (json.has("type")) {
        type = json.getString("type");
    }

    if (json.has("width")) {
        width = json.getInt("width");
    }

    if (json.has("height")) {
        height = json.getInt("height");
    }

    if (json.has("quantity")) {
        quantity = json.getInt("quantity");
    }

    if (json.has("lifespan")) {
        lifespan = json.getInt("lifespan");
    }

    // offset position
    x = json.optInt("x");
    y = json.optInt("y");

    animator = json.optString("animator");
    motion_trail = json.optString("motion_trail");
    particles = getParticles(json.optJSONArray("particles"));
}

From source file:com.ymt.demo1.plates.hub.MyHubFragment.java

/**
 * ?/*  www .  j  a v a2  s  . com*/
 */
protected StringRequest getHubMyPost(String userName, int index) {
    return new StringRequest(BaseURLUtil.getHubMyPost(userName, index), new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                if (jsonObject.getInt("retCode") == 0) {
                    countGetter.getPostCount(jsonObject.getInt("count"));

                    JSONArray array = jsonObject.getJSONArray("data");
                    int length = array.length();
                    for (int i = 0; i < length; i++) {
                        JSONObject object = array.getJSONObject(i);
                        MyHubPost post = new MyHubPost();
                        post.setFid(object.optInt("fid"));
                        post.setReplies(object.optInt("replies"));
                        post.setViews(object.optInt("views"));
                        post.setTid(object.optInt("tid"));
                        post.setAuthor(object.optString("author"));
                        post.setLastposter(object.optString("lastposter"));
                        post.setSubject(object.optString("subject"));
                        post.setName(object.optString("name"));
                        post.setLastpost(object.optString("lastpost"));
                        post.setDateline(object.optString("dateline"));
                        postList.add(post);

                    }
                    hubPostAdapter.setSubjects(postList);
                }
            } catch (JSONException e) {
                AppContext.toastBadJson();
            }

            pullToRefreshListView.onRefreshComplete();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            AppContext.toastBadInternet();
            pullToRefreshListView.onRefreshComplete();
        }
    });
}

From source file:com.ymt.demo1.plates.hub.MyHubFragment.java

/**
 * /*w w  w. ja  va 2  s.  com*/
 */
protected StringRequest getHubMyReplies(String userName, int index) {
    return new StringRequest(BaseURLUtil.getHubMyReplies(userName, index), new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                if (jsonObject.getInt("retCode") == 0) {
                    countGetter.getReplyCount(jsonObject.getInt("count"));

                    JSONArray array = jsonObject.getJSONArray("data");
                    int length = array.length();
                    for (int i = 0; i < length; i++) {
                        JSONObject object = array.getJSONObject(i);
                        MyHubReply reply = new MyHubReply();
                        reply.setMessage(object.optString("message"));
                        reply.setFid(object.optInt("fid"));
                        reply.setLastposter(object.optString("lastposter"));
                        reply.setReplies(object.optInt("replies"));
                        reply.setViews(object.optInt("views"));
                        reply.setSubject(object.optString("subject"));
                        reply.setName(object.optString("name"));
                        reply.setPid(object.optInt("pid"));
                        reply.setDateline(object.optString("dateline"));
                        reply.setTid(object.optInt("tid"));
                        replyList.add(reply);

                    }
                    hubReplyAdapter.setSubjects(replyList);
                }
            } catch (JSONException e) {
                AppContext.toastBadJson();
            }

            pullToRefreshListView.onRefreshComplete();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            AppContext.toastBadInternet();
            pullToRefreshListView.onRefreshComplete();
        }
    });
}