From 215b8fb63061971189668bab2f7699a98cdb274b Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Thu, 27 Aug 2020 03:07:51 +0530 Subject: [PATCH 01/10] Fix formatting issues --- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 103 +----------------- 1 file changed, 2 insertions(+), 101 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 1ac0f519d1..e39f061a65 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -89,7 +89,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public Policy addPolicy(Policy policy) throws PolicyManagementException { - try { PolicyManagementDAOFactory.beginTransaction(); if (policy.getProfile() != null && policy.getProfile().getProfileId() == 0) { @@ -107,19 +106,15 @@ public class PolicyManagerImpl implements PolicyManager { if (policy.getUsers() != null) { policyDAO.addPolicyToUser(policy.getUsers(), policy); } - if (policy.getRoles() != null) { policyDAO.addPolicyToRole(policy.getRoles(), policy); } - if (policy.getDevices() != null) { policyDAO.addPolicyToDevice(policy.getDevices(), policy); } - if (policy.getDeviceGroups() != null && !policy.getDeviceGroups().isEmpty()) { policyDAO.addDeviceGroupsToPolicy(policy); } - if (policy.getPolicyCriterias() != null) { List criteria = policy.getPolicyCriterias(); for (PolicyCriterion criterion : criteria) { @@ -139,7 +134,6 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyCriteria(policy); policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); } - if (policy.getCorrectiveActions() != null && !policy.getCorrectiveActions().isEmpty()) { if (log.isDebugEnabled()) { log.debug("Adding corrective actions for policy " + policy.getPolicyName() + @@ -147,17 +141,14 @@ public class PolicyManagerImpl implements PolicyManager { } policyDAO.addCorrectiveActionsOfPolicy(policy.getCorrectiveActions(), policy.getId()); } - if (policy.isActive()) { policyDAO.activatePolicy(policy.getId()); } PolicyManagementDAOFactory.commitTransaction(); - } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while adding the policy (" + policy.getId() + " - " + policy.getPolicyName() + ")", e); - } catch (ProfileManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while adding the profile related to policy (" + @@ -174,7 +165,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public Policy updatePolicy(Policy policy) throws PolicyManagementException { - try { // Previous policy needs to be obtained before beginning the transaction Policy previousPolicy = this.getPolicy(policy.getId()); @@ -183,15 +173,12 @@ public class PolicyManagerImpl implements PolicyManager { // This will keep track of the policies updated. policyDAO.recordUpdatedPolicy(policy); - List existingFeaturesList = new ArrayList<>(); List newFeaturesList = new ArrayList<>(); List featuresToDelete = new ArrayList<>(); List temp = new ArrayList<>(); List updateDFes = new ArrayList<>(); - List updatedFeatureList = policy.getProfile().getProfileFeaturesList(); - List existingProfileFeaturesList = previousPolicy.getProfile().getProfileFeaturesList(); // Checks for the existing features @@ -232,27 +219,20 @@ public class PolicyManagerImpl implements PolicyManager { if (!newFeaturesList.isEmpty()) { featureDAO.addProfileFeatures(newFeaturesList, profileId); } - if (!featuresToDelete.isEmpty()) { for (ProfileFeature pf : featuresToDelete) featureDAO.deleteProfileFeatures(pf.getId()); } - policyDAO.deleteCriteriaAndDeviceRelatedConfigs(policy.getId()); - - if (policy.getUsers() != null) { policyDAO.updateUserOfPolicy(policy.getUsers(), previousPolicy); } - if (policy.getRoles() != null) { policyDAO.updateRolesOfPolicy(policy.getRoles(), previousPolicy); } - if (policy.getDevices() != null) { policyDAO.addPolicyToDevice(policy.getDevices(), previousPolicy); } - if (policy.getDeviceGroups() != null && !policy.getDeviceGroups().isEmpty()) { policyDAO.addDeviceGroupsToPolicy(policy); } @@ -308,19 +288,15 @@ public class PolicyManagerImpl implements PolicyManager { log.debug("Updating corrective actions for policy " + policy.getPolicyName() + " having policy id " + policy.getId()); } - if (!correctiveActionsToUpdate.isEmpty()) { policyDAO.updateCorrectiveActionsOfPolicy(correctiveActionsToUpdate, previousPolicy.getId()); } - if (!correctiveActionsToAdd.isEmpty()) { policyDAO.addCorrectiveActionsOfPolicy(correctiveActionsToAdd, previousPolicy.getId()); } - if (!correctiveActionsToDelete.isEmpty()) { policyDAO.deleteCorrectiveActionsOfPolicy(correctiveActionsToDelete, previousPolicy.getId()); } - PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); @@ -345,7 +321,6 @@ public class PolicyManagerImpl implements PolicyManager { public boolean updatePolicyPriorities(List policies) throws PolicyManagementException { boolean bool; try { -// List existingPolicies = this.getPolicies(); List existingPolicies; if (policyConfiguration.getCacheEnable()) { existingPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); @@ -405,7 +380,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean deletePolicy(int policyId) throws PolicyManagementException { boolean bool; - List policies = this.getPolicies(); Policy pol = null; for (Policy p : policies) { @@ -433,7 +407,6 @@ public class PolicyManagerImpl implements PolicyManager { } featureDAO.deleteFeaturesOfProfile(policy.getProfileId()); - profileDAO.deleteProfile(policy.getProfileId()); PolicyManagementDAOFactory.commitTransaction(); return bool; @@ -491,7 +464,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException { - List deviceList = new ArrayList<>(); DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder .getInstance().getDeviceManagementService(); @@ -566,7 +538,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public Policy addPolicyToUser(List usernameList, Policy policy) throws PolicyManagementException { - try { PolicyManagementDAOFactory.beginTransaction(); if (policy.getId() == 0) { @@ -598,22 +569,17 @@ public class PolicyManagerImpl implements PolicyManager { @Override public Policy getPolicyByProfileID(int profileId) throws PolicyManagementException { - Policy policy; Profile profile; List deviceList; List roleNames; - try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicyByProfileID(profileId); - roleNames = policyDAO.getPolicyAppliedRoles(policy.getId()); profile = profileDAO.getProfile(profileId); policy.setProfile(profile); policy.setRoles(roleNames); - - } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to profile ID (" + profileId + ")", e); @@ -634,7 +600,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public Policy getPolicy(int policyId) throws PolicyManagementException { - Policy policy; List deviceList; List roleNames; @@ -642,13 +607,8 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicy(policyId); - roleNames = policyDAO.getPolicyAppliedRoles(policyId); userNames = policyDAO.getPolicyAppliedUsers(policyId); - - //Profile profile = profileDAO.getProfile(policy.getProfileId()); - - policy.setRoles(roleNames); policy.setUsers(userNames); @@ -657,18 +617,11 @@ public class PolicyManagerImpl implements PolicyManager { " having policy id " + policy.getId()); } policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policyId)); - } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" + policyId + ")", e); -// } catch (ProfileManagerDAOException e) { -// throw new PolicyManagementException("Error occurred while getting the profile related to policy ID (" + -// policyId + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); -// } catch (ProfileManagementException e) { -// throw new PolicyManagementException("Error occurred while getting the profile related to policy ID (" + -// policyId + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -678,24 +631,17 @@ public class PolicyManagerImpl implements PolicyManager { policy.setDevices(deviceList); try { - // PolicyManagementDAOFactory.openConnection(); Profile profile = profileManager.getProfile(policy.getProfileId()); policy.setProfile(profile); } catch (ProfileManagementException e) { throw new PolicyManagementException("Error occurred while getting the profile related to policy ID (" + policyId + ")", e); -// } catch (SQLException e) { -// throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); -// } finally { -// PolicyManagementDAOFactory.closeConnection(); } - return policy; } @Override public List getPolicies() throws PolicyManagementException { - List policyList; List profileList; try { @@ -718,20 +664,16 @@ public class PolicyManagerImpl implements PolicyManager { } // Following is done because connection close has been implemented in every method. - for (Policy policy : policyList) { policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId())); } - return policyList; } @Override public List getPoliciesOfDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { - List policyIdList; List policies = new ArrayList<>(); - DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder .getInstance().getDeviceManagementService(); Device device; @@ -754,7 +696,6 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.closeConnection(); } -// List tempPolicyList = this.getPolicies(); List tempPolicyList; if (policyConfiguration.getCacheEnable()) { tempPolicyList = PolicyCacheManagerImpl.getInstance().getAllPolicies(); @@ -777,9 +718,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public List getPoliciesOfDeviceType(String deviceTypeName) throws PolicyManagementException { List policies = new ArrayList<>(); -// try { - // List profileList = profileManager.getProfilesOfDeviceType(deviceTypeName); -// List allPolicies = this.getPolicies(); List allPolicies; if (policyConfiguration.getCacheEnable()) { allPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); @@ -792,28 +730,14 @@ public class PolicyManagerImpl implements PolicyManager { policies.add(policy); } } - -// for (Profile profile : profileList) { -// for (Policy policy : allPolicies) { -// if (policy.getProfileId() == profile.getProfileId()) { -// policy.setProfile(profile); -// policies.add(policy); -// } -// } -// } Collections.sort(policies); -// } catch (ProfileManagementException e) { -// throw new PolicyManagementException("Error occurred while getting all the profile features.", e); -// } return policies; } @Override public List getPoliciesOfRole(String roleName) throws PolicyManagementException { - List policies = new ArrayList<>(); List policyIdList; - try { PolicyManagementDAOFactory.openConnection(); policyIdList = policyDAO.getPolicyOfRole(roleName); @@ -825,7 +749,6 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.closeConnection(); } -// List tempPolicyList = this.getPolicies(); List tempPolicyList; if (policyConfiguration.getCacheEnable()) { tempPolicyList = PolicyCacheManagerImpl.getInstance().getAllPolicies(); @@ -846,10 +769,8 @@ public class PolicyManagerImpl implements PolicyManager { @Override public List getPoliciesOfUser(String username) throws PolicyManagementException { - List policies = new ArrayList<>(); List policyIdList; - try { PolicyManagementDAOFactory.openConnection(); policyIdList = policyDAO.getPolicyOfUser(username); @@ -860,7 +781,6 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } -// List tempPolicyList = this.getPolicies(); List tempPolicyList; if (policyConfiguration.getCacheEnable()) { tempPolicyList = PolicyCacheManagerImpl.getInstance().getAllPolicies(); @@ -881,7 +801,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public List getPolicyAppliedDevicesIds(int policyId) throws PolicyManagementException { - List deviceList = new ArrayList<>(); List deviceIds; DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder @@ -955,17 +874,11 @@ public class PolicyManagerImpl implements PolicyManager { @Override public UpdatedPolicyDeviceListBean applyChangesMadeToPolicies() throws PolicyManagementException { - List changedDeviceTypes = new ArrayList<>(); List updatedPolicies = new ArrayList<>(); List updatedPolicyIds = new ArrayList<>(); boolean transactionDone = false; try { - //HashMap map = policyDAO.getUpdatedPolicyIdandDeviceTypeId(); -// List activePolicies = new ArrayList<>(); -// List inactivePolicies = new ArrayList<>(); - -// List allPolicies = this.getPolicies(); List allPolicies; if (policyConfiguration.getCacheEnable()) { allPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); @@ -980,11 +893,6 @@ public class PolicyManagerImpl implements PolicyManager { changedDeviceTypes.add(policy.getProfile().getDeviceType()); } } -// if (policy.isActive()) { -// activePolicies.add(policy); -// } else { -// inactivePolicies.add(policy); -// } } PolicyManagementDAOFactory.beginTransaction(); transactionDone = true; @@ -1068,7 +976,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { - boolean exist; DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder .getInstance().getDeviceManagementService(); @@ -1095,7 +1002,6 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean setPolicyApplied(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { - DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder .getInstance().getDeviceManagementService(); Device device; @@ -1105,7 +1011,6 @@ public class PolicyManagerImpl implements PolicyManager { throw new PolicyManagementException("Error occurred while getting the device details (" + deviceIdentifier.getId() + ")", e); } - try { PolicyManagementDAOFactory.openConnection(); policyDAO.setPolicyApplied(device.getId(), device.getEnrolmentInfo().getId()); @@ -1159,7 +1064,6 @@ public class PolicyManagerImpl implements PolicyManager { public Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException { Policy policy; try { - //int policyId = policyDAO.getAppliedPolicyId(device.getId()); PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getAppliedPolicy(device.getId(), device.getEnrolmentInfo().getId()); } catch (PolicyManagerDAOException e) { @@ -1211,8 +1115,8 @@ public class PolicyManagerImpl implements PolicyManager { private void addPolicyRevokeOperation(List deviceIdentifiers) throws PolicyManagementException { try { - String type = null; - if (deviceIdentifiers.size() > 0) { + String type; + if (!deviceIdentifiers.isEmpty()) { type = deviceIdentifiers.get(0).getType(); PolicyManagementDataHolder.getInstance().getDeviceManagementService().addOperation(type, this.getPolicyRevokeOperation(), deviceIdentifiers); @@ -1264,11 +1168,9 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } - for (Policy policy : policyList) { policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId())); } - return policyList; } @@ -1283,7 +1185,6 @@ public class PolicyManagerImpl implements PolicyManager { policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId())); policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId())); policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId())); - List deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId()); if (!deviceGroupWrappers.isEmpty()) { deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers); From ef8af6b4546a6c94aba034eb4711a90d4dda7974 Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Thu, 27 Aug 2020 05:29:24 +0530 Subject: [PATCH 02/10] Fix APPM custom permission loading issue --- .../mgt/core/impl/AppmDataHandlerImpl.java | 3 --- .../core/lifecycle/LifecycleStateManager.java | 5 +++-- .../src/main/resources/conf/application-mgt.xml | 16 ++++++++-------- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/AppmDataHandlerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/AppmDataHandlerImpl.java index 46763dae2d..40c3de260c 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/AppmDataHandlerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/AppmDataHandlerImpl.java @@ -17,21 +17,18 @@ package org.wso2.carbon.device.application.mgt.core.impl; -import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.config.LifecycleState; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException; import org.wso2.carbon.device.application.mgt.core.util.APIUtil; -import org.wso2.carbon.device.application.mgt.core.util.DAOUtil; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java index 612c055867..e0f9a2f796 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java @@ -38,7 +38,7 @@ import java.util.Map; public class LifecycleStateManager { private Map lifecycleStates; - private static Log log = LogFactory.getLog(LifecycleStateManager.class); + private static final Log log = LogFactory.getLog(LifecycleStateManager.class); public void init(List states) throws LifecycleManagementException { lifecycleStates = new HashMap<>(); @@ -48,7 +48,8 @@ public class LifecycleStateManager { } lifecycleStates.put(lifecycleState.getName().toUpperCase(), lifecycleState); try { - PermissionUtils.putPermission(lifecycleState.getPermission()); + PermissionUtils + .putPermission(PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + lifecycleState.getPermission()); } catch (PermissionManagementException e) { String msg = "Error when adding permission " + lifecycleState.getPermission() + " related to the " + "state: " + lifecycleState.getName(); diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml index aa48301903..d0d02a058a 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml @@ -77,13 +77,13 @@ true true true - /permission/admin/app-mgt/life-cycle/application/create + /app-mgt/life-cycle/application/create In-Review - /permission/admin/app-mgt/life-cycle/application/review + /app-mgt/life-cycle/application/review Rejected Approved @@ -91,7 +91,7 @@ - /permission/admin/app-mgt/life-cycle/application/approve + /app-mgt/life-cycle/application/approve In-Review Published @@ -99,28 +99,28 @@ true - /permission/admin/app-mgt/life-cycle/application/reject + /app-mgt/life-cycle/application/reject In-Review true - /permission/admin/app-mgt/life-cycle/application/publish + /app-mgt/life-cycle/application/publish Blocked Deprecated - /permission/admin/app-mgt/life-cycle/application/block + /app-mgt/life-cycle/application/block Published Deprecated - /permission/admin/app-mgt/life-cycle/application/deprecate + /app-mgt/life-cycle/application/deprecate Published Retired @@ -128,7 +128,7 @@ true - /permission/admin/app-mgt/life-cycle/application/retire + /app-mgt/life-cycle/application/retire From 7558f82a76bafc041902f8ffa3b985616bce829d Mon Sep 17 00:00:00 2001 From: Saad Sahibjan Date: Thu, 27 Aug 2020 16:37:52 +0530 Subject: [PATCH 03/10] Add error log for backend policy validation failure --- .../mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index a9fc47691e..d58c4ce870 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -83,6 +83,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { .validatePolicyDetails(policyWrapper); // validation failure results; if (!features.isEmpty()) { + log.error("Policy feature/s validation failed."); return Response.status(Response.Status.BAD_REQUEST).entity(features).build(); } PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); @@ -223,6 +224,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { .validatePolicyDetails(policyWrapper); // validation failure results; if (!features.isEmpty()) { + log.error("Policy feature/s validation failed."); return Response.status(Response.Status.BAD_REQUEST).entity(features).build(); } PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); @@ -480,6 +482,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { = RequestValidationUtil.validateProfileFeatures(profileFeaturesList); // validation failure results; if (!features.isEmpty()) { + log.error("Policy feature/s validation failed."); return Response.status(Response.Status.BAD_REQUEST).entity(features).build(); } return Response.status(Response.Status.OK).entity("Valid request").build(); From d9c12bfca6c618ced9c106e6a6faa3a7d09be113 Mon Sep 17 00:00:00 2001 From: anjula-sack Date: Wed, 24 Jun 2020 21:09:23 +0530 Subject: [PATCH 04/10] Remove duplicated EsLint dependencies from APPM publisher --- .../react-app/package.json | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json index 49eae0fc0d..f929dfc1e9 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json @@ -17,14 +17,9 @@ "acorn": "^6.2.0", "antd": "^4.0.0", "axios": "^0.19.0", - "babel-eslint": "^9.0.0", "d3": "^5.9.7", "dagre": "^0.8.4", "entgra-icons-react": "^1.0.0", - "eslint": "^5.16.0", - "eslint-plugin-import": "^2.18.2", - "eslint-plugin-jsx-a11y": "^6.2.3", - "eslint-plugin-react": "^7.16.0", "fetch": "^1.1.0", "imagemin": "^6.1.0", "keymirror": "^0.1.1", @@ -64,7 +59,9 @@ "eslint": "^5.16.0", "eslint-config-prettier": "4.3.0", "eslint-plugin-babel": "5.3.0", + "eslint-plugin-import": "^2.21.2", "eslint-plugin-jsx": "0.0.2", + "eslint-plugin-jsx-a11y": "^6.3.1", "eslint-plugin-prettier": "3.1.0", "eslint-plugin-react": "7.14.2", "express": "^4.17.1", From e96145db25cb0ca898c46e899e3dae5efa8b1df4 Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Tue, 8 Sep 2020 07:43:51 +0530 Subject: [PATCH 05/10] Improve APPM subscribing flow --- .../common/ApplicationSubscriptionInfo.java | 52 +++ .../core/impl/SubscriptionManagerImpl.java | 378 ++++++++---------- .../application/mgt/core/util/HelperUtil.java | 10 +- 3 files changed, 223 insertions(+), 217 deletions(-) create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationSubscriptionInfo.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationSubscriptionInfo.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationSubscriptionInfo.java new file mode 100644 index 0000000000..648e8585f9 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationSubscriptionInfo.java @@ -0,0 +1,52 @@ +/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.application.mgt.common; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.util.ArrayList; +import java.util.List; + +public class ApplicationSubscriptionInfo { + + List devices; + List subscribers; + List errorDeviceIdentifiers; + String appSupportingDeviceTypeName; + + public List getDevices() { return devices; } + + public void setDevices(List devices) { this.devices = devices; } + + public List getSubscribers() { return subscribers; } + + public void setSubscribers(List subscribers) { this.subscribers = subscribers; } + + public List getErrorDeviceIdentifiers() { return errorDeviceIdentifiers; } + + public void setErrorDeviceIdentifiers(List errorDeviceIdentifiers) { + this.errorDeviceIdentifiers = errorDeviceIdentifiers; + } + + public String getAppSupportingDeviceTypeName() { return appSupportingDeviceTypeName; } + + public void setAppSupportingDeviceTypeName(String appSupportingDeviceTypeName) { + this.appSupportingDeviceTypeName = appSupportingDeviceTypeName; + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java index 47545d4c83..158b67ff10 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -29,6 +29,7 @@ import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.application.mgt.common.ApplicationInstallResponse; +import org.wso2.carbon.device.application.mgt.common.ApplicationSubscriptionInfo; import org.wso2.carbon.device.application.mgt.common.ApplicationType; import org.wso2.carbon.device.application.mgt.common.DeviceSubscriptionData; import org.wso2.carbon.device.application.mgt.common.DeviceTypes; @@ -76,7 +77,6 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus; 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.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; @@ -120,84 +120,16 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.debug("Install application release which has UUID " + applicationUUID + " to " + params.size() + " users."); } - try { - validateRequest(params, subType, action); - DeviceManagementProviderService deviceManagementProviderService = HelperUtil - .getDeviceManagementProviderService(); - GroupManagementProviderService groupManagementProviderService = HelperUtil - .getGroupManagementProviderService(); - String deviceTypeName = null; - List devices = new ArrayList<>(); - List subscribers = new ArrayList<>(); - List errorDeviceIdentifiers = new ArrayList<>(); - ApplicationInstallResponse applicationInstallResponse; - - //todo validate users, groups and roles - ApplicationDTO applicationDTO = getApplicationDTO(applicationUUID); - if (SubscriptionType.DEVICE.toString().equals(subType)) { - for (T param : params) { - DeviceIdentifier deviceIdentifier = (DeviceIdentifier) param; - if (StringUtils.isEmpty(deviceIdentifier.getId()) || StringUtils - .isEmpty(deviceIdentifier.getType())) { - log.warn("Found a device identifier which has either empty identity of the device or empty" - + " device type. Hence ignoring the device identifier. "); - continue; - } - if (!ApplicationType.WEB_CLIP.toString().equals(applicationDTO.getType())) { - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - if (!deviceType.getName().equals(deviceIdentifier.getType())) { - log.warn("Found a device identifier which is not matched with the supported device type " - + "of the application release which has UUID " + applicationUUID + " Application " - + "supported device type is " + deviceType.getName() + " and the " - + "identifier of which has a different device type is " + deviceIdentifier.getId()); - errorDeviceIdentifiers.add(deviceIdentifier); - continue; - } - } - devices.add(deviceManagementProviderService.getDevice(deviceIdentifier, false)); - } - } else if (SubscriptionType.USER.toString().equalsIgnoreCase(subType)) { - for (T param : params) { - String username = (String) param; - subscribers.add(username); - devices.addAll(deviceManagementProviderService.getDevicesOfUser(username)); - } - } else if (SubscriptionType.ROLE.toString().equalsIgnoreCase(subType)) { - for (T param : params) { - String roleName = (String) param; - subscribers.add(roleName); - devices.addAll(deviceManagementProviderService.getAllDevicesOfRole(roleName)); - } - } else if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { - for (T param : params) { - String groupName = (String) param; - subscribers.add(groupName); - devices.addAll(groupManagementProviderService.getAllDevicesOfGroup(groupName, true)); - } - } - if (!ApplicationType.WEB_CLIP.toString().equals(applicationDTO.getType()) && !SubscriptionType.DEVICE - .toString().equals(subType)) { - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - deviceTypeName = deviceType.getName(); - //filter devices by device type - String tmpDeviceTypeName = deviceTypeName; - devices.removeIf(device -> !tmpDeviceTypeName.equals(device.getType())); - } + validateRequest(params, subType, action); + //todo validate users, groups and roles + ApplicationDTO applicationDTO = getApplicationDTO(applicationUUID); + ApplicationSubscriptionInfo applicationSubscriptionInfo = getAppSubscriptionInfo(applicationDTO, subType, params); + ApplicationInstallResponse applicationInstallResponse = performActionOnDevices(applicationSubscriptionInfo.getAppSupportingDeviceTypeName(), + applicationSubscriptionInfo.getDevices(), applicationDTO, subType, applicationSubscriptionInfo.getSubscribers(), action); - applicationInstallResponse = performActionOnDevices(deviceTypeName, devices, applicationDTO, - subType, subscribers, action); - applicationInstallResponse.setErrorDeviceIdentifiers(errorDeviceIdentifiers); - return applicationInstallResponse; - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting devices of given users or given roles."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (GroupManagementException e) { - String msg = "Error occurred while getting devices of given groups"; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } + applicationInstallResponse.setErrorDeviceIdentifiers(applicationSubscriptionInfo.getErrorDeviceIdentifiers()); + return applicationInstallResponse; } @Override @@ -321,141 +253,73 @@ public class SubscriptionManagerImpl implements SubscriptionManager { @Override public void performEntAppSubscription(String applicationUUID, List params, String subType, String action, - boolean requiresUpdatingExternal) - throws ApplicationManagementException { + boolean requiresUpdatingExternal) throws ApplicationManagementException { if (log.isDebugEnabled()) { - log.debug("Google Ent app Install operation is received to application which has UUID " - + applicationUUID + " to perform on " + params.size() + " params."); + log.debug("Google Ent app Install operation is received to application which has UUID " + applicationUUID + + " to perform on " + params.size() + " params."); + } + if (params.isEmpty()) { + String msg = "In order to subscribe/unsubscribe application release, you should provide list of " + + "subscribers. But found an empty list of subscribers."; + log.error(msg); + throw new BadRequestException(msg); } - try { - if (params.isEmpty()) { - String msg = "In order to subscribe/unsubscribe application release, you should provide list of " - + "subscribers. But found an empty list of subscribers."; - log.error(msg); - throw new BadRequestException(msg); - } - - ApplicationDTO applicationDTO = getApplicationDTO(applicationUUID); - ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - int applicationReleaseId = applicationReleaseDTO.getId(); - if (!ApplicationType.PUBLIC.toString().equals(applicationDTO.getType())) { - String msg = "Application type is not public. Hence you can't perform google ent.install operation on " - + "this application. Application name " + applicationDTO.getName() + " Application Type " - + applicationDTO.getType(); - log.error(msg); - throw new BadRequestException(msg); - } - - List categories = getApplicationCategories(applicationDTO.getId()); - if (!categories.contains("GooglePlaySyncedApp")) { - String msg = "This is not google play store synced application. Hence can't perform enterprise app " - + "installation."; - log.error(msg); - throw new BadRequestException(msg); - } - - DeviceManagementProviderService deviceManagementProviderService = HelperUtil - .getDeviceManagementProviderService(); - - List devices = new ArrayList<>(); - List subscribers = new ArrayList<>(); - List appSubscribingDeviceIds; - List appReSubscribingDeviceIds = new ArrayList<>(); - List deviceIdentifiers = new ArrayList<>(); - //todo validate users, groups and roles - if (SubscriptionType.DEVICE.toString().equals(subType)) { - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - for (T param : params) { - DeviceIdentifier deviceIdentifier = (DeviceIdentifier) param; - if (StringUtils.isEmpty(deviceIdentifier.getId()) || StringUtils - .isEmpty(deviceIdentifier.getType())) { - log.warn("Found a device identifier which has either empty identity of the device or empty" - + " device type. Hence ignoring the device identifier. "); - continue; - } - if (!deviceType.getName().equals(deviceIdentifier.getType())) { - log.warn("Found a device identifier which is not matched with the supported device type " - + "of the application release which has UUID " + applicationUUID + " Application " - + "supported device type is " + deviceType.getName() + " and the " - + "identifier of which has a different device type is " + deviceIdentifier.getId()); - continue; - } - deviceIdentifiers.add(deviceIdentifier); - devices.add(deviceManagementProviderService.getDevice(deviceIdentifier, false)); - } - } else if (SubscriptionType.USER.toString().equalsIgnoreCase(subType)) { - for (T param : params) { - String username = (String) param; - subscribers.add(username); - devices.addAll(deviceManagementProviderService.getDevicesOfUser(username)); - } - } else if (SubscriptionType.ROLE.toString().equalsIgnoreCase(subType)) { - for (T param : params) { - String roleName = (String) param; - subscribers.add(roleName); - devices.addAll(deviceManagementProviderService.getAllDevicesOfRole(roleName)); - } - } else if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { - GroupManagementProviderService groupManagementProviderService = HelperUtil - .getGroupManagementProviderService(); - for (T param : params) { - String groupName = (String) param; - subscribers.add(groupName); - devices.addAll(groupManagementProviderService.getAllDevicesOfGroup(groupName, false)); - } - } else { - String msg = "Found invalid subscription type " + subType+ " to install application release" ; - log.error(msg); - throw new BadRequestException(msg); - } + ApplicationDTO applicationDTO = getApplicationDTO(applicationUUID); + ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); + int applicationReleaseId = applicationReleaseDTO.getId(); + if (!ApplicationType.PUBLIC.toString().equals(applicationDTO.getType())) { + String msg = "Application type is not public. Hence you can't perform google ent.install operation on " + + "this application. Application name " + applicationDTO.getName() + " Application Type " + + applicationDTO.getType(); + log.error(msg); + throw new BadRequestException(msg); + } - /*If subscription type is not device we need to crete device identifiers object list by referring retrieved - list of devices.*/ - if (!SubscriptionType.DEVICE.toString().equalsIgnoreCase(subType)) { - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - String deviceTypeName = deviceType.getName(); - //filter devices by device type - devices.removeIf(device -> !deviceTypeName.equals(device.getType())); - devices.forEach(device -> { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(device.getDeviceIdentifier()); - deviceIdentifier.setType(device.getType()); - deviceIdentifiers.add(deviceIdentifier); - }); - } + List categories = getApplicationCategories(applicationDTO.getId()); + if (!categories.contains("GooglePlaySyncedApp")) { + String msg = "This is not google play store synced application. Hence can't perform enterprise app " + + "installation."; + log.error(msg); + throw new BadRequestException(msg); + } - if (requiresUpdatingExternal) { - //Installing the application - ApplicationPolicyDTO applicationPolicyDTO = new ApplicationPolicyDTO(); - applicationPolicyDTO.setApplicationDTO(applicationDTO); - applicationPolicyDTO.setDeviceIdentifierList(deviceIdentifiers); - applicationPolicyDTO.setAction(action.toUpperCase()); - installEnrollmentApplications(applicationPolicyDTO); - } + List appReSubscribingDeviceIds = new ArrayList<>(); + List deviceIdentifiers = new ArrayList<>(); - appSubscribingDeviceIds = devices.stream().map(Device::getId).collect(Collectors.toList()); - Map deviceSubscriptions = getDeviceSubscriptions(appSubscribingDeviceIds, - applicationReleaseId); - for (Map.Entry deviceSubscription: deviceSubscriptions.entrySet()){ - appReSubscribingDeviceIds.add(deviceSubscription.getKey()); - appSubscribingDeviceIds.remove(deviceSubscription.getKey()); - } + ApplicationSubscriptionInfo applicationSubscriptionInfo = getAppSubscriptionInfo(applicationDTO, subType, + params); + applicationSubscriptionInfo.getDevices().forEach(device -> { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(device.getDeviceIdentifier()); + deviceIdentifier.setType(device.getType()); + deviceIdentifiers.add(deviceIdentifier); + }); + + if (requiresUpdatingExternal) { + //Installing the application + ApplicationPolicyDTO applicationPolicyDTO = new ApplicationPolicyDTO(); + applicationPolicyDTO.setApplicationDTO(applicationDTO); + applicationPolicyDTO.setDeviceIdentifierList(deviceIdentifiers); + applicationPolicyDTO.setAction(action.toUpperCase()); + installEnrollmentApplications(applicationPolicyDTO); + } - updateSubscriptionsForEntInstall(applicationReleaseId, appSubscribingDeviceIds, appReSubscribingDeviceIds, - subscribers, subType, action); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting devices of given users or given roles."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (GroupManagementException e) { - String msg = "Error occurred while getting devices of given groups"; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); + List appSubscribingDeviceIds = applicationSubscriptionInfo.getDevices().stream().map(Device::getId) + .collect(Collectors.toList()); + Map deviceSubscriptions = getDeviceSubscriptions(appSubscribingDeviceIds, + applicationReleaseId); + for (Map.Entry deviceSubscription : deviceSubscriptions.entrySet()) { + appReSubscribingDeviceIds.add(deviceSubscription.getKey()); + appSubscribingDeviceIds.remove(deviceSubscription.getKey()); } + + updateSubscriptionsForEntInstall(applicationReleaseId, appSubscribingDeviceIds, appReSubscribingDeviceIds, + applicationSubscriptionInfo.getSubscribers(), subType, action); } - @Override public void installAppsForDevice(DeviceIdentifier deviceIdentifier, List releaseUUIDs) + @Override + public void installAppsForDevice(DeviceIdentifier deviceIdentifier, List releaseUUIDs) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); @@ -519,6 +383,105 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } } + /** + * Gets Application subscribing info by using requesting params + * + * @param applicationDTO Application DTO + * @param params list of subscribers. This list can be of either + * {@link org.wso2.carbon.device.mgt.common.DeviceIdentifier} if {@param subType} is equal + * to DEVICE or + * {@link String} if {@param subType} is USER, ROLE or GROUP + * @param subType subscription type. E.g. DEVICE, USER, ROLE, GROUP {@see { + * @param generic type of the method. + * @return {@link ApplicationSubscriptionInfo} + * @throws ApplicationManagementException if error occurred while getting Application subscription info + */ + private ApplicationSubscriptionInfo getAppSubscriptionInfo(ApplicationDTO applicationDTO, String subType, + List params) throws ApplicationManagementException { + + DeviceManagementProviderService deviceManagementProviderService = HelperUtil + .getDeviceManagementProviderService(); + GroupManagementProviderService groupManagementProviderService = HelperUtil.getGroupManagementProviderService(); + List devices = new ArrayList<>(); + List subscribers = new ArrayList<>(); + List errorDeviceIdentifiers = new ArrayList<>(); + String deviceTypeName = null; + + try { + if (!ApplicationType.WEB_CLIP.toString().equals(applicationDTO.getType())) { + deviceTypeName = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()).getName(); + } + + if (SubscriptionType.DEVICE.toString().equals(subType)) { + for (T param : params) { + DeviceIdentifier deviceIdentifier = (DeviceIdentifier) param; + if (StringUtils.isEmpty(deviceIdentifier.getId()) || StringUtils + .isEmpty(deviceIdentifier.getType())) { + log.warn("Found a device identifier which has either empty identity of the device or empty" + + " device type. Hence ignoring the device identifier. "); + continue; + } + if (!ApplicationType.WEB_CLIP.toString().equals(applicationDTO.getType()) && !deviceIdentifier + .getType().equals(deviceTypeName)) { + log.warn("Found a device identifier which is not matched with the supported device type " + + "of the application release which has UUID " + applicationDTO + .getApplicationReleaseDTOs().get(0).getUuid() + " Application " + + "supported device type is " + deviceTypeName + " and the identifier of which has a " + + "different device type is " + deviceIdentifier.getId()); + errorDeviceIdentifiers.add(deviceIdentifier); + continue; + } + devices.add(deviceManagementProviderService.getDevice(deviceIdentifier, false)); + } + } else if (SubscriptionType.USER.toString().equalsIgnoreCase(subType)) { + for (T param : params) { + String username = (String) param; + subscribers.add(username); + devices.addAll(deviceManagementProviderService.getDevicesOfUser(username)); + } + } else if (SubscriptionType.ROLE.toString().equalsIgnoreCase(subType)) { + for (T param : params) { + String roleName = (String) param; + subscribers.add(roleName); + devices.addAll(deviceManagementProviderService.getAllDevicesOfRole(roleName)); + } + } else if (SubscriptionType.GROUP.toString().equalsIgnoreCase(subType)) { + for (T param : params) { + String groupName = (String) param; + subscribers.add(groupName); + devices.addAll(groupManagementProviderService.getAllDevicesOfGroup(groupName, true)); + } + } else { + String msg = "Found invalid subscription type " + subType+ " to install application release" ; + log.error(msg); + throw new BadRequestException(msg); + } + + if (!ApplicationType.WEB_CLIP.toString().equals(applicationDTO.getType()) && !SubscriptionType.DEVICE + .toString().equals(subType)) { + //filter devices by device type + String tmpDeviceTypeName = deviceTypeName; + devices.removeIf(device -> !tmpDeviceTypeName.equals(device.getType())); + } + + ApplicationSubscriptionInfo applicationSubscriptionInfo = new ApplicationSubscriptionInfo(); + applicationSubscriptionInfo.setDevices(devices); + applicationSubscriptionInfo.setSubscribers(subscribers); + applicationSubscriptionInfo.setErrorDeviceIdentifiers(errorDeviceIdentifiers); + applicationSubscriptionInfo.setAppSupportingDeviceTypeName(deviceTypeName); + return applicationSubscriptionInfo; + } catch (DeviceManagementException e) { + String msg = "Error occurred while getting devices of given users or given roles or while getting device " + + "type info."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (GroupManagementException e) { + String msg = "Error occurred while getting devices of given groups"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + /** * This method is responsible to update subscription data for google enterprise install. * @@ -567,8 +530,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } } - - /** * THis method is responsible to validate application install or uninstall request. * @@ -704,14 +665,12 @@ public class SubscriptionManagerImpl implements SubscriptionManager { || Operation.Status.IN_PROGRESS.toString().equals(deviceSubscriptionDTO.getStatus())) { subscribingDeviceIdHolder.getSkippedDevices().put(deviceIdentifier, device.getId()); } else if (deviceSubscriptionDTO.isUnsubscribed()) { - if (Operation.Status.COMPLETED.toString().equals(deviceSubscriptionDTO.getStatus())) { - subscribingDeviceIdHolder.getAppReInstallableDevices().put(deviceIdentifier, device.getId()); - } else { + if (!Operation.Status.COMPLETED.toString().equals(deviceSubscriptionDTO.getStatus())) { /*We can't ensure whether app is uninstalled successfully or not hence allow to perform both install and uninstall operations*/ subscribingDeviceIdHolder.getAppReUnInstallableDevices().put(deviceIdentifier, device.getId()); - subscribingDeviceIdHolder.getAppReInstallableDevices().put(deviceIdentifier, device.getId()); } + subscribingDeviceIdHolder.getAppReInstallableDevices().put(deviceIdentifier, device.getId()); } else if (!deviceSubscriptionDTO.isUnsubscribed() && Operation.Status.COMPLETED.toString() .equals(deviceSubscriptionDTO.getStatus())) { subscribingDeviceIdHolder.getAppInstalledDevices().put(deviceIdentifier, device.getId()); @@ -1126,8 +1085,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } @Override - public PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, - String status) + public PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, String status) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); DeviceManagementProviderService deviceManagementProviderService = HelperUtil diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java index bcfd052326..fcc7698169 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java @@ -20,24 +20,20 @@ package org.wso2.carbon.device.application.mgt.core.util; 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.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import java.util.List; -import java.util.UUID; - /** * Utility methods used in the Application Management. */ public class HelperUtil { - private static Log log = LogFactory.getLog(HelperUtil.class); + private static final Log log = LogFactory.getLog(HelperUtil.class); private static DeviceManagementProviderService deviceManagementProviderService; private static GroupManagementProviderService groupManagementProviderService; - public static DeviceManagementProviderService getDeviceManagementProviderService() { + public static synchronized DeviceManagementProviderService getDeviceManagementProviderService() { if (deviceManagementProviderService == null) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); deviceManagementProviderService = (DeviceManagementProviderService) ctx @@ -51,7 +47,7 @@ public class HelperUtil { return deviceManagementProviderService; } - public static GroupManagementProviderService getGroupManagementProviderService() { + public static synchronized GroupManagementProviderService getGroupManagementProviderService() { if (groupManagementProviderService == null) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); groupManagementProviderService = (GroupManagementProviderService) ctx From 400c9a2ac9224e5beb053619c6688dc936233c57 Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Wed, 9 Sep 2020 11:17:20 +0530 Subject: [PATCH 06/10] Add report invoker for the product distribution --- .../src/main/resources/p2.inf | 1 + 1 file changed, 1 insertion(+) diff --git a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf index 6e7e6d01df..7887868228 100644 --- a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf +++ b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf @@ -3,3 +3,4 @@ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../depl org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/publisher-ui-request-handler.war,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/store-ui-request-handler.war,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/entgra-ui-request-handler.war,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/mdm-reports-ui-request-handler.war,overwrite:true);\ From e9400a0888007157687d574fe8e95a843bed6cd4 Mon Sep 17 00:00:00 2001 From: Kaveesha Date: Sun, 30 Aug 2020 22:44:24 +0530 Subject: [PATCH 07/10] Fix QR generating issue in Cloud App --- .../core/otp/mgt/dao/OTPManagementDAO.java | 7 ++-- .../dao/impl/GenericOTPManagementDAOImpl.java | 37 +++++++++---------- .../mgt/service/OTPManagementServiceImpl.java | 33 +++++++++++++---- 3 files changed, 47 insertions(+), 30 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/OTPManagementDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/OTPManagementDAO.java index 4c3690f5d0..44bb2a3064 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/OTPManagementDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/OTPManagementDAO.java @@ -20,15 +20,16 @@ package org.wso2.carbon.device.mgt.core.otp.mgt.dao; import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OneTimePinDTO; import org.wso2.carbon.device.mgt.core.otp.mgt.exception.OTPManagementDAOException; +import java.util.List; + public interface OTPManagementDAO { /** * Save OTP token data and tenant details of registering user - * @param oneTimePinDTO OTPMailDTO - * @return Primary key of the newly adding data raw + * @param oneTimePinDTOList OTPMailDTO * @throws OTPManagementDAOException if error occurred whule storing data */ - int addOTPData(OneTimePinDTO oneTimePinDTO) throws OTPManagementDAOException; + void addOTPData(List oneTimePinDTOList) throws OTPManagementDAOException; /** * Get OTP data for requesting One Time Token diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java index 273cf6c1a5..58b55197a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java @@ -32,17 +32,20 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.Calendar; +import java.util.List; public class GenericOTPManagementDAOImpl extends AbstractDAOImpl implements OTPManagementDAO { private static final Log log = LogFactory.getLog(GenericOTPManagementDAOImpl.class); @Override - public int addOTPData(OneTimePinDTO oneTimePinDTO) throws OTPManagementDAOException { + public void addOTPData(List oneTimePinDTOList) throws OTPManagementDAOException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to create an OTP data entry"); log.debug("OTP Details : "); - log.debug("OTP key : " + oneTimePinDTO.getOtpToken() + " Email : " + oneTimePinDTO.getEmail()); + for(OneTimePinDTO oneTimePinDTO: oneTimePinDTOList){ + log.debug("OTP key : " + oneTimePinDTO.getOtpToken() + " Email : " + oneTimePinDTO.getEmail()); + } } String sql = "INSERT INTO DM_OTP_DATA " @@ -57,29 +60,25 @@ public class GenericOTPManagementDAOImpl extends AbstractDAOImpl implements OTPM Connection conn = this.getDBConnection(); Calendar calendar = Calendar.getInstance(); Timestamp timestamp = new Timestamp(calendar.getTime().getTime()); - try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { - stmt.setString(1, oneTimePinDTO.getOtpToken()); - stmt.setString(2, oneTimePinDTO.getEmail()); - stmt.setString(3, oneTimePinDTO.getEmailType()); - stmt.setString(4, oneTimePinDTO.getMetaInfo()); - stmt.setTimestamp(5, timestamp); - stmt.setInt(6, oneTimePinDTO.getTenantId()); - stmt.setString(7, oneTimePinDTO.getUsername()); - stmt.executeUpdate(); - try (ResultSet rs = stmt.getGeneratedKeys()) { - if (rs.next()) { - return rs.getInt(1); - } - return -1; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + for (OneTimePinDTO oneTimePinDTO : oneTimePinDTOList) { + stmt.setString(1, oneTimePinDTO.getOtpToken()); + stmt.setString(2, oneTimePinDTO.getEmail()); + stmt.setString(3, oneTimePinDTO.getEmailType()); + stmt.setString(4, oneTimePinDTO.getMetaInfo()); + stmt.setTimestamp(5, timestamp); + stmt.setInt(6, oneTimePinDTO.getTenantId()); + stmt.setString(7, oneTimePinDTO.getUsername()); + stmt.addBatch(); } + stmt.executeBatch(); } } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the DB connection to create an opt entry for email " - + oneTimePinDTO.getEmail(); + String msg = "Error occurred while obtaining the DB connection to create an opt entry."; log.error(msg, e); throw new OTPManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "Error occurred while executing SQL to create an otp entry for email " + oneTimePinDTO.getEmail(); + String msg = "Error occurred while executing SQL to create an otp entry"; log.error(msg, e); throw new OTPManagementDAOException(msg, e); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java index 9b25987e84..c80502ec4f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java @@ -61,6 +61,8 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; +import java.util.ArrayList; +import java.util.Collections; public class OTPManagementServiceImpl implements OTPManagementService { @@ -82,12 +84,7 @@ public class OTPManagementServiceImpl implements OTPManagementService { otpWrapper.getUsername(), tenant, -1234); try { ConnectionManagerUtil.beginDBTransaction(); - if (this.otpManagementDAO.addOTPData(oneTimePinDTO) == -1) { - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "OTP data saving failed. Please, contact Administrator"; - log.error(msg); - throw new OTPManagementException(msg); - } + this.otpManagementDAO.addOTPData(Collections.singletonList(oneTimePinDTO)); Properties props = new Properties(); props.setProperty("first-name", tenant.getAdminFirstName()); props.setProperty("otp-token", oneTimePinDTO.getOtpToken()); @@ -98,12 +95,12 @@ public class OTPManagementServiceImpl implements OTPManagementService { log.error(msg, e); throw new OTPManagementException(msg, e); } catch (DBConnectionException e) { - String msg = "Error occurred while getting database connection."; + String msg = "Error occurred while getting database connection to add OPT data."; log.error(msg, e); throw new OTPManagementException(msg, e); } catch (OTPManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred while saving the OTP data. Email address: " + oneTimePinDTO.getEmail(); + String msg = "Error occurred while saving the OTP data for given email" ; log.error(msg, e); throw new OTPManagementException(msg, e); } finally { @@ -219,24 +216,44 @@ public class OTPManagementServiceImpl implements OTPManagementService { } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); OneTimePinDTO oneTimePinDTO; + List oneTimePinDTOList = new ArrayList<>(); Properties props = new Properties(); props.setProperty("enrollment-steps", enrollmentSteps.toString()); try { + ConnectionManagerUtil.beginDBTransaction(); for (String username : deviceEnrollmentInvitation.getUsernames()) { String emailAddress = DeviceManagerUtil.getUserClaimValue( username, DeviceManagementConstants.User.CLAIM_EMAIL_ADDRESS); oneTimePinDTO = createOneTimePin(emailAddress, OTPEmailTypes.DEVICE_ENROLLMENT.toString(), username, null, tenantId); + oneTimePinDTOList.add(oneTimePinDTO); props.setProperty("first-name", DeviceManagerUtil. getUserClaimValue(username, DeviceManagementConstants.User.CLAIM_FIRST_NAME)); props.setProperty("username", username); props.setProperty("otp-token", oneTimePinDTO.getOtpToken()); sendMail(props, emailAddress, DeviceManagementConstants.EmailAttributes.USER_ENROLLMENT_TEMPLATE); } + this.otpManagementDAO.addOTPData(oneTimePinDTOList); + ConnectionManagerUtil.commitDBTransaction(); } catch (UserStoreException e) { String msg = "Error occurred while getting claim values to invite user"; log.error(msg, e); throw new OTPManagementException(msg, e); + } catch (DBConnectionException e) { + String msg = "Error occurred while getting database connection to add OPT data."; + log.error(msg, e); + throw new OTPManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "SQL Error occurred when adding OPT data to send device enrollment Invitation."; + log.error(msg, e); + throw new OTPManagementException(msg, e); + } catch (OTPManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while saving the OTP data."; + log.error(msg, e); + throw new OTPManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); } } From bbecbb6f8a74fe9b32c7e00f6f41149426d9971c Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Sat, 12 Sep 2020 08:43:38 +0530 Subject: [PATCH 08/10] Fix build failure --- .../react-app/package.json | 1 + .../react-app/package.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json index f929dfc1e9..21144caacf 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.ui/react-app/package.json @@ -17,6 +17,7 @@ "acorn": "^6.2.0", "antd": "^4.0.0", "axios": "^0.19.0", + "babel-eslint": "^10.1.0", "d3": "^5.9.7", "dagre": "^0.8.4", "entgra-icons-react": "^1.0.0", diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/package.json b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/package.json index 91b0a4158b..7f84052960 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/package.json +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.ui/react-app/package.json @@ -13,7 +13,7 @@ "acorn": "^6.2.0", "antd": "^4.0.0", "axios": "^0.18.1", - "babel-eslint": "^9.0.0", + "babel-eslint": "^10.1.0", "d3": "^5.9.7", "dagre": "^0.8.4", "imagemin": "^5.3.1", From 6104d26ebe6c56a7d42937e03793f978d5ededfb Mon Sep 17 00:00:00 2001 From: Kaveesha Date: Mon, 14 Sep 2020 12:39:57 +0530 Subject: [PATCH 09/10] Add device name to Geo Cluster Locations data list --- .../service/impl/GeoLocationBasedServiceImplTest.java | 4 ++-- .../device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java | 4 +++- .../mgt/core/dao/impl/device/GenericDeviceDAOImpl.java | 2 ++ .../mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java | 4 +++- .../org/wso2/carbon/device/mgt/core/geo/GeoCluster.java | 8 +++++++- 5 files changed, 17 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java index 5553e02d22..d19e835848 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java @@ -47,10 +47,10 @@ public class GeoLocationBasedServiceImplTest { List geoClusters = new ArrayList<>(); geoClusters.add(new GeoCluster(new GeoCoordinate(1.5, 80.7), new GeoCoordinate(1.1, 79.5), new GeoCoordinate(1.9, 82.1), 3, - "tb32", "aegtew234", "android", "1234")); + "tb32", "aegtew234", "test1", "android", "1234")); geoClusters.add(new GeoCluster(new GeoCoordinate(10.2, 86.1), new GeoCoordinate(9.8, 84.7), new GeoCoordinate(11.1, 88.1), 4, - "t1gd", "swerty12s", "android", "1234")); + "t1gd", "swerty12s", "t2test", "android", "1234")); Mockito.doReturn(geoClusters).when(deviceManagementProviderService) .findGeoClusters(null, Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 3d279928f6..825b684e0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -1733,6 +1733,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { " MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_LONGITUDE," + " SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,?) AS GEOHASH_PREFIX, COUNT(*) AS COUNT," + " MIN(DEVICE.DEVICE_IDENTIFICATION) AS DEVICE_IDENTIFICATION," + + " MIN(DEVICE.NAME) AS NAME," + " MIN(DEVICE_TYPE.NAME) AS TYPE, " + " MIN(DEVICE.LAST_UPDATED_TIMESTAMP) AS LAST_UPDATED_TIMESTAMP " + "FROM DM_DEVICE_LOCATION AS DEVICE_LOCATION,DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE " + @@ -1763,13 +1764,14 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { double min_longitude = rs.getDouble("MIN_LONGITUDE"); double max_longitude = rs.getDouble("MAX_LONGITUDE"); String device_identification = rs.getString("DEVICE_IDENTIFICATION"); + String device_name = rs.getString("NAME"); String device_type = rs.getString("TYPE"); String last_seen = rs.getString("LAST_UPDATED_TIMESTAMP"); long count = rs.getLong("COUNT"); String geohashPrefix = rs.getString("GEOHASH_PREFIX"); geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude), new GeoCoordinate(min_latitude, min_longitude), new GeoCoordinate(max_latitude, max_longitude), - count, geohashPrefix, device_identification, device_type, last_seen)); + count, geohashPrefix, device_identification, device_name, device_type, last_seen)); } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving information of " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 63df06538d..f4bda81221 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -30,6 +30,8 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.geo.GeoCluster; +import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import java.sql.Connection; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 7aa74a1f1c..1d0d9c246c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -968,6 +968,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { + ") AS GEOHASH_PREFIX, " + "COUNT(*) AS COUNT, " + "MIN(DEVICE.DEVICE_IDENTIFICATION) AS DEVICE_IDENTIFICATION, " + + "MIN(DEVICE.NAME) AS NAME, " + "MIN(DEVICE_TYPE.NAME) AS TYPE, " + "MIN(DEVICE.LAST_UPDATED_TIMESTAMP) AS LAST_UPDATED_TIMESTAMP, " + "COUNT(DEVICE_LOCATION.GEO_HASH) " @@ -1004,6 +1005,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { double min_longitude = rs.getDouble("MIN_LONGITUDE"); double max_longitude = rs.getDouble("MAX_LONGITUDE"); String device_identification = rs.getString("DEVICE_IDENTIFICATION"); + String device_name = rs.getString("NAME"); String device_type = rs.getString("TYPE"); String last_seen = rs.getString("LAST_UPDATED_TIMESTAMP"); long count = rs.getLong("COUNT"); @@ -1011,7 +1013,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude), new GeoCoordinate(min_latitude, min_longitude), new GeoCoordinate(max_latitude, max_longitude), count, geohashPrefix, - device_identification, device_type, last_seen)); + device_identification, device_name, device_type, last_seen)); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/GeoCluster.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/GeoCluster.java index 6fa306f20b..e4838aaf6e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/GeoCluster.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/GeoCluster.java @@ -9,18 +9,20 @@ public class GeoCluster { private long count; private String geohashPrefix; private String deviceIdentification; + private String deviceName; private String deviceType; private String lastSeen; public GeoCluster(GeoCoordinate coordinates, GeoCoordinate southWestBound, GeoCoordinate northEastBound, long count, - String geohashPrefix, String deviceIdentification, String deviceType, String lastSeen){ + String geohashPrefix, String deviceIdentification, String deviceName, String deviceType, String lastSeen){ this.coordinates=coordinates; this.southWestBound=southWestBound; this.northEastBound=northEastBound; this.count=count; this.geohashPrefix=geohashPrefix; this.deviceIdentification=deviceIdentification; + this.deviceName=deviceName; this.deviceType=deviceType; this.lastSeen = lastSeen; @@ -50,6 +52,10 @@ public class GeoCluster { return deviceIdentification; } + public String getDeviceName() { + return deviceName; + } + public String getDeviceType() { return deviceType; } From 90dac0a10103e2a2a399ee3ec082a4876c36dd09 Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Thu, 24 Sep 2020 08:53:35 +0530 Subject: [PATCH 10/10] Add location bean classes and format the source --- .../core/impl/SubscriptionManagerImpl.java | 6 +- .../impl/DeviceManagementServiceImpl.java | 82 +++++++++-------- .../common/device/details/LocationBean.java | 89 +++++++++++++++++++ .../device/details/LocationEventBean.java | 69 ++++++++++++++ .../core/dao/impl/AbstractDeviceDAOImpl.java | 65 +++++++------- .../DeviceManagementProviderServiceImpl.java | 13 +-- .../src/main/resources/conf/mdm-ui-config.xml | 2 + 7 files changed, 243 insertions(+), 83 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationBean.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationEventBean.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java index 158b67ff10..c844ddaf08 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -108,7 +108,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { private LifecycleStateManager lifecycleStateManager; public SubscriptionManagerImpl() { - lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); + this.lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO(); this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); } @@ -549,7 +549,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { boolean isValidSubType = Arrays.stream(SubscriptionType.values()) .anyMatch(sub -> sub.name().equalsIgnoreCase(subType)); if (!isValidSubType) { - String msg = "Found invalid subscription type " + subType+ " to install application release" ; + String msg = "Found invalid subscription type " + subType+ " to subscribe application release" ; log.error(msg); throw new BadRequestException(msg); } @@ -579,8 +579,10 @@ public class SubscriptionManagerImpl implements SubscriptionManager { ApplicationDTO applicationDTO, String subType, List subscribers, String action) throws ApplicationManagementException { + //Get app subscribing info of each device SubscribingDeviceIdHolder subscribingDeviceIdHolder = getSubscribingDeviceIdHolder(devices, applicationDTO.getApplicationReleaseDTOs().get(0).getId()); + List activityList = new ArrayList<>(); List deviceIdentifiers = new ArrayList<>(); List ignoredDeviceIdentifiers = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 73a07b7aad..bd04c963bd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -504,15 +504,13 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.OK).entity(device).build(); } - @Path("/{deviceType}/{deviceId}/location-history") @GET - public Response getDeviceLocationInfo(@PathParam("deviceType") String deviceType, - @PathParam("deviceId") String deviceId, - @QueryParam("from") long from, @QueryParam("to") long to) { - - String errorMessage; - DeviceLocationHistory deviceLocationHistory = new DeviceLocationHistory(); - + @Path("/{deviceType}/{deviceId}/location-history") + public Response getDeviceLocationInfo( + @PathParam("deviceType") String deviceType, + @PathParam("deviceId") String deviceId, + @QueryParam("from") long from, + @QueryParam("to") long to) { try { RequestValidationUtil.validateDeviceIdentifier(deviceType, deviceId); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); @@ -520,81 +518,81 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(deviceType); if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) { String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + deviceId + "'"; log.error(msg); - return Response.status(Response.Status.UNAUTHORIZED).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build(); + return Response.status(Response.Status.UNAUTHORIZED).entity(new ErrorResponse.ErrorResponseBuilder() + .setCode(Response.Status.UNAUTHORIZED.getStatusCode()).setMessage(msg).build()).build(); } if (from == 0 || to == 0) { - errorMessage = "Invalid values for from/to"; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage)).build(); + String msg = "Invalid values for from/to"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse.ErrorResponseBuilder() + .setCode(Response.Status.BAD_REQUEST.getStatusCode()).setMessage(msg)).build(); } - List> locationHistorySnapshotList = new ArrayList<>(); // Get the location history snapshots for the given period - List deviceLocationHistorySnapshots = dms.getDeviceLocationInfo(deviceIdentifier, from, to); + List deviceLocationHistorySnapshots = dms + .getDeviceLocationInfo(deviceIdentifier, from, to); OperationMonitoringTaskConfig operationMonitoringTaskConfig = dms.getDeviceMonitoringConfig(deviceType); int taskFrequency = operationMonitoringTaskConfig.getFrequency(); int operationRecurrentTimes = 0; List monitoringOperations = operationMonitoringTaskConfig.getMonitoringOperation(); - for (MonitoringOperation monitoringOperation : - monitoringOperations) { + for (MonitoringOperation monitoringOperation : monitoringOperations) { if (monitoringOperation.getTaskName().equals("DEVICE_LOCATION")) { operationRecurrentTimes = monitoringOperation.getRecurrentTimes(); break; } } + // Device Location operation frequency in milliseconds. Adding 100000 ms as an error long operationFrequency = taskFrequency * operationRecurrentTimes + 100000; + Queue deviceLocationHistorySnapshotsQueue = new LinkedList<>( + deviceLocationHistorySnapshots); + List> locationHistorySnapshotList = new ArrayList<>(); - Queue deviceLocationHistorySnapshotsQueue = new LinkedList<>(deviceLocationHistorySnapshots); - - while (deviceLocationHistorySnapshotsQueue.size() > 0) { + while (!deviceLocationHistorySnapshotsQueue.isEmpty()) { List snapshots = new ArrayList<>(); // Make a copy of remaining snapshots - List cachedSnapshots = new ArrayList<>(deviceLocationHistorySnapshotsQueue); + List cachedSnapshots = new ArrayList<>( + deviceLocationHistorySnapshotsQueue); for (int i = 0; i < cachedSnapshots.size(); i++) { DeviceLocationHistorySnapshot currentSnapshot = deviceLocationHistorySnapshotsQueue.poll(); snapshots.add(currentSnapshot); - if (deviceLocationHistorySnapshotsQueue.size() > 0) { + if (!deviceLocationHistorySnapshotsQueue.isEmpty()) { DeviceLocationHistorySnapshot nextSnapshot = deviceLocationHistorySnapshotsQueue.peek(); - if (nextSnapshot.getUpdatedTime().getTime() - currentSnapshot.getUpdatedTime().getTime() > operationFrequency) { + if (nextSnapshot.getUpdatedTime().getTime() - currentSnapshot.getUpdatedTime().getTime() + > operationFrequency) { break; } } } locationHistorySnapshotList.add(snapshots); } + DeviceLocationHistory deviceLocationHistory = new DeviceLocationHistory(); deviceLocationHistory.setLocationHistorySnapshots(locationHistorySnapshotList); - - + return Response.status(Response.Status.OK).entity(deviceLocationHistory).build(); } catch (DeviceManagementException e) { - errorMessage = "Error occurred while fetching the device information."; - log.error(errorMessage, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()).build(); + String msg = "Error occurred while fetching the device information."; + log.error(msg, e); + return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder() + .setCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setMessage(msg).build()).build(); } catch (DeviceAccessAuthorizationException e) { - errorMessage = "Error occurred while checking the device authorization."; - log.error(errorMessage, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()).build(); - } catch (InputValidationException e){ - errorMessage = "Invalid device Id or device type"; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage)).build(); + String msg = "Error occurred while checking the device authorization."; + log.error(msg, e); + return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder() + .setCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setMessage(msg).build()).build(); + } catch (InputValidationException e) { + String msg = "Invalid device Id or device type"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorResponse.ErrorResponseBuilder() + .setCode(Response.Status.BAD_REQUEST.getStatusCode()).setMessage(msg)).build(); } - return Response.status(Response.Status.OK).entity(deviceLocationHistory).build(); } @GET diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationBean.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationBean.java new file mode 100644 index 0000000000..261d387e03 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationBean.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.device.details; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel( + value = "LocationBean", + description = "This class carries all information related IOS Device location." +) +public class LocationBean { + + @ApiModelProperty( + name = "latitude", + value = "Latitude of the IOS device Location.", + required = true + ) + private float latitude; + @ApiModelProperty( + name = "longitude", + value = "Longitude of the IOS device Location.", + required = true + ) + private float longitude; + @ApiModelProperty( + name = "operationId", + value = "Specific Id of the Location operation.", + required = true + ) + private String operationId; + + @ApiModelProperty( + name = "locationEvents", + value = "If this is a device initiated location publishing." + ) + private List locations; + + public List getLocationEvents() { + return locations; + } + + public void setLocationEvents(List locationEvents) { + this.locations = locationEvents; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + + public float getLatitude() { + return latitude; + } + + public void setLatitude(float latitude) { + this.latitude = latitude; + } + + public float getLongitude() { + return longitude; + } + + public void setLongitude(float longitude) { + this.longitude = longitude; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationEventBean.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationEventBean.java new file mode 100644 index 0000000000..6e1ef6c976 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/LocationEventBean.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.device.details; + +import io.swagger.annotations.ApiModelProperty; + +public class LocationEventBean { + + @ApiModelProperty( + name = "latitude", + value = "Latitude of the IOS device Location.", + required = true + ) + private String latitude; + + @ApiModelProperty( + name = "longitude", + value = "Longitude of the IOS device Location.", + required = true + ) + private String longitude; + + @ApiModelProperty( + name = "timestamp", + value = "Device Location time.", + required = true + ) + private String timestamp; + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 825b684e0c..a23346ac39 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -1830,40 +1830,45 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, long to) - throws DeviceManagementDAOException { - - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; + public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, + long to) throws DeviceManagementDAOException { List deviceLocationHistories = new ArrayList<>(); + String sql = "SELECT " + + "DEVICE_ID, " + + "TENANT_ID, " + + "DEVICE_ID_NAME, " + + "DEVICE_TYPE_NAME, " + + "LATITUDE, " + + "LONGITUDE, " + + "SPEED, " + + "HEADING, " + + "TIMESTAMP, " + + "GEO_HASH, " + + "DEVICE_OWNER, " + + "DEVICE_ALTITUDE, " + + "DISTANCE " + + "FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " + + "WHERE " + + "DEVICE_ID_NAME = ? AND " + + "DEVICE_TYPE_NAME = ? AND " + + "TIMESTAMP BETWEEN ? AND ?"; try { - conn = this.getConnection(); - - String sql = - "SELECT DEVICE_ID, TENANT_ID, DEVICE_ID_NAME, DEVICE_TYPE_NAME, LATITUDE, LONGITUDE, SPEED, " + - "HEADING, TIMESTAMP, GEO_HASH, DEVICE_OWNER, DEVICE_ALTITUDE, DISTANCE " + - "FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " + - "WHERE DEVICE_ID_NAME = ? " + - "AND DEVICE_TYPE_NAME = ? " + - "AND TIMESTAMP >= ? " + - "AND TIMESTAMP <= ?"; - - stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceIdentifier.getId()); - stmt.setString(2, deviceIdentifier.getType()); - stmt.setLong(3, from); - stmt.setLong(4, to); - rs = stmt.executeQuery(); - while (rs.next()) { - deviceLocationHistories.add(DeviceManagementDAOUtil.loadDeviceLocation(rs)); + Connection conn = this.getConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, deviceIdentifier.getId()); + stmt.setString(2, deviceIdentifier.getType()); + stmt.setLong(3, from); + stmt.setLong(4, to); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + deviceLocationHistories.add(DeviceManagementDAOUtil.loadDeviceLocation(rs)); + } + } } } catch (SQLException e) { - String errMessage = "Error occurred while obtaining the DB connection to get device location information"; - log.error(errMessage, e); - throw new DeviceManagementDAOException(errMessage, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while obtaining the DB connection to get device location information"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } return deviceLocationHistories; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 5e28129390..f313477937 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -3051,26 +3051,21 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, long to) - throws DeviceManagementException { - + public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, + long to) throws DeviceManagementException { if (log.isDebugEnabled()) { log.debug("Get device location information"); } - List deviceLocationHistory; - String errMessage; - try { DeviceManagementDAOFactory.openConnection(); deviceLocationHistory = deviceDAO.getDeviceLocationInfo(deviceIdentifier, from, to); - } catch (DeviceManagementDAOException e) { - errMessage = "Error occurred in getDeviceLocationInfo"; + String errMessage = "Error occurred in getDeviceLocationInfo"; log.error(errMessage, e); throw new DeviceManagementException(errMessage, e); } catch (SQLException e) { - errMessage = "Error occurred while opening a connection to the data source"; + String errMessage = "Error occurred while opening a connection to the data source"; log.error(errMessage, e); throw new DeviceManagementException(errMessage, e); } finally { diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index e9c88e3321..e201cb9635 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -148,6 +148,8 @@ perm:user:permission-view perm:ios:view-configuration perm:ios:manage-configuration + perm:ios:dep-view + perm:ios:dep-add perm:windows:view-configuration perm:windows:manage-configuration perm:android:lock-devices