Example usage for org.json JSONObject isNull

List of usage examples for org.json JSONObject isNull

Introduction

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

Prototype

public boolean isNull(String key) 

Source Link

Document

Determine if the value associated with the key is null or if there is no value.

Usage

From source file:fr.pasteque.pos.customers.CustomerInfoExt.java

public CustomerInfoExt(JSONObject o) {
    super(null);/*from ww w  .j a  v a 2s  . co  m*/
    if (!o.isNull("id")) {
        this.id = o.getString("id");
    }
    if (!o.isNull("number")) {
        this.taxid = o.getString("number");
    }
    if (!o.isNull("dispName")) {
        this.name = o.getString("dispName");
    }
    if (!o.isNull("key")) {
        this.searchkey = o.getString("key");
    }
    if (!o.isNull("custTaxId")) {
        this.taxcustomerid = o.getString("custTaxId");
    }
    if (!o.isNull("discountProfileId")) {
        this.discountProfileId = o.getInt("discountProfileId");
    }
    if (!o.isNull("notes")) {
        this.notes = o.getString("notes");
    }
    this.visible = o.getBoolean("visible");
    if (!o.isNull("card")) {
        this.card = o.getString("card");
    }
    if (!o.isNull("maxDebt")) {
        this.maxdebt = o.getDouble("maxDebt");
    }
    if (!o.isNull("debtDate")) {
        this.curdate = DateUtils.readSecTimestamp(o.getLong("debtDate"));
    }
    if (!o.isNull("currDebt")) {
        this.curdebt = o.getDouble("currDebt");
    }
    this.prepaid = o.getDouble("prepaid");
    if (!o.isNull("firstName")) {
        this.firstname = o.getString("firstName");
    }
    if (!o.isNull("lastName")) {
        this.lastname = o.getString("lastName");
    }
    if (!o.isNull("email")) {
        this.email = o.getString("email");
    }
    if (!o.isNull("phone1")) {
        this.phone = o.getString("phone1");
    }
    if (!o.isNull("phone2")) {
        this.phone2 = o.getString("phone2");
    }
    if (!o.isNull("fax")) {
        this.fax = o.getString("fax");
    }
    if (!o.isNull("addr1")) {
        this.address = o.getString("addr1");
    }
    if (!o.isNull("addr2")) {
        this.address2 = o.getString("addr2");
    }
    if (!o.isNull("zipCode")) {
        this.postal = o.getString("zipCode");
    }
    if (!o.isNull("city")) {
        this.city = o.getString("city");
    }
    if (!o.isNull("region")) {
        this.region = o.getString("region");
    }
    if (!o.isNull("country")) {
        this.country = o.getString("country");
    }
}

From source file:com.imaginary.home.cloud.device.PoweredDevice.java

static public void mapPoweredDevice(@Nonnull ControllerRelay relay, @Nonnull JSONObject json,
        @Nonnull Map<String, Object> state) throws JSONException {
    mapDevice(relay, json, state);//from www. j a  v a  2 s .c o m
    state.put("deviceType", "powered");
    state.put("on", json.has("on") && !json.isNull("on") && json.getBoolean("on"));
}

From source file:org.official.json.CookieList.java

/**
 * Convert a JSONObject into a cookie list. A cookie list is a sequence
 * of name/value pairs. The names are separated from the values by '='.
 * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
 * in the names and values are replaced by "%hh".
 * @param jo A JSONObject//from   ww w  . j  a v a2  s.c  o  m
 * @return A cookie list string
 * @throws JSONException
 */
public static String toString(JSONObject jo) throws JSONException {
    boolean b = false;
    Iterator<String> keys = jo.keys();
    String string;
    StringBuilder sb = new StringBuilder();
    while (keys.hasNext()) {
        string = keys.next();
        if (!jo.isNull(string)) {
            if (b) {
                sb.append(';');
            }
            sb.append(Cookie.escape(string));
            sb.append("=");
            sb.append(Cookie.escape(jo.getString(string)));
            b = true;
        }
    }
    return sb.toString();
}

From source file:org.wso2.emm.agent.services.PolicyTester.java

@SuppressWarnings("static-access")
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public boolean testPolicy(String code, String data) {
    if (code.equals(CommonUtilities.OPERATION_CLEAR_PASSWORD)) {
        ComponentName demoDeviceAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class);
        JSONObject jobj = new JSONObject();
        // data = intent.getStringExtra("data");
        try {//  www . j a  v  a 2 s. c o m
            Map<String, String> params = new HashMap<String, String>();
            params.put("code", code);
            params.put("status", "200");

            if (IS_ENFORCE) {
                devicePolicyManager.setPasswordQuality(demoDeviceAdmin,
                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
                devicePolicyManager.resetPassword("", DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
                devicePolicyManager.lockNow();
                devicePolicyManager.setPasswordQuality(demoDeviceAdmin,
                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
                jobj.put("status", true);
            } else {
                if (devicePolicyManager.getPasswordQuality(
                        demoDeviceAdmin) != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
                    jobj.put("status", false);
                } else {
                    jobj.put("status", true);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            jobj.put("code", code);

            //finalArray.put(jobj);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    } else if (code.equals(CommonUtilities.OPERATION_WIFI)) {
        boolean wifistatus = false;
        JSONObject jobjc = new JSONObject();
        WiFiConfig config = new WiFiConfig(context);
        // data = intent.getStringExtra("data");
        JSONParser jp = new JSONParser();
        try {
            JSONObject jobj = new JSONObject(data);
            if (!jobj.isNull("ssid")) {
                ssid = (String) jobj.get("ssid");
            }
            if (!jobj.isNull("password")) {
                password = (String) jobj.get("password");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String, String> inparams = new HashMap<String, String>();
        inparams.put("code", code);
        if (IS_ENFORCE) {
            try {
                wifistatus = config.saveWEPConfig(ssid, password);
                jobjc.put("status", true);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            if (config.readWEPConfig(ssid)) {
                jobjc.put("status", true);
            } else {
                jobjc.put("status", false);
                if (usermessage != null && usermessage != "") {
                    usermessage += "\nYou are not using company WIFI account, please change your WIFI configuration \n";
                } else {
                    usermessage += "You are not using company WIFI account, please change your WIFI configuration \n";
                }

            }
            jobjc.put("code", code);

            finalArray.put(jobjc);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    } else if (code.equals(CommonUtilities.OPERATION_DISABLE_CAMERA)) {
        ComponentName cameraAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class);
        boolean camFunc = false;
        // data = intent.getStringExtra("data");
        JSONParser jp = new JSONParser();
        try {
            JSONObject jobj = new JSONObject(data);

            if (!jobj.isNull("function") && jobj.get("function").toString().equalsIgnoreCase("enable")) {
                camFunc = false;
            } else if (!jobj.isNull("function")
                    && jobj.get("function").toString().equalsIgnoreCase("disable")) {
                camFunc = true;
            } else if (!jobj.isNull("function")) {
                camFunc = Boolean.parseBoolean(jobj.get("function").toString());
            }

            Map<String, String> params = new HashMap<String, String>();
            params.put("code", code);
            params.put("status", "200");
            String cammode = "Disabled";
            if (camFunc) {
                cammode = "Disabled";
            } else {
                cammode = "Enabled";
            }

            if (IS_ENFORCE && (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)) {
                devicePolicyManager.setCameraDisabled(cameraAdmin, camFunc);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jobj = new JSONObject();
        try {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                if (!camFunc) {
                    if (!devicePolicyManager.getCameraDisabled(cameraAdmin)) {
                        jobj.put("status", true);
                    } else {
                        jobj.put("status", false);
                    }
                } else {
                    if (devicePolicyManager.getCameraDisabled(cameraAdmin)) {
                        jobj.put("status", true);
                    } else {
                        jobj.put("status", false);
                        /*if(usermessage!=null && usermessage!=""){
                           usermessage+="\nYour camera should be deactivated according to the policy, please deactivate your camera\n";
                        }else{
                           usermessage+="Your camera should be deactivated according to the policy, please deactivate your camera \n";
                        }*/
                    }
                }
            } else {
                jobj.put("status", false);
            }
            jobj.put("code", code);

            finalArray.put(jobj);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    } else if (code.equals(CommonUtilities.OPERATION_ENCRYPT_STORAGE)) {
        boolean encryptFunc = true;
        String pass = "";

        JSONParser jp = new JSONParser();
        try {
            JSONObject jobj = new JSONObject(data);

            if (!jobj.isNull("function") && jobj.get("function").toString().equalsIgnoreCase("encrypt")) {
                encryptFunc = true;
            } else if (!jobj.isNull("function")
                    && jobj.get("function").toString().equalsIgnoreCase("decrypt")) {
                encryptFunc = false;
            } else if (!jobj.isNull("function")) {
                encryptFunc = Boolean.parseBoolean(jobj.get("function").toString());
            }

            ComponentName admin = new ComponentName(context, WSO2DeviceAdminReceiver.class);
            Map<String, String> params = new HashMap<String, String>();
            params.put("code", code);

            if (IS_ENFORCE) {
                if (encryptFunc && devicePolicyManager
                        .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) {
                    if (devicePolicyManager
                            .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_INACTIVE) {
                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            devicePolicyManager.setStorageEncryption(admin, encryptFunc);
                            Intent intent = new Intent(DevicePolicyManager.ACTION_START_ENCRYPTION);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intent);
                        }
                    }
                } else if (!encryptFunc && devicePolicyManager
                        .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) {
                    if (devicePolicyManager
                            .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVE
                            || devicePolicyManager
                                    .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVATING) {
                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            devicePolicyManager.setStorageEncryption(admin, encryptFunc);
                        }
                    }
                }
            }
            if (devicePolicyManager
                    .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) {
                params.put("status", "200");
            } else {
                params.put("status", "400");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jobj = new JSONObject();
        try {
            jobj.put("code", code);
            if (encryptFunc) {
                if (devicePolicyManager
                        .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED
                        && devicePolicyManager
                                .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_INACTIVE) {
                    jobj.put("status", true);
                } else {
                    jobj.put("status", false);
                    if (usermessage != null && usermessage != "") {
                        usermessage += "\nYour device should be encrypted according to the policy, please enable device encryption through device settings\n";
                    } else {
                        usermessage += "Your device should be encrypted according to the policy, please enable device encryption through device settings \n";
                    }
                }
            } else {
                if (devicePolicyManager
                        .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED
                        || devicePolicyManager
                                .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_INACTIVE) {
                    jobj.put("status", true);
                } else {
                    jobj.put("status", false);
                }
            }
            finalArray.put(jobj);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else if (code.equals(CommonUtilities.OPERATION_MUTE)) {

        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("code", code);
            params.put("status", "200");
            if (IS_ENFORCE) {
                muteDevice();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jobj = new JSONObject();
        try {
            jobj.put("code", code);
            if (isMuted()) {
                jobj.put("status", true);
            } else {
                jobj.put("status", false);
                if (usermessage != null && usermessage != "") {
                    usermessage += "\nYour phone should be muted according to the policy, please mute your phone \n";
                } else {
                    usermessage += "Your phone should be muted according to the policy, please mute your phone \n";
                }
            }
            finalArray.put(jobj);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    } else if (code.equals(CommonUtilities.OPERATION_PASSWORD_POLICY)) {

        ComponentName demoDeviceAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class);
        JSONObject jobjx = new JSONObject();
        int attempts, length, history, specialChars;
        String alphanumeric, complex;
        boolean b_alphanumeric = false, b_complex = false, is_comply = true, comply_fac1 = true,
                comply_fac2 = true, comply_fac3 = true, comply_fac4 = true, comply_fac5 = true,
                comply_fac6 = true, comply_fac7 = true;
        long timout;
        Map<String, String> inparams = new HashMap<String, String>();
        // data = intent.getStringExtra("data");
        JSONParser jp = new JSONParser();
        try {
            JSONObject jobjpass = new JSONObject();
            jobjpass.put("code", CommonUtilities.OPERATION_CHANGE_LOCK_CODE);

            if (devicePolicyManager.isActivePasswordSufficient()) {
                is_comply = true;
                //finalArray.put(jobjpass);
            } else {
                is_comply = false;
            }

            JSONObject jobj = new JSONObject(data);
            if (!jobj.isNull("maxFailedAttempts") && jobj.get("maxFailedAttempts") != null) {
                attempts = Integer.parseInt((String) jobj.get("maxFailedAttempts"));
                if (IS_ENFORCE) {
                    devicePolicyManager.setMaximumFailedPasswordsForWipe(demoDeviceAdmin, attempts);
                    comply_fac1 = true;
                } else {
                    if (devicePolicyManager.getMaximumFailedPasswordsForWipe(demoDeviceAdmin) != attempts) {
                        comply_fac1 = false;
                    } else {
                        comply_fac1 = true;
                    }
                }
            }

            if (!jobj.isNull("minLength") && jobj.get("minLength") != null) {
                length = Integer.parseInt((String) jobj.get("minLength"));
                if (IS_ENFORCE) {
                    devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, length);
                    comply_fac2 = true;
                } else {
                    if (devicePolicyManager.getPasswordMinimumLength(demoDeviceAdmin) != length) {
                        comply_fac2 = false;
                    } else {
                        comply_fac2 = true;
                    }
                }
            }

            if (!jobj.isNull("pinHistory") && jobj.get("pinHistory") != null) {
                history = Integer.parseInt((String) jobj.get("pinHistory"));
                if (IS_ENFORCE) {
                    devicePolicyManager.setPasswordHistoryLength(demoDeviceAdmin, history);
                    comply_fac3 = true;
                } else {
                    if (devicePolicyManager.getPasswordHistoryLength(demoDeviceAdmin) != history) {
                        comply_fac3 = false;
                    } else {
                        comply_fac3 = true;
                    }
                }
            }

            if (!jobj.isNull("minComplexChars") && jobj.get("minComplexChars") != null) {
                specialChars = Integer.parseInt((String) jobj.get("minComplexChars"));
                if (IS_ENFORCE) {
                    devicePolicyManager.setPasswordMinimumSymbols(demoDeviceAdmin, specialChars);
                    comply_fac4 = true;
                } else {
                    if (devicePolicyManager.getPasswordMinimumSymbols(demoDeviceAdmin) != specialChars) {
                        comply_fac4 = false;
                    } else {
                        comply_fac4 = true;
                    }
                }
            }

            if (!jobj.isNull("requireAlphanumeric") && jobj.get("requireAlphanumeric") != null) {

                if (jobj.get("requireAlphanumeric") instanceof String) {
                    alphanumeric = (String) jobj.get("requireAlphanumeric").toString();
                    if (alphanumeric.equals("true")) {
                        b_alphanumeric = true;
                    } else {
                        b_alphanumeric = false;
                    }
                } else if (jobj.get("requireAlphanumeric") instanceof Boolean) {
                    b_alphanumeric = jobj.getBoolean("requireAlphanumeric");
                }
                if (b_alphanumeric) {
                    if (IS_ENFORCE) {
                        devicePolicyManager.setPasswordQuality(demoDeviceAdmin,
                                DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
                        comply_fac5 = true;
                    } else {
                        if (devicePolicyManager.getPasswordQuality(
                                demoDeviceAdmin) != DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC) {
                            comply_fac5 = false;
                        } else {
                            comply_fac5 = true;
                        }
                    }
                } else {
                    if (devicePolicyManager.getPasswordQuality(
                            demoDeviceAdmin) == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC) {
                        comply_fac5 = false;
                    } else {
                        comply_fac5 = true;
                    }
                }
            }

            if (!jobj.isNull("allowSimple") && jobj.get("allowSimple") != null) {

                if (jobj.get("allowSimple") instanceof String) {
                    complex = (String) jobj.get("allowSimple").toString();
                    if (complex.equals("true")) {
                        b_complex = true;
                    } else {
                        b_complex = false;
                    }
                } else if (jobj.get("allowSimple") instanceof Boolean) {
                    b_complex = jobj.getBoolean("allowSimple");
                }

                if (!b_complex) {
                    if (IS_ENFORCE) {
                        devicePolicyManager.setPasswordQuality(demoDeviceAdmin,
                                DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
                        comply_fac6 = true;
                    } else {
                        if (devicePolicyManager.getPasswordQuality(
                                demoDeviceAdmin) != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
                            comply_fac6 = false;
                        } else {
                            comply_fac6 = true;
                        }
                    }
                } else {
                    if (devicePolicyManager.getPasswordQuality(
                            demoDeviceAdmin) == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
                        comply_fac6 = false;
                    } else {
                        comply_fac6 = true;
                    }
                }
            }

            if (!jobj.isNull("maxPINAgeInDays") && jobj.get("maxPINAgeInDays") != null) {
                int daysOfExp = Integer.parseInt((String) jobj.get("maxPINAgeInDays"));
                timout = (long) (daysOfExp * 24 * 60 * 60 * 1000);
                if (IS_ENFORCE) {
                    devicePolicyManager.setPasswordExpirationTimeout(demoDeviceAdmin, timout);
                    comply_fac7 = true;
                } else {
                    if (devicePolicyManager.getPasswordExpirationTimeout(demoDeviceAdmin) != timout) {
                        comply_fac7 = false;
                    } else {
                        comply_fac7 = true;
                    }
                }
            }

            if (!is_comply || !comply_fac1 || !comply_fac2 || !comply_fac3 || !comply_fac4 || !comply_fac5
                    || !comply_fac6 || !comply_fac7) {
                jobjx.put("status", false);
                if (usermessage != null && usermessage != "") {
                    usermessage += "\nYour screen lock password doesn't meet current policy requirement. Please reset your passcode \n";
                } else {
                    usermessage += "Your screen lock password doesn't meet current policy requirement. Please reset your passcode \n";
                }
            } else {
                jobjx.put("status", true);
            }

            inparams.put("code", code);
            inparams.put("status", "200");

        } catch (Exception e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

        try {
            jobjx.put("code", code);

            finalArray.put(jobjx);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    } else if (code.equals(CommonUtilities.OPERATION_BLACKLIST_APPS)) {
        ArrayList<PInfo> apps = appList.getInstalledApps(false); /*
                                                                 * false =
                                                                 * no system
                                                                 * packages
                                                                 */
        JSONArray jsonArray = new JSONArray();
        int max = apps.size();

        Boolean flag = true;

        try {
            JSONObject appObj = new JSONObject(data);
            String identity = (String) appObj.get("identity");
            for (int j = 0; j < max; j++) {
                JSONObject jsonObj = new JSONObject();
                try {
                    jsonObj.put("name", apps.get(j).appname);
                    jsonObj.put("package", apps.get(j).pname);
                    if (identity.trim().equals(apps.get(j).pname)) {
                        jsonObj.put("notviolated", false);
                        flag = false;
                        jsonObj.put("package", apps.get(j).pname);
                        if (apps.get(j).appname != null) {
                            appcount++;
                            apz = appcount + ". " + apps.get(j).appname;
                        }

                        if (apz != null || !apz.trim().equals("")) {
                            if (usermessage != null && usermessage != "") {
                                if (appcount > 1) {
                                    usermessage += "\n" + apz;
                                } else {
                                    usermessage += "\nFollowing apps are blacklisted by your MDM Admin, please remove them \n\n"
                                            + apz;
                                }
                            } else {
                                if (appcount > 1) {
                                    usermessage += "\n" + apz;
                                } else {
                                    usermessage += "Following apps are blacklisted by your MDM Admin, please remove them \n\n"
                                            + apz;
                                }

                            }
                        }

                    } else {
                        jsonObj.put("notviolated", true);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                jsonArray.put(jsonObj);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        /*
         * for(int i=0;i<apps.length;i++){ jsonArray.add(apps[i]); }
         */
        JSONObject appsObj = new JSONObject();
        try {
            //appsObj.put("data", jsonArray);
            appsObj.put("status", flag);
            appsObj.put("code", code);
            finalArray.put(appsObj);

        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }

    return true;
}

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

/**
 * Parses alert details found in the alert list API response
 * This structure is different than the alert detail API response
 *//*from   w w  w .j  ava  2 s.c o  m*/
@NonNull
private Alert parseAlert(JSONObject alertNode) throws JSONException {
    String id = alertNode.getString("id");

    long start = 0;
    if (!alertNode.isNull("kezd")) {
        JSONObject beginNode = alertNode.getJSONObject("kezd");
        start = beginNode.getLong("epoch");
    }

    long end = 0;
    if (!alertNode.isNull("vege")) {
        JSONObject endNode = alertNode.getJSONObject("vege");
        end = endNode.getLong("epoch");
    }

    long timestamp;
    JSONObject modifiedNode = alertNode.getJSONObject("modositva");
    timestamp = modifiedNode.getLong("epoch");

    String url = getUrl(id);

    String header = Utils.capitalizeString(alertNode.getString("elnevezes"));

    List<Route> affectedRoutes;
    JSONArray routesArray = alertNode.getJSONArray("jaratokByFajta");
    affectedRoutes = parseAffectedRoutes(routesArray);

    return new Alert(id, start, end, timestamp, url, header, null, affectedRoutes, true);
}

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

/**
 * Parses alert details found in the alert detail API response
 * This structure is different than the alert list API response
 *///from  w w w  .  j a v a 2s. c o  m
private Alert parseAlertDetail(JSONObject response) throws JSONException {
    String id = response.getString("id");

    long start = 0;
    if (!response.isNull("kezdEpoch")) {
        start = response.getLong("kezdEpoch");
    }

    long end = 0;
    if (!response.isNull("vegeEpoch")) {
        end = response.getLong("vegeEpoch");
    }

    long timestamp = 0;
    if (!response.isNull("modEpoch")) {
        timestamp = response.getLong("modEpoch");
    }

    String url = getUrl(id);

    String header;
    // The API returns a header of 3 parts separated by "|" characters. We need the last part.
    String rawHeader = response.getString("targy");
    String[] rawHeaderParts = rawHeader.split("\\|");
    header = Utils.capitalizeString(rawHeaderParts[2].trim());

    String description;
    StringBuilder descriptionBuilder = new StringBuilder();
    descriptionBuilder.append(response.getString("feed"));

    JSONArray routesArray = Utils.jsonObjectToArray(response.getJSONObject("jaratok"));
    for (int i = 0; i < routesArray.length(); i++) {
        JSONObject routeNode = routesArray.getJSONObject(i);
        JSONObject optionsNode = routeNode.getJSONObject("opciok");

        if (!optionsNode.isNull("szabad_szoveg")) {
            JSONArray routeTextArray = optionsNode.getJSONArray("szabad_szoveg");
            for (int j = 0; j < routeTextArray.length(); j++) {
                descriptionBuilder.append("<br />");
                descriptionBuilder.append(routeTextArray.getString(j));
            }
        }
    }
    description = descriptionBuilder.toString();

    List<Route> affectedRoutes;
    JSONObject routeDetailsNode = response.getJSONObject("jarat_adatok");
    Iterator<String> affectedRouteIds = response.getJSONObject("jaratok").keys();
    // Some routes in routeDetailsNode are not affected by the alert, but alternative
    // recommended routes. The real affected routes' IDs are in "jaratok"
    affectedRoutes = parseDetailedAffectedRoutes(routeDetailsNode, affectedRouteIds);

    return new Alert(id, start, end, timestamp, url, header, description, affectedRoutes, false);
}

From source file:com.nolanofra.test.lazyLoader.MainActivity.java

private ArrayList<Video> getVideos(String url) {
    ArrayList<Video> videos = new ArrayList<Video>();

    String jsonString = executeGet(url);

    JSONTokener tokener = new JSONTokener(jsonString);

    JSONObject objectMain = null;/*w  w  w. j a  va2  s  . c  o m*/

    try {
        objectMain = new JSONObject(tokener);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject data = null;
    JSONArray itemsArray = null;
    try {
        data = objectMain.getJSONObject("data");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    try {
        itemsArray = data.getJSONArray("items");

        for (int i = 0; i < itemsArray.length(); i++) {
            JSONObject videoRoot = itemsArray.getJSONObject(i);
            JSONObject video = videoRoot.getJSONObject("video");
            Video v = new Video();
            v.title = video.getString("title");
            if (!video.isNull("description"))
                v.description = video.getString("description");
            if (!video.isNull("thumbnail")) {
                JSONObject thumbnail = video.getJSONObject("thumbnail");
                v.thumbnailHQDefault = thumbnail.getString("hqDefault");
                v.thumbnailSQDefault = thumbnail.getString("sqDefault");
            }

            videos.add(v);
        }
    } catch (Exception e) {
        Log.d("error", e.getMessage());
    }

    return videos;
}

From source file:jessmchung.groupon.parsers.DealOptionsParser.java

@Override
public DealOptions parse(JSONObject json) throws JSONException {
    DealOptions obj = new DealOptions();
    if (json.has("buyUrl"))
        obj.setBuyUrl(json.getString("buyUrl"));
    if (json.has("expiresAt")) {
        try {/* w  ww.  ja  va2 s  .c o m*/
            obj.setExpiresAt(parseDate(json.getString("expiresAt")));
        } catch (ParseException ex) {
            System.out.println("Could not parse " + json.getString("expiresAt"));
        }
    }
    if (json.has("price")) {
        JSONObject price = json.getJSONObject("price");
        obj.setPrice(new PriceParser().parse(price));
    }
    if (json.has("discountPercent"))
        obj.setDiscountPercent(json.getDouble("discountPercent"));
    if (json.has("soldQuantity"))
        obj.setSoldQuantity(json.getInt("soldQuantity"));
    if (json.has("initialQuantity") && !json.isNull("initialQuantity"))
        obj.setInitialQuantity(json.getInt("initialQuantity"));
    if (json.has("externalUrl"))
        obj.setExternalUrl(json.getString("externalUrl"));
    if (json.has("minimumPurchaseQuantity"))
        obj.setMinimumPurchaseQuantity(json.getInt("minimumPurchaseQuantity"));
    if (json.has("limitedQuantity"))
        obj.setIsLimitedQuantity(json.getBoolean("isLimitedQuantity"));
    if (json.has("value")) {
        JSONObject value = json.getJSONObject("value");
        obj.setValue(new PriceParser().parse(value));
    }
    if (json.has("maximumPurchaseQuantity"))
        obj.setMaximumPurchaseQuantity(json.getInt("maximumPurchaseQuantity"));
    if (json.has("title"))
        obj.setTitle(json.getString("title"));
    if (json.has("discount")) {
        JSONObject discount = json.getJSONObject("discount");
        obj.setValue(new PriceParser().parse(discount));
    }
    if (json.has("remainingQuantity") && !json.isNull("remainingQuantity"))
        obj.setRemainingQuantity(json.getInt("remainingQuantity"));
    if (json.has("id"))
        obj.setId(json.getInt("id"));
    if (json.has("isSoldOut"))
        obj.setIsSoldOut(json.getBoolean("isSoldOut"));
    if (json.has("redemptionLocations")) {
        JSONArray locationsArray = json.getJSONArray("redemptionLocations");
        obj.setRedemptionLocations(new RedemptionLocationParser().parse(locationsArray));
    }

    return obj;
}

From source file:net.dv8tion.jda.core.handle.ReadyHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    EntityBuilder builder = api.getEntityBuilder();

    //Core/*from   ww w .  jav a 2  s .  c  o  m*/
    JSONArray guilds = content.getJSONArray("guilds");
    JSONObject selfJson = content.getJSONObject("user");

    builder.createSelfUser(selfJson);

    if (api.getAccountType() == AccountType.CLIENT && !content.isNull("user_settings")) {
        // handle user settings
        JSONObject userSettingsJson = content.getJSONObject("user_settings");
        UserSettingsImpl userSettingsObj = (UserSettingsImpl) api.asClient().getSettings();
        userSettingsObj
                // TODO: set all information and handle updates
                .setStatus(userSettingsJson.isNull("status") ? OnlineStatus.ONLINE
                        : OnlineStatus.fromKey(userSettingsJson.getString("status")));
        // update presence information unless the status is ONLINE
        if (userSettingsObj.getStatus() != OnlineStatus.ONLINE)
            ((PresenceImpl) api.getPresence()).setCacheStatus(userSettingsObj.getStatus());
    }

    //Keep a list of all guilds in incompleteGuilds that need to be setup (GuildMemberChunk / GuildSync)
    //Send all guilds to the EntityBuilder's first pass to setup caching for when GUILD_CREATE comes
    // or, for Client accounts, to start the setup process (since we already have guild info)
    //Callback points to guildSetupComplete so that when MemberChunking and GuildSync processes are done, we can
    // "check off" the completed guild from the set of guilds in incompleteGuilds.

    for (int i = 0; i < guilds.length(); i++) {
        JSONObject guild = guilds.getJSONObject(i);
        incompleteGuilds.add(guild.getLong("id"));
    }

    //We use two different for-loops here so that we cache all of the ids before sending them off to the EntityBuilder
    //  due to the checks in checkIfReadyToSendRequests and guildSetupComplete triggering too soon otherwise.
    // Specifically: incompleteGuilds.size() == acknowledgedGuilds.size() and
    //  incompleteGuilds.size() == unavailableGuilds.size() respectively.

    for (int i = 0; i < guilds.length(); i++) {
        JSONObject guild = guilds.getJSONObject(i);

        //If a Guild isn't unavailable, then it is possible that we were given all information
        // needed to fully load the guild. In this case, we provide the method `guildSetupComplete`
        // as the secondPassCallback so it can immediately be called to signify that the provided guild
        // is loaded and ready to go.
        //If a Guild is unavailable it won't have the information needed, so we pass null as the secondPassCallback
        // for now and wait for the GUILD_CREATE event to give us the required information.
        if (guild.has("unavailable") && guild.getBoolean("unavailable"))
            builder.createGuildFirstPass(guild, null);
        else
            builder.createGuildFirstPass(guild, this::guildSetupComplete);
    }

    if (guilds.length() == 0)
        guildLoadComplete(content);

    return null;
}

From source file:twitter4j.internal.json.InternalJSONFactoryImpl.java

/**
 * returns a GeoLocation instance if a "geo" element is found.
 * //  ww  w .  j a v  a  2s  .  com
 * @param json JSONObject to be parsed
 * @return GeoLocation instance
 * @throws TwitterException when coordinates is not included in geo element
 *             (should be an API side issue)
 */
/* package */
static GeoLocation createGeoLocation(final JSONObject json) throws TwitterException {
    try {
        if (!json.isNull("geo")) {
            String coordinates = json.getJSONObject("geo").getString("coordinates");
            coordinates = coordinates.substring(1, coordinates.length() - 1);
            final String[] point = InternalStringUtil.split(coordinates, ",");
            return new GeoLocation(Double.parseDouble(point[0]), Double.parseDouble(point[1]));
        }
    } catch (final JSONException jsone) {
        throw new TwitterException(jsone);
    }
    return null;
}