Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.collectionspace.chain.csp.persistence.services.TestPermissions.java

@Test
public void testPermissions() throws Exception {
    //create role
    JSONObject roledata = createRole("role.json");
    String role = roledata.getString("roleId");
    log.info(roledata.toString());/*w  ww.j  a v  a 2 s.  com*/
    assertFalse(roledata == null);

    //list permissions for role
    //cspace-services/authorization/roles/{csid}/permroles/xxx

    Storage ss;
    ss = makeServicesStorage();
    JSONObject data = ss.getPathsJSON("roles/" + role + "/permrole", null);
    String[] roleperms = (String[]) data.get("listItems");
    log.info(data.toString());

    if (roleperms.length > 0) {
        log.info("has permissions already");
    }

    //add a permission
    //get acquisition crudl

    ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
    String resourceName = "acquisition";

    JSONObject permrestrictions = new JSONObject();
    permrestrictions.put("keywords", resourceName);
    permrestrictions.put("queryString", "CRUDL");
    permrestrictions.put("queryTerm", "actGrp");

    JSONObject pdata = ss.getPathsJSON("permission", permrestrictions);
    String[] perms = (String[]) pdata.get("listItems");
    String permID = "";
    if (perms.length > 0) {
        permID = perms[0];
    } else {
        //need to create this permission type
        fail("missing permission type Acquisition CRUDL " + permrestrictions.toString());
    }

    JSONObject permdata = new JSONObject();
    permdata.put("permissionId", permID);
    permdata.put("resourceName", resourceName);
    JSONArray permarray = new JSONArray();
    permarray.put(permdata);

    JSONObject addperm = new JSONObject();
    addperm.put("permission", permarray);
    addperm.put("role", roledata);

    log.info(addperm.toString());
    //add permissions to role

    String path = ss.autocreateJSON("permrole", addperm, null);
    log.info(path);
    assertNotNull(path);

    //test permissions is in role

    //delete role
    ss.deleteJSON("role/" + role);
    try {
        ss.retrieveJSON("role/" + role, new JSONObject());
        assertFalse(true); // XXX use JUnit exception annotation
    } catch (UnderlyingStorageException e) {
        assertTrue(true); // XXX use JUnit exception annotation
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.TestPermissions.java

private JSONObject createRole(String jsonFile) {

    Storage ss;/*from   ww  w .j  a  v a 2  s  . co m*/
    try {
        //delete this role if exist
        JSONObject u1 = getJSON(jsonFile);
        String roleName = u1.getString("roleName");
        JSONObject test = new JSONObject();
        test.put("keywords", roleName);
        ss = makeServicesStorage();
        /* delete role if already exists */
        JSONObject data = ss.getPathsJSON("role/", test);
        String[] paths = (String[]) data.get("listItems");
        log.info(data.toString());
        if (paths.length > 0) {
            ss.deleteJSON("role/" + paths[0]);
        }

        //create role
        String path = ss.autocreateJSON("role/", u1, null);
        assertNotNull(path);

        JSONObject u3 = ss.retrieveJSON("role/" + path, new JSONObject());
        assertNotNull(u3);
        //return role path

        JSONObject roledata = new JSONObject();
        roledata.put("roleName", roleName);
        roledata.put("roleId", path);
        return roledata;

    } catch (CSPDependencyException e) {
        fail("CSPDependencyException:" + e.getMessage());
    } catch (JSONException e) {
        fail("JSONException:" + e.getMessage());
    } catch (ExistException e) {
        fail("ExistException:" + e.getMessage());
    } catch (UnimplementedException e) {
        fail("UnimplementedException:" + e.getMessage());
    } catch (UnderlyingStorageException e) {
        fail("UnderlyingStorageException:" + e.getMessage());
    } catch (IOException e) {
        fail("IOException:" + e.getMessage());
    }
    return null;
}

From source file:org.collectionspace.chain.csp.persistence.services.TestPermissions.java

private JSONObject createUser(String jsonFile) {

    Storage ss;//from  w w w  .j a va2  s .  c o  m
    try {
        JSONObject u1 = getJSON(jsonFile);
        String screenName = u1.getString("screenName");
        String userId = u1.getString("userId");
        JSONObject test = new JSONObject();
        test.put("userId", userId);
        ss = makeServicesStorage();
        /* delete user if already exists */
        JSONObject data = ss.getPathsJSON("users/", test);
        String[] paths = (String[]) data.get("listItems");
        if (paths.length > 0)
            ss.deleteJSON("users/" + paths[0]);

        /* create the user based on json */
        /* will give a hidden 500 error if userid is not unique (useful eh?) */
        String path = ss.autocreateJSON("users/", u1, null);
        assertNotNull(path);
        JSONObject u2 = getJSON(jsonFile);
        ss.updateJSON("users/" + path, u2, new JSONObject());
        JSONObject u3 = ss.retrieveJSON("users/" + path, new JSONObject());
        assertNotNull(u3);

        JSONObject userdata = new JSONObject();
        userdata.put("screenName", screenName);
        userdata.put("accountId", path);//csid
        userdata.put("userId", userId);//really email
        return userdata;
    } catch (CSPDependencyException e) {
        fail("CSPDependencyException:" + e.getMessage());
    } catch (JSONException e) {
        fail("JSONException:" + e.getMessage());
    } catch (ExistException e) {
        fail("ExistException:" + e.getMessage());
    } catch (UnimplementedException e) {
        fail("UnimplementedException:" + e.getMessage());
    } catch (UnderlyingStorageException e) {
        fail("UnderlyingStorageException:" + e.getMessage());
    } catch (IOException e) {
        fail("IOException:" + e.getMessage());
    }
    return null;
}

From source file:de.quadrillenschule.azocamsyncd.astromode_old.PhotoProjectProfile.java

public void fromJSONProfile(String jsonProfile, PhotoProject project) {
    photoSeries = new LinkedList<>();
    try {/*w  w w  .j a v  a 2 s.co  m*/
        JSONObject jsa = new JSONObject(jsonProfile);

        ReceivePhotoSerie[] psArray = new ReceivePhotoSerie[jsa.names().length()];
        for (int i = 0; i < jsa.names().length(); i++) {
            JSONObject seriesArray = (JSONObject) jsa.get(jsa.names().getString(i));
            ReceivePhotoSerie ps = new ReceivePhotoSerie(project);
            ps.setName(jsa.names().get(i).toString());
            ps.setNumberOfPlannedPhotos(seriesArray.getInt(Columns.NUMBER_OF_PLANNED_PHOTOS.name()));
            ps.setExposureTimeInMs(seriesArray.getLong(Columns.EXPOSURE_TIME.name()));
            psArray[seriesArray.getInt("ORDER_NUMBER")] = ps;
        }
        for (ReceivePhotoSerie ps : psArray) {
            photoSeries.add(ps);
        }
    } catch (JSONException ex) {
        Logger.getLogger(PhotoProjectProfile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.activiti.cycle.impl.connector.signavio.SignavioConnector.java

public JSONObject getPublicRootDirectory() throws IOException, JSONException {
    Response directoryResponse = getJsonResponse(conf.getDirectoryUrl());
    JsonRepresentation jsonData = new JsonRepresentation(directoryResponse.getEntity());
    JSONArray rootJsonArray = jsonData.toJsonArray();

    if (log.isLoggable(Level.FINEST)) {
        SignavioLogHelper.logJSONArray(log, rootJsonArray);
    }/*www .j  a  v  a  2s. c o m*/

    // find the directory of type public which contains all directories and
    // models of this account
    for (int i = 0; i < rootJsonArray.length(); i++) {
        JSONObject rootObject = rootJsonArray.getJSONObject(i);
        if ("public".equals(rootObject.getJSONObject("rep").get("type"))) {
            return rootObject;
        }
    }

    if (log.isLoggable(Level.FINEST)) {
        SignavioLogHelper.logCookieAndBody(log, directoryResponse);
    }

    throw new RepositoryException("No directory root found in signavio repository.");
}

From source file:com.marketcloud.marketcloud.Users.java

/**
 * Authentication: allows the user to login.
 *
 * @param email    user's email/* w  w w  .j a va2  s .com*/
 * @param password user's password
 * @return true if the login is successful, false if not
 */
@SuppressWarnings("unused")
public boolean authenticate(String email, String password)
        throws NullPointerException, ExecutionException, InterruptedException, JSONException {
    JSONObject jsonObject = toJsonObject(email, password);

    if (jsonObject != null) {
        jsonObject = new Connect(context).run("post", "http://api.marketcloud.it/v0/users/authenticate",
                publicKey, jsonObject.toString());

        if (!(boolean) jsonObject.get("status"))
            return false;
        else {

            tm.setToken("auth", jsonObject.getJSONObject("data").getString("token"));

            return true;
        }
    }

    return false;
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.UpstreamsStatsExtractor.java

private Map<String, String> getUpstreamsStatsV6(JSONObject upstreams) {
    Map<String, String> upstreamsStats = new HashMap<String, String>();
    Set<String> serverGroupNames = upstreams.keySet();

    for (String serverGroupName : serverGroupNames) {
        JSONObject jsonObject = upstreams.getJSONObject(serverGroupName);

        Set<String> keys = jsonObject.keySet();
        for (String key : keys) {
            Object element = jsonObject.get(key);

            if (element instanceof JSONArray) {
                JSONArray serverGroups = (JSONArray) element;

                for (int i = 0; i < serverGroups.length(); i++) {
                    JSONObject server = serverGroups.getJSONObject(i);
                    collectMetrics(upstreamsStats, serverGroupName, server);
                }//from w ww.j  a  v a2s .com
            }
        }
    }
    return upstreamsStats;
}

From source file:org.b3log.xiaov.service.BaiduQueryService.java

/**
 * Chat with Baidu Robot.//from w  ww  . ja v a 2  s . co  m
 *
 * @param msg the specified message
 * @return robot returned message, return {@code null} if not found
 */
public String chat(String msg) {
    if (StringUtils.isBlank(msg)) {
        return null;
    }

    if (msg.startsWith(XiaoVs.QQ_BOT_NAME + " ")) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME + " ", "");
    }
    if (msg.startsWith(XiaoVs.QQ_BOT_NAME + "")) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME + "", "");
    }
    if (msg.startsWith(XiaoVs.QQ_BOT_NAME + ",")) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME + ",", "");
    }
    if (msg.startsWith(XiaoVs.QQ_BOT_NAME)) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME, "");
    }

    if (StringUtils.isBlank(msg)) {
        msg = "~";
    }

    String BAIDU_URL = "https://sp0.baidu.com/yLsHczq6KgQFm2e88IuM_a/s?sample_name=bear_brain&request_query=#MSG#&bear_type=2";

    final HTTPRequest request = new HTTPRequest();
    request.setRequestMethod(HTTPRequestMethod.POST);
    try {

        BAIDU_URL = BAIDU_URL.replace("#MSG#", URLEncoder.encode(msg, "UTF-8"));
    } catch (final UnsupportedEncodingException e) {
        LOGGER.log(Level.ERROR, "Chat with Baidu Robot failed", e);

        return null;
    }

    try {
        final HTTPHeader header = new HTTPHeader("Cookie", BAIDU_COOKIE);
        request.addHeader(header);
        request.setURL(new URL(BAIDU_URL));

        final HTTPResponse response = URL_FETCH_SVC.fetch(request);
        final JSONObject data = new JSONObject(new String(response.getContent(), "UTF-8"));

        LOGGER.info(new String(response.getContent(), "UTF-8"));

        final String content = (String) data.getJSONArray("result_list").getJSONObject(0).get("result_content");
        String ret = (String) new JSONObject(content).get("answer");
        ret = ret.replaceAll("?", XiaoVs.QQ_BOT_NAME);

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Chat with Baidu Robot failed", e);
    }

    return null;
}

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 {/*w w  w  .ja v a2s.  com*/
            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.mi.xserv.XservBase.java

protected String urlEncodedJSON(JSONObject params) {
    String url_encode = "";
    if (params != null) {
        Iterator<?> keys = params.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String value = "";
            try {
                value = params.get(key).toString();
            } catch (JSONException ignored) {
            }/*from  www. j av a  2  s.  co  m*/
            try {
                if (url_encode.length() > 0) {
                    url_encode += "&";
                }
                url_encode += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException ignored) {
            }
        }
    }
    return url_encode;
}