List of usage examples for org.json JSONObject getBoolean
public boolean getBoolean(String key) throws JSONException
From source file:com.connectsdk.cordova.JSCommandDispatcher.java
@CommandMethod public void volumeControl_setMute(JSCommand command, JSONObject args) throws JSONException { boolean mute = args.getBoolean("mute"); device.getVolumeControl().setMute(mute, command.getResponseListener()); }
From source file:com.creationgroundmedia.popularmovies.sync.MovieSyncAdapter.java
private void getMovieDataFromJson(String movieJsonStr) throws JSONException { if (movieJsonStr == null) { return;//w w w. j av a 2 s.co m } JSONObject movieJSON = new JSONObject(movieJsonStr); JSONArray movieList = movieJSON.getJSONArray(mContext.getString(R.string.jsonresults)); Vector<ContentValues> cvVector = new Vector<ContentValues>(movieList.length()); for (int i = 0; i < movieList.length(); i++) { JSONObject titleJSON = movieList.getJSONObject(i); ContentValues movieValues = new ContentValues(); String title = titleJSON.getString(mContext.getString(R.string.jsontitle)); movieValues.put(MoviesContract.MovieEntry.COLUMN_ADULT, titleJSON.getBoolean(mContext.getString(R.string.jsonadult)) ? 1 : 0); movieValues.put(MoviesContract.MovieEntry.COLUMN_BACKDROP_PATH, titleJSON.getString(mContext.getString(R.string.jsonbackdrop))); movieValues.put(MoviesContract.MovieEntry.COLUMN_FAVORITE, 0); movieValues.put(MoviesContract.MovieEntry.COLUMN_FRESH, 1); movieValues.put(MoviesContract.MovieEntry.COLUMN_ID_KEY, titleJSON.getLong(mContext.getString(R.string.jsonid))); movieValues.put(MoviesContract.MovieEntry.COLUMN_ORIGINAL_LANGUAGE, titleJSON.getString(mContext.getString(R.string.jsonoriginallanguage))); movieValues.put(MoviesContract.MovieEntry.COLUMN_OVERVIEW, titleJSON.getString(mContext.getString(R.string.jsonoverview))); movieValues.put(MoviesContract.MovieEntry.COLUMN_POPULARITY, titleJSON.getString(mContext.getString(R.string.jsonpopularity))); movieValues.put(MoviesContract.MovieEntry.COLUMN_POSTER_PATH, titleJSON.getString(mContext.getString(R.string.jsonposter))); movieValues.put(MoviesContract.MovieEntry.COLUMN_RELEASE_DATE, titleJSON.getString(mContext.getString(R.string.jsondate))); movieValues.put(MoviesContract.MovieEntry.COLUMN_SORTTITLE, trimLeadingThe(title)); movieValues.put(MoviesContract.MovieEntry.COLUMN_TITLE, title); movieValues.put(MoviesContract.MovieEntry.COLUMN_VIDEO, titleJSON.getBoolean(mContext.getString(R.string.jsonvideo)) ? 1 : 0); movieValues.put(MoviesContract.MovieEntry.COLUMN_VOTE_AVERAGE, titleJSON.getString(mContext.getString(R.string.jsonvoteaverage))); movieValues.put(MoviesContract.MovieEntry.COLUMN_VOTE_COUNT, titleJSON.getInt(mContext.getString(R.string.jsonvotecount))); cvVector.add(movieValues); } ContentValues[] cvArray = new ContentValues[cvVector.size()]; cvVector.toArray(cvArray); int inserted = mContext.getContentResolver().bulkInsert(MoviesContract.MovieEntry.CONTENT_URI, cvArray); }
From source file:com.bearstech.android.myownsync.client.User.java
/** * Creates and returns an instance of the user from the provided JSON data. * /* www .j av a 2s. c o m*/ * @param user The JSONObject containing user data * @return user The new instance of Voiper user created from the JSON data. */ public static User valueOf(JSONObject user) { try { final int userId = user.getInt("user_id"); final boolean deleted = user.has("d") ? user.getBoolean("d") : false; final String userName = user.getString("username"); final String firstName = opt_get(user, "firstname"); final String lastName = opt_get(user, "lastname"); final String middleName = opt_get(user, "middlename"); final String nameSuffix = opt_get(user, "namesuffix"); final String pGivenName = opt_get(user, "phonetic_given_name"); final String pMiddleName = opt_get(user, "phonetic_middle_name"); final String pFamilyName = opt_get(user, "phonetic_family_name"); final String nickname = opt_get(user, "nickname"); final String website = opt_get(user, "website"); final String status = opt_get(user, "status"); User u = new User(userName, firstName, lastName, middleName, nameSuffix, pGivenName, pMiddleName, pFamilyName, nickname, website, status, deleted, userId); if (user.has("orga")) { final JSONArray orgas = user.getJSONArray("orga"); for (int i = 0; i < orgas.length(); ++i) { JSONObject orga = orgas.getJSONObject(i); u.addOrga(orga.getString("name"), orga.getString("role")); } } if (user.has("phone")) { final JSONArray phones = user.getJSONArray("phone"); for (int i = 0; i < phones.length(); ++i) { JSONObject phone = phones.getJSONObject(i); u.addPhone(phone.getString("phonetype"), phone.getString("phone")); } } if (user.has("email")) { final JSONArray emails = user.getJSONArray("email"); for (int i = 0; i < emails.length(); ++i) { JSONObject email = emails.getJSONObject(i); u.addEmail(email.getString("emailtype"), email.getString("email")); } } if (user.has("address")) { final JSONArray addresses = user.getJSONArray("address"); for (int i = 0; i < addresses.length(); ++i) { JSONObject address = addresses.getJSONObject(i); u.addAddress(opt_get(address, "addrtype"), opt_get(address, "street"), opt_get(address, "postcode"), opt_get(address, "city"), opt_get(address, "country")); } } if (user.has("IM")) { final JSONArray IMs = user.getJSONArray("IM"); for (int i = 0; i < IMs.length(); ++i) { JSONObject IM = IMs.getJSONObject(i); u.addIM(IM.getString("type"), IM.getString("handle")); } } Log.d("User", "JSON object: " + user); Log.d("User", "resulted user is " + u.getLastName()); return u; } catch (final Exception ex) { Log.i("User", "Error parsing JSON user object" + ex.toString()); } return null; }
From source file:com.owncloud.android.authenticator.ConnectionCheckerRunnable.java
private boolean tryConnection(String urlSt) { boolean retval = false; GetMethod get = null;/* w w w . j av a 2 s . c o m*/ try { WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(urlSt)); get = new GetMethod(urlSt); int status = wc.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT); String response = get.getResponseBodyAsString(); switch (status) { case HttpStatus.SC_OK: { JSONObject json = new JSONObject(response); if (!json.getBoolean("installed")) { mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; break; } mOCVersion = new OwnCloudVersion(json.getString("version")); if (!mOCVersion.isVersionValid()) { mLatestResult = ResultType.BAD_OC_VERSION; break; } retval = true; break; } case HttpStatus.SC_NOT_FOUND: mLatestResult = ResultType.FILE_NOT_FOUND; break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; break; default: mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "Not handled status received from server: " + status); } } catch (JSONException e) { mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; Log.e(TAG, "JSON exception while trying connection (instance not configured) ", e); } catch (SocketException e) { mLatestResult = ResultType.WRONG_CONNECTION; Log.e(TAG, "Socket exception while trying connection", e); } catch (SocketTimeoutException e) { mLatestResult = ResultType.TIMEOUT; Log.e(TAG, "Socket timeout exception while trying connection", e); } catch (MalformedURLException e) { mLatestResult = ResultType.INCORRECT_ADDRESS; Log.e(TAG, "Connect exception while trying connection", e); } catch (UnknownHostException e) { mLatestResult = ResultType.HOST_NOT_AVAILABLE; Log.e(TAG, "Unknown host exception while trying connection", e); } catch (SSLPeerUnverifiedException e) { // specially meaningful SSLException mLatestResult = ResultType.SSL_UNVERIFIED_SERVER; Log.e(TAG, "SSL Peer Unverified exception while trying connection", e); } catch (SSLException e) { mLatestResult = ResultType.SSL_INIT_ERROR; Log.e(TAG, "SSL exception while trying connection", e); } catch (ConnectTimeoutException e) { // timeout specific exception from org.apache.commons.httpclient mLatestResult = ResultType.TIMEOUT; Log.e(TAG, "Socket timeout exception while trying connection", e); } catch (HttpException e) { // other specific exceptions from org.apache.commons.httpclient mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "HTTP exception while trying connection", e); } catch (IOException e) { // UnkownsServiceException, and any other transport exceptions that could occur mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "I/O exception while trying connection", e); } catch (Exception e) { mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "Unexpected exception while trying connection", e); } finally { if (get != null) get.releaseConnection(); } return retval; }
From source file:org.wso2.iot.system.service.SystemService.java
@Override protected void onHandleIntent(Intent intent) { context = this.getApplicationContext(); cdmDeviceAdmin = new ComponentName(this, ServiceDeviceAdminReceiver.class); devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mUserManager = (UserManager) getSystemService(Context.USER_SERVICE); String AGENT_PACKAGE_NAME = context.getPackageName(); AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME, Constants.AGENT_APP_PACKAGE_NAME }; if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) { startAdmin();//from www . ja v a 2 s . c o m } else { /*This function handles the "Execute Command on Device" Operation. All requests are handled on a single worker thread. They may take as long as necessary (and will not block the application's main thread), but only one request will be processed at a time.*/ Log.d(TAG, "Entered onHandleIntent of the Command Runner Service."); Bundle extras = intent.getExtras(); if (extras != null) { operationCode = extras.getString("operation"); if (extras.containsKey("command")) { command = extras.getString("command"); if (command != null) { restrictionCode = command.equals("true"); } } if (extras.containsKey("appUri")) { appUri = extras.getString("appUri"); } if (extras.containsKey("operationId")) { operationId = extras.getInt("operationId"); } } if ((operationCode != null)) { if (Constants.AGENT_APP_PACKAGE_NAME.equals(intent.getPackage())) { Log.d(TAG, "IoT agent has sent a command with operation code: " + operationCode + " command: " + command); doTask(operationCode); } else { Log.d(TAG, "Received command from external application. operation code: " + operationCode + " command: " + command); boolean isAutomaticRetry; switch (operationCode) { case Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY: if ("false".equals(command) || "true".equals(command)) { isAutomaticRetry = "true".equals(command); Preference.putBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry), isAutomaticRetry); if (isAutomaticRetry) { String status = Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)); if (Constants.Status.WIFI_OFF.equals(status) && !checkNetworkOnline()) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.FAILED); } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_DOWNLOAD.equals(status)) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.FAILED); } else if (Constants.Status.BATTERY_LEVEL_INSUFFICIENT_TO_INSTALL .equals(Preference.getString(context, context.getResources() .getString(R.string.upgrade_install_status)))) { Preference.putString(context, context.getResources().getString(R.string.upgrade_install_status), Constants.Status.FAILED); } } CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, 0, command); //Sending command as the message CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, Constants.Code.SUCCESS, Constants.Status.SUCCESSFUL, "Updated"); } else { CommonUtils.sendBroadcast(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, "Invalid command argument."); } break; case Constants.Operation.UPGRADE_FIRMWARE: try { JSONObject upgradeData = new JSONObject(command); isAutomaticRetry = !Preference.hasPreferenceKey(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)) || Preference.getBoolean(context, context.getResources() .getString(R.string.firmware_upgrade_automatic_retry)); if (!upgradeData.isNull( context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) { isAutomaticRetry = upgradeData.getBoolean(context.getResources() .getString(R.string.firmware_upgrade_automatic_retry)); } CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_AUTOMATIC_RETRY, 0, (isAutomaticRetry ? "true" : "false")); } catch (JSONException e) { String error = "Failed to build JSON object form the request: " + command; Log.e(TAG, error); Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.MALFORMED_REQUEST); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, error); break; } case Constants.Operation.GET_FIRMWARE_UPGRADE_PACKAGE_STATUS: case Constants.Operation.GET_FIRMWARE_BUILD_DATE: case Constants.Operation.GET_FIRMWARE_UPGRADE_DOWNLOAD_PROGRESS: doTask(operationCode); break; default: Log.e(TAG, "Invalid operation code: " + operationCode); break; } } } } context.registerReceiver(new BatteryChargingStateReceiver(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); //Checking is there any interrupted firmware download is there String status = Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)); if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) { Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.REQUEST_PLACED); Timer timeoutTimer = new Timer(); timeoutTimer.schedule(new TimerTask() { @Override public void run() { if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)))) { if (Preference.getBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) { Log.i(TAG, "Found incomplete firmware download. Proceeding with last download request from the agent."); OTADownload otaDownload = new OTADownload(context); otaDownload.startOTA(); } } } }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); } }
From source file:org.wso2.iot.system.service.SystemService.java
/** * Upgrading device firmware over the air (OTA). *//*from ww w.j av a2 s .co m*/ public void upgradeFirmware(final boolean isStatusCheck) { Log.i(TAG, "An upgrade has been requested"); Preference.putBoolean(context, context.getResources().getString(R.string.firmware_status_check_in_progress), isStatusCheck); Preference.putString(context, context.getResources().getString(R.string.firmware_download_progress), String.valueOf(DEFAULT_STATE_INFO_CODE)); Preference.putInt(context, context.getResources().getString(R.string.operation_id), operationId); String schedule = null; String server; if (command != null && !command.trim().isEmpty()) { try { JSONObject upgradeData = new JSONObject(command); if (!upgradeData.isNull(context.getResources().getString(R.string.alarm_schedule))) { schedule = (String) upgradeData.get(context.getResources().getString(R.string.alarm_schedule)); } boolean isAutomaticRetry = !Preference.hasPreferenceKey(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)) || Preference.getBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)); if (!upgradeData .isNull(context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) { isAutomaticRetry = upgradeData.getBoolean( context.getResources().getString(R.string.firmware_upgrade_automatic_retry)); if (!isAutomaticRetry) { Log.i(TAG, "Automatic retry on firmware upgrade failure is disabled."); } } Preference.putBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry), isAutomaticRetry); if (!upgradeData.isNull(context.getResources().getString(R.string.firmware_server))) { server = (String) upgradeData.get(context.getResources().getString(R.string.firmware_server)); // When the server is empty, that means it is indicating to download from default server if (!server.isEmpty() && !Patterns.WEB_URL.matcher(server).matches()) { String message = "Firmware upgrade URL provided is not valid."; CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.MALFORMED_OTA_URL, message); CommonUtils.callAgentApp(context, Constants.Operation.FIRMWARE_UPGRADE_FAILURE, Preference.getInt(context, context.getResources().getString(R.string.operation_id)), message); Log.e(TAG, message); return; } else { Preference.putString(context, context.getResources().getString(R.string.firmware_server), server); } } } catch (JSONException e) { Log.e(TAG, "Firmware upgrade payload parsing failed." + e); return; } } if (schedule != null && !schedule.trim().isEmpty()) { Log.i(TAG, "Upgrade scheduled received: " + schedule); Preference.putString(context, context.getResources().getString(R.string.alarm_schedule), schedule); try { AlarmUtils.setOneTimeAlarm(context, schedule, Constants.Operation.UPGRADE_FIRMWARE, null); } catch (ParseException e) { CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.MALFORMED_REQUEST, e.getMessage()); } } else { if (isStatusCheck) { Log.i(TAG, "Firmware status check is initiated by admin."); } else { Log.i(TAG, "Upgrade request initiated by admin."); String status = Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)); boolean isAutomaticUpgrade = Preference.getBoolean(context, context.getResources().getString(R.string.firmware_upgrade_automatic_retry)); if (Constants.Status.WIFI_OFF.equals(status) && isAutomaticUpgrade && !checkNetworkOnline()) { String msg = "Ignoring request as service waiting for WiFi to start upgrade."; Log.d(TAG, msg); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING, Constants.Status.OTA_UPGRADE_PENDING, msg); return; } else if (Constants.Status.OTA_UPGRADE_ONGOING.equals(status)) { String msg = "Checking for existing download. Will proceed this request if current download is no longer ongoing."; Log.d(TAG, msg); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.PENDING, Constants.Status.OTA_UPGRADE_ONGOING, msg); Preference.putString(context, context.getResources().getString(R.string.upgrade_download_status), Constants.Status.REQUEST_PLACED); Timer timeoutTimer = new Timer(); timeoutTimer.schedule(new TimerTask() { @Override public void run() { if (Constants.Status.REQUEST_PLACED.equals(Preference.getString(context, context.getResources().getString(R.string.upgrade_download_status)))) { Log.d(TAG, "Download is no longer ongoing. Proceeding download request from the agent."); OTADownload otaDownload = new OTADownload(context); otaDownload.startOTA(); } else { String msg = "Request ignored because another download is ongoing."; Log.d(TAG, msg); CommonUtils.sendBroadcast(context, Constants.Operation.UPGRADE_FIRMWARE, Constants.Code.FAILURE, Constants.Status.OTA_UPGRADE_ONGOING, msg); } } }, Constants.FIRMWARE_UPGRADE_READ_TIMEOUT); return; } } //Prepare for upgrade OTADownload otaDownload = new OTADownload(context); otaDownload.startOTA(); } }
From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworkParser.java
public BikeNetworkParser(String toParse, boolean stripIdFromStationName) throws ParseException { ArrayList<Station> stations = new ArrayList<>(); try {//from www .ja v a 2s . c o m JSONObject jsonObject = new JSONObject(toParse); JSONObject rawNetwork = jsonObject.getJSONObject("network"); /* network name & id */ String networkId = rawNetwork.getString("id"); String networkName = rawNetwork.getString("name"); String networkCompany = rawNetwork.getString("company"); /* network location */ BikeNetworkLocation networkLocation; { JSONObject rawLocation = rawNetwork.getJSONObject("location"); double latitude = rawLocation.getDouble("latitude"); double longitude = rawLocation.getDouble("longitude"); String city = rawLocation.getString("city"); String country = rawLocation.getString("country"); networkLocation = new BikeNetworkLocation(latitude, longitude, city, country); } /* stations list */ { JSONArray rawStations = rawNetwork.getJSONArray("stations"); for (int i = 0; i < rawStations.length(); i++) { JSONObject rawStation = rawStations.getJSONObject(i); String id = rawStation.getString("id"); String name = rawStation.getString("name"); if (stripIdFromStationName) name = name.replaceAll("^[0-9 ]*- *", ""); String lastUpdate = rawStation.getString("timestamp"); double latitude = rawStation.getDouble("latitude"); double longitude = rawStation.getDouble("longitude"); int freeBikes = rawStation.getInt("free_bikes"); int emptySlots; if (!rawStation.isNull("empty_slots")) { emptySlots = rawStation.getInt("empty_slots"); } else { emptySlots = -1; } Station station = new Station(id, name, lastUpdate, latitude, longitude, freeBikes, emptySlots); /* extra info */ if (rawStation.has("extra")) { JSONObject rawExtra = rawStation.getJSONObject("extra"); /* address */ if (rawExtra.has("address")) { station.setAddress(rawExtra.getString("address")); } else if (rawExtra.has("description")) { station.setAddress(rawExtra.getString("description")); } /* banking */ if (rawExtra.has("banking")) { // JCDecaux station.setBanking(rawExtra.getBoolean("banking")); } else if (rawExtra.has("payment")) { if (rawExtra.getString("payment").equals("AVEC_TPE")) { // vlille station.setBanking(true); } else { station.setBanking(false); } } else if (rawExtra.has("ticket")) { // dublinbikes, citycycle station.setBanking(rawExtra.getBoolean("ticket")); } /* bonus */ if (rawExtra.has("bonus")) { station.setBonus(rawExtra.getBoolean("bonus")); } /* status */ if (rawExtra.has("status")) { String status = rawExtra.getString("status"); if (status.equals("CLOSED") // villo || status.equals("CLS") // ClearChannel || status.equals("1") // vlille || status.equals("offline")) { // idecycle station.setStatus(StationStatus.CLOSED); } else { station.setStatus(StationStatus.OPEN); } } else if (rawExtra.has("statusValue")) { if (rawExtra.getString("statusValue").equals("Not In Service")) { // Bike Share station.setStatus(StationStatus.CLOSED); } else { station.setStatus(StationStatus.OPEN); } } else if (rawExtra.has("locked")) { if (rawExtra.getBoolean("locked")) { // bixi station.setStatus(StationStatus.CLOSED); } else { station.setStatus(StationStatus.OPEN); } } else if (rawExtra.has("open")) { if (!rawExtra.getBoolean("open")) { // dublinbikes, citycycle station.setStatus(StationStatus.CLOSED); } else { station.setStatus(StationStatus.OPEN); } } } stations.add(station); } } bikeNetwork = new BikeNetwork(networkId, networkName, networkCompany, networkLocation, stations); } catch (JSONException e) { throw new ParseException("Error parsing JSON", 0); } }
From source file:com.cartlc.tracker.server.DCPing.java
public void ping() { Timber.i("ping()"); try {//from w w w . java 2 s.c om if (PrefHelper.getInstance().getTechID() == 0) { return; } String deviceId = ServerHelper.getInstance().getDeviceId(); JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("device_id", deviceId); jsonObject.accumulate("tech_id", PrefHelper.getInstance().getTechID()); String response = post(PING, jsonObject); if (response == null) { Timber.e("ping(): Unexpected NULL response from server"); return; } JSONObject object = parseResult(response); if (object.has(UPLOAD_RESET_TRIGGER)) { if (object.getBoolean(UPLOAD_RESET_TRIGGER)) { Timber.i("UPLOAD RESET!"); DatabaseManager.getInstance().clearUploaded(); } } if (object.has(RE_REGISTER_TRIGGER)) { if (object.getBoolean(RE_REGISTER_TRIGGER)) { Timber.i("RE-REGISTER DETECTED!"); sendRegistration(); } } int version_project = object.getInt(PrefHelper.VERSION_PROJECT); int version_equipment = object.getInt(PrefHelper.VERSION_EQUIPMENT); int version_note = object.getInt(PrefHelper.VERSION_NOTE); int version_company = object.getInt(PrefHelper.VERSION_COMPANY); int version_truck = object.getInt(PrefHelper.VERSION_TRUCK); if (PrefHelper.getInstance().getVersionProject() != version_project) { Timber.i("New project version " + version_project); queryProjects(); PrefHelper.getInstance().setVersionProject(version_project); } if (PrefHelper.getInstance().getVersionCompany() != version_company) { queryCompanies(); Timber.i("New company version " + version_company); PrefHelper.getInstance().setVersionCompany(version_company); } if (PrefHelper.getInstance().getVersionEquipment() != version_equipment) { queryEquipments(); Timber.i("New equipment version " + version_equipment); PrefHelper.getInstance().setVersionEquipment(version_equipment); } if (PrefHelper.getInstance().getVersionNote() != version_note) { queryNotes(); Timber.i("New note version " + version_note); PrefHelper.getInstance().setVersionNote(version_note); } if (PrefHelper.getInstance().getVersionTruck() != version_truck) { queryTrucks(); Timber.i("New truck version " + version_truck); PrefHelper.getInstance().setVersionTruck(version_truck); } List<DataEntry> entries = TableEntry.getInstance().queryPendingDataToUploadToMaster(); int count = 0; if (entries.size() > 0) { count = sendEntries(entries); } if (count > 0) { EventBus.getDefault().post(new EventPingDone()); } entries = TableEntry.getInstance().queryPendingPicturesToUpload(); if (entries.size() > 0) { AmazonHelper.getInstance().sendPictures(entries); } TablePictureCollection.getInstance().clearUploadedUnscaledPhotos(); List<TableCrash.CrashLine> lines = TableCrash.getInstance().queryNeedsUploading(); sendCrashLines(lines); // If any entries do not yet have server-id's, try to get them. entries = TableEntry.getInstance().queryServerIds(); if (entries.size() > 0) { Timber.i("FOUND " + entries.size() + " entries without server IDS"); sendEntries(entries); } else { Timber.i("All entries have server ids"); } } catch (Exception ex) { Timber.e(ex); } }
From source file:org.wso2.emm.agent.services.Operation.java
@SuppressWarnings("static-access") @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public JSONArray doTask(String code_in, String data_in, int req_mode) { Log.e("doTask", "code:" + code_in + "\n" + data_in); String data_input = data_in;//from ww w . j a v a 2 s . co m String code_input = code_in; String notification = ""; String ssid = ""; String password = ""; devicePolicyManager = (DevicePolicyManager) context.getApplicationContext() .getSystemService(Context.DEVICE_POLICY_SERVICE); appList = new ApplicationManager(context.getApplicationContext()); deviceInfo = new DeviceInfo(context); gps = new GPSTracker(context); smsManager = SmsManager.getDefault(); conversations = new TrackCallSMS(context); deviceState = new PhoneState(context); JSONArray resultArr = new JSONArray(); JSONObject result = new JSONObject(); if (code_input.equals(CommonUtilities.OPERATION_DEVICE_INFO)) { PhoneState phoneState = new PhoneState(context); JSONObject obj = new JSONObject(); JSONObject battery_obj = new JSONObject(); JSONObject inmemory_obj = new JSONObject(); JSONObject exmemory_obj = new JSONObject(); JSONObject location_obj = new JSONObject(); double latitude = 0; double longitude = 0; try { latitude = gps.getLatitude(); longitude = gps.getLongitude(); int batteryLevel = (int) Math.floor(phoneState.getBatteryLevel()); // int batteryLevel = 40; battery_obj.put("level", batteryLevel); inmemory_obj.put("total", deviceInfo.getTotalInternalMemorySize()); inmemory_obj.put("available", deviceInfo.getAvailableInternalMemorySize()); exmemory_obj.put("total", deviceInfo.getTotalExternalMemorySize()); exmemory_obj.put("available", deviceInfo.getAvailableExternalMemorySize()); location_obj.put("latitude", latitude); location_obj.put("longitude", longitude); obj.put("battery", battery_obj); obj.put("internal_memory", inmemory_obj); obj.put("external_memory", exmemory_obj); if (latitude != 0 && longitude != 0) { obj.put("location_obj", location_obj); } obj.put("operator", deviceInfo.getNetworkOperatorName()); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); params.put("data", obj.toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", obj); Map<String, String> as = new HashMap<String, String>(); as.put("all", params.toString()); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { // ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Battery Level : " + phoneState.getBatteryLevel() + ", Total Memory : " + deviceInfo.formatSizeGB(deviceInfo.getTotalInternalMemorySize() + deviceInfo.getTotalExternalMemorySize()) + ", Available Memory : " + deviceInfo.formatSizeGB(deviceInfo.getAvailableInternalMemorySize() + deviceInfo.getAvailableExternalMemorySize()), null, null); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_DEVICE_LOCATION)) { LocationServices ls = new LocationServices(context); Log.v("Latitude", ls.getLatitude()); double latitude = 0; double longitude = 0; JSONObject obj = new JSONObject(); try { latitude = gps.getLatitude(); longitude = gps.getLongitude(); obj.put("latitude", latitude); obj.put("longitude", longitude); Map<String, String> params = new HashMap<String, String>(); params.put("code", CommonUtilities.OPERATION_DEVICE_LOCATION); params.put("msgID", token); params.put("status", "200"); params.put("data", obj.toString()); //for local notification\ resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", obj); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Longitude : " + longitude + ",Latitude : " + latitude, null, null); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_GET_APPLICATION_LIST)) { ArrayList<PInfo> apps = appList.getInstalledApps(false); /* * false = * no system * packages */ JSONArray jsonArray = new JSONArray(); int max = apps.size(); String apz = ""; Log.e("APP TOTAL : ", "" + max); for (int i = 0; i < max; i++) { JSONObject jsonObj = new JSONObject(); try { jsonObj.put("name", Uri.encode(apps.get(i).appname)); jsonObj.put("package", apps.get(i).pname); jsonObj.put("icon", apps.get(i).icon); apz += apps.get(i).appname + " ,"; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } jsonArray.put(jsonObj); } JSONObject appsObj = new JSONObject(); try { //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", jsonArray); appsObj.put("apps", jsonArray); Map<String, String> params = new HashMap<String, String>(); params.put("code", CommonUtilities.OPERATION_GET_APPLICATION_LIST); params.put("msgID", token); params.put("status", "200"); //params.put("data", Uri.encode(jsonArray.toString())); Log.e("PASSING MSG ID : ", token); Log.e("PASSING CODE : ", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, apz, null, null); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_LOCK_DEVICE)) { Log.d(TAG, "Locking device now"); try { Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Device Locked Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, params.toString()); } devicePolicyManager.lockNow(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_WIPE_DATA)) { Log.d(TAG, "RESETing device now - all user data will be ERASED to factory settings"); String pin = null; SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); String pinSaved = mainPref.getString("pin", ""); try { JSONObject jobj = new JSONObject(data_input); pin = (String) jobj.get("pin"); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); //for local notification resultArr.put(result); if (pin.trim().equals(pinSaved.trim())) { params.put("status", "200"); result.put("status", "true"); } else { params.put("status", "400"); result.put("status", "false"); } result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { if (pin.trim().equals(pinSaved.trim())) { smsManager.sendTextMessage(recepient, null, "Device Wiped Successfully", null, null); } else { smsManager.sendTextMessage(recepient, null, "Wrong PIN", null, null); } } if (pin.trim().equals(pinSaved.trim())) { Toast.makeText(context, "Device is being wiped", Toast.LENGTH_LONG).show(); try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } devicePolicyManager.wipeData(ACTIVATION_REQUEST); } else { Toast.makeText(context, "Device wipe failed due to wrong PIN", Toast.LENGTH_LONG).show(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_CLEAR_PASSWORD)) { ComponentName demoDeviceAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class); try { Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Lock code cleared Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, params.toString()); } devicePolicyManager.setPasswordQuality(demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, 0); devicePolicyManager.resetPassword("", DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); devicePolicyManager.lockNow(); devicePolicyManager.setPasswordQuality(demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_NOTIFICATION)) { JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); if (jobj.get("notification").toString() != null || jobj.get("notification").toString().equals("")) { notification = jobj.get("notification").toString(); } else if (jobj.get("Notification").toString() != null || jobj.get("Notification").toString().equals("")) { notification = jobj.get("Notification").toString(); } else { notification = ""; } Log.v("Notification", notification); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Notification Receieved Successfully", null, null); } Intent intent = new Intent(context, AlertActivity.class); intent.putExtra("message", notification); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_WIFI)) { boolean wifistatus = false; JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); 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_input); inparams.put("msgID", token); WiFiConfig config = new WiFiConfig(context); try { //for local notification resultArr.put(result); result.put("code", code_input); wifistatus = config.saveWEPConfig(ssid, password); if (wifistatus) { inparams.put("status", "200"); result.put("status", "true"); } else { inparams.put("status", "400"); result.put("status", "false"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "WiFi Configured Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, inparams.toString()); } } } else if (code_input.equals(CommonUtilities.OPERATION_DISABLE_CAMERA)) { boolean camFunc = false; JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); 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()); } ComponentName cameraAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); String cammode = "Disabled"; if (camFunc) { cammode = "Disabled"; } else { cammode = "Enabled"; } if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Camera " + cammode + " Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, params.toString()); } if (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(); } } else if (code_input.equals(CommonUtilities.OPERATION_INSTALL_APPLICATION) || code_input.equals(CommonUtilities.OPERATION_INSTALL_APPLICATION_BUNDLE)) { try { //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (code_input.equals(CommonUtilities.OPERATION_INSTALL_APPLICATION)) { JSONObject jobj = new JSONObject(data_input); installApplication(jobj, code_input); } else if (code_input.equals(CommonUtilities.OPERATION_INSTALL_APPLICATION_BUNDLE)) { JSONArray jArray = null; jArray = new JSONArray(data_input); for (int i = 0; i < jArray.length(); i++) { JSONObject appObj = (JSONObject) jArray.getJSONObject(i); installApplication(appObj, code_input); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_UNINSTALL_APPLICATION)) { String packageName = ""; JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); packageName = (String) jobj.get("identity"); Log.v("Package Name : ", packageName); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Application uninstalled Successfully", null, null); } appList.unInstallApplication(packageName); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_ENCRYPT_STORAGE)) { boolean encryptFunc = true; String pass = ""; JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); 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_input); params.put("msgID", token); 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); } } } //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (devicePolicyManager .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) { params.put("status", "200"); result.put("status", "true"); } else { params.put("status", "400"); result.put("status", "false"); } if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { // //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Storage Encrypted Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, params.toString()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_MUTE)) { Log.d(TAG, "Muting Device"); try { Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { // //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Device Muted Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, params.toString()); } muteDevice(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_TRACK_CALLS)) { try { Map<String, String> params = new HashMap<String, String>(); params.put("code", CommonUtilities.OPERATION_TRACK_CALLS); params.put("msgID", token); params.put("status", "200"); params.put("data", conversations.getCallDetails().toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", new JSONObject(conversations.getCallDetails().toString())); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, conversations.getCallDetails().toString(), null, null); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_TRACK_SMS)) { int MESSAGE_TYPE_INBOX = 1; int MESSAGE_TYPE_SENT = 2; JSONObject smsObj = new JSONObject(); try { smsObj.put("inbox", conversations.getSMS(MESSAGE_TYPE_INBOX)); smsObj.put("sent", conversations.getSMS(MESSAGE_TYPE_SENT)); Map<String, String> params = new HashMap<String, String>(); params.put("code", CommonUtilities.OPERATION_TRACK_SMS); params.put("msgID", token); params.put("status", "200"); params.put("data", smsObj.toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", smsObj); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, smsObj.toString(), null, null); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_DATA_USAGE)) { JSONObject dataObj = new JSONObject(); try { Map<String, String> params = new HashMap<String, String>(); params.put("code", CommonUtilities.OPERATION_DATA_USAGE); params.put("msgID", token); params.put("status", "200"); params.put("data", deviceState.takeDataUsageSnapShot().toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", new JSONObject(deviceState.takeDataUsageSnapShot().toString())); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, dataObj.toString(), null, null); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_STATUS)) { boolean encryptStatus = false; boolean passCodeStatus = false; try { if (devicePolicyManager .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) { if (devicePolicyManager .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVE || devicePolicyManager .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVATING) { encryptStatus = true; } else { encryptStatus = false; } } if (devicePolicyManager.isActivePasswordSufficient()) { passCodeStatus = true; } else { passCodeStatus = false; } } catch (Exception ex) { ex.printStackTrace(); passCodeStatus = false; } JSONObject dataObj = new JSONObject(); try { dataObj.put("encryption", encryptStatus); dataObj.put("passcode", passCodeStatus); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); params.put("data", dataObj.toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", dataObj); if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, dataObj.toString(), null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, params.toString()); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_WEBCLIP)) { String appUrl = ""; String title = ""; JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); Log.v("WEBCLIP DATA : ", data.toString()); appUrl = (String) jobj.get("identity"); title = (String) jobj.get("title"); Log.v("Web App URL : ", appUrl); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "WebClip created Successfully", null, null); } appList.createWebAppBookmark(appUrl, title); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_PASSWORD_POLICY)) { ComponentName demoDeviceAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class); int attempts, length, history, specialChars; String alphanumeric, complex; boolean b_alphanumeric, b_complex; long timout; Map<String, String> inparams = new HashMap<String, String>(); JSONParser jp = new JSONParser(); //for local notification resultArr.put(result); try { result.put("code", code_input); JSONObject jobj = new JSONObject(data_input); if (!jobj.isNull("maxFailedAttempts") && jobj.get("maxFailedAttempts") != null) { attempts = Integer.parseInt((String) jobj.get("maxFailedAttempts")); devicePolicyManager.setMaximumFailedPasswordsForWipe(demoDeviceAdmin, attempts); } if (!jobj.isNull("minLength") && jobj.get("minLength") != null) { length = Integer.parseInt((String) jobj.get("minLength")); devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, length); } if (!jobj.isNull("pinHistory") && jobj.get("pinHistory") != null) { history = Integer.parseInt((String) jobj.get("pinHistory")); devicePolicyManager.setPasswordHistoryLength(demoDeviceAdmin, history); } if (!jobj.isNull("minComplexChars") && jobj.get("minComplexChars") != null) { specialChars = Integer.parseInt((String) jobj.get("minComplexChars")); devicePolicyManager.setPasswordMinimumSymbols(demoDeviceAdmin, specialChars); } if (!jobj.isNull("requireAlphanumeric") && jobj.get("requireAlphanumeric") != null) { if (jobj.get("requireAlphanumeric") instanceof String) { alphanumeric = (String) jobj.get("requireAlphanumeric"); if (alphanumeric.equals("true")) { devicePolicyManager.setPasswordQuality(demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC); } } else if (jobj.get("requireAlphanumeric") instanceof Boolean) { b_alphanumeric = jobj.getBoolean("requireAlphanumeric"); if (b_alphanumeric) { devicePolicyManager.setPasswordQuality(demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC); } } } if (!jobj.isNull("allowSimple") && jobj.get("allowSimple") != null) { if (jobj.get("allowSimple") instanceof String) { complex = (String) jobj.get("allowSimple"); if (!complex.equals("true")) { devicePolicyManager.setPasswordQuality(demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX); } } else if (jobj.get("allowSimple") instanceof Boolean) { b_complex = jobj.getBoolean("allowSimple"); if (!b_complex) { devicePolicyManager.setPasswordQuality(demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX); } } } if (!jobj.isNull("maxPINAgeInDays") && jobj.get("maxPINAgeInDays") != null) { int daysOfExp = Integer.parseInt((String) jobj.get("maxPINAgeInDays")); timout = (long) (daysOfExp * 24 * 60 * 60 * 1000); devicePolicyManager.setPasswordExpirationTimeout(demoDeviceAdmin, timout); } SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); String policy = mainPref.getString("policy", ""); inparams.put("code", code_input); inparams.put("msgID", token); inparams.put("status", "200"); result.put("status", "true"); } catch (Exception e) { // TODO Auto-generated catch block params.put("status", "400"); try { result.put("status", "false"); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { try { if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Password Policies Successfully Set", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, inparams.toString()); } } catch (Exception ex) { ex.printStackTrace(); } } } else if (code_input.equals(CommonUtilities.OPERATION_EMAIL_CONFIGURATION)) { String emailname = "", emailtype = "", ic_username = "", ic_password = "", ic_hostname = ""; long timout; Map<String, String> inparams = new HashMap<String, String>(); //for local notification resultArr.put(result); JSONParser jp = new JSONParser(); try { result.put("code", code_input); JSONObject jobj = new JSONObject(data_input); if (!jobj.isNull("type") && jobj.get("type") != null) { emailtype = (String) jobj.get("type"); } if (!jobj.isNull("displayname") && jobj.get("displayname") != null) { emailname = (String) jobj.get("displayname"); } if (!jobj.isNull("username") && jobj.get("username") != null) { ic_username = (String) jobj.get("username"); } if (!jobj.isNull("password") && jobj.get("password") != null) { ic_password = (String) jobj.get("password"); } if (emailtype.trim().equals("GMAIL")) { ic_hostname = "imap.googlemail.com"; } else if (emailtype.equals("YAHOO")) { ic_hostname = ""; } else if (emailtype.equals("HOTMAIL")) { ic_hostname = ""; } inparams.put("code", code_input); inparams.put("msgID", token); inparams.put("status", "200"); result.put("status", "true"); } catch (Exception e) { // TODO Auto-generated catch block params.put("status", "400"); try { result.put("status", "false"); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally { try { if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Email Configured Successfully Set", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, inparams.toString()); } } catch (Exception ex) { ex.printStackTrace(); } } } else if (code_input.equals(CommonUtilities.OPERATION_INSTALL_GOOGLE_APP)) { String packageName = ""; JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); packageName = (String) jobj.get("package"); Log.v("Package Name : ", packageName); Map<String, String> params = new HashMap<String, String>(); params.put("code", code_input); params.put("msgID", token); params.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Application installed Successfully", null, null); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse("market://details?id=" + packageName)); context.startActivity(intent); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_CHANGE_LOCK_CODE)) { ComponentName demoDeviceAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class); devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, 3); String pass = ""; Map<String, String> inparams = new HashMap<String, String>(); JSONParser jp = new JSONParser(); try { JSONObject jobj = new JSONObject(data_input); if (!jobj.isNull("password")) { pass = (String) jobj.get("password"); } inparams.put("code", code_input); inparams.put("msgID", token); inparams.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Lock code changed Successfully", null, null); } if (!pass.equals("")) { devicePolicyManager.resetPassword(pass, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); devicePolicyManager.lockNow(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (req_mode == REQUEST_MODE_NORMAL) { if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Lock code changed Successfully", null, null); } } else { if (policy_count != 0) { policy_count++; } bundle_params.put("" + policy_count, inparams.toString()); } } catch (Exception ex) { ex.printStackTrace(); } } } else if (code_input.equals(CommonUtilities.OPERATION_POLICY_BUNDLE)) { Map<String, String> params = new HashMap<String, String>(); try { params.put("code", code); params.put("msgID", policy_token); params.put("status", "200"); params.put("data", bundle_params.toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", new JSONObject(bundle_params.toString())); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Bundle Executed Successfully", null, null); } } catch (Exception ex) { ex.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_POLICY_MONITOR)) { JSONArray sendjArray; JSONObject jobj = null; try { if (this.data != null && !this.data.trim().equals("")) jobj = new JSONObject(this.data); sendjArray = jobj.getJSONArray("policies"); int type = Integer.parseInt((String) jobj.get("type").toString().trim()); if (type != 1 && type != 2 && type != 3) { type = 1; } Log.e("PASSING MSG ID : ", policy_token); Log.e("PASSING CODE : ", code_input); Log.e("PASSING TYPE : ", String.valueOf(type)); PolicyTester tester = new PolicyTester(context, sendjArray, type, policy_token); //for local notification resultArr = tester.finalArray; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_POLICY_REVOKE)) { try { Map<String, String> inparams = new HashMap<String, String>(); inparams.put("code", code_input); inparams.put("msgID", token); inparams.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, "Lock code changed Successfully", null, null); } revokePolicy(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_ENTERPRISE_WIPE_DATA)) { try { Map<String, String> inparams = new HashMap<String, String>(); inparams.put("code", code_input); inparams.put("msgID", token); inparams.put("status", "200"); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(inparams, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { // smsManager.sendTextMessage(recepient, null, // "Lock code changed Successfully", null, null); } enterpriseWipe = true; ServerUtils.clearAppData(context); Intent intent = new Intent(context, SettingsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (code_input.equals(CommonUtilities.OPERATION_BLACKLIST_APPS)) { ArrayList<PInfo> apps = appList.getInstalledApps(false); /* * false = * no system * packages */ JSONArray jsonArray = new JSONArray(); int max = apps.size(); if (max > 10) { //max = 10; } String apz = ""; try { JSONObject appsObj = new JSONObject(data_input); if (!appsObj.isNull("data")) { appsObj = (JSONObject) appsObj.get("data"); } // JSONObject appObj = (JSONObject) appsObj.get("data"); String identity = (String) appsObj.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); jsonObj.put("package", apps.get(j).pname); } else { jsonObj.put("notviolated", true); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } jsonArray.put(jsonObj); } } catch (Exception ex) { ex.printStackTrace(); } JSONObject appsObj = new JSONObject(); try { appsObj.put("apps", jsonArray); Map<String, String> params = new HashMap<String, String>(); params.put("code", CommonUtilities.OPERATION_GET_APPLICATION_LIST); params.put("msgID", token); params.put("status", "200"); params.put("data", jsonArray.toString()); //for local notification resultArr.put(result); result.put("status", "true"); result.put("code", code_input); result.put("data", jsonArray); if (mode == CommonUtilities.MESSAGE_MODE_GCM) { //ServerUtilities.pushData(params, context); } else if (mode == CommonUtilities.MESSAGE_MODE_SMS) { smsManager.sendTextMessage(recepient, null, apz, null, null); } SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE); String policy = mainPref.getString("policy", ""); if (policy != null && policy != "") { if (apz != null || !apz.trim().equals("")) { } } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return resultArr; }
From source file:com.github.mhendred.face4j.model.UserStatus.java
public UserStatus(final JSONObject jObj) throws JSONException { uid = jObj.getString("uid"); training_set_size = jObj.getInt("training_set_size"); last_trained = jObj.getLong("last_trained"); training_in_progress = jObj.getBoolean("training_in_progress"); }