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, int defaultValue) 

Source Link

Document

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

Usage

From source file:com.polyvi.xface.extension.security.XSecurityExt.java

/**
 * //w w  w  . j  av  a2  s  .c o m
 *
 * @param sKey
 *            
 * @param sourceData
 *            ??
 * @param options
 *            ?
 * @return ??
 */
private String encrypt(String sKey, String sourceData, JSONObject options)
        throws XCryptionException, XCryptionException {
    if (XStringUtils.isEmptyString(sKey)) {
        XLog.e(CLASS_NAME, KEY_EMPTY_ERROR);
        throw new XCryptionException(KEY_EMPTY_ERROR);
    }
    int cryptAlgorithm = DES_ALOGRITHEM;
    int encodeDataType = ENCODE_TYPE_STRING;
    int encodeKeyType = ENCODE_TYPE_STRING;
    if (options != null) {
        cryptAlgorithm = options.optInt(KEY_CRYPT_ALGORITHM, DES_ALOGRITHEM);
        encodeDataType = options.optInt(KEY_ENCODE_DATA_TYPE, ENCODE_TYPE_BASE64);
        encodeKeyType = options.optInt(KEY_ENCODE_KEY_TYPE, ENCODE_TYPE_STRING);
    }
    byte[] keyBytes = null;
    keyBytes = getBytesEncode(encodeKeyType, sKey);
    switch (cryptAlgorithm) {
    case TRIPLE_DES_ALOGRITHEM:
        switch (encodeDataType) {
        case ENCODE_TYPE_HEX:
            return XStringUtils.hexEncode(mCryptor.encryptBytesFor3DES(sourceData.getBytes(), keyBytes));
        default:
            return XBase64.encodeToString((mCryptor.encryptBytesFor3DES(sourceData.getBytes(), keyBytes)),
                    XBase64.NO_WRAP);
        }
    case RSA_ALOGRITHEM:
        switch (encodeDataType) {
        case ENCODE_TYPE_HEX:
            return XStringUtils.hexEncode(mCryptor.encryptRSA(sourceData.getBytes(), keyBytes));
        default:
            return XBase64.encodeToString((mCryptor.encryptRSA(sourceData.getBytes(), keyBytes)),
                    XBase64.NO_WRAP);
        }
    default:
        switch (encodeDataType) {
        case ENCODE_TYPE_HEX:
            return XStringUtils.hexEncode(mCryptor.encryptBytesForDES(sourceData.getBytes(), keyBytes));
        default:
            return XBase64.encodeToString((mCryptor.encryptBytesForDES(sourceData.getBytes(), keyBytes)),
                    XBase64.NO_WRAP);
        }
    }
}

From source file:com.polyvi.xface.extension.security.XSecurityExt.java

/**
 * //from   w  w w  .ja v  a  2 s  .c  o m
 *
 * @param sKey
 *            
 * @param sourceData
 *            ??
 * @param options
 *            ?
 * @return ??
 */
private String decrypt(String sKey, String sourceData, JSONObject options) throws XCryptionException {
    if (XStringUtils.isEmptyString(sKey)) {
        XLog.e(CLASS_NAME, KEY_EMPTY_ERROR);
        throw new XCryptionException(KEY_EMPTY_ERROR);
    }
    int cryptAlgorithm = DES_ALOGRITHEM;
    int encodeDataType = ENCODE_TYPE_STRING;
    int encodeKeyType = ENCODE_TYPE_STRING;
    if (options != null) {
        cryptAlgorithm = options.optInt(KEY_CRYPT_ALGORITHM, DES_ALOGRITHEM);
        encodeDataType = options.optInt(KEY_ENCODE_DATA_TYPE, ENCODE_TYPE_STRING);
        encodeKeyType = options.optInt(KEY_ENCODE_KEY_TYPE, ENCODE_TYPE_STRING);
    }
    byte[] keyBytes = null;
    keyBytes = getBytesEncode(encodeKeyType, sKey);
    switch (cryptAlgorithm) {
    case TRIPLE_DES_ALOGRITHEM:
        switch (encodeDataType) {
        case ENCODE_TYPE_HEX:
            return new String(mCryptor.decryptBytesFor3DES(XStringUtils.hexDecode(sourceData), keyBytes));
        default:
            return new String(
                    mCryptor.decryptBytesFor3DES(XBase64.decode(sourceData, XBase64.NO_WRAP), keyBytes));
        }
    case RSA_ALOGRITHEM:
        switch (encodeDataType) {
        case ENCODE_TYPE_HEX:
            return new String(mCryptor.decryptRSA(XStringUtils.hexDecode(sourceData), keyBytes));
        default:
            return new String(mCryptor.decryptRSA(XBase64.decode(sourceData, XBase64.NO_WRAP), keyBytes));
        }
    default:
        switch (encodeDataType) {
        case ENCODE_TYPE_HEX:
            return new String(mCryptor.decryptBytesForDES(XStringUtils.hexDecode(sourceData), keyBytes));
        default:
            return new String(
                    mCryptor.decryptBytesForDES(XBase64.decode(sourceData, XBase64.NO_WRAP), keyBytes));
        }
    }
}

From source file:com.phelps.liteweibo.model.weibo.User.java

public static User parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*  w  w  w.  j a v a 2s. c o  m*/

    User user = new User();
    user.id = jsonObject.optString("id", "");
    user.idstr = jsonObject.optString("idstr", "");
    user.screen_name = jsonObject.optString("screen_name", "");
    user.name = jsonObject.optString("name", "");
    user.province = jsonObject.optInt("province", -1);
    user.city = jsonObject.optInt("city", -1);
    user.location = jsonObject.optString("location", "");
    user.description = jsonObject.optString("description", "");
    user.url = jsonObject.optString("url", "");
    user.profile_image_url = jsonObject.optString("profile_image_url", "");
    user.profile_url = jsonObject.optString("profile_url", "");
    user.domain = jsonObject.optString("domain", "");
    user.weihao = jsonObject.optString("weihao", "");
    user.gender = jsonObject.optString("gender", "");
    user.followers_count = jsonObject.optInt("followers_count", 0);
    user.friends_count = jsonObject.optInt("friends_count", 0);
    user.statuses_count = jsonObject.optInt("statuses_count", 0);
    user.favourites_count = jsonObject.optInt("favourites_count", 0);
    user.created_at = jsonObject.optString("created_at", "");
    user.following = jsonObject.optBoolean("following", false);
    user.allow_all_act_msg = jsonObject.optBoolean("allow_all_act_msg", false);
    user.geo_enabled = jsonObject.optBoolean("geo_enabled", false);
    user.verified = jsonObject.optBoolean("verified", false);
    user.verified_type = jsonObject.optInt("verified_type", -1);
    user.remark = jsonObject.optString("remark", "");
    //user.status             = jsonObject.optString("status", ""); // XXX: NO Need ?
    user.allow_all_comment = jsonObject.optBoolean("allow_all_comment", true);
    user.avatar_large = jsonObject.optString("avatar_large", "");
    user.avatar_hd = jsonObject.optString("avatar_hd", "");
    user.verified_reason = jsonObject.optString("verified_reason", "");
    user.follow_me = jsonObject.optBoolean("follow_me", false);
    user.online_status = jsonObject.optInt("online_status", 0);
    user.bi_followers_count = jsonObject.optInt("bi_followers_count", 0);
    user.lang = jsonObject.optString("lang", "");

    // ???OpenAPI ??
    user.star = jsonObject.optString("star", "");
    user.mbtype = jsonObject.optString("mbtype", "");
    user.mbrank = jsonObject.optString("mbrank", "");
    user.block_word = jsonObject.optString("block_word", "");

    return user;
}

From source file:com.tonikorin.cordova.plugin.LocationProvider.LocationService.java

private void handleLocationQuery(JSONObject messageIn, String time) throws JSONException, IOException {
    Log.d(TAG, "Handle location query...");
    String ownName = config.optString("member", "");
    JSONObject teams = config.optJSONObject("teams");
    String teamName;//from   ww  w  . j  a  v  a 2 s .  c  o  m
    String teamPassword;
    String teamHost;
    JSONObject team = null;
    if (teams != null)
        team = teams.optJSONObject(messageIn.optString("teamId"));
    if (team != null) {
        teamName = team.optString("name", "");
        teamPassword = team.optString("password", "");
        ownName = team.optString("member", ownName);
        teamHost = team.optString("host", "");
    } else
        return; // => URI hanging in PostServer
    String msgType = messageIn.optString("messageType", LOCATE);
    // Create Messaging Server interface
    String messageUrl = config.optString("messageUrl", "").replace("{host}", teamHost);
    MessageServer msgServer = new MessageServer(ownName, teamName, teamPassword, messageUrl);
    if (messageIn.optString("memberName").equals(ownName)) {
        updateLocateHistory(messageIn, true, msgType, time);
        msgServer.post(RESERVED);
        SystemClock.sleep(5000);// 5 sec delay
        String pushUrl = config.optString("pushUrl", "").replace("{host}", teamHost);
        msgServer.updatePushToken(ownName, teamName, config.optString("token", ""), pushUrl);
        return;
    }
    // Read extra team configuration (e.g. icon and schedule)
    TeamConfig cTeam = new TeamConfig(config, teamName);
    // Store details about location query
    updateLocateHistory(messageIn, cTeam.isBlocked(), msgType, time);
    if (cTeam.isBlocked())
        msgServer.addBlockedField();
    msgServer.post(ALIVE);
    if (cTeam.isBlocked() || CHAT.equals(msgType))
        return; // skip giving your location
    try {
        //Log.d(TAG, "myContext: " + myContext.getPackageName());
        new MyLocation(myContext, myLocationResult, messageIn.optInt("accuracy", 50),
                config.optInt("timeout", 60)).start();
        JSONObject location = myLocationResult.getJsonLocation();
        //Log.d(TAG, "Background position accuracy: " + location.optInt("accuracy"));
        if (cTeam.getIcon() != null)
            msgServer.addIconField(cTeam.getIcon());
        msgServer.post(POSITION, location.toString());
    } catch (Exception e) {
        Log.e(TAG, "LocationProvider exception ", e);
        msgServer.post(FAILURE, e.getMessage());
    }
    Log.d(TAG, "Handle location query...completed!");
}

From source file:ezy.boost.update.UpdateInfo.java

private static UpdateInfo parse(JSONObject o) {
    UpdateInfo info = new UpdateInfo();
    if (o == null) {
        return info;
    }/*from ww w  .  j  a  va2  s  .c o  m*/
    info.hasUpdate = o.optBoolean("hasUpdate", false);
    if (!info.hasUpdate) {
        return info;
    }
    info.isSilent = o.optBoolean("isSilent", false);
    info.isForce = o.optBoolean("isForce", false);
    info.isAutoInstall = o.optBoolean("isAutoInstall", !info.isSilent);
    info.isIgnorable = o.optBoolean("isIgnorable", true);
    info.isPatch = o.optBoolean("isPatch", false);

    info.versionCode = o.optInt("versionCode", 0);
    info.versionName = o.optString("versionName");
    info.updateContent = o.optString("updateContent");

    info.url = o.optString("url");
    info.md5 = o.optString("md5");
    info.size = o.optLong("size", 0);

    if (!info.isPatch) {
        return info;
    }
    info.patchUrl = o.optString("patchUrl");
    info.patchMd5 = o.optString("patchMd5");
    info.patchSize = o.optLong("patchSize", 0);
    return info;
}

From source file:com.example.wcl.test_weiboshare.StatusList.java

public static StatusList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/* w  w w .  j a  v a 2 s.c om*/

    StatusList statuses = new StatusList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        statuses.hasvisible = jsonObject.optBoolean("hasvisible", false);
        statuses.previous_cursor = jsonObject.optString("previous_cursor", "0");
        statuses.next_cursor = jsonObject.optString("next_cursor", "0");
        statuses.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("statuses");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            statuses.statusList = new ArrayList<Status>(length);
            for (int ix = 0; ix < length; ix++) {
                statuses.statusList.add(Status.parse(jsonArray.getJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return statuses;
}

From source file:com.phelps.liteweibo.model.weibo.Tag.java

public static Tag parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//from  w  w  w  .j a va2s . c  om

    Tag tag = new Tag();
    tag.id = jsonObject.optInt("id", 0);
    tag.tag = jsonObject.optString("tag", "");

    return tag;
}

From source file:com.external.androidquery.service.MarketService.java

protected void callback(String url, JSONObject jo, AjaxStatus status) {

    if (jo == null)
        return;/* w ww . j  av  a2 s . c  o  m*/

    String latestVer = jo.optString("version", "0");
    int latestCode = jo.optInt("code", 0);

    AQUtility.debug("version", getVersion() + "->" + latestVer + ":" + getVersionCode() + "->" + latestCode);
    AQUtility.debug("outdated", outdated(latestVer, latestCode));

    if (force || outdated(latestVer, latestCode)) {
        showUpdateDialog(jo);
    }

}

From source file:org.eclipse.orion.server.cf.handlers.v1.AppsHandlerV1.java

@Override
protected CFJob handlePut(App resource, HttpServletRequest request, HttpServletResponse response,
        final String pathString) {
    final JSONObject targetJSON2 = extractJSONData(
            IOUtilities.getQueryParameter(request, CFProtocolConstants.KEY_TARGET));

    IPath path = pathString != null ? new Path(pathString) : new Path("");
    final String appGuid = path.segment(0);
    boolean addRoute = "routes".equals(path.segment(1));
    final String routeGuid = addRoute ? path.segment(2) : null;

    if (addRoute)
        return new CFJob(request, false) {
            @Override// ww w  . j a  va  2  s.  co  m
            protected IStatus performJob() {
                try {
                    ComputeTargetCommand computeTarget = new ComputeTargetCommand(this.userId, targetJSON2);
                    IStatus status = computeTarget.doIt();
                    if (!status.isOK())
                        return status;
                    Target target = computeTarget.getTarget();

                    GetAppByGuidCommand getAppByGuid = new GetAppByGuidCommand(target.getCloud(), appGuid);
                    IStatus getAppByGuidStatus = getAppByGuid.doIt();
                    if (!getAppByGuidStatus.isOK())
                        return getAppByGuidStatus;
                    App app = getAppByGuid.getApp();

                    GetRouteByGuidCommand getRouteByGuid = new GetRouteByGuidCommand(target.getCloud(),
                            routeGuid);
                    IStatus getRouteByGuidStatus = getRouteByGuid.doIt();
                    if (!getRouteByGuidStatus.isOK())
                        return getRouteByGuidStatus;
                    Route route = getRouteByGuid.getRoute();

                    MapRouteCommand unmapRoute = new MapRouteCommand(target, app, route.getGuid());
                    return unmapRoute.doIt();
                } catch (Exception e) {
                    String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                    ServerStatus status = new ServerStatus(IStatus.ERROR,
                            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                    logger.error(msg, e);
                    return status;
                }
            }
        };

    final JSONObject jsonData = extractJSONData(request);
    final JSONObject targetJSON = jsonData.optJSONObject(CFProtocolConstants.KEY_TARGET);

    final String state = jsonData.optString(CFProtocolConstants.KEY_STATE, null);
    final String appName = jsonData.optString(CFProtocolConstants.KEY_NAME, null);
    final String contentLocation = ServletResourceHandler.toOrionLocation(request,
            jsonData.optString(CFProtocolConstants.KEY_CONTENT_LOCATION, null));

    /* default application startup is one minute */
    int userTimeout = jsonData.optInt(CFProtocolConstants.KEY_TIMEOUT, 60);
    final int timeout = (userTimeout > 0) ? userTimeout : 0;

    /* TODO: The force shouldn't be always with us */
    final boolean force = jsonData.optBoolean(CFProtocolConstants.KEY_FORCE, true);

    return new CFJob(request, false) {
        @Override
        protected IStatus performJob() {
            try {
                ComputeTargetCommand computeTarget = new ComputeTargetCommand(this.userId, targetJSON);
                IStatus status = computeTarget.doIt();
                if (!status.isOK())
                    return status;
                Target target = computeTarget.getTarget();

                /* parse the application manifest */
                String manifestAppName = null;
                ParseManifestCommand parseManifestCommand = null;
                if (contentLocation != null) {
                    parseManifestCommand = new ParseManifestCommand(target, this.userId, contentLocation);
                    status = parseManifestCommand.doIt();
                    if (!status.isOK())
                        return status;

                    /* get the manifest name */
                    ManifestParseTree manifest = parseManifestCommand.getManifest();
                    if (manifest != null) {
                        ManifestParseTree applications = manifest.get(CFProtocolConstants.V2_KEY_APPLICATIONS);
                        if (applications.getChildren().size() > 0)
                            manifestAppName = applications.get(0).get(CFProtocolConstants.V2_KEY_NAME)
                                    .getValue();
                    }
                }

                GetAppCommand getAppCommand = new GetAppCommand(target,
                        appName != null ? appName : manifestAppName);
                status = getAppCommand.doIt();
                App app = getAppCommand.getApp();

                if (CFProtocolConstants.KEY_STARTED.equals(state)) {
                    if (!status.isOK())
                        return status;
                    return new StartAppCommand(target, app, timeout).doIt();
                } else if (CFProtocolConstants.KEY_STOPPED.equals(state)) {
                    if (!status.isOK())
                        return status;
                    return new StopAppCommand(target, app).doIt();
                } else {
                    if (parseManifestCommand == null) {
                        String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                        status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                msg, null);
                        logger.error(msg);
                        return status;
                    }
                }

                // push new application
                if (app == null)
                    app = new App();

                app.setName(appName != null ? appName : manifestAppName);
                app.setManifest(parseManifestCommand.getManifest());

                status = new PushAppCommand(target, app, parseManifestCommand.getAppStore(), force).doIt();
                if (!status.isOK())
                    return status;

                // get the app again
                getAppCommand = new GetAppCommand(target, app.getName());
                getAppCommand.doIt();
                app = getAppCommand.getApp();
                app.setManifest(parseManifestCommand.getManifest());

                new StartAppCommand(target, app).doIt();

                return status;
            } catch (Exception e) {
                String msg = NLS.bind("Failed to handle request for {0}", pathString); //$NON-NLS-1$
                ServerStatus status = new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
                logger.error(msg, e);
                return status;
            }
        }
    };
}

From source file:com.google.blockly.model.FieldAngle.java

public static FieldAngle fromJson(JSONObject json) throws BlockLoadingException {
    String name = json.optString("name");
    if (TextUtils.isEmpty(name)) {
        throw new BlockLoadingException("field_angle \"name\" attribute must not be empty.");
    }// w ww  . jav  a  2 s .  co  m

    return new FieldAngle(name, json.optInt("angle", 90));
}