From cafdeaef487d308be2abff9be97c3df9569bbe2a Mon Sep 17 00:00:00 2001 From: charitha Date: Fri, 13 Oct 2017 12:54:11 +0530 Subject: [PATCH] Refactor code to be optimized --- .../DeviceManagementAdminServiceImpl.java | 177 ++------ .../impl/DeviceManagementServiceImpl.java | 24 +- .../DeviceTypeConfigurationServiceImpl.java | 8 +- .../impl/EventReceiverServiceImpl.java | 7 +- .../android/util/AndroidAPIUtils.java | 400 +---------------- .../android/util/AndroidDeviceUtils.java | 405 ++++++++++++++++-- 6 files changed, 419 insertions(+), 602 deletions(-) diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java index 81d94ad1b..f3beca09d 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java @@ -62,8 +62,8 @@ import org.wso2.carbon.mdm.services.android.bean.wrapper.WipeDataBeanWrapper; import org.wso2.carbon.mdm.services.android.exception.BadRequestException; import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException; import org.wso2.carbon.mdm.services.android.services.DeviceManagementAdminService; -import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; import org.wso2.carbon.mdm.services.android.util.AndroidConstants; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; import javax.validation.Valid; import javax.ws.rs.Consumes; @@ -110,7 +110,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setType(Operation.Type.PROFILE); operation.setEnabled(true); operation.setPayLoad(lock.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceLockBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceLockBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -122,11 +122,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -143,7 +138,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.DEVICE_UNLOCK); operation.setType(Operation.Type.COMMAND); operation.setEnabled(true); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -155,11 +150,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -175,7 +165,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCATION); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -187,11 +177,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -207,7 +192,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.CLEAR_PASSWORD); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -219,11 +204,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -247,7 +227,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.CAMERA); operation.setType(Operation.Type.COMMAND); operation.setEnabled(camera.isEnabled()); - Activity activity = AndroidAPIUtils.getOperationResponse(cameraBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(cameraBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -259,11 +239,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -279,7 +254,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.DEVICE_INFO); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -290,11 +265,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe String errorMessage = "Issue in retrieving operation management service instance"; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -310,7 +280,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.LOGCAT); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -321,11 +291,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe String errorMessage = "Issue in retrieving operation management service instance"; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -341,7 +306,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -353,11 +318,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -381,7 +341,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(wipeData.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(wipeDataBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(wipeDataBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -393,11 +353,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -413,7 +368,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.APPLICATION_LIST); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -425,11 +380,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -445,7 +395,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.DEVICE_RING); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -457,11 +407,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -477,7 +422,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe CommandOperation operation = new CommandOperation(); operation.setCode(AndroidConstants.OperationCodes.DEVICE_REBOOT); operation.setType(Operation.Type.COMMAND); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -489,11 +434,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -510,7 +450,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.DEVICE_MUTE); operation.setType(Operation.Type.COMMAND); operation.setEnabled(true); - Activity activity = AndroidAPIUtils.getOperationResponse(deviceIDs, operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -522,11 +462,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -556,7 +491,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.INSTALL_APPLICATION); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(applicationInstallation.toJSON()); - Activity activity = AndroidAPIUtils + Activity activity = AndroidDeviceUtils .getOperationResponse(applicationInstallationBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (JSONException e) { @@ -574,11 +509,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -607,7 +537,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setType(Operation.Type.PROFILE); operation.setPayLoad(applicationUpdate.toJSON()); - Activity activity = AndroidAPIUtils + Activity activity = AndroidDeviceUtils .getOperationResponse(applicationUpdateBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { @@ -620,11 +550,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -651,7 +576,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.UNINSTALL_APPLICATION); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(applicationUninstallation.toJSON()); - Activity activity = AndroidAPIUtils + Activity activity = AndroidDeviceUtils .getOperationResponse(applicationUninstallationBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { @@ -664,11 +589,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -692,7 +612,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.BLACKLIST_APPLICATIONS); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(blacklistApplications.toJSON()); - Activity activity = AndroidAPIUtils + Activity activity = AndroidDeviceUtils .getOperationResponse(blacklistApplicationsBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { @@ -705,11 +625,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -735,7 +650,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.UPGRADE_FIRMWARE); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(upgradeFirmware.toJSON()); - Activity activity = AndroidAPIUtils + Activity activity = AndroidDeviceUtils .getOperationResponse(upgradeFirmwareBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { @@ -748,11 +663,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -776,7 +686,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.VPN); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(vpn.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(vpnConfiguration.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(vpnConfiguration.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -788,11 +698,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -816,7 +721,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.NOTIFICATION); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(notification.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(notificationBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(notificationBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -828,11 +733,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -857,7 +757,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setType(Operation.Type.PROFILE); operation.setPayLoad(wifi.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(wifiBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(wifiBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -869,11 +769,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -897,7 +792,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.ENCRYPT_STORAGE); operation.setType(Operation.Type.COMMAND); operation.setEnabled(deviceEncryption.isEncrypted()); - Activity activity = AndroidAPIUtils.getOperationResponse(encryptionBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(encryptionBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -909,11 +804,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -937,7 +827,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_CODE); operation.setType(Operation.Type.PROFILE); operation.setPayLoad(lockCode.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(lockCodeBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(lockCodeBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -949,11 +839,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -978,7 +863,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setType(Operation.Type.PROFILE); operation.setPayLoad(passcodePolicy.toJSON()); - Activity activity = AndroidAPIUtils + Activity activity = AndroidDeviceUtils .getOperationResponse(passwordPolicyBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { @@ -991,11 +876,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } @@ -1021,7 +901,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe operation.setType(Operation.Type.PROFILE); operation.setPayLoad(webClip.toJSON()); - Activity activity = AndroidAPIUtils.getOperationResponse(webClipBeanWrapper.getDeviceIDs(), operation); + Activity activity = AndroidDeviceUtils.getOperationResponse(webClipBeanWrapper.getDeviceIDs(), operation); return Response.status(Response.Status.CREATED).entity(activity).build(); } catch (InvalidDeviceException e) { String errorMessage = "Invalid Device Identifiers found."; @@ -1033,11 +913,6 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe log.error(errorMessage, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); - } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); } } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java index c401bb25d..9990421f7 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java @@ -20,7 +20,6 @@ package org.wso2.carbon.mdm.services.android.services.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; @@ -126,7 +125,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } - DeviceIdentifier deviceIdentifier = AndroidAPIUtils.convertToDeviceIdentifierObject(id); + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); try { if (!AndroidDeviceUtils.isValidDeviceIdentifier(deviceIdentifier)) { String msg = "Device not found for identifier '" + id + "'"; @@ -168,7 +167,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { List pendingOperations; try { - pendingOperations = AndroidAPIUtils.getPendingOperations(deviceIdentifier); + pendingOperations = AndroidDeviceUtils.getPendingOperations(deviceIdentifier); } catch (OperationManagementException e) { String msg = "Issue in retrieving operation management service instance"; log.error(msg, e); @@ -182,7 +181,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { throws OperationManagementException, PolicyComplianceException, ApplicationManagementException, NotificationManagementException, DeviceManagementException { for (org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation : operations) { - AndroidAPIUtils.updateOperation(deviceId, operation); + AndroidDeviceUtils.updateOperation(deviceId, operation); if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) { org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new org.wso2.carbon.device.mgt.common.notification.mgt.Notification(); @@ -233,10 +232,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceLocation deviceLocation = extractLocation(deviceIdentifier, androidDevice.getProperties()); if (deviceLocation != null) { try { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceInformationManager informationManager = - (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); - + DeviceInformationManager informationManager = AndroidAPIUtils + .getDeviceInformationManagerService(); informationManager.addDeviceLocation(deviceLocation); } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while updating the device location upon android " + @@ -265,10 +262,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); } - } - PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService(); - policyManagerService.getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType())); - if (status) { + PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService(); + policyManagerService.getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType())); + Message responseMessage = new Message(); responseMessage.setResponseCode(Response.Status.OK.toString()); responseMessage.setResponseMessage("Android device, which carries the id '" + @@ -316,7 +312,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Path("/{id}/status") @Override public Response isEnrolled(@PathParam("id") String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { - DeviceIdentifier deviceIdentifier = AndroidAPIUtils.convertToDeviceIdentifierObject(id); + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); try { Device device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); if (device != null) { @@ -421,7 +417,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Override public Response disEnrollDevice(@PathParam("id") String id) { boolean result; - DeviceIdentifier deviceIdentifier = AndroidAPIUtils.convertToDeviceIdentifierObject(id); + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); try { result = AndroidAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier); if (result) { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java index c6b343215..dad6cb454 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java @@ -31,10 +31,14 @@ import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorExcep import org.wso2.carbon.mdm.services.android.services.DeviceTypeConfigurationService; import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; import org.wso2.carbon.mdm.services.android.util.AndroidConstants; -import org.wso2.carbon.mdm.services.android.util.Message; import javax.validation.Valid; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java index 2c012737f..6d01dae3e 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java @@ -32,6 +32,7 @@ import org.wso2.carbon.mdm.services.android.exception.NotFoundException; import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException; import org.wso2.carbon.mdm.services.android.services.EventReceiverService; import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; import org.wso2.carbon.mdm.services.android.util.Message; import javax.validation.Valid; @@ -127,7 +128,7 @@ public class EventReceiverServiceImpl implements EventReceiverService { String query = "deviceIdentifier:" + deviceId; List deviceStates; try { - deviceStates = AndroidAPIUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); + deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); if (deviceStates == null) { throw new NotFoundException( new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No any alerts are " + @@ -153,7 +154,7 @@ public class EventReceiverServiceImpl implements EventReceiverService { String query = "deviceIdentifier:" + deviceId + " AND _timestamp: [" + fromDate + " TO " + toDate + "]"; List deviceStates; try { - deviceStates = AndroidAPIUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); + deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); if (deviceStates == null) { throw new NotFoundException( new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No any alerts are " + @@ -178,7 +179,7 @@ public class EventReceiverServiceImpl implements EventReceiverService { String query = "deviceIdentifier:" + deviceId + " AND type:" + type; List deviceStates; try { - deviceStates = AndroidAPIUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); + deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); if (deviceStates == null) { throw new NotFoundException( new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No any alerts are " + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java index 123c753c7..f8c37fe5f 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java @@ -18,54 +18,17 @@ package org.wso2.carbon.mdm.services.android.util; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; -import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; -import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; -import org.wso2.carbon.analytics.datasource.commons.Record; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.mdm.services.android.bean.DeviceState; -import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; -import org.wso2.carbon.mdm.services.android.exception.BadRequestException; -import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * AndroidAPIUtil class provides utility functions used by Android REST-API classes. */ @@ -73,11 +36,8 @@ public class AndroidAPIUtils { private static Log log = LogFactory.getLog(AndroidAPIUtils.class); - public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) { - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - return identifier; + private AndroidAPIUtils(){ + throw new IllegalStateException("Utility class"); } public static String getAuthenticatedUser() { @@ -102,48 +62,18 @@ public class AndroidAPIUtils { return deviceManagementProviderService; } -// public static GCMService getGCMService() { -// PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); -// GCMService gcmService = (GCMService) ctx.getOSGiService(GCMService.class, null); -// if (gcmService == null) { -// String msg = "FCM service has not initialized."; -// log.error(msg); -// throw new IllegalStateException(msg); -// } -// return gcmService; -// } - - public static MediaType getResponseMediaType(String acceptHeader) { - MediaType responseMediaType; - if (MediaType.WILDCARD.equals(acceptHeader)) { - responseMediaType = MediaType.APPLICATION_JSON_TYPE; - } else { - responseMediaType = MediaType.valueOf(acceptHeader); - } - return responseMediaType; - } - - public static Activity getOperationResponse(List deviceIDs, Operation operation) - throws DeviceManagementException, OperationManagementException, InvalidDeviceException { - if (deviceIDs == null || deviceIDs.size() == 0) { - String errorMessage = "Device identifier list is empty"; - log.error(errorMessage); - throw new BadRequestException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); - } - DeviceIdentifier deviceIdentifier; - List deviceIdentifiers = new ArrayList<>(); - for (String deviceId : deviceIDs) { - deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); - deviceIdentifiers.add(deviceIdentifier); + public static DeviceInformationManager getDeviceInformationManagerService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceInformationManager informationManager = + (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); + if (informationManager == null) { + String msg = "Information Manager service not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } - return getDeviceManagementService().addOperation( - DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); + return informationManager; } - public static PolicyManagerService getPolicyManagerService() { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PolicyManagerService policyManagerService = (PolicyManagerService) ctx.getOSGiService( @@ -205,312 +135,4 @@ public class AndroidAPIUtils { return analyticsDataAPI; } - public static List getAllEventsForDevice(String tableName, String query) throws AnalyticsException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); - int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); - if (eventCount == 0) { - return null; - } - List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount); - List recordIds = getRecordIds(resultEntries); - AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); - Map deviceStateses = createDeviceStatusData(AnalyticsDataAPIUtil.listRecords( - analyticsDataAPI, response)); - return getSortedDeviceStateData(deviceStateses, resultEntries); - } - - private static List getRecordIds(List searchResults) { - List ids = new ArrayList(); - for (SearchResultEntry searchResult : searchResults) { - ids.add(searchResult.getId()); - } - return ids; - } - - public static Map createDeviceStatusData(List records) { - Map deviceStatuses = new HashMap(); - for (Record record : records) { - DeviceState deviceState = createDeviceStatusData(record); - deviceStatuses.put(deviceState.getId(), deviceState); - } - return deviceStatuses; - } - - private static DeviceState createDeviceStatusData(Record record) { - DeviceState deviceState = new DeviceState(); - deviceState.setId(record.getId()); - deviceState.setValues(record.getValues()); - return deviceState; - } - - public static List getSortedDeviceStateData(Map sensorDatas, - List searchResults) { - List sortedRecords = new ArrayList(); - for (SearchResultEntry searchResultEntry : searchResults) { - sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); - } - return sortedRecords; - } - - public static void updateOperation(String deviceId, Operation operation) - throws OperationManagementException, PolicyComplianceException, ApplicationManagementException { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - - if (!Operation.Status.ERROR.equals(operation.getStatus()) && - AndroidConstants.OperationCodes.MONITOR.equals(operation.getCode())) { - if (log.isDebugEnabled()) { - log.info("Received compliance status from MONITOR operation ID: " + operation.getId()); - } - getPolicyManagerService().checkPolicyCompliance(deviceIdentifier, - getComplianceFeatures(operation.getPayLoad())); - } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. - OperationCodes.APPLICATION_LIST.equals(operation.getCode())) { - if (log.isDebugEnabled()) { - log.info("Received applications list from device '" + deviceId + "'"); - } - updateApplicationList(operation, deviceIdentifier); - - } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. - OperationCodes.DEVICE_INFO.equals(operation.getCode())) { - - try { - if (log.isDebugEnabled()){ - log.debug("Operation response: " + operation.getOperationResponse()); - } - Device device = new Gson().fromJson(operation.getOperationResponse(), Device.class); - org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = convertDeviceToInfo(device); - updateDeviceInfo(deviceIdentifier, deviceInfo); - } catch (DeviceDetailsMgtException e) { - throw new OperationManagementException("Error occurred while updating the device information.", e); - } - - - } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && - AndroidConstants.OperationCodes.DEVICE_LOCATION.equals(operation.getCode())) { - try { - DeviceLocation location = new Gson().fromJson(operation.getOperationResponse(), DeviceLocation.class); - // reason for checking "location.getLatitude() != null" because when device fails to provide - // device location and send status instead, above Gson converter create new location object - // with null attributes - if (location != null && location.getLatitude() != null) { - location.setDeviceIdentifier(deviceIdentifier); - updateDeviceLocation(location); - } - } catch (DeviceDetailsMgtException e) { - throw new OperationManagementException("Error occurred while updating the device location.", e); - } - } - getDeviceManagementService().updateOperation(deviceIdentifier, operation); - } - - public static List getPendingOperations - (DeviceIdentifier deviceIdentifier) throws OperationManagementException { - - List operations; - operations = getDeviceManagementService().getPendingOperations(deviceIdentifier); - return operations; - } - - private static void updateApplicationList(Operation operation, DeviceIdentifier deviceIdentifier) - throws ApplicationManagementException { - // Parsing json string to get applications list. - if (operation.getOperationResponse() != null) { - JsonElement jsonElement = new JsonParser().parse(operation.getOperationResponse()); - JsonArray jsonArray = jsonElement.getAsJsonArray(); - Application app; - List applications = new ArrayList(jsonArray.size()); - for (JsonElement element : jsonArray) { - app = new Application(); - app.setName(element.getAsJsonObject(). - get(AndroidConstants.ApplicationProperties.NAME).getAsString()); - app.setApplicationIdentifier(element.getAsJsonObject(). - get(AndroidConstants.ApplicationProperties.IDENTIFIER).getAsString()); - app.setPlatform(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS) != null) { - app.setMemoryUsage(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS).getAsInt()); - } - if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION) != null) { - app.setVersion(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION).getAsString()); - } - if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE) != null) { - app.setActive(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE).getAsBoolean()); - } - applications.add(app); - } - getApplicationManagerService().updateApplicationListInstalledInDevice(deviceIdentifier, applications); - } else { - log.error("Operation Response is null."); - } - - } - - - private static void updateDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceInformationManager informationManager = - (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); - - informationManager.addDeviceLocation(deviceLocation); - } - - - private static void updateDeviceInfo(DeviceIdentifier deviceId, DeviceInfo deviceInfo) - throws DeviceDetailsMgtException { - - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceInformationManager informationManager = - (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); - - informationManager.addDeviceInfo(deviceId, deviceInfo); - } - - - private static org.wso2.carbon.device.mgt.common.device.details.DeviceInfo convertDeviceToInfo(Device device) { - - org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = - new org.wso2.carbon.device.mgt.common.device.details.DeviceInfo(); - if (deviceInfo.getDeviceDetailsMap() == null) { - deviceInfo.setDeviceDetailsMap(new HashMap()); - } - List props = device.getProperties(); - - for (Device.Property prop : props) { - if (Utils.getDeviceDetailsColumnNames().containsValue(prop.getName())) { - if (prop.getName().equalsIgnoreCase("DEVICE_MODEL")) { - deviceInfo.setDeviceModel(prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("VENDOR")) { - deviceInfo.setVendor(prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("OS_VERSION")) { - deviceInfo.setOsVersion(prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("IMEI")) { - deviceInfo.getDeviceDetailsMap().put("IMEI", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("IMSI")) { - deviceInfo.getDeviceDetailsMap().put("IMSI", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("MAC")) { - deviceInfo.getDeviceDetailsMap().put("mac", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("SERIAL")) { - deviceInfo.getDeviceDetailsMap().put("serial", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("OS_BUILD_DATE")) { - deviceInfo.setOsBuildDate(prop.getValue()); - } - } else { - if (prop.getName().equalsIgnoreCase("CPU_INFO")) { - deviceInfo.getDeviceDetailsMap().put("cpuUser", - getProperty(prop.getValue(), "User")); - deviceInfo.getDeviceDetailsMap().put("cpuSystem", - getProperty(prop.getValue(), "System")); - deviceInfo.getDeviceDetailsMap().put("IOW", - getProperty(prop.getValue(), "IOW")); - deviceInfo.getDeviceDetailsMap().put("IRQ", - getProperty(prop.getValue(), "IRQ")); - } else if (prop.getName().equalsIgnoreCase("RAM_INFO")) { - deviceInfo.setTotalRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "TOTAL_MEMORY"))); - deviceInfo.setAvailableRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "AVAILABLE_MEMORY"))); - - deviceInfo.getDeviceDetailsMap().put("ramThreshold", - getProperty(prop.getValue(), "THRESHOLD")); - deviceInfo.getDeviceDetailsMap().put("ramLowMemory", - getProperty(prop.getValue(), "LOW_MEMORY")); - } else if (prop.getName().equalsIgnoreCase("BATTERY_INFO")) { - deviceInfo.setPluggedIn(Boolean.parseBoolean(getProperty(prop.getValue(), "PLUGGED"))); - - deviceInfo.getDeviceDetailsMap().put("batteryLevel", - getProperty(prop.getValue(), "BATTERY_LEVEL")); - deviceInfo.getDeviceDetailsMap().put("batteryScale", - getProperty(prop.getValue(), "SCALE")); - deviceInfo.getDeviceDetailsMap().put("batteryVoltage", - getProperty(prop.getValue(), "BATTERY_VOLTAGE")); - deviceInfo.getDeviceDetailsMap().put("batteryTemperature", - getProperty(prop.getValue(), "TEMPERATURE")); - deviceInfo.getDeviceDetailsMap().put("batteryCurrentTemperature", - getProperty(prop.getValue(), "CURRENT_AVERAGE")); - deviceInfo.getDeviceDetailsMap().put("batteryTechnology", - getProperty(prop.getValue(), "TECHNOLOGY")); - deviceInfo.getDeviceDetailsMap().put("batteryHealth", - getProperty(prop.getValue(), "HEALTH")); - deviceInfo.getDeviceDetailsMap().put("batteryStatus", - getProperty(prop.getValue(), "STATUS")); - } else if (prop.getName().equalsIgnoreCase("NETWORK_INFO")) { - deviceInfo.setSsid(getProperty(prop.getValue(), "WIFI_SSID")); - deviceInfo.setConnectionType(getProperty(prop.getValue(), "CONNECTION_TYPE")); - - deviceInfo.getDeviceDetailsMap().put("mobileSignalStrength", - getProperty(prop.getValue(), "MOBILE_SIGNAL_STRENGTH")); - deviceInfo.getDeviceDetailsMap().put("wifiSignalStrength", - getProperty(prop.getValue(), "WIFI_SIGNAL_STRENGTH")); - } else if (prop.getName().equalsIgnoreCase("DEVICE_INFO")) { - deviceInfo.setBatteryLevel(Double.parseDouble( - getProperty(prop.getValue(), "BATTERY_LEVEL"))); - deviceInfo.setInternalTotalMemory(Double.parseDouble( - getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY"))); - deviceInfo.setInternalAvailableMemory(Double.parseDouble( - getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY"))); - deviceInfo.setExternalTotalMemory(Double.parseDouble( - getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY"))); - deviceInfo.setExternalAvailableMemory(Double.parseDouble( - getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY"))); - - deviceInfo.getDeviceDetailsMap().put("encryptionEnabled", - getProperty(prop.getValue(), "ENCRYPTION_ENABLED")); - deviceInfo.getDeviceDetailsMap().put("passcodeEnabled", - getProperty(prop.getValue(), "PASSCODE_ENABLED")); - deviceInfo.getDeviceDetailsMap().put("operator", - getProperty(prop.getValue(), "OPERATOR")); - deviceInfo.getDeviceDetailsMap().put("PhoneNumber", - getProperty(prop.getValue(), "PHONE_NUMBER")); - } - } - } - return deviceInfo; - } - - private static String getProperty(String a, String needed) { - - JsonElement jsonElement = new JsonParser().parse(a); - JsonArray jsonArray = jsonElement.getAsJsonArray(); - boolean exist = false; - for (JsonElement element : jsonArray) { - // if (((JsonObject) element).entrySet().iterator().next().getValue().getAsString().equalsIgnoreCase(needed)); - for (Map.Entry ob : ((JsonObject) element).entrySet()) { - JsonElement val = ob.getValue(); - if (val != null && !val.isJsonNull()) { - if (exist) { - return val.getAsString().replace("%", ""); - } - if (val.getAsString().equalsIgnoreCase(needed)) { - exist = true; - } - } - } - } - return ""; - } - - private static List getComplianceFeatures(Object compliancePayload) throws PolicyComplianceException { - String compliancePayloadString = new Gson().toJson(compliancePayload); - if (compliancePayload == null) { - return null; - } - // Parsing json string to get compliance features. - JsonElement jsonElement; - if (compliancePayloadString instanceof String) { - jsonElement = new JsonParser().parse(compliancePayloadString); - } else { - throw new PolicyComplianceException("Invalid policy compliance payload"); - } - - JsonArray jsonArray = jsonElement.getAsJsonArray(); - Gson gson = new Gson(); - ComplianceFeature complianceFeature; - List complianceFeatures = new ArrayList(jsonArray.size()); - - for (JsonElement element : jsonArray) { - complianceFeature = gson.fromJson(element, ComplianceFeature.class); - complianceFeatures.add(complianceFeature); - } - return complianceFeatures; - } } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java index 61a4c5183..b56071121 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java @@ -18,15 +18,49 @@ package org.wso2.carbon.mdm.services.android.util; -import org.apache.commons.lang.StringUtils; -import org.wso2.carbon.device.mgt.common.*; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; +import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; +import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; +import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; +import org.wso2.carbon.analytics.datasource.commons.Record; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; +import org.wso2.carbon.mdm.services.android.bean.DeviceState; import org.wso2.carbon.mdm.services.android.bean.ErrorListItem; import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; import org.wso2.carbon.mdm.services.android.exception.BadRequestException; import javax.validation.ConstraintViolation; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; /** @@ -34,63 +68,347 @@ import java.util.Set; */ public class AndroidDeviceUtils { - private static final String COMMA_SEPARATION_PATTERN = ", "; + private static Log log = LogFactory.getLog(AndroidDeviceUtils.class); - public DeviceIDHolder validateDeviceIdentifiers(List deviceIDs) { + private AndroidDeviceUtils(){ + throw new IllegalStateException("Utility class"); + } + + public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { + Device device = AndroidAPIUtils.getDeviceManagementService(). + getDevice(deviceIdentifier, false); + return !(device == null || device.getDeviceIdentifier() == null || + device.getDeviceIdentifier().isEmpty() || + device.getEnrolmentInfo() == null || + EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())); + } + + public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(deviceId); + identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + return identifier; + } + + public static Activity getOperationResponse(List deviceIDs, Operation operation) + throws OperationManagementException, InvalidDeviceException { + if (deviceIDs == null || deviceIDs.isEmpty()) { + String errorMessage = "Device identifier list is empty"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + DeviceIdentifier deviceIdentifier; + List deviceIdentifiers = new ArrayList<>(); + for (String deviceId : deviceIDs) { + deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); + deviceIdentifiers.add(deviceIdentifier); + } + return AndroidAPIUtils.getDeviceManagementService().addOperation( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); + } - List errorDeviceIdList = new ArrayList(); - List validDeviceIDList = new ArrayList(); + public static List getAllEventsForDevice(String tableName, String query) throws AnalyticsException { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + AnalyticsDataAPI analyticsDataAPI = AndroidAPIUtils.getAnalyticsDataAPI(); + int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); + if (eventCount == 0) { + return null; + } + List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount); + List recordIds = getRecordIds(resultEntries); + AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); + Map deviceStateses = createDeviceStatusData(AnalyticsDataAPIUtil.listRecords( + analyticsDataAPI, response)); + return getSortedDeviceStateData(deviceStateses, resultEntries); + } - int deviceIDCounter = 0; - for (String deviceID : deviceIDs) { + private static List getRecordIds(List searchResults) { + List ids = new ArrayList<>(); + for (SearchResultEntry searchResult : searchResults) { + ids.add(searchResult.getId()); + } + return ids; + } - deviceIDCounter++; + public static Map createDeviceStatusData(List records) { + Map deviceStatuses = new HashMap<>(); + for (Record record : records) { + DeviceState deviceState = createDeviceStatusData(record); + deviceStatuses.put(deviceState.getId(), deviceState); + } + return deviceStatuses; + } - if (deviceID == null || deviceID.isEmpty()) { - errorDeviceIdList.add(String.format(AndroidConstants.DeviceConstants.DEVICE_ID_NOT_FOUND, - deviceIDCounter)); - continue; + private static DeviceState createDeviceStatusData(Record record) { + DeviceState deviceState = new DeviceState(); + deviceState.setId(record.getId()); + deviceState.setValues(record.getValues()); + return deviceState; + } + + public static List getSortedDeviceStateData(Map sensorDatas, + List searchResults) { + List sortedRecords = new ArrayList<>(); + for (SearchResultEntry searchResultEntry : searchResults) { + sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); + } + return sortedRecords; + } + + public static void updateOperation(String deviceId, Operation operation) + throws OperationManagementException, PolicyComplianceException, ApplicationManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + + if (!Operation.Status.ERROR.equals(operation.getStatus()) && + AndroidConstants.OperationCodes.MONITOR.equals(operation.getCode())) { + if (log.isDebugEnabled()) { + log.info("Received compliance status from MONITOR operation ID: " + operation.getId()); + } + AndroidAPIUtils.getPolicyManagerService().checkPolicyCompliance(deviceIdentifier, + getComplianceFeatures(operation.getPayLoad())); + } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. + OperationCodes.APPLICATION_LIST.equals(operation.getCode())) { + if (log.isDebugEnabled()) { + log.info("Received applications list from device '" + deviceId + "'"); } + updateApplicationList(operation, deviceIdentifier); + + } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. + OperationCodes.DEVICE_INFO.equals(operation.getCode())) { try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceID); - deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes. - MOBILE_DEVICE_TYPE_ANDROID); - - if (isValidDeviceIdentifier(deviceIdentifier)) { - validDeviceIDList.add(deviceIdentifier); - } else { - errorDeviceIdList.add(String.format(AndroidConstants.DeviceConstants. - DEVICE_ID_NOT_FOUND, deviceID)); + if (log.isDebugEnabled()){ + log.debug("Operation response: " + operation.getOperationResponse()); + } + Device device = new Gson().fromJson(operation.getOperationResponse(), Device.class); + org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = convertDeviceToInfo(device); + updateDeviceInfo(deviceIdentifier, deviceInfo); + } catch (DeviceDetailsMgtException e) { + throw new OperationManagementException("Error occurred while updating the device information.", e); + } + + + } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && + AndroidConstants.OperationCodes.DEVICE_LOCATION.equals(operation.getCode())) { + try { + DeviceLocation location = new Gson().fromJson(operation.getOperationResponse(), DeviceLocation.class); + // reason for checking "location.getLatitude() != null" because when device fails to provide + // device location and send status instead, above Gson converter create new location object + // with null attributes + if (location != null && location.getLatitude() != null) { + location.setDeviceIdentifier(deviceIdentifier); + updateDeviceLocation(location); + } + } catch (DeviceDetailsMgtException e) { + throw new OperationManagementException("Error occurred while updating the device location.", e); + } + } + AndroidAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation); + } + + public static List getPendingOperations + (DeviceIdentifier deviceIdentifier) throws OperationManagementException { + + List operations; + operations = AndroidAPIUtils.getDeviceManagementService().getPendingOperations(deviceIdentifier); + return operations; + } + + private static void updateApplicationList(Operation operation, DeviceIdentifier deviceIdentifier) + throws ApplicationManagementException { + // Parsing json string to get applications list. + if (operation.getOperationResponse() != null) { + JsonElement jsonElement = new JsonParser().parse(operation.getOperationResponse()); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Application app; + List applications = new ArrayList<>(jsonArray.size()); + for (JsonElement element : jsonArray) { + app = new Application(); + app.setName(element.getAsJsonObject(). + get(AndroidConstants.ApplicationProperties.NAME).getAsString()); + app.setApplicationIdentifier(element.getAsJsonObject(). + get(AndroidConstants.ApplicationProperties.IDENTIFIER).getAsString()); + app.setPlatform(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS) != null) { + app.setMemoryUsage(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS).getAsInt()); + } + if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION) != null) { + app.setVersion(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION).getAsString()); } - } catch (DeviceManagementException e) { - errorDeviceIdList.add(String.format(AndroidConstants.DeviceConstants.DEVICE_ID_SERVICE_NOT_FOUND, - deviceIDCounter)); + if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE) != null) { + app.setActive(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE).getAsBoolean()); + } + applications.add(app); } + AndroidAPIUtils.getApplicationManagerService().updateApplicationListInstalledInDevice(deviceIdentifier, applications); + } else { + log.error("Operation Response is null."); } - DeviceIDHolder deviceIDHolder = new DeviceIDHolder(); - deviceIDHolder.setValidDeviceIDList(validDeviceIDList); - deviceIDHolder.setErrorDeviceIdList(errorDeviceIdList); + } + + private static void updateDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceInformationManager informationManager = + (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); - return deviceIDHolder; + informationManager.addDeviceLocation(deviceLocation); } - public String convertErrorMapIntoErrorMessage(List errorDeviceIdList) { - return StringUtils.join(errorDeviceIdList.iterator(), COMMA_SEPARATION_PATTERN); + private static void updateDeviceInfo(DeviceIdentifier deviceId, DeviceInfo deviceInfo) + throws DeviceDetailsMgtException { + DeviceInformationManager informationManager = AndroidAPIUtils.getDeviceInformationManagerService(); + informationManager.addDeviceInfo(deviceId, deviceInfo); } - public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { - Device device = AndroidAPIUtils.getDeviceManagementService(). - getDevice(deviceIdentifier, false); - if (device == null || device.getDeviceIdentifier() == null || - device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) { - return false; - } else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) { - return false; + private static org.wso2.carbon.device.mgt.common.device.details.DeviceInfo convertDeviceToInfo(Device device) { + + org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = + new org.wso2.carbon.device.mgt.common.device.details.DeviceInfo(); + if (deviceInfo.getDeviceDetailsMap() == null) { + deviceInfo.setDeviceDetailsMap(new HashMap<>()); } - return true; + List props = device.getProperties(); + + for (Device.Property prop : props) { + if (Utils.getDeviceDetailsColumnNames().containsValue(prop.getName())) { + if (prop.getName().equalsIgnoreCase("DEVICE_MODEL")) { + deviceInfo.setDeviceModel(prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("VENDOR")) { + deviceInfo.setVendor(prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("OS_VERSION")) { + deviceInfo.setOsVersion(prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("IMEI")) { + deviceInfo.getDeviceDetailsMap().put("IMEI", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("IMSI")) { + deviceInfo.getDeviceDetailsMap().put("IMSI", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("MAC")) { + deviceInfo.getDeviceDetailsMap().put("mac", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("SERIAL")) { + deviceInfo.getDeviceDetailsMap().put("serial", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("OS_BUILD_DATE")) { + deviceInfo.setOsBuildDate(prop.getValue()); + } + } else { + if (prop.getName().equalsIgnoreCase("CPU_INFO")) { + deviceInfo.getDeviceDetailsMap().put("cpuUser", + getProperty(prop.getValue(), "User")); + deviceInfo.getDeviceDetailsMap().put("cpuSystem", + getProperty(prop.getValue(), "System")); + deviceInfo.getDeviceDetailsMap().put("IOW", + getProperty(prop.getValue(), "IOW")); + deviceInfo.getDeviceDetailsMap().put("IRQ", + getProperty(prop.getValue(), "IRQ")); + } else if (prop.getName().equalsIgnoreCase("RAM_INFO")) { + deviceInfo.setTotalRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "TOTAL_MEMORY"))); + deviceInfo.setAvailableRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "AVAILABLE_MEMORY"))); + + deviceInfo.getDeviceDetailsMap().put("ramThreshold", + getProperty(prop.getValue(), "THRESHOLD")); + deviceInfo.getDeviceDetailsMap().put("ramLowMemory", + getProperty(prop.getValue(), "LOW_MEMORY")); + } else if (prop.getName().equalsIgnoreCase("BATTERY_INFO")) { + deviceInfo.setPluggedIn(Boolean.parseBoolean(getProperty(prop.getValue(), "PLUGGED"))); + + deviceInfo.getDeviceDetailsMap().put("batteryLevel", + getProperty(prop.getValue(), "BATTERY_LEVEL")); + deviceInfo.getDeviceDetailsMap().put("batteryScale", + getProperty(prop.getValue(), "SCALE")); + deviceInfo.getDeviceDetailsMap().put("batteryVoltage", + getProperty(prop.getValue(), "BATTERY_VOLTAGE")); + deviceInfo.getDeviceDetailsMap().put("batteryTemperature", + getProperty(prop.getValue(), "TEMPERATURE")); + deviceInfo.getDeviceDetailsMap().put("batteryCurrentTemperature", + getProperty(prop.getValue(), "CURRENT_AVERAGE")); + deviceInfo.getDeviceDetailsMap().put("batteryTechnology", + getProperty(prop.getValue(), "TECHNOLOGY")); + deviceInfo.getDeviceDetailsMap().put("batteryHealth", + getProperty(prop.getValue(), "HEALTH")); + deviceInfo.getDeviceDetailsMap().put("batteryStatus", + getProperty(prop.getValue(), "STATUS")); + } else if (prop.getName().equalsIgnoreCase("NETWORK_INFO")) { + deviceInfo.setSsid(getProperty(prop.getValue(), "WIFI_SSID")); + deviceInfo.setConnectionType(getProperty(prop.getValue(), "CONNECTION_TYPE")); + + deviceInfo.getDeviceDetailsMap().put("mobileSignalStrength", + getProperty(prop.getValue(), "MOBILE_SIGNAL_STRENGTH")); + deviceInfo.getDeviceDetailsMap().put("wifiSignalStrength", + getProperty(prop.getValue(), "WIFI_SIGNAL_STRENGTH")); + } else if (prop.getName().equalsIgnoreCase("DEVICE_INFO")) { + deviceInfo.setBatteryLevel(Double.parseDouble( + getProperty(prop.getValue(), "BATTERY_LEVEL"))); + deviceInfo.setInternalTotalMemory(Double.parseDouble( + getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY"))); + deviceInfo.setInternalAvailableMemory(Double.parseDouble( + getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY"))); + deviceInfo.setExternalTotalMemory(Double.parseDouble( + getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY"))); + deviceInfo.setExternalAvailableMemory(Double.parseDouble( + getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY"))); + + deviceInfo.getDeviceDetailsMap().put("encryptionEnabled", + getProperty(prop.getValue(), "ENCRYPTION_ENABLED")); + deviceInfo.getDeviceDetailsMap().put("passcodeEnabled", + getProperty(prop.getValue(), "PASSCODE_ENABLED")); + deviceInfo.getDeviceDetailsMap().put("operator", + getProperty(prop.getValue(), "OPERATOR")); + deviceInfo.getDeviceDetailsMap().put("PhoneNumber", + getProperty(prop.getValue(), "PHONE_NUMBER")); + } + } + } + return deviceInfo; + } + + private static String getProperty(String a, String needed) { + + JsonElement jsonElement = new JsonParser().parse(a); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + boolean exist = false; + for (JsonElement element : jsonArray) { + for (Map.Entry ob : ((JsonObject) element).entrySet()) { + JsonElement val = ob.getValue(); + if (val != null && !val.isJsonNull()) { + if (exist) { + return val.getAsString().replace("%", ""); + } + if (val.getAsString().equalsIgnoreCase(needed)) { + exist = true; + } + } + } + } + return ""; + } + + private static List getComplianceFeatures(Object compliancePayload) throws PolicyComplianceException { + String compliancePayloadString = new Gson().toJson(compliancePayload); + if (compliancePayload == null) { + return null; + } + // Parsing json string to get compliance features. + JsonElement jsonElement; + if (compliancePayloadString instanceof String) { + jsonElement = new JsonParser().parse(compliancePayloadString); + } else { + throw new PolicyComplianceException("Invalid policy compliance payload"); + } + + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Gson gson = new Gson(); + ComplianceFeature complianceFeature; + List complianceFeatures = new ArrayList(jsonArray.size()); + + for (JsonElement element : jsonArray) { + complianceFeature = gson.fromJson(element, ComplianceFeature.class); + complianceFeatures.add(complianceFeature); + } + return complianceFeatures; } /** @@ -107,9 +425,10 @@ public class AndroidDeviceUtils { /** * Returns generic ErrorResponse. + * * @param message specific error message - * @param code - * @param description + * @param code error code + * @param description error description * @return generic Response with error specific details. */ public static ErrorResponse getErrorResponse(String message, Long code, String description) {